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