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