Merge branch 'vendor/OPENSSL'
[dragonfly.git] / sbin / ccdconfig / ccdconfig.c
1 /*
2  * Copyright (c) 1995 Jason R. Thorpe.
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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed for the NetBSD Project
16  *      by Jason R. Thorpe.
17  * 4. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $NetBSD: ccdconfig.c,v 1.2.2.1 1995/11/11 02:43:35 thorpej Exp $
33  * $FreeBSD: src/sbin/ccdconfig/ccdconfig.c,v 1.16.2.2 2000/12/11 01:03:25 obrien Exp $
34  */
35
36 #define _KERNEL_STRUCTURES
37 #include <sys/param.h>
38 #include <sys/linker.h>
39 #include <sys/stat.h>
40 #include <sys/module.h>
41 #include <ctype.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <kvm.h>
46 #include <limits.h>
47 #include <paths.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52
53 #include <sys/devicestat.h>
54 #include <sys/ccdvar.h>
55
56 #include "pathnames.h"
57
58 static  int lineno = 0;
59 static  int verbose = 0;
60 static  const char *ccdconf = _PATH_CCDCONF;
61
62 static  char *core = NULL;
63 static  char *kernel = NULL;
64
65 struct  flagval {
66         const char      *fv_flag;
67         int     fv_val;
68 } flagvaltab[] = {
69         { "CCDF_SWAP",          CCDF_SWAP },
70         { "CCDF_UNIFORM",       CCDF_UNIFORM },
71         { "CCDF_MIRROR",        CCDF_MIRROR },
72         { "CCDF_PARITY",        CCDF_PARITY },
73         { NULL,                 0 },
74 };
75
76 static  struct nlist nl[] = {
77         { "_ccd_softc", 0, 0, 0, 0 },
78 #define SYM_CCDSOFTC            0
79         { "_numccd", 0, 0, 0, 0 },
80 #define SYM_NUMCCD              1
81         { NULL , 0, 0, 0, 0 },
82 };
83
84 #define CCD_CONFIG              0       /* configure a device */
85 #define CCD_CONFIGALL           1       /* configure all devices */
86 #define CCD_UNCONFIG            2       /* unconfigure a device */
87 #define CCD_UNCONFIGALL         3       /* unconfigure all devices */
88 #define CCD_DUMP                4       /* dump a ccd's configuration */
89
90 static  int checkdev(char *);
91 static  int do_io(char *, u_long, struct ccd_ioctl *);
92 static  int do_single(int, char **, int);
93 static  int do_all(int);
94 static  int dump_ccd(int, char **);
95 static  int getmaxpartitions(void);
96 static  int flags_to_val(char *);
97 static  void print_ccd_info(struct ccd_softc *, kvm_t *);
98 static  char *resolve_ccdname(char *);
99 static  void usage(void);
100
101 int
102 main(int argc, char **argv)
103 {
104         int ch, options = 0, action = CCD_CONFIG;
105
106         while ((ch = getopt(argc, argv, "cCf:gM:N:uUv")) != -1) {
107                 switch (ch) {
108                 case 'c':
109                         action = CCD_CONFIG;
110                         ++options;
111                         break;
112
113                 case 'C':
114                         action = CCD_CONFIGALL;
115                         ++options;
116                         break;
117
118                 case 'f':
119                         ccdconf = optarg;
120                         break;
121
122                 case 'g':
123                         action = CCD_DUMP;
124                         break;
125
126                 case 'M':
127                         core = optarg;
128                         break;
129
130                 case 'N':
131                         kernel = optarg;
132                         break;
133
134                 case 'u':
135                         action = CCD_UNCONFIG;
136                         ++options;
137                         break;
138
139                 case 'U':
140                         action = CCD_UNCONFIGALL;
141                         ++options;
142                         break;
143
144                 case 'v':
145                         verbose = 1;
146                         break;
147
148                 default:
149                         usage();
150                 }
151         }
152         argc -= optind;
153         argv += optind;
154
155         if (options > 1)
156                 usage();
157
158         /*
159          * Discard setgid privileges if not the running kernel so that bad
160          * guys can't print interesting stuff from kernel memory.
161          */
162         if (core != NULL || kernel != NULL || action != CCD_DUMP) {
163                 setegid(getgid());
164                 setgid(getgid());
165         }
166
167         if (modfind("ccd") < 0) {
168                 /* Not present in kernel, try loading it */
169                 if (kldload("ccd") < 0 || modfind("ccd") < 0) {
170                         warn("ccd module not available!\n"
171                             "NOTE: Systems which don't have /boot as part of"
172                             " the root partition\n"
173                             "      (as is the case with the default HAMMER"
174                             " install) need to load ccd(4)\n"
175                             "      via /boot/loader.conf or compile it into"
176                             " the kernel.");
177                 }
178         }
179
180         switch (action) {
181                 case CCD_CONFIG:
182                 case CCD_UNCONFIG:
183                         exit(do_single(argc, argv, action));
184                         /* NOTREACHED */
185
186                 case CCD_CONFIGALL:
187                 case CCD_UNCONFIGALL:
188                         exit(do_all(action));
189                         /* NOTREACHED */
190
191                 case CCD_DUMP:
192                         exit(dump_ccd(argc, argv));
193                         /* NOTREACHED */
194         }
195         /* NOTREACHED */
196         return (0);
197 }
198
199 static int
200 do_single(int argc, char **argv, int action)
201 {
202         struct ccd_ioctl ccio;
203         char *ccd, *cp, *cp2, **disks;
204         int noflags = 0, ileave, flags = 0, j;
205         unsigned int i;
206
207         bzero(&ccio, sizeof(ccio));
208
209         /*
210          * If unconfiguring, all arguments are treated as ccds.
211          */
212         if (action == CCD_UNCONFIG || action == CCD_UNCONFIGALL) {
213                 for (i = 0; argc != 0; ) {
214                         cp = *argv++; --argc;
215                         if ((ccd = resolve_ccdname(cp)) == NULL) {
216                                 warnx("invalid ccd name: %s", cp);
217                                 i = 1;
218                                 continue;
219                         }
220                         if (do_io(ccd, CCDIOCCLR, &ccio))
221                                 i = 1;
222                         else
223                                 if (verbose)
224                                         printf("%s unconfigured\n", cp);
225                 }
226                 return (i);
227         }
228
229         /* Make sure there are enough arguments. */
230         if (argc < 4) {
231                 if (argc == 3) {
232                         /* Assume that no flags are specified. */
233                         noflags = 1;
234                 } else {
235                         if (action == CCD_CONFIGALL) {
236                                 warnx("%s: bad line: %d", ccdconf, lineno);
237                                 return (1);
238                         } else
239                                 usage();
240                 }
241         }
242
243         /* First argument is the ccd to configure. */
244         cp = *argv++; --argc;
245         if ((ccd = resolve_ccdname(cp)) == NULL) {
246                 warnx("invalid ccd name: %s", cp);
247                 return (1);
248         }
249
250         /* Next argument is the interleave factor. */
251         cp = *argv++; --argc;
252         errno = 0;      /* to check for ERANGE */
253         ileave = (int)strtol(cp, &cp2, 10);
254         if ((errno == ERANGE) || (ileave < 0) || (*cp2 != '\0')) {
255                 warnx("invalid interleave factor: %s", cp);
256                 return (1);
257         }
258
259         if (noflags == 0) {
260                 /* Next argument is the ccd configuration flags. */
261                 cp = *argv++; --argc;
262                 if ((flags = flags_to_val(cp)) < 0) {
263                         warnx("invalid flags argument: %s", cp);
264                         return (1);
265                 }
266         }
267
268         /* Next is the list of disks to make the ccd from. */
269         disks = malloc(argc * sizeof(char *));
270         if (disks == NULL) {
271                 warnx("no memory to configure ccd");
272                 return (1);
273         }
274         for (i = 0; argc != 0; ) {
275                 cp = *argv++; --argc;
276                 if ((j = checkdev(cp)) == 0)
277                         disks[i++] = cp;
278                 else {
279                         warnx("%s: %s", cp, strerror(j));
280                         return (1);
281                 }
282         }
283
284         /* Fill in the ccio. */
285         ccio.ccio_disks = disks;
286         ccio.ccio_ndisks = i;
287         ccio.ccio_ileave = ileave;
288         ccio.ccio_flags = flags;
289
290         if (do_io(ccd, CCDIOCSET, &ccio)) {
291                 free(disks);
292                 return (1);
293         }
294
295         if (verbose) {
296                 printf("ccd%d: %d components ", ccio.ccio_unit,
297                     ccio.ccio_ndisks);
298                 for (i = 0; i < ccio.ccio_ndisks; ++i) {
299                         if ((cp2 = strrchr(disks[i], '/')) != NULL)
300                                 ++cp2;
301                         else
302                                 cp2 = disks[i];
303                         printf("%c%s%c",
304                             i == 0 ? '(' : ' ', cp2,
305                             i == ccio.ccio_ndisks - 1 ? ')' : ',');
306                 }
307                 printf(", %ju blocks ", (uintmax_t)ccio.ccio_size);
308                 if (ccio.ccio_ileave != 0)
309                         printf("interleaved at %d blocks\n", ccio.ccio_ileave);
310                 else
311                         printf("concatenated\n");
312         }
313
314         free(disks);
315         return (0);
316 }
317
318 static int
319 do_all(int action)
320 {
321         FILE *f;
322         char line[_POSIX2_LINE_MAX];
323         char *cp, **argv;
324         int argc, rval;
325         gid_t egid;
326
327         rval = 0;
328         egid = getegid();
329         setegid(getgid());
330         if ((f = fopen(ccdconf, "r")) == NULL) {
331                 setegid(egid);
332                 warn("fopen: %s", ccdconf);
333                 return (1);
334         }
335         setegid(egid);
336
337         while (fgets(line, sizeof(line), f) != NULL) {
338                 argc = 0;
339                 argv = NULL;
340                 ++lineno;
341                 if ((cp = strrchr(line, '\n')) != NULL)
342                         *cp = '\0';
343
344                 /* Break up the line and pass it's contents to do_single(). */
345                 if (line[0] == '\0')
346                         goto end_of_line;
347                 for (cp = line; (cp = strtok(cp, " \t")) != NULL; cp = NULL) {
348                         if (*cp == '#')
349                                 break;
350                         if ((argv = realloc(argv,
351                             sizeof(char *) * ++argc)) == NULL) {
352                                 warnx("no memory to configure ccds");
353                                 return (1);
354                         }
355                         argv[argc - 1] = cp;
356                         /*
357                          * If our action is to unconfigure all, then pass
358                          * just the first token to do_single() and ignore
359                          * the rest.  Since this will be encountered on
360                          * our first pass through the line, the Right
361                          * Thing will happen.
362                          */
363                         if (action == CCD_UNCONFIGALL) {
364                                 if (do_single(argc, argv, action))
365                                         rval = 1;
366                                 goto end_of_line;
367                         }
368                 }
369                 if (argc != 0)
370                         if (do_single(argc, argv, action))
371                                 rval = 1;
372
373  end_of_line:
374                 if (argv != NULL)
375                         free(argv);
376         }
377
378         fclose(f);
379         return (rval);
380 }
381
382 static int
383 checkdev(char *path)
384 {
385         struct stat st;
386
387         if (stat(path, &st) != 0)
388                 return (errno);
389
390         if (!S_ISBLK(st.st_mode) && !S_ISCHR(st.st_mode))
391                 return (EINVAL);
392
393         return (0);
394 }
395
396 static int
397 pathtounit(char *path, int *unitp)
398 {
399         struct stat st;
400         int maxpartitions;
401
402         if (stat(path, &st) != 0)
403                 return (errno);
404
405         if (!S_ISBLK(st.st_mode) && !S_ISCHR(st.st_mode))
406                 return (EINVAL);
407
408         if ((maxpartitions = getmaxpartitions()) < 0)
409                 return (errno);
410
411         *unitp = minor(st.st_rdev) / maxpartitions;
412
413         return (0);
414 }
415
416 static char *
417 resolve_ccdname(char *name)
418 {
419         char *path;
420
421         if (name[0] == '/' || name[0] == '.') {
422                 /* Assume they gave the correct pathname. */
423                 return (strdup(name));
424         }
425
426         asprintf(&path, "%s%s", _PATH_DEV, name);
427
428         return (path);
429 }
430
431 static int
432 do_io(char *path, u_long cmd, struct ccd_ioctl *cciop)
433 {
434         int fd;
435         const char *cp;
436
437         if ((fd = open(path, O_RDWR, 0640)) < 0) {
438                 warn("open: %s", path);
439                 return (1);
440         }
441
442         if (ioctl(fd, cmd, cciop) < 0) {
443                 switch (cmd) {
444                 case CCDIOCSET:
445                         cp = "CCDIOCSET";
446                         break;
447
448                 case CCDIOCCLR:
449                         cp = "CCDIOCCLR";
450                         break;
451
452                 default:
453                         cp = "unknown";
454                 }
455                 warn("ioctl (%s): %s", cp, path);
456                 return (1);
457         }
458
459         return (0);
460 }
461
462 #define KVM_ABORT(kd, str) {                                            \
463         kvm_close((kd));                                                \
464         warnx("%s", (str));                                                     \
465         warnx("%s", kvm_geterr((kd)));                                  \
466         return (1);                                                     \
467 }
468
469 static int
470 dump_ccd(int argc, char **argv)
471 {
472         char errbuf[_POSIX2_LINE_MAX], *ccd, *cp;
473         struct ccd_softc *cs, *kcs;
474         ssize_t readsize;
475         int i = 0, error, numccd, numconfiged = 0;
476         kvm_t *kd;
477
478         bzero(errbuf, sizeof(errbuf));
479
480         if ((kd = kvm_openfiles(kernel, core, NULL, O_RDONLY,
481             errbuf)) == NULL) {
482                 warnx("can't open kvm: %s", errbuf);
483                 return (1);
484         }
485
486         if (kvm_nlist(kd, nl))
487                 KVM_ABORT(kd, "ccd-related symbols not available");
488
489         /* Check to see how many ccds are currently configured. */
490         if (kvm_read(kd, nl[SYM_NUMCCD].n_value, (char *)&numccd,
491             sizeof(numccd)) != sizeof(numccd))
492                 KVM_ABORT(kd, "can't determine number of configured ccds");
493
494         if (numccd == 0) {
495                 printf("ccd driver in kernel, but is uninitialized\n");
496                 goto done;
497         }
498
499         /* Allocate space for the configuration data. */
500         readsize = numccd * sizeof(struct ccd_softc);
501         if ((cs = malloc(readsize)) == NULL) {
502                 warnx("no memory for configuration data");
503                 goto bad;
504         }
505         bzero(cs, readsize);
506
507         /*
508          * Read the ccd configuration data from the kernel and dump
509          * it to stdout.
510          */
511         if (kvm_read(kd, nl[SYM_CCDSOFTC].n_value, (char *)&kcs,
512             sizeof(kcs)) != sizeof(kcs)) {
513                 free(cs);
514                 KVM_ABORT(kd, "can't find pointer to configuration data");
515         }
516         if (kvm_read(kd, (u_long)kcs, (char *)cs, readsize) != readsize) {
517                 free(cs);
518                 KVM_ABORT(kd, "can't read configuration data");
519         }
520
521         if (argc == 0) {
522                 for (i = 0; i < numccd; ++i)
523                         if (cs[i].sc_flags & CCDF_INITED) {
524                                 ++numconfiged;
525                                 print_ccd_info(&cs[i], kd);
526                         }
527
528                 if (numconfiged == 0)
529                         printf("no concatenated disks configured\n");
530         } else {
531                 while (argc) {
532                         cp = *argv++; --argc;
533                         if ((ccd = resolve_ccdname(cp)) == NULL) {
534                                 warnx("invalid ccd name: %s", cp);
535                                 continue;
536                         }
537                         if ((error = pathtounit(ccd, &i)) != 0) {
538                                 warnx("%s: %s", ccd, strerror(error));
539                                 continue;
540                         }
541                         if (i >= numccd) {
542                                 warnx("ccd%d not configured", i);
543                                 continue;
544                         }
545                         if (cs[i].sc_flags & CCDF_INITED)
546                                 print_ccd_info(&cs[i], kd);
547                         else
548                                 printf("ccd%d not configured\n", i);
549                 }
550         }
551
552         free(cs);
553
554  done:
555         kvm_close(kd);
556         return (0);
557
558  bad:
559         kvm_close(kd);
560         return (1);
561 }
562
563 static void
564 print_ccd_info(struct ccd_softc *cs, kvm_t *kd)
565 {
566         static int header_printed = 0;
567         struct ccdcinfo *cip;
568         ssize_t readsize;
569         char path[MAXPATHLEN];
570         unsigned int i;
571
572         if (header_printed == 0 && verbose) {
573                 printf("# ccd\t\tileave\tflags\tcompnent devices\n");
574                 header_printed = 1;
575         }
576
577         readsize = cs->sc_nccdisks * sizeof(struct ccdcinfo);
578         if ((cip = malloc(readsize)) == NULL) {
579                 warn("ccd%d: can't allocate memory for component info",
580                     cs->sc_unit);
581                 return;
582         }
583         bzero(cip, readsize);
584
585         /* Dump out softc information. */
586         printf("ccd%d\t\t%d\t%d\t", cs->sc_unit, cs->sc_ileave,
587             cs->sc_cflags & CCDF_USERMASK);
588         fflush(stdout);
589
590         /* Read in the component info. */
591         if (kvm_read(kd, (u_long)cs->sc_cinfo, (char *)cip,
592             readsize) != readsize) {
593                 printf("\n");
594                 warnx("can't read component info");
595                 warnx("%s", kvm_geterr(kd));
596                 goto done;
597         }
598
599         /* Read component pathname and display component info. */
600         for (i = 0; i < cs->sc_nccdisks; ++i) {
601                 if ((unsigned)kvm_read(kd, (u_long)cip[i].ci_path, (char *)path,
602                     cip[i].ci_pathlen) != cip[i].ci_pathlen) {
603                         printf("\n");
604                         warnx("can't read component pathname");
605                         warnx("%s", kvm_geterr(kd));
606                         goto done;
607                 }
608                 printf((i + 1 < cs->sc_nccdisks) ? "%s " : "%s\n", path);
609                 fflush(stdout);
610         }
611
612  done:
613         free(cip);
614 }
615
616 static int
617 getmaxpartitions(void)
618 {
619     return (MAXPARTITIONS);
620 }
621
622 static int
623 flags_to_val(char *flags)
624 {
625         char *cp, *tok;
626         int i, tmp, val = ~CCDF_USERMASK;
627         size_t flagslen;
628
629         /*
630          * The most common case is that of NIL flags, so check for
631          * those first.
632          */
633         if (strcmp("none", flags) == 0 || strcmp("0x0", flags) == 0 ||
634             strcmp("0", flags) == 0)
635                 return (0);
636
637         flagslen = strlen(flags);
638
639         /* Check for values represented by strings. */
640         if ((cp = strdup(flags)) == NULL)
641                 err(1, "no memory to parse flags");
642         tmp = 0;
643         for (tok = cp; (tok = strtok(tok, ",")) != NULL; tok = NULL) {
644                 for (i = 0; flagvaltab[i].fv_flag != NULL; ++i)
645                         if (strcmp(tok, flagvaltab[i].fv_flag) == 0)
646                                 break;
647                 if (flagvaltab[i].fv_flag == NULL) {
648                         free(cp);
649                         goto bad_string;
650                 }
651                 tmp |= flagvaltab[i].fv_val;
652         }
653
654         /* If we get here, the string was ok. */
655         free(cp);
656         val = tmp;
657         goto out;
658
659  bad_string:
660
661         /* Check for values represented in hex. */
662         if (flagslen > 2 && flags[0] == '0' && flags[1] == 'x') {
663                 errno = 0;      /* to check for ERANGE */
664                 val = (int)strtol(&flags[2], &cp, 16);
665                 if ((errno == ERANGE) || (*cp != '\0'))
666                         return (-1);
667                 goto out;
668         }
669
670         /* Check for values represented in decimal. */
671         errno = 0;      /* to check for ERANGE */
672         val = (int)strtol(flags, &cp, 10);
673         if ((errno == ERANGE) || (*cp != '\0'))
674                 return (-1);
675
676  out:
677         return (((val & ~CCDF_USERMASK) == 0) ? val : -1);
678 }
679
680 static void
681 usage(void)
682 {
683         fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n",
684                 "usage: ccdconfig [-cv] ccd ileave [flags] dev ...",
685                 "       ccdconfig -C [-v] [-f config_file]",
686                 "       ccdconfig -u [-v] ccd ...",
687                 "       ccdconfig -U [-v] [-f config_file]",
688                 "       ccdconfig -g [-M core] [-N system] [ccd ...]");
689         exit(1);
690 }