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