xref: /titanic_50/usr/src/cmd/zpool/zpool_vdev.c (revision 41efec2219526a9b3ecce26f97aba761ef1e1d0d)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * Functions to convert between a list of vdevs and an nvlist representing the
31  * configuration.  Each entry in the list can be one of:
32  *
33  * 	Device vdevs
34  * 		disk=(path=..., devid=...)
35  * 		file=(path=...)
36  *
37  * 	Group vdevs
38  * 		raidz[1|2]=(...)
39  * 		mirror=(...)
40  *
41  * 	Hot spares
42  *
43  * While the underlying implementation supports it, group vdevs cannot contain
44  * other group vdevs.  All userland verification of devices is contained within
45  * this file.  If successful, the nvlist returned can be passed directly to the
46  * kernel; we've done as much verification as possible in userland.
47  *
48  * Hot spares are a special case, and passed down as an array of disk vdevs, at
49  * the same level as the root of the vdev tree.
50  *
51  * The only function exported by this file is 'make_root_vdev'.  The
52  * function performs several passes:
53  *
54  * 	1. Construct the vdev specification.  Performs syntax validation and
55  *         makes sure each device is valid.
56  * 	2. Check for devices in use.  Using libdiskmgt, makes sure that no
57  *         devices are also in use.  Some can be overridden using the 'force'
58  *         flag, others cannot.
59  * 	3. Check for replication errors if the 'force' flag is not specified.
60  *         validates that the replication level is consistent across the
61  *         entire pool.
62  * 	4. Call libzfs to label any whole disks with an EFI label.
63  */
64 
65 #include <assert.h>
66 #include <devid.h>
67 #include <errno.h>
68 #include <fcntl.h>
69 #include <libdiskmgt.h>
70 #include <libintl.h>
71 #include <libnvpair.h>
72 #include <stdio.h>
73 #include <string.h>
74 #include <unistd.h>
75 #include <sys/efi_partition.h>
76 #include <sys/stat.h>
77 #include <sys/vtoc.h>
78 #include <sys/mntent.h>
79 
80 #include "zpool_util.h"
81 
82 #define	DISK_ROOT	"/dev/dsk"
83 #define	RDISK_ROOT	"/dev/rdsk"
84 #define	BACKUP_SLICE	"s2"
85 
86 /*
87  * For any given vdev specification, we can have multiple errors.  The
88  * vdev_error() function keeps track of whether we have seen an error yet, and
89  * prints out a header if its the first error we've seen.
90  */
91 boolean_t error_seen;
92 boolean_t is_force;
93 
94 /*PRINTFLIKE1*/
95 static void
96 vdev_error(const char *fmt, ...)
97 {
98 	va_list ap;
99 
100 	if (!error_seen) {
101 		(void) fprintf(stderr, gettext("invalid vdev specification\n"));
102 		if (!is_force)
103 			(void) fprintf(stderr, gettext("use '-f' to override "
104 			    "the following errors:\n"));
105 		else
106 			(void) fprintf(stderr, gettext("the following errors "
107 			    "must be manually repaired:\n"));
108 		error_seen = B_TRUE;
109 	}
110 
111 	va_start(ap, fmt);
112 	(void) vfprintf(stderr, fmt, ap);
113 	va_end(ap);
114 }
115 
116 static void
117 libdiskmgt_error(int error)
118 {
119 	/*
120 	 * ENXIO/ENODEV is a valid error message if the device doesn't live in
121 	 * /dev/dsk.  Don't bother printing an error message in this case.
122 	 */
123 	if (error == ENXIO || error == ENODEV)
124 		return;
125 
126 	(void) fprintf(stderr, gettext("warning: device in use checking "
127 	    "failed: %s\n"), strerror(error));
128 }
129 
130 /*
131  * Validate a device, passing the bulk of the work off to libdiskmgt.
132  */
133 static int
134 check_slice(const char *path, int force, boolean_t wholedisk, boolean_t isspare)
135 {
136 	char *msg;
137 	int error = 0;
138 
139 	if (dm_inuse((char *)path, &msg, isspare ? DM_WHO_ZPOOL_SPARE :
140 	    (force ? DM_WHO_ZPOOL_FORCE : DM_WHO_ZPOOL), &error) || error) {
141 		if (error != 0) {
142 			libdiskmgt_error(error);
143 			return (0);
144 		} else {
145 			vdev_error("%s", msg);
146 			free(msg);
147 			return (-1);
148 		}
149 	}
150 
151 	/*
152 	 * If we're given a whole disk, ignore overlapping slices since we're
153 	 * about to label it anyway.
154 	 */
155 	error = 0;
156 	if (!wholedisk && !force &&
157 	    (dm_isoverlapping((char *)path, &msg, &error) || error)) {
158 		if (error == 0) {
159 			/* dm_isoverlapping returned -1 */
160 			vdev_error(gettext("%s overlaps with %s\n"), path, msg);
161 			free(msg);
162 			return (-1);
163 		} else if (error != ENODEV) {
164 			/* libdiskmgt's devcache only handles physical drives */
165 			libdiskmgt_error(error);
166 			return (0);
167 		}
168 	}
169 
170 	return (0);
171 }
172 
173 
174 /*
175  * Validate a whole disk.  Iterate over all slices on the disk and make sure
176  * that none is in use by calling check_slice().
177  */
178 static int
179 check_disk(const char *name, dm_descriptor_t disk, int force, int isspare)
180 {
181 	dm_descriptor_t *drive, *media, *slice;
182 	int err = 0;
183 	int i;
184 	int ret;
185 
186 	/*
187 	 * Get the drive associated with this disk.  This should never fail,
188 	 * because we already have an alias handle open for the device.
189 	 */
190 	if ((drive = dm_get_associated_descriptors(disk, DM_DRIVE,
191 	    &err)) == NULL || *drive == NULL) {
192 		if (err)
193 			libdiskmgt_error(err);
194 		return (0);
195 	}
196 
197 	if ((media = dm_get_associated_descriptors(*drive, DM_MEDIA,
198 	    &err)) == NULL) {
199 		dm_free_descriptors(drive);
200 		if (err)
201 			libdiskmgt_error(err);
202 		return (0);
203 	}
204 
205 	dm_free_descriptors(drive);
206 
207 	/*
208 	 * It is possible that the user has specified a removable media drive,
209 	 * and the media is not present.
210 	 */
211 	if (*media == NULL) {
212 		dm_free_descriptors(media);
213 		vdev_error(gettext("'%s' has no media in drive\n"), name);
214 		return (-1);
215 	}
216 
217 	if ((slice = dm_get_associated_descriptors(*media, DM_SLICE,
218 	    &err)) == NULL) {
219 		dm_free_descriptors(media);
220 		if (err)
221 			libdiskmgt_error(err);
222 		return (0);
223 	}
224 
225 	dm_free_descriptors(media);
226 
227 	ret = 0;
228 
229 	/*
230 	 * Iterate over all slices and report any errors.  We don't care about
231 	 * overlapping slices because we are using the whole disk.
232 	 */
233 	for (i = 0; slice[i] != NULL; i++) {
234 		char *name = dm_get_name(slice[i], &err);
235 
236 		if (check_slice(name, force, B_TRUE, isspare) != 0)
237 			ret = -1;
238 
239 		dm_free_name(name);
240 	}
241 
242 	dm_free_descriptors(slice);
243 	return (ret);
244 }
245 
246 /*
247  * Validate a device.
248  */
249 static int
250 check_device(const char *path, boolean_t force, boolean_t isspare)
251 {
252 	dm_descriptor_t desc;
253 	int err;
254 	char *dev;
255 
256 	/*
257 	 * For whole disks, libdiskmgt does not include the leading dev path.
258 	 */
259 	dev = strrchr(path, '/');
260 	assert(dev != NULL);
261 	dev++;
262 	if ((desc = dm_get_descriptor_by_name(DM_ALIAS, dev, &err)) != NULL) {
263 		err = check_disk(path, desc, force, isspare);
264 		dm_free_descriptor(desc);
265 		return (err);
266 	}
267 
268 	return (check_slice(path, force, B_FALSE, isspare));
269 }
270 
271 /*
272  * Check that a file is valid.  All we can do in this case is check that it's
273  * not in use by another pool, and not in use by swap.
274  */
275 static int
276 check_file(const char *file, boolean_t force, boolean_t isspare)
277 {
278 	char  *name;
279 	int fd;
280 	int ret = 0;
281 	int err;
282 	pool_state_t state;
283 	boolean_t inuse;
284 
285 	if (dm_inuse_swap(file, &err)) {
286 		if (err)
287 			libdiskmgt_error(err);
288 		else
289 			vdev_error(gettext("%s is currently used by swap. "
290 			    "Please see swap(1M).\n"), file);
291 		return (-1);
292 	}
293 
294 	if ((fd = open(file, O_RDONLY)) < 0)
295 		return (0);
296 
297 	if (zpool_in_use(g_zfs, fd, &state, &name, &inuse) == 0 && inuse) {
298 		const char *desc;
299 
300 		switch (state) {
301 		case POOL_STATE_ACTIVE:
302 			desc = gettext("active");
303 			break;
304 
305 		case POOL_STATE_EXPORTED:
306 			desc = gettext("exported");
307 			break;
308 
309 		case POOL_STATE_POTENTIALLY_ACTIVE:
310 			desc = gettext("potentially active");
311 			break;
312 
313 		default:
314 			desc = gettext("unknown");
315 			break;
316 		}
317 
318 		/*
319 		 * Allow hot spares to be shared between pools.
320 		 */
321 		if (state == POOL_STATE_SPARE && isspare)
322 			return (0);
323 
324 		if (state == POOL_STATE_ACTIVE ||
325 		    state == POOL_STATE_SPARE || !force) {
326 			switch (state) {
327 			case POOL_STATE_SPARE:
328 				vdev_error(gettext("%s is reserved as a hot "
329 				    "spare for pool %s\n"), file, name);
330 				break;
331 			default:
332 				vdev_error(gettext("%s is part of %s pool "
333 				    "'%s'\n"), file, desc, name);
334 				break;
335 			}
336 			ret = -1;
337 		}
338 
339 		free(name);
340 	}
341 
342 	(void) close(fd);
343 	return (ret);
344 }
345 
346 
347 /*
348  * By "whole disk" we mean an entire physical disk (something we can
349  * label, toggle the write cache on, etc.) as opposed to the full
350  * capacity of a pseudo-device such as lofi or did.  We act as if we
351  * are labeling the disk, which should be a pretty good test of whether
352  * it's a viable device or not.  Returns B_TRUE if it is and B_FALSE if
353  * it isn't.
354  */
355 static boolean_t
356 is_whole_disk(const char *arg)
357 {
358 	struct dk_gpt *label;
359 	int	fd;
360 	char	path[MAXPATHLEN];
361 
362 	(void) snprintf(path, sizeof (path), "%s%s%s",
363 	    RDISK_ROOT, strrchr(arg, '/'), BACKUP_SLICE);
364 	if ((fd = open(path, O_RDWR | O_NDELAY)) < 0)
365 		return (B_FALSE);
366 	if (efi_alloc_and_init(fd, EFI_NUMPAR, &label) != 0) {
367 		(void) close(fd);
368 		return (B_FALSE);
369 	}
370 	efi_free(label);
371 	(void) close(fd);
372 	return (B_TRUE);
373 }
374 
375 /*
376  * Create a leaf vdev.  Determine if this is a file or a device.  If it's a
377  * device, fill in the device id to make a complete nvlist.  Valid forms for a
378  * leaf vdev are:
379  *
380  * 	/dev/dsk/xxx	Complete disk path
381  * 	/xxx		Full path to file
382  * 	xxx		Shorthand for /dev/dsk/xxx
383  */
384 static nvlist_t *
385 make_leaf_vdev(const char *arg, uint64_t is_log)
386 {
387 	char path[MAXPATHLEN];
388 	struct stat64 statbuf;
389 	nvlist_t *vdev = NULL;
390 	char *type = NULL;
391 	boolean_t wholedisk = B_FALSE;
392 
393 	/*
394 	 * Determine what type of vdev this is, and put the full path into
395 	 * 'path'.  We detect whether this is a device of file afterwards by
396 	 * checking the st_mode of the file.
397 	 */
398 	if (arg[0] == '/') {
399 		/*
400 		 * Complete device or file path.  Exact type is determined by
401 		 * examining the file descriptor afterwards.
402 		 */
403 		wholedisk = is_whole_disk(arg);
404 		if (!wholedisk && (stat64(arg, &statbuf) != 0)) {
405 			(void) fprintf(stderr,
406 			    gettext("cannot open '%s': %s\n"),
407 			    arg, strerror(errno));
408 			return (NULL);
409 		}
410 
411 		(void) strlcpy(path, arg, sizeof (path));
412 	} else {
413 		/*
414 		 * This may be a short path for a device, or it could be total
415 		 * gibberish.  Check to see if it's a known device in
416 		 * /dev/dsk/.  As part of this check, see if we've been given a
417 		 * an entire disk (minus the slice number).
418 		 */
419 		(void) snprintf(path, sizeof (path), "%s/%s", DISK_ROOT,
420 		    arg);
421 		wholedisk = is_whole_disk(path);
422 		if (!wholedisk && (stat64(path, &statbuf) != 0)) {
423 			/*
424 			 * If we got ENOENT, then the user gave us
425 			 * gibberish, so try to direct them with a
426 			 * reasonable error message.  Otherwise,
427 			 * regurgitate strerror() since it's the best we
428 			 * can do.
429 			 */
430 			if (errno == ENOENT) {
431 				(void) fprintf(stderr,
432 				    gettext("cannot open '%s': no such "
433 				    "device in %s\n"), arg, DISK_ROOT);
434 				(void) fprintf(stderr,
435 				    gettext("must be a full path or "
436 				    "shorthand device name\n"));
437 				return (NULL);
438 			} else {
439 				(void) fprintf(stderr,
440 				    gettext("cannot open '%s': %s\n"),
441 				    path, strerror(errno));
442 				return (NULL);
443 			}
444 		}
445 	}
446 
447 	/*
448 	 * Determine whether this is a device or a file.
449 	 */
450 	if (wholedisk || S_ISBLK(statbuf.st_mode)) {
451 		type = VDEV_TYPE_DISK;
452 	} else if (S_ISREG(statbuf.st_mode)) {
453 		type = VDEV_TYPE_FILE;
454 	} else {
455 		(void) fprintf(stderr, gettext("cannot use '%s': must be a "
456 		    "block device or regular file\n"), path);
457 		return (NULL);
458 	}
459 
460 	/*
461 	 * Finally, we have the complete device or file, and we know that it is
462 	 * acceptable to use.  Construct the nvlist to describe this vdev.  All
463 	 * vdevs have a 'path' element, and devices also have a 'devid' element.
464 	 */
465 	verify(nvlist_alloc(&vdev, NV_UNIQUE_NAME, 0) == 0);
466 	verify(nvlist_add_string(vdev, ZPOOL_CONFIG_PATH, path) == 0);
467 	verify(nvlist_add_string(vdev, ZPOOL_CONFIG_TYPE, type) == 0);
468 	verify(nvlist_add_uint64(vdev, ZPOOL_CONFIG_IS_LOG, is_log) == 0);
469 	if (strcmp(type, VDEV_TYPE_DISK) == 0)
470 		verify(nvlist_add_uint64(vdev, ZPOOL_CONFIG_WHOLE_DISK,
471 		    (uint64_t)wholedisk) == 0);
472 
473 	/*
474 	 * For a whole disk, defer getting its devid until after labeling it.
475 	 */
476 	if (S_ISBLK(statbuf.st_mode) && !wholedisk) {
477 		/*
478 		 * Get the devid for the device.
479 		 */
480 		int fd;
481 		ddi_devid_t devid;
482 		char *minor = NULL, *devid_str = NULL;
483 
484 		if ((fd = open(path, O_RDONLY)) < 0) {
485 			(void) fprintf(stderr, gettext("cannot open '%s': "
486 			    "%s\n"), path, strerror(errno));
487 			nvlist_free(vdev);
488 			return (NULL);
489 		}
490 
491 		if (devid_get(fd, &devid) == 0) {
492 			if (devid_get_minor_name(fd, &minor) == 0 &&
493 			    (devid_str = devid_str_encode(devid, minor)) !=
494 			    NULL) {
495 				verify(nvlist_add_string(vdev,
496 				    ZPOOL_CONFIG_DEVID, devid_str) == 0);
497 			}
498 			if (devid_str != NULL)
499 				devid_str_free(devid_str);
500 			if (minor != NULL)
501 				devid_str_free(minor);
502 			devid_free(devid);
503 		}
504 
505 		(void) close(fd);
506 	}
507 
508 	return (vdev);
509 }
510 
511 /*
512  * Go through and verify the replication level of the pool is consistent.
513  * Performs the following checks:
514  *
515  * 	For the new spec, verifies that devices in mirrors and raidz are the
516  * 	same size.
517  *
518  * 	If the current configuration already has inconsistent replication
519  * 	levels, ignore any other potential problems in the new spec.
520  *
521  * 	Otherwise, make sure that the current spec (if there is one) and the new
522  * 	spec have consistent replication levels.
523  */
524 typedef struct replication_level {
525 	char *zprl_type;
526 	uint64_t zprl_children;
527 	uint64_t zprl_parity;
528 } replication_level_t;
529 
530 #define	ZPOOL_FUZZ	(16 * 1024 * 1024)
531 
532 /*
533  * Given a list of toplevel vdevs, return the current replication level.  If
534  * the config is inconsistent, then NULL is returned.  If 'fatal' is set, then
535  * an error message will be displayed for each self-inconsistent vdev.
536  */
537 static replication_level_t *
538 get_replication(nvlist_t *nvroot, boolean_t fatal)
539 {
540 	nvlist_t **top;
541 	uint_t t, toplevels;
542 	nvlist_t **child;
543 	uint_t c, children;
544 	nvlist_t *nv;
545 	char *type;
546 	replication_level_t lastrep, rep, *ret;
547 	boolean_t dontreport;
548 
549 	ret = safe_malloc(sizeof (replication_level_t));
550 
551 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
552 	    &top, &toplevels) == 0);
553 
554 	lastrep.zprl_type = NULL;
555 	for (t = 0; t < toplevels; t++) {
556 		uint64_t is_log = B_FALSE;
557 
558 		nv = top[t];
559 
560 		/*
561 		 * For separate logs we ignore the top level vdev replication
562 		 * constraints.
563 		 */
564 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG, &is_log);
565 		if (is_log)
566 			continue;
567 
568 		verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE,
569 		    &type) == 0);
570 		if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
571 		    &child, &children) != 0) {
572 			/*
573 			 * This is a 'file' or 'disk' vdev.
574 			 */
575 			rep.zprl_type = type;
576 			rep.zprl_children = 1;
577 			rep.zprl_parity = 0;
578 		} else {
579 			uint64_t vdev_size;
580 
581 			/*
582 			 * This is a mirror or RAID-Z vdev.  Go through and make
583 			 * sure the contents are all the same (files vs. disks),
584 			 * keeping track of the number of elements in the
585 			 * process.
586 			 *
587 			 * We also check that the size of each vdev (if it can
588 			 * be determined) is the same.
589 			 */
590 			rep.zprl_type = type;
591 			rep.zprl_children = 0;
592 
593 			if (strcmp(type, VDEV_TYPE_RAIDZ) == 0) {
594 				verify(nvlist_lookup_uint64(nv,
595 				    ZPOOL_CONFIG_NPARITY,
596 				    &rep.zprl_parity) == 0);
597 				assert(rep.zprl_parity != 0);
598 			} else {
599 				rep.zprl_parity = 0;
600 			}
601 
602 			/*
603 			 * The 'dontreport' variable indicates that we've
604 			 * already reported an error for this spec, so don't
605 			 * bother doing it again.
606 			 */
607 			type = NULL;
608 			dontreport = 0;
609 			vdev_size = -1ULL;
610 			for (c = 0; c < children; c++) {
611 				nvlist_t *cnv = child[c];
612 				char *path;
613 				struct stat64 statbuf;
614 				uint64_t size = -1ULL;
615 				char *childtype;
616 				int fd, err;
617 
618 				rep.zprl_children++;
619 
620 				verify(nvlist_lookup_string(cnv,
621 				    ZPOOL_CONFIG_TYPE, &childtype) == 0);
622 
623 				/*
624 				 * If this is a replacing or spare vdev, then
625 				 * get the real first child of the vdev.
626 				 */
627 				if (strcmp(childtype,
628 				    VDEV_TYPE_REPLACING) == 0 ||
629 				    strcmp(childtype, VDEV_TYPE_SPARE) == 0) {
630 					nvlist_t **rchild;
631 					uint_t rchildren;
632 
633 					verify(nvlist_lookup_nvlist_array(cnv,
634 					    ZPOOL_CONFIG_CHILDREN, &rchild,
635 					    &rchildren) == 0);
636 					assert(rchildren == 2);
637 					cnv = rchild[0];
638 
639 					verify(nvlist_lookup_string(cnv,
640 					    ZPOOL_CONFIG_TYPE,
641 					    &childtype) == 0);
642 				}
643 
644 				verify(nvlist_lookup_string(cnv,
645 				    ZPOOL_CONFIG_PATH, &path) == 0);
646 
647 				/*
648 				 * If we have a raidz/mirror that combines disks
649 				 * with files, report it as an error.
650 				 */
651 				if (!dontreport && type != NULL &&
652 				    strcmp(type, childtype) != 0) {
653 					if (ret != NULL)
654 						free(ret);
655 					ret = NULL;
656 					if (fatal)
657 						vdev_error(gettext(
658 						    "mismatched replication "
659 						    "level: %s contains both "
660 						    "files and devices\n"),
661 						    rep.zprl_type);
662 					else
663 						return (NULL);
664 					dontreport = B_TRUE;
665 				}
666 
667 				/*
668 				 * According to stat(2), the value of 'st_size'
669 				 * is undefined for block devices and character
670 				 * devices.  But there is no effective way to
671 				 * determine the real size in userland.
672 				 *
673 				 * Instead, we'll take advantage of an
674 				 * implementation detail of spec_size().  If the
675 				 * device is currently open, then we (should)
676 				 * return a valid size.
677 				 *
678 				 * If we still don't get a valid size (indicated
679 				 * by a size of 0 or MAXOFFSET_T), then ignore
680 				 * this device altogether.
681 				 */
682 				if ((fd = open(path, O_RDONLY)) >= 0) {
683 					err = fstat64(fd, &statbuf);
684 					(void) close(fd);
685 				} else {
686 					err = stat64(path, &statbuf);
687 				}
688 
689 				if (err != 0 ||
690 				    statbuf.st_size == 0 ||
691 				    statbuf.st_size == MAXOFFSET_T)
692 					continue;
693 
694 				size = statbuf.st_size;
695 
696 				/*
697 				 * Also make sure that devices and
698 				 * slices have a consistent size.  If
699 				 * they differ by a significant amount
700 				 * (~16MB) then report an error.
701 				 */
702 				if (!dontreport &&
703 				    (vdev_size != -1ULL &&
704 				    (labs(size - vdev_size) >
705 				    ZPOOL_FUZZ))) {
706 					if (ret != NULL)
707 						free(ret);
708 					ret = NULL;
709 					if (fatal)
710 						vdev_error(gettext(
711 						    "%s contains devices of "
712 						    "different sizes\n"),
713 						    rep.zprl_type);
714 					else
715 						return (NULL);
716 					dontreport = B_TRUE;
717 				}
718 
719 				type = childtype;
720 				vdev_size = size;
721 			}
722 		}
723 
724 		/*
725 		 * At this point, we have the replication of the last toplevel
726 		 * vdev in 'rep'.  Compare it to 'lastrep' to see if its
727 		 * different.
728 		 */
729 		if (lastrep.zprl_type != NULL) {
730 			if (strcmp(lastrep.zprl_type, rep.zprl_type) != 0) {
731 				if (ret != NULL)
732 					free(ret);
733 				ret = NULL;
734 				if (fatal)
735 					vdev_error(gettext(
736 					    "mismatched replication level: "
737 					    "both %s and %s vdevs are "
738 					    "present\n"),
739 					    lastrep.zprl_type, rep.zprl_type);
740 				else
741 					return (NULL);
742 			} else if (lastrep.zprl_parity != rep.zprl_parity) {
743 				if (ret)
744 					free(ret);
745 				ret = NULL;
746 				if (fatal)
747 					vdev_error(gettext(
748 					    "mismatched replication level: "
749 					    "both %llu and %llu device parity "
750 					    "%s vdevs are present\n"),
751 					    lastrep.zprl_parity,
752 					    rep.zprl_parity,
753 					    rep.zprl_type);
754 				else
755 					return (NULL);
756 			} else if (lastrep.zprl_children != rep.zprl_children) {
757 				if (ret)
758 					free(ret);
759 				ret = NULL;
760 				if (fatal)
761 					vdev_error(gettext(
762 					    "mismatched replication level: "
763 					    "both %llu-way and %llu-way %s "
764 					    "vdevs are present\n"),
765 					    lastrep.zprl_children,
766 					    rep.zprl_children,
767 					    rep.zprl_type);
768 				else
769 					return (NULL);
770 			}
771 		}
772 		lastrep = rep;
773 	}
774 
775 	if (ret != NULL)
776 		*ret = rep;
777 
778 	return (ret);
779 }
780 
781 /*
782  * Check the replication level of the vdev spec against the current pool.  Calls
783  * get_replication() to make sure the new spec is self-consistent.  If the pool
784  * has a consistent replication level, then we ignore any errors.  Otherwise,
785  * report any difference between the two.
786  */
787 static int
788 check_replication(nvlist_t *config, nvlist_t *newroot)
789 {
790 	nvlist_t **child;
791 	uint_t	children;
792 	replication_level_t *current = NULL, *new;
793 	int ret;
794 
795 	/*
796 	 * If we have a current pool configuration, check to see if it's
797 	 * self-consistent.  If not, simply return success.
798 	 */
799 	if (config != NULL) {
800 		nvlist_t *nvroot;
801 
802 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
803 		    &nvroot) == 0);
804 		if ((current = get_replication(nvroot, B_FALSE)) == NULL)
805 			return (0);
806 	}
807 	/*
808 	 * for spares there may be no children, and therefore no
809 	 * replication level to check
810 	 */
811 	if ((nvlist_lookup_nvlist_array(newroot, ZPOOL_CONFIG_CHILDREN,
812 	    &child, &children) != 0) || (children == 0)) {
813 		free(current);
814 		return (0);
815 	}
816 
817 	/*
818 	 * If all we have is logs then there's no replication level to check.
819 	 */
820 	if (num_logs(newroot) == children) {
821 		free(current);
822 		return (0);
823 	}
824 
825 	/*
826 	 * Get the replication level of the new vdev spec, reporting any
827 	 * inconsistencies found.
828 	 */
829 	if ((new = get_replication(newroot, B_TRUE)) == NULL) {
830 		free(current);
831 		return (-1);
832 	}
833 
834 	/*
835 	 * Check to see if the new vdev spec matches the replication level of
836 	 * the current pool.
837 	 */
838 	ret = 0;
839 	if (current != NULL) {
840 		if (strcmp(current->zprl_type, new->zprl_type) != 0) {
841 			vdev_error(gettext(
842 			    "mismatched replication level: pool uses %s "
843 			    "and new vdev is %s\n"),
844 			    current->zprl_type, new->zprl_type);
845 			ret = -1;
846 		} else if (current->zprl_parity != new->zprl_parity) {
847 			vdev_error(gettext(
848 			    "mismatched replication level: pool uses %llu "
849 			    "device parity and new vdev uses %llu\n"),
850 			    current->zprl_parity, new->zprl_parity);
851 			ret = -1;
852 		} else if (current->zprl_children != new->zprl_children) {
853 			vdev_error(gettext(
854 			    "mismatched replication level: pool uses %llu-way "
855 			    "%s and new vdev uses %llu-way %s\n"),
856 			    current->zprl_children, current->zprl_type,
857 			    new->zprl_children, new->zprl_type);
858 			ret = -1;
859 		}
860 	}
861 
862 	free(new);
863 	if (current != NULL)
864 		free(current);
865 
866 	return (ret);
867 }
868 
869 /*
870  * Go through and find any whole disks in the vdev specification, labelling them
871  * as appropriate.  When constructing the vdev spec, we were unable to open this
872  * device in order to provide a devid.  Now that we have labelled the disk and
873  * know that slice 0 is valid, we can construct the devid now.
874  *
875  * If the disk was already labeled with an EFI label, we will have gotten the
876  * devid already (because we were able to open the whole disk).  Otherwise, we
877  * need to get the devid after we label the disk.
878  */
879 static int
880 make_disks(zpool_handle_t *zhp, nvlist_t *nv)
881 {
882 	nvlist_t **child;
883 	uint_t c, children;
884 	char *type, *path, *diskname;
885 	char buf[MAXPATHLEN];
886 	uint64_t wholedisk;
887 	int fd;
888 	int ret;
889 	ddi_devid_t devid;
890 	char *minor = NULL, *devid_str = NULL;
891 
892 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
893 
894 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
895 	    &child, &children) != 0) {
896 
897 		if (strcmp(type, VDEV_TYPE_DISK) != 0)
898 			return (0);
899 
900 		/*
901 		 * We have a disk device.  Get the path to the device
902 		 * and see if it's a whole disk by appending the backup
903 		 * slice and stat()ing the device.
904 		 */
905 		verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
906 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
907 		    &wholedisk) != 0 || !wholedisk)
908 			return (0);
909 
910 		diskname = strrchr(path, '/');
911 		assert(diskname != NULL);
912 		diskname++;
913 		if (zpool_label_disk(g_zfs, zhp, diskname) == -1)
914 			return (-1);
915 
916 		/*
917 		 * Fill in the devid, now that we've labeled the disk.
918 		 */
919 		(void) snprintf(buf, sizeof (buf), "%ss0", path);
920 		if ((fd = open(buf, O_RDONLY)) < 0) {
921 			(void) fprintf(stderr,
922 			    gettext("cannot open '%s': %s\n"),
923 			    buf, strerror(errno));
924 			return (-1);
925 		}
926 
927 		if (devid_get(fd, &devid) == 0) {
928 			if (devid_get_minor_name(fd, &minor) == 0 &&
929 			    (devid_str = devid_str_encode(devid, minor)) !=
930 			    NULL) {
931 				verify(nvlist_add_string(nv,
932 				    ZPOOL_CONFIG_DEVID, devid_str) == 0);
933 			}
934 			if (devid_str != NULL)
935 				devid_str_free(devid_str);
936 			if (minor != NULL)
937 				devid_str_free(minor);
938 			devid_free(devid);
939 		}
940 
941 		/*
942 		 * Update the path to refer to the 's0' slice.  The presence of
943 		 * the 'whole_disk' field indicates to the CLI that we should
944 		 * chop off the slice number when displaying the device in
945 		 * future output.
946 		 */
947 		verify(nvlist_add_string(nv, ZPOOL_CONFIG_PATH, buf) == 0);
948 
949 		(void) close(fd);
950 
951 		return (0);
952 	}
953 
954 	for (c = 0; c < children; c++)
955 		if ((ret = make_disks(zhp, child[c])) != 0)
956 			return (ret);
957 
958 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
959 	    &child, &children) == 0)
960 		for (c = 0; c < children; c++)
961 			if ((ret = make_disks(zhp, child[c])) != 0)
962 				return (ret);
963 
964 	return (0);
965 }
966 
967 /*
968  * Determine if the given path is a hot spare within the given configuration.
969  */
970 static boolean_t
971 is_spare(nvlist_t *config, const char *path)
972 {
973 	int fd;
974 	pool_state_t state;
975 	char *name = NULL;
976 	nvlist_t *label;
977 	uint64_t guid, spareguid;
978 	nvlist_t *nvroot;
979 	nvlist_t **spares;
980 	uint_t i, nspares;
981 	boolean_t inuse;
982 
983 	if ((fd = open(path, O_RDONLY)) < 0)
984 		return (B_FALSE);
985 
986 	if (zpool_in_use(g_zfs, fd, &state, &name, &inuse) != 0 ||
987 	    !inuse ||
988 	    state != POOL_STATE_SPARE ||
989 	    zpool_read_label(fd, &label) != 0) {
990 		free(name);
991 		(void) close(fd);
992 		return (B_FALSE);
993 	}
994 	free(name);
995 
996 	(void) close(fd);
997 	verify(nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) == 0);
998 	nvlist_free(label);
999 
1000 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1001 	    &nvroot) == 0);
1002 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1003 	    &spares, &nspares) == 0) {
1004 		for (i = 0; i < nspares; i++) {
1005 			verify(nvlist_lookup_uint64(spares[i],
1006 			    ZPOOL_CONFIG_GUID, &spareguid) == 0);
1007 			if (spareguid == guid)
1008 				return (B_TRUE);
1009 		}
1010 	}
1011 
1012 	return (B_FALSE);
1013 }
1014 
1015 /*
1016  * Go through and find any devices that are in use.  We rely on libdiskmgt for
1017  * the majority of this task.
1018  */
1019 static int
1020 check_in_use(nvlist_t *config, nvlist_t *nv, int force, int isreplacing,
1021     int isspare)
1022 {
1023 	nvlist_t **child;
1024 	uint_t c, children;
1025 	char *type, *path;
1026 	int ret;
1027 	char buf[MAXPATHLEN];
1028 	uint64_t wholedisk;
1029 
1030 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
1031 
1032 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1033 	    &child, &children) != 0) {
1034 
1035 		verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
1036 
1037 		/*
1038 		 * As a generic check, we look to see if this is a replace of a
1039 		 * hot spare within the same pool.  If so, we allow it
1040 		 * regardless of what libdiskmgt or zpool_in_use() says.
1041 		 */
1042 		if (isreplacing) {
1043 			if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
1044 			    &wholedisk) == 0 && wholedisk)
1045 				(void) snprintf(buf, sizeof (buf), "%ss0",
1046 				    path);
1047 			else
1048 				(void) strlcpy(buf, path, sizeof (buf));
1049 			if (is_spare(config, buf))
1050 				return (0);
1051 		}
1052 
1053 		if (strcmp(type, VDEV_TYPE_DISK) == 0)
1054 			ret = check_device(path, force, isspare);
1055 
1056 		if (strcmp(type, VDEV_TYPE_FILE) == 0)
1057 			ret = check_file(path, force, isspare);
1058 
1059 		return (ret);
1060 	}
1061 
1062 	for (c = 0; c < children; c++)
1063 		if ((ret = check_in_use(config, child[c], force,
1064 		    isreplacing, B_FALSE)) != 0)
1065 			return (ret);
1066 
1067 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1068 	    &child, &children) == 0)
1069 		for (c = 0; c < children; c++)
1070 			if ((ret = check_in_use(config, child[c], force,
1071 			    isreplacing, B_TRUE)) != 0)
1072 				return (ret);
1073 	return (0);
1074 }
1075 
1076 static const char *
1077 is_grouping(const char *type, int *mindev)
1078 {
1079 	if (strcmp(type, "raidz") == 0 || strcmp(type, "raidz1") == 0) {
1080 		if (mindev != NULL)
1081 			*mindev = 2;
1082 		return (VDEV_TYPE_RAIDZ);
1083 	}
1084 
1085 	if (strcmp(type, "raidz2") == 0) {
1086 		if (mindev != NULL)
1087 			*mindev = 3;
1088 		return (VDEV_TYPE_RAIDZ);
1089 	}
1090 
1091 	if (strcmp(type, "mirror") == 0) {
1092 		if (mindev != NULL)
1093 			*mindev = 2;
1094 		return (VDEV_TYPE_MIRROR);
1095 	}
1096 
1097 	if (strcmp(type, "spare") == 0) {
1098 		if (mindev != NULL)
1099 			*mindev = 1;
1100 		return (VDEV_TYPE_SPARE);
1101 	}
1102 
1103 	if (strcmp(type, "log") == 0) {
1104 		if (mindev != NULL)
1105 			*mindev = 1;
1106 		return (VDEV_TYPE_LOG);
1107 	}
1108 
1109 	return (NULL);
1110 }
1111 
1112 /*
1113  * Construct a syntactically valid vdev specification,
1114  * and ensure that all devices and files exist and can be opened.
1115  * Note: we don't bother freeing anything in the error paths
1116  * because the program is just going to exit anyway.
1117  */
1118 nvlist_t *
1119 construct_spec(int argc, char **argv)
1120 {
1121 	nvlist_t *nvroot, *nv, **top, **spares;
1122 	int t, toplevels, mindev, nspares, nlogs;
1123 	const char *type;
1124 	uint64_t is_log;
1125 	boolean_t seen_logs;
1126 
1127 	top = NULL;
1128 	toplevels = 0;
1129 	spares = NULL;
1130 	nspares = 0;
1131 	nlogs = 0;
1132 	is_log = B_FALSE;
1133 	seen_logs = B_FALSE;
1134 
1135 	while (argc > 0) {
1136 		nv = NULL;
1137 
1138 		/*
1139 		 * If it's a mirror or raidz, the subsequent arguments are
1140 		 * its leaves -- until we encounter the next mirror or raidz.
1141 		 */
1142 		if ((type = is_grouping(argv[0], &mindev)) != NULL) {
1143 			nvlist_t **child = NULL;
1144 			int c, children = 0;
1145 
1146 			if (strcmp(type, VDEV_TYPE_SPARE) == 0) {
1147 				if (spares != NULL) {
1148 					(void) fprintf(stderr,
1149 					    gettext("invalid vdev "
1150 					    "specification: 'spare' can be "
1151 					    "specified only once\n"));
1152 					return (NULL);
1153 				}
1154 				is_log = B_FALSE;
1155 			}
1156 
1157 			if (strcmp(type, VDEV_TYPE_LOG) == 0) {
1158 				if (seen_logs) {
1159 					(void) fprintf(stderr,
1160 					    gettext("invalid vdev "
1161 					    "specification: 'log' can be "
1162 					    "specified only once\n"));
1163 					return (NULL);
1164 				}
1165 				seen_logs = B_TRUE;
1166 				is_log = B_TRUE;
1167 				argc--;
1168 				argv++;
1169 				/*
1170 				 * A log is not a real grouping device.
1171 				 * We just set is_log and continue.
1172 				 */
1173 				continue;
1174 			}
1175 
1176 			if (is_log) {
1177 				if (strcmp(type, VDEV_TYPE_MIRROR) != 0) {
1178 					(void) fprintf(stderr,
1179 					    gettext("invalid vdev "
1180 					    "specification: unsupported 'log' "
1181 					    "device: %s\n"), type);
1182 					return (NULL);
1183 				}
1184 				nlogs++;
1185 			}
1186 
1187 			for (c = 1; c < argc; c++) {
1188 				if (is_grouping(argv[c], NULL) != NULL)
1189 					break;
1190 				children++;
1191 				child = realloc(child,
1192 				    children * sizeof (nvlist_t *));
1193 				if (child == NULL)
1194 					zpool_no_memory();
1195 				if ((nv = make_leaf_vdev(argv[c], B_FALSE))
1196 				    == NULL)
1197 					return (NULL);
1198 				child[children - 1] = nv;
1199 			}
1200 
1201 			if (children < mindev) {
1202 				(void) fprintf(stderr, gettext("invalid vdev "
1203 				    "specification: %s requires at least %d "
1204 				    "devices\n"), argv[0], mindev);
1205 				return (NULL);
1206 			}
1207 
1208 			argc -= c;
1209 			argv += c;
1210 
1211 			if (strcmp(type, VDEV_TYPE_SPARE) == 0) {
1212 				spares = child;
1213 				nspares = children;
1214 				continue;
1215 			} else {
1216 				verify(nvlist_alloc(&nv, NV_UNIQUE_NAME,
1217 				    0) == 0);
1218 				verify(nvlist_add_string(nv, ZPOOL_CONFIG_TYPE,
1219 				    type) == 0);
1220 				verify(nvlist_add_uint64(nv,
1221 				    ZPOOL_CONFIG_IS_LOG, is_log) == 0);
1222 				if (strcmp(type, VDEV_TYPE_RAIDZ) == 0) {
1223 					verify(nvlist_add_uint64(nv,
1224 					    ZPOOL_CONFIG_NPARITY,
1225 					    mindev - 1) == 0);
1226 				}
1227 				verify(nvlist_add_nvlist_array(nv,
1228 				    ZPOOL_CONFIG_CHILDREN, child,
1229 				    children) == 0);
1230 
1231 				for (c = 0; c < children; c++)
1232 					nvlist_free(child[c]);
1233 				free(child);
1234 			}
1235 		} else {
1236 			/*
1237 			 * We have a device.  Pass off to make_leaf_vdev() to
1238 			 * construct the appropriate nvlist describing the vdev.
1239 			 */
1240 			if ((nv = make_leaf_vdev(argv[0], is_log)) == NULL)
1241 				return (NULL);
1242 			if (is_log)
1243 				nlogs++;
1244 			argc--;
1245 			argv++;
1246 		}
1247 
1248 		toplevels++;
1249 		top = realloc(top, toplevels * sizeof (nvlist_t *));
1250 		if (top == NULL)
1251 			zpool_no_memory();
1252 		top[toplevels - 1] = nv;
1253 	}
1254 
1255 	if (toplevels == 0 && nspares == 0) {
1256 		(void) fprintf(stderr, gettext("invalid vdev "
1257 		    "specification: at least one toplevel vdev must be "
1258 		    "specified\n"));
1259 		return (NULL);
1260 	}
1261 
1262 	if (seen_logs && nlogs == 0) {
1263 		(void) fprintf(stderr, gettext("invalid vdev specification: "
1264 		    "log requires at least 1 device\n"));
1265 		return (NULL);
1266 	}
1267 
1268 	/*
1269 	 * Finally, create nvroot and add all top-level vdevs to it.
1270 	 */
1271 	verify(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, 0) == 0);
1272 	verify(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
1273 	    VDEV_TYPE_ROOT) == 0);
1274 	verify(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
1275 	    top, toplevels) == 0);
1276 	if (nspares != 0)
1277 		verify(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1278 		    spares, nspares) == 0);
1279 
1280 	for (t = 0; t < toplevels; t++)
1281 		nvlist_free(top[t]);
1282 	for (t = 0; t < nspares; t++)
1283 		nvlist_free(spares[t]);
1284 	if (spares)
1285 		free(spares);
1286 	free(top);
1287 
1288 	return (nvroot);
1289 }
1290 
1291 
1292 /*
1293  * Get and validate the contents of the given vdev specification.  This ensures
1294  * that the nvlist returned is well-formed, that all the devices exist, and that
1295  * they are not currently in use by any other known consumer.  The 'poolconfig'
1296  * parameter is the current configuration of the pool when adding devices
1297  * existing pool, and is used to perform additional checks, such as changing the
1298  * replication level of the pool.  It can be 'NULL' to indicate that this is a
1299  * new pool.  The 'force' flag controls whether devices should be forcefully
1300  * added, even if they appear in use.
1301  */
1302 nvlist_t *
1303 make_root_vdev(zpool_handle_t *zhp, int force, int check_rep,
1304     boolean_t isreplacing, int argc, char **argv)
1305 {
1306 	nvlist_t *newroot;
1307 	nvlist_t *poolconfig = NULL;
1308 	is_force = force;
1309 
1310 	/*
1311 	 * Construct the vdev specification.  If this is successful, we know
1312 	 * that we have a valid specification, and that all devices can be
1313 	 * opened.
1314 	 */
1315 	if ((newroot = construct_spec(argc, argv)) == NULL)
1316 		return (NULL);
1317 
1318 	if (zhp && ((poolconfig = zpool_get_config(zhp, NULL)) == NULL))
1319 		return (NULL);
1320 
1321 	/*
1322 	 * Validate each device to make sure that its not shared with another
1323 	 * subsystem.  We do this even if 'force' is set, because there are some
1324 	 * uses (such as a dedicated dump device) that even '-f' cannot
1325 	 * override.
1326 	 */
1327 	if (check_in_use(poolconfig, newroot, force, isreplacing,
1328 	    B_FALSE) != 0) {
1329 		nvlist_free(newroot);
1330 		return (NULL);
1331 	}
1332 
1333 	/*
1334 	 * Check the replication level of the given vdevs and report any errors
1335 	 * found.  We include the existing pool spec, if any, as we need to
1336 	 * catch changes against the existing replication level.
1337 	 */
1338 	if (check_rep && check_replication(poolconfig, newroot) != 0) {
1339 		nvlist_free(newroot);
1340 		return (NULL);
1341 	}
1342 
1343 	/*
1344 	 * Run through the vdev specification and label any whole disks found.
1345 	 */
1346 	if (make_disks(zhp, newroot) != 0) {
1347 		nvlist_free(newroot);
1348 		return (NULL);
1349 	}
1350 
1351 	return (newroot);
1352 }
1353