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