xref: /freebsd/sys/contrib/openzfs/cmd/zpool/zpool_vdev.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 
13 /*
14  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
15  * Copyright (c) 2013, 2018 by Delphix. All rights reserved.
16  * Copyright (c) 2016, 2017 Intel Corporation.
17  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
18  */
19 
20 /*
21  * Functions to convert between a list of vdevs and an nvlist representing the
22  * configuration.  Each entry in the list can be one of:
23  *
24  * 	Device vdevs
25  * 		disk=(path=..., devid=...)
26  * 		file=(path=...)
27  *
28  * 	Group vdevs
29  * 		raidz[1|2]=(...)
30  * 		mirror=(...)
31  *
32  * 	Hot spares
33  *
34  * While the underlying implementation supports it, group vdevs cannot contain
35  * other group vdevs.  All userland verification of devices is contained within
36  * this file.  If successful, the nvlist returned can be passed directly to the
37  * kernel; we've done as much verification as possible in userland.
38  *
39  * Hot spares are a special case, and passed down as an array of disk vdevs, at
40  * the same level as the root of the vdev tree.
41  *
42  * The only function exported by this file is 'make_root_vdev'.  The
43  * function performs several passes:
44  *
45  * 	1. Construct the vdev specification.  Performs syntax validation and
46  *         makes sure each device is valid.
47  * 	2. Check for devices in use.  Using libblkid to make sure that no
48  *         devices are also in use.  Some can be overridden using the 'force'
49  *         flag, others cannot.
50  * 	3. Check for replication errors if the 'force' flag is not specified.
51  *         validates that the replication level is consistent across the
52  *         entire pool.
53  * 	4. Call libzfs to label any whole disks with an EFI label.
54  */
55 
56 #include <assert.h>
57 #include <ctype.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <libintl.h>
61 #include <libnvpair.h>
62 #include <libzutil.h>
63 #include <limits.h>
64 #include <sys/spa.h>
65 #include <stdio.h>
66 #include <string.h>
67 #include <unistd.h>
68 #include "zpool_util.h"
69 #include <sys/zfs_context.h>
70 #include <sys/stat.h>
71 
72 /*
73  * For any given vdev specification, we can have multiple errors.  The
74  * vdev_error() function keeps track of whether we have seen an error yet, and
75  * prints out a header if its the first error we've seen.
76  */
77 boolean_t error_seen;
78 boolean_t is_force;
79 
80 void
vdev_error(const char * fmt,...)81 vdev_error(const char *fmt, ...)
82 {
83 	va_list ap;
84 
85 	if (!error_seen) {
86 		(void) fprintf(stderr, gettext("invalid vdev specification\n"));
87 		if (!is_force)
88 			(void) fprintf(stderr, gettext("use '-f' to override "
89 			    "the following errors:\n"));
90 		else
91 			(void) fprintf(stderr, gettext("the following errors "
92 			    "must be manually repaired:\n"));
93 		error_seen = B_TRUE;
94 	}
95 
96 	va_start(ap, fmt);
97 	(void) vfprintf(stderr, fmt, ap);
98 	va_end(ap);
99 }
100 
101 /*
102  * Check that a file is valid.  All we can do in this case is check that it's
103  * not in use by another pool, and not in use by swap.
104  */
105 int
check_file_generic(const char * file,boolean_t force,boolean_t isspare)106 check_file_generic(const char *file, boolean_t force, boolean_t isspare)
107 {
108 	char  *name;
109 	int fd;
110 	int ret = 0;
111 	pool_state_t state;
112 	boolean_t inuse;
113 
114 	if ((fd = open(file, O_RDONLY)) < 0)
115 		return (0);
116 
117 	if (zpool_in_use(g_zfs, fd, &state, &name, &inuse) == 0 && inuse) {
118 		const char *desc;
119 
120 		switch (state) {
121 		case POOL_STATE_ACTIVE:
122 			desc = gettext("active");
123 			break;
124 
125 		case POOL_STATE_EXPORTED:
126 			desc = gettext("exported");
127 			break;
128 
129 		case POOL_STATE_POTENTIALLY_ACTIVE:
130 			desc = gettext("potentially active");
131 			break;
132 
133 		default:
134 			desc = gettext("unknown");
135 			break;
136 		}
137 
138 		/*
139 		 * Allow hot spares to be shared between pools.
140 		 */
141 		if (state == POOL_STATE_SPARE && isspare) {
142 			free(name);
143 			(void) close(fd);
144 			return (0);
145 		}
146 
147 		if (state == POOL_STATE_ACTIVE ||
148 		    state == POOL_STATE_SPARE || !force) {
149 			switch (state) {
150 			case POOL_STATE_SPARE:
151 				vdev_error(gettext("%s is reserved as a hot "
152 				    "spare for pool %s\n"), file, name);
153 				break;
154 			default:
155 				vdev_error(gettext("%s is part of %s pool "
156 				    "'%s'\n"), file, desc, name);
157 				break;
158 			}
159 			ret = -1;
160 		}
161 
162 		free(name);
163 	}
164 
165 	(void) close(fd);
166 	return (ret);
167 }
168 
169 /*
170  * This may be a shorthand device path or it could be total gibberish.
171  * Check to see if it is a known device available in zfs_vdev_paths.
172  * As part of this check, see if we've been given an entire disk
173  * (minus the slice number).
174  */
175 static int
is_shorthand_path(const char * arg,char * path,size_t path_size,struct stat64 * statbuf,boolean_t * wholedisk)176 is_shorthand_path(const char *arg, char *path, size_t path_size,
177     struct stat64 *statbuf, boolean_t *wholedisk)
178 {
179 	int error;
180 
181 	error = zfs_resolve_shortname(arg, path, path_size);
182 	if (error == 0) {
183 		*wholedisk = zfs_dev_is_whole_disk(path);
184 		if (*wholedisk || (stat64(path, statbuf) == 0))
185 			return (0);
186 	}
187 
188 	(void) strlcpy(path, arg, path_size);
189 	memset(statbuf, 0, sizeof (*statbuf));
190 	*wholedisk = B_FALSE;
191 
192 	return (error);
193 }
194 
195 /*
196  * Determine if the given path is a hot spare within the given configuration.
197  * If no configuration is given we rely solely on the label.
198  */
199 static boolean_t
is_spare(nvlist_t * config,const char * path)200 is_spare(nvlist_t *config, const char *path)
201 {
202 	int fd;
203 	pool_state_t state;
204 	char *name = NULL;
205 	nvlist_t *label;
206 	uint64_t guid, spareguid;
207 	nvlist_t *nvroot;
208 	nvlist_t **spares;
209 	uint_t i, nspares;
210 	boolean_t inuse;
211 
212 	if (zpool_is_draid_spare(path))
213 		return (B_TRUE);
214 
215 	if ((fd = open(path, O_RDONLY|O_DIRECT)) < 0)
216 		return (B_FALSE);
217 
218 	if (zpool_in_use(g_zfs, fd, &state, &name, &inuse) != 0 ||
219 	    !inuse ||
220 	    state != POOL_STATE_SPARE ||
221 	    zpool_read_label(fd, &label, NULL) != 0) {
222 		free(name);
223 		(void) close(fd);
224 		return (B_FALSE);
225 	}
226 	free(name);
227 	(void) close(fd);
228 
229 	if (config == NULL) {
230 		nvlist_free(label);
231 		return (B_TRUE);
232 	}
233 
234 	verify(nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) == 0);
235 	nvlist_free(label);
236 
237 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
238 	    &nvroot) == 0);
239 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
240 	    &spares, &nspares) == 0) {
241 		for (i = 0; i < nspares; i++) {
242 			verify(nvlist_lookup_uint64(spares[i],
243 			    ZPOOL_CONFIG_GUID, &spareguid) == 0);
244 			if (spareguid == guid)
245 				return (B_TRUE);
246 		}
247 	}
248 
249 	return (B_FALSE);
250 }
251 
252 /*
253  * Create a leaf vdev.  Determine if this is a file or a device.  If it's a
254  * device, fill in the device id to make a complete nvlist.  Valid forms for a
255  * leaf vdev are:
256  *
257  *	/dev/xxx	Complete disk path
258  *	/xxx		Full path to file
259  *	xxx		Shorthand for <zfs_vdev_paths>/xxx
260  *	draid*		Virtual dRAID spare
261  */
262 static nvlist_t *
make_leaf_vdev(const char * arg,boolean_t is_primary,uint64_t ashift)263 make_leaf_vdev(const char *arg, boolean_t is_primary, uint64_t ashift)
264 {
265 	char path[MAXPATHLEN];
266 	struct stat64 statbuf;
267 	nvlist_t *vdev = NULL;
268 	const char *type = NULL;
269 	boolean_t wholedisk = B_FALSE;
270 	int err;
271 
272 	/*
273 	 * Determine what type of vdev this is, and put the full path into
274 	 * 'path'.  We detect whether this is a device of file afterwards by
275 	 * checking the st_mode of the file.
276 	 */
277 	if (arg[0] == '/') {
278 		/*
279 		 * Complete device or file path.  Exact type is determined by
280 		 * examining the file descriptor afterwards.  Symbolic links
281 		 * are resolved to their real paths to determine whole disk
282 		 * and S_ISBLK/S_ISREG type checks.  However, we are careful
283 		 * to store the given path as ZPOOL_CONFIG_PATH to ensure we
284 		 * can leverage udev's persistent device labels.
285 		 */
286 		if (realpath(arg, path) == NULL) {
287 			(void) fprintf(stderr,
288 			    gettext("cannot resolve path '%s'\n"), arg);
289 			return (NULL);
290 		}
291 
292 		wholedisk = zfs_dev_is_whole_disk(path);
293 		if (!wholedisk && (stat64(path, &statbuf) != 0)) {
294 			(void) fprintf(stderr,
295 			    gettext("cannot open '%s': %s\n"),
296 			    path, strerror(errno));
297 			return (NULL);
298 		}
299 
300 		/* After whole disk check restore original passed path */
301 		(void) strlcpy(path, arg, sizeof (path));
302 	} else if (zpool_is_draid_spare(arg)) {
303 		if (!is_primary) {
304 			(void) fprintf(stderr,
305 			    gettext("cannot open '%s': dRAID spares can only "
306 			    "be used to replace primary vdevs\n"), arg);
307 			return (NULL);
308 		}
309 
310 		wholedisk = B_TRUE;
311 		(void) strlcpy(path, arg, sizeof (path));
312 		type = VDEV_TYPE_DRAID_SPARE;
313 	} else {
314 		err = is_shorthand_path(arg, path, sizeof (path),
315 		    &statbuf, &wholedisk);
316 		if (err != 0) {
317 			/*
318 			 * If we got ENOENT, then the user gave us
319 			 * gibberish, so try to direct them with a
320 			 * reasonable error message.  Otherwise,
321 			 * regurgitate strerror() since it's the best we
322 			 * can do.
323 			 */
324 			if (err == ENOENT) {
325 				(void) fprintf(stderr,
326 				    gettext("cannot open '%s': no such "
327 				    "device in %s\n"), arg, DISK_ROOT);
328 				(void) fprintf(stderr,
329 				    gettext("must be a full path or "
330 				    "shorthand device name\n"));
331 				return (NULL);
332 			} else {
333 				(void) fprintf(stderr,
334 				    gettext("cannot open '%s': %s\n"),
335 				    path, strerror(errno));
336 				return (NULL);
337 			}
338 		}
339 	}
340 
341 	if (type == NULL) {
342 		/*
343 		 * Determine whether this is a device or a file.
344 		 */
345 		if (wholedisk || S_ISBLK(statbuf.st_mode)) {
346 			type = VDEV_TYPE_DISK;
347 		} else if (S_ISREG(statbuf.st_mode)) {
348 			type = VDEV_TYPE_FILE;
349 		} else {
350 			fprintf(stderr, gettext("cannot use '%s': must "
351 			    "be a block device or regular file\n"), path);
352 			return (NULL);
353 		}
354 	}
355 
356 	/*
357 	 * Finally, we have the complete device or file, and we know that it is
358 	 * acceptable to use.  Construct the nvlist to describe this vdev.  All
359 	 * vdevs have a 'path' element, and devices also have a 'devid' element.
360 	 */
361 	verify(nvlist_alloc(&vdev, NV_UNIQUE_NAME, 0) == 0);
362 	verify(nvlist_add_string(vdev, ZPOOL_CONFIG_PATH, path) == 0);
363 	verify(nvlist_add_string(vdev, ZPOOL_CONFIG_TYPE, type) == 0);
364 
365 	/* Lookup and add the enclosure sysfs path (if exists) */
366 	update_vdev_config_dev_sysfs_path(vdev, path,
367 	    ZPOOL_CONFIG_VDEV_ENC_SYSFS_PATH);
368 
369 	if (strcmp(type, VDEV_TYPE_DISK) == 0)
370 		verify(nvlist_add_uint64(vdev, ZPOOL_CONFIG_WHOLE_DISK,
371 		    (uint64_t)wholedisk) == 0);
372 
373 	/*
374 	 * If the device is known to incorrectly report its physical sector
375 	 * size explicitly provide the known correct value.
376 	 */
377 	if (ashift == 0) {
378 		int sector_size;
379 
380 		if (check_sector_size_database(path, &sector_size) == B_TRUE)
381 			ashift = highbit64(sector_size) - 1;
382 	}
383 
384 	if (ashift > 0)
385 		(void) nvlist_add_uint64(vdev, ZPOOL_CONFIG_ASHIFT, ashift);
386 
387 	return (vdev);
388 }
389 
390 /*
391  * Go through and verify the replication level of the pool is consistent.
392  * Performs the following checks:
393  *
394  * 	For the new spec, verifies that devices in mirrors and raidz are the
395  * 	same size.
396  *
397  * 	If the current configuration already has inconsistent replication
398  * 	levels, ignore any other potential problems in the new spec.
399  *
400  * 	Otherwise, make sure that the current spec (if there is one) and the new
401  * 	spec have consistent replication levels.
402  *
403  *	If there is no current spec (create), make sure new spec has at least
404  *	one general purpose vdev.
405  */
406 typedef struct replication_level {
407 	const char *zprl_type;
408 	uint64_t zprl_children;
409 	uint64_t zprl_parity;
410 } replication_level_t;
411 
412 #define	ZPOOL_FUZZ	(16 * 1024 * 1024)
413 
414 /*
415  * N.B. For the purposes of comparing replication levels dRAID can be
416  * considered functionally equivalent to raidz.
417  */
418 static boolean_t
is_raidz_mirror(replication_level_t * a,replication_level_t * b,replication_level_t ** raidz,replication_level_t ** mirror)419 is_raidz_mirror(replication_level_t *a, replication_level_t *b,
420     replication_level_t **raidz, replication_level_t **mirror)
421 {
422 	if ((strcmp(a->zprl_type, "raidz") == 0 ||
423 	    strcmp(a->zprl_type, "draid") == 0) &&
424 	    strcmp(b->zprl_type, "mirror") == 0) {
425 		*raidz = a;
426 		*mirror = b;
427 		return (B_TRUE);
428 	}
429 	return (B_FALSE);
430 }
431 
432 /*
433  * Comparison for determining if dRAID and raidz where passed in either order.
434  */
435 static boolean_t
is_raidz_draid(replication_level_t * a,replication_level_t * b)436 is_raidz_draid(replication_level_t *a, replication_level_t *b)
437 {
438 	if ((strcmp(a->zprl_type, "raidz") == 0 ||
439 	    strcmp(a->zprl_type, "draid") == 0) &&
440 	    (strcmp(b->zprl_type, "raidz") == 0 ||
441 	    strcmp(b->zprl_type, "draid") == 0)) {
442 		return (B_TRUE);
443 	}
444 
445 	return (B_FALSE);
446 }
447 
448 /*
449  * Given a list of toplevel vdevs, return the current replication level.  If
450  * the config is inconsistent, then NULL is returned.  If 'fatal' is set, then
451  * an error message will be displayed for each self-inconsistent vdev.
452  */
453 static replication_level_t *
get_replication(nvlist_t * nvroot,boolean_t fatal)454 get_replication(nvlist_t *nvroot, boolean_t fatal)
455 {
456 	nvlist_t **top;
457 	uint_t t, toplevels;
458 	nvlist_t **child;
459 	uint_t c, children;
460 	nvlist_t *nv;
461 	const char *type;
462 	replication_level_t lastrep = {0};
463 	replication_level_t rep;
464 	replication_level_t *ret;
465 	replication_level_t *raidz, *mirror;
466 	boolean_t dontreport;
467 
468 	ret = safe_malloc(sizeof (replication_level_t));
469 
470 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
471 	    &top, &toplevels) == 0);
472 
473 	for (t = 0; t < toplevels; t++) {
474 		uint64_t is_log = B_FALSE;
475 
476 		nv = top[t];
477 
478 		/*
479 		 * For separate logs we ignore the top level vdev replication
480 		 * constraints.
481 		 */
482 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG, &is_log);
483 		if (is_log)
484 			continue;
485 
486 		/*
487 		 * Ignore holes introduced by removing aux devices, along
488 		 * with indirect vdevs introduced by previously removed
489 		 * vdevs.
490 		 */
491 		verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
492 		if (strcmp(type, VDEV_TYPE_HOLE) == 0 ||
493 		    strcmp(type, VDEV_TYPE_INDIRECT) == 0)
494 			continue;
495 
496 		if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
497 		    &child, &children) != 0) {
498 			/*
499 			 * This is a 'file' or 'disk' vdev.
500 			 */
501 			rep.zprl_type = type;
502 			rep.zprl_children = 1;
503 			rep.zprl_parity = 0;
504 		} else {
505 			int64_t vdev_size;
506 
507 			/*
508 			 * This is a mirror or RAID-Z vdev.  Go through and make
509 			 * sure the contents are all the same (files vs. disks),
510 			 * keeping track of the number of elements in the
511 			 * process.
512 			 *
513 			 * We also check that the size of each vdev (if it can
514 			 * be determined) is the same.
515 			 */
516 			rep.zprl_type = type;
517 			rep.zprl_children = 0;
518 
519 			if (strcmp(type, VDEV_TYPE_RAIDZ) == 0 ||
520 			    strcmp(type, VDEV_TYPE_DRAID) == 0) {
521 				verify(nvlist_lookup_uint64(nv,
522 				    ZPOOL_CONFIG_NPARITY,
523 				    &rep.zprl_parity) == 0);
524 				assert(rep.zprl_parity != 0);
525 			} else {
526 				rep.zprl_parity = 0;
527 			}
528 
529 			/*
530 			 * The 'dontreport' variable indicates that we've
531 			 * already reported an error for this spec, so don't
532 			 * bother doing it again.
533 			 */
534 			type = NULL;
535 			dontreport = 0;
536 			vdev_size = -1LL;
537 			for (c = 0; c < children; c++) {
538 				nvlist_t *cnv = child[c];
539 				const char *path;
540 				struct stat64 statbuf;
541 				const char *childtype;
542 				int fd, err;
543 
544 				rep.zprl_children++;
545 
546 				verify(nvlist_lookup_string(cnv,
547 				    ZPOOL_CONFIG_TYPE, &childtype) == 0);
548 
549 				/*
550 				 * If this is a replacing or spare vdev, then
551 				 * get the real first child of the vdev: do this
552 				 * in a loop because replacing and spare vdevs
553 				 * can be nested.
554 				 */
555 				while (strcmp(childtype,
556 				    VDEV_TYPE_REPLACING) == 0 ||
557 				    strcmp(childtype, VDEV_TYPE_SPARE) == 0) {
558 					nvlist_t **rchild;
559 					uint_t rchildren;
560 
561 					verify(nvlist_lookup_nvlist_array(cnv,
562 					    ZPOOL_CONFIG_CHILDREN, &rchild,
563 					    &rchildren) == 0);
564 					assert(rchildren == 2);
565 					cnv = rchild[0];
566 
567 					verify(nvlist_lookup_string(cnv,
568 					    ZPOOL_CONFIG_TYPE,
569 					    &childtype) == 0);
570 				}
571 
572 				verify(nvlist_lookup_string(cnv,
573 				    ZPOOL_CONFIG_PATH, &path) == 0);
574 
575 				/*
576 				 * Skip active spares they should never cause
577 				 * the pool to be evaluated as inconsistent.
578 				 */
579 				if (is_spare(NULL, path))
580 					continue;
581 
582 				/*
583 				 * If we have a raidz/mirror that combines disks
584 				 * with files, only report it as an error when
585 				 * fatal is set to ensure all the replication
586 				 * checks aren't skipped in check_replication().
587 				 */
588 				if (fatal && !dontreport && type != NULL &&
589 				    strcmp(type, childtype) != 0) {
590 					if (ret != NULL)
591 						free(ret);
592 					ret = NULL;
593 					vdev_error(gettext(
594 					    "mismatched replication "
595 					    "level: %s contains both "
596 					    "files and devices\n"),
597 					    rep.zprl_type);
598 					dontreport = B_TRUE;
599 				}
600 
601 				/*
602 				 * According to stat(2), the value of 'st_size'
603 				 * is undefined for block devices and character
604 				 * devices.  But there is no effective way to
605 				 * determine the real size in userland.
606 				 *
607 				 * Instead, we'll take advantage of an
608 				 * implementation detail of spec_size().  If the
609 				 * device is currently open, then we (should)
610 				 * return a valid size.
611 				 *
612 				 * If we still don't get a valid size (indicated
613 				 * by a size of 0 or MAXOFFSET_T), then ignore
614 				 * this device altogether.
615 				 */
616 				if ((fd = open(path, O_RDONLY)) >= 0) {
617 					err = fstat64_blk(fd, &statbuf);
618 					(void) close(fd);
619 				} else {
620 					err = stat64(path, &statbuf);
621 				}
622 
623 				if (err != 0 ||
624 				    statbuf.st_size == 0 ||
625 				    statbuf.st_size == MAXOFFSET_T)
626 					continue;
627 
628 				int64_t size = statbuf.st_size;
629 
630 				/*
631 				 * Also make sure that devices and
632 				 * slices have a consistent size.  If
633 				 * they differ by a significant amount
634 				 * (~16MB) then report an error.
635 				 */
636 				if (!dontreport &&
637 				    (vdev_size != -1LL &&
638 				    (llabs(size - vdev_size) >
639 				    ZPOOL_FUZZ))) {
640 					if (ret != NULL)
641 						free(ret);
642 					ret = NULL;
643 					if (fatal)
644 						vdev_error(gettext(
645 						    "%s contains devices of "
646 						    "different sizes\n"),
647 						    rep.zprl_type);
648 					else
649 						return (NULL);
650 					dontreport = B_TRUE;
651 				}
652 
653 				type = childtype;
654 				vdev_size = size;
655 			}
656 		}
657 
658 		/*
659 		 * At this point, we have the replication of the last toplevel
660 		 * vdev in 'rep'.  Compare it to 'lastrep' to see if it is
661 		 * different.
662 		 */
663 		if (lastrep.zprl_type != NULL) {
664 			if (is_raidz_mirror(&lastrep, &rep, &raidz, &mirror) ||
665 			    is_raidz_mirror(&rep, &lastrep, &raidz, &mirror)) {
666 				/*
667 				 * Accepted raidz and mirror when they can
668 				 * handle the same number of disk failures.
669 				 */
670 				if (raidz->zprl_parity !=
671 				    mirror->zprl_children - 1) {
672 					if (ret != NULL)
673 						free(ret);
674 					ret = NULL;
675 					if (fatal)
676 						vdev_error(gettext(
677 						    "mismatched replication "
678 						    "level: "
679 						    "%s and %s vdevs with "
680 						    "different redundancy, "
681 						    "%llu vs. %llu (%llu-way) "
682 						    "are present\n"),
683 						    raidz->zprl_type,
684 						    mirror->zprl_type,
685 						    (u_longlong_t)
686 						    raidz->zprl_parity,
687 						    (u_longlong_t)
688 						    mirror->zprl_children - 1,
689 						    (u_longlong_t)
690 						    mirror->zprl_children);
691 					else
692 						return (NULL);
693 				}
694 			} else if (is_raidz_draid(&lastrep, &rep)) {
695 				/*
696 				 * Accepted raidz and draid when they can
697 				 * handle the same number of disk failures.
698 				 */
699 				if (lastrep.zprl_parity != rep.zprl_parity) {
700 					if (ret != NULL)
701 						free(ret);
702 					ret = NULL;
703 					if (fatal)
704 						vdev_error(gettext(
705 						    "mismatched replication "
706 						    "level: %s and %s vdevs "
707 						    "with different "
708 						    "redundancy, %llu vs. "
709 						    "%llu are present\n"),
710 						    lastrep.zprl_type,
711 						    rep.zprl_type,
712 						    (u_longlong_t)
713 						    lastrep.zprl_parity,
714 						    (u_longlong_t)
715 						    rep.zprl_parity);
716 					else
717 						return (NULL);
718 				}
719 			} else if (strcmp(lastrep.zprl_type, rep.zprl_type) !=
720 			    0) {
721 				if (ret != NULL)
722 					free(ret);
723 				ret = NULL;
724 				if (fatal)
725 					vdev_error(gettext(
726 					    "mismatched replication level: "
727 					    "both %s and %s vdevs are "
728 					    "present\n"),
729 					    lastrep.zprl_type, rep.zprl_type);
730 				else
731 					return (NULL);
732 			} else if (lastrep.zprl_parity != rep.zprl_parity) {
733 				if (ret)
734 					free(ret);
735 				ret = NULL;
736 				if (fatal)
737 					vdev_error(gettext(
738 					    "mismatched replication level: "
739 					    "both %llu and %llu device parity "
740 					    "%s vdevs are present\n"),
741 					    (u_longlong_t)
742 					    lastrep.zprl_parity,
743 					    (u_longlong_t)rep.zprl_parity,
744 					    rep.zprl_type);
745 				else
746 					return (NULL);
747 			} else if (lastrep.zprl_children != rep.zprl_children) {
748 				if (ret)
749 					free(ret);
750 				ret = NULL;
751 				if (fatal)
752 					vdev_error(gettext(
753 					    "mismatched replication level: "
754 					    "both %llu-way and %llu-way %s "
755 					    "vdevs are present\n"),
756 					    (u_longlong_t)
757 					    lastrep.zprl_children,
758 					    (u_longlong_t)
759 					    rep.zprl_children,
760 					    rep.zprl_type);
761 				else
762 					return (NULL);
763 			}
764 		}
765 		lastrep = rep;
766 	}
767 
768 	if (ret != NULL)
769 		*ret = rep;
770 
771 	return (ret);
772 }
773 
774 /*
775  * Check the replication level of the vdev spec against the current pool.  Calls
776  * get_replication() to make sure the new spec is self-consistent.  If the pool
777  * has a consistent replication level, then we ignore any errors.  Otherwise,
778  * report any difference between the two.
779  */
780 static int
check_replication(nvlist_t * config,nvlist_t * newroot)781 check_replication(nvlist_t *config, nvlist_t *newroot)
782 {
783 	nvlist_t **child;
784 	uint_t	children;
785 	replication_level_t *current = NULL, *new;
786 	replication_level_t *raidz, *mirror;
787 	int ret;
788 
789 	/*
790 	 * If we have a current pool configuration, check to see if it's
791 	 * self-consistent.  If not, simply return success.
792 	 */
793 	if (config != NULL) {
794 		nvlist_t *nvroot;
795 
796 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
797 		    &nvroot) == 0);
798 		if ((current = get_replication(nvroot, B_FALSE)) == NULL)
799 			return (0);
800 	}
801 	/*
802 	 * for spares there may be no children, and therefore no
803 	 * replication level to check
804 	 */
805 	if ((nvlist_lookup_nvlist_array(newroot, ZPOOL_CONFIG_CHILDREN,
806 	    &child, &children) != 0) || (children == 0)) {
807 		free(current);
808 		return (0);
809 	}
810 
811 	/*
812 	 * If all we have is logs then there's no replication level to check.
813 	 */
814 	if (num_logs(newroot) == children) {
815 		free(current);
816 		return (0);
817 	}
818 
819 	/*
820 	 * Get the replication level of the new vdev spec, reporting any
821 	 * inconsistencies found.
822 	 */
823 	if ((new = get_replication(newroot, B_TRUE)) == NULL) {
824 		free(current);
825 		return (-1);
826 	}
827 
828 	/*
829 	 * Check to see if the new vdev spec matches the replication level of
830 	 * the current pool.
831 	 */
832 	ret = 0;
833 	if (current != NULL) {
834 		if (is_raidz_mirror(current, new, &raidz, &mirror) ||
835 		    is_raidz_mirror(new, current, &raidz, &mirror)) {
836 			if (raidz->zprl_parity != mirror->zprl_children - 1) {
837 				vdev_error(gettext(
838 				    "mismatched replication level: pool and "
839 				    "new vdev with different redundancy, %s "
840 				    "and %s vdevs, %llu vs. %llu (%llu-way)\n"),
841 				    raidz->zprl_type,
842 				    mirror->zprl_type,
843 				    (u_longlong_t)raidz->zprl_parity,
844 				    (u_longlong_t)mirror->zprl_children - 1,
845 				    (u_longlong_t)mirror->zprl_children);
846 				ret = -1;
847 			}
848 		} else if (is_raidz_draid(current, new)) {
849 			if (current->zprl_parity != new->zprl_parity) {
850 				vdev_error(gettext(
851 				    "mismatched replication level: pool and "
852 				    "new vdev with different redundancy, %s "
853 				    "and %s vdevs, %llu vs. %llu\n"),
854 				    current->zprl_type,
855 				    new->zprl_type,
856 				    (u_longlong_t)current->zprl_parity,
857 				    (u_longlong_t)new->zprl_parity);
858 				ret = -1;
859 			}
860 		} else if (strcmp(current->zprl_type, new->zprl_type) != 0) {
861 			vdev_error(gettext(
862 			    "mismatched replication level: pool uses %s "
863 			    "and new vdev is %s\n"),
864 			    current->zprl_type, new->zprl_type);
865 			ret = -1;
866 		} else if (current->zprl_parity != new->zprl_parity) {
867 			vdev_error(gettext(
868 			    "mismatched replication level: pool uses %llu "
869 			    "device parity and new vdev uses %llu\n"),
870 			    (u_longlong_t)current->zprl_parity,
871 			    (u_longlong_t)new->zprl_parity);
872 			ret = -1;
873 		} else if (current->zprl_children != new->zprl_children) {
874 			vdev_error(gettext(
875 			    "mismatched replication level: pool uses %llu-way "
876 			    "%s and new vdev uses %llu-way %s\n"),
877 			    (u_longlong_t)current->zprl_children,
878 			    current->zprl_type,
879 			    (u_longlong_t)new->zprl_children,
880 			    new->zprl_type);
881 			ret = -1;
882 		}
883 	}
884 
885 	free(new);
886 	if (current != NULL)
887 		free(current);
888 
889 	return (ret);
890 }
891 
892 static int
zero_label(const char * path)893 zero_label(const char *path)
894 {
895 	const int size = 4096;
896 	char buf[size];
897 	int err, fd;
898 
899 	if ((fd = open(path, O_WRONLY|O_EXCL)) < 0) {
900 		(void) fprintf(stderr, gettext("cannot open '%s': %s\n"),
901 		    path, strerror(errno));
902 		return (-1);
903 	}
904 
905 	memset(buf, 0, size);
906 	err = write(fd, buf, size);
907 	(void) fdatasync(fd);
908 	(void) close(fd);
909 
910 	if (err == -1) {
911 		(void) fprintf(stderr, gettext("cannot zero first %d bytes "
912 		    "of '%s': %s\n"), size, path, strerror(errno));
913 		return (-1);
914 	}
915 
916 	if (err != size) {
917 		(void) fprintf(stderr, gettext("could only zero %d/%d bytes "
918 		    "of '%s'\n"), err, size, path);
919 		return (-1);
920 	}
921 
922 	return (0);
923 }
924 
925 static void
lines_to_stderr(char * lines[],int lines_cnt)926 lines_to_stderr(char *lines[], int lines_cnt)
927 {
928 	int i;
929 	for (i = 0; i < lines_cnt; i++) {
930 		fprintf(stderr, "%s\n", lines[i]);
931 	}
932 }
933 
934 /*
935  * Go through and find any whole disks in the vdev specification, labelling them
936  * as appropriate.  When constructing the vdev spec, we were unable to open this
937  * device in order to provide a devid.  Now that we have labelled the disk and
938  * know that slice 0 is valid, we can construct the devid now.
939  *
940  * If the disk was already labeled with an EFI label, we will have gotten the
941  * devid already (because we were able to open the whole disk).  Otherwise, we
942  * need to get the devid after we label the disk.
943  */
944 static int
make_disks(zpool_handle_t * zhp,nvlist_t * nv,boolean_t replacing)945 make_disks(zpool_handle_t *zhp, nvlist_t *nv, boolean_t replacing)
946 {
947 	nvlist_t **child;
948 	uint_t c, children;
949 	const char *type, *path;
950 	char devpath[MAXPATHLEN];
951 	char udevpath[MAXPATHLEN];
952 	uint64_t wholedisk;
953 	struct stat64 statbuf;
954 	int is_exclusive = 0;
955 	int fd;
956 	int ret;
957 
958 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
959 
960 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
961 	    &child, &children) != 0) {
962 
963 		if (strcmp(type, VDEV_TYPE_DISK) != 0)
964 			return (0);
965 
966 		/*
967 		 * We have a disk device.  If this is a whole disk write
968 		 * out the efi partition table, otherwise write zero's to
969 		 * the first 4k of the partition.  This is to ensure that
970 		 * libblkid will not misidentify the partition due to a
971 		 * magic value left by the previous filesystem.
972 		 */
973 		verify(!nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path));
974 		verify(!nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
975 		    &wholedisk));
976 
977 		if (!wholedisk) {
978 			/*
979 			 * Update device id string for mpath nodes (Linux only)
980 			 */
981 			if (is_mpath_whole_disk(path))
982 				update_vdev_config_dev_strs(nv);
983 
984 			if (!is_spare(NULL, path))
985 				(void) zero_label(path);
986 			return (0);
987 		}
988 
989 		if (realpath(path, devpath) == NULL) {
990 			ret = errno;
991 			(void) fprintf(stderr,
992 			    gettext("cannot resolve path '%s'\n"), path);
993 			return (ret);
994 		}
995 
996 		/*
997 		 * Remove any previously existing symlink from a udev path to
998 		 * the device before labeling the disk.  This ensures that
999 		 * only newly created links are used.  Otherwise there is a
1000 		 * window between when udev deletes and recreates the link
1001 		 * during which access attempts will fail with ENOENT.
1002 		 */
1003 		(void) strlcpy(udevpath, path, MAXPATHLEN);
1004 		(void) zfs_append_partition(udevpath, MAXPATHLEN);
1005 
1006 		fd = open(devpath, O_RDWR|O_EXCL);
1007 		if (fd == -1) {
1008 			if (errno == EBUSY)
1009 				is_exclusive = 1;
1010 #ifdef __FreeBSD__
1011 			if (errno == EPERM)
1012 				is_exclusive = 1;
1013 #endif
1014 		} else {
1015 			(void) close(fd);
1016 		}
1017 
1018 		/*
1019 		 * If the partition exists, contains a valid spare label,
1020 		 * and is opened exclusively there is no need to partition
1021 		 * it.  Hot spares have already been partitioned and are
1022 		 * held open exclusively by the kernel as a safety measure.
1023 		 *
1024 		 * If the provided path is for a /dev/disk/ device its
1025 		 * symbolic link will be removed, partition table created,
1026 		 * and then block until udev creates the new link.
1027 		 */
1028 		if (!is_exclusive && !is_spare(NULL, udevpath)) {
1029 			char *devnode = strrchr(devpath, '/') + 1;
1030 			char **lines = NULL;
1031 			int lines_cnt = 0;
1032 
1033 			ret = strncmp(udevpath, UDISK_ROOT, strlen(UDISK_ROOT));
1034 			if (ret == 0) {
1035 				ret = lstat64(udevpath, &statbuf);
1036 				if (ret == 0 && S_ISLNK(statbuf.st_mode))
1037 					(void) unlink(udevpath);
1038 			}
1039 
1040 			/*
1041 			 * When labeling a pool the raw device node name
1042 			 * is provided as it appears under /dev/.
1043 			 *
1044 			 * Note that 'zhp' will be NULL when we're creating a
1045 			 * pool.
1046 			 */
1047 			if (zpool_prepare_and_label_disk(g_zfs, zhp, devnode,
1048 			    nv, zhp == NULL ? "create" :
1049 			    replacing ? "replace" : "add", &lines,
1050 			    &lines_cnt) != 0) {
1051 				(void) fprintf(stderr,
1052 				    gettext(
1053 				    "Error preparing/labeling disk.\n"));
1054 				if (lines_cnt > 0) {
1055 					(void) fprintf(stderr,
1056 					gettext("zfs_prepare_disk output:\n"));
1057 					lines_to_stderr(lines, lines_cnt);
1058 				}
1059 
1060 				libzfs_free_str_array(lines, lines_cnt);
1061 				return (-1);
1062 			}
1063 			libzfs_free_str_array(lines, lines_cnt);
1064 
1065 			/*
1066 			 * Wait for udev to signal the device is available
1067 			 * by the provided path.
1068 			 */
1069 			ret = zpool_label_disk_wait(udevpath, DISK_LABEL_WAIT);
1070 			if (ret) {
1071 				(void) fprintf(stderr,
1072 				    gettext("missing link: %s was "
1073 				    "partitioned but %s is missing\n"),
1074 				    devnode, udevpath);
1075 				return (ret);
1076 			}
1077 
1078 			ret = zero_label(udevpath);
1079 			if (ret)
1080 				return (ret);
1081 		}
1082 
1083 		/*
1084 		 * Update the path to refer to the partition.  The presence of
1085 		 * the 'whole_disk' field indicates to the CLI that we should
1086 		 * chop off the partition number when displaying the device in
1087 		 * future output.
1088 		 */
1089 		verify(nvlist_add_string(nv, ZPOOL_CONFIG_PATH, udevpath) == 0);
1090 
1091 		/*
1092 		 * Update device id strings for whole disks (Linux only)
1093 		 */
1094 		update_vdev_config_dev_strs(nv);
1095 
1096 		return (0);
1097 	}
1098 
1099 	for (c = 0; c < children; c++)
1100 		if ((ret = make_disks(zhp, child[c], replacing)) != 0)
1101 			return (ret);
1102 
1103 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1104 	    &child, &children) == 0)
1105 		for (c = 0; c < children; c++)
1106 			if ((ret = make_disks(zhp, child[c], replacing)) != 0)
1107 				return (ret);
1108 
1109 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1110 	    &child, &children) == 0)
1111 		for (c = 0; c < children; c++)
1112 			if ((ret = make_disks(zhp, child[c], replacing)) != 0)
1113 				return (ret);
1114 
1115 	return (0);
1116 }
1117 
1118 /*
1119  * Go through and find any devices that are in use.  We rely on libdiskmgt for
1120  * the majority of this task.
1121  */
1122 static boolean_t
is_device_in_use(nvlist_t * config,nvlist_t * nv,boolean_t force,boolean_t replacing,boolean_t isspare)1123 is_device_in_use(nvlist_t *config, nvlist_t *nv, boolean_t force,
1124     boolean_t replacing, boolean_t isspare)
1125 {
1126 	nvlist_t **child;
1127 	uint_t c, children;
1128 	const char *type, *path;
1129 	int ret = 0;
1130 	char buf[MAXPATHLEN];
1131 	uint64_t wholedisk = B_FALSE;
1132 	boolean_t anyinuse = B_FALSE;
1133 
1134 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
1135 
1136 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1137 	    &child, &children) != 0) {
1138 
1139 		verify(!nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path));
1140 		if (strcmp(type, VDEV_TYPE_DISK) == 0)
1141 			verify(!nvlist_lookup_uint64(nv,
1142 			    ZPOOL_CONFIG_WHOLE_DISK, &wholedisk));
1143 
1144 		/*
1145 		 * As a generic check, we look to see if this is a replace of a
1146 		 * hot spare within the same pool.  If so, we allow it
1147 		 * regardless of what libblkid or zpool_in_use() says.
1148 		 */
1149 		if (replacing) {
1150 			(void) strlcpy(buf, path, sizeof (buf));
1151 			if (wholedisk) {
1152 				ret = zfs_append_partition(buf,  sizeof (buf));
1153 				if (ret == -1)
1154 					return (-1);
1155 			}
1156 
1157 			if (is_spare(config, buf))
1158 				return (B_FALSE);
1159 		}
1160 
1161 		if (strcmp(type, VDEV_TYPE_DISK) == 0)
1162 			ret = check_device(path, force, isspare, wholedisk);
1163 
1164 		else if (strcmp(type, VDEV_TYPE_FILE) == 0)
1165 			ret = check_file(path, force, isspare);
1166 
1167 		return (ret != 0);
1168 	}
1169 
1170 	for (c = 0; c < children; c++)
1171 		if (is_device_in_use(config, child[c], force, replacing,
1172 		    B_FALSE))
1173 			anyinuse = B_TRUE;
1174 
1175 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1176 	    &child, &children) == 0)
1177 		for (c = 0; c < children; c++)
1178 			if (is_device_in_use(config, child[c], force, replacing,
1179 			    B_TRUE))
1180 				anyinuse = B_TRUE;
1181 
1182 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1183 	    &child, &children) == 0)
1184 		for (c = 0; c < children; c++)
1185 			if (is_device_in_use(config, child[c], force, replacing,
1186 			    B_FALSE))
1187 				anyinuse = B_TRUE;
1188 
1189 	return (anyinuse);
1190 }
1191 
1192 /*
1193  * Returns the parity level extracted from a raidz or draid type.
1194  * If the parity cannot be determined zero is returned.
1195  */
1196 static int
get_parity(const char * type)1197 get_parity(const char *type)
1198 {
1199 	long parity = 0;
1200 	const char *p;
1201 
1202 	if (strncmp(type, VDEV_TYPE_RAIDZ, strlen(VDEV_TYPE_RAIDZ)) == 0) {
1203 		p = type + strlen(VDEV_TYPE_RAIDZ);
1204 
1205 		if (*p == '\0') {
1206 			/* when unspecified default to single parity */
1207 			return (1);
1208 		} else if (*p == '0') {
1209 			/* no zero prefixes allowed */
1210 			return (0);
1211 		} else {
1212 			/* 0-3, no suffixes allowed */
1213 			char *end;
1214 			errno = 0;
1215 			parity = strtol(p, &end, 10);
1216 			if (errno != 0 || *end != '\0' ||
1217 			    parity < 1 || parity > VDEV_RAIDZ_MAXPARITY) {
1218 				return (0);
1219 			}
1220 		}
1221 	} else if (strncmp(type, VDEV_TYPE_DRAID,
1222 	    strlen(VDEV_TYPE_DRAID)) == 0) {
1223 		p = type + strlen(VDEV_TYPE_DRAID);
1224 
1225 		if (*p == '\0' || *p == ':') {
1226 			/* when unspecified default to single parity */
1227 			return (1);
1228 		} else if (*p == '0') {
1229 			/* no zero prefixes allowed */
1230 			return (0);
1231 		} else {
1232 			/* 0-3, allowed suffixes: '\0' or ':' */
1233 			char *end;
1234 			errno = 0;
1235 			parity = strtol(p, &end, 10);
1236 			if (errno != 0 ||
1237 			    parity < 1 || parity > VDEV_DRAID_MAXPARITY ||
1238 			    (*end != '\0' && *end != ':')) {
1239 				return (0);
1240 			}
1241 		}
1242 	}
1243 
1244 	return ((int)parity);
1245 }
1246 
1247 /*
1248  * Assign the minimum and maximum number of devices allowed for
1249  * the specified type.  On error NULL is returned, otherwise the
1250  * type prefix is returned (raidz, mirror, etc).
1251  */
1252 static const char *
is_grouping(const char * type,int * mindev,int * maxdev)1253 is_grouping(const char *type, int *mindev, int *maxdev)
1254 {
1255 	int nparity;
1256 
1257 	if (strncmp(type, VDEV_TYPE_RAIDZ, strlen(VDEV_TYPE_RAIDZ)) == 0 ||
1258 	    strncmp(type, VDEV_TYPE_DRAID, strlen(VDEV_TYPE_DRAID)) == 0) {
1259 		nparity = get_parity(type);
1260 		if (nparity == 0)
1261 			return (NULL);
1262 		if (mindev != NULL)
1263 			*mindev = nparity + 1;
1264 		if (maxdev != NULL)
1265 			*maxdev = 255;
1266 
1267 		if (strncmp(type, VDEV_TYPE_RAIDZ,
1268 		    strlen(VDEV_TYPE_RAIDZ)) == 0) {
1269 			return (VDEV_TYPE_RAIDZ);
1270 		} else {
1271 			return (VDEV_TYPE_DRAID);
1272 		}
1273 	}
1274 
1275 	if (maxdev != NULL)
1276 		*maxdev = INT_MAX;
1277 
1278 	if (strcmp(type, "mirror") == 0) {
1279 		if (mindev != NULL)
1280 			*mindev = 2;
1281 		return (VDEV_TYPE_MIRROR);
1282 	}
1283 
1284 	if (strcmp(type, "spare") == 0) {
1285 		if (mindev != NULL)
1286 			*mindev = 1;
1287 		return (VDEV_TYPE_SPARE);
1288 	}
1289 
1290 	if (strcmp(type, "log") == 0) {
1291 		if (mindev != NULL)
1292 			*mindev = 1;
1293 		return (VDEV_TYPE_LOG);
1294 	}
1295 
1296 	if (strcmp(type, VDEV_ALLOC_BIAS_SPECIAL) == 0 ||
1297 	    strcmp(type, VDEV_ALLOC_BIAS_DEDUP) == 0) {
1298 		if (mindev != NULL)
1299 			*mindev = 1;
1300 		return (type);
1301 	}
1302 
1303 	if (strcmp(type, "cache") == 0) {
1304 		if (mindev != NULL)
1305 			*mindev = 1;
1306 		return (VDEV_TYPE_L2CACHE);
1307 	}
1308 
1309 	return (NULL);
1310 }
1311 
1312 /*
1313  * Extract the configuration parameters encoded in the dRAID type and
1314  * use them to generate a dRAID configuration.  The expected format is:
1315  *
1316  * draid[<parity>][:<data>d][:<children>c][:<spares>s][:<width>w]
1317  *
1318  * The intent is to be able to generate a good configuration when no
1319  * additional information is provided.  The only mandatory component
1320  * of the 'type' is the 'draid' prefix.  If a value is not provided
1321  * then reasonable defaults are used.  The optional components may
1322  * appear in any order but the d/s/c/w suffix is required.
1323  *
1324  * Valid inputs:
1325  * - data:     number of data devices per group (1-255)
1326  * - parity:   number of parity devices per group (1-3)
1327  * - children: total number of devices in slice (1-255)
1328  * - width:    total number of devices, multiple of children (1-255 for now)
1329  * - spares:   number of distributed spare devices (0-100)
1330  *
1331  * Examples:
1332  * - zpool create tank draid <devices...>
1333  * - zpool create tank draid2:8d:51c:2s <devices...>
1334  * - zpool create tank draid2:8d:12c:96w:8s <devices...>
1335  */
1336 static int
draid_config_by_type(nvlist_t * nv,const char * type,uint64_t width,int nfgroup,int nfdomain)1337 draid_config_by_type(nvlist_t *nv, const char *type, uint64_t width,
1338     int nfgroup, int nfdomain)
1339 {
1340 	uint64_t nparity;
1341 	uint64_t nspares = 0;
1342 	uint64_t ndata = UINT64_MAX;
1343 	uint64_t ngroups = 1;
1344 	uint64_t children = 0;
1345 	long value;
1346 
1347 	if (strncmp(type, VDEV_TYPE_DRAID, strlen(VDEV_TYPE_DRAID)) != 0)
1348 		return (EINVAL);
1349 
1350 	if (nfgroup && nfdomain) /* must be only one of two or none */
1351 		return (EINVAL);
1352 
1353 	nparity = (uint64_t)get_parity(type);
1354 	if (nparity == 0 || nparity > VDEV_DRAID_MAXPARITY) {
1355 		fprintf(stderr,
1356 		    gettext("invalid dRAID parity level %llu; must be "
1357 		    "between 1 and %d\n"), (u_longlong_t)nparity,
1358 		    VDEV_DRAID_MAXPARITY);
1359 		return (EINVAL);
1360 	}
1361 
1362 	char *p = (char *)type;
1363 	while ((p = strchr(p, ':')) != NULL) {
1364 		char *end;
1365 
1366 		p = p + 1;
1367 		errno = 0;
1368 
1369 		if (!isdigit(p[0])) {
1370 			(void) fprintf(stderr, gettext("invalid dRAID "
1371 			    "syntax; expected [:<number><c|d|s>] not '%s'\n"),
1372 			    type);
1373 			return (EINVAL);
1374 		}
1375 
1376 		/* Expected non-zero value with c/d/s/w suffix */
1377 		value = strtol(p, &end, 10);
1378 		char suffix = tolower(*end);
1379 		if (errno != 0 ||
1380 		    (suffix != 'c' && suffix != 'd' && suffix != 's' &&
1381 		    suffix != 'w')) {
1382 			(void) fprintf(stderr, gettext("invalid dRAID "
1383 			    "syntax; expected [:<number><c|d|s|w>], "
1384 			    "not '%s'\n"), type);
1385 			return (EINVAL);
1386 		}
1387 
1388 		if (suffix == 'c') {
1389 			if ((uint64_t)value > width ||
1390 			    width % (uint64_t)value != 0) {
1391 				fprintf(stderr,
1392 				    gettext("invalid number of dRAID disks; "
1393 				    "multiple of %llu required but %llu "
1394 				    "provided\n"), (u_longlong_t)value,
1395 				    (u_longlong_t)width);
1396 				return (EINVAL);
1397 			}
1398 			children = value;
1399 		} else if (suffix == 'w') {
1400 			if ((uint64_t)value != width) {
1401 				fprintf(stderr,
1402 				    gettext("invalid number of dRAID disks; "
1403 				    "%llu required but %llu provided\n"),
1404 				    (u_longlong_t)value, (u_longlong_t)width);
1405 				return (EINVAL);
1406 			}
1407 		} else if (suffix == 'd') {
1408 			ndata = (uint64_t)value;
1409 		} else if (suffix == 's') {
1410 			nspares = (uint64_t)value;
1411 		} else {
1412 			verify(0); /* Unreachable */
1413 		}
1414 	}
1415 
1416 	if (!children && nfgroup)
1417 		children = width / nfgroup;
1418 	if (!children && nfdomain)
1419 		children = nfdomain;
1420 	if (!children)
1421 		children = width;
1422 
1423 	int fgrps = width / children;
1424 
1425 	if (fgrps == 1 && (nfgroup || nfdomain)) {
1426 		fprintf(stderr, gettext("failure domains are not set "
1427 		    "in dRAID vdev descriptor\n"));
1428 		return (EINVAL);
1429 	}
1430 
1431 	if (fgrps > 1 && nfgroup && fgrps != nfgroup) {
1432 		fprintf(stderr, gettext("invalid number of failure groups "
1433 		    "%d, must be %d\n"), nfgroup, fgrps);
1434 		return (EINVAL);
1435 	}
1436 
1437 	if (fgrps > 1 && nfdomain && nfdomain != children) {
1438 		fprintf(stderr, gettext("invalid number of failure domains "
1439 		    "%d, must be %llu\n"), nfdomain, (u_longlong_t)children);
1440 		return (EINVAL);
1441 	}
1442 
1443 	int nspare = nspares / fgrps;
1444 	if (nspares % fgrps)
1445 		nspare++;
1446 
1447 	/*
1448 	 * When a specific number of data disks is not provided limit a
1449 	 * redundancy group to 8 data disks.  This value was selected to
1450 	 * provide a reasonable tradeoff between capacity and performance.
1451 	 */
1452 	if (ndata == UINT64_MAX) {
1453 		if (children > (nspare + nparity)) {
1454 			ndata = MIN(children - nspare - nparity, 8);
1455 		} else {
1456 			fprintf(stderr, gettext("requested number of "
1457 			    "distributed spares %llu and parity level %llu "
1458 			    "leaves no disks available for data\n"),
1459 			    (u_longlong_t)nspare, (u_longlong_t)nparity);
1460 			return (EINVAL);
1461 		}
1462 	}
1463 
1464 	/* Verify the maximum allowed group size is never exceeded. */
1465 	if (ndata == 0 || (ndata + nparity > children - nspare)) {
1466 		fprintf(stderr, gettext("requested number of dRAID data "
1467 		    "disks %llu per group is too high,\nat most %llu disks "
1468 		    "are available for data\n"), (u_longlong_t)ndata,
1469 		    (u_longlong_t)(children - nspare - nparity));
1470 		return (EINVAL);
1471 	}
1472 
1473 	/*
1474 	 * Verify the requested number of spares can be satisfied.
1475 	 * An arbitrary limit of 100 distributed spares is applied.
1476 	 */
1477 	if (nspare > 100 || nspare > (children - (ndata + nparity))) {
1478 		fprintf(stderr,
1479 		    gettext("invalid number of dRAID spares %llu; additional "
1480 		    "disks would be required\n"), (u_longlong_t)nspares);
1481 		return (EINVAL);
1482 	}
1483 
1484 	/* Verify the requested number children is sufficient. */
1485 	if (children < (ndata + nparity + nspare)) {
1486 		fprintf(stderr, gettext("%llu disks were provided, but at "
1487 		    "least %llu disks are required for this config\n"),
1488 		    (u_longlong_t)children,
1489 		    (u_longlong_t)(ndata + nparity + nspare));
1490 	}
1491 
1492 	if (width > VDEV_DRAID_MAX_CHILDREN) {
1493 		fprintf(stderr, gettext("%llu disks were provided, but "
1494 		    "dRAID only supports up to %u disks"),
1495 		    (u_longlong_t)children, VDEV_DRAID_MAX_CHILDREN);
1496 	}
1497 
1498 	/*
1499 	 * Calculate the minimum number of groups required to fill a slice.
1500 	 * This is the LCM of the stripe width (ndata + nparity) and the
1501 	 * number of data drives (children - nspare).
1502 	 *
1503 	 * In case of failure domains, some failure groups may have less
1504 	 * number of spares than others, so they will have different number
1505 	 * of ngroups.
1506 	 */
1507 	uint64_t ndisks1 = children - (nspares / fgrps);
1508 	uint64_t ndisks2 = (nspares % fgrps) ? ndisks1 - 1 : ndisks1;
1509 	while (ngroups * (ndata + nparity) % ndisks2 != 0 ||
1510 	    (ndisks1 != ndisks2 &&
1511 	    ((ngroups + 1) * (ndata + nparity) % ndisks1) != 0))
1512 		ngroups++;
1513 
1514 	/* Keep bigger valude of ngroups for the next calculation. */
1515 	if (ndisks1 != ndisks2)
1516 		ngroups++;
1517 
1518 	/*
1519 	 * Total ngroups in all failure groups. The failure groups with
1520 	 * additional spare (nspares % fgrps) have one less ngroups.
1521 	 */
1522 	ngroups = (ngroups - 1) * (nspares % fgrps) +
1523 	    ngroups * (fgrps - (nspares % fgrps));
1524 
1525 	/* Store the basic dRAID configuration. */
1526 	fnvlist_add_uint64(nv, ZPOOL_CONFIG_NPARITY, nparity);
1527 	fnvlist_add_uint64(nv, ZPOOL_CONFIG_DRAID_NDATA, ndata);
1528 	fnvlist_add_uint64(nv, ZPOOL_CONFIG_DRAID_NSPARES, nspares);
1529 	fnvlist_add_uint64(nv, ZPOOL_CONFIG_DRAID_NGROUPS, ngroups);
1530 	fnvlist_add_uint64(nv, ZPOOL_CONFIG_DRAID_NCHILDREN, children);
1531 
1532 	return (0);
1533 }
1534 
1535 /*
1536  * Construct a syntactically valid vdev specification,
1537  * and ensure that all devices and files exist and can be opened.
1538  * Note: we don't bother freeing anything in the error paths
1539  * because the program is just going to exit anyway.
1540  */
1541 static nvlist_t *
construct_spec(nvlist_t * props,int argc,char ** argv)1542 construct_spec(nvlist_t *props, int argc, char **argv)
1543 {
1544 	nvlist_t *nvroot, *nv, **top, **spares, **l2cache;
1545 	int t, toplevels, mindev, maxdev, nspares, nlogs, nl2cache;
1546 	const char *type, *fulltype;
1547 	boolean_t is_log, is_special, is_dedup, is_spare;
1548 	boolean_t seen_logs;
1549 	uint64_t ashift = 0;
1550 
1551 	if (props != NULL) {
1552 		const char *value = NULL;
1553 
1554 		if (nvlist_lookup_string(props,
1555 		    zpool_prop_to_name(ZPOOL_PROP_ASHIFT), &value) == 0) {
1556 			if (zfs_nicestrtonum(NULL, value, &ashift) != 0) {
1557 				(void) fprintf(stderr,
1558 				    gettext("ashift must be a number.\n"));
1559 				return (NULL);
1560 			}
1561 			if (ashift != 0 &&
1562 			    (ashift < ASHIFT_MIN || ashift > ASHIFT_MAX)) {
1563 				(void) fprintf(stderr,
1564 				    gettext("invalid 'ashift=%" PRIu64 "' "
1565 				    "property: only values between %" PRId32 " "
1566 				    "and %" PRId32 " are allowed.\n"),
1567 				    ashift, ASHIFT_MIN, ASHIFT_MAX);
1568 				return (NULL);
1569 			}
1570 		}
1571 	}
1572 
1573 	top = NULL;
1574 	toplevels = 0;
1575 	spares = NULL;
1576 	l2cache = NULL;
1577 	nspares = 0;
1578 	nlogs = 0;
1579 	nl2cache = 0;
1580 	is_log = is_special = is_dedup = is_spare = B_FALSE;
1581 	seen_logs = B_FALSE;
1582 	nvroot = NULL;
1583 
1584 	while (argc > 0) {
1585 		fulltype = argv[0];
1586 		nv = NULL;
1587 
1588 		/*
1589 		 * If it's a mirror, raidz, or draid the subsequent arguments
1590 		 * are its leaves -- until we encounter the next mirror,
1591 		 * raidz or draid.
1592 		 */
1593 		if ((type = is_grouping(fulltype, &mindev, &maxdev)) != NULL) {
1594 			nvlist_t **child = NULL;
1595 			int c, children = 0;
1596 
1597 			if (strcmp(type, VDEV_TYPE_SPARE) == 0) {
1598 				if (spares != NULL) {
1599 					(void) fprintf(stderr,
1600 					    gettext("invalid vdev "
1601 					    "specification: 'spare' can be "
1602 					    "specified only once\n"));
1603 					goto spec_out;
1604 				}
1605 				is_spare = B_TRUE;
1606 				is_log = is_special = is_dedup = B_FALSE;
1607 			}
1608 
1609 			if (strcmp(type, VDEV_TYPE_LOG) == 0) {
1610 				if (seen_logs) {
1611 					(void) fprintf(stderr,
1612 					    gettext("invalid vdev "
1613 					    "specification: 'log' can be "
1614 					    "specified only once\n"));
1615 					goto spec_out;
1616 				}
1617 				seen_logs = B_TRUE;
1618 				is_log = B_TRUE;
1619 				is_special = is_dedup = is_spare = B_FALSE;
1620 				argc--;
1621 				argv++;
1622 				/*
1623 				 * A log is not a real grouping device.
1624 				 * We just set is_log and continue.
1625 				 */
1626 				continue;
1627 			}
1628 
1629 			if (strcmp(type, VDEV_ALLOC_BIAS_SPECIAL) == 0) {
1630 				is_special = B_TRUE;
1631 				is_log = is_dedup = is_spare = B_FALSE;
1632 				argc--;
1633 				argv++;
1634 				continue;
1635 			}
1636 
1637 			if (strcmp(type, VDEV_ALLOC_BIAS_DEDUP) == 0) {
1638 				is_dedup = B_TRUE;
1639 				is_log = is_special = is_spare = B_FALSE;
1640 				argc--;
1641 				argv++;
1642 				continue;
1643 			}
1644 
1645 			if (strcmp(type, VDEV_TYPE_L2CACHE) == 0) {
1646 				if (l2cache != NULL) {
1647 					(void) fprintf(stderr,
1648 					    gettext("invalid vdev "
1649 					    "specification: 'cache' can be "
1650 					    "specified only once\n"));
1651 					goto spec_out;
1652 				}
1653 				is_log = is_special = B_FALSE;
1654 				is_dedup = is_spare = B_FALSE;
1655 			}
1656 
1657 			if (is_log) {
1658 				if (strcmp(type, VDEV_TYPE_MIRROR) != 0) {
1659 					(void) fprintf(stderr,
1660 					    gettext("invalid vdev "
1661 					    "specification: unsupported 'log' "
1662 					    "device: %s\n"), type);
1663 					goto spec_out;
1664 				}
1665 				nlogs++;
1666 			}
1667 
1668 			int nfdomain = 0, nfgroup = 0;
1669 			int fdndev = 0, fgndev = 0;
1670 			int fdndev_prev = 0, fgndev_prev = 0;
1671 
1672 			for (c = 1; c < argc; c++) {
1673 				if (is_grouping(argv[c], NULL, NULL) != NULL)
1674 					break;
1675 
1676 				if (strcmp(argv[c], "fgroup") == 0 ||
1677 				    strcmp(argv[c], "failure_group") == 0) {
1678 					if (fgndev_prev &&
1679 					    fgndev_prev != fgndev)
1680 						break;
1681 					fgndev_prev = fgndev;
1682 					fgndev = 0;
1683 					nfgroup++;
1684 					continue;
1685 				}
1686 
1687 				if (strcmp(argv[c], "fdomain") == 0 ||
1688 				    strcmp(argv[c], "failure_domain") == 0) {
1689 					if (fdndev_prev &&
1690 					    fdndev_prev != fdndev)
1691 						break;
1692 					fdndev_prev = fdndev;
1693 					fdndev = 0;
1694 					nfdomain++;
1695 					continue;
1696 				}
1697 
1698 				if (nfgroup)
1699 					fgndev++;
1700 				if (nfdomain)
1701 					fdndev++;
1702 
1703 				children++;
1704 				child = realloc(child,
1705 				    children * sizeof (nvlist_t *));
1706 				if (child == NULL)
1707 					zpool_no_memory();
1708 				if ((nv = make_leaf_vdev(argv[c],
1709 				    !(is_log || is_special || is_dedup ||
1710 				    is_spare), ashift)) == NULL) {
1711 					for (c = 0; c < children - 1; c++)
1712 						nvlist_free(child[c]);
1713 					free(child);
1714 					goto spec_out;
1715 				}
1716 
1717 				child[children - 1] = nv;
1718 			}
1719 
1720 			if (children < mindev) {
1721 				(void) fprintf(stderr, gettext("invalid vdev "
1722 				    "specification: %s requires at least %d "
1723 				    "devices\n"), argv[0], mindev);
1724 				for (c = 0; c < children; c++)
1725 					nvlist_free(child[c]);
1726 				free(child);
1727 				goto spec_out;
1728 			}
1729 
1730 			if (children > maxdev) {
1731 				(void) fprintf(stderr, gettext("invalid vdev "
1732 				    "specification: %s supports no more than "
1733 				    "%d devices\n"), argv[0], maxdev);
1734 				for (c = 0; c < children; c++)
1735 					nvlist_free(child[c]);
1736 				free(child);
1737 				goto spec_out;
1738 			}
1739 
1740 			if ((nfdomain || nfgroup) &&
1741 			    strcmp(type, VDEV_TYPE_DRAID) != 0) {
1742 				(void) fprintf(stderr, gettext("invalid vdev "
1743 				    "specification: %s is not dRAID and cannot "
1744 				    "have failure domains\n"), argv[0]);
1745 				for (c = 0; c < children; c++)
1746 					nvlist_free(child[c]);
1747 				free(child);
1748 				goto spec_out;
1749 			}
1750 
1751 			if (nfgroup && nfdomain) {
1752 				(void) fprintf(stderr, gettext("invalid vdev "
1753 				    "specification: %s has mixed configuration "
1754 				    "of %d failure groups and %d failure "
1755 				    "domains, it must have either fgroups or "
1756 				    "fdomains, not both\n"), argv[0],
1757 				    nfgroup, nfdomain);
1758 				for (c = 0; c < children; c++)
1759 					nvlist_free(child[c]);
1760 				free(child);
1761 				goto spec_out;
1762 			}
1763 
1764 			if (nfgroup == 1 || nfdomain == 1) {
1765 				(void) fprintf(stderr, gettext("invalid vdev "
1766 				    "specification: %s has only one failure %s "
1767 				    "configured, it must be more than one\n"),
1768 				    argv[0], nfgroup ? "group" : "domain");
1769 				for (c = 0; c < children; c++)
1770 					nvlist_free(child[c]);
1771 				free(child);
1772 				goto spec_out;
1773 			}
1774 
1775 			if (fgndev_prev != fgndev) {
1776 				(void) fprintf(stderr, gettext("invalid vdev "
1777 				    "specification: %s has different number of "
1778 				    "devices in failure group %d than in "
1779 				    "previous group: %d != %d\n"), argv[0],
1780 				    nfgroup, fgndev, fgndev_prev);
1781 				for (c = 0; c < children; c++)
1782 					nvlist_free(child[c]);
1783 				free(child);
1784 				goto spec_out;
1785 			}
1786 
1787 			if (fdndev_prev != fdndev) {
1788 				(void) fprintf(stderr, gettext("invalid vdev "
1789 				    "specification: %s has different number of "
1790 				    "devices in failure domain %d than in "
1791 				    "previous domain: %d != %d\n"), argv[0],
1792 				    nfdomain, fdndev, fdndev_prev);
1793 				for (c = 0; c < children; c++)
1794 					nvlist_free(child[c]);
1795 				free(child);
1796 				goto spec_out;
1797 			}
1798 
1799 			if (nfdomain) {
1800 				/* Put children in the right order */
1801 				nvlist_t **ch = NULL;
1802 				ch = realloc(ch,
1803 				    children * sizeof (nvlist_t *));
1804 				if (ch == NULL)
1805 					zpool_no_memory();
1806 				int dlen = children / nfdomain;
1807 				int i = 0;
1808 				for (int g = 0; g < dlen; g++)
1809 					for (int d = 0; d < nfdomain; d++)
1810 						ch[i++] = child[g + (d * dlen)];
1811 				free(child);
1812 				child = ch;
1813 			}
1814 
1815 			argc -= c;
1816 			argv += c;
1817 
1818 			if (strcmp(type, VDEV_TYPE_SPARE) == 0) {
1819 				spares = child;
1820 				nspares = children;
1821 				continue;
1822 			} else if (strcmp(type, VDEV_TYPE_L2CACHE) == 0) {
1823 				l2cache = child;
1824 				nl2cache = children;
1825 				continue;
1826 			} else {
1827 				/* create a top-level vdev with children */
1828 				verify(nvlist_alloc(&nv, NV_UNIQUE_NAME,
1829 				    0) == 0);
1830 				verify(nvlist_add_string(nv, ZPOOL_CONFIG_TYPE,
1831 				    type) == 0);
1832 				verify(nvlist_add_uint64(nv,
1833 				    ZPOOL_CONFIG_IS_LOG, is_log) == 0);
1834 				if (is_log) {
1835 					verify(nvlist_add_string(nv,
1836 					    ZPOOL_CONFIG_ALLOCATION_BIAS,
1837 					    VDEV_ALLOC_BIAS_LOG) == 0);
1838 				}
1839 				if (is_special) {
1840 					verify(nvlist_add_string(nv,
1841 					    ZPOOL_CONFIG_ALLOCATION_BIAS,
1842 					    VDEV_ALLOC_BIAS_SPECIAL) == 0);
1843 				}
1844 				if (is_dedup) {
1845 					verify(nvlist_add_string(nv,
1846 					    ZPOOL_CONFIG_ALLOCATION_BIAS,
1847 					    VDEV_ALLOC_BIAS_DEDUP) == 0);
1848 				}
1849 				if (ashift > 0) {
1850 					fnvlist_add_uint64(nv,
1851 					    ZPOOL_CONFIG_ASHIFT, ashift);
1852 				}
1853 				if (strcmp(type, VDEV_TYPE_RAIDZ) == 0) {
1854 					verify(nvlist_add_uint64(nv,
1855 					    ZPOOL_CONFIG_NPARITY,
1856 					    mindev - 1) == 0);
1857 				}
1858 				if (strcmp(type, VDEV_TYPE_DRAID) == 0) {
1859 					if (draid_config_by_type(nv,
1860 					    fulltype, children, nfgroup,
1861 					    nfdomain) != 0) {
1862 						for (c = 0; c < children; c++)
1863 							nvlist_free(child[c]);
1864 						free(child);
1865 						goto spec_out;
1866 					}
1867 				}
1868 				verify(nvlist_add_nvlist_array(nv,
1869 				    ZPOOL_CONFIG_CHILDREN,
1870 				    (const nvlist_t **)child, children) == 0);
1871 
1872 				for (c = 0; c < children; c++)
1873 					nvlist_free(child[c]);
1874 				free(child);
1875 			}
1876 		} else {
1877 			/*
1878 			 * We have a device.  Pass off to make_leaf_vdev() to
1879 			 * construct the appropriate nvlist describing the vdev.
1880 			 */
1881 			if ((nv = make_leaf_vdev(argv[0], !(is_log ||
1882 			    is_special || is_dedup || is_spare),
1883 			    ashift)) == NULL)
1884 				goto spec_out;
1885 
1886 			verify(nvlist_add_uint64(nv,
1887 			    ZPOOL_CONFIG_IS_LOG, is_log) == 0);
1888 			if (is_log) {
1889 				verify(nvlist_add_string(nv,
1890 				    ZPOOL_CONFIG_ALLOCATION_BIAS,
1891 				    VDEV_ALLOC_BIAS_LOG) == 0);
1892 				nlogs++;
1893 			}
1894 
1895 			if (is_special) {
1896 				verify(nvlist_add_string(nv,
1897 				    ZPOOL_CONFIG_ALLOCATION_BIAS,
1898 				    VDEV_ALLOC_BIAS_SPECIAL) == 0);
1899 			}
1900 			if (is_dedup) {
1901 				verify(nvlist_add_string(nv,
1902 				    ZPOOL_CONFIG_ALLOCATION_BIAS,
1903 				    VDEV_ALLOC_BIAS_DEDUP) == 0);
1904 			}
1905 			argc--;
1906 			argv++;
1907 		}
1908 
1909 		toplevels++;
1910 		top = realloc(top, toplevels * sizeof (nvlist_t *));
1911 		if (top == NULL)
1912 			zpool_no_memory();
1913 		top[toplevels - 1] = nv;
1914 	}
1915 
1916 	if (toplevels == 0 && nspares == 0 && nl2cache == 0) {
1917 		(void) fprintf(stderr, gettext("invalid vdev "
1918 		    "specification: at least one toplevel vdev must be "
1919 		    "specified\n"));
1920 		goto spec_out;
1921 	}
1922 
1923 	if (seen_logs && nlogs == 0) {
1924 		(void) fprintf(stderr, gettext("invalid vdev specification: "
1925 		    "log requires at least 1 device\n"));
1926 		goto spec_out;
1927 	}
1928 
1929 	/*
1930 	 * Finally, create nvroot and add all top-level vdevs to it.
1931 	 */
1932 	verify(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, 0) == 0);
1933 	verify(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
1934 	    VDEV_TYPE_ROOT) == 0);
1935 	verify(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
1936 	    (const nvlist_t **)top, toplevels) == 0);
1937 	if (nspares != 0)
1938 		verify(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1939 		    (const nvlist_t **)spares, nspares) == 0);
1940 	if (nl2cache != 0)
1941 		verify(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1942 		    (const nvlist_t **)l2cache, nl2cache) == 0);
1943 
1944 spec_out:
1945 	for (t = 0; t < toplevels; t++)
1946 		nvlist_free(top[t]);
1947 	for (t = 0; t < nspares; t++)
1948 		nvlist_free(spares[t]);
1949 	for (t = 0; t < nl2cache; t++)
1950 		nvlist_free(l2cache[t]);
1951 
1952 	free(spares);
1953 	free(l2cache);
1954 	free(top);
1955 
1956 	return (nvroot);
1957 }
1958 
1959 nvlist_t *
split_mirror_vdev(zpool_handle_t * zhp,char * newname,nvlist_t * props,splitflags_t flags,int argc,char ** argv)1960 split_mirror_vdev(zpool_handle_t *zhp, char *newname, nvlist_t *props,
1961     splitflags_t flags, int argc, char **argv)
1962 {
1963 	nvlist_t *newroot = NULL, **child;
1964 	uint_t c, children;
1965 
1966 	if (argc > 0) {
1967 		if ((newroot = construct_spec(props, argc, argv)) == NULL) {
1968 			(void) fprintf(stderr, gettext("Unable to build a "
1969 			    "pool from the specified devices\n"));
1970 			return (NULL);
1971 		}
1972 
1973 		if (!flags.dryrun && make_disks(zhp, newroot, B_FALSE) != 0) {
1974 			nvlist_free(newroot);
1975 			return (NULL);
1976 		}
1977 
1978 		/* avoid any tricks in the spec */
1979 		verify(nvlist_lookup_nvlist_array(newroot,
1980 		    ZPOOL_CONFIG_CHILDREN, &child, &children) == 0);
1981 		for (c = 0; c < children; c++) {
1982 			const char *path;
1983 			const char *type;
1984 			int min, max;
1985 
1986 			verify(nvlist_lookup_string(child[c],
1987 			    ZPOOL_CONFIG_PATH, &path) == 0);
1988 			if ((type = is_grouping(path, &min, &max)) != NULL) {
1989 				(void) fprintf(stderr, gettext("Cannot use "
1990 				    "'%s' as a device for splitting\n"), type);
1991 				nvlist_free(newroot);
1992 				return (NULL);
1993 			}
1994 		}
1995 	}
1996 
1997 	if (zpool_vdev_split(zhp, newname, &newroot, props, flags) != 0) {
1998 		nvlist_free(newroot);
1999 		return (NULL);
2000 	}
2001 
2002 	return (newroot);
2003 }
2004 
2005 static int
num_normal_vdevs(nvlist_t * nvroot)2006 num_normal_vdevs(nvlist_t *nvroot)
2007 {
2008 	nvlist_t **top;
2009 	uint_t t, toplevels, normal = 0;
2010 
2011 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
2012 	    &top, &toplevels) == 0);
2013 
2014 	for (t = 0; t < toplevels; t++) {
2015 		uint64_t log = B_FALSE;
2016 
2017 		(void) nvlist_lookup_uint64(top[t], ZPOOL_CONFIG_IS_LOG, &log);
2018 		if (log)
2019 			continue;
2020 		if (nvlist_exists(top[t], ZPOOL_CONFIG_ALLOCATION_BIAS))
2021 			continue;
2022 
2023 		normal++;
2024 	}
2025 
2026 	return (normal);
2027 }
2028 
2029 /*
2030  * Get and validate the contents of the given vdev specification.  This ensures
2031  * that the nvlist returned is well-formed, that all the devices exist, and that
2032  * they are not currently in use by any other known consumer.  The 'poolconfig'
2033  * parameter is the current configuration of the pool when adding devices
2034  * existing pool, and is used to perform additional checks, such as changing the
2035  * replication level of the pool.  It can be 'NULL' to indicate that this is a
2036  * new pool.  The 'force' flag controls whether devices should be forcefully
2037  * added, even if they appear in use.
2038  */
2039 nvlist_t *
make_root_vdev(zpool_handle_t * zhp,nvlist_t * props,int force,int check_rep,boolean_t replacing,boolean_t dryrun,int argc,char ** argv)2040 make_root_vdev(zpool_handle_t *zhp, nvlist_t *props, int force, int check_rep,
2041     boolean_t replacing, boolean_t dryrun, int argc, char **argv)
2042 {
2043 	nvlist_t *newroot;
2044 	nvlist_t *poolconfig = NULL;
2045 	is_force = force;
2046 
2047 	/*
2048 	 * Construct the vdev specification.  If this is successful, we know
2049 	 * that we have a valid specification, and that all devices can be
2050 	 * opened.
2051 	 */
2052 	if ((newroot = construct_spec(props, argc, argv)) == NULL)
2053 		return (NULL);
2054 
2055 	if (zhp && ((poolconfig = zpool_get_config(zhp, NULL)) == NULL)) {
2056 		nvlist_free(newroot);
2057 		return (NULL);
2058 	}
2059 
2060 	/*
2061 	 * Validate each device to make sure that it's not shared with another
2062 	 * subsystem.  We do this even if 'force' is set, because there are some
2063 	 * uses (such as a dedicated dump device) that even '-f' cannot
2064 	 * override.
2065 	 */
2066 	if (is_device_in_use(poolconfig, newroot, force, replacing, B_FALSE)) {
2067 		nvlist_free(newroot);
2068 		return (NULL);
2069 	}
2070 
2071 	/*
2072 	 * Check the replication level of the given vdevs and report any errors
2073 	 * found.  We include the existing pool spec, if any, as we need to
2074 	 * catch changes against the existing replication level.
2075 	 */
2076 	if (check_rep && check_replication(poolconfig, newroot) != 0) {
2077 		nvlist_free(newroot);
2078 		return (NULL);
2079 	}
2080 
2081 	/*
2082 	 * On pool create the new vdev spec must have one normal vdev.
2083 	 */
2084 	if (poolconfig == NULL && num_normal_vdevs(newroot) == 0) {
2085 		vdev_error(gettext("at least one general top-level vdev must "
2086 		    "be specified\n"));
2087 		nvlist_free(newroot);
2088 		return (NULL);
2089 	}
2090 
2091 	/*
2092 	 * Run through the vdev specification and label any whole disks found.
2093 	 */
2094 	if (!dryrun && make_disks(zhp, newroot, replacing) != 0) {
2095 		nvlist_free(newroot);
2096 		return (NULL);
2097 	}
2098 
2099 	return (newroot);
2100 }
2101