]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/geom/core/geom.c
MFV r328225: 8603 rename zilog's "zl_writer_lock" to "zl_issuer_lock"
[FreeBSD/FreeBSD.git] / sbin / geom / core / geom.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2004-2009 Pawel Jakub Dawidek <pjd@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include <sys/param.h>
33 #include <sys/linker.h>
34 #include <sys/module.h>
35 #include <sys/stat.h>
36 #include <sys/sysctl.h>
37 #include <ctype.h>
38 #include <err.h>
39 #include <errno.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <stdarg.h>
43 #include <stdint.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <libgen.h>
47 #include <libutil.h>
48 #include <inttypes.h>
49 #include <dlfcn.h>
50 #include <assert.h>
51 #include <libgeom.h>
52 #include <geom.h>
53
54 #include "misc/subr.h"
55
56 #ifdef STATIC_GEOM_CLASSES
57 extern uint32_t gpart_version;
58 extern struct g_command gpart_class_commands[];
59 extern uint32_t glabel_version;
60 extern struct g_command glabel_class_commands[];
61 #endif
62
63 static char comm[MAXPATHLEN], *class_name = NULL, *gclass_name = NULL;
64 static uint32_t *version = NULL;
65 static int verbose = 0;
66 static struct g_command *class_commands = NULL;
67
68 #define GEOM_CLASS_CMDS 0x01
69 #define GEOM_STD_CMDS   0x02
70 static struct g_command *find_command(const char *cmdstr, int flags);
71 static int std_available(const char *name);
72
73 static void std_help(struct gctl_req *req, unsigned flags);
74 static void std_list(struct gctl_req *req, unsigned flags);
75 static void std_status(struct gctl_req *req, unsigned flags);
76 static void std_load(struct gctl_req *req, unsigned flags);
77 static void std_unload(struct gctl_req *req, unsigned flags);
78
79 static struct g_command std_commands[] = {
80         { "help", 0, std_help, G_NULL_OPTS, NULL },
81         { "list", 0, std_list,
82             {
83                 { 'a', "all", NULL, G_TYPE_BOOL },
84                 G_OPT_SENTINEL
85             },
86             "[-a] [name ...]"
87         },
88         { "status", 0, std_status,
89             {
90                 { 'a', "all", NULL, G_TYPE_BOOL },
91                 { 'g', "geoms", NULL, G_TYPE_BOOL },
92                 { 's', "script", NULL, G_TYPE_BOOL },
93                 G_OPT_SENTINEL
94             },
95             "[-ags] [name ...]"
96         },
97         { "load", G_FLAG_VERBOSE | G_FLAG_LOADKLD, std_load, G_NULL_OPTS,
98             NULL },
99         { "unload", G_FLAG_VERBOSE, std_unload, G_NULL_OPTS, NULL },
100         G_CMD_SENTINEL
101 };
102
103 static void
104 usage_command(struct g_command *cmd, const char *prefix)
105 {
106         struct g_option *opt;
107         unsigned i;
108
109         if (cmd->gc_usage != NULL) {
110                 char *pos, *ptr, *sptr;
111
112                 sptr = ptr = strdup(cmd->gc_usage);
113                 while ((pos = strsep(&ptr, "\n")) != NULL) {
114                         if (*pos == '\0')
115                                 continue;
116                         fprintf(stderr, "%s %s %s %s\n", prefix, comm,
117                             cmd->gc_name, pos);
118                 }
119                 free(sptr);
120                 return;
121         }
122
123         fprintf(stderr, "%s %s %s", prefix, comm, cmd->gc_name);
124         if ((cmd->gc_flags & G_FLAG_VERBOSE) != 0)
125                 fprintf(stderr, " [-v]");
126         for (i = 0; ; i++) {
127                 opt = &cmd->gc_options[i];
128                 if (opt->go_name == NULL)
129                         break;
130                 if (opt->go_val != NULL || G_OPT_TYPE(opt) == G_TYPE_BOOL)
131                         fprintf(stderr, " [");
132                 else
133                         fprintf(stderr, " ");
134                 fprintf(stderr, "-%c", opt->go_char);
135                 if (G_OPT_TYPE(opt) != G_TYPE_BOOL)
136                         fprintf(stderr, " %s", opt->go_name);
137                 if (opt->go_val != NULL || G_OPT_TYPE(opt) == G_TYPE_BOOL)
138                         fprintf(stderr, "]");
139         }
140         fprintf(stderr, "\n");
141 }
142
143 static void
144 usage(void)
145 {
146
147         if (class_name == NULL) {
148                 errx(EXIT_FAILURE, "usage: %s <class> <command> [options]",
149                     "geom");
150         } else {
151                 struct g_command *cmd;
152                 const char *prefix;
153                 unsigned i;
154
155                 prefix = "usage:";
156                 if (class_commands != NULL) {
157                         for (i = 0; ; i++) {
158                                 cmd = &class_commands[i];
159                                 if (cmd->gc_name == NULL)
160                                         break;
161                                 usage_command(cmd, prefix);
162                                 prefix = "      ";
163                         }
164                 }
165                 for (i = 0; ; i++) {
166                         cmd = &std_commands[i];
167                         if (cmd->gc_name == NULL)
168                                 break;
169                         /*
170                          * If class defines command, which has the same name as
171                          * standard command, skip it, because it was already
172                          * shown on usage().
173                          */
174                         if (find_command(cmd->gc_name, GEOM_CLASS_CMDS) != NULL)
175                                 continue;
176                         usage_command(cmd, prefix);
177                         prefix = "      ";
178                 }
179                 exit(EXIT_FAILURE);
180         }
181 }
182
183 static void
184 load_module(void)
185 {
186         char name1[64], name2[64];
187
188         snprintf(name1, sizeof(name1), "g_%s", class_name);
189         snprintf(name2, sizeof(name2), "geom_%s", class_name);
190         if (modfind(name1) < 0) {
191                 /* Not present in kernel, try loading it. */
192                 if (kldload(name2) < 0 || modfind(name1) < 0) {
193                         if (errno != EEXIST) {
194                                 errx(EXIT_FAILURE,
195                                     "%s module not available!", name2);
196                         }
197                 }
198         }
199 }
200
201 static int
202 strlcatf(char *str, size_t size, const char *format, ...)
203 {
204         size_t len;
205         va_list ap;
206         int ret;
207
208         len = strlen(str);
209         str += len;
210         size -= len;
211
212         va_start(ap, format);
213         ret = vsnprintf(str, size, format, ap);
214         va_end(ap);
215
216         return (ret);
217 }
218
219 /*
220  * Find given option in options available for given command.
221  */
222 static struct g_option *
223 find_option(struct g_command *cmd, char ch)
224 {
225         struct g_option *opt;
226         unsigned i;
227
228         for (i = 0; ; i++) {
229                 opt = &cmd->gc_options[i];
230                 if (opt->go_name == NULL)
231                         return (NULL);
232                 if (opt->go_char == ch)
233                         return (opt);
234         }
235         /* NOTREACHED */
236         return (NULL);
237 }
238
239 /*
240  * Add given option to gctl_req.
241  */
242 static void
243 set_option(struct gctl_req *req, struct g_option *opt, const char *val)
244 {
245         const char *optname;
246         uint64_t number;
247         void *ptr;
248
249         if (G_OPT_ISMULTI(opt)) {
250                 size_t optnamesize;
251
252                 if (G_OPT_NUM(opt) == UCHAR_MAX)
253                         errx(EXIT_FAILURE, "Too many -%c options.", opt->go_char);
254
255                 /*
256                  * Base option name length plus 3 bytes for option number
257                  * (max. 255 options) plus 1 byte for terminating '\0'.
258                  */
259                 optnamesize = strlen(opt->go_name) + 3 + 1;
260                 ptr = malloc(optnamesize);
261                 if (ptr == NULL)
262                         errx(EXIT_FAILURE, "No memory.");
263                 snprintf(ptr, optnamesize, "%s%u", opt->go_name, G_OPT_NUM(opt));
264                 G_OPT_NUMINC(opt);
265                 optname = ptr;
266         } else {
267                 optname = opt->go_name;
268         }
269
270         if (G_OPT_TYPE(opt) == G_TYPE_NUMBER) {
271                 if (expand_number(val, &number) == -1) {
272                         err(EXIT_FAILURE, "Invalid value for '%c' argument",
273                             opt->go_char);
274                 }
275                 ptr = malloc(sizeof(intmax_t));
276                 if (ptr == NULL)
277                         errx(EXIT_FAILURE, "No memory.");
278                 *(intmax_t *)ptr = number;
279                 opt->go_val = ptr;
280                 gctl_ro_param(req, optname, sizeof(intmax_t), opt->go_val);
281         } else if (G_OPT_TYPE(opt) == G_TYPE_STRING) {
282                 gctl_ro_param(req, optname, -1, val);
283         } else if (G_OPT_TYPE(opt) == G_TYPE_BOOL) {
284                 ptr = malloc(sizeof(int));
285                 if (ptr == NULL)
286                         errx(EXIT_FAILURE, "No memory.");
287                 *(int *)ptr = *val - '0';
288                 opt->go_val = ptr;
289                 gctl_ro_param(req, optname, sizeof(int), opt->go_val);
290         } else {
291                 assert(!"Invalid type");
292         }
293
294         if (G_OPT_ISMULTI(opt))
295                 free(__DECONST(char *, optname));
296 }
297
298 /*
299  * 1. Add given argument by caller.
300  * 2. Add default values of not given arguments.
301  * 3. Add the rest of arguments.
302  */
303 static void
304 parse_arguments(struct g_command *cmd, struct gctl_req *req, int *argc,
305     char ***argv)
306 {
307         struct g_option *opt;
308         char opts[64];
309         unsigned i;
310         int ch;
311
312         *opts = '\0';
313         if ((cmd->gc_flags & G_FLAG_VERBOSE) != 0)
314                 strlcat(opts, "v", sizeof(opts));
315         for (i = 0; ; i++) {
316                 opt = &cmd->gc_options[i];
317                 if (opt->go_name == NULL)
318                         break;
319                 assert(G_OPT_TYPE(opt) != 0);
320                 assert((opt->go_type & ~(G_TYPE_MASK | G_TYPE_MULTI)) == 0);
321                 /* Multiple bool arguments makes no sense. */
322                 assert(G_OPT_TYPE(opt) != G_TYPE_BOOL ||
323                     (opt->go_type & G_TYPE_MULTI) == 0);
324                 strlcatf(opts, sizeof(opts), "%c", opt->go_char);
325                 if (G_OPT_TYPE(opt) != G_TYPE_BOOL)
326                         strlcat(opts, ":", sizeof(opts));
327         }
328
329         /*
330          * Add specified arguments.
331          */
332         while ((ch = getopt(*argc, *argv, opts)) != -1) {
333                 /* Standard (not passed to kernel) options. */
334                 switch (ch) {
335                 case 'v':
336                         verbose = 1;
337                         continue;
338                 }
339                 /* Options passed to kernel. */
340                 opt = find_option(cmd, ch);
341                 if (opt == NULL)
342                         usage();
343                 if (!G_OPT_ISMULTI(opt) && G_OPT_ISDONE(opt)) {
344                         warnx("Option '%c' specified twice.", opt->go_char);
345                         usage();
346                 }
347                 G_OPT_DONE(opt);
348
349                 if (G_OPT_TYPE(opt) == G_TYPE_BOOL)
350                         set_option(req, opt, "1");
351                 else
352                         set_option(req, opt, optarg);
353         }
354         *argc -= optind;
355         *argv += optind;
356
357         /*
358          * Add not specified arguments, but with default values.
359          */
360         for (i = 0; ; i++) {
361                 opt = &cmd->gc_options[i];
362                 if (opt->go_name == NULL)
363                         break;
364                 if (G_OPT_ISDONE(opt))
365                         continue;
366
367                 if (G_OPT_TYPE(opt) == G_TYPE_BOOL) {
368                         assert(opt->go_val == NULL);
369                         set_option(req, opt, "0");
370                 } else {
371                         if (opt->go_val == NULL) {
372                                 warnx("Option '%c' not specified.",
373                                     opt->go_char);
374                                 usage();
375                         } else if (opt->go_val == G_VAL_OPTIONAL) {
376                                 /* add nothing. */
377                         } else {
378                                 set_option(req, opt, opt->go_val);
379                         }
380                 }
381         }
382
383         /*
384          * Add rest of given arguments.
385          */
386         gctl_ro_param(req, "nargs", sizeof(int), argc);
387         for (i = 0; i < (unsigned)*argc; i++) {
388                 char argname[16];
389
390                 snprintf(argname, sizeof(argname), "arg%u", i);
391                 gctl_ro_param(req, argname, -1, (*argv)[i]);
392         }
393 }
394
395 /*
396  * Find given command in commands available for given class.
397  */
398 static struct g_command *
399 find_command(const char *cmdstr, int flags)
400 {
401         struct g_command *cmd;
402         unsigned i;
403
404         /*
405          * First try to find command defined by loaded library.
406          */
407         if ((flags & GEOM_CLASS_CMDS) != 0 && class_commands != NULL) {
408                 for (i = 0; ; i++) {
409                         cmd = &class_commands[i];
410                         if (cmd->gc_name == NULL)
411                                 break;
412                         if (strcmp(cmd->gc_name, cmdstr) == 0)
413                                 return (cmd);
414                 }
415         }
416         /*
417          * Now try to find in standard commands.
418          */
419         if ((flags & GEOM_STD_CMDS) != 0) {
420                 for (i = 0; ; i++) {
421                         cmd = &std_commands[i];
422                         if (cmd->gc_name == NULL)
423                                 break;
424                         if (strcmp(cmd->gc_name, cmdstr) == 0)
425                                 return (cmd);
426                 }
427         }
428         return (NULL);
429 }
430
431 static unsigned
432 set_flags(struct g_command *cmd)
433 {
434         unsigned flags = 0;
435
436         if ((cmd->gc_flags & G_FLAG_VERBOSE) != 0 && verbose)
437                 flags |= G_FLAG_VERBOSE;
438
439         return (flags);
440 }
441
442 /*
443  * Run command.
444  */
445 static void
446 run_command(int argc, char *argv[])
447 {
448         struct g_command *cmd;
449         struct gctl_req *req;
450         const char *errstr;
451         char buf[4096];
452
453         /* First try to find a command defined by a class. */
454         cmd = find_command(argv[0], GEOM_CLASS_CMDS);
455         if (cmd == NULL) {
456                 /* Now, try to find a standard command. */
457                 cmd = find_command(argv[0], GEOM_STD_CMDS);
458                 if (cmd == NULL) {
459                         warnx("Unknown command: %s.", argv[0]);
460                         usage();
461                 }
462                 if (!std_available(cmd->gc_name)) {
463                         warnx("Command '%s' not available.", argv[0]);
464                         exit(EXIT_FAILURE);
465                 }
466         }
467         if ((cmd->gc_flags & G_FLAG_LOADKLD) != 0)
468                 load_module();
469
470         req = gctl_get_handle();
471         gctl_ro_param(req, "class", -1, gclass_name);
472         gctl_ro_param(req, "verb", -1, argv[0]);
473         if (version != NULL)
474                 gctl_ro_param(req, "version", sizeof(*version), version);
475         parse_arguments(cmd, req, &argc, &argv);
476
477         bzero(buf, sizeof(buf));
478         if (cmd->gc_func != NULL) {
479                 unsigned flags;
480
481                 flags = set_flags(cmd);
482                 cmd->gc_func(req, flags);
483                 errstr = req->error;
484         } else {
485                 gctl_rw_param(req, "output", sizeof(buf), buf);
486                 errstr = gctl_issue(req);
487         }
488         if (errstr != NULL && errstr[0] != '\0') {
489                 warnx("%s", errstr);
490                 if (strncmp(errstr, "warning: ", strlen("warning: ")) != 0) {
491                         gctl_free(req);
492                         exit(EXIT_FAILURE);
493                 }
494         }
495         if (buf[0] != '\0')
496                 printf("%s", buf);
497         gctl_free(req);
498         if (verbose)
499                 printf("Done.\n");
500         exit(EXIT_SUCCESS);
501 }
502
503 #ifndef STATIC_GEOM_CLASSES
504 static const char *
505 library_path(void)
506 {
507         const char *path;
508
509         path = getenv("GEOM_LIBRARY_PATH");
510         if (path == NULL)
511                 path = GEOM_CLASS_DIR;
512         return (path);
513 }
514
515 static void
516 load_library(void)
517 {
518         char *curpath, path[MAXPATHLEN], *tofree, *totalpath;
519         uint32_t *lib_version;
520         void *dlh;
521         int ret;
522
523         ret = 0;
524         tofree = totalpath = strdup(library_path());
525         if (totalpath == NULL)
526                 err(EXIT_FAILURE, "Not enough memory for library path");
527
528         if (strchr(totalpath, ':') != NULL)
529                 curpath = strsep(&totalpath, ":");
530         else
531                 curpath = totalpath;
532         /* Traverse the paths to find one that contains the library we want. */
533         while (curpath != NULL) {
534                 snprintf(path, sizeof(path), "%s/geom_%s.so", curpath,
535                     class_name);
536                 ret = access(path, F_OK);
537                 if (ret == -1) {
538                         if (errno == ENOENT) {
539                                 /*
540                                  * If we cannot find library, try the next
541                                  * path.
542                                  */
543                                 curpath = strsep(&totalpath, ":");
544                                 continue;
545                         }
546                         err(EXIT_FAILURE, "Cannot access library");
547                 }
548                 break;
549         }
550         free(tofree);
551         /* No library was found, but standard commands can still be used */
552         if (ret == -1)
553                 return;
554         dlh = dlopen(path, RTLD_NOW);
555         if (dlh == NULL)
556                 errx(EXIT_FAILURE, "Cannot open library: %s.", dlerror());
557         lib_version = dlsym(dlh, "lib_version");
558         if (lib_version == NULL) {
559                 warnx("Cannot find symbol %s: %s.", "lib_version", dlerror());
560                 dlclose(dlh);
561                 exit(EXIT_FAILURE);
562         }
563         if (*lib_version != G_LIB_VERSION) {
564                 dlclose(dlh);
565                 errx(EXIT_FAILURE, "%s and %s are not synchronized.",
566                     getprogname(), path);
567         }
568         version = dlsym(dlh, "version");
569         if (version == NULL) {
570                 warnx("Cannot find symbol %s: %s.", "version", dlerror());
571                 dlclose(dlh);
572                 exit(EXIT_FAILURE);
573         }
574         class_commands = dlsym(dlh, "class_commands");
575         if (class_commands == NULL) {
576                 warnx("Cannot find symbol %s: %s.", "class_commands",
577                     dlerror());
578                 dlclose(dlh);
579                 exit(EXIT_FAILURE);
580         }
581 }
582 #endif  /* !STATIC_GEOM_CLASSES */
583
584 /*
585  * Class name should be all capital letters.
586  */
587 static void
588 set_class_name(void)
589 {
590         char *s1, *s2;
591
592         s1 = class_name;
593         for (; *s1 != '\0'; s1++)
594                 *s1 = tolower(*s1);
595         gclass_name = malloc(strlen(class_name) + 1);
596         if (gclass_name == NULL)
597                 errx(EXIT_FAILURE, "No memory");
598         s1 = gclass_name;
599         s2 = class_name;
600         for (; *s2 != '\0'; s2++)
601                 *s1++ = toupper(*s2);
602         *s1 = '\0';
603 }
604
605 static void
606 get_class(int *argc, char ***argv)
607 {
608
609         snprintf(comm, sizeof(comm), "%s", basename((*argv)[0]));
610         if (strcmp(comm, "geom") == 0) {
611                 if (*argc < 2)
612                         usage();
613                 else if (*argc == 2) {
614                         if (strcmp((*argv)[1], "-h") == 0 ||
615                             strcmp((*argv)[1], "help") == 0) {
616                                 usage();
617                         }
618                 }
619                 strlcatf(comm, sizeof(comm), " %s", (*argv)[1]);
620                 class_name = (*argv)[1];
621                 *argc -= 2;
622                 *argv += 2;
623         } else if (*comm == 'g') {
624                 class_name = comm + 1;
625                 *argc -= 1;
626                 *argv += 1;
627         } else {
628                 errx(EXIT_FAILURE, "Invalid utility name.");
629         }
630
631 #ifndef STATIC_GEOM_CLASSES
632         load_library();
633 #else
634         if (!strcasecmp(class_name, "part")) {
635                 version = &gpart_version;
636                 class_commands = gpart_class_commands;
637         } else if (!strcasecmp(class_name, "label")) {
638                 version = &glabel_version;
639                 class_commands = glabel_class_commands;
640         }
641 #endif /* !STATIC_GEOM_CLASSES */
642
643         set_class_name();
644
645         /* If we can't load or list, it's not a class. */
646         if (!std_available("load") && !std_available("list"))
647                 errx(EXIT_FAILURE, "Invalid class name.");
648
649         if (*argc < 1)
650                 usage();
651 }
652
653 int
654 main(int argc, char *argv[])
655 {
656
657         get_class(&argc, &argv);
658         run_command(argc, argv);
659         /* NOTREACHED */
660
661         exit(EXIT_FAILURE);
662 }
663
664 static struct gclass *
665 find_class(struct gmesh *mesh, const char *name)
666 {
667         struct gclass *classp;
668
669         LIST_FOREACH(classp, &mesh->lg_class, lg_class) {
670                 if (strcmp(classp->lg_name, name) == 0)
671                         return (classp);
672         }
673         return (NULL);
674 }
675
676 static struct ggeom *
677 find_geom(struct gclass *classp, const char *name)
678 {
679         struct ggeom *gp;
680
681         LIST_FOREACH(gp, &classp->lg_geom, lg_geom) {
682                 if (strcmp(gp->lg_name, name) == 0)
683                         return (gp);
684         }
685         return (NULL);
686 }
687
688 static void
689 list_one_provider(struct gprovider *pp, const char *prefix)
690 {
691         struct gconfig *conf;
692         char buf[5];
693
694         printf("Name: %s\n", pp->lg_name);
695         humanize_number(buf, sizeof(buf), (int64_t)pp->lg_mediasize, "",
696             HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
697         printf("%sMediasize: %jd (%s)\n", prefix, (intmax_t)pp->lg_mediasize,
698             buf);
699         printf("%sSectorsize: %u\n", prefix, pp->lg_sectorsize);
700         if (pp->lg_stripesize > 0 || pp->lg_stripeoffset > 0) {
701                 printf("%sStripesize: %ju\n", prefix, pp->lg_stripesize);
702                 printf("%sStripeoffset: %ju\n", prefix, pp->lg_stripeoffset);
703         }
704         printf("%sMode: %s\n", prefix, pp->lg_mode);
705         LIST_FOREACH(conf, &pp->lg_config, lg_config) {
706                 printf("%s%s: %s\n", prefix, conf->lg_name, conf->lg_val);
707         }
708 }
709
710 static void
711 list_one_consumer(struct gconsumer *cp, const char *prefix)
712 {
713         struct gprovider *pp;
714         struct gconfig *conf;
715
716         pp = cp->lg_provider;
717         if (pp == NULL)
718                 printf("[no provider]\n");
719         else {
720                 char buf[5];
721
722                 printf("Name: %s\n", pp->lg_name);
723                 humanize_number(buf, sizeof(buf), (int64_t)pp->lg_mediasize, "",
724                     HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
725                 printf("%sMediasize: %jd (%s)\n", prefix,
726                     (intmax_t)pp->lg_mediasize, buf);
727                 printf("%sSectorsize: %u\n", prefix, pp->lg_sectorsize);
728                 if (pp->lg_stripesize > 0 || pp->lg_stripeoffset > 0) {
729                         printf("%sStripesize: %ju\n", prefix, pp->lg_stripesize);
730                         printf("%sStripeoffset: %ju\n", prefix, pp->lg_stripeoffset);
731                 }
732                 printf("%sMode: %s\n", prefix, cp->lg_mode);
733         }
734         LIST_FOREACH(conf, &cp->lg_config, lg_config) {
735                 printf("%s%s: %s\n", prefix, conf->lg_name, conf->lg_val);
736         }
737 }
738
739 static void
740 list_one_geom(struct ggeom *gp)
741 {
742         struct gprovider *pp;
743         struct gconsumer *cp;
744         struct gconfig *conf;
745         unsigned n;
746
747         printf("Geom name: %s\n", gp->lg_name);
748         LIST_FOREACH(conf, &gp->lg_config, lg_config) {
749                 printf("%s: %s\n", conf->lg_name, conf->lg_val);
750         }
751         if (!LIST_EMPTY(&gp->lg_provider)) {
752                 printf("Providers:\n");
753                 n = 1;
754                 LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
755                         printf("%u. ", n++);
756                         list_one_provider(pp, "   ");
757                 }
758         }
759         if (!LIST_EMPTY(&gp->lg_consumer)) {
760                 printf("Consumers:\n");
761                 n = 1;
762                 LIST_FOREACH(cp, &gp->lg_consumer, lg_consumer) {
763                         printf("%u. ", n++);
764                         list_one_consumer(cp, "   ");
765                 }
766         }
767         printf("\n");
768 }
769
770 static void
771 std_help(struct gctl_req *req __unused, unsigned flags __unused)
772 {
773
774         usage();
775 }
776
777 static int
778 std_list_available(void)
779 {
780         struct gmesh mesh;
781         struct gclass *classp;
782         int error;
783
784         error = geom_gettree(&mesh);
785         if (error != 0)
786                 errc(EXIT_FAILURE, error, "Cannot get GEOM tree");
787         classp = find_class(&mesh, gclass_name);
788         geom_deletetree(&mesh);
789         if (classp != NULL)
790                 return (1);
791         return (0);
792 }
793
794 static void
795 std_list(struct gctl_req *req, unsigned flags __unused)
796 {
797         struct gmesh mesh;
798         struct gclass *classp;
799         struct ggeom *gp;
800         const char *name;
801         int all, error, i, nargs;
802
803         error = geom_gettree(&mesh);
804         if (error != 0)
805                 errc(EXIT_FAILURE, error, "Cannot get GEOM tree");
806         classp = find_class(&mesh, gclass_name);
807         if (classp == NULL) {
808                 geom_deletetree(&mesh);
809                 errx(EXIT_FAILURE, "Class %s not found.", gclass_name);
810         }
811         nargs = gctl_get_int(req, "nargs");
812         all = gctl_get_int(req, "all");
813         if (nargs > 0) {
814                 for (i = 0; i < nargs; i++) {
815                         name = gctl_get_ascii(req, "arg%d", i);
816                         gp = find_geom(classp, name);
817                         if (gp == NULL)
818                                 errx(EXIT_FAILURE, "No such geom: %s.", name);
819                         list_one_geom(gp);
820                 }
821         } else {
822                 LIST_FOREACH(gp, &classp->lg_geom, lg_geom) {
823                         if (LIST_EMPTY(&gp->lg_provider) && !all)
824                                 continue;
825                         list_one_geom(gp);
826                 }
827         }
828         geom_deletetree(&mesh);
829 }
830
831 static int
832 std_status_available(void)
833 {
834
835         /* 'status' command is available when 'list' command is. */
836         return (std_list_available());
837 }
838
839 static void
840 status_update_len(struct ggeom *gp, int *name_len, int *status_len)
841 {
842         struct gconfig *conf;
843         int len;
844
845         assert(gp != NULL);
846         assert(name_len != NULL);
847         assert(status_len != NULL);
848
849         len = strlen(gp->lg_name);
850         if (*name_len < len)
851                 *name_len = len;
852         LIST_FOREACH(conf, &gp->lg_config, lg_config) {
853                 if (strcasecmp(conf->lg_name, "state") == 0) {
854                         len = strlen(conf->lg_val);
855                         if (*status_len < len)
856                                 *status_len = len;
857                 }
858         }
859 }
860
861 static void
862 status_update_len_prs(struct ggeom *gp, int *name_len, int *status_len)
863 {
864         struct gprovider *pp;
865         struct gconfig *conf;
866         int len, glen;
867
868         assert(gp != NULL);
869         assert(name_len != NULL);
870         assert(status_len != NULL);
871
872         glen = 0;
873         LIST_FOREACH(conf, &gp->lg_config, lg_config) {
874                 if (strcasecmp(conf->lg_name, "state") == 0) {
875                         glen = strlen(conf->lg_val);
876                         break;
877                 }
878         }
879         LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
880                 len = strlen(pp->lg_name);
881                 if (*name_len < len)
882                         *name_len = len;
883                 len = glen;
884                 LIST_FOREACH(conf, &pp->lg_config, lg_config) {
885                         if (strcasecmp(conf->lg_name, "state") == 0) {
886                                 len = strlen(conf->lg_val);
887                                 break;
888                         }
889                 }
890                 if (*status_len < len)
891                         *status_len = len;
892         }
893 }
894
895 static char *
896 status_one_consumer(struct gconsumer *cp)
897 {
898         static char buf[256];
899         struct gprovider *pp;
900         struct gconfig *conf;
901         const char *state, *syncr;
902
903         pp = cp->lg_provider;
904         if (pp == NULL)
905                 return (NULL);
906         state = NULL;
907         syncr = NULL;
908         LIST_FOREACH(conf, &cp->lg_config, lg_config) {
909                 if (strcasecmp(conf->lg_name, "state") == 0)
910                         state = conf->lg_val;
911                 if (strcasecmp(conf->lg_name, "synchronized") == 0)
912                         syncr = conf->lg_val;
913         }
914         if (state == NULL && syncr == NULL)
915                 snprintf(buf, sizeof(buf), "%s", pp->lg_name);
916         else if (state != NULL && syncr != NULL) {
917                 snprintf(buf, sizeof(buf), "%s (%s, %s)", pp->lg_name,
918                     state, syncr);
919         } else {
920                 snprintf(buf, sizeof(buf), "%s (%s)", pp->lg_name,
921                     state ? state : syncr);
922         }
923         return (buf);
924 }
925
926 static void
927 status_one_geom(struct ggeom *gp, int script, int name_len, int status_len)
928 {
929         struct gconsumer *cp;
930         struct gconfig *conf;
931         const char *name, *status, *component;
932         int gotone;
933
934         name = gp->lg_name;
935         status = "N/A";
936         LIST_FOREACH(conf, &gp->lg_config, lg_config) {
937                 if (strcasecmp(conf->lg_name, "state") == 0) {
938                         status = conf->lg_val;
939                         break;
940                 }
941         }
942         gotone = 0;
943         LIST_FOREACH(cp, &gp->lg_consumer, lg_consumer) {
944                 component = status_one_consumer(cp);
945                 if (component == NULL)
946                         continue;
947                 gotone = 1;
948                 printf("%*s  %*s  %s\n", name_len, name, status_len, status,
949                     component);
950                 if (!script)
951                         name = status = "";
952         }
953         if (!gotone) {
954                 printf("%*s  %*s  %s\n", name_len, name, status_len, status,
955                     "N/A");
956         }
957 }
958
959 static void
960 status_one_geom_prs(struct ggeom *gp, int script, int name_len, int status_len)
961 {
962         struct gprovider *pp;
963         struct gconsumer *cp;
964         struct gconfig *conf;
965         const char *name, *status, *component;
966         int gotone;
967
968         LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
969                 name = pp->lg_name;
970                 status = "N/A";
971                 LIST_FOREACH(conf, &gp->lg_config, lg_config) {
972                         if (strcasecmp(conf->lg_name, "state") == 0) {
973                                 status = conf->lg_val;
974                                 break;
975                         }
976                 }
977                 LIST_FOREACH(conf, &pp->lg_config, lg_config) {
978                         if (strcasecmp(conf->lg_name, "state") == 0) {
979                                 status = conf->lg_val;
980                                 break;
981                         }
982                 }
983                 gotone = 0;
984                 LIST_FOREACH(cp, &gp->lg_consumer, lg_consumer) {
985                         component = status_one_consumer(cp);
986                         if (component == NULL)
987                                 continue;
988                         gotone = 1;
989                         printf("%*s  %*s  %s\n", name_len, name,
990                             status_len, status, component);
991                         if (!script)
992                                 name = status = "";
993                 }
994                 if (!gotone) {
995                         printf("%*s  %*s  %s\n", name_len, name,
996                             status_len, status, "N/A");
997                 }
998         }
999 }
1000
1001 static void
1002 std_status(struct gctl_req *req, unsigned flags __unused)
1003 {
1004         struct gmesh mesh;
1005         struct gclass *classp;
1006         struct ggeom *gp;
1007         const char *name;
1008         int name_len, status_len;
1009         int all, error, geoms, i, n, nargs, script;
1010
1011         error = geom_gettree(&mesh);
1012         if (error != 0)
1013                 errc(EXIT_FAILURE, error, "Cannot get GEOM tree");
1014         classp = find_class(&mesh, gclass_name);
1015         if (classp == NULL)
1016                 errx(EXIT_FAILURE, "Class %s not found.", gclass_name);
1017         nargs = gctl_get_int(req, "nargs");
1018         all = gctl_get_int(req, "all");
1019         geoms = gctl_get_int(req, "geoms");
1020         script = gctl_get_int(req, "script");
1021         if (script) {
1022                 name_len = 0;
1023                 status_len = 0;
1024         } else {
1025                 name_len = strlen("Name");
1026                 status_len = strlen("Status");
1027         }
1028         if (nargs > 0) {
1029                 for (i = 0, n = 0; i < nargs; i++) {
1030                         name = gctl_get_ascii(req, "arg%d", i);
1031                         gp = find_geom(classp, name);
1032                         if (gp == NULL)
1033                                 errx(EXIT_FAILURE, "No such geom: %s.", name);
1034                         if (geoms) {
1035                                 status_update_len(gp,
1036                                     &name_len, &status_len);
1037                         } else {
1038                                 status_update_len_prs(gp,
1039                                     &name_len, &status_len);
1040                         }
1041                         n++;
1042                 }
1043                 if (n == 0)
1044                         goto end;
1045         } else {
1046                 n = 0;
1047                 LIST_FOREACH(gp, &classp->lg_geom, lg_geom) {
1048                         if (LIST_EMPTY(&gp->lg_provider) && !all)
1049                                 continue;
1050                         if (geoms) {
1051                                 status_update_len(gp,
1052                                     &name_len, &status_len);
1053                         } else {
1054                                 status_update_len_prs(gp,
1055                                     &name_len, &status_len);
1056                         }
1057                         n++;
1058                 }
1059                 if (n == 0)
1060                         goto end;
1061         }
1062         if (!script) {
1063                 printf("%*s  %*s  %s\n", name_len, "Name", status_len, "Status",
1064                     "Components");
1065         }
1066         if (nargs > 0) {
1067                 for (i = 0; i < nargs; i++) {
1068                         name = gctl_get_ascii(req, "arg%d", i);
1069                         gp = find_geom(classp, name);
1070                         if (gp == NULL)
1071                                 continue;
1072                         if (geoms) {
1073                                 status_one_geom(gp, script, name_len,
1074                                     status_len);
1075                         } else {
1076                                 status_one_geom_prs(gp, script, name_len,
1077                                     status_len);
1078                         }
1079                 }
1080         } else {
1081                 LIST_FOREACH(gp, &classp->lg_geom, lg_geom) {
1082                         if (LIST_EMPTY(&gp->lg_provider) && !all)
1083                                 continue;
1084                         if (geoms) {
1085                                 status_one_geom(gp, script, name_len,
1086                                     status_len);
1087                         } else {
1088                                 status_one_geom_prs(gp, script, name_len,
1089                                     status_len);
1090                         }
1091                 }
1092         }
1093 end:
1094         geom_deletetree(&mesh);
1095 }
1096
1097 static int
1098 std_load_available(void)
1099 {
1100         char name[MAXPATHLEN], paths[MAXPATHLEN * 8], *p;
1101         struct stat sb;
1102         size_t len;
1103
1104         snprintf(name, sizeof(name), "g_%s", class_name);
1105         /*
1106          * If already in kernel, "load" command is not available.
1107          */
1108         if (modfind(name) >= 0)
1109                 return (0);
1110         bzero(paths, sizeof(paths));
1111         len = sizeof(paths);
1112         if (sysctlbyname("kern.module_path", paths, &len, NULL, 0) < 0)
1113                 err(EXIT_FAILURE, "sysctl(kern.module_path)");
1114         for (p = strtok(paths, ";"); p != NULL; p = strtok(NULL, ";")) {
1115                 snprintf(name, sizeof(name), "%s/geom_%s.ko", p, class_name);
1116                 /*
1117                  * If geom_<name>.ko file exists, "load" command is available.
1118                  */
1119                 if (stat(name, &sb) == 0)
1120                         return (1);
1121         }
1122         return (0);
1123 }
1124
1125 static void
1126 std_load(struct gctl_req *req __unused, unsigned flags)
1127 {
1128
1129         /*
1130          * Do nothing special here, because of G_FLAG_LOADKLD flag,
1131          * module is already loaded.
1132          */
1133         if ((flags & G_FLAG_VERBOSE) != 0)
1134                 printf("Module available.\n");
1135 }
1136
1137 static int
1138 std_unload_available(void)
1139 {
1140         char name[64];
1141         int id;
1142
1143         snprintf(name, sizeof(name), "geom_%s", class_name);
1144         id = kldfind(name);
1145         if (id >= 0)
1146                 return (1);
1147         return (0);
1148 }
1149
1150 static void
1151 std_unload(struct gctl_req *req, unsigned flags __unused)
1152 {
1153         char name[64];
1154         int id;
1155
1156         snprintf(name, sizeof(name), "geom_%s", class_name);
1157         id = kldfind(name);
1158         if (id < 0) {
1159                 gctl_error(req, "Could not find module: %s.", strerror(errno));
1160                 return;
1161         }
1162         if (kldunload(id) < 0) {
1163                 gctl_error(req, "Could not unload module: %s.",
1164                     strerror(errno));
1165                 return;
1166         }
1167 }
1168
1169 static int
1170 std_available(const char *name)
1171 {
1172
1173         if (strcmp(name, "help") == 0)
1174                 return (1);
1175         else if (strcmp(name, "list") == 0)
1176                 return (std_list_available());
1177         else if (strcmp(name, "status") == 0)
1178                 return (std_status_available());
1179         else if (strcmp(name, "load") == 0)
1180                 return (std_load_available());
1181         else if (strcmp(name, "unload") == 0)
1182                 return (std_unload_available());
1183         else
1184                 assert(!"Unknown standard command.");
1185         return (0);
1186 }