xref: /freebsd/sbin/mdconfig/mdconfig.c (revision f5147e312f43a9050468de539aeafa072caa1a60)
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, "reserve"))
197 				mdio.md_options |= MD_RESERVE;
198 			else if (!strcmp(optarg, "noreserve"))
199 				mdio.md_options &= ~MD_RESERVE;
200 			else if (!strcmp(optarg, "verify"))
201 				mdio.md_options |= MD_VERIFY;
202 			else if (!strcmp(optarg, "noverify"))
203 				mdio.md_options &= ~MD_VERIFY;
204 			else
205 				errx(1, "unknown option: %s", optarg);
206 			break;
207 		case 'S':
208 			mdio.md_sectorsize = strtoul(optarg, &p, 0);
209 			break;
210 		case 's':
211 			if (sflag != NULL)
212 				errx(1, "-s can be passed only once");
213 			sflag = optarg;
214 			mdio.md_mediasize = (off_t)strtoumax(optarg, &p, 0);
215 			if (p == NULL || *p == '\0')
216 				mdio.md_mediasize *= DEV_BSIZE;
217 			else if (*p == 'b' || *p == 'B')
218 				; /* do nothing */
219 			else if (*p == 'k' || *p == 'K')
220 				mdio.md_mediasize <<= 10;
221 			else if (*p == 'm' || *p == 'M')
222 				mdio.md_mediasize <<= 20;
223 			else if (*p == 'g' || *p == 'G')
224 				mdio.md_mediasize <<= 30;
225 			else if (*p == 't' || *p == 'T') {
226 				mdio.md_mediasize <<= 30;
227 				mdio.md_mediasize <<= 10;
228 			} else if (*p == 'p' || *p == 'P') {
229 				mdio.md_mediasize <<= 30;
230 				mdio.md_mediasize <<= 20;
231 			} else
232 				errx(1, "unknown suffix on -s argument");
233 			break;
234 		case 'u':
235 			if (!strncmp(optarg, _PATH_DEV, sizeof(_PATH_DEV) - 1))
236 				optarg += sizeof(_PATH_DEV) - 1;
237 			if (!strncmp(optarg, MD_NAME, sizeof(MD_NAME) - 1))
238 				optarg += sizeof(MD_NAME) - 1;
239 			uflag = optarg;
240 			break;
241 		case 'v':
242 			vflag = OPT_VERBOSE;
243 			break;
244 		case 'x':
245 			mdio.md_fwsectors = strtoul(optarg, &p, 0);
246 			break;
247 		case 'y':
248 			mdio.md_fwheads = strtoul(optarg, &p, 0);
249 			break;
250 		case 'L':
251 			strlcpy(mdio.md_label, optarg, PATH_MAX);
252 			break;
253 		default:
254 			usage();
255 		}
256 	}
257 
258 	argc -= optind;
259 	argv += optind;
260 
261 	if (action == UNSET)
262 		action = ATTACH;
263 
264 	if (action == ATTACH) {
265 		if (tflag == NULL) {
266 			/*
267 			 * Try to infer the type based on other arguments.
268 			 */
269 			if (fflag != NULL || argc > 0) {
270 				/* Imply ``-t vnode'' */
271 				mdio.md_type = MD_VNODE;
272 				mdio.md_options |= MD_CLUSTER | MD_AUTOUNIT |
273 				    MD_COMPRESS;
274 			} else if (sflag != NULL) {
275 				/* Imply ``-t swap'' */
276 				mdio.md_type = MD_SWAP;
277 				mdio.md_options |= MD_CLUSTER | MD_AUTOUNIT |
278 				    MD_COMPRESS;
279 			} else
280 				errx(1, "unable to determine type");
281 		}
282 
283 		if ((fflag != NULL || argc > 0) && mdio.md_type != MD_VNODE)
284 			errx(1, "only -t vnode can be used with file name");
285 
286 		if (mdio.md_type == MD_VNODE) {
287 			if (fflag != NULL) {
288 				if (argc != 0)
289 					usage();
290 				md_set_file(fflag);
291 			} else {
292 				if (argc != 1)
293 					usage();
294 				md_set_file(*argv);
295 			}
296 
297 			if ((mdio.md_options & MD_READONLY) == 0 &&
298 			    access(mdio.md_file, W_OK) < 0 &&
299 			    (errno == EACCES || errno == EPERM ||
300 			     errno == EROFS)) {
301 				warnx("WARNING: opening backing store: %s "
302 				    "readonly", mdio.md_file);
303 				mdio.md_options |= MD_READONLY;
304 			}
305 		}
306 
307 		if ((mdio.md_type == MD_MALLOC || mdio.md_type == MD_SWAP ||
308 		    mdio.md_type == MD_NULL) && sflag == NULL)
309 			errx(1, "must specify -s for -t malloc, -t swap, "
310 			    "or -t null");
311 		if (mdio.md_type == MD_VNODE && mdio.md_file[0] == '\0')
312 			errx(1, "must specify -f for -t vnode");
313 	} else {
314 		if (mdio.md_sectorsize != 0)
315 			errx(1, "-S can only be used with -a");
316 		if (action != RESIZE && sflag != NULL)
317 			errx(1, "-s can only be used with -a and -r");
318 		if (mdio.md_fwsectors != 0)
319 			errx(1, "-x can only be used with -a");
320 		if (mdio.md_fwheads != 0)
321 			errx(1, "-y can only be used with -a");
322 		if (fflag != NULL && action != LIST)
323 			errx(1, "-f can only be used with -a and -l");
324 		if (tflag != NULL)
325 			errx(1, "-t can only be used with -a");
326 		if (argc > 0)
327 			errx(1, "file can only be used with -a");
328 		if ((action != DETACH && action != RESIZE) &&
329 		    (mdio.md_options & ~MD_AUTOUNIT) != 0)
330 			errx(1, "-o can only be used with -a, -d, and -r");
331 		if (action == DETACH &&
332 		    (mdio.md_options & ~(MD_FORCE | MD_AUTOUNIT)) != 0)
333 			errx(1, "only -o [no]force can be used with -d");
334 		if (action == RESIZE &&
335 		    (mdio.md_options & ~(MD_FORCE | MD_RESERVE | MD_AUTOUNIT)) != 0)
336 			errx(1, "only -o [no]force and -o [no]reserve can be used with -r");
337 	}
338 
339 	if (action == RESIZE && sflag == NULL)
340 		errx(1, "must specify -s for -r");
341 
342 	if (action != LIST && vflag == OPT_VERBOSE)
343 		errx(1, "-v can only be used with -l");
344 
345 	if (uflag != NULL) {
346 		mdio.md_unit = strtoul(uflag, &p, 0);
347 		if (mdio.md_unit == (unsigned)ULONG_MAX || *p != '\0')
348 			errx(1, "bad unit: %s", uflag);
349 		mdio.md_options &= ~MD_AUTOUNIT;
350 	}
351 
352 	mdio.md_version = MDIOVERSION;
353 
354 	if (!kld_isloaded("g_md") && kld_load("geom_md") == -1)
355 		err(1, "failed to load geom_md module");
356 
357 	fd = open(_PATH_DEV MDCTL_NAME, O_RDWR, 0);
358 	if (fd < 0)
359 		err(1, "open(%s%s)", _PATH_DEV, MDCTL_NAME);
360 
361 	if (action == ATTACH) {
362 		i = ioctl(fd, MDIOCATTACH, &mdio);
363 		if (i < 0)
364 			err(1, "ioctl(%s%s)", _PATH_DEV, MDCTL_NAME);
365 		if (mdio.md_options & MD_AUTOUNIT)
366 			printf("%s%d\n", nflag ? "" : MD_NAME, mdio.md_unit);
367 	} else if (action == DETACH) {
368 		if (mdio.md_options & MD_AUTOUNIT)
369 			errx(1, "-d requires -u");
370 		i = ioctl(fd, MDIOCDETACH, &mdio);
371 		if (i < 0)
372 			err(1, "ioctl(%s%s)", _PATH_DEV, MDCTL_NAME);
373 	} else if (action == RESIZE) {
374 		if (mdio.md_options & MD_AUTOUNIT)
375 			errx(1, "-r requires -u");
376 		i = ioctl(fd, MDIOCRESIZE, &mdio);
377 		if (i < 0)
378 			err(1, "ioctl(%s%s)", _PATH_DEV, MDCTL_NAME);
379 	} else if (action == LIST) {
380 		if (mdio.md_options & MD_AUTOUNIT) {
381 			/*
382 			 * Listing all devices. This is why we pass NULL
383 			 * together with OPT_LIST.
384 			 */
385 			return (md_list(NULL, OPT_LIST | vflag, fflag));
386 		} else
387 			return (md_query(uflag, vflag, fflag));
388 	} else
389 		usage();
390 	close(fd);
391 	return (0);
392 }
393 
394 static void
395 md_set_file(const char *fn)
396 {
397 	struct stat sb;
398 	int fd;
399 
400 	if (realpath(fn, mdio.md_file) == NULL)
401 		err(1, "could not find full path for %s", fn);
402 	fd = open(mdio.md_file, O_RDONLY);
403 	if (fd < 0)
404 		err(1, "could not open %s", fn);
405 	if (fstat(fd, &sb) == -1)
406 		err(1, "could not stat %s", fn);
407 	if (!S_ISREG(sb.st_mode))
408 		errx(1, "%s is not a regular file", fn);
409 	if (mdio.md_mediasize == 0)
410 		mdio.md_mediasize = sb.st_size;
411 	close(fd);
412 }
413 
414 /*
415  * Lists md(4) disks. Is used also as a query routine, since it handles XML
416  * interface. 'units' can be NULL for listing memory disks. It might be
417  * coma-separated string containing md(4) disk names. 'opt' distinguished
418  * between list and query mode.
419  */
420 static int
421 md_list(const char *units, int opt, const char *fflag)
422 {
423 	struct gmesh gm;
424 	struct gprovider *pp;
425 	struct gconf *gc;
426 	struct gident *gid;
427 	struct devstat *gsp;
428 	struct ggeom *gg;
429 	struct gclass *gcl;
430 	void *sq;
431 	int retcode, ffound, ufound;
432 	char *length;
433 	const char *type, *file, *label;
434 
435 	type = file = length = NULL;
436 
437 	retcode = geom_gettree(&gm);
438 	if (retcode != 0)
439 		return (-1);
440 	retcode = geom_stats_open();
441 	if (retcode != 0)
442 		return (-1);
443 	sq = geom_stats_snapshot_get();
444 	if (sq == NULL)
445 		return (-1);
446 
447 	ffound = ufound = 0;
448 	while ((gsp = geom_stats_snapshot_next(sq)) != NULL) {
449 		gid = geom_lookupid(&gm, gsp->id);
450 		if (gid == NULL)
451 			continue;
452 		if (gid->lg_what == ISPROVIDER) {
453 			pp = gid->lg_ptr;
454 			gg = pp->lg_geom;
455 			gcl = gg->lg_class;
456 			if (strcmp(gcl->lg_name, CLASS_NAME_MD) != 0)
457 				continue;
458 			if ((opt & OPT_UNIT) && (units != NULL)) {
459 				retcode = md_find(units, pp->lg_name);
460 				if (retcode != 1)
461 					continue;
462 				else
463 					ufound = 1;
464 			}
465 			gc = &pp->lg_config;
466 			type = geom_config_get(gc, "type");
467 			if (type != NULL && (strcmp(type, "vnode") == 0 ||
468 			    strcmp(type, "preload") == 0)) {
469 				file = geom_config_get(gc, "file");
470 				if (fflag != NULL &&
471 				    strcmp(fflag, file) != 0)
472 					continue;
473 				else
474 					ffound = 1;
475 			} else if (fflag != NULL)
476 					continue;
477 			if (nflag && strncmp(pp->lg_name, MD_NAME, 2) == 0)
478 				printf("%s", pp->lg_name + 2);
479 			else
480 				printf("%s", pp->lg_name);
481 
482 			if (opt & OPT_VERBOSE ||
483 			    ((opt & OPT_UNIT) && fflag == NULL)) {
484 				length = geom_config_get(gc, "length");
485 				printf("\t%s\t", type);
486 				if (length != NULL)
487 					md_prthumanval(length);
488 				if (file == NULL)
489 					file = "-";
490 				printf("\t%s", file);
491 				file = NULL;
492 				label = geom_config_get(gc, "label");
493 				if (label == NULL)
494 					label = "";
495 				printf("\t%s", label);
496 			}
497 			opt |= OPT_DONE;
498 			if ((opt & OPT_LIST) && !(opt & OPT_VERBOSE))
499 				printf(" ");
500 			else
501 				printf("\n");
502 		}
503 	}
504 	if ((opt & OPT_LIST) && (opt & OPT_DONE) && !(opt & OPT_VERBOSE))
505 		printf("\n");
506 	/* XXX: Check if it's enough to clean everything. */
507 	geom_stats_snapshot_free(sq);
508 	if (opt & OPT_UNIT) {
509 		if (((fflag == NULL) && ufound) ||
510 		    ((fflag == NULL) && (units != NULL) && ufound) ||
511 		    ((fflag != NULL) && ffound) ||
512 		    ((fflag != NULL) && (units != NULL) && ufound && ffound))
513 			return (0);
514 	} else if (opt & OPT_LIST) {
515 		if ((fflag == NULL) ||
516 		    ((fflag != NULL) && ffound))
517 			return (0);
518 	}
519 	return (-1);
520 }
521 
522 /*
523  * Returns value of 'name' from gconfig structure.
524  */
525 static char *
526 geom_config_get(struct gconf *g, const char *name)
527 {
528 	struct gconfig *gce;
529 
530 	LIST_FOREACH(gce, g, lg_config) {
531 		if (strcmp(gce->lg_name, name) == 0)
532 			return (gce->lg_val);
533 	}
534 	return (NULL);
535 }
536 
537 /*
538  * List is comma separated list of MD disks. name is a
539  * device name we look for.  Returns 1 if found and 0
540  * otherwise.
541  */
542 static int
543 md_find(const char *list, const char *name)
544 {
545 	int ret;
546 	char num[PATH_MAX];
547 	char *ptr, *p, *u;
548 
549 	ret = 0;
550 	ptr = strdup(list);
551 	if (ptr == NULL)
552 		return (-1);
553 	for (p = ptr; (u = strsep(&p, ",")) != NULL;) {
554 		if (strncmp(u, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
555 			u += sizeof(_PATH_DEV) - 1;
556 		/* Just in case user specified number instead of full name */
557 		snprintf(num, sizeof(num), "%s%s", MD_NAME, u);
558 		if (strcmp(u, name) == 0 || strcmp(num, name) == 0) {
559 			ret = 1;
560 			break;
561 		}
562 	}
563 	free(ptr);
564 	return (ret);
565 }
566 
567 static void
568 md_prthumanval(char *length)
569 {
570 	char buf[6];
571 	uintmax_t bytes;
572 	char *endptr;
573 
574 	errno = 0;
575 	bytes = strtoumax(length, &endptr, 10);
576 	if (errno != 0 || *endptr != '\0' || bytes > INT64_MAX)
577 		return;
578 	humanize_number(buf, sizeof(buf), (int64_t)bytes, "",
579 	    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
580 	(void)printf("%6s", buf);
581 }
582 
583 static int
584 md_query(const char *name, const int opt, const char *fflag)
585 {
586 
587 	return (md_list(name, opt | OPT_UNIT, fflag));
588 }
589