xref: /freebsd/sbin/mdconfig/mdconfig.c (revision b7c60aadbbd5c846a250c05791fe7406d6d78bf4)
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 <stdarg.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 
56 static struct md_ioctl mdio;
57 static enum {UNSET, ATTACH, DETACH, LIST} action = UNSET;
58 static int nflag;
59 
60 static void usage(void);
61 static void md_set_file(const char *);
62 static int md_find(char *, const char *);
63 static int md_query(char *name);
64 static int md_list(char *units, int opt);
65 static char *geom_config_get(struct gconf *g, const char *name);
66 static void md_prthumanval(char *length);
67 
68 #define OPT_VERBOSE	0x01
69 #define OPT_UNIT	0x02
70 #define OPT_DONE	0x04
71 #define OPT_LIST	0x10
72 
73 #define CLASS_NAME_MD	"MD"
74 
75 static void
76 usage(void)
77 {
78 
79 	fprintf(stderr,
80 "usage: mdconfig -a -t type [-n] [-o [no]option] ... [-f file]\n"
81 "                [-s size] [-S sectorsize] [-u unit]\n"
82 "                [-x sectors/track] [-y heads/cylinder]\n"
83 "       mdconfig -d -u unit [-o [no]force]\n"
84 "       mdconfig -l [-v] [-n] [-u unit]\n"
85 "       mdconfig file\n");
86 	fprintf(stderr, "\t\ttype = {malloc, preload, vnode, swap}\n");
87 	fprintf(stderr, "\t\toption = {cluster, compress, reserve}\n");
88 	fprintf(stderr, "\t\tsize = %%d (512 byte blocks), %%db (B),\n");
89 	fprintf(stderr, "\t\t       %%dk (kB), %%dm (MB), %%dg (GB) or\n");
90 	fprintf(stderr, "\t\t       %%dt (TB)\n");
91 	exit(1);
92 }
93 
94 int
95 main(int argc, char **argv)
96 {
97 	int ch, fd, i, vflag;
98 	char *p;
99 	char *fflag = NULL, *tflag = NULL, *uflag = NULL;
100 
101 	bzero(&mdio, sizeof(mdio));
102 	mdio.md_file = malloc(PATH_MAX);
103 	if (mdio.md_file == NULL)
104 		err(1, "could not allocate memory");
105 	vflag = 0;
106 	bzero(mdio.md_file, PATH_MAX);
107 
108 	if (argc == 1)
109 		usage();
110 
111 	while ((ch = getopt(argc, argv, "ab:df:lno:s:S:t:u:vx:y:")) != -1) {
112 		switch (ch) {
113 		case 'a':
114 			if (action != UNSET && action != ATTACH)
115 				errx(1,
116 				    "-a is mutually exclusive with -d and -l");
117 			action = ATTACH;
118 			break;
119 		case 'd':
120 			if (action != UNSET && action != DETACH)
121 				errx(1,
122 				    "-d is mutually exclusive with -a and -l");
123 			action = DETACH;
124 			mdio.md_options |= MD_AUTOUNIT;
125 			break;
126 		case 'l':
127 			if (action != UNSET && action != LIST)
128 				errx(1,
129 				    "-l is mutually exclusive with -a and -d");
130 			action = LIST;
131 			mdio.md_options |= MD_AUTOUNIT;
132 			break;
133 		case 'n':
134 			nflag = 1;
135 			break;
136 		case 't':
137 			if (tflag != NULL)
138 				errx(1, "-t can be passed only once");
139 			tflag = optarg;
140 			if (!strcmp(optarg, "malloc")) {
141 				mdio.md_type = MD_MALLOC;
142 				mdio.md_options |= MD_AUTOUNIT | MD_COMPRESS;
143 			} else if (!strcmp(optarg, "preload")) {
144 				mdio.md_type = MD_PRELOAD;
145 			} else if (!strcmp(optarg, "vnode")) {
146 				mdio.md_type = MD_VNODE;
147 				mdio.md_options |= MD_CLUSTER | MD_AUTOUNIT | MD_COMPRESS;
148 			} else if (!strcmp(optarg, "swap")) {
149 				mdio.md_type = MD_SWAP;
150 				mdio.md_options |= MD_CLUSTER | MD_AUTOUNIT | MD_COMPRESS;
151 			} else
152 				errx(1, "unknown type: %s", optarg);
153 			break;
154 		case 'f':
155 			if (fflag != NULL)
156 				errx(1, "-f can be passed only once");
157 			fflag = optarg;
158 			break;
159 		case 'o':
160 			if (!strcmp(optarg, "async"))
161 				mdio.md_options |= MD_ASYNC;
162 			else if (!strcmp(optarg, "noasync"))
163 				mdio.md_options &= ~MD_ASYNC;
164 			else if (!strcmp(optarg, "cluster"))
165 				mdio.md_options |= MD_CLUSTER;
166 			else if (!strcmp(optarg, "nocluster"))
167 				mdio.md_options &= ~MD_CLUSTER;
168 			else if (!strcmp(optarg, "compress"))
169 				mdio.md_options |= MD_COMPRESS;
170 			else if (!strcmp(optarg, "nocompress"))
171 				mdio.md_options &= ~MD_COMPRESS;
172 			else if (!strcmp(optarg, "force"))
173 				mdio.md_options |= MD_FORCE;
174 			else if (!strcmp(optarg, "noforce"))
175 				mdio.md_options &= ~MD_FORCE;
176 			else if (!strcmp(optarg, "readonly"))
177 				mdio.md_options |= MD_READONLY;
178 			else if (!strcmp(optarg, "noreadonly"))
179 				mdio.md_options &= ~MD_READONLY;
180 			else if (!strcmp(optarg, "reserve"))
181 				mdio.md_options |= MD_RESERVE;
182 			else if (!strcmp(optarg, "noreserve"))
183 				mdio.md_options &= ~MD_RESERVE;
184 			else
185 				errx(1, "unknown option: %s", optarg);
186 			break;
187 		case 'S':
188 			mdio.md_sectorsize = strtoul(optarg, &p, 0);
189 			break;
190 		case 's':
191 			mdio.md_mediasize = (off_t)strtoumax(optarg, &p, 0);
192 			if (p == NULL || *p == '\0')
193 				mdio.md_mediasize *= DEV_BSIZE;
194 			else if (*p == 'b' || *p == 'B')
195 				; /* do nothing */
196 			else if (*p == 'k' || *p == 'K')
197 				mdio.md_mediasize <<= 10;
198 			else if (*p == 'm' || *p == 'M')
199 				mdio.md_mediasize <<= 20;
200 			else if (*p == 'g' || *p == 'G')
201 				mdio.md_mediasize <<= 30;
202 			else if (*p == 't' || *p == 'T') {
203 				mdio.md_mediasize <<= 30;
204 				mdio.md_mediasize <<= 10;
205 			} else
206 				errx(1, "unknown suffix on -s argument");
207 			break;
208 		case 'u':
209 			if (!strncmp(optarg, "/dev/", 5))
210 				optarg += 5;
211 			if (!strncmp(optarg, MD_NAME, sizeof(MD_NAME) - 1))
212 				optarg += sizeof(MD_NAME) - 1;
213 			uflag = optarg;
214 			break;
215 		case 'v':
216 			vflag = OPT_VERBOSE;
217 			break;
218 		case 'x':
219 			mdio.md_fwsectors = strtoul(optarg, &p, 0);
220 			break;
221 		case 'y':
222 			mdio.md_fwheads = strtoul(optarg, &p, 0);
223 			break;
224 		default:
225 			usage();
226 		}
227 	}
228 
229 	argc -= optind;
230 	argv += optind;
231 
232 	if (action == UNSET)
233 		action = ATTACH;
234 
235 	if (action == ATTACH) {
236 		if (tflag == NULL) {
237 			/*
238 			 * Try to infer the type based on other arguments.
239 			 */
240 			if (fflag != NULL || argc > 0) {
241 				/* Imply ``-t vnode'' */
242 				mdio.md_type = MD_VNODE;
243 				mdio.md_options |= MD_CLUSTER | MD_AUTOUNIT |
244 				    MD_COMPRESS;
245 			} else if (mdio.md_mediasize != 0) {
246 				/* Imply ``-t swap'' */
247 				mdio.md_type = MD_SWAP;
248 				mdio.md_options |= MD_CLUSTER | MD_AUTOUNIT |
249 				    MD_COMPRESS;
250 			} else
251 				errx(1, "unable to determine type");
252 		}
253 
254 		if ((fflag != NULL || argc > 0) && mdio.md_type != MD_VNODE)
255 			errx(1, "only -t vnode can be used with file name");
256 
257 		if (mdio.md_type == MD_VNODE) {
258 			if (fflag != NULL) {
259 				if (argc != 0)
260 					usage();
261 				md_set_file(fflag);
262 			} else {
263 				if (argc != 1)
264 					usage();
265 				md_set_file(*argv);
266 			}
267 
268 			if ((mdio.md_options & MD_READONLY) == 0 &&
269 			    access(mdio.md_file, W_OK) < 0 &&
270 			    (errno == EACCES || errno == EPERM ||
271 			     errno == EROFS)) {
272 				warnx("WARNING: opening backing store: %s "
273 				    "readonly", mdio.md_file);
274 				mdio.md_options |= MD_READONLY;
275 			}
276 		}
277 
278 		if ((mdio.md_type == MD_MALLOC || mdio.md_type == MD_SWAP) &&
279 		    mdio.md_mediasize == 0)
280 			errx(1, "must specify -s for -t malloc or -t swap");
281 		if (mdio.md_type == MD_VNODE && mdio.md_file[0] == '\0')
282 			errx(1, "must specify -f for -t vnode");
283 	} else {
284 		if (mdio.md_sectorsize != 0)
285 			errx(1, "-S can only be used with -a");
286 		if (mdio.md_mediasize != 0)
287 			errx(1, "-s can only be used with -a");
288 		if (mdio.md_fwsectors != 0)
289 			errx(1, "-x can only be used with -a");
290 		if (mdio.md_fwheads != 0)
291 			errx(1, "-y can only be used with -a");
292 		if (fflag != NULL)
293 			errx(1, "-f can only be used with -a");
294 		if (tflag != NULL)
295 			errx(1, "-t can only be used with -a");
296 		if (argc > 0)
297 			errx(1, "file can only be used with -a");
298 		if (action != DETACH && (mdio.md_options & ~MD_AUTOUNIT) != 0)
299 			errx(1, "-o can only be used with -a and -d");
300 		if (action == DETACH &&
301 		    (mdio.md_options & ~(MD_FORCE | MD_AUTOUNIT)) != 0)
302 			errx(1, "only -o [no]force can be used with -d");
303 	}
304 
305 	if (action != LIST && vflag == OPT_VERBOSE)
306 		errx(1, "-v can only be used with -l");
307 
308 	if (uflag != NULL) {
309 		mdio.md_unit = strtoul(uflag, &p, 0);
310 		if (mdio.md_unit == (unsigned)ULONG_MAX || *p != '\0')
311 			errx(1, "bad unit: %s", uflag);
312 		mdio.md_options &= ~MD_AUTOUNIT;
313 	}
314 
315 	mdio.md_version = MDIOVERSION;
316 
317 	if (!kld_isloaded("g_md") && kld_load("geom_md") == -1)
318 		err(1, "failed to load geom_md module");
319 
320 	fd = open("/dev/" MDCTL_NAME, O_RDWR, 0);
321 	if (fd < 0)
322 		err(1, "open(/dev/%s)", MDCTL_NAME);
323 
324 	if (action == ATTACH) {
325 		i = ioctl(fd, MDIOCATTACH, &mdio);
326 		if (i < 0)
327 			err(1, "ioctl(/dev/%s)", MDCTL_NAME);
328 		if (mdio.md_options & MD_AUTOUNIT)
329 			printf("%s%d\n", nflag ? "" : MD_NAME, mdio.md_unit);
330 	} else if (action == DETACH) {
331 		if (mdio.md_options & MD_AUTOUNIT)
332 			errx(1, "-d requires -u");
333 		i = ioctl(fd, MDIOCDETACH, &mdio);
334 		if (i < 0)
335 			err(1, "ioctl(/dev/%s)", MDCTL_NAME);
336 	} else if (action == LIST) {
337 		if (mdio.md_options & MD_AUTOUNIT) {
338 			/*
339 			 * Listing all devices. This is why we pass NULL
340 			 * together with OPT_LIST.
341 			 */
342 			md_list(NULL, OPT_LIST | vflag);
343 		} else
344 			return (md_query(uflag));
345 
346 	} else
347 		usage();
348 	close(fd);
349 	return (0);
350 }
351 
352 static void
353 md_set_file(const char *fn)
354 {
355 	struct stat sb;
356 	int fd;
357 
358 	if (realpath(fn, mdio.md_file) == NULL)
359 		err(1, "could not find full path for %s", fn);
360 	fd = open(mdio.md_file, O_RDONLY);
361 	if (fd < 0)
362 		err(1, "could not open %s", fn);
363 	if (fstat(fd, &sb) == -1)
364 		err(1, "could not stat %s", fn);
365 	if (!S_ISREG(sb.st_mode))
366 		errx(1, "%s is not a regular file", fn);
367 	if (mdio.md_mediasize == 0)
368 		mdio.md_mediasize = sb.st_size;
369 	close(fd);
370 }
371 
372 /*
373  * Lists md(4) disks. Is used also as a query routine, since it handles XML
374  * interface. 'units' can be NULL for listing memory disks. It might be
375  * coma-separated string containing md(4) disk names. 'opt' distinguished
376  * between list and query mode.
377  */
378 static int
379 md_list(char *units, int opt)
380 {
381 	struct gmesh gm;
382 	struct gprovider *pp;
383 	struct gconf *gc;
384 	struct gident *gid;
385 	struct devstat *gsp;
386 	struct ggeom *gg;
387 	struct gclass *gcl;
388 	void *sq;
389 	int retcode, found;
390 	char *type, *file, *length;
391 
392 	type = file = length = NULL;
393 
394 	retcode = geom_gettree(&gm);
395 	if (retcode != 0)
396 		return (-1);
397 	retcode = geom_stats_open();
398 	if (retcode != 0)
399 		return (-1);
400 	sq = geom_stats_snapshot_get();
401 	if (sq == NULL)
402 		return (-1);
403 
404 	found = 0;
405 	while ((gsp = geom_stats_snapshot_next(sq)) != NULL) {
406 		gid = geom_lookupid(&gm, gsp->id);
407 		if (gid == NULL)
408 			continue;
409 		if (gid->lg_what == ISPROVIDER) {
410 			pp = gid->lg_ptr;
411 			gg = pp->lg_geom;
412 			gcl = gg->lg_class;
413 			if (strcmp(gcl->lg_name, CLASS_NAME_MD) != 0)
414 				continue;
415 			if ((opt & OPT_UNIT) && (units != NULL)) {
416 				retcode = md_find(units, pp->lg_name);
417 				if (retcode != 1)
418 					continue;
419 				else
420 					found = 1;
421 			}
422 			gc = &pp->lg_config;
423 			if (nflag && strncmp(pp->lg_name, "md", 2) == 0)
424 				printf("%s", pp->lg_name + 2);
425 			else
426 				printf("%s", pp->lg_name);
427 
428 			if (opt & OPT_VERBOSE || opt & OPT_UNIT) {
429 				type = geom_config_get(gc, "type");
430 				if (strcmp(type, "vnode") == 0)
431 					file = geom_config_get(gc, "file");
432 				length = geom_config_get(gc, "length");
433 				printf("\t%s\t", type);
434 				if (length != NULL)
435 					md_prthumanval(length);
436 				if (file != NULL) {
437 					printf("\t%s", file);
438 					file = NULL;
439 				}
440 			}
441 			opt |= OPT_DONE;
442 			if ((opt & OPT_LIST) && !(opt & OPT_VERBOSE))
443 				printf(" ");
444 			else
445 				printf("\n");
446 		}
447 	}
448 	if ((opt & OPT_LIST) && (opt & OPT_DONE) && !(opt & OPT_VERBOSE))
449 		printf("\n");
450 	/* XXX: Check if it's enough to clean everything. */
451 	geom_stats_snapshot_free(sq);
452 	if ((opt & OPT_UNIT) && found)
453 		return (0);
454 	else
455 		return (-1);
456 }
457 
458 /*
459  * Returns value of 'name' from gconfig structure.
460  */
461 static char *
462 geom_config_get(struct gconf *g, const char *name)
463 {
464 	struct gconfig *gce;
465 
466 	LIST_FOREACH(gce, g, lg_config) {
467 		if (strcmp(gce->lg_name, name) == 0)
468 			return (gce->lg_val);
469 	}
470 	return (NULL);
471 }
472 
473 /*
474  * List is comma separated list of MD disks. name is a
475  * device name we look for.  Returns 1 if found and 0
476  * otherwise.
477  */
478 static int
479 md_find(char *list, const char *name)
480 {
481 	int ret;
482 	char num[16];
483 	char *ptr, *p, *u;
484 
485 	ret = 0;
486 	ptr = strdup(list);
487 	if (ptr == NULL)
488 		return (-1);
489 	for (p = ptr; (u = strsep(&p, ",")) != NULL;) {
490 		if (strncmp(u, "/dev/", 5) == 0)
491 			u += 5;
492 		/* Just in case user specified number instead of full name */
493 		snprintf(num, sizeof(num), "md%s", u);
494 		if (strcmp(u, name) == 0 || strcmp(num, name) == 0) {
495 			ret = 1;
496 			break;
497 		}
498 	}
499 	free(ptr);
500 	return (ret);
501 }
502 
503 static void
504 md_prthumanval(char *length)
505 {
506 	char buf[6];
507 	uintmax_t bytes;
508 	char *endptr;
509 
510 	errno = 0;
511 	bytes = strtoumax(length, &endptr, 10);
512 	if (errno != 0 || *endptr != '\0' || bytes > INT64_MAX)
513 		return;
514 	humanize_number(buf, sizeof(buf), (int64_t)bytes, "",
515 	    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
516 	(void)printf("%6s", buf);
517 }
518 
519 int
520 md_query(char *name)
521 {
522 
523 	return (md_list(name, OPT_UNIT));
524 }
525