]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - cmd/zpool/zpool_vdev.c
More ashift improvements
[FreeBSD/FreeBSD.git] / cmd / zpool / zpool_vdev.c
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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2013, 2015 by Delphix. All rights reserved.
25  * Copyright (c) 2016 Intel Corporation.
26  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
27  */
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 libblkid to make 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 <ctype.h>
67 #include <devid.h>
68 #include <errno.h>
69 #include <fcntl.h>
70 #include <libintl.h>
71 #include <libnvpair.h>
72 #include <limits.h>
73 #include <sys/spa.h>
74 #include <scsi/scsi.h>
75 #include <scsi/sg.h>
76 #include <stdio.h>
77 #include <string.h>
78 #include <unistd.h>
79 #include <sys/efi_partition.h>
80 #include <sys/stat.h>
81 #include <sys/vtoc.h>
82 #include <sys/mntent.h>
83 #include <uuid/uuid.h>
84 #include <blkid/blkid.h>
85 #include "zpool_util.h"
86 #include <sys/zfs_context.h>
87
88 /*
89  * For any given vdev specification, we can have multiple errors.  The
90  * vdev_error() function keeps track of whether we have seen an error yet, and
91  * prints out a header if its the first error we've seen.
92  */
93 boolean_t error_seen;
94 boolean_t is_force;
95
96 typedef struct vdev_disk_db_entry
97 {
98         char id[24];
99         int sector_size;
100 } vdev_disk_db_entry_t;
101
102 /*
103  * Database of block devices that lie about physical sector sizes.  The
104  * identification string must be precisely 24 characters to avoid false
105  * negatives
106  */
107 static vdev_disk_db_entry_t vdev_disk_database[] = {
108         {"ATA     ADATA SSD S396 3", 8192},
109         {"ATA     APPLE SSD SM128E", 8192},
110         {"ATA     APPLE SSD SM256E", 8192},
111         {"ATA     APPLE SSD SM512E", 8192},
112         {"ATA     APPLE SSD SM768E", 8192},
113         {"ATA     C400-MTFDDAC064M", 8192},
114         {"ATA     C400-MTFDDAC128M", 8192},
115         {"ATA     C400-MTFDDAC256M", 8192},
116         {"ATA     C400-MTFDDAC512M", 8192},
117         {"ATA     Corsair Force 3 ", 8192},
118         {"ATA     Corsair Force GS", 8192},
119         {"ATA     INTEL SSDSA2CT04", 8192},
120         {"ATA     INTEL SSDSA2BZ10", 8192},
121         {"ATA     INTEL SSDSA2BZ20", 8192},
122         {"ATA     INTEL SSDSA2BZ30", 8192},
123         {"ATA     INTEL SSDSA2CW04", 8192},
124         {"ATA     INTEL SSDSA2CW08", 8192},
125         {"ATA     INTEL SSDSA2CW12", 8192},
126         {"ATA     INTEL SSDSA2CW16", 8192},
127         {"ATA     INTEL SSDSA2CW30", 8192},
128         {"ATA     INTEL SSDSA2CW60", 8192},
129         {"ATA     INTEL SSDSC2CT06", 8192},
130         {"ATA     INTEL SSDSC2CT12", 8192},
131         {"ATA     INTEL SSDSC2CT18", 8192},
132         {"ATA     INTEL SSDSC2CT24", 8192},
133         {"ATA     INTEL SSDSC2CW06", 8192},
134         {"ATA     INTEL SSDSC2CW12", 8192},
135         {"ATA     INTEL SSDSC2CW18", 8192},
136         {"ATA     INTEL SSDSC2CW24", 8192},
137         {"ATA     INTEL SSDSC2CW48", 8192},
138         {"ATA     KINGSTON SH100S3", 8192},
139         {"ATA     KINGSTON SH103S3", 8192},
140         {"ATA     M4-CT064M4SSD2  ", 8192},
141         {"ATA     M4-CT128M4SSD2  ", 8192},
142         {"ATA     M4-CT256M4SSD2  ", 8192},
143         {"ATA     M4-CT512M4SSD2  ", 8192},
144         {"ATA     OCZ-AGILITY2    ", 8192},
145         {"ATA     OCZ-AGILITY3    ", 8192},
146         {"ATA     OCZ-VERTEX2 3.5 ", 8192},
147         {"ATA     OCZ-VERTEX3     ", 8192},
148         {"ATA     OCZ-VERTEX3 LT  ", 8192},
149         {"ATA     OCZ-VERTEX3 MI  ", 8192},
150         {"ATA     OCZ-VERTEX4     ", 8192},
151         {"ATA     SAMSUNG MZ7WD120", 8192},
152         {"ATA     SAMSUNG MZ7WD240", 8192},
153         {"ATA     SAMSUNG MZ7WD480", 8192},
154         {"ATA     SAMSUNG MZ7WD960", 8192},
155         {"ATA     SAMSUNG SSD 830 ", 8192},
156         {"ATA     Samsung SSD 840 ", 8192},
157         {"ATA     SanDisk SSD U100", 8192},
158         {"ATA     TOSHIBA THNSNH06", 8192},
159         {"ATA     TOSHIBA THNSNH12", 8192},
160         {"ATA     TOSHIBA THNSNH25", 8192},
161         {"ATA     TOSHIBA THNSNH51", 8192},
162         {"ATA     APPLE SSD TS064C", 4096},
163         {"ATA     APPLE SSD TS128C", 4096},
164         {"ATA     APPLE SSD TS256C", 4096},
165         {"ATA     APPLE SSD TS512C", 4096},
166         {"ATA     INTEL SSDSA2M040", 4096},
167         {"ATA     INTEL SSDSA2M080", 4096},
168         {"ATA     INTEL SSDSA2M160", 4096},
169         {"ATA     INTEL SSDSC2MH12", 4096},
170         {"ATA     INTEL SSDSC2MH25", 4096},
171         {"ATA     OCZ CORE_SSD    ", 4096},
172         {"ATA     OCZ-VERTEX      ", 4096},
173         {"ATA     SAMSUNG MCCOE32G", 4096},
174         {"ATA     SAMSUNG MCCOE64G", 4096},
175         {"ATA     SAMSUNG SSD PM80", 4096},
176         /* Flash drives optimized for 4KB IOs on larger pages */
177         {"ATA     INTEL SSDSC2BA10", 4096},
178         {"ATA     INTEL SSDSC2BA20", 4096},
179         {"ATA     INTEL SSDSC2BA40", 4096},
180         {"ATA     INTEL SSDSC2BA80", 4096},
181         {"ATA     INTEL SSDSC2BB08", 4096},
182         {"ATA     INTEL SSDSC2BB12", 4096},
183         {"ATA     INTEL SSDSC2BB16", 4096},
184         {"ATA     INTEL SSDSC2BB24", 4096},
185         {"ATA     INTEL SSDSC2BB30", 4096},
186         {"ATA     INTEL SSDSC2BB40", 4096},
187         {"ATA     INTEL SSDSC2BB48", 4096},
188         {"ATA     INTEL SSDSC2BB60", 4096},
189         {"ATA     INTEL SSDSC2BB80", 4096},
190         {"ATA     INTEL SSDSC2BW24", 4096},
191         {"ATA     INTEL SSDSC2BP24", 4096},
192         {"ATA     INTEL SSDSC2BP48", 4096},
193         {"NA      SmrtStorSDLKAE9W", 4096},
194         /* Imported from Open Solaris */
195         {"ATA     MARVELL SD88SA02", 4096},
196         /* Advanced format Hard drives */
197         {"ATA     Hitachi HDS5C303", 4096},
198         {"ATA     SAMSUNG HD204UI ", 4096},
199         {"ATA     ST2000DL004 HD20", 4096},
200         {"ATA     WDC WD10EARS-00M", 4096},
201         {"ATA     WDC WD10EARS-00S", 4096},
202         {"ATA     WDC WD10EARS-00Z", 4096},
203         {"ATA     WDC WD15EARS-00M", 4096},
204         {"ATA     WDC WD15EARS-00S", 4096},
205         {"ATA     WDC WD15EARS-00Z", 4096},
206         {"ATA     WDC WD20EARS-00M", 4096},
207         {"ATA     WDC WD20EARS-00S", 4096},
208         {"ATA     WDC WD20EARS-00Z", 4096},
209         {"ATA     WDC WD1600BEVT-0", 4096},
210         {"ATA     WDC WD2500BEVT-0", 4096},
211         {"ATA     WDC WD3200BEVT-0", 4096},
212         {"ATA     WDC WD5000BEVT-0", 4096},
213         /* Virtual disks: Assume zvols with default volblocksize */
214 #if 0
215         {"ATA     QEMU HARDDISK   ", 8192},
216         {"IET     VIRTUAL-DISK    ", 8192},
217         {"OI      COMSTAR         ", 8192},
218         {"SUN     COMSTAR         ", 8192},
219         {"NETAPP  LUN             ", 8192},
220 #endif
221 };
222
223 static const int vdev_disk_database_size =
224         sizeof (vdev_disk_database) / sizeof (vdev_disk_database[0]);
225
226 #define INQ_REPLY_LEN   96
227 #define INQ_CMD_LEN     6
228
229 static boolean_t
230 check_sector_size_database(char *path, int *sector_size)
231 {
232         unsigned char inq_buff[INQ_REPLY_LEN];
233         unsigned char sense_buffer[32];
234         unsigned char inq_cmd_blk[INQ_CMD_LEN] =
235             {INQUIRY, 0, 0, 0, INQ_REPLY_LEN, 0};
236         sg_io_hdr_t io_hdr;
237         int error;
238         int fd;
239         int i;
240
241         /* Prepare INQUIRY command */
242         memset(&io_hdr, 0, sizeof (sg_io_hdr_t));
243         io_hdr.interface_id = 'S';
244         io_hdr.cmd_len = sizeof (inq_cmd_blk);
245         io_hdr.mx_sb_len = sizeof (sense_buffer);
246         io_hdr.dxfer_direction = SG_DXFER_FROM_DEV;
247         io_hdr.dxfer_len = INQ_REPLY_LEN;
248         io_hdr.dxferp = inq_buff;
249         io_hdr.cmdp = inq_cmd_blk;
250         io_hdr.sbp = sense_buffer;
251         io_hdr.timeout = 10;            /* 10 milliseconds is ample time */
252
253         if ((fd = open(path, O_RDONLY|O_DIRECT)) < 0)
254                 return (B_FALSE);
255
256         error = ioctl(fd, SG_IO, (unsigned long) &io_hdr);
257
258         (void) close(fd);
259
260         if (error < 0)
261                 return (B_FALSE);
262
263         if ((io_hdr.info & SG_INFO_OK_MASK) != SG_INFO_OK)
264                 return (B_FALSE);
265
266         for (i = 0; i < vdev_disk_database_size; i++) {
267                 if (memcmp(inq_buff + 8, vdev_disk_database[i].id, 24))
268                         continue;
269
270                 *sector_size = vdev_disk_database[i].sector_size;
271                 return (B_TRUE);
272         }
273
274         return (B_FALSE);
275 }
276
277 /*PRINTFLIKE1*/
278 static void
279 vdev_error(const char *fmt, ...)
280 {
281         va_list ap;
282
283         if (!error_seen) {
284                 (void) fprintf(stderr, gettext("invalid vdev specification\n"));
285                 if (!is_force)
286                         (void) fprintf(stderr, gettext("use '-f' to override "
287                             "the following errors:\n"));
288                 else
289                         (void) fprintf(stderr, gettext("the following errors "
290                             "must be manually repaired:\n"));
291                 error_seen = B_TRUE;
292         }
293
294         va_start(ap, fmt);
295         (void) vfprintf(stderr, fmt, ap);
296         va_end(ap);
297 }
298
299 /*
300  * Check that a file is valid.  All we can do in this case is check that it's
301  * not in use by another pool, and not in use by swap.
302  */
303 static int
304 check_file(const char *file, boolean_t force, boolean_t isspare)
305 {
306         char  *name;
307         int fd;
308         int ret = 0;
309         pool_state_t state;
310         boolean_t inuse;
311
312         if ((fd = open(file, O_RDONLY)) < 0)
313                 return (0);
314
315         if (zpool_in_use(g_zfs, fd, &state, &name, &inuse) == 0 && inuse) {
316                 const char *desc;
317
318                 switch (state) {
319                 case POOL_STATE_ACTIVE:
320                         desc = gettext("active");
321                         break;
322
323                 case POOL_STATE_EXPORTED:
324                         desc = gettext("exported");
325                         break;
326
327                 case POOL_STATE_POTENTIALLY_ACTIVE:
328                         desc = gettext("potentially active");
329                         break;
330
331                 default:
332                         desc = gettext("unknown");
333                         break;
334                 }
335
336                 /*
337                  * Allow hot spares to be shared between pools.
338                  */
339                 if (state == POOL_STATE_SPARE && isspare) {
340                         free(name);
341                         (void) close(fd);
342                         return (0);
343                 }
344
345                 if (state == POOL_STATE_ACTIVE ||
346                     state == POOL_STATE_SPARE || !force) {
347                         switch (state) {
348                         case POOL_STATE_SPARE:
349                                 vdev_error(gettext("%s is reserved as a hot "
350                                     "spare for pool %s\n"), file, name);
351                                 break;
352                         default:
353                                 vdev_error(gettext("%s is part of %s pool "
354                                     "'%s'\n"), file, desc, name);
355                                 break;
356                         }
357                         ret = -1;
358                 }
359
360                 free(name);
361         }
362
363         (void) close(fd);
364         return (ret);
365 }
366
367 static void
368 check_error(int err)
369 {
370         (void) fprintf(stderr, gettext("warning: device in use checking "
371             "failed: %s\n"), strerror(err));
372 }
373
374 static int
375 check_slice(const char *path, blkid_cache cache, int force, boolean_t isspare)
376 {
377         int err;
378         char *value;
379
380         /* No valid type detected device is safe to use */
381         value = blkid_get_tag_value(cache, "TYPE", path);
382         if (value == NULL)
383                 return (0);
384
385         /*
386          * If libblkid detects a ZFS device, we check the device
387          * using check_file() to see if it's safe.  The one safe
388          * case is a spare device shared between multiple pools.
389          */
390         if (strcmp(value, "zfs_member") == 0) {
391                 err = check_file(path, force, isspare);
392         } else {
393                 if (force) {
394                         err = 0;
395                 } else {
396                         err = -1;
397                         vdev_error(gettext("%s contains a filesystem of "
398                             "type '%s'\n"), path, value);
399                 }
400         }
401
402         free(value);
403
404         return (err);
405 }
406
407 /*
408  * Validate that a disk including all partitions are safe to use.
409  *
410  * For EFI labeled disks this can done relatively easily with the libefi
411  * library.  The partition numbers are extracted from the label and used
412  * to generate the expected /dev/ paths.  Each partition can then be
413  * checked for conflicts.
414  *
415  * For non-EFI labeled disks (MBR/EBR/etc) the same process is possible
416  * but due to the lack of a readily available libraries this scanning is
417  * not implemented.  Instead only the device path as given is checked.
418  */
419 static int
420 check_disk(const char *path, blkid_cache cache, int force,
421     boolean_t isspare, boolean_t iswholedisk)
422 {
423         struct dk_gpt *vtoc;
424         char slice_path[MAXPATHLEN];
425         int err = 0;
426         int fd, i;
427
428         if (!iswholedisk)
429                 return (check_slice(path, cache, force, isspare));
430
431         if ((fd = open(path, O_RDONLY|O_DIRECT)) < 0) {
432                 check_error(errno);
433                 return (-1);
434         }
435
436         /*
437          * Expected to fail for non-EFI labled disks.  Just check the device
438          * as given and do not attempt to detect and scan partitions.
439          */
440         err = efi_alloc_and_read(fd, &vtoc);
441         if (err) {
442                 (void) close(fd);
443                 return (check_slice(path, cache, force, isspare));
444         }
445
446         /*
447          * The primary efi partition label is damaged however the secondary
448          * label at the end of the device is intact.  Rather than use this
449          * label we should play it safe and treat this as a non efi device.
450          */
451         if (vtoc->efi_flags & EFI_GPT_PRIMARY_CORRUPT) {
452                 efi_free(vtoc);
453                 (void) close(fd);
454
455                 if (force) {
456                         /* Partitions will now be created using the backup */
457                         return (0);
458                 } else {
459                         vdev_error(gettext("%s contains a corrupt primary "
460                             "EFI label.\n"), path);
461                         return (-1);
462                 }
463         }
464
465         for (i = 0; i < vtoc->efi_nparts; i++) {
466
467                 if (vtoc->efi_parts[i].p_tag == V_UNASSIGNED ||
468                     uuid_is_null((uchar_t *)&vtoc->efi_parts[i].p_guid))
469                         continue;
470
471                 if (strncmp(path, UDISK_ROOT, strlen(UDISK_ROOT)) == 0)
472                         (void) snprintf(slice_path, sizeof (slice_path),
473                             "%s%s%d", path, "-part", i+1);
474                 else
475                         (void) snprintf(slice_path, sizeof (slice_path),
476                             "%s%s%d", path, isdigit(path[strlen(path)-1]) ?
477                             "p" : "", i+1);
478
479                 err = check_slice(slice_path, cache, force, isspare);
480                 if (err)
481                         break;
482         }
483
484         efi_free(vtoc);
485         (void) close(fd);
486
487         return (err);
488 }
489
490 static int
491 check_device(const char *path, boolean_t force,
492     boolean_t isspare, boolean_t iswholedisk)
493 {
494         blkid_cache cache;
495         int error;
496
497         error = blkid_get_cache(&cache, NULL);
498         if (error != 0) {
499                 check_error(error);
500                 return (-1);
501         }
502
503         error = check_disk(path, cache, force, isspare, iswholedisk);
504         blkid_put_cache(cache);
505
506         return (error);
507 }
508
509 /*
510  * This may be a shorthand device path or it could be total gibberish.
511  * Check to see if it is a known device available in zfs_vdev_paths.
512  * As part of this check, see if we've been given an entire disk
513  * (minus the slice number).
514  */
515 static int
516 is_shorthand_path(const char *arg, char *path, size_t path_size,
517     struct stat64 *statbuf, boolean_t *wholedisk)
518 {
519         int error;
520
521         error = zfs_resolve_shortname(arg, path, path_size);
522         if (error == 0) {
523                 *wholedisk = zfs_dev_is_whole_disk(path);
524                 if (*wholedisk || (stat64(path, statbuf) == 0))
525                         return (0);
526         }
527
528         strlcpy(path, arg, path_size);
529         memset(statbuf, 0, sizeof (*statbuf));
530         *wholedisk = B_FALSE;
531
532         return (error);
533 }
534
535 /*
536  * Determine if the given path is a hot spare within the given configuration.
537  * If no configuration is given we rely solely on the label.
538  */
539 static boolean_t
540 is_spare(nvlist_t *config, const char *path)
541 {
542         int fd;
543         pool_state_t state;
544         char *name = NULL;
545         nvlist_t *label;
546         uint64_t guid, spareguid;
547         nvlist_t *nvroot;
548         nvlist_t **spares;
549         uint_t i, nspares;
550         boolean_t inuse;
551
552         if ((fd = open(path, O_RDONLY)) < 0)
553                 return (B_FALSE);
554
555         if (zpool_in_use(g_zfs, fd, &state, &name, &inuse) != 0 ||
556             !inuse ||
557             state != POOL_STATE_SPARE ||
558             zpool_read_label(fd, &label, NULL) != 0) {
559                 free(name);
560                 (void) close(fd);
561                 return (B_FALSE);
562         }
563         free(name);
564         (void) close(fd);
565
566         if (config == NULL) {
567                 nvlist_free(label);
568                 return (B_TRUE);
569         }
570
571         verify(nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) == 0);
572         nvlist_free(label);
573
574         verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
575             &nvroot) == 0);
576         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
577             &spares, &nspares) == 0) {
578                 for (i = 0; i < nspares; i++) {
579                         verify(nvlist_lookup_uint64(spares[i],
580                             ZPOOL_CONFIG_GUID, &spareguid) == 0);
581                         if (spareguid == guid)
582                                 return (B_TRUE);
583                 }
584         }
585
586         return (B_FALSE);
587 }
588
589 /*
590  * Create a leaf vdev.  Determine if this is a file or a device.  If it's a
591  * device, fill in the device id to make a complete nvlist.  Valid forms for a
592  * leaf vdev are:
593  *
594  *      /dev/xxx        Complete disk path
595  *      /xxx            Full path to file
596  *      xxx             Shorthand for <zfs_vdev_paths>/xxx
597  */
598 static nvlist_t *
599 make_leaf_vdev(nvlist_t *props, const char *arg, uint64_t is_log)
600 {
601         char path[MAXPATHLEN];
602         struct stat64 statbuf;
603         nvlist_t *vdev = NULL;
604         char *type = NULL;
605         boolean_t wholedisk = B_FALSE;
606         uint64_t ashift = 0;
607         int err;
608
609         /*
610          * Determine what type of vdev this is, and put the full path into
611          * 'path'.  We detect whether this is a device of file afterwards by
612          * checking the st_mode of the file.
613          */
614         if (arg[0] == '/') {
615                 /*
616                  * Complete device or file path.  Exact type is determined by
617                  * examining the file descriptor afterwards.  Symbolic links
618                  * are resolved to their real paths to determine whole disk
619                  * and S_ISBLK/S_ISREG type checks.  However, we are careful
620                  * to store the given path as ZPOOL_CONFIG_PATH to ensure we
621                  * can leverage udev's persistent device labels.
622                  */
623                 if (realpath(arg, path) == NULL) {
624                         (void) fprintf(stderr,
625                             gettext("cannot resolve path '%s'\n"), arg);
626                         return (NULL);
627                 }
628
629                 wholedisk = zfs_dev_is_whole_disk(path);
630                 if (!wholedisk && (stat64(path, &statbuf) != 0)) {
631                         (void) fprintf(stderr,
632                             gettext("cannot open '%s': %s\n"),
633                             path, strerror(errno));
634                         return (NULL);
635                 }
636
637                 /* After whole disk check restore original passed path */
638                 strlcpy(path, arg, sizeof (path));
639         } else {
640                 err = is_shorthand_path(arg, path, sizeof (path),
641                     &statbuf, &wholedisk);
642                 if (err != 0) {
643                         /*
644                          * If we got ENOENT, then the user gave us
645                          * gibberish, so try to direct them with a
646                          * reasonable error message.  Otherwise,
647                          * regurgitate strerror() since it's the best we
648                          * can do.
649                          */
650                         if (err == ENOENT) {
651                                 (void) fprintf(stderr,
652                                     gettext("cannot open '%s': no such "
653                                     "device in %s\n"), arg, DISK_ROOT);
654                                 (void) fprintf(stderr,
655                                     gettext("must be a full path or "
656                                     "shorthand device name\n"));
657                                 return (NULL);
658                         } else {
659                                 (void) fprintf(stderr,
660                                     gettext("cannot open '%s': %s\n"),
661                                     path, strerror(errno));
662                                 return (NULL);
663                         }
664                 }
665         }
666
667         /*
668          * Determine whether this is a device or a file.
669          */
670         if (wholedisk || S_ISBLK(statbuf.st_mode)) {
671                 type = VDEV_TYPE_DISK;
672         } else if (S_ISREG(statbuf.st_mode)) {
673                 type = VDEV_TYPE_FILE;
674         } else {
675                 (void) fprintf(stderr, gettext("cannot use '%s': must be a "
676                     "block device or regular file\n"), path);
677                 return (NULL);
678         }
679
680         /*
681          * Finally, we have the complete device or file, and we know that it is
682          * acceptable to use.  Construct the nvlist to describe this vdev.  All
683          * vdevs have a 'path' element, and devices also have a 'devid' element.
684          */
685         verify(nvlist_alloc(&vdev, NV_UNIQUE_NAME, 0) == 0);
686         verify(nvlist_add_string(vdev, ZPOOL_CONFIG_PATH, path) == 0);
687         verify(nvlist_add_string(vdev, ZPOOL_CONFIG_TYPE, type) == 0);
688         verify(nvlist_add_uint64(vdev, ZPOOL_CONFIG_IS_LOG, is_log) == 0);
689         if (strcmp(type, VDEV_TYPE_DISK) == 0)
690                 verify(nvlist_add_uint64(vdev, ZPOOL_CONFIG_WHOLE_DISK,
691                     (uint64_t)wholedisk) == 0);
692
693         /*
694          * Override defaults if custom properties are provided.
695          */
696         if (props != NULL) {
697                 char *value = NULL;
698
699                 if (nvlist_lookup_string(props,
700                     zpool_prop_to_name(ZPOOL_PROP_ASHIFT), &value) == 0) {
701                         if (zfs_nicestrtonum(NULL, value, &ashift) != 0) {
702                                 (void) fprintf(stderr,
703                                     gettext("ashift must be a number.\n"));
704                                 return (NULL);
705                         }
706                         if (ashift != 0 &&
707                             (ashift < ASHIFT_MIN || ashift > ASHIFT_MAX)) {
708                                 (void) fprintf(stderr,
709                                     gettext("invalid 'ashift=%" PRIu64 "' "
710                                     "property: only values between %" PRId32 " "
711                                     "and %" PRId32 " are allowed.\n"),
712                                     ashift, ASHIFT_MIN, ASHIFT_MAX);
713                                 return (NULL);
714                         }
715                 }
716         }
717
718         /*
719          * If the device is known to incorrectly report its physical sector
720          * size explicitly provide the known correct value.
721          */
722         if (ashift == 0) {
723                 int sector_size;
724
725                 if (check_sector_size_database(path, &sector_size) == B_TRUE)
726                         ashift = highbit64(sector_size) - 1;
727         }
728
729         if (ashift > 0)
730                 (void) nvlist_add_uint64(vdev, ZPOOL_CONFIG_ASHIFT, ashift);
731
732         return (vdev);
733 }
734
735 /*
736  * Go through and verify the replication level of the pool is consistent.
737  * Performs the following checks:
738  *
739  *      For the new spec, verifies that devices in mirrors and raidz are the
740  *      same size.
741  *
742  *      If the current configuration already has inconsistent replication
743  *      levels, ignore any other potential problems in the new spec.
744  *
745  *      Otherwise, make sure that the current spec (if there is one) and the new
746  *      spec have consistent replication levels.
747  */
748 typedef struct replication_level {
749         char *zprl_type;
750         uint64_t zprl_children;
751         uint64_t zprl_parity;
752 } replication_level_t;
753
754 #define ZPOOL_FUZZ      (16 * 1024 * 1024)
755
756 static boolean_t
757 is_raidz_mirror(replication_level_t *a, replication_level_t *b,
758     replication_level_t **raidz, replication_level_t **mirror)
759 {
760         if (strcmp(a->zprl_type, "raidz") == 0 &&
761             strcmp(b->zprl_type, "mirror") == 0) {
762                 *raidz = a;
763                 *mirror = b;
764                 return (B_TRUE);
765         }
766         return (B_FALSE);
767 }
768
769 /*
770  * Given a list of toplevel vdevs, return the current replication level.  If
771  * the config is inconsistent, then NULL is returned.  If 'fatal' is set, then
772  * an error message will be displayed for each self-inconsistent vdev.
773  */
774 static replication_level_t *
775 get_replication(nvlist_t *nvroot, boolean_t fatal)
776 {
777         nvlist_t **top;
778         uint_t t, toplevels;
779         nvlist_t **child;
780         uint_t c, children;
781         nvlist_t *nv;
782         char *type;
783         replication_level_t lastrep = {0};
784         replication_level_t rep;
785         replication_level_t *ret;
786         replication_level_t *raidz, *mirror;
787         boolean_t dontreport;
788
789         ret = safe_malloc(sizeof (replication_level_t));
790
791         verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
792             &top, &toplevels) == 0);
793
794         for (t = 0; t < toplevels; t++) {
795                 uint64_t is_log = B_FALSE;
796
797                 nv = top[t];
798
799                 /*
800                  * For separate logs we ignore the top level vdev replication
801                  * constraints.
802                  */
803                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG, &is_log);
804                 if (is_log)
805                         continue;
806
807                 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE,
808                     &type) == 0);
809                 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
810                     &child, &children) != 0) {
811                         /*
812                          * This is a 'file' or 'disk' vdev.
813                          */
814                         rep.zprl_type = type;
815                         rep.zprl_children = 1;
816                         rep.zprl_parity = 0;
817                 } else {
818                         uint64_t vdev_size;
819
820                         /*
821                          * This is a mirror or RAID-Z vdev.  Go through and make
822                          * sure the contents are all the same (files vs. disks),
823                          * keeping track of the number of elements in the
824                          * process.
825                          *
826                          * We also check that the size of each vdev (if it can
827                          * be determined) is the same.
828                          */
829                         rep.zprl_type = type;
830                         rep.zprl_children = 0;
831
832                         if (strcmp(type, VDEV_TYPE_RAIDZ) == 0) {
833                                 verify(nvlist_lookup_uint64(nv,
834                                     ZPOOL_CONFIG_NPARITY,
835                                     &rep.zprl_parity) == 0);
836                                 assert(rep.zprl_parity != 0);
837                         } else {
838                                 rep.zprl_parity = 0;
839                         }
840
841                         /*
842                          * The 'dontreport' variable indicates that we've
843                          * already reported an error for this spec, so don't
844                          * bother doing it again.
845                          */
846                         type = NULL;
847                         dontreport = 0;
848                         vdev_size = -1ULL;
849                         for (c = 0; c < children; c++) {
850                                 nvlist_t *cnv = child[c];
851                                 char *path;
852                                 struct stat64 statbuf;
853                                 uint64_t size = -1ULL;
854                                 char *childtype;
855                                 int fd, err;
856
857                                 rep.zprl_children++;
858
859                                 verify(nvlist_lookup_string(cnv,
860                                     ZPOOL_CONFIG_TYPE, &childtype) == 0);
861
862                                 /*
863                                  * If this is a replacing or spare vdev, then
864                                  * get the real first child of the vdev.
865                                  */
866                                 if (strcmp(childtype,
867                                     VDEV_TYPE_REPLACING) == 0 ||
868                                     strcmp(childtype, VDEV_TYPE_SPARE) == 0) {
869                                         nvlist_t **rchild;
870                                         uint_t rchildren;
871
872                                         verify(nvlist_lookup_nvlist_array(cnv,
873                                             ZPOOL_CONFIG_CHILDREN, &rchild,
874                                             &rchildren) == 0);
875                                         assert(rchildren == 2);
876                                         cnv = rchild[0];
877
878                                         verify(nvlist_lookup_string(cnv,
879                                             ZPOOL_CONFIG_TYPE,
880                                             &childtype) == 0);
881                                 }
882
883                                 verify(nvlist_lookup_string(cnv,
884                                     ZPOOL_CONFIG_PATH, &path) == 0);
885
886                                 /*
887                                  * If we have a raidz/mirror that combines disks
888                                  * with files, report it as an error.
889                                  */
890                                 if (!dontreport && type != NULL &&
891                                     strcmp(type, childtype) != 0) {
892                                         if (ret != NULL)
893                                                 free(ret);
894                                         ret = NULL;
895                                         if (fatal)
896                                                 vdev_error(gettext(
897                                                     "mismatched replication "
898                                                     "level: %s contains both "
899                                                     "files and devices\n"),
900                                                     rep.zprl_type);
901                                         else
902                                                 return (NULL);
903                                         dontreport = B_TRUE;
904                                 }
905
906                                 /*
907                                  * According to stat(2), the value of 'st_size'
908                                  * is undefined for block devices and character
909                                  * devices.  But there is no effective way to
910                                  * determine the real size in userland.
911                                  *
912                                  * Instead, we'll take advantage of an
913                                  * implementation detail of spec_size().  If the
914                                  * device is currently open, then we (should)
915                                  * return a valid size.
916                                  *
917                                  * If we still don't get a valid size (indicated
918                                  * by a size of 0 or MAXOFFSET_T), then ignore
919                                  * this device altogether.
920                                  */
921                                 if ((fd = open(path, O_RDONLY)) >= 0) {
922                                         err = fstat64(fd, &statbuf);
923                                         (void) close(fd);
924                                 } else {
925                                         err = stat64(path, &statbuf);
926                                 }
927
928                                 if (err != 0 ||
929                                     statbuf.st_size == 0 ||
930                                     statbuf.st_size == MAXOFFSET_T)
931                                         continue;
932
933                                 size = statbuf.st_size;
934
935                                 /*
936                                  * Also make sure that devices and
937                                  * slices have a consistent size.  If
938                                  * they differ by a significant amount
939                                  * (~16MB) then report an error.
940                                  */
941                                 if (!dontreport &&
942                                     (vdev_size != -1ULL &&
943                                     (labs(size - vdev_size) >
944                                     ZPOOL_FUZZ))) {
945                                         if (ret != NULL)
946                                                 free(ret);
947                                         ret = NULL;
948                                         if (fatal)
949                                                 vdev_error(gettext(
950                                                     "%s contains devices of "
951                                                     "different sizes\n"),
952                                                     rep.zprl_type);
953                                         else
954                                                 return (NULL);
955                                         dontreport = B_TRUE;
956                                 }
957
958                                 type = childtype;
959                                 vdev_size = size;
960                         }
961                 }
962
963                 /*
964                  * At this point, we have the replication of the last toplevel
965                  * vdev in 'rep'.  Compare it to 'lastrep' to see if its
966                  * different.
967                  */
968                 if (lastrep.zprl_type != NULL) {
969                         if (is_raidz_mirror(&lastrep, &rep, &raidz, &mirror) ||
970                             is_raidz_mirror(&rep, &lastrep, &raidz, &mirror)) {
971                                 /*
972                                  * Accepted raidz and mirror when they can
973                                  * handle the same number of disk failures.
974                                  */
975                                 if (raidz->zprl_parity !=
976                                     mirror->zprl_children - 1) {
977                                         if (ret != NULL)
978                                                 free(ret);
979                                         ret = NULL;
980                                         if (fatal)
981                                                 vdev_error(gettext(
982                                                     "mismatched replication "
983                                                     "level: "
984                                                     "%s and %s vdevs with "
985                                                     "different redundancy, "
986                                                     "%llu vs. %llu (%llu-way) "
987                                                     "are present\n"),
988                                                     raidz->zprl_type,
989                                                     mirror->zprl_type,
990                                                     raidz->zprl_parity,
991                                                     mirror->zprl_children - 1,
992                                                     mirror->zprl_children);
993                                         else
994                                                 return (NULL);
995                                 }
996                         } else if (strcmp(lastrep.zprl_type, rep.zprl_type) !=
997                             0) {
998                                 if (ret != NULL)
999                                         free(ret);
1000                                 ret = NULL;
1001                                 if (fatal)
1002                                         vdev_error(gettext(
1003                                             "mismatched replication level: "
1004                                             "both %s and %s vdevs are "
1005                                             "present\n"),
1006                                             lastrep.zprl_type, rep.zprl_type);
1007                                 else
1008                                         return (NULL);
1009                         } else if (lastrep.zprl_parity != rep.zprl_parity) {
1010                                 if (ret)
1011                                         free(ret);
1012                                 ret = NULL;
1013                                 if (fatal)
1014                                         vdev_error(gettext(
1015                                             "mismatched replication level: "
1016                                             "both %llu and %llu device parity "
1017                                             "%s vdevs are present\n"),
1018                                             lastrep.zprl_parity,
1019                                             rep.zprl_parity,
1020                                             rep.zprl_type);
1021                                 else
1022                                         return (NULL);
1023                         } else if (lastrep.zprl_children != rep.zprl_children) {
1024                                 if (ret)
1025                                         free(ret);
1026                                 ret = NULL;
1027                                 if (fatal)
1028                                         vdev_error(gettext(
1029                                             "mismatched replication level: "
1030                                             "both %llu-way and %llu-way %s "
1031                                             "vdevs are present\n"),
1032                                             lastrep.zprl_children,
1033                                             rep.zprl_children,
1034                                             rep.zprl_type);
1035                                 else
1036                                         return (NULL);
1037                         }
1038                 }
1039                 lastrep = rep;
1040         }
1041
1042         if (ret != NULL)
1043                 *ret = rep;
1044
1045         return (ret);
1046 }
1047
1048 /*
1049  * Check the replication level of the vdev spec against the current pool.  Calls
1050  * get_replication() to make sure the new spec is self-consistent.  If the pool
1051  * has a consistent replication level, then we ignore any errors.  Otherwise,
1052  * report any difference between the two.
1053  */
1054 static int
1055 check_replication(nvlist_t *config, nvlist_t *newroot)
1056 {
1057         nvlist_t **child;
1058         uint_t  children;
1059         replication_level_t *current = NULL, *new;
1060         int ret;
1061
1062         /*
1063          * If we have a current pool configuration, check to see if it's
1064          * self-consistent.  If not, simply return success.
1065          */
1066         if (config != NULL) {
1067                 nvlist_t *nvroot;
1068
1069                 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1070                     &nvroot) == 0);
1071                 if ((current = get_replication(nvroot, B_FALSE)) == NULL)
1072                         return (0);
1073         }
1074         /*
1075          * for spares there may be no children, and therefore no
1076          * replication level to check
1077          */
1078         if ((nvlist_lookup_nvlist_array(newroot, ZPOOL_CONFIG_CHILDREN,
1079             &child, &children) != 0) || (children == 0)) {
1080                 free(current);
1081                 return (0);
1082         }
1083
1084         /*
1085          * If all we have is logs then there's no replication level to check.
1086          */
1087         if (num_logs(newroot) == children) {
1088                 free(current);
1089                 return (0);
1090         }
1091
1092         /*
1093          * Get the replication level of the new vdev spec, reporting any
1094          * inconsistencies found.
1095          */
1096         if ((new = get_replication(newroot, B_TRUE)) == NULL) {
1097                 free(current);
1098                 return (-1);
1099         }
1100
1101         /*
1102          * Check to see if the new vdev spec matches the replication level of
1103          * the current pool.
1104          */
1105         ret = 0;
1106         if (current != NULL) {
1107                 if (strcmp(current->zprl_type, new->zprl_type) != 0) {
1108                         vdev_error(gettext(
1109                             "mismatched replication level: pool uses %s "
1110                             "and new vdev is %s\n"),
1111                             current->zprl_type, new->zprl_type);
1112                         ret = -1;
1113                 } else if (current->zprl_parity != new->zprl_parity) {
1114                         vdev_error(gettext(
1115                             "mismatched replication level: pool uses %llu "
1116                             "device parity and new vdev uses %llu\n"),
1117                             current->zprl_parity, new->zprl_parity);
1118                         ret = -1;
1119                 } else if (current->zprl_children != new->zprl_children) {
1120                         vdev_error(gettext(
1121                             "mismatched replication level: pool uses %llu-way "
1122                             "%s and new vdev uses %llu-way %s\n"),
1123                             current->zprl_children, current->zprl_type,
1124                             new->zprl_children, new->zprl_type);
1125                         ret = -1;
1126                 }
1127         }
1128
1129         free(new);
1130         if (current != NULL)
1131                 free(current);
1132
1133         return (ret);
1134 }
1135
1136 static int
1137 zero_label(char *path)
1138 {
1139         const int size = 4096;
1140         char buf[size];
1141         int err, fd;
1142
1143         if ((fd = open(path, O_WRONLY|O_EXCL)) < 0) {
1144                 (void) fprintf(stderr, gettext("cannot open '%s': %s\n"),
1145                     path, strerror(errno));
1146                 return (-1);
1147         }
1148
1149         memset(buf, 0, size);
1150         err = write(fd, buf, size);
1151         (void) fdatasync(fd);
1152         (void) close(fd);
1153
1154         if (err == -1) {
1155                 (void) fprintf(stderr, gettext("cannot zero first %d bytes "
1156                     "of '%s': %s\n"), size, path, strerror(errno));
1157                 return (-1);
1158         }
1159
1160         if (err != size) {
1161                 (void) fprintf(stderr, gettext("could only zero %d/%d bytes "
1162                     "of '%s'\n"), err, size, path);
1163                 return (-1);
1164         }
1165
1166         return (0);
1167 }
1168
1169 /*
1170  * Go through and find any whole disks in the vdev specification, labelling them
1171  * as appropriate.  When constructing the vdev spec, we were unable to open this
1172  * device in order to provide a devid.  Now that we have labelled the disk and
1173  * know that slice 0 is valid, we can construct the devid now.
1174  *
1175  * If the disk was already labeled with an EFI label, we will have gotten the
1176  * devid already (because we were able to open the whole disk).  Otherwise, we
1177  * need to get the devid after we label the disk.
1178  */
1179 static int
1180 make_disks(zpool_handle_t *zhp, nvlist_t *nv)
1181 {
1182         nvlist_t **child;
1183         uint_t c, children;
1184         char *type, *path;
1185         char devpath[MAXPATHLEN];
1186         char udevpath[MAXPATHLEN];
1187         uint64_t wholedisk;
1188         struct stat64 statbuf;
1189         int is_exclusive = 0;
1190         int fd;
1191         int ret;
1192
1193         verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
1194
1195         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1196             &child, &children) != 0) {
1197
1198                 if (strcmp(type, VDEV_TYPE_DISK) != 0)
1199                         return (0);
1200
1201                 /*
1202                  * We have a disk device.  If this is a whole disk write
1203                  * out the efi partition table, otherwise write zero's to
1204                  * the first 4k of the partition.  This is to ensure that
1205                  * libblkid will not misidentify the partition due to a
1206                  * magic value left by the previous filesystem.
1207                  */
1208                 verify(!nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path));
1209                 verify(!nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
1210                     &wholedisk));
1211
1212                 if (!wholedisk) {
1213                         /*
1214                          * Update device id string for mpath nodes (Linux only)
1215                          */
1216                         if (is_mpath_whole_disk(path))
1217                                 update_vdev_config_dev_strs(nv);
1218
1219                         (void) zero_label(path);
1220                         return (0);
1221                 }
1222
1223                 if (realpath(path, devpath) == NULL) {
1224                         ret = errno;
1225                         (void) fprintf(stderr,
1226                             gettext("cannot resolve path '%s'\n"), path);
1227                         return (ret);
1228                 }
1229
1230                 /*
1231                  * Remove any previously existing symlink from a udev path to
1232                  * the device before labeling the disk.  This ensures that
1233                  * only newly created links are used.  Otherwise there is a
1234                  * window between when udev deletes and recreates the link
1235                  * during which access attempts will fail with ENOENT.
1236                  */
1237                 strlcpy(udevpath, path, MAXPATHLEN);
1238                 (void) zfs_append_partition(udevpath, MAXPATHLEN);
1239
1240                 fd = open(devpath, O_RDWR|O_EXCL);
1241                 if (fd == -1) {
1242                         if (errno == EBUSY)
1243                                 is_exclusive = 1;
1244                 } else {
1245                         (void) close(fd);
1246                 }
1247
1248                 /*
1249                  * If the partition exists, contains a valid spare label,
1250                  * and is opened exclusively there is no need to partition
1251                  * it.  Hot spares have already been partitioned and are
1252                  * held open exclusively by the kernel as a safety measure.
1253                  *
1254                  * If the provided path is for a /dev/disk/ device its
1255                  * symbolic link will be removed, partition table created,
1256                  * and then block until udev creates the new link.
1257                  */
1258                 if (!is_exclusive || !is_spare(NULL, udevpath)) {
1259                         char *devnode = strrchr(devpath, '/') + 1;
1260
1261                         ret = strncmp(udevpath, UDISK_ROOT, strlen(UDISK_ROOT));
1262                         if (ret == 0) {
1263                                 ret = lstat64(udevpath, &statbuf);
1264                                 if (ret == 0 && S_ISLNK(statbuf.st_mode))
1265                                         (void) unlink(udevpath);
1266                         }
1267
1268                         /*
1269                          * When labeling a pool the raw device node name
1270                          * is provided as it appears under /dev/.
1271                          */
1272                         if (zpool_label_disk(g_zfs, zhp, devnode) == -1)
1273                                 return (-1);
1274
1275                         /*
1276                          * Wait for udev to signal the device is available
1277                          * by the provided path.
1278                          */
1279                         ret = zpool_label_disk_wait(udevpath, DISK_LABEL_WAIT);
1280                         if (ret) {
1281                                 (void) fprintf(stderr,
1282                                     gettext("missing link: %s was "
1283                                     "partitioned but %s is missing\n"),
1284                                     devnode, udevpath);
1285                                 return (ret);
1286                         }
1287
1288                         ret = zero_label(udevpath);
1289                         if (ret)
1290                                 return (ret);
1291                 }
1292
1293                 /*
1294                  * Update the path to refer to the partition.  The presence of
1295                  * the 'whole_disk' field indicates to the CLI that we should
1296                  * chop off the partition number when displaying the device in
1297                  * future output.
1298                  */
1299                 verify(nvlist_add_string(nv, ZPOOL_CONFIG_PATH, udevpath) == 0);
1300
1301                 /*
1302                  * Update device id strings for whole disks (Linux only)
1303                  */
1304                 update_vdev_config_dev_strs(nv);
1305
1306                 return (0);
1307         }
1308
1309         for (c = 0; c < children; c++)
1310                 if ((ret = make_disks(zhp, child[c])) != 0)
1311                         return (ret);
1312
1313         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1314             &child, &children) == 0)
1315                 for (c = 0; c < children; c++)
1316                         if ((ret = make_disks(zhp, child[c])) != 0)
1317                                 return (ret);
1318
1319         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1320             &child, &children) == 0)
1321                 for (c = 0; c < children; c++)
1322                         if ((ret = make_disks(zhp, child[c])) != 0)
1323                                 return (ret);
1324
1325         return (0);
1326 }
1327
1328 /*
1329  * Go through and find any devices that are in use.  We rely on libdiskmgt for
1330  * the majority of this task.
1331  */
1332 static boolean_t
1333 is_device_in_use(nvlist_t *config, nvlist_t *nv, boolean_t force,
1334     boolean_t replacing, boolean_t isspare)
1335 {
1336         nvlist_t **child;
1337         uint_t c, children;
1338         char *type, *path;
1339         int ret = 0;
1340         char buf[MAXPATHLEN];
1341         uint64_t wholedisk = B_FALSE;
1342         boolean_t anyinuse = B_FALSE;
1343
1344         verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
1345
1346         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1347             &child, &children) != 0) {
1348
1349                 verify(!nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path));
1350                 if (strcmp(type, VDEV_TYPE_DISK) == 0)
1351                         verify(!nvlist_lookup_uint64(nv,
1352                             ZPOOL_CONFIG_WHOLE_DISK, &wholedisk));
1353
1354                 /*
1355                  * As a generic check, we look to see if this is a replace of a
1356                  * hot spare within the same pool.  If so, we allow it
1357                  * regardless of what libblkid or zpool_in_use() says.
1358                  */
1359                 if (replacing) {
1360                         (void) strlcpy(buf, path, sizeof (buf));
1361                         if (wholedisk) {
1362                                 ret = zfs_append_partition(buf,  sizeof (buf));
1363                                 if (ret == -1)
1364                                         return (-1);
1365                         }
1366
1367                         if (is_spare(config, buf))
1368                                 return (B_FALSE);
1369                 }
1370
1371                 if (strcmp(type, VDEV_TYPE_DISK) == 0)
1372                         ret = check_device(path, force, isspare, wholedisk);
1373
1374                 else if (strcmp(type, VDEV_TYPE_FILE) == 0)
1375                         ret = check_file(path, force, isspare);
1376
1377                 return (ret != 0);
1378         }
1379
1380         for (c = 0; c < children; c++)
1381                 if (is_device_in_use(config, child[c], force, replacing,
1382                     B_FALSE))
1383                         anyinuse = B_TRUE;
1384
1385         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1386             &child, &children) == 0)
1387                 for (c = 0; c < children; c++)
1388                         if (is_device_in_use(config, child[c], force, replacing,
1389                             B_TRUE))
1390                                 anyinuse = B_TRUE;
1391
1392         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1393             &child, &children) == 0)
1394                 for (c = 0; c < children; c++)
1395                         if (is_device_in_use(config, child[c], force, replacing,
1396                             B_FALSE))
1397                                 anyinuse = B_TRUE;
1398
1399         return (anyinuse);
1400 }
1401
1402 static const char *
1403 is_grouping(const char *type, int *mindev, int *maxdev)
1404 {
1405         if (strncmp(type, "raidz", 5) == 0) {
1406                 const char *p = type + 5;
1407                 char *end;
1408                 long nparity;
1409
1410                 if (*p == '\0') {
1411                         nparity = 1;
1412                 } else if (*p == '0') {
1413                         return (NULL); /* no zero prefixes allowed */
1414                 } else {
1415                         errno = 0;
1416                         nparity = strtol(p, &end, 10);
1417                         if (errno != 0 || nparity < 1 || nparity >= 255 ||
1418                             *end != '\0')
1419                                 return (NULL);
1420                 }
1421
1422                 if (mindev != NULL)
1423                         *mindev = nparity + 1;
1424                 if (maxdev != NULL)
1425                         *maxdev = 255;
1426                 return (VDEV_TYPE_RAIDZ);
1427         }
1428
1429         if (maxdev != NULL)
1430                 *maxdev = INT_MAX;
1431
1432         if (strcmp(type, "mirror") == 0) {
1433                 if (mindev != NULL)
1434                         *mindev = 2;
1435                 return (VDEV_TYPE_MIRROR);
1436         }
1437
1438         if (strcmp(type, "spare") == 0) {
1439                 if (mindev != NULL)
1440                         *mindev = 1;
1441                 return (VDEV_TYPE_SPARE);
1442         }
1443
1444         if (strcmp(type, "log") == 0) {
1445                 if (mindev != NULL)
1446                         *mindev = 1;
1447                 return (VDEV_TYPE_LOG);
1448         }
1449
1450         if (strcmp(type, "cache") == 0) {
1451                 if (mindev != NULL)
1452                         *mindev = 1;
1453                 return (VDEV_TYPE_L2CACHE);
1454         }
1455
1456         return (NULL);
1457 }
1458
1459 /*
1460  * Construct a syntactically valid vdev specification,
1461  * and ensure that all devices and files exist and can be opened.
1462  * Note: we don't bother freeing anything in the error paths
1463  * because the program is just going to exit anyway.
1464  */
1465 nvlist_t *
1466 construct_spec(nvlist_t *props, int argc, char **argv)
1467 {
1468         nvlist_t *nvroot, *nv, **top, **spares, **l2cache;
1469         int t, toplevels, mindev, maxdev, nspares, nlogs, nl2cache;
1470         const char *type;
1471         uint64_t is_log;
1472         boolean_t seen_logs;
1473
1474         top = NULL;
1475         toplevels = 0;
1476         spares = NULL;
1477         l2cache = NULL;
1478         nspares = 0;
1479         nlogs = 0;
1480         nl2cache = 0;
1481         is_log = B_FALSE;
1482         seen_logs = B_FALSE;
1483         nvroot = NULL;
1484
1485         while (argc > 0) {
1486                 nv = NULL;
1487
1488                 /*
1489                  * If it's a mirror or raidz, the subsequent arguments are
1490                  * its leaves -- until we encounter the next mirror or raidz.
1491                  */
1492                 if ((type = is_grouping(argv[0], &mindev, &maxdev)) != NULL) {
1493                         nvlist_t **child = NULL;
1494                         int c, children = 0;
1495
1496                         if (strcmp(type, VDEV_TYPE_SPARE) == 0) {
1497                                 if (spares != NULL) {
1498                                         (void) fprintf(stderr,
1499                                             gettext("invalid vdev "
1500                                             "specification: 'spare' can be "
1501                                             "specified only once\n"));
1502                                         goto spec_out;
1503                                 }
1504                                 is_log = B_FALSE;
1505                         }
1506
1507                         if (strcmp(type, VDEV_TYPE_LOG) == 0) {
1508                                 if (seen_logs) {
1509                                         (void) fprintf(stderr,
1510                                             gettext("invalid vdev "
1511                                             "specification: 'log' can be "
1512                                             "specified only once\n"));
1513                                         goto spec_out;
1514                                 }
1515                                 seen_logs = B_TRUE;
1516                                 is_log = B_TRUE;
1517                                 argc--;
1518                                 argv++;
1519                                 /*
1520                                  * A log is not a real grouping device.
1521                                  * We just set is_log and continue.
1522                                  */
1523                                 continue;
1524                         }
1525
1526                         if (strcmp(type, VDEV_TYPE_L2CACHE) == 0) {
1527                                 if (l2cache != NULL) {
1528                                         (void) fprintf(stderr,
1529                                             gettext("invalid vdev "
1530                                             "specification: 'cache' can be "
1531                                             "specified only once\n"));
1532                                         goto spec_out;
1533                                 }
1534                                 is_log = B_FALSE;
1535                         }
1536
1537                         if (is_log) {
1538                                 if (strcmp(type, VDEV_TYPE_MIRROR) != 0) {
1539                                         (void) fprintf(stderr,
1540                                             gettext("invalid vdev "
1541                                             "specification: unsupported 'log' "
1542                                             "device: %s\n"), type);
1543                                         goto spec_out;
1544                                 }
1545                                 nlogs++;
1546                         }
1547
1548                         for (c = 1; c < argc; c++) {
1549                                 if (is_grouping(argv[c], NULL, NULL) != NULL)
1550                                         break;
1551                                 children++;
1552                                 child = realloc(child,
1553                                     children * sizeof (nvlist_t *));
1554                                 if (child == NULL)
1555                                         zpool_no_memory();
1556                                 if ((nv = make_leaf_vdev(props, argv[c],
1557                                     B_FALSE)) == NULL) {
1558                                         for (c = 0; c < children - 1; c++)
1559                                                 nvlist_free(child[c]);
1560                                         free(child);
1561                                         goto spec_out;
1562                                 }
1563
1564                                 child[children - 1] = nv;
1565                         }
1566
1567                         if (children < mindev) {
1568                                 (void) fprintf(stderr, gettext("invalid vdev "
1569                                     "specification: %s requires at least %d "
1570                                     "devices\n"), argv[0], mindev);
1571                                 for (c = 0; c < children; c++)
1572                                         nvlist_free(child[c]);
1573                                 free(child);
1574                                 goto spec_out;
1575                         }
1576
1577                         if (children > maxdev) {
1578                                 (void) fprintf(stderr, gettext("invalid vdev "
1579                                     "specification: %s supports no more than "
1580                                     "%d devices\n"), argv[0], maxdev);
1581                                 for (c = 0; c < children; c++)
1582                                         nvlist_free(child[c]);
1583                                 free(child);
1584                                 goto spec_out;
1585                         }
1586
1587                         argc -= c;
1588                         argv += c;
1589
1590                         if (strcmp(type, VDEV_TYPE_SPARE) == 0) {
1591                                 spares = child;
1592                                 nspares = children;
1593                                 continue;
1594                         } else if (strcmp(type, VDEV_TYPE_L2CACHE) == 0) {
1595                                 l2cache = child;
1596                                 nl2cache = children;
1597                                 continue;
1598                         } else {
1599                                 verify(nvlist_alloc(&nv, NV_UNIQUE_NAME,
1600                                     0) == 0);
1601                                 verify(nvlist_add_string(nv, ZPOOL_CONFIG_TYPE,
1602                                     type) == 0);
1603                                 verify(nvlist_add_uint64(nv,
1604                                     ZPOOL_CONFIG_IS_LOG, is_log) == 0);
1605                                 if (strcmp(type, VDEV_TYPE_RAIDZ) == 0) {
1606                                         verify(nvlist_add_uint64(nv,
1607                                             ZPOOL_CONFIG_NPARITY,
1608                                             mindev - 1) == 0);
1609                                 }
1610                                 verify(nvlist_add_nvlist_array(nv,
1611                                     ZPOOL_CONFIG_CHILDREN, child,
1612                                     children) == 0);
1613
1614                                 for (c = 0; c < children; c++)
1615                                         nvlist_free(child[c]);
1616                                 free(child);
1617                         }
1618                 } else {
1619                         /*
1620                          * We have a device.  Pass off to make_leaf_vdev() to
1621                          * construct the appropriate nvlist describing the vdev.
1622                          */
1623                         if ((nv = make_leaf_vdev(props, argv[0],
1624                             is_log)) == NULL)
1625                                 goto spec_out;
1626
1627                         if (is_log)
1628                                 nlogs++;
1629                         argc--;
1630                         argv++;
1631                 }
1632
1633                 toplevels++;
1634                 top = realloc(top, toplevels * sizeof (nvlist_t *));
1635                 if (top == NULL)
1636                         zpool_no_memory();
1637                 top[toplevels - 1] = nv;
1638         }
1639
1640         if (toplevels == 0 && nspares == 0 && nl2cache == 0) {
1641                 (void) fprintf(stderr, gettext("invalid vdev "
1642                     "specification: at least one toplevel vdev must be "
1643                     "specified\n"));
1644                 goto spec_out;
1645         }
1646
1647         if (seen_logs && nlogs == 0) {
1648                 (void) fprintf(stderr, gettext("invalid vdev specification: "
1649                     "log requires at least 1 device\n"));
1650                 goto spec_out;
1651         }
1652
1653         /*
1654          * Finally, create nvroot and add all top-level vdevs to it.
1655          */
1656         verify(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, 0) == 0);
1657         verify(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
1658             VDEV_TYPE_ROOT) == 0);
1659         verify(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
1660             top, toplevels) == 0);
1661         if (nspares != 0)
1662                 verify(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1663                     spares, nspares) == 0);
1664         if (nl2cache != 0)
1665                 verify(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1666                     l2cache, nl2cache) == 0);
1667
1668 spec_out:
1669         for (t = 0; t < toplevels; t++)
1670                 nvlist_free(top[t]);
1671         for (t = 0; t < nspares; t++)
1672                 nvlist_free(spares[t]);
1673         for (t = 0; t < nl2cache; t++)
1674                 nvlist_free(l2cache[t]);
1675
1676         free(spares);
1677         free(l2cache);
1678         free(top);
1679
1680         return (nvroot);
1681 }
1682
1683 nvlist_t *
1684 split_mirror_vdev(zpool_handle_t *zhp, char *newname, nvlist_t *props,
1685     splitflags_t flags, int argc, char **argv)
1686 {
1687         nvlist_t *newroot = NULL, **child;
1688         uint_t c, children;
1689
1690         if (argc > 0) {
1691                 if ((newroot = construct_spec(props, argc, argv)) == NULL) {
1692                         (void) fprintf(stderr, gettext("Unable to build a "
1693                             "pool from the specified devices\n"));
1694                         return (NULL);
1695                 }
1696
1697                 if (!flags.dryrun && make_disks(zhp, newroot) != 0) {
1698                         nvlist_free(newroot);
1699                         return (NULL);
1700                 }
1701
1702                 /* avoid any tricks in the spec */
1703                 verify(nvlist_lookup_nvlist_array(newroot,
1704                     ZPOOL_CONFIG_CHILDREN, &child, &children) == 0);
1705                 for (c = 0; c < children; c++) {
1706                         char *path;
1707                         const char *type;
1708                         int min, max;
1709
1710                         verify(nvlist_lookup_string(child[c],
1711                             ZPOOL_CONFIG_PATH, &path) == 0);
1712                         if ((type = is_grouping(path, &min, &max)) != NULL) {
1713                                 (void) fprintf(stderr, gettext("Cannot use "
1714                                     "'%s' as a device for splitting\n"), type);
1715                                 nvlist_free(newroot);
1716                                 return (NULL);
1717                         }
1718                 }
1719         }
1720
1721         if (zpool_vdev_split(zhp, newname, &newroot, props, flags) != 0) {
1722                 nvlist_free(newroot);
1723                 return (NULL);
1724         }
1725
1726         return (newroot);
1727 }
1728
1729 /*
1730  * Get and validate the contents of the given vdev specification.  This ensures
1731  * that the nvlist returned is well-formed, that all the devices exist, and that
1732  * they are not currently in use by any other known consumer.  The 'poolconfig'
1733  * parameter is the current configuration of the pool when adding devices
1734  * existing pool, and is used to perform additional checks, such as changing the
1735  * replication level of the pool.  It can be 'NULL' to indicate that this is a
1736  * new pool.  The 'force' flag controls whether devices should be forcefully
1737  * added, even if they appear in use.
1738  */
1739 nvlist_t *
1740 make_root_vdev(zpool_handle_t *zhp, nvlist_t *props, int force, int check_rep,
1741     boolean_t replacing, boolean_t dryrun, int argc, char **argv)
1742 {
1743         nvlist_t *newroot;
1744         nvlist_t *poolconfig = NULL;
1745         is_force = force;
1746
1747         /*
1748          * Construct the vdev specification.  If this is successful, we know
1749          * that we have a valid specification, and that all devices can be
1750          * opened.
1751          */
1752         if ((newroot = construct_spec(props, argc, argv)) == NULL)
1753                 return (NULL);
1754
1755         if (zhp && ((poolconfig = zpool_get_config(zhp, NULL)) == NULL)) {
1756                 nvlist_free(newroot);
1757                 return (NULL);
1758         }
1759
1760         /*
1761          * Validate each device to make sure that its not shared with another
1762          * subsystem.  We do this even if 'force' is set, because there are some
1763          * uses (such as a dedicated dump device) that even '-f' cannot
1764          * override.
1765          */
1766         if (is_device_in_use(poolconfig, newroot, force, replacing, B_FALSE)) {
1767                 nvlist_free(newroot);
1768                 return (NULL);
1769         }
1770
1771         /*
1772          * Check the replication level of the given vdevs and report any errors
1773          * found.  We include the existing pool spec, if any, as we need to
1774          * catch changes against the existing replication level.
1775          */
1776         if (check_rep && check_replication(poolconfig, newroot) != 0) {
1777                 nvlist_free(newroot);
1778                 return (NULL);
1779         }
1780
1781         /*
1782          * Run through the vdev specification and label any whole disks found.
1783          */
1784         if (!dryrun && make_disks(zhp, newroot) != 0) {
1785                 nvlist_free(newroot);
1786                 return (NULL);
1787         }
1788
1789         return (newroot);
1790 }