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