xref: /freebsd/sbin/mdconfig/mdconfig.c (revision ef36b3f75658d201edb495068db5e1be49593de5)
1 /*-
2  * Copyright (c) 2000-2004 Poul-Henning Kamp <phk@FreeBSD.org>
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  * $FreeBSD$
31  */
32 
33 #include <sys/param.h>
34 #include <sys/devicestat.h>
35 #include <sys/ioctl.h>
36 #include <sys/linker.h>
37 #include <sys/mdioctl.h>
38 #include <sys/module.h>
39 #include <sys/resource.h>
40 #include <sys/stat.h>
41 
42 #include <assert.h>
43 #include <devstat.h>
44 #include <err.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <inttypes.h>
48 #include <libgeom.h>
49 #include <libutil.h>
50 #include <paths.h>
51 #include <stdarg.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 static struct md_ioctl mdio;
58 static enum {UNSET, ATTACH, DETACH, RESIZE, LIST} action = UNSET;
59 static int nflag;
60 
61 static void usage(void);
62 static void md_set_file(const char *);
63 static int md_find(const char *, const char *);
64 static int md_query(const char *, const int, const char *);
65 static int md_list(const char *, int, const char *);
66 static char *geom_config_get(struct gconf *g, const char *name);
67 static void md_prthumanval(char *length);
68 
69 #define OPT_VERBOSE	0x01
70 #define OPT_UNIT	0x02
71 #define OPT_DONE	0x04
72 #define OPT_LIST	0x10
73 
74 #define CLASS_NAME_MD	"MD"
75 
76 static void
77 usage(void)
78 {
79 
80 	fprintf(stderr,
81 "usage: mdconfig -a -t type [-n] [-o [no]option] ... [-f file]\n"
82 "                [-s size] [-S sectorsize] [-u unit] [-L label]\n"
83 "                [-x sectors/track] [-y heads/cylinder]\n"
84 "       mdconfig -d -u unit [-o [no]force]\n"
85 "       mdconfig -r -u unit -s size [-o [no]force]\n"
86 "       mdconfig -l [-v] [-n] [-f file] [-u unit]\n"
87 "       mdconfig file\n");
88 	fprintf(stderr, "\t\ttype = {malloc, vnode, swap}\n");
89 	fprintf(stderr, "\t\toption = {cluster, compress, reserve}\n");
90 	fprintf(stderr, "\t\tsize = %%d (512 byte blocks), %%db (B),\n");
91 	fprintf(stderr, "\t\t       %%dk (kB), %%dm (MB), %%dg (GB), \n");
92 	fprintf(stderr, "\t\t       %%dt (TB), or %%dp (PB)\n");
93 	exit(1);
94 }
95 
96 int
97 main(int argc, char **argv)
98 {
99 	int ch, fd, i, vflag;
100 	char *p;
101 	char *fflag = NULL, *sflag = NULL, *tflag = NULL, *uflag = NULL;
102 
103 	bzero(&mdio, sizeof(mdio));
104 	mdio.md_file = malloc(PATH_MAX);
105 	mdio.md_label = malloc(PATH_MAX);
106 	if (mdio.md_file == NULL || mdio.md_label == NULL)
107 		err(1, "could not allocate memory");
108 	vflag = 0;
109 	bzero(mdio.md_file, PATH_MAX);
110 	bzero(mdio.md_label, PATH_MAX);
111 
112 	if (argc == 1)
113 		usage();
114 
115 	while ((ch = getopt(argc, argv, "ab:df:lno:rs:S:t:u:vx:y:L:")) != -1) {
116 		switch (ch) {
117 		case 'a':
118 			if (action != UNSET && action != ATTACH)
119 				errx(1, "-a is mutually exclusive "
120 				    "with -d, -r, and -l");
121 			action = ATTACH;
122 			break;
123 		case 'd':
124 			if (action != UNSET && action != DETACH)
125 				errx(1, "-d is mutually exclusive "
126 				    "with -a, -r, and -l");
127 			action = DETACH;
128 			mdio.md_options |= MD_AUTOUNIT;
129 			break;
130 		case 'r':
131 			if (action != UNSET && action != RESIZE)
132 				errx(1, "-r is mutually exclusive "
133 				    "with -a, -d, and -l");
134 			action = RESIZE;
135 			mdio.md_options |= MD_AUTOUNIT;
136 			break;
137 		case 'l':
138 			if (action != UNSET && action != LIST)
139 				errx(1, "-l is mutually exclusive "
140 				    "with -a, -r, and -d");
141 			action = LIST;
142 			mdio.md_options |= MD_AUTOUNIT;
143 			break;
144 		case 'n':
145 			nflag = 1;
146 			break;
147 		case 't':
148 			if (tflag != NULL)
149 				errx(1, "-t can be passed only once");
150 			tflag = optarg;
151 			if (!strcmp(optarg, "malloc")) {
152 				mdio.md_type = MD_MALLOC;
153 				mdio.md_options |= MD_AUTOUNIT | MD_COMPRESS;
154 			} else if (!strcmp(optarg, "vnode")) {
155 				mdio.md_type = MD_VNODE;
156 				mdio.md_options |= MD_CLUSTER | MD_AUTOUNIT | MD_COMPRESS;
157 			} else if (!strcmp(optarg, "swap")) {
158 				mdio.md_type = MD_SWAP;
159 				mdio.md_options |= MD_CLUSTER | MD_AUTOUNIT | MD_COMPRESS;
160 			} else if (!strcmp(optarg, "null")) {
161 				mdio.md_type = MD_NULL;
162 				mdio.md_options |= MD_CLUSTER | MD_AUTOUNIT | MD_COMPRESS;
163 			} else
164 				errx(1, "unknown type: %s", optarg);
165 			break;
166 		case 'f':
167 			if (fflag != NULL)
168 				errx(1, "-f can be passed only once");
169 			fflag = realpath(optarg, NULL);
170 			if (fflag == NULL)
171 				err(1, "realpath");
172 			break;
173 		case 'o':
174 			if (!strcmp(optarg, "async"))
175 				mdio.md_options |= MD_ASYNC;
176 			else if (!strcmp(optarg, "noasync"))
177 				mdio.md_options &= ~MD_ASYNC;
178 			else if (!strcmp(optarg, "cluster"))
179 				mdio.md_options |= MD_CLUSTER;
180 			else if (!strcmp(optarg, "nocluster"))
181 				mdio.md_options &= ~MD_CLUSTER;
182 			else if (!strcmp(optarg, "compress"))
183 				mdio.md_options |= MD_COMPRESS;
184 			else if (!strcmp(optarg, "nocompress"))
185 				mdio.md_options &= ~MD_COMPRESS;
186 			else if (!strcmp(optarg, "force"))
187 				mdio.md_options |= MD_FORCE;
188 			else if (!strcmp(optarg, "noforce"))
189 				mdio.md_options &= ~MD_FORCE;
190 			else if (!strcmp(optarg, "readonly"))
191 				mdio.md_options |= MD_READONLY;
192 			else if (!strcmp(optarg, "noreadonly"))
193 				mdio.md_options &= ~MD_READONLY;
194 			else if (!strcmp(optarg, "reserve"))
195 				mdio.md_options |= MD_RESERVE;
196 			else if (!strcmp(optarg, "noreserve"))
197 				mdio.md_options &= ~MD_RESERVE;
198 			else if (!strcmp(optarg, "verify"))
199 				mdio.md_options |= MD_VERIFY;
200 			else if (!strcmp(optarg, "noverify"))
201 				mdio.md_options &= ~MD_VERIFY;
202 			else
203 				errx(1, "unknown option: %s", optarg);
204 			break;
205 		case 'S':
206 			mdio.md_sectorsize = strtoul(optarg, &p, 0);
207 			break;
208 		case 's':
209 			if (sflag != NULL)
210 				errx(1, "-s can be passed only once");
211 			sflag = optarg;
212 			mdio.md_mediasize = (off_t)strtoumax(optarg, &p, 0);
213 			if (p == NULL || *p == '\0')
214 				mdio.md_mediasize *= DEV_BSIZE;
215 			else if (*p == 'b' || *p == 'B')
216 				; /* do nothing */
217 			else if (*p == 'k' || *p == 'K')
218 				mdio.md_mediasize <<= 10;
219 			else if (*p == 'm' || *p == 'M')
220 				mdio.md_mediasize <<= 20;
221 			else if (*p == 'g' || *p == 'G')
222 				mdio.md_mediasize <<= 30;
223 			else if (*p == 't' || *p == 'T') {
224 				mdio.md_mediasize <<= 30;
225 				mdio.md_mediasize <<= 10;
226 			} else if (*p == 'p' || *p == 'P') {
227 				mdio.md_mediasize <<= 30;
228 				mdio.md_mediasize <<= 20;
229 			} else
230 				errx(1, "unknown suffix on -s argument");
231 			break;
232 		case 'u':
233 			if (!strncmp(optarg, _PATH_DEV, sizeof(_PATH_DEV) - 1))
234 				optarg += sizeof(_PATH_DEV) - 1;
235 			if (!strncmp(optarg, MD_NAME, sizeof(MD_NAME) - 1))
236 				optarg += sizeof(MD_NAME) - 1;
237 			uflag = optarg;
238 			break;
239 		case 'v':
240 			vflag = OPT_VERBOSE;
241 			break;
242 		case 'x':
243 			mdio.md_fwsectors = strtoul(optarg, &p, 0);
244 			break;
245 		case 'y':
246 			mdio.md_fwheads = strtoul(optarg, &p, 0);
247 			break;
248 		case 'L':
249 			strlcpy(mdio.md_label, optarg, PATH_MAX);
250 			break;
251 		default:
252 			usage();
253 		}
254 	}
255 
256 	argc -= optind;
257 	argv += optind;
258 
259 	if (action == UNSET)
260 		action = ATTACH;
261 
262 	if (action == ATTACH) {
263 		if (tflag == NULL) {
264 			/*
265 			 * Try to infer the type based on other arguments.
266 			 */
267 			if (fflag != NULL || argc > 0) {
268 				/* Imply ``-t vnode'' */
269 				mdio.md_type = MD_VNODE;
270 				mdio.md_options |= MD_CLUSTER | MD_AUTOUNIT |
271 				    MD_COMPRESS;
272 			} else if (sflag != NULL) {
273 				/* Imply ``-t swap'' */
274 				mdio.md_type = MD_SWAP;
275 				mdio.md_options |= MD_CLUSTER | MD_AUTOUNIT |
276 				    MD_COMPRESS;
277 			} else
278 				errx(1, "unable to determine type");
279 		}
280 
281 		if ((fflag != NULL || argc > 0) && mdio.md_type != MD_VNODE)
282 			errx(1, "only -t vnode can be used with file name");
283 
284 		if (mdio.md_type == MD_VNODE) {
285 			if (fflag != NULL) {
286 				if (argc != 0)
287 					usage();
288 				md_set_file(fflag);
289 			} else {
290 				if (argc != 1)
291 					usage();
292 				md_set_file(*argv);
293 			}
294 
295 			if ((mdio.md_options & MD_READONLY) == 0 &&
296 			    access(mdio.md_file, W_OK) < 0 &&
297 			    (errno == EACCES || errno == EPERM ||
298 			     errno == EROFS)) {
299 				warnx("WARNING: opening backing store: %s "
300 				    "readonly", mdio.md_file);
301 				mdio.md_options |= MD_READONLY;
302 			}
303 		}
304 
305 		if ((mdio.md_type == MD_MALLOC || mdio.md_type == MD_SWAP ||
306 		    mdio.md_type == MD_NULL) && sflag == NULL)
307 			errx(1, "must specify -s for -t malloc, -t swap, "
308 			    "or -t null");
309 		if (mdio.md_type == MD_VNODE && mdio.md_file[0] == '\0')
310 			errx(1, "must specify -f for -t vnode");
311 	} else {
312 		if (mdio.md_sectorsize != 0)
313 			errx(1, "-S can only be used with -a");
314 		if (action != RESIZE && sflag != NULL)
315 			errx(1, "-s can only be used with -a and -r");
316 		if (mdio.md_fwsectors != 0)
317 			errx(1, "-x can only be used with -a");
318 		if (mdio.md_fwheads != 0)
319 			errx(1, "-y can only be used with -a");
320 		if (fflag != NULL && action != LIST)
321 			errx(1, "-f can only be used with -a and -l");
322 		if (tflag != NULL)
323 			errx(1, "-t can only be used with -a");
324 		if (argc > 0)
325 			errx(1, "file can only be used with -a");
326 		if ((action != DETACH && action != RESIZE) &&
327 		    (mdio.md_options & ~MD_AUTOUNIT) != 0)
328 			errx(1, "-o can only be used with -a, -d, and -r");
329 		if (action == DETACH &&
330 		    (mdio.md_options & ~(MD_FORCE | MD_AUTOUNIT)) != 0)
331 			errx(1, "only -o [no]force can be used with -d");
332 		if (action == RESIZE &&
333 		    (mdio.md_options & ~(MD_FORCE | MD_RESERVE | MD_AUTOUNIT)) != 0)
334 			errx(1, "only -o [no]force and -o [no]reserve can be used with -r");
335 	}
336 
337 	if (action == RESIZE && sflag == NULL)
338 		errx(1, "must specify -s for -r");
339 
340 	if (action != LIST && vflag == OPT_VERBOSE)
341 		errx(1, "-v can only be used with -l");
342 
343 	if (uflag != NULL) {
344 		mdio.md_unit = strtoul(uflag, &p, 0);
345 		if (mdio.md_unit == (unsigned)ULONG_MAX || *p != '\0')
346 			errx(1, "bad unit: %s", uflag);
347 		mdio.md_options &= ~MD_AUTOUNIT;
348 	}
349 
350 	mdio.md_version = MDIOVERSION;
351 
352 	if (!kld_isloaded("g_md") && kld_load("geom_md") == -1)
353 		err(1, "failed to load geom_md module");
354 
355 	fd = open(_PATH_DEV MDCTL_NAME, O_RDWR, 0);
356 	if (fd < 0)
357 		err(1, "open(%s%s)", _PATH_DEV, MDCTL_NAME);
358 
359 	if (action == ATTACH) {
360 		i = ioctl(fd, MDIOCATTACH, &mdio);
361 		if (i < 0)
362 			err(1, "ioctl(%s%s)", _PATH_DEV, MDCTL_NAME);
363 		if (mdio.md_options & MD_AUTOUNIT)
364 			printf("%s%d\n", nflag ? "" : MD_NAME, mdio.md_unit);
365 	} else if (action == DETACH) {
366 		if (mdio.md_options & MD_AUTOUNIT)
367 			errx(1, "-d requires -u");
368 		i = ioctl(fd, MDIOCDETACH, &mdio);
369 		if (i < 0)
370 			err(1, "ioctl(%s%s)", _PATH_DEV, MDCTL_NAME);
371 	} else if (action == RESIZE) {
372 		if (mdio.md_options & MD_AUTOUNIT)
373 			errx(1, "-r requires -u");
374 		i = ioctl(fd, MDIOCRESIZE, &mdio);
375 		if (i < 0)
376 			err(1, "ioctl(%s%s)", _PATH_DEV, MDCTL_NAME);
377 	} else if (action == LIST) {
378 		if (mdio.md_options & MD_AUTOUNIT) {
379 			/*
380 			 * Listing all devices. This is why we pass NULL
381 			 * together with OPT_LIST.
382 			 */
383 			return (md_list(NULL, OPT_LIST | vflag, fflag));
384 		} else
385 			return (md_query(uflag, vflag, fflag));
386 	} else
387 		usage();
388 	close(fd);
389 	return (0);
390 }
391 
392 static void
393 md_set_file(const char *fn)
394 {
395 	struct stat sb;
396 	int fd;
397 
398 	if (realpath(fn, mdio.md_file) == NULL)
399 		err(1, "could not find full path for %s", fn);
400 	fd = open(mdio.md_file, O_RDONLY);
401 	if (fd < 0)
402 		err(1, "could not open %s", fn);
403 	if (fstat(fd, &sb) == -1)
404 		err(1, "could not stat %s", fn);
405 	if (!S_ISREG(sb.st_mode))
406 		errx(1, "%s is not a regular file", fn);
407 	if (mdio.md_mediasize == 0)
408 		mdio.md_mediasize = sb.st_size;
409 	close(fd);
410 }
411 
412 /*
413  * Lists md(4) disks. Is used also as a query routine, since it handles XML
414  * interface. 'units' can be NULL for listing memory disks. It might be
415  * coma-separated string containing md(4) disk names. 'opt' distinguished
416  * between list and query mode.
417  */
418 static int
419 md_list(const char *units, int opt, const char *fflag)
420 {
421 	struct gmesh gm;
422 	struct gprovider *pp;
423 	struct gconf *gc;
424 	struct gident *gid;
425 	struct devstat *gsp;
426 	struct ggeom *gg;
427 	struct gclass *gcl;
428 	void *sq;
429 	int retcode, ffound, ufound;
430 	char *length;
431 	const char *type, *file, *label;
432 
433 	type = file = length = NULL;
434 
435 	retcode = geom_gettree(&gm);
436 	if (retcode != 0)
437 		return (-1);
438 	retcode = geom_stats_open();
439 	if (retcode != 0)
440 		return (-1);
441 	sq = geom_stats_snapshot_get();
442 	if (sq == NULL)
443 		return (-1);
444 
445 	ffound = ufound = 0;
446 	while ((gsp = geom_stats_snapshot_next(sq)) != NULL) {
447 		gid = geom_lookupid(&gm, gsp->id);
448 		if (gid == NULL)
449 			continue;
450 		if (gid->lg_what == ISPROVIDER) {
451 			pp = gid->lg_ptr;
452 			gg = pp->lg_geom;
453 			gcl = gg->lg_class;
454 			if (strcmp(gcl->lg_name, CLASS_NAME_MD) != 0)
455 				continue;
456 			if ((opt & OPT_UNIT) && (units != NULL)) {
457 				retcode = md_find(units, pp->lg_name);
458 				if (retcode != 1)
459 					continue;
460 				else
461 					ufound = 1;
462 			}
463 			gc = &pp->lg_config;
464 			type = geom_config_get(gc, "type");
465 			if (type != NULL && (strcmp(type, "vnode") == 0 ||
466 			    strcmp(type, "preload") == 0)) {
467 				file = geom_config_get(gc, "file");
468 				if (fflag != NULL &&
469 				    strcmp(fflag, file) != 0)
470 					continue;
471 				else
472 					ffound = 1;
473 			} else if (fflag != NULL)
474 					continue;
475 			if (nflag && strncmp(pp->lg_name, MD_NAME, 2) == 0)
476 				printf("%s", pp->lg_name + 2);
477 			else
478 				printf("%s", pp->lg_name);
479 
480 			if (opt & OPT_VERBOSE ||
481 			    ((opt & OPT_UNIT) && fflag == NULL)) {
482 				length = geom_config_get(gc, "length");
483 				printf("\t%s\t", type);
484 				if (length != NULL)
485 					md_prthumanval(length);
486 				if (file == NULL)
487 					file = "-";
488 				printf("\t%s", file);
489 				file = NULL;
490 				label = geom_config_get(gc, "label");
491 				if (label == NULL)
492 					label = "";
493 				printf("\t%s", label);
494 			}
495 			opt |= OPT_DONE;
496 			if ((opt & OPT_LIST) && !(opt & OPT_VERBOSE))
497 				printf(" ");
498 			else
499 				printf("\n");
500 		}
501 	}
502 	if ((opt & OPT_LIST) && (opt & OPT_DONE) && !(opt & OPT_VERBOSE))
503 		printf("\n");
504 	/* XXX: Check if it's enough to clean everything. */
505 	geom_stats_snapshot_free(sq);
506 	if (opt & OPT_UNIT) {
507 		if (((fflag == NULL) && ufound) ||
508 		    ((fflag == NULL) && (units != NULL) && ufound) ||
509 		    ((fflag != NULL) && ffound) ||
510 		    ((fflag != NULL) && (units != NULL) && ufound && ffound))
511 			return (0);
512 	} else if (opt & OPT_LIST) {
513 		if ((fflag == NULL) ||
514 		    ((fflag != NULL) && ffound))
515 			return (0);
516 	}
517 	return (-1);
518 }
519 
520 /*
521  * Returns value of 'name' from gconfig structure.
522  */
523 static char *
524 geom_config_get(struct gconf *g, const char *name)
525 {
526 	struct gconfig *gce;
527 
528 	LIST_FOREACH(gce, g, lg_config) {
529 		if (strcmp(gce->lg_name, name) == 0)
530 			return (gce->lg_val);
531 	}
532 	return (NULL);
533 }
534 
535 /*
536  * List is comma separated list of MD disks. name is a
537  * device name we look for.  Returns 1 if found and 0
538  * otherwise.
539  */
540 static int
541 md_find(const char *list, const char *name)
542 {
543 	int ret;
544 	char num[PATH_MAX];
545 	char *ptr, *p, *u;
546 
547 	ret = 0;
548 	ptr = strdup(list);
549 	if (ptr == NULL)
550 		return (-1);
551 	for (p = ptr; (u = strsep(&p, ",")) != NULL;) {
552 		if (strncmp(u, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
553 			u += sizeof(_PATH_DEV) - 1;
554 		/* Just in case user specified number instead of full name */
555 		snprintf(num, sizeof(num), "%s%s", MD_NAME, u);
556 		if (strcmp(u, name) == 0 || strcmp(num, name) == 0) {
557 			ret = 1;
558 			break;
559 		}
560 	}
561 	free(ptr);
562 	return (ret);
563 }
564 
565 static void
566 md_prthumanval(char *length)
567 {
568 	char buf[6];
569 	uintmax_t bytes;
570 	char *endptr;
571 
572 	errno = 0;
573 	bytes = strtoumax(length, &endptr, 10);
574 	if (errno != 0 || *endptr != '\0' || bytes > INT64_MAX)
575 		return;
576 	humanize_number(buf, sizeof(buf), (int64_t)bytes, "",
577 	    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
578 	(void)printf("%6s", buf);
579 }
580 
581 static int
582 md_query(const char *name, const int opt, const char *fflag)
583 {
584 
585 	return (md_list(name, opt | OPT_UNIT, fflag));
586 }
587