]> granicus.if.org Git - zfs/blob - lib/libzfs/libzfs_pool.c
zpool: bogus error for invalid dedupditto value
[zfs] / lib / libzfs / libzfs_pool.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 2015 Nexenta Systems, Inc.  All rights reserved.
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
26  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
27  * Copyright (c) 2018 Datto Inc.
28  * Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
29  * Copyright (c) 2017, Intel Corporation.
30  * Copyright (c) 2018, loli10K <ezomori.nozomu@gmail.com>
31  */
32
33 #include <errno.h>
34 #include <devid.h>
35 #include <libintl.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <strings.h>
39 #include <unistd.h>
40 #include <libgen.h>
41 #include <zone.h>
42 #include <sys/stat.h>
43 #include <sys/efi_partition.h>
44 #include <sys/systeminfo.h>
45 #include <sys/vtoc.h>
46 #include <sys/zfs_ioctl.h>
47 #include <sys/vdev_disk.h>
48 #include <dlfcn.h>
49 #include <libzutil.h>
50
51 #include "zfs_namecheck.h"
52 #include "zfs_prop.h"
53 #include "libzfs_impl.h"
54 #include "zfs_comutil.h"
55 #include "zfeature_common.h"
56
57 static int read_efi_label(nvlist_t *config, diskaddr_t *sb);
58 static boolean_t zpool_vdev_is_interior(const char *name);
59
60 typedef struct prop_flags {
61         int create:1;   /* Validate property on creation */
62         int import:1;   /* Validate property on import */
63 } prop_flags_t;
64
65 /*
66  * ====================================================================
67  *   zpool property functions
68  * ====================================================================
69  */
70
71 static int
72 zpool_get_all_props(zpool_handle_t *zhp)
73 {
74         zfs_cmd_t zc = {"\0"};
75         libzfs_handle_t *hdl = zhp->zpool_hdl;
76
77         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
78
79         if (zcmd_alloc_dst_nvlist(hdl, &zc, 0) != 0)
80                 return (-1);
81
82         while (ioctl(hdl->libzfs_fd, ZFS_IOC_POOL_GET_PROPS, &zc) != 0) {
83                 if (errno == ENOMEM) {
84                         if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
85                                 zcmd_free_nvlists(&zc);
86                                 return (-1);
87                         }
88                 } else {
89                         zcmd_free_nvlists(&zc);
90                         return (-1);
91                 }
92         }
93
94         if (zcmd_read_dst_nvlist(hdl, &zc, &zhp->zpool_props) != 0) {
95                 zcmd_free_nvlists(&zc);
96                 return (-1);
97         }
98
99         zcmd_free_nvlists(&zc);
100
101         return (0);
102 }
103
104 static int
105 zpool_props_refresh(zpool_handle_t *zhp)
106 {
107         nvlist_t *old_props;
108
109         old_props = zhp->zpool_props;
110
111         if (zpool_get_all_props(zhp) != 0)
112                 return (-1);
113
114         nvlist_free(old_props);
115         return (0);
116 }
117
118 static const char *
119 zpool_get_prop_string(zpool_handle_t *zhp, zpool_prop_t prop,
120     zprop_source_t *src)
121 {
122         nvlist_t *nv, *nvl;
123         uint64_t ival;
124         char *value;
125         zprop_source_t source;
126
127         nvl = zhp->zpool_props;
128         if (nvlist_lookup_nvlist(nvl, zpool_prop_to_name(prop), &nv) == 0) {
129                 verify(nvlist_lookup_uint64(nv, ZPROP_SOURCE, &ival) == 0);
130                 source = ival;
131                 verify(nvlist_lookup_string(nv, ZPROP_VALUE, &value) == 0);
132         } else {
133                 source = ZPROP_SRC_DEFAULT;
134                 if ((value = (char *)zpool_prop_default_string(prop)) == NULL)
135                         value = "-";
136         }
137
138         if (src)
139                 *src = source;
140
141         return (value);
142 }
143
144 uint64_t
145 zpool_get_prop_int(zpool_handle_t *zhp, zpool_prop_t prop, zprop_source_t *src)
146 {
147         nvlist_t *nv, *nvl;
148         uint64_t value;
149         zprop_source_t source;
150
151         if (zhp->zpool_props == NULL && zpool_get_all_props(zhp)) {
152                 /*
153                  * zpool_get_all_props() has most likely failed because
154                  * the pool is faulted, but if all we need is the top level
155                  * vdev's guid then get it from the zhp config nvlist.
156                  */
157                 if ((prop == ZPOOL_PROP_GUID) &&
158                     (nvlist_lookup_nvlist(zhp->zpool_config,
159                     ZPOOL_CONFIG_VDEV_TREE, &nv) == 0) &&
160                     (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &value)
161                     == 0)) {
162                         return (value);
163                 }
164                 return (zpool_prop_default_numeric(prop));
165         }
166
167         nvl = zhp->zpool_props;
168         if (nvlist_lookup_nvlist(nvl, zpool_prop_to_name(prop), &nv) == 0) {
169                 verify(nvlist_lookup_uint64(nv, ZPROP_SOURCE, &value) == 0);
170                 source = value;
171                 verify(nvlist_lookup_uint64(nv, ZPROP_VALUE, &value) == 0);
172         } else {
173                 source = ZPROP_SRC_DEFAULT;
174                 value = zpool_prop_default_numeric(prop);
175         }
176
177         if (src)
178                 *src = source;
179
180         return (value);
181 }
182
183 /*
184  * Map VDEV STATE to printed strings.
185  */
186 const char *
187 zpool_state_to_name(vdev_state_t state, vdev_aux_t aux)
188 {
189         switch (state) {
190         case VDEV_STATE_CLOSED:
191         case VDEV_STATE_OFFLINE:
192                 return (gettext("OFFLINE"));
193         case VDEV_STATE_REMOVED:
194                 return (gettext("REMOVED"));
195         case VDEV_STATE_CANT_OPEN:
196                 if (aux == VDEV_AUX_CORRUPT_DATA || aux == VDEV_AUX_BAD_LOG)
197                         return (gettext("FAULTED"));
198                 else if (aux == VDEV_AUX_SPLIT_POOL)
199                         return (gettext("SPLIT"));
200                 else
201                         return (gettext("UNAVAIL"));
202         case VDEV_STATE_FAULTED:
203                 return (gettext("FAULTED"));
204         case VDEV_STATE_DEGRADED:
205                 return (gettext("DEGRADED"));
206         case VDEV_STATE_HEALTHY:
207                 return (gettext("ONLINE"));
208
209         default:
210                 break;
211         }
212
213         return (gettext("UNKNOWN"));
214 }
215
216 /*
217  * Map POOL STATE to printed strings.
218  */
219 const char *
220 zpool_pool_state_to_name(pool_state_t state)
221 {
222         switch (state) {
223         default:
224                 break;
225         case POOL_STATE_ACTIVE:
226                 return (gettext("ACTIVE"));
227         case POOL_STATE_EXPORTED:
228                 return (gettext("EXPORTED"));
229         case POOL_STATE_DESTROYED:
230                 return (gettext("DESTROYED"));
231         case POOL_STATE_SPARE:
232                 return (gettext("SPARE"));
233         case POOL_STATE_L2CACHE:
234                 return (gettext("L2CACHE"));
235         case POOL_STATE_UNINITIALIZED:
236                 return (gettext("UNINITIALIZED"));
237         case POOL_STATE_UNAVAIL:
238                 return (gettext("UNAVAIL"));
239         case POOL_STATE_POTENTIALLY_ACTIVE:
240                 return (gettext("POTENTIALLY_ACTIVE"));
241         }
242
243         return (gettext("UNKNOWN"));
244 }
245
246 /*
247  * Given a pool handle, return the pool health string ("ONLINE", "DEGRADED",
248  * "SUSPENDED", etc).
249  */
250 const char *
251 zpool_get_state_str(zpool_handle_t *zhp)
252 {
253         zpool_errata_t errata;
254         zpool_status_t status;
255         nvlist_t *nvroot;
256         vdev_stat_t *vs;
257         uint_t vsc;
258         const char *str;
259
260         status = zpool_get_status(zhp, NULL, &errata);
261
262         if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
263                 str = gettext("FAULTED");
264         } else if (status == ZPOOL_STATUS_IO_FAILURE_WAIT ||
265             status == ZPOOL_STATUS_IO_FAILURE_MMP) {
266                 str = gettext("SUSPENDED");
267         } else {
268                 verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
269                     ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
270                 verify(nvlist_lookup_uint64_array(nvroot,
271                     ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
272                     == 0);
273                 str = zpool_state_to_name(vs->vs_state, vs->vs_aux);
274         }
275         return (str);
276 }
277
278 /*
279  * Get a zpool property value for 'prop' and return the value in
280  * a pre-allocated buffer.
281  */
282 int
283 zpool_get_prop(zpool_handle_t *zhp, zpool_prop_t prop, char *buf,
284     size_t len, zprop_source_t *srctype, boolean_t literal)
285 {
286         uint64_t intval;
287         const char *strval;
288         zprop_source_t src = ZPROP_SRC_NONE;
289
290         if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
291                 switch (prop) {
292                 case ZPOOL_PROP_NAME:
293                         (void) strlcpy(buf, zpool_get_name(zhp), len);
294                         break;
295
296                 case ZPOOL_PROP_HEALTH:
297                         (void) strlcpy(buf, zpool_get_state_str(zhp), len);
298                         break;
299
300                 case ZPOOL_PROP_GUID:
301                         intval = zpool_get_prop_int(zhp, prop, &src);
302                         (void) snprintf(buf, len, "%llu", (u_longlong_t)intval);
303                         break;
304
305                 case ZPOOL_PROP_ALTROOT:
306                 case ZPOOL_PROP_CACHEFILE:
307                 case ZPOOL_PROP_COMMENT:
308                         if (zhp->zpool_props != NULL ||
309                             zpool_get_all_props(zhp) == 0) {
310                                 (void) strlcpy(buf,
311                                     zpool_get_prop_string(zhp, prop, &src),
312                                     len);
313                                 break;
314                         }
315                         /* FALLTHROUGH */
316                 default:
317                         (void) strlcpy(buf, "-", len);
318                         break;
319                 }
320
321                 if (srctype != NULL)
322                         *srctype = src;
323                 return (0);
324         }
325
326         if (zhp->zpool_props == NULL && zpool_get_all_props(zhp) &&
327             prop != ZPOOL_PROP_NAME)
328                 return (-1);
329
330         switch (zpool_prop_get_type(prop)) {
331         case PROP_TYPE_STRING:
332                 (void) strlcpy(buf, zpool_get_prop_string(zhp, prop, &src),
333                     len);
334                 break;
335
336         case PROP_TYPE_NUMBER:
337                 intval = zpool_get_prop_int(zhp, prop, &src);
338
339                 switch (prop) {
340                 case ZPOOL_PROP_SIZE:
341                 case ZPOOL_PROP_ALLOCATED:
342                 case ZPOOL_PROP_FREE:
343                 case ZPOOL_PROP_FREEING:
344                 case ZPOOL_PROP_LEAKED:
345                 case ZPOOL_PROP_ASHIFT:
346                         if (literal)
347                                 (void) snprintf(buf, len, "%llu",
348                                     (u_longlong_t)intval);
349                         else
350                                 (void) zfs_nicenum(intval, buf, len);
351                         break;
352
353                 case ZPOOL_PROP_EXPANDSZ:
354                 case ZPOOL_PROP_CHECKPOINT:
355                         if (intval == 0) {
356                                 (void) strlcpy(buf, "-", len);
357                         } else if (literal) {
358                                 (void) snprintf(buf, len, "%llu",
359                                     (u_longlong_t)intval);
360                         } else {
361                                 (void) zfs_nicebytes(intval, buf, len);
362                         }
363                         break;
364
365                 case ZPOOL_PROP_CAPACITY:
366                         if (literal) {
367                                 (void) snprintf(buf, len, "%llu",
368                                     (u_longlong_t)intval);
369                         } else {
370                                 (void) snprintf(buf, len, "%llu%%",
371                                     (u_longlong_t)intval);
372                         }
373                         break;
374
375                 case ZPOOL_PROP_FRAGMENTATION:
376                         if (intval == UINT64_MAX) {
377                                 (void) strlcpy(buf, "-", len);
378                         } else if (literal) {
379                                 (void) snprintf(buf, len, "%llu",
380                                     (u_longlong_t)intval);
381                         } else {
382                                 (void) snprintf(buf, len, "%llu%%",
383                                     (u_longlong_t)intval);
384                         }
385                         break;
386
387                 case ZPOOL_PROP_DEDUPRATIO:
388                         if (literal)
389                                 (void) snprintf(buf, len, "%llu.%02llu",
390                                     (u_longlong_t)(intval / 100),
391                                     (u_longlong_t)(intval % 100));
392                         else
393                                 (void) snprintf(buf, len, "%llu.%02llux",
394                                     (u_longlong_t)(intval / 100),
395                                     (u_longlong_t)(intval % 100));
396                         break;
397
398                 case ZPOOL_PROP_HEALTH:
399                         (void) strlcpy(buf, zpool_get_state_str(zhp), len);
400                         break;
401                 case ZPOOL_PROP_VERSION:
402                         if (intval >= SPA_VERSION_FEATURES) {
403                                 (void) snprintf(buf, len, "-");
404                                 break;
405                         }
406                         /* FALLTHROUGH */
407                 default:
408                         (void) snprintf(buf, len, "%llu", (u_longlong_t)intval);
409                 }
410                 break;
411
412         case PROP_TYPE_INDEX:
413                 intval = zpool_get_prop_int(zhp, prop, &src);
414                 if (zpool_prop_index_to_string(prop, intval, &strval)
415                     != 0)
416                         return (-1);
417                 (void) strlcpy(buf, strval, len);
418                 break;
419
420         default:
421                 abort();
422         }
423
424         if (srctype)
425                 *srctype = src;
426
427         return (0);
428 }
429
430 /*
431  * Check if the bootfs name has the same pool name as it is set to.
432  * Assuming bootfs is a valid dataset name.
433  */
434 static boolean_t
435 bootfs_name_valid(const char *pool, char *bootfs)
436 {
437         int len = strlen(pool);
438         if (bootfs[0] == '\0')
439                 return (B_TRUE);
440
441         if (!zfs_name_valid(bootfs, ZFS_TYPE_FILESYSTEM|ZFS_TYPE_SNAPSHOT))
442                 return (B_FALSE);
443
444         if (strncmp(pool, bootfs, len) == 0 &&
445             (bootfs[len] == '/' || bootfs[len] == '\0'))
446                 return (B_TRUE);
447
448         return (B_FALSE);
449 }
450
451 boolean_t
452 zpool_is_bootable(zpool_handle_t *zhp)
453 {
454         char bootfs[ZFS_MAX_DATASET_NAME_LEN];
455
456         return (zpool_get_prop(zhp, ZPOOL_PROP_BOOTFS, bootfs,
457             sizeof (bootfs), NULL, B_FALSE) == 0 && strncmp(bootfs, "-",
458             sizeof (bootfs)) != 0);
459 }
460
461
462 /*
463  * Given an nvlist of zpool properties to be set, validate that they are
464  * correct, and parse any numeric properties (index, boolean, etc) if they are
465  * specified as strings.
466  */
467 static nvlist_t *
468 zpool_valid_proplist(libzfs_handle_t *hdl, const char *poolname,
469     nvlist_t *props, uint64_t version, prop_flags_t flags, char *errbuf)
470 {
471         nvpair_t *elem;
472         nvlist_t *retprops;
473         zpool_prop_t prop;
474         char *strval;
475         uint64_t intval;
476         char *slash, *check;
477         struct stat64 statbuf;
478         zpool_handle_t *zhp;
479
480         if (nvlist_alloc(&retprops, NV_UNIQUE_NAME, 0) != 0) {
481                 (void) no_memory(hdl);
482                 return (NULL);
483         }
484
485         elem = NULL;
486         while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
487                 const char *propname = nvpair_name(elem);
488
489                 prop = zpool_name_to_prop(propname);
490                 if (prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname)) {
491                         int err;
492                         char *fname = strchr(propname, '@') + 1;
493
494                         err = zfeature_lookup_name(fname, NULL);
495                         if (err != 0) {
496                                 ASSERT3U(err, ==, ENOENT);
497                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
498                                     "invalid feature '%s'"), fname);
499                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
500                                 goto error;
501                         }
502
503                         if (nvpair_type(elem) != DATA_TYPE_STRING) {
504                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
505                                     "'%s' must be a string"), propname);
506                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
507                                 goto error;
508                         }
509
510                         (void) nvpair_value_string(elem, &strval);
511                         if (strcmp(strval, ZFS_FEATURE_ENABLED) != 0 &&
512                             strcmp(strval, ZFS_FEATURE_DISABLED) != 0) {
513                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
514                                     "property '%s' can only be set to "
515                                     "'enabled' or 'disabled'"), propname);
516                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
517                                 goto error;
518                         }
519
520                         if (!flags.create &&
521                             strcmp(strval, ZFS_FEATURE_DISABLED) == 0) {
522                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
523                                     "property '%s' can only be set to "
524                                     "'disabled' at creation time"), propname);
525                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
526                                 goto error;
527                         }
528
529                         if (nvlist_add_uint64(retprops, propname, 0) != 0) {
530                                 (void) no_memory(hdl);
531                                 goto error;
532                         }
533                         continue;
534                 }
535
536                 /*
537                  * Make sure this property is valid and applies to this type.
538                  */
539                 if (prop == ZPOOL_PROP_INVAL) {
540                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
541                             "invalid property '%s'"), propname);
542                         (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
543                         goto error;
544                 }
545
546                 if (zpool_prop_readonly(prop)) {
547                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' "
548                             "is readonly"), propname);
549                         (void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
550                         goto error;
551                 }
552
553                 if (!flags.create && zpool_prop_setonce(prop)) {
554                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
555                             "property '%s' can only be set at "
556                             "creation time"), propname);
557                         (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
558                         goto error;
559                 }
560
561                 if (zprop_parse_value(hdl, elem, prop, ZFS_TYPE_POOL, retprops,
562                     &strval, &intval, errbuf) != 0)
563                         goto error;
564
565                 /*
566                  * Perform additional checking for specific properties.
567                  */
568                 switch (prop) {
569                 case ZPOOL_PROP_VERSION:
570                         if (intval < version ||
571                             !SPA_VERSION_IS_SUPPORTED(intval)) {
572                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
573                                     "property '%s' number %d is invalid."),
574                                     propname, intval);
575                                 (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
576                                 goto error;
577                         }
578                         break;
579
580                 case ZPOOL_PROP_ASHIFT:
581                         if (intval != 0 &&
582                             (intval < ASHIFT_MIN || intval > ASHIFT_MAX)) {
583                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
584                                     "property '%s' number %d is invalid, only "
585                                     "values between %" PRId32 " and "
586                                     "%" PRId32 " are allowed."),
587                                     propname, intval, ASHIFT_MIN, ASHIFT_MAX);
588                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
589                                 goto error;
590                         }
591                         break;
592
593                 case ZPOOL_PROP_BOOTFS:
594                         if (flags.create || flags.import) {
595                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
596                                     "property '%s' cannot be set at creation "
597                                     "or import time"), propname);
598                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
599                                 goto error;
600                         }
601
602                         if (version < SPA_VERSION_BOOTFS) {
603                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
604                                     "pool must be upgraded to support "
605                                     "'%s' property"), propname);
606                                 (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
607                                 goto error;
608                         }
609
610                         /*
611                          * bootfs property value has to be a dataset name and
612                          * the dataset has to be in the same pool as it sets to.
613                          */
614                         if (!bootfs_name_valid(poolname, strval)) {
615                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' "
616                                     "is an invalid name"), strval);
617                                 (void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
618                                 goto error;
619                         }
620
621                         if ((zhp = zpool_open_canfail(hdl, poolname)) == NULL) {
622                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
623                                     "could not open pool '%s'"), poolname);
624                                 (void) zfs_error(hdl, EZFS_OPENFAILED, errbuf);
625                                 goto error;
626                         }
627                         zpool_close(zhp);
628                         break;
629
630                 case ZPOOL_PROP_ALTROOT:
631                         if (!flags.create && !flags.import) {
632                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
633                                     "property '%s' can only be set during pool "
634                                     "creation or import"), propname);
635                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
636                                 goto error;
637                         }
638
639                         if (strval[0] != '/') {
640                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
641                                     "bad alternate root '%s'"), strval);
642                                 (void) zfs_error(hdl, EZFS_BADPATH, errbuf);
643                                 goto error;
644                         }
645                         break;
646
647                 case ZPOOL_PROP_CACHEFILE:
648                         if (strval[0] == '\0')
649                                 break;
650
651                         if (strcmp(strval, "none") == 0)
652                                 break;
653
654                         if (strval[0] != '/') {
655                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
656                                     "property '%s' must be empty, an "
657                                     "absolute path, or 'none'"), propname);
658                                 (void) zfs_error(hdl, EZFS_BADPATH, errbuf);
659                                 goto error;
660                         }
661
662                         slash = strrchr(strval, '/');
663
664                         if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
665                             strcmp(slash, "/..") == 0) {
666                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
667                                     "'%s' is not a valid file"), strval);
668                                 (void) zfs_error(hdl, EZFS_BADPATH, errbuf);
669                                 goto error;
670                         }
671
672                         *slash = '\0';
673
674                         if (strval[0] != '\0' &&
675                             (stat64(strval, &statbuf) != 0 ||
676                             !S_ISDIR(statbuf.st_mode))) {
677                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
678                                     "'%s' is not a valid directory"),
679                                     strval);
680                                 (void) zfs_error(hdl, EZFS_BADPATH, errbuf);
681                                 goto error;
682                         }
683
684                         *slash = '/';
685                         break;
686
687                 case ZPOOL_PROP_COMMENT:
688                         for (check = strval; *check != '\0'; check++) {
689                                 if (!isprint(*check)) {
690                                         zfs_error_aux(hdl,
691                                             dgettext(TEXT_DOMAIN,
692                                             "comment may only have printable "
693                                             "characters"));
694                                         (void) zfs_error(hdl, EZFS_BADPROP,
695                                             errbuf);
696                                         goto error;
697                                 }
698                         }
699                         if (strlen(strval) > ZPROP_MAX_COMMENT) {
700                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
701                                     "comment must not exceed %d characters"),
702                                     ZPROP_MAX_COMMENT);
703                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
704                                 goto error;
705                         }
706                         break;
707                 case ZPOOL_PROP_READONLY:
708                         if (!flags.import) {
709                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
710                                     "property '%s' can only be set at "
711                                     "import time"), propname);
712                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
713                                 goto error;
714                         }
715                         break;
716                 case ZPOOL_PROP_MULTIHOST:
717                         if (get_system_hostid() == 0) {
718                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
719                                     "requires a non-zero system hostid"));
720                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
721                                 goto error;
722                         }
723                         break;
724                 case ZPOOL_PROP_DEDUPDITTO:
725                         if (intval < ZIO_DEDUPDITTO_MIN && intval != 0) {
726                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
727                                     "property '%s' value %d is invalid; only "
728                                     "values of 0 or >= %" PRId32 " are allowed "
729                                     "for this property."),
730                                     propname, intval, ZIO_DEDUPDITTO_MIN);
731                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
732                                 goto error;
733                         }
734                         break;
735
736                 default:
737                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
738                             "property '%s'(%d) not defined"), propname, prop);
739                         break;
740                 }
741         }
742
743         return (retprops);
744 error:
745         nvlist_free(retprops);
746         return (NULL);
747 }
748
749 /*
750  * Set zpool property : propname=propval.
751  */
752 int
753 zpool_set_prop(zpool_handle_t *zhp, const char *propname, const char *propval)
754 {
755         zfs_cmd_t zc = {"\0"};
756         int ret = -1;
757         char errbuf[1024];
758         nvlist_t *nvl = NULL;
759         nvlist_t *realprops;
760         uint64_t version;
761         prop_flags_t flags = { 0 };
762
763         (void) snprintf(errbuf, sizeof (errbuf),
764             dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
765             zhp->zpool_name);
766
767         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
768                 return (no_memory(zhp->zpool_hdl));
769
770         if (nvlist_add_string(nvl, propname, propval) != 0) {
771                 nvlist_free(nvl);
772                 return (no_memory(zhp->zpool_hdl));
773         }
774
775         version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
776         if ((realprops = zpool_valid_proplist(zhp->zpool_hdl,
777             zhp->zpool_name, nvl, version, flags, errbuf)) == NULL) {
778                 nvlist_free(nvl);
779                 return (-1);
780         }
781
782         nvlist_free(nvl);
783         nvl = realprops;
784
785         /*
786          * Execute the corresponding ioctl() to set this property.
787          */
788         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
789
790         if (zcmd_write_src_nvlist(zhp->zpool_hdl, &zc, nvl) != 0) {
791                 nvlist_free(nvl);
792                 return (-1);
793         }
794
795         ret = zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_SET_PROPS, &zc);
796
797         zcmd_free_nvlists(&zc);
798         nvlist_free(nvl);
799
800         if (ret)
801                 (void) zpool_standard_error(zhp->zpool_hdl, errno, errbuf);
802         else
803                 (void) zpool_props_refresh(zhp);
804
805         return (ret);
806 }
807
808 int
809 zpool_expand_proplist(zpool_handle_t *zhp, zprop_list_t **plp)
810 {
811         libzfs_handle_t *hdl = zhp->zpool_hdl;
812         zprop_list_t *entry;
813         char buf[ZFS_MAXPROPLEN];
814         nvlist_t *features = NULL;
815         nvpair_t *nvp;
816         zprop_list_t **last;
817         boolean_t firstexpand = (NULL == *plp);
818         int i;
819
820         if (zprop_expand_list(hdl, plp, ZFS_TYPE_POOL) != 0)
821                 return (-1);
822
823         last = plp;
824         while (*last != NULL)
825                 last = &(*last)->pl_next;
826
827         if ((*plp)->pl_all)
828                 features = zpool_get_features(zhp);
829
830         if ((*plp)->pl_all && firstexpand) {
831                 for (i = 0; i < SPA_FEATURES; i++) {
832                         zprop_list_t *entry = zfs_alloc(hdl,
833                             sizeof (zprop_list_t));
834                         entry->pl_prop = ZPROP_INVAL;
835                         entry->pl_user_prop = zfs_asprintf(hdl, "feature@%s",
836                             spa_feature_table[i].fi_uname);
837                         entry->pl_width = strlen(entry->pl_user_prop);
838                         entry->pl_all = B_TRUE;
839
840                         *last = entry;
841                         last = &entry->pl_next;
842                 }
843         }
844
845         /* add any unsupported features */
846         for (nvp = nvlist_next_nvpair(features, NULL);
847             nvp != NULL; nvp = nvlist_next_nvpair(features, nvp)) {
848                 char *propname;
849                 boolean_t found;
850                 zprop_list_t *entry;
851
852                 if (zfeature_is_supported(nvpair_name(nvp)))
853                         continue;
854
855                 propname = zfs_asprintf(hdl, "unsupported@%s",
856                     nvpair_name(nvp));
857
858                 /*
859                  * Before adding the property to the list make sure that no
860                  * other pool already added the same property.
861                  */
862                 found = B_FALSE;
863                 entry = *plp;
864                 while (entry != NULL) {
865                         if (entry->pl_user_prop != NULL &&
866                             strcmp(propname, entry->pl_user_prop) == 0) {
867                                 found = B_TRUE;
868                                 break;
869                         }
870                         entry = entry->pl_next;
871                 }
872                 if (found) {
873                         free(propname);
874                         continue;
875                 }
876
877                 entry = zfs_alloc(hdl, sizeof (zprop_list_t));
878                 entry->pl_prop = ZPROP_INVAL;
879                 entry->pl_user_prop = propname;
880                 entry->pl_width = strlen(entry->pl_user_prop);
881                 entry->pl_all = B_TRUE;
882
883                 *last = entry;
884                 last = &entry->pl_next;
885         }
886
887         for (entry = *plp; entry != NULL; entry = entry->pl_next) {
888
889                 if (entry->pl_fixed)
890                         continue;
891
892                 if (entry->pl_prop != ZPROP_INVAL &&
893                     zpool_get_prop(zhp, entry->pl_prop, buf, sizeof (buf),
894                     NULL, B_FALSE) == 0) {
895                         if (strlen(buf) > entry->pl_width)
896                                 entry->pl_width = strlen(buf);
897                 }
898         }
899
900         return (0);
901 }
902
903 /*
904  * Get the state for the given feature on the given ZFS pool.
905  */
906 int
907 zpool_prop_get_feature(zpool_handle_t *zhp, const char *propname, char *buf,
908     size_t len)
909 {
910         uint64_t refcount;
911         boolean_t found = B_FALSE;
912         nvlist_t *features = zpool_get_features(zhp);
913         boolean_t supported;
914         const char *feature = strchr(propname, '@') + 1;
915
916         supported = zpool_prop_feature(propname);
917         ASSERT(supported || zpool_prop_unsupported(propname));
918
919         /*
920          * Convert from feature name to feature guid. This conversion is
921          * unnecessary for unsupported@... properties because they already
922          * use guids.
923          */
924         if (supported) {
925                 int ret;
926                 spa_feature_t fid;
927
928                 ret = zfeature_lookup_name(feature, &fid);
929                 if (ret != 0) {
930                         (void) strlcpy(buf, "-", len);
931                         return (ENOTSUP);
932                 }
933                 feature = spa_feature_table[fid].fi_guid;
934         }
935
936         if (nvlist_lookup_uint64(features, feature, &refcount) == 0)
937                 found = B_TRUE;
938
939         if (supported) {
940                 if (!found) {
941                         (void) strlcpy(buf, ZFS_FEATURE_DISABLED, len);
942                 } else  {
943                         if (refcount == 0)
944                                 (void) strlcpy(buf, ZFS_FEATURE_ENABLED, len);
945                         else
946                                 (void) strlcpy(buf, ZFS_FEATURE_ACTIVE, len);
947                 }
948         } else {
949                 if (found) {
950                         if (refcount == 0) {
951                                 (void) strcpy(buf, ZFS_UNSUPPORTED_INACTIVE);
952                         } else {
953                                 (void) strcpy(buf, ZFS_UNSUPPORTED_READONLY);
954                         }
955                 } else {
956                         (void) strlcpy(buf, "-", len);
957                         return (ENOTSUP);
958                 }
959         }
960
961         return (0);
962 }
963
964 /*
965  * Validate the given pool name, optionally putting an extended error message in
966  * 'buf'.
967  */
968 boolean_t
969 zpool_name_valid(libzfs_handle_t *hdl, boolean_t isopen, const char *pool)
970 {
971         namecheck_err_t why;
972         char what;
973         int ret;
974
975         ret = pool_namecheck(pool, &why, &what);
976
977         /*
978          * The rules for reserved pool names were extended at a later point.
979          * But we need to support users with existing pools that may now be
980          * invalid.  So we only check for this expanded set of names during a
981          * create (or import), and only in userland.
982          */
983         if (ret == 0 && !isopen &&
984             (strncmp(pool, "mirror", 6) == 0 ||
985             strncmp(pool, "raidz", 5) == 0 ||
986             strncmp(pool, "spare", 5) == 0 ||
987             strcmp(pool, "log") == 0)) {
988                 if (hdl != NULL)
989                         zfs_error_aux(hdl,
990                             dgettext(TEXT_DOMAIN, "name is reserved"));
991                 return (B_FALSE);
992         }
993
994
995         if (ret != 0) {
996                 if (hdl != NULL) {
997                         switch (why) {
998                         case NAME_ERR_TOOLONG:
999                                 zfs_error_aux(hdl,
1000                                     dgettext(TEXT_DOMAIN, "name is too long"));
1001                                 break;
1002
1003                         case NAME_ERR_INVALCHAR:
1004                                 zfs_error_aux(hdl,
1005                                     dgettext(TEXT_DOMAIN, "invalid character "
1006                                     "'%c' in pool name"), what);
1007                                 break;
1008
1009                         case NAME_ERR_NOLETTER:
1010                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1011                                     "name must begin with a letter"));
1012                                 break;
1013
1014                         case NAME_ERR_RESERVED:
1015                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1016                                     "name is reserved"));
1017                                 break;
1018
1019                         case NAME_ERR_DISKLIKE:
1020                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1021                                     "pool name is reserved"));
1022                                 break;
1023
1024                         case NAME_ERR_LEADING_SLASH:
1025                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1026                                     "leading slash in name"));
1027                                 break;
1028
1029                         case NAME_ERR_EMPTY_COMPONENT:
1030                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1031                                     "empty component in name"));
1032                                 break;
1033
1034                         case NAME_ERR_TRAILING_SLASH:
1035                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1036                                     "trailing slash in name"));
1037                                 break;
1038
1039                         case NAME_ERR_MULTIPLE_DELIMITERS:
1040                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1041                                     "multiple '@' and/or '#' delimiters in "
1042                                     "name"));
1043                                 break;
1044
1045                         case NAME_ERR_NO_AT:
1046                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1047                                     "permission set is missing '@'"));
1048                                 break;
1049
1050                         default:
1051                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1052                                     "(%d) not defined"), why);
1053                                 break;
1054                         }
1055                 }
1056                 return (B_FALSE);
1057         }
1058
1059         return (B_TRUE);
1060 }
1061
1062 /*
1063  * Open a handle to the given pool, even if the pool is currently in the FAULTED
1064  * state.
1065  */
1066 zpool_handle_t *
1067 zpool_open_canfail(libzfs_handle_t *hdl, const char *pool)
1068 {
1069         zpool_handle_t *zhp;
1070         boolean_t missing;
1071
1072         /*
1073          * Make sure the pool name is valid.
1074          */
1075         if (!zpool_name_valid(hdl, B_TRUE, pool)) {
1076                 (void) zfs_error_fmt(hdl, EZFS_INVALIDNAME,
1077                     dgettext(TEXT_DOMAIN, "cannot open '%s'"),
1078                     pool);
1079                 return (NULL);
1080         }
1081
1082         if ((zhp = zfs_alloc(hdl, sizeof (zpool_handle_t))) == NULL)
1083                 return (NULL);
1084
1085         zhp->zpool_hdl = hdl;
1086         (void) strlcpy(zhp->zpool_name, pool, sizeof (zhp->zpool_name));
1087
1088         if (zpool_refresh_stats(zhp, &missing) != 0) {
1089                 zpool_close(zhp);
1090                 return (NULL);
1091         }
1092
1093         if (missing) {
1094                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "no such pool"));
1095                 (void) zfs_error_fmt(hdl, EZFS_NOENT,
1096                     dgettext(TEXT_DOMAIN, "cannot open '%s'"), pool);
1097                 zpool_close(zhp);
1098                 return (NULL);
1099         }
1100
1101         return (zhp);
1102 }
1103
1104 /*
1105  * Like the above, but silent on error.  Used when iterating over pools (because
1106  * the configuration cache may be out of date).
1107  */
1108 int
1109 zpool_open_silent(libzfs_handle_t *hdl, const char *pool, zpool_handle_t **ret)
1110 {
1111         zpool_handle_t *zhp;
1112         boolean_t missing;
1113
1114         if ((zhp = zfs_alloc(hdl, sizeof (zpool_handle_t))) == NULL)
1115                 return (-1);
1116
1117         zhp->zpool_hdl = hdl;
1118         (void) strlcpy(zhp->zpool_name, pool, sizeof (zhp->zpool_name));
1119
1120         if (zpool_refresh_stats(zhp, &missing) != 0) {
1121                 zpool_close(zhp);
1122                 return (-1);
1123         }
1124
1125         if (missing) {
1126                 zpool_close(zhp);
1127                 *ret = NULL;
1128                 return (0);
1129         }
1130
1131         *ret = zhp;
1132         return (0);
1133 }
1134
1135 /*
1136  * Similar to zpool_open_canfail(), but refuses to open pools in the faulted
1137  * state.
1138  */
1139 zpool_handle_t *
1140 zpool_open(libzfs_handle_t *hdl, const char *pool)
1141 {
1142         zpool_handle_t *zhp;
1143
1144         if ((zhp = zpool_open_canfail(hdl, pool)) == NULL)
1145                 return (NULL);
1146
1147         if (zhp->zpool_state == POOL_STATE_UNAVAIL) {
1148                 (void) zfs_error_fmt(hdl, EZFS_POOLUNAVAIL,
1149                     dgettext(TEXT_DOMAIN, "cannot open '%s'"), zhp->zpool_name);
1150                 zpool_close(zhp);
1151                 return (NULL);
1152         }
1153
1154         return (zhp);
1155 }
1156
1157 /*
1158  * Close the handle.  Simply frees the memory associated with the handle.
1159  */
1160 void
1161 zpool_close(zpool_handle_t *zhp)
1162 {
1163         nvlist_free(zhp->zpool_config);
1164         nvlist_free(zhp->zpool_old_config);
1165         nvlist_free(zhp->zpool_props);
1166         free(zhp);
1167 }
1168
1169 /*
1170  * Return the name of the pool.
1171  */
1172 const char *
1173 zpool_get_name(zpool_handle_t *zhp)
1174 {
1175         return (zhp->zpool_name);
1176 }
1177
1178
1179 /*
1180  * Return the state of the pool (ACTIVE or UNAVAILABLE)
1181  */
1182 int
1183 zpool_get_state(zpool_handle_t *zhp)
1184 {
1185         return (zhp->zpool_state);
1186 }
1187
1188 /*
1189  * Check if vdev list contains a special vdev
1190  */
1191 static boolean_t
1192 zpool_has_special_vdev(nvlist_t *nvroot)
1193 {
1194         nvlist_t **child;
1195         uint_t children;
1196
1197         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN, &child,
1198             &children) == 0) {
1199                 for (uint_t c = 0; c < children; c++) {
1200                         char *bias;
1201
1202                         if (nvlist_lookup_string(child[c],
1203                             ZPOOL_CONFIG_ALLOCATION_BIAS, &bias) == 0 &&
1204                             strcmp(bias, VDEV_ALLOC_BIAS_SPECIAL) == 0) {
1205                                 return (B_TRUE);
1206                         }
1207                 }
1208         }
1209         return (B_FALSE);
1210 }
1211
1212 /*
1213  * Create the named pool, using the provided vdev list.  It is assumed
1214  * that the consumer has already validated the contents of the nvlist, so we
1215  * don't have to worry about error semantics.
1216  */
1217 int
1218 zpool_create(libzfs_handle_t *hdl, const char *pool, nvlist_t *nvroot,
1219     nvlist_t *props, nvlist_t *fsprops)
1220 {
1221         zfs_cmd_t zc = {"\0"};
1222         nvlist_t *zc_fsprops = NULL;
1223         nvlist_t *zc_props = NULL;
1224         nvlist_t *hidden_args = NULL;
1225         uint8_t *wkeydata = NULL;
1226         uint_t wkeylen = 0;
1227         char msg[1024];
1228         int ret = -1;
1229
1230         (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1231             "cannot create '%s'"), pool);
1232
1233         if (!zpool_name_valid(hdl, B_FALSE, pool))
1234                 return (zfs_error(hdl, EZFS_INVALIDNAME, msg));
1235
1236         if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
1237                 return (-1);
1238
1239         if (props) {
1240                 prop_flags_t flags = { .create = B_TRUE, .import = B_FALSE };
1241
1242                 if ((zc_props = zpool_valid_proplist(hdl, pool, props,
1243                     SPA_VERSION_1, flags, msg)) == NULL) {
1244                         goto create_failed;
1245                 }
1246         }
1247
1248         if (fsprops) {
1249                 uint64_t zoned;
1250                 char *zonestr;
1251
1252                 zoned = ((nvlist_lookup_string(fsprops,
1253                     zfs_prop_to_name(ZFS_PROP_ZONED), &zonestr) == 0) &&
1254                     strcmp(zonestr, "on") == 0);
1255
1256                 if ((zc_fsprops = zfs_valid_proplist(hdl, ZFS_TYPE_FILESYSTEM,
1257                     fsprops, zoned, NULL, NULL, B_TRUE, msg)) == NULL) {
1258                         goto create_failed;
1259                 }
1260
1261                 if (nvlist_exists(zc_fsprops,
1262                     zfs_prop_to_name(ZFS_PROP_SPECIAL_SMALL_BLOCKS)) &&
1263                     !zpool_has_special_vdev(nvroot)) {
1264                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1265                             "%s property requires a special vdev"),
1266                             zfs_prop_to_name(ZFS_PROP_SPECIAL_SMALL_BLOCKS));
1267                         (void) zfs_error(hdl, EZFS_BADPROP, msg);
1268                         goto create_failed;
1269                 }
1270
1271                 if (!zc_props &&
1272                     (nvlist_alloc(&zc_props, NV_UNIQUE_NAME, 0) != 0)) {
1273                         goto create_failed;
1274                 }
1275                 if (zfs_crypto_create(hdl, NULL, zc_fsprops, props, B_TRUE,
1276                     &wkeydata, &wkeylen) != 0) {
1277                         zfs_error(hdl, EZFS_CRYPTOFAILED, msg);
1278                         goto create_failed;
1279                 }
1280                 if (nvlist_add_nvlist(zc_props,
1281                     ZPOOL_ROOTFS_PROPS, zc_fsprops) != 0) {
1282                         goto create_failed;
1283                 }
1284                 if (wkeydata != NULL) {
1285                         if (nvlist_alloc(&hidden_args, NV_UNIQUE_NAME, 0) != 0)
1286                                 goto create_failed;
1287
1288                         if (nvlist_add_uint8_array(hidden_args, "wkeydata",
1289                             wkeydata, wkeylen) != 0)
1290                                 goto create_failed;
1291
1292                         if (nvlist_add_nvlist(zc_props, ZPOOL_HIDDEN_ARGS,
1293                             hidden_args) != 0)
1294                                 goto create_failed;
1295                 }
1296         }
1297
1298         if (zc_props && zcmd_write_src_nvlist(hdl, &zc, zc_props) != 0)
1299                 goto create_failed;
1300
1301         (void) strlcpy(zc.zc_name, pool, sizeof (zc.zc_name));
1302
1303         if ((ret = zfs_ioctl(hdl, ZFS_IOC_POOL_CREATE, &zc)) != 0) {
1304
1305                 zcmd_free_nvlists(&zc);
1306                 nvlist_free(zc_props);
1307                 nvlist_free(zc_fsprops);
1308                 nvlist_free(hidden_args);
1309                 if (wkeydata != NULL)
1310                         free(wkeydata);
1311
1312                 switch (errno) {
1313                 case EBUSY:
1314                         /*
1315                          * This can happen if the user has specified the same
1316                          * device multiple times.  We can't reliably detect this
1317                          * until we try to add it and see we already have a
1318                          * label.  This can also happen under if the device is
1319                          * part of an active md or lvm device.
1320                          */
1321                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1322                             "one or more vdevs refer to the same device, or "
1323                             "one of\nthe devices is part of an active md or "
1324                             "lvm device"));
1325                         return (zfs_error(hdl, EZFS_BADDEV, msg));
1326
1327                 case ERANGE:
1328                         /*
1329                          * This happens if the record size is smaller or larger
1330                          * than the allowed size range, or not a power of 2.
1331                          *
1332                          * NOTE: although zfs_valid_proplist is called earlier,
1333                          * this case may have slipped through since the
1334                          * pool does not exist yet and it is therefore
1335                          * impossible to read properties e.g. max blocksize
1336                          * from the pool.
1337                          */
1338                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1339                             "record size invalid"));
1340                         return (zfs_error(hdl, EZFS_BADPROP, msg));
1341
1342                 case EOVERFLOW:
1343                         /*
1344                          * This occurs when one of the devices is below
1345                          * SPA_MINDEVSIZE.  Unfortunately, we can't detect which
1346                          * device was the problem device since there's no
1347                          * reliable way to determine device size from userland.
1348                          */
1349                         {
1350                                 char buf[64];
1351
1352                                 zfs_nicebytes(SPA_MINDEVSIZE, buf,
1353                                     sizeof (buf));
1354
1355                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1356                                     "one or more devices is less than the "
1357                                     "minimum size (%s)"), buf);
1358                         }
1359                         return (zfs_error(hdl, EZFS_BADDEV, msg));
1360
1361                 case ENOSPC:
1362                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1363                             "one or more devices is out of space"));
1364                         return (zfs_error(hdl, EZFS_BADDEV, msg));
1365
1366                 case ENOTBLK:
1367                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1368                             "cache device must be a disk or disk slice"));
1369                         return (zfs_error(hdl, EZFS_BADDEV, msg));
1370
1371                 default:
1372                         return (zpool_standard_error(hdl, errno, msg));
1373                 }
1374         }
1375
1376 create_failed:
1377         zcmd_free_nvlists(&zc);
1378         nvlist_free(zc_props);
1379         nvlist_free(zc_fsprops);
1380         nvlist_free(hidden_args);
1381         if (wkeydata != NULL)
1382                 free(wkeydata);
1383         return (ret);
1384 }
1385
1386 /*
1387  * Destroy the given pool.  It is up to the caller to ensure that there are no
1388  * datasets left in the pool.
1389  */
1390 int
1391 zpool_destroy(zpool_handle_t *zhp, const char *log_str)
1392 {
1393         zfs_cmd_t zc = {"\0"};
1394         zfs_handle_t *zfp = NULL;
1395         libzfs_handle_t *hdl = zhp->zpool_hdl;
1396         char msg[1024];
1397
1398         if (zhp->zpool_state == POOL_STATE_ACTIVE &&
1399             (zfp = zfs_open(hdl, zhp->zpool_name, ZFS_TYPE_FILESYSTEM)) == NULL)
1400                 return (-1);
1401
1402         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1403         zc.zc_history = (uint64_t)(uintptr_t)log_str;
1404
1405         if (zfs_ioctl(hdl, ZFS_IOC_POOL_DESTROY, &zc) != 0) {
1406                 (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1407                     "cannot destroy '%s'"), zhp->zpool_name);
1408
1409                 if (errno == EROFS) {
1410                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1411                             "one or more devices is read only"));
1412                         (void) zfs_error(hdl, EZFS_BADDEV, msg);
1413                 } else {
1414                         (void) zpool_standard_error(hdl, errno, msg);
1415                 }
1416
1417                 if (zfp)
1418                         zfs_close(zfp);
1419                 return (-1);
1420         }
1421
1422         if (zfp) {
1423                 remove_mountpoint(zfp);
1424                 zfs_close(zfp);
1425         }
1426
1427         return (0);
1428 }
1429
1430 /*
1431  * Create a checkpoint in the given pool.
1432  */
1433 int
1434 zpool_checkpoint(zpool_handle_t *zhp)
1435 {
1436         libzfs_handle_t *hdl = zhp->zpool_hdl;
1437         char msg[1024];
1438         int error;
1439
1440         error = lzc_pool_checkpoint(zhp->zpool_name);
1441         if (error != 0) {
1442                 (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1443                     "cannot checkpoint '%s'"), zhp->zpool_name);
1444                 (void) zpool_standard_error(hdl, error, msg);
1445                 return (-1);
1446         }
1447
1448         return (0);
1449 }
1450
1451 /*
1452  * Discard the checkpoint from the given pool.
1453  */
1454 int
1455 zpool_discard_checkpoint(zpool_handle_t *zhp)
1456 {
1457         libzfs_handle_t *hdl = zhp->zpool_hdl;
1458         char msg[1024];
1459         int error;
1460
1461         error = lzc_pool_checkpoint_discard(zhp->zpool_name);
1462         if (error != 0) {
1463                 (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1464                     "cannot discard checkpoint in '%s'"), zhp->zpool_name);
1465                 (void) zpool_standard_error(hdl, error, msg);
1466                 return (-1);
1467         }
1468
1469         return (0);
1470 }
1471
1472 /*
1473  * Add the given vdevs to the pool.  The caller must have already performed the
1474  * necessary verification to ensure that the vdev specification is well-formed.
1475  */
1476 int
1477 zpool_add(zpool_handle_t *zhp, nvlist_t *nvroot)
1478 {
1479         zfs_cmd_t zc = {"\0"};
1480         int ret;
1481         libzfs_handle_t *hdl = zhp->zpool_hdl;
1482         char msg[1024];
1483         nvlist_t **spares, **l2cache;
1484         uint_t nspares, nl2cache;
1485
1486         (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1487             "cannot add to '%s'"), zhp->zpool_name);
1488
1489         if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) <
1490             SPA_VERSION_SPARES &&
1491             nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1492             &spares, &nspares) == 0) {
1493                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be "
1494                     "upgraded to add hot spares"));
1495                 return (zfs_error(hdl, EZFS_BADVERSION, msg));
1496         }
1497
1498         if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) <
1499             SPA_VERSION_L2CACHE &&
1500             nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1501             &l2cache, &nl2cache) == 0) {
1502                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be "
1503                     "upgraded to add cache devices"));
1504                 return (zfs_error(hdl, EZFS_BADVERSION, msg));
1505         }
1506
1507         if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
1508                 return (-1);
1509         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1510
1511         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_ADD, &zc) != 0) {
1512                 switch (errno) {
1513                 case EBUSY:
1514                         /*
1515                          * This can happen if the user has specified the same
1516                          * device multiple times.  We can't reliably detect this
1517                          * until we try to add it and see we already have a
1518                          * label.
1519                          */
1520                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1521                             "one or more vdevs refer to the same device"));
1522                         (void) zfs_error(hdl, EZFS_BADDEV, msg);
1523                         break;
1524
1525                 case EINVAL:
1526                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1527                             "invalid config; a pool with removing/removed "
1528                             "vdevs does not support adding raidz vdevs"));
1529                         (void) zfs_error(hdl, EZFS_BADDEV, msg);
1530                         break;
1531
1532                 case EOVERFLOW:
1533                         /*
1534                          * This occurrs when one of the devices is below
1535                          * SPA_MINDEVSIZE.  Unfortunately, we can't detect which
1536                          * device was the problem device since there's no
1537                          * reliable way to determine device size from userland.
1538                          */
1539                         {
1540                                 char buf[64];
1541
1542                                 zfs_nicebytes(SPA_MINDEVSIZE, buf,
1543                                     sizeof (buf));
1544
1545                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1546                                     "device is less than the minimum "
1547                                     "size (%s)"), buf);
1548                         }
1549                         (void) zfs_error(hdl, EZFS_BADDEV, msg);
1550                         break;
1551
1552                 case ENOTSUP:
1553                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1554                             "pool must be upgraded to add these vdevs"));
1555                         (void) zfs_error(hdl, EZFS_BADVERSION, msg);
1556                         break;
1557
1558                 case ENOTBLK:
1559                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1560                             "cache device must be a disk or disk slice"));
1561                         (void) zfs_error(hdl, EZFS_BADDEV, msg);
1562                         break;
1563
1564                 default:
1565                         (void) zpool_standard_error(hdl, errno, msg);
1566                 }
1567
1568                 ret = -1;
1569         } else {
1570                 ret = 0;
1571         }
1572
1573         zcmd_free_nvlists(&zc);
1574
1575         return (ret);
1576 }
1577
1578 /*
1579  * Exports the pool from the system.  The caller must ensure that there are no
1580  * mounted datasets in the pool.
1581  */
1582 static int
1583 zpool_export_common(zpool_handle_t *zhp, boolean_t force, boolean_t hardforce,
1584     const char *log_str)
1585 {
1586         zfs_cmd_t zc = {"\0"};
1587         char msg[1024];
1588
1589         (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1590             "cannot export '%s'"), zhp->zpool_name);
1591
1592         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1593         zc.zc_cookie = force;
1594         zc.zc_guid = hardforce;
1595         zc.zc_history = (uint64_t)(uintptr_t)log_str;
1596
1597         if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_EXPORT, &zc) != 0) {
1598                 switch (errno) {
1599                 case EXDEV:
1600                         zfs_error_aux(zhp->zpool_hdl, dgettext(TEXT_DOMAIN,
1601                             "use '-f' to override the following errors:\n"
1602                             "'%s' has an active shared spare which could be"
1603                             " used by other pools once '%s' is exported."),
1604                             zhp->zpool_name, zhp->zpool_name);
1605                         return (zfs_error(zhp->zpool_hdl, EZFS_ACTIVE_SPARE,
1606                             msg));
1607                 default:
1608                         return (zpool_standard_error_fmt(zhp->zpool_hdl, errno,
1609                             msg));
1610                 }
1611         }
1612
1613         return (0);
1614 }
1615
1616 int
1617 zpool_export(zpool_handle_t *zhp, boolean_t force, const char *log_str)
1618 {
1619         return (zpool_export_common(zhp, force, B_FALSE, log_str));
1620 }
1621
1622 int
1623 zpool_export_force(zpool_handle_t *zhp, const char *log_str)
1624 {
1625         return (zpool_export_common(zhp, B_TRUE, B_TRUE, log_str));
1626 }
1627
1628 static void
1629 zpool_rewind_exclaim(libzfs_handle_t *hdl, const char *name, boolean_t dryrun,
1630     nvlist_t *config)
1631 {
1632         nvlist_t *nv = NULL;
1633         uint64_t rewindto;
1634         int64_t loss = -1;
1635         struct tm t;
1636         char timestr[128];
1637
1638         if (!hdl->libzfs_printerr || config == NULL)
1639                 return;
1640
1641         if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nv) != 0 ||
1642             nvlist_lookup_nvlist(nv, ZPOOL_CONFIG_REWIND_INFO, &nv) != 0) {
1643                 return;
1644         }
1645
1646         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_TIME, &rewindto) != 0)
1647                 return;
1648         (void) nvlist_lookup_int64(nv, ZPOOL_CONFIG_REWIND_TIME, &loss);
1649
1650         if (localtime_r((time_t *)&rewindto, &t) != NULL &&
1651             strftime(timestr, 128, "%c", &t) != 0) {
1652                 if (dryrun) {
1653                         (void) printf(dgettext(TEXT_DOMAIN,
1654                             "Would be able to return %s "
1655                             "to its state as of %s.\n"),
1656                             name, timestr);
1657                 } else {
1658                         (void) printf(dgettext(TEXT_DOMAIN,
1659                             "Pool %s returned to its state as of %s.\n"),
1660                             name, timestr);
1661                 }
1662                 if (loss > 120) {
1663                         (void) printf(dgettext(TEXT_DOMAIN,
1664                             "%s approximately %lld "),
1665                             dryrun ? "Would discard" : "Discarded",
1666                             ((longlong_t)loss + 30) / 60);
1667                         (void) printf(dgettext(TEXT_DOMAIN,
1668                             "minutes of transactions.\n"));
1669                 } else if (loss > 0) {
1670                         (void) printf(dgettext(TEXT_DOMAIN,
1671                             "%s approximately %lld "),
1672                             dryrun ? "Would discard" : "Discarded",
1673                             (longlong_t)loss);
1674                         (void) printf(dgettext(TEXT_DOMAIN,
1675                             "seconds of transactions.\n"));
1676                 }
1677         }
1678 }
1679
1680 void
1681 zpool_explain_recover(libzfs_handle_t *hdl, const char *name, int reason,
1682     nvlist_t *config)
1683 {
1684         nvlist_t *nv = NULL;
1685         int64_t loss = -1;
1686         uint64_t edata = UINT64_MAX;
1687         uint64_t rewindto;
1688         struct tm t;
1689         char timestr[128];
1690
1691         if (!hdl->libzfs_printerr)
1692                 return;
1693
1694         if (reason >= 0)
1695                 (void) printf(dgettext(TEXT_DOMAIN, "action: "));
1696         else
1697                 (void) printf(dgettext(TEXT_DOMAIN, "\t"));
1698
1699         /* All attempted rewinds failed if ZPOOL_CONFIG_LOAD_TIME missing */
1700         if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nv) != 0 ||
1701             nvlist_lookup_nvlist(nv, ZPOOL_CONFIG_REWIND_INFO, &nv) != 0 ||
1702             nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_TIME, &rewindto) != 0)
1703                 goto no_info;
1704
1705         (void) nvlist_lookup_int64(nv, ZPOOL_CONFIG_REWIND_TIME, &loss);
1706         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_DATA_ERRORS,
1707             &edata);
1708
1709         (void) printf(dgettext(TEXT_DOMAIN,
1710             "Recovery is possible, but will result in some data loss.\n"));
1711
1712         if (localtime_r((time_t *)&rewindto, &t) != NULL &&
1713             strftime(timestr, 128, "%c", &t) != 0) {
1714                 (void) printf(dgettext(TEXT_DOMAIN,
1715                     "\tReturning the pool to its state as of %s\n"
1716                     "\tshould correct the problem.  "),
1717                     timestr);
1718         } else {
1719                 (void) printf(dgettext(TEXT_DOMAIN,
1720                     "\tReverting the pool to an earlier state "
1721                     "should correct the problem.\n\t"));
1722         }
1723
1724         if (loss > 120) {
1725                 (void) printf(dgettext(TEXT_DOMAIN,
1726                     "Approximately %lld minutes of data\n"
1727                     "\tmust be discarded, irreversibly.  "),
1728                     ((longlong_t)loss + 30) / 60);
1729         } else if (loss > 0) {
1730                 (void) printf(dgettext(TEXT_DOMAIN,
1731                     "Approximately %lld seconds of data\n"
1732                     "\tmust be discarded, irreversibly.  "),
1733                     (longlong_t)loss);
1734         }
1735         if (edata != 0 && edata != UINT64_MAX) {
1736                 if (edata == 1) {
1737                         (void) printf(dgettext(TEXT_DOMAIN,
1738                             "After rewind, at least\n"
1739                             "\tone persistent user-data error will remain.  "));
1740                 } else {
1741                         (void) printf(dgettext(TEXT_DOMAIN,
1742                             "After rewind, several\n"
1743                             "\tpersistent user-data errors will remain.  "));
1744                 }
1745         }
1746         (void) printf(dgettext(TEXT_DOMAIN,
1747             "Recovery can be attempted\n\tby executing 'zpool %s -F %s'.  "),
1748             reason >= 0 ? "clear" : "import", name);
1749
1750         (void) printf(dgettext(TEXT_DOMAIN,
1751             "A scrub of the pool\n"
1752             "\tis strongly recommended after recovery.\n"));
1753         return;
1754
1755 no_info:
1756         (void) printf(dgettext(TEXT_DOMAIN,
1757             "Destroy and re-create the pool from\n\ta backup source.\n"));
1758 }
1759
1760 /*
1761  * zpool_import() is a contracted interface. Should be kept the same
1762  * if possible.
1763  *
1764  * Applications should use zpool_import_props() to import a pool with
1765  * new properties value to be set.
1766  */
1767 int
1768 zpool_import(libzfs_handle_t *hdl, nvlist_t *config, const char *newname,
1769     char *altroot)
1770 {
1771         nvlist_t *props = NULL;
1772         int ret;
1773
1774         if (altroot != NULL) {
1775                 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
1776                         return (zfs_error_fmt(hdl, EZFS_NOMEM,
1777                             dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1778                             newname));
1779                 }
1780
1781                 if (nvlist_add_string(props,
1782                     zpool_prop_to_name(ZPOOL_PROP_ALTROOT), altroot) != 0 ||
1783                     nvlist_add_string(props,
1784                     zpool_prop_to_name(ZPOOL_PROP_CACHEFILE), "none") != 0) {
1785                         nvlist_free(props);
1786                         return (zfs_error_fmt(hdl, EZFS_NOMEM,
1787                             dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1788                             newname));
1789                 }
1790         }
1791
1792         ret = zpool_import_props(hdl, config, newname, props,
1793             ZFS_IMPORT_NORMAL);
1794         nvlist_free(props);
1795         return (ret);
1796 }
1797
1798 static void
1799 print_vdev_tree(libzfs_handle_t *hdl, const char *name, nvlist_t *nv,
1800     int indent)
1801 {
1802         nvlist_t **child;
1803         uint_t c, children;
1804         char *vname;
1805         uint64_t is_log = 0;
1806
1807         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG,
1808             &is_log);
1809
1810         if (name != NULL)
1811                 (void) printf("\t%*s%s%s\n", indent, "", name,
1812                     is_log ? " [log]" : "");
1813
1814         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1815             &child, &children) != 0)
1816                 return;
1817
1818         for (c = 0; c < children; c++) {
1819                 vname = zpool_vdev_name(hdl, NULL, child[c], VDEV_NAME_TYPE_ID);
1820                 print_vdev_tree(hdl, vname, child[c], indent + 2);
1821                 free(vname);
1822         }
1823 }
1824
1825 void
1826 zpool_print_unsup_feat(nvlist_t *config)
1827 {
1828         nvlist_t *nvinfo, *unsup_feat;
1829         nvpair_t *nvp;
1830
1831         verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nvinfo) ==
1832             0);
1833         verify(nvlist_lookup_nvlist(nvinfo, ZPOOL_CONFIG_UNSUP_FEAT,
1834             &unsup_feat) == 0);
1835
1836         for (nvp = nvlist_next_nvpair(unsup_feat, NULL); nvp != NULL;
1837             nvp = nvlist_next_nvpair(unsup_feat, nvp)) {
1838                 char *desc;
1839
1840                 verify(nvpair_type(nvp) == DATA_TYPE_STRING);
1841                 verify(nvpair_value_string(nvp, &desc) == 0);
1842
1843                 if (strlen(desc) > 0)
1844                         (void) printf("\t%s (%s)\n", nvpair_name(nvp), desc);
1845                 else
1846                         (void) printf("\t%s\n", nvpair_name(nvp));
1847         }
1848 }
1849
1850 /*
1851  * Import the given pool using the known configuration and a list of
1852  * properties to be set. The configuration should have come from
1853  * zpool_find_import(). The 'newname' parameters control whether the pool
1854  * is imported with a different name.
1855  */
1856 int
1857 zpool_import_props(libzfs_handle_t *hdl, nvlist_t *config, const char *newname,
1858     nvlist_t *props, int flags)
1859 {
1860         zfs_cmd_t zc = {"\0"};
1861         zpool_load_policy_t policy;
1862         nvlist_t *nv = NULL;
1863         nvlist_t *nvinfo = NULL;
1864         nvlist_t *missing = NULL;
1865         char *thename;
1866         char *origname;
1867         int ret;
1868         int error = 0;
1869         char errbuf[1024];
1870
1871         verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1872             &origname) == 0);
1873
1874         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1875             "cannot import pool '%s'"), origname);
1876
1877         if (newname != NULL) {
1878                 if (!zpool_name_valid(hdl, B_FALSE, newname))
1879                         return (zfs_error_fmt(hdl, EZFS_INVALIDNAME,
1880                             dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1881                             newname));
1882                 thename = (char *)newname;
1883         } else {
1884                 thename = origname;
1885         }
1886
1887         if (props != NULL) {
1888                 uint64_t version;
1889                 prop_flags_t flags = { .create = B_FALSE, .import = B_TRUE };
1890
1891                 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
1892                     &version) == 0);
1893
1894                 if ((props = zpool_valid_proplist(hdl, origname,
1895                     props, version, flags, errbuf)) == NULL)
1896                         return (-1);
1897                 if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
1898                         nvlist_free(props);
1899                         return (-1);
1900                 }
1901                 nvlist_free(props);
1902         }
1903
1904         (void) strlcpy(zc.zc_name, thename, sizeof (zc.zc_name));
1905
1906         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1907             &zc.zc_guid) == 0);
1908
1909         if (zcmd_write_conf_nvlist(hdl, &zc, config) != 0) {
1910                 zcmd_free_nvlists(&zc);
1911                 return (-1);
1912         }
1913         if (zcmd_alloc_dst_nvlist(hdl, &zc, zc.zc_nvlist_conf_size * 2) != 0) {
1914                 zcmd_free_nvlists(&zc);
1915                 return (-1);
1916         }
1917
1918         zc.zc_cookie = flags;
1919         while ((ret = zfs_ioctl(hdl, ZFS_IOC_POOL_IMPORT, &zc)) != 0 &&
1920             errno == ENOMEM) {
1921                 if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
1922                         zcmd_free_nvlists(&zc);
1923                         return (-1);
1924                 }
1925         }
1926         if (ret != 0)
1927                 error = errno;
1928
1929         (void) zcmd_read_dst_nvlist(hdl, &zc, &nv);
1930
1931         zcmd_free_nvlists(&zc);
1932
1933         zpool_get_load_policy(config, &policy);
1934
1935         if (error) {
1936                 char desc[1024];
1937                 char aux[256];
1938
1939                 /*
1940                  * Dry-run failed, but we print out what success
1941                  * looks like if we found a best txg
1942                  */
1943                 if (policy.zlp_rewind & ZPOOL_TRY_REWIND) {
1944                         zpool_rewind_exclaim(hdl, newname ? origname : thename,
1945                             B_TRUE, nv);
1946                         nvlist_free(nv);
1947                         return (-1);
1948                 }
1949
1950                 if (newname == NULL)
1951                         (void) snprintf(desc, sizeof (desc),
1952                             dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1953                             thename);
1954                 else
1955                         (void) snprintf(desc, sizeof (desc),
1956                             dgettext(TEXT_DOMAIN, "cannot import '%s' as '%s'"),
1957                             origname, thename);
1958
1959                 switch (error) {
1960                 case ENOTSUP:
1961                         if (nv != NULL && nvlist_lookup_nvlist(nv,
1962                             ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0 &&
1963                             nvlist_exists(nvinfo, ZPOOL_CONFIG_UNSUP_FEAT)) {
1964                                 (void) printf(dgettext(TEXT_DOMAIN, "This "
1965                                     "pool uses the following feature(s) not "
1966                                     "supported by this system:\n"));
1967                                 zpool_print_unsup_feat(nv);
1968                                 if (nvlist_exists(nvinfo,
1969                                     ZPOOL_CONFIG_CAN_RDONLY)) {
1970                                         (void) printf(dgettext(TEXT_DOMAIN,
1971                                             "All unsupported features are only "
1972                                             "required for writing to the pool."
1973                                             "\nThe pool can be imported using "
1974                                             "'-o readonly=on'.\n"));
1975                                 }
1976                         }
1977                         /*
1978                          * Unsupported version.
1979                          */
1980                         (void) zfs_error(hdl, EZFS_BADVERSION, desc);
1981                         break;
1982
1983                 case EREMOTEIO:
1984                         if (nv != NULL && nvlist_lookup_nvlist(nv,
1985                             ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0) {
1986                                 char *hostname = "<unknown>";
1987                                 uint64_t hostid = 0;
1988                                 mmp_state_t mmp_state;
1989
1990                                 mmp_state = fnvlist_lookup_uint64(nvinfo,
1991                                     ZPOOL_CONFIG_MMP_STATE);
1992
1993                                 if (nvlist_exists(nvinfo,
1994                                     ZPOOL_CONFIG_MMP_HOSTNAME))
1995                                         hostname = fnvlist_lookup_string(nvinfo,
1996                                             ZPOOL_CONFIG_MMP_HOSTNAME);
1997
1998                                 if (nvlist_exists(nvinfo,
1999                                     ZPOOL_CONFIG_MMP_HOSTID))
2000                                         hostid = fnvlist_lookup_uint64(nvinfo,
2001                                             ZPOOL_CONFIG_MMP_HOSTID);
2002
2003                                 if (mmp_state == MMP_STATE_ACTIVE) {
2004                                         (void) snprintf(aux, sizeof (aux),
2005                                             dgettext(TEXT_DOMAIN, "pool is imp"
2006                                             "orted on host '%s' (hostid=%lx).\n"
2007                                             "Export the pool on the other "
2008                                             "system, then run 'zpool import'."),
2009                                             hostname, (unsigned long) hostid);
2010                                 } else if (mmp_state == MMP_STATE_NO_HOSTID) {
2011                                         (void) snprintf(aux, sizeof (aux),
2012                                             dgettext(TEXT_DOMAIN, "pool has "
2013                                             "the multihost property on and "
2014                                             "the\nsystem's hostid is not set. "
2015                                             "Set a unique system hostid with "
2016                                             "the zgenhostid(8) command.\n"));
2017                                 }
2018
2019                                 (void) zfs_error_aux(hdl, aux);
2020                         }
2021                         (void) zfs_error(hdl, EZFS_ACTIVE_POOL, desc);
2022                         break;
2023
2024                 case EINVAL:
2025                         (void) zfs_error(hdl, EZFS_INVALCONFIG, desc);
2026                         break;
2027
2028                 case EROFS:
2029                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2030                             "one or more devices is read only"));
2031                         (void) zfs_error(hdl, EZFS_BADDEV, desc);
2032                         break;
2033
2034                 case ENXIO:
2035                         if (nv && nvlist_lookup_nvlist(nv,
2036                             ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0 &&
2037                             nvlist_lookup_nvlist(nvinfo,
2038                             ZPOOL_CONFIG_MISSING_DEVICES, &missing) == 0) {
2039                                 (void) printf(dgettext(TEXT_DOMAIN,
2040                                     "The devices below are missing or "
2041                                     "corrupted, use '-m' to import the pool "
2042                                     "anyway:\n"));
2043                                 print_vdev_tree(hdl, NULL, missing, 2);
2044                                 (void) printf("\n");
2045                         }
2046                         (void) zpool_standard_error(hdl, error, desc);
2047                         break;
2048
2049                 case EEXIST:
2050                         (void) zpool_standard_error(hdl, error, desc);
2051                         break;
2052
2053                 case EBUSY:
2054                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2055                             "one or more devices are already in use\n"));
2056                         (void) zfs_error(hdl, EZFS_BADDEV, desc);
2057                         break;
2058                 case ENAMETOOLONG:
2059                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2060                             "new name of at least one dataset is longer than "
2061                             "the maximum allowable length"));
2062                         (void) zfs_error(hdl, EZFS_NAMETOOLONG, desc);
2063                         break;
2064                 default:
2065                         (void) zpool_standard_error(hdl, error, desc);
2066                         zpool_explain_recover(hdl,
2067                             newname ? origname : thename, -error, nv);
2068                         break;
2069                 }
2070
2071                 nvlist_free(nv);
2072                 ret = -1;
2073         } else {
2074                 zpool_handle_t *zhp;
2075
2076                 /*
2077                  * This should never fail, but play it safe anyway.
2078                  */
2079                 if (zpool_open_silent(hdl, thename, &zhp) != 0)
2080                         ret = -1;
2081                 else if (zhp != NULL)
2082                         zpool_close(zhp);
2083                 if (policy.zlp_rewind &
2084                     (ZPOOL_DO_REWIND | ZPOOL_TRY_REWIND)) {
2085                         zpool_rewind_exclaim(hdl, newname ? origname : thename,
2086                             ((policy.zlp_rewind & ZPOOL_TRY_REWIND) != 0), nv);
2087                 }
2088                 nvlist_free(nv);
2089                 return (0);
2090         }
2091
2092         return (ret);
2093 }
2094
2095 /*
2096  * Scan the pool.
2097  */
2098 int
2099 zpool_scan(zpool_handle_t *zhp, pool_scan_func_t func, pool_scrub_cmd_t cmd)
2100 {
2101         zfs_cmd_t zc = {"\0"};
2102         char msg[1024];
2103         int err;
2104         libzfs_handle_t *hdl = zhp->zpool_hdl;
2105
2106         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2107         zc.zc_cookie = func;
2108         zc.zc_flags = cmd;
2109
2110         if (zfs_ioctl(hdl, ZFS_IOC_POOL_SCAN, &zc) == 0)
2111                 return (0);
2112
2113         err = errno;
2114
2115         /* ECANCELED on a scrub means we resumed a paused scrub */
2116         if (err == ECANCELED && func == POOL_SCAN_SCRUB &&
2117             cmd == POOL_SCRUB_NORMAL)
2118                 return (0);
2119
2120         if (err == ENOENT && func != POOL_SCAN_NONE && cmd == POOL_SCRUB_NORMAL)
2121                 return (0);
2122
2123         if (func == POOL_SCAN_SCRUB) {
2124                 if (cmd == POOL_SCRUB_PAUSE) {
2125                         (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2126                             "cannot pause scrubbing %s"), zc.zc_name);
2127                 } else {
2128                         assert(cmd == POOL_SCRUB_NORMAL);
2129                         (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2130                             "cannot scrub %s"), zc.zc_name);
2131                 }
2132         } else if (func == POOL_SCAN_NONE) {
2133                 (void) snprintf(msg, sizeof (msg),
2134                     dgettext(TEXT_DOMAIN, "cannot cancel scrubbing %s"),
2135                     zc.zc_name);
2136         } else {
2137                 assert(!"unexpected result");
2138         }
2139
2140         if (err == EBUSY) {
2141                 nvlist_t *nvroot;
2142                 pool_scan_stat_t *ps = NULL;
2143                 uint_t psc;
2144
2145                 verify(nvlist_lookup_nvlist(zhp->zpool_config,
2146                     ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
2147                 (void) nvlist_lookup_uint64_array(nvroot,
2148                     ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &psc);
2149                 if (ps && ps->pss_func == POOL_SCAN_SCRUB) {
2150                         if (cmd == POOL_SCRUB_PAUSE)
2151                                 return (zfs_error(hdl, EZFS_SCRUB_PAUSED, msg));
2152                         else
2153                                 return (zfs_error(hdl, EZFS_SCRUBBING, msg));
2154                 } else {
2155                         return (zfs_error(hdl, EZFS_RESILVERING, msg));
2156                 }
2157         } else if (err == ENOENT) {
2158                 return (zfs_error(hdl, EZFS_NO_SCRUB, msg));
2159         } else {
2160                 return (zpool_standard_error(hdl, err, msg));
2161         }
2162 }
2163
2164 /*
2165  * Find a vdev that matches the search criteria specified. We use the
2166  * the nvpair name to determine how we should look for the device.
2167  * 'avail_spare' is set to TRUE if the provided guid refers to an AVAIL
2168  * spare; but FALSE if its an INUSE spare.
2169  */
2170 static nvlist_t *
2171 vdev_to_nvlist_iter(nvlist_t *nv, nvlist_t *search, boolean_t *avail_spare,
2172     boolean_t *l2cache, boolean_t *log)
2173 {
2174         uint_t c, children;
2175         nvlist_t **child;
2176         nvlist_t *ret;
2177         uint64_t is_log;
2178         char *srchkey;
2179         nvpair_t *pair = nvlist_next_nvpair(search, NULL);
2180
2181         /* Nothing to look for */
2182         if (search == NULL || pair == NULL)
2183                 return (NULL);
2184
2185         /* Obtain the key we will use to search */
2186         srchkey = nvpair_name(pair);
2187
2188         switch (nvpair_type(pair)) {
2189         case DATA_TYPE_UINT64:
2190                 if (strcmp(srchkey, ZPOOL_CONFIG_GUID) == 0) {
2191                         uint64_t srchval, theguid;
2192
2193                         verify(nvpair_value_uint64(pair, &srchval) == 0);
2194                         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
2195                             &theguid) == 0);
2196                         if (theguid == srchval)
2197                                 return (nv);
2198                 }
2199                 break;
2200
2201         case DATA_TYPE_STRING: {
2202                 char *srchval, *val;
2203
2204                 verify(nvpair_value_string(pair, &srchval) == 0);
2205                 if (nvlist_lookup_string(nv, srchkey, &val) != 0)
2206                         break;
2207
2208                 /*
2209                  * Search for the requested value. Special cases:
2210                  *
2211                  * - ZPOOL_CONFIG_PATH for whole disk entries.  These end in
2212                  *   "-part1", or "p1".  The suffix is hidden from the user,
2213                  *   but included in the string, so this matches around it.
2214                  * - ZPOOL_CONFIG_PATH for short names zfs_strcmp_shortname()
2215                  *   is used to check all possible expanded paths.
2216                  * - looking for a top-level vdev name (i.e. ZPOOL_CONFIG_TYPE).
2217                  *
2218                  * Otherwise, all other searches are simple string compares.
2219                  */
2220                 if (strcmp(srchkey, ZPOOL_CONFIG_PATH) == 0) {
2221                         uint64_t wholedisk = 0;
2222
2223                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
2224                             &wholedisk);
2225                         if (zfs_strcmp_pathname(srchval, val, wholedisk) == 0)
2226                                 return (nv);
2227
2228                 } else if (strcmp(srchkey, ZPOOL_CONFIG_TYPE) == 0 && val) {
2229                         char *type, *idx, *end, *p;
2230                         uint64_t id, vdev_id;
2231
2232                         /*
2233                          * Determine our vdev type, keeping in mind
2234                          * that the srchval is composed of a type and
2235                          * vdev id pair (i.e. mirror-4).
2236                          */
2237                         if ((type = strdup(srchval)) == NULL)
2238                                 return (NULL);
2239
2240                         if ((p = strrchr(type, '-')) == NULL) {
2241                                 free(type);
2242                                 break;
2243                         }
2244                         idx = p + 1;
2245                         *p = '\0';
2246
2247                         /*
2248                          * If the types don't match then keep looking.
2249                          */
2250                         if (strncmp(val, type, strlen(val)) != 0) {
2251                                 free(type);
2252                                 break;
2253                         }
2254
2255                         verify(zpool_vdev_is_interior(type));
2256                         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID,
2257                             &id) == 0);
2258
2259                         errno = 0;
2260                         vdev_id = strtoull(idx, &end, 10);
2261
2262                         free(type);
2263                         if (errno != 0)
2264                                 return (NULL);
2265
2266                         /*
2267                          * Now verify that we have the correct vdev id.
2268                          */
2269                         if (vdev_id == id)
2270                                 return (nv);
2271                 }
2272
2273                 /*
2274                  * Common case
2275                  */
2276                 if (strcmp(srchval, val) == 0)
2277                         return (nv);
2278                 break;
2279         }
2280
2281         default:
2282                 break;
2283         }
2284
2285         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2286             &child, &children) != 0)
2287                 return (NULL);
2288
2289         for (c = 0; c < children; c++) {
2290                 if ((ret = vdev_to_nvlist_iter(child[c], search,
2291                     avail_spare, l2cache, NULL)) != NULL) {
2292                         /*
2293                          * The 'is_log' value is only set for the toplevel
2294                          * vdev, not the leaf vdevs.  So we always lookup the
2295                          * log device from the root of the vdev tree (where
2296                          * 'log' is non-NULL).
2297                          */
2298                         if (log != NULL &&
2299                             nvlist_lookup_uint64(child[c],
2300                             ZPOOL_CONFIG_IS_LOG, &is_log) == 0 &&
2301                             is_log) {
2302                                 *log = B_TRUE;
2303                         }
2304                         return (ret);
2305                 }
2306         }
2307
2308         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
2309             &child, &children) == 0) {
2310                 for (c = 0; c < children; c++) {
2311                         if ((ret = vdev_to_nvlist_iter(child[c], search,
2312                             avail_spare, l2cache, NULL)) != NULL) {
2313                                 *avail_spare = B_TRUE;
2314                                 return (ret);
2315                         }
2316                 }
2317         }
2318
2319         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
2320             &child, &children) == 0) {
2321                 for (c = 0; c < children; c++) {
2322                         if ((ret = vdev_to_nvlist_iter(child[c], search,
2323                             avail_spare, l2cache, NULL)) != NULL) {
2324                                 *l2cache = B_TRUE;
2325                                 return (ret);
2326                         }
2327                 }
2328         }
2329
2330         return (NULL);
2331 }
2332
2333 /*
2334  * Given a physical path or guid, find the associated vdev.
2335  */
2336 nvlist_t *
2337 zpool_find_vdev_by_physpath(zpool_handle_t *zhp, const char *ppath,
2338     boolean_t *avail_spare, boolean_t *l2cache, boolean_t *log)
2339 {
2340         nvlist_t *search, *nvroot, *ret;
2341         uint64_t guid;
2342         char *end;
2343
2344         verify(nvlist_alloc(&search, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2345
2346         guid = strtoull(ppath, &end, 0);
2347         if (guid != 0 && *end == '\0') {
2348                 verify(nvlist_add_uint64(search, ZPOOL_CONFIG_GUID, guid) == 0);
2349         } else {
2350                 verify(nvlist_add_string(search, ZPOOL_CONFIG_PHYS_PATH,
2351                     ppath) == 0);
2352         }
2353
2354         verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
2355             &nvroot) == 0);
2356
2357         *avail_spare = B_FALSE;
2358         *l2cache = B_FALSE;
2359         if (log != NULL)
2360                 *log = B_FALSE;
2361         ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log);
2362         nvlist_free(search);
2363
2364         return (ret);
2365 }
2366
2367 /*
2368  * Determine if we have an "interior" top-level vdev (i.e mirror/raidz).
2369  */
2370 static boolean_t
2371 zpool_vdev_is_interior(const char *name)
2372 {
2373         if (strncmp(name, VDEV_TYPE_RAIDZ, strlen(VDEV_TYPE_RAIDZ)) == 0 ||
2374             strncmp(name, VDEV_TYPE_SPARE, strlen(VDEV_TYPE_SPARE)) == 0 ||
2375             strncmp(name,
2376             VDEV_TYPE_REPLACING, strlen(VDEV_TYPE_REPLACING)) == 0 ||
2377             strncmp(name, VDEV_TYPE_MIRROR, strlen(VDEV_TYPE_MIRROR)) == 0)
2378                 return (B_TRUE);
2379         return (B_FALSE);
2380 }
2381
2382 nvlist_t *
2383 zpool_find_vdev(zpool_handle_t *zhp, const char *path, boolean_t *avail_spare,
2384     boolean_t *l2cache, boolean_t *log)
2385 {
2386         char *end;
2387         nvlist_t *nvroot, *search, *ret;
2388         uint64_t guid;
2389
2390         verify(nvlist_alloc(&search, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2391
2392         guid = strtoull(path, &end, 0);
2393         if (guid != 0 && *end == '\0') {
2394                 verify(nvlist_add_uint64(search, ZPOOL_CONFIG_GUID, guid) == 0);
2395         } else if (zpool_vdev_is_interior(path)) {
2396                 verify(nvlist_add_string(search, ZPOOL_CONFIG_TYPE, path) == 0);
2397         } else {
2398                 verify(nvlist_add_string(search, ZPOOL_CONFIG_PATH, path) == 0);
2399         }
2400
2401         verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
2402             &nvroot) == 0);
2403
2404         *avail_spare = B_FALSE;
2405         *l2cache = B_FALSE;
2406         if (log != NULL)
2407                 *log = B_FALSE;
2408         ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log);
2409         nvlist_free(search);
2410
2411         return (ret);
2412 }
2413
2414 static int
2415 vdev_is_online(nvlist_t *nv)
2416 {
2417         uint64_t ival;
2418
2419         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE, &ival) == 0 ||
2420             nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED, &ival) == 0 ||
2421             nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED, &ival) == 0)
2422                 return (0);
2423
2424         return (1);
2425 }
2426
2427 /*
2428  * Helper function for zpool_get_physpaths().
2429  */
2430 static int
2431 vdev_get_one_physpath(nvlist_t *config, char *physpath, size_t physpath_size,
2432     size_t *bytes_written)
2433 {
2434         size_t bytes_left, pos, rsz;
2435         char *tmppath;
2436         const char *format;
2437
2438         if (nvlist_lookup_string(config, ZPOOL_CONFIG_PHYS_PATH,
2439             &tmppath) != 0)
2440                 return (EZFS_NODEVICE);
2441
2442         pos = *bytes_written;
2443         bytes_left = physpath_size - pos;
2444         format = (pos == 0) ? "%s" : " %s";
2445
2446         rsz = snprintf(physpath + pos, bytes_left, format, tmppath);
2447         *bytes_written += rsz;
2448
2449         if (rsz >= bytes_left) {
2450                 /* if physpath was not copied properly, clear it */
2451                 if (bytes_left != 0) {
2452                         physpath[pos] = 0;
2453                 }
2454                 return (EZFS_NOSPC);
2455         }
2456         return (0);
2457 }
2458
2459 static int
2460 vdev_get_physpaths(nvlist_t *nv, char *physpath, size_t phypath_size,
2461     size_t *rsz, boolean_t is_spare)
2462 {
2463         char *type;
2464         int ret;
2465
2466         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
2467                 return (EZFS_INVALCONFIG);
2468
2469         if (strcmp(type, VDEV_TYPE_DISK) == 0) {
2470                 /*
2471                  * An active spare device has ZPOOL_CONFIG_IS_SPARE set.
2472                  * For a spare vdev, we only want to boot from the active
2473                  * spare device.
2474                  */
2475                 if (is_spare) {
2476                         uint64_t spare = 0;
2477                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
2478                             &spare);
2479                         if (!spare)
2480                                 return (EZFS_INVALCONFIG);
2481                 }
2482
2483                 if (vdev_is_online(nv)) {
2484                         if ((ret = vdev_get_one_physpath(nv, physpath,
2485                             phypath_size, rsz)) != 0)
2486                                 return (ret);
2487                 }
2488         } else if (strcmp(type, VDEV_TYPE_MIRROR) == 0 ||
2489             strcmp(type, VDEV_TYPE_RAIDZ) == 0 ||
2490             strcmp(type, VDEV_TYPE_REPLACING) == 0 ||
2491             (is_spare = (strcmp(type, VDEV_TYPE_SPARE) == 0))) {
2492                 nvlist_t **child;
2493                 uint_t count;
2494                 int i, ret;
2495
2496                 if (nvlist_lookup_nvlist_array(nv,
2497                     ZPOOL_CONFIG_CHILDREN, &child, &count) != 0)
2498                         return (EZFS_INVALCONFIG);
2499
2500                 for (i = 0; i < count; i++) {
2501                         ret = vdev_get_physpaths(child[i], physpath,
2502                             phypath_size, rsz, is_spare);
2503                         if (ret == EZFS_NOSPC)
2504                                 return (ret);
2505                 }
2506         }
2507
2508         return (EZFS_POOL_INVALARG);
2509 }
2510
2511 /*
2512  * Get phys_path for a root pool config.
2513  * Return 0 on success; non-zero on failure.
2514  */
2515 static int
2516 zpool_get_config_physpath(nvlist_t *config, char *physpath, size_t phypath_size)
2517 {
2518         size_t rsz;
2519         nvlist_t *vdev_root;
2520         nvlist_t **child;
2521         uint_t count;
2522         char *type;
2523
2524         rsz = 0;
2525
2526         if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2527             &vdev_root) != 0)
2528                 return (EZFS_INVALCONFIG);
2529
2530         if (nvlist_lookup_string(vdev_root, ZPOOL_CONFIG_TYPE, &type) != 0 ||
2531             nvlist_lookup_nvlist_array(vdev_root, ZPOOL_CONFIG_CHILDREN,
2532             &child, &count) != 0)
2533                 return (EZFS_INVALCONFIG);
2534
2535         /*
2536          * root pool can only have a single top-level vdev.
2537          */
2538         if (strcmp(type, VDEV_TYPE_ROOT) != 0 || count != 1)
2539                 return (EZFS_POOL_INVALARG);
2540
2541         (void) vdev_get_physpaths(child[0], physpath, phypath_size, &rsz,
2542             B_FALSE);
2543
2544         /* No online devices */
2545         if (rsz == 0)
2546                 return (EZFS_NODEVICE);
2547
2548         return (0);
2549 }
2550
2551 /*
2552  * Get phys_path for a root pool
2553  * Return 0 on success; non-zero on failure.
2554  */
2555 int
2556 zpool_get_physpath(zpool_handle_t *zhp, char *physpath, size_t phypath_size)
2557 {
2558         return (zpool_get_config_physpath(zhp->zpool_config, physpath,
2559             phypath_size));
2560 }
2561
2562 /*
2563  * If the device has being dynamically expanded then we need to relabel
2564  * the disk to use the new unallocated space.
2565  */
2566 static int
2567 zpool_relabel_disk(libzfs_handle_t *hdl, const char *path, const char *msg)
2568 {
2569         int fd, error;
2570
2571         if ((fd = open(path, O_RDWR|O_DIRECT)) < 0) {
2572                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot "
2573                     "relabel '%s': unable to open device: %d"), path, errno);
2574                 return (zfs_error(hdl, EZFS_OPENFAILED, msg));
2575         }
2576
2577         /*
2578          * It's possible that we might encounter an error if the device
2579          * does not have any unallocated space left. If so, we simply
2580          * ignore that error and continue on.
2581          *
2582          * Also, we don't call efi_rescan() - that would just return EBUSY.
2583          * The module will do it for us in vdev_disk_open().
2584          */
2585         error = efi_use_whole_disk(fd);
2586
2587         /* Flush the buffers to disk and invalidate the page cache. */
2588         (void) fsync(fd);
2589         (void) ioctl(fd, BLKFLSBUF);
2590
2591         (void) close(fd);
2592         if (error && error != VT_ENOSPC) {
2593                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot "
2594                     "relabel '%s': unable to read disk capacity"), path);
2595                 return (zfs_error(hdl, EZFS_NOCAP, msg));
2596         }
2597
2598         return (0);
2599 }
2600
2601 /*
2602  * Convert a vdev path to a GUID.  Returns GUID or 0 on error.
2603  *
2604  * If is_spare, is_l2cache, or is_log is non-NULL, then store within it
2605  * if the VDEV is a spare, l2cache, or log device.  If they're NULL then
2606  * ignore them.
2607  */
2608 static uint64_t
2609 zpool_vdev_path_to_guid_impl(zpool_handle_t *zhp, const char *path,
2610     boolean_t *is_spare, boolean_t *is_l2cache, boolean_t *is_log)
2611 {
2612         uint64_t guid;
2613         boolean_t spare = B_FALSE, l2cache = B_FALSE, log = B_FALSE;
2614         nvlist_t *tgt;
2615
2616         if ((tgt = zpool_find_vdev(zhp, path, &spare, &l2cache,
2617             &log)) == NULL)
2618                 return (0);
2619
2620         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &guid) == 0);
2621         if (is_spare != NULL)
2622                 *is_spare = spare;
2623         if (is_l2cache != NULL)
2624                 *is_l2cache = l2cache;
2625         if (is_log != NULL)
2626                 *is_log = log;
2627
2628         return (guid);
2629 }
2630
2631 /* Convert a vdev path to a GUID.  Returns GUID or 0 on error. */
2632 uint64_t
2633 zpool_vdev_path_to_guid(zpool_handle_t *zhp, const char *path)
2634 {
2635         return (zpool_vdev_path_to_guid_impl(zhp, path, NULL, NULL, NULL));
2636 }
2637
2638 /*
2639  * Bring the specified vdev online.   The 'flags' parameter is a set of the
2640  * ZFS_ONLINE_* flags.
2641  */
2642 int
2643 zpool_vdev_online(zpool_handle_t *zhp, const char *path, int flags,
2644     vdev_state_t *newstate)
2645 {
2646         zfs_cmd_t zc = {"\0"};
2647         char msg[1024];
2648         char *pathname;
2649         nvlist_t *tgt;
2650         boolean_t avail_spare, l2cache, islog;
2651         libzfs_handle_t *hdl = zhp->zpool_hdl;
2652         int error;
2653
2654         if (flags & ZFS_ONLINE_EXPAND) {
2655                 (void) snprintf(msg, sizeof (msg),
2656                     dgettext(TEXT_DOMAIN, "cannot expand %s"), path);
2657         } else {
2658                 (void) snprintf(msg, sizeof (msg),
2659                     dgettext(TEXT_DOMAIN, "cannot online %s"), path);
2660         }
2661
2662         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2663         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2664             &islog)) == NULL)
2665                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
2666
2667         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2668
2669         if (avail_spare)
2670                 return (zfs_error(hdl, EZFS_ISSPARE, msg));
2671
2672         if ((flags & ZFS_ONLINE_EXPAND ||
2673             zpool_get_prop_int(zhp, ZPOOL_PROP_AUTOEXPAND, NULL)) &&
2674             nvlist_lookup_string(tgt, ZPOOL_CONFIG_PATH, &pathname) == 0) {
2675                 uint64_t wholedisk = 0;
2676
2677                 (void) nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_WHOLE_DISK,
2678                     &wholedisk);
2679
2680                 /*
2681                  * XXX - L2ARC 1.0 devices can't support expansion.
2682                  */
2683                 if (l2cache) {
2684                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2685                             "cannot expand cache devices"));
2686                         return (zfs_error(hdl, EZFS_VDEVNOTSUP, msg));
2687                 }
2688
2689                 if (wholedisk) {
2690                         const char *fullpath = path;
2691                         char buf[MAXPATHLEN];
2692
2693                         if (path[0] != '/') {
2694                                 error = zfs_resolve_shortname(path, buf,
2695                                     sizeof (buf));
2696                                 if (error != 0)
2697                                         return (zfs_error(hdl, EZFS_NODEVICE,
2698                                             msg));
2699
2700                                 fullpath = buf;
2701                         }
2702
2703                         error = zpool_relabel_disk(hdl, fullpath, msg);
2704                         if (error != 0)
2705                                 return (error);
2706                 }
2707         }
2708
2709         zc.zc_cookie = VDEV_STATE_ONLINE;
2710         zc.zc_obj = flags;
2711
2712         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) != 0) {
2713                 if (errno == EINVAL) {
2714                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "was split "
2715                             "from this pool into a new one.  Use '%s' "
2716                             "instead"), "zpool detach");
2717                         return (zfs_error(hdl, EZFS_POSTSPLIT_ONLINE, msg));
2718                 }
2719                 return (zpool_standard_error(hdl, errno, msg));
2720         }
2721
2722         *newstate = zc.zc_cookie;
2723         return (0);
2724 }
2725
2726 /*
2727  * Take the specified vdev offline
2728  */
2729 int
2730 zpool_vdev_offline(zpool_handle_t *zhp, const char *path, boolean_t istmp)
2731 {
2732         zfs_cmd_t zc = {"\0"};
2733         char msg[1024];
2734         nvlist_t *tgt;
2735         boolean_t avail_spare, l2cache;
2736         libzfs_handle_t *hdl = zhp->zpool_hdl;
2737
2738         (void) snprintf(msg, sizeof (msg),
2739             dgettext(TEXT_DOMAIN, "cannot offline %s"), path);
2740
2741         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2742         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2743             NULL)) == NULL)
2744                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
2745
2746         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2747
2748         if (avail_spare)
2749                 return (zfs_error(hdl, EZFS_ISSPARE, msg));
2750
2751         zc.zc_cookie = VDEV_STATE_OFFLINE;
2752         zc.zc_obj = istmp ? ZFS_OFFLINE_TEMPORARY : 0;
2753
2754         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2755                 return (0);
2756
2757         switch (errno) {
2758         case EBUSY:
2759
2760                 /*
2761                  * There are no other replicas of this device.
2762                  */
2763                 return (zfs_error(hdl, EZFS_NOREPLICAS, msg));
2764
2765         case EEXIST:
2766                 /*
2767                  * The log device has unplayed logs
2768                  */
2769                 return (zfs_error(hdl, EZFS_UNPLAYED_LOGS, msg));
2770
2771         default:
2772                 return (zpool_standard_error(hdl, errno, msg));
2773         }
2774 }
2775
2776 /*
2777  * Mark the given vdev faulted.
2778  */
2779 int
2780 zpool_vdev_fault(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux)
2781 {
2782         zfs_cmd_t zc = {"\0"};
2783         char msg[1024];
2784         libzfs_handle_t *hdl = zhp->zpool_hdl;
2785
2786         (void) snprintf(msg, sizeof (msg),
2787             dgettext(TEXT_DOMAIN, "cannot fault %llu"), (u_longlong_t)guid);
2788
2789         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2790         zc.zc_guid = guid;
2791         zc.zc_cookie = VDEV_STATE_FAULTED;
2792         zc.zc_obj = aux;
2793
2794         if (ioctl(hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2795                 return (0);
2796
2797         switch (errno) {
2798         case EBUSY:
2799
2800                 /*
2801                  * There are no other replicas of this device.
2802                  */
2803                 return (zfs_error(hdl, EZFS_NOREPLICAS, msg));
2804
2805         default:
2806                 return (zpool_standard_error(hdl, errno, msg));
2807         }
2808
2809 }
2810
2811 /*
2812  * Mark the given vdev degraded.
2813  */
2814 int
2815 zpool_vdev_degrade(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux)
2816 {
2817         zfs_cmd_t zc = {"\0"};
2818         char msg[1024];
2819         libzfs_handle_t *hdl = zhp->zpool_hdl;
2820
2821         (void) snprintf(msg, sizeof (msg),
2822             dgettext(TEXT_DOMAIN, "cannot degrade %llu"), (u_longlong_t)guid);
2823
2824         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2825         zc.zc_guid = guid;
2826         zc.zc_cookie = VDEV_STATE_DEGRADED;
2827         zc.zc_obj = aux;
2828
2829         if (ioctl(hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2830                 return (0);
2831
2832         return (zpool_standard_error(hdl, errno, msg));
2833 }
2834
2835 /*
2836  * Returns TRUE if the given nvlist is a vdev that was originally swapped in as
2837  * a hot spare.
2838  */
2839 static boolean_t
2840 is_replacing_spare(nvlist_t *search, nvlist_t *tgt, int which)
2841 {
2842         nvlist_t **child;
2843         uint_t c, children;
2844         char *type;
2845
2846         if (nvlist_lookup_nvlist_array(search, ZPOOL_CONFIG_CHILDREN, &child,
2847             &children) == 0) {
2848                 verify(nvlist_lookup_string(search, ZPOOL_CONFIG_TYPE,
2849                     &type) == 0);
2850
2851                 if (strcmp(type, VDEV_TYPE_SPARE) == 0 &&
2852                     children == 2 && child[which] == tgt)
2853                         return (B_TRUE);
2854
2855                 for (c = 0; c < children; c++)
2856                         if (is_replacing_spare(child[c], tgt, which))
2857                                 return (B_TRUE);
2858         }
2859
2860         return (B_FALSE);
2861 }
2862
2863 /*
2864  * Attach new_disk (fully described by nvroot) to old_disk.
2865  * If 'replacing' is specified, the new disk will replace the old one.
2866  */
2867 int
2868 zpool_vdev_attach(zpool_handle_t *zhp,
2869     const char *old_disk, const char *new_disk, nvlist_t *nvroot, int replacing)
2870 {
2871         zfs_cmd_t zc = {"\0"};
2872         char msg[1024];
2873         int ret;
2874         nvlist_t *tgt;
2875         boolean_t avail_spare, l2cache, islog;
2876         uint64_t val;
2877         char *newname;
2878         nvlist_t **child;
2879         uint_t children;
2880         nvlist_t *config_root;
2881         libzfs_handle_t *hdl = zhp->zpool_hdl;
2882         boolean_t rootpool = zpool_is_bootable(zhp);
2883
2884         if (replacing)
2885                 (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2886                     "cannot replace %s with %s"), old_disk, new_disk);
2887         else
2888                 (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2889                     "cannot attach %s to %s"), new_disk, old_disk);
2890
2891         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2892         if ((tgt = zpool_find_vdev(zhp, old_disk, &avail_spare, &l2cache,
2893             &islog)) == NULL)
2894                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
2895
2896         if (avail_spare)
2897                 return (zfs_error(hdl, EZFS_ISSPARE, msg));
2898
2899         if (l2cache)
2900                 return (zfs_error(hdl, EZFS_ISL2CACHE, msg));
2901
2902         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2903         zc.zc_cookie = replacing;
2904
2905         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
2906             &child, &children) != 0 || children != 1) {
2907                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2908                     "new device must be a single disk"));
2909                 return (zfs_error(hdl, EZFS_INVALCONFIG, msg));
2910         }
2911
2912         verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
2913             ZPOOL_CONFIG_VDEV_TREE, &config_root) == 0);
2914
2915         if ((newname = zpool_vdev_name(NULL, NULL, child[0], 0)) == NULL)
2916                 return (-1);
2917
2918         /*
2919          * If the target is a hot spare that has been swapped in, we can only
2920          * replace it with another hot spare.
2921          */
2922         if (replacing &&
2923             nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_IS_SPARE, &val) == 0 &&
2924             (zpool_find_vdev(zhp, newname, &avail_spare, &l2cache,
2925             NULL) == NULL || !avail_spare) &&
2926             is_replacing_spare(config_root, tgt, 1)) {
2927                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2928                     "can only be replaced by another hot spare"));
2929                 free(newname);
2930                 return (zfs_error(hdl, EZFS_BADTARGET, msg));
2931         }
2932
2933         free(newname);
2934
2935         if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
2936                 return (-1);
2937
2938         ret = zfs_ioctl(hdl, ZFS_IOC_VDEV_ATTACH, &zc);
2939
2940         zcmd_free_nvlists(&zc);
2941
2942         if (ret == 0) {
2943                 if (rootpool) {
2944                         /*
2945                          * XXX need a better way to prevent user from
2946                          * booting up a half-baked vdev.
2947                          */
2948                         (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Make "
2949                             "sure to wait until resilver is done "
2950                             "before rebooting.\n"));
2951                 }
2952                 return (0);
2953         }
2954
2955         switch (errno) {
2956         case ENOTSUP:
2957                 /*
2958                  * Can't attach to or replace this type of vdev.
2959                  */
2960                 if (replacing) {
2961                         uint64_t version = zpool_get_prop_int(zhp,
2962                             ZPOOL_PROP_VERSION, NULL);
2963
2964                         if (islog)
2965                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2966                                     "cannot replace a log with a spare"));
2967                         else if (version >= SPA_VERSION_MULTI_REPLACE)
2968                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2969                                     "already in replacing/spare config; wait "
2970                                     "for completion or use 'zpool detach'"));
2971                         else
2972                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2973                                     "cannot replace a replacing device"));
2974                 } else {
2975                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2976                             "can only attach to mirrors and top-level "
2977                             "disks"));
2978                 }
2979                 (void) zfs_error(hdl, EZFS_BADTARGET, msg);
2980                 break;
2981
2982         case EINVAL:
2983                 /*
2984                  * The new device must be a single disk.
2985                  */
2986                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2987                     "new device must be a single disk"));
2988                 (void) zfs_error(hdl, EZFS_INVALCONFIG, msg);
2989                 break;
2990
2991         case EBUSY:
2992                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "%s is busy, "
2993                     "or device removal is in progress"),
2994                     new_disk);
2995                 (void) zfs_error(hdl, EZFS_BADDEV, msg);
2996                 break;
2997
2998         case EOVERFLOW:
2999                 /*
3000                  * The new device is too small.
3001                  */
3002                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3003                     "device is too small"));
3004                 (void) zfs_error(hdl, EZFS_BADDEV, msg);
3005                 break;
3006
3007         case EDOM:
3008                 /*
3009                  * The new device has a different optimal sector size.
3010                  */
3011                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3012                     "new device has a different optimal sector size; use the "
3013                     "option '-o ashift=N' to override the optimal size"));
3014                 (void) zfs_error(hdl, EZFS_BADDEV, msg);
3015                 break;
3016
3017         case ENAMETOOLONG:
3018                 /*
3019                  * The resulting top-level vdev spec won't fit in the label.
3020                  */
3021                 (void) zfs_error(hdl, EZFS_DEVOVERFLOW, msg);
3022                 break;
3023
3024         default:
3025                 (void) zpool_standard_error(hdl, errno, msg);
3026         }
3027
3028         return (-1);
3029 }
3030
3031 /*
3032  * Detach the specified device.
3033  */
3034 int
3035 zpool_vdev_detach(zpool_handle_t *zhp, const char *path)
3036 {
3037         zfs_cmd_t zc = {"\0"};
3038         char msg[1024];
3039         nvlist_t *tgt;
3040         boolean_t avail_spare, l2cache;
3041         libzfs_handle_t *hdl = zhp->zpool_hdl;
3042
3043         (void) snprintf(msg, sizeof (msg),
3044             dgettext(TEXT_DOMAIN, "cannot detach %s"), path);
3045
3046         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3047         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3048             NULL)) == NULL)
3049                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
3050
3051         if (avail_spare)
3052                 return (zfs_error(hdl, EZFS_ISSPARE, msg));
3053
3054         if (l2cache)
3055                 return (zfs_error(hdl, EZFS_ISL2CACHE, msg));
3056
3057         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
3058
3059         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_DETACH, &zc) == 0)
3060                 return (0);
3061
3062         switch (errno) {
3063
3064         case ENOTSUP:
3065                 /*
3066                  * Can't detach from this type of vdev.
3067                  */
3068                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "only "
3069                     "applicable to mirror and replacing vdevs"));
3070                 (void) zfs_error(hdl, EZFS_BADTARGET, msg);
3071                 break;
3072
3073         case EBUSY:
3074                 /*
3075                  * There are no other replicas of this device.
3076                  */
3077                 (void) zfs_error(hdl, EZFS_NOREPLICAS, msg);
3078                 break;
3079
3080         default:
3081                 (void) zpool_standard_error(hdl, errno, msg);
3082         }
3083
3084         return (-1);
3085 }
3086
3087 /*
3088  * Find a mirror vdev in the source nvlist.
3089  *
3090  * The mchild array contains a list of disks in one of the top-level mirrors
3091  * of the source pool.  The schild array contains a list of disks that the
3092  * user specified on the command line.  We loop over the mchild array to
3093  * see if any entry in the schild array matches.
3094  *
3095  * If a disk in the mchild array is found in the schild array, we return
3096  * the index of that entry.  Otherwise we return -1.
3097  */
3098 static int
3099 find_vdev_entry(zpool_handle_t *zhp, nvlist_t **mchild, uint_t mchildren,
3100     nvlist_t **schild, uint_t schildren)
3101 {
3102         uint_t mc;
3103
3104         for (mc = 0; mc < mchildren; mc++) {
3105                 uint_t sc;
3106                 char *mpath = zpool_vdev_name(zhp->zpool_hdl, zhp,
3107                     mchild[mc], 0);
3108
3109                 for (sc = 0; sc < schildren; sc++) {
3110                         char *spath = zpool_vdev_name(zhp->zpool_hdl, zhp,
3111                             schild[sc], 0);
3112                         boolean_t result = (strcmp(mpath, spath) == 0);
3113
3114                         free(spath);
3115                         if (result) {
3116                                 free(mpath);
3117                                 return (mc);
3118                         }
3119                 }
3120
3121                 free(mpath);
3122         }
3123
3124         return (-1);
3125 }
3126
3127 /*
3128  * Split a mirror pool.  If newroot points to null, then a new nvlist
3129  * is generated and it is the responsibility of the caller to free it.
3130  */
3131 int
3132 zpool_vdev_split(zpool_handle_t *zhp, char *newname, nvlist_t **newroot,
3133     nvlist_t *props, splitflags_t flags)
3134 {
3135         zfs_cmd_t zc = {"\0"};
3136         char msg[1024];
3137         nvlist_t *tree, *config, **child, **newchild, *newconfig = NULL;
3138         nvlist_t **varray = NULL, *zc_props = NULL;
3139         uint_t c, children, newchildren, lastlog = 0, vcount, found = 0;
3140         libzfs_handle_t *hdl = zhp->zpool_hdl;
3141         uint64_t vers, readonly = B_FALSE;
3142         boolean_t freelist = B_FALSE, memory_err = B_TRUE;
3143         int retval = 0;
3144
3145         (void) snprintf(msg, sizeof (msg),
3146             dgettext(TEXT_DOMAIN, "Unable to split %s"), zhp->zpool_name);
3147
3148         if (!zpool_name_valid(hdl, B_FALSE, newname))
3149                 return (zfs_error(hdl, EZFS_INVALIDNAME, msg));
3150
3151         if ((config = zpool_get_config(zhp, NULL)) == NULL) {
3152                 (void) fprintf(stderr, gettext("Internal error: unable to "
3153                     "retrieve pool configuration\n"));
3154                 return (-1);
3155         }
3156
3157         verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &tree)
3158             == 0);
3159         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION, &vers) == 0);
3160
3161         if (props) {
3162                 prop_flags_t flags = { .create = B_FALSE, .import = B_TRUE };
3163                 if ((zc_props = zpool_valid_proplist(hdl, zhp->zpool_name,
3164                     props, vers, flags, msg)) == NULL)
3165                         return (-1);
3166                 (void) nvlist_lookup_uint64(zc_props,
3167                     zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
3168                 if (readonly) {
3169                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3170                             "property %s can only be set at import time"),
3171                             zpool_prop_to_name(ZPOOL_PROP_READONLY));
3172                         return (-1);
3173                 }
3174         }
3175
3176         if (nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN, &child,
3177             &children) != 0) {
3178                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3179                     "Source pool is missing vdev tree"));
3180                 nvlist_free(zc_props);
3181                 return (-1);
3182         }
3183
3184         varray = zfs_alloc(hdl, children * sizeof (nvlist_t *));
3185         vcount = 0;
3186
3187         if (*newroot == NULL ||
3188             nvlist_lookup_nvlist_array(*newroot, ZPOOL_CONFIG_CHILDREN,
3189             &newchild, &newchildren) != 0)
3190                 newchildren = 0;
3191
3192         for (c = 0; c < children; c++) {
3193                 uint64_t is_log = B_FALSE, is_hole = B_FALSE;
3194                 char *type;
3195                 nvlist_t **mchild, *vdev;
3196                 uint_t mchildren;
3197                 int entry;
3198
3199                 /*
3200                  * Unlike cache & spares, slogs are stored in the
3201                  * ZPOOL_CONFIG_CHILDREN array.  We filter them out here.
3202                  */
3203                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3204                     &is_log);
3205                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
3206                     &is_hole);
3207                 if (is_log || is_hole) {
3208                         /*
3209                          * Create a hole vdev and put it in the config.
3210                          */
3211                         if (nvlist_alloc(&vdev, NV_UNIQUE_NAME, 0) != 0)
3212                                 goto out;
3213                         if (nvlist_add_string(vdev, ZPOOL_CONFIG_TYPE,
3214                             VDEV_TYPE_HOLE) != 0)
3215                                 goto out;
3216                         if (nvlist_add_uint64(vdev, ZPOOL_CONFIG_IS_HOLE,
3217                             1) != 0)
3218                                 goto out;
3219                         if (lastlog == 0)
3220                                 lastlog = vcount;
3221                         varray[vcount++] = vdev;
3222                         continue;
3223                 }
3224                 lastlog = 0;
3225                 verify(nvlist_lookup_string(child[c], ZPOOL_CONFIG_TYPE, &type)
3226                     == 0);
3227                 if (strcmp(type, VDEV_TYPE_MIRROR) != 0) {
3228                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3229                             "Source pool must be composed only of mirrors\n"));
3230                         retval = zfs_error(hdl, EZFS_INVALCONFIG, msg);
3231                         goto out;
3232                 }
3233
3234                 verify(nvlist_lookup_nvlist_array(child[c],
3235                     ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren) == 0);
3236
3237                 /* find or add an entry for this top-level vdev */
3238                 if (newchildren > 0 &&
3239                     (entry = find_vdev_entry(zhp, mchild, mchildren,
3240                     newchild, newchildren)) >= 0) {
3241                         /* We found a disk that the user specified. */
3242                         vdev = mchild[entry];
3243                         ++found;
3244                 } else {
3245                         /* User didn't specify a disk for this vdev. */
3246                         vdev = mchild[mchildren - 1];
3247                 }
3248
3249                 if (nvlist_dup(vdev, &varray[vcount++], 0) != 0)
3250                         goto out;
3251         }
3252
3253         /* did we find every disk the user specified? */
3254         if (found != newchildren) {
3255                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Device list must "
3256                     "include at most one disk from each mirror"));
3257                 retval = zfs_error(hdl, EZFS_INVALCONFIG, msg);
3258                 goto out;
3259         }
3260
3261         /* Prepare the nvlist for populating. */
3262         if (*newroot == NULL) {
3263                 if (nvlist_alloc(newroot, NV_UNIQUE_NAME, 0) != 0)
3264                         goto out;
3265                 freelist = B_TRUE;
3266                 if (nvlist_add_string(*newroot, ZPOOL_CONFIG_TYPE,
3267                     VDEV_TYPE_ROOT) != 0)
3268                         goto out;
3269         } else {
3270                 verify(nvlist_remove_all(*newroot, ZPOOL_CONFIG_CHILDREN) == 0);
3271         }
3272
3273         /* Add all the children we found */
3274         if (nvlist_add_nvlist_array(*newroot, ZPOOL_CONFIG_CHILDREN, varray,
3275             lastlog == 0 ? vcount : lastlog) != 0)
3276                 goto out;
3277
3278         /*
3279          * If we're just doing a dry run, exit now with success.
3280          */
3281         if (flags.dryrun) {
3282                 memory_err = B_FALSE;
3283                 freelist = B_FALSE;
3284                 goto out;
3285         }
3286
3287         /* now build up the config list & call the ioctl */
3288         if (nvlist_alloc(&newconfig, NV_UNIQUE_NAME, 0) != 0)
3289                 goto out;
3290
3291         if (nvlist_add_nvlist(newconfig,
3292             ZPOOL_CONFIG_VDEV_TREE, *newroot) != 0 ||
3293             nvlist_add_string(newconfig,
3294             ZPOOL_CONFIG_POOL_NAME, newname) != 0 ||
3295             nvlist_add_uint64(newconfig, ZPOOL_CONFIG_VERSION, vers) != 0)
3296                 goto out;
3297
3298         /*
3299          * The new pool is automatically part of the namespace unless we
3300          * explicitly export it.
3301          */
3302         if (!flags.import)
3303                 zc.zc_cookie = ZPOOL_EXPORT_AFTER_SPLIT;
3304         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3305         (void) strlcpy(zc.zc_string, newname, sizeof (zc.zc_string));
3306         if (zcmd_write_conf_nvlist(hdl, &zc, newconfig) != 0)
3307                 goto out;
3308         if (zc_props != NULL && zcmd_write_src_nvlist(hdl, &zc, zc_props) != 0)
3309                 goto out;
3310
3311         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SPLIT, &zc) != 0) {
3312                 retval = zpool_standard_error(hdl, errno, msg);
3313                 goto out;
3314         }
3315
3316         freelist = B_FALSE;
3317         memory_err = B_FALSE;
3318
3319 out:
3320         if (varray != NULL) {
3321                 int v;
3322
3323                 for (v = 0; v < vcount; v++)
3324                         nvlist_free(varray[v]);
3325                 free(varray);
3326         }
3327         zcmd_free_nvlists(&zc);
3328         nvlist_free(zc_props);
3329         nvlist_free(newconfig);
3330         if (freelist) {
3331                 nvlist_free(*newroot);
3332                 *newroot = NULL;
3333         }
3334
3335         if (retval != 0)
3336                 return (retval);
3337
3338         if (memory_err)
3339                 return (no_memory(hdl));
3340
3341         return (0);
3342 }
3343
3344 /*
3345  * Remove the given device.
3346  */
3347 int
3348 zpool_vdev_remove(zpool_handle_t *zhp, const char *path)
3349 {
3350         zfs_cmd_t zc = {"\0"};
3351         char msg[1024];
3352         nvlist_t *tgt;
3353         boolean_t avail_spare, l2cache, islog;
3354         libzfs_handle_t *hdl = zhp->zpool_hdl;
3355         uint64_t version;
3356
3357         (void) snprintf(msg, sizeof (msg),
3358             dgettext(TEXT_DOMAIN, "cannot remove %s"), path);
3359
3360         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3361         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3362             &islog)) == NULL)
3363                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
3364
3365         version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
3366         if (islog && version < SPA_VERSION_HOLES) {
3367                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3368                     "pool must be upgraded to support log removal"));
3369                 return (zfs_error(hdl, EZFS_BADVERSION, msg));
3370         }
3371
3372         if (!islog && !avail_spare && !l2cache && zpool_is_bootable(zhp)) {
3373                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3374                     "root pool can not have removed devices, "
3375                     "because GRUB does not understand them"));
3376                 return (zfs_error(hdl, EINVAL, msg));
3377         }
3378
3379         zc.zc_guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
3380
3381         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_REMOVE, &zc) == 0)
3382                 return (0);
3383
3384         switch (errno) {
3385
3386         case EINVAL:
3387                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3388                     "invalid config; all top-level vdevs must "
3389                     "have the same sector size and not be raidz."));
3390                 (void) zfs_error(hdl, EZFS_INVALCONFIG, msg);
3391                 break;
3392
3393         case EBUSY:
3394                 if (islog) {
3395                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3396                             "Mount encrypted datasets to replay logs."));
3397                 } else {
3398                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3399                             "Pool busy; removal may already be in progress"));
3400                 }
3401                 (void) zfs_error(hdl, EZFS_BUSY, msg);
3402                 break;
3403
3404         case EACCES:
3405                 if (islog) {
3406                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3407                             "Mount encrypted datasets to replay logs."));
3408                         (void) zfs_error(hdl, EZFS_BUSY, msg);
3409                 } else {
3410                         (void) zpool_standard_error(hdl, errno, msg);
3411                 }
3412                 break;
3413
3414         default:
3415                 (void) zpool_standard_error(hdl, errno, msg);
3416         }
3417         return (-1);
3418 }
3419
3420 int
3421 zpool_vdev_remove_cancel(zpool_handle_t *zhp)
3422 {
3423         zfs_cmd_t zc;
3424         char msg[1024];
3425         libzfs_handle_t *hdl = zhp->zpool_hdl;
3426
3427         (void) snprintf(msg, sizeof (msg),
3428             dgettext(TEXT_DOMAIN, "cannot cancel removal"));
3429
3430         bzero(&zc, sizeof (zc));
3431         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3432         zc.zc_cookie = 1;
3433
3434         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_REMOVE, &zc) == 0)
3435                 return (0);
3436
3437         return (zpool_standard_error(hdl, errno, msg));
3438 }
3439
3440 int
3441 zpool_vdev_indirect_size(zpool_handle_t *zhp, const char *path,
3442     uint64_t *sizep)
3443 {
3444         char msg[1024];
3445         nvlist_t *tgt;
3446         boolean_t avail_spare, l2cache, islog;
3447         libzfs_handle_t *hdl = zhp->zpool_hdl;
3448
3449         (void) snprintf(msg, sizeof (msg),
3450             dgettext(TEXT_DOMAIN, "cannot determine indirect size of %s"),
3451             path);
3452
3453         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3454             &islog)) == NULL)
3455                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
3456
3457         if (avail_spare || l2cache || islog) {
3458                 *sizep = 0;
3459                 return (0);
3460         }
3461
3462         if (nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_INDIRECT_SIZE, sizep) != 0) {
3463                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3464                     "indirect size not available"));
3465                 return (zfs_error(hdl, EINVAL, msg));
3466         }
3467         return (0);
3468 }
3469
3470 /*
3471  * Clear the errors for the pool, or the particular device if specified.
3472  */
3473 int
3474 zpool_clear(zpool_handle_t *zhp, const char *path, nvlist_t *rewindnvl)
3475 {
3476         zfs_cmd_t zc = {"\0"};
3477         char msg[1024];
3478         nvlist_t *tgt;
3479         zpool_load_policy_t policy;
3480         boolean_t avail_spare, l2cache;
3481         libzfs_handle_t *hdl = zhp->zpool_hdl;
3482         nvlist_t *nvi = NULL;
3483         int error;
3484
3485         if (path)
3486                 (void) snprintf(msg, sizeof (msg),
3487                     dgettext(TEXT_DOMAIN, "cannot clear errors for %s"),
3488                     path);
3489         else
3490                 (void) snprintf(msg, sizeof (msg),
3491                     dgettext(TEXT_DOMAIN, "cannot clear errors for %s"),
3492                     zhp->zpool_name);
3493
3494         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3495         if (path) {
3496                 if ((tgt = zpool_find_vdev(zhp, path, &avail_spare,
3497                     &l2cache, NULL)) == NULL)
3498                         return (zfs_error(hdl, EZFS_NODEVICE, msg));
3499
3500                 /*
3501                  * Don't allow error clearing for hot spares.  Do allow
3502                  * error clearing for l2cache devices.
3503                  */
3504                 if (avail_spare)
3505                         return (zfs_error(hdl, EZFS_ISSPARE, msg));
3506
3507                 verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID,
3508                     &zc.zc_guid) == 0);
3509         }
3510
3511         zpool_get_load_policy(rewindnvl, &policy);
3512         zc.zc_cookie = policy.zlp_rewind;
3513
3514         if (zcmd_alloc_dst_nvlist(hdl, &zc, zhp->zpool_config_size * 2) != 0)
3515                 return (-1);
3516
3517         if (zcmd_write_src_nvlist(hdl, &zc, rewindnvl) != 0)
3518                 return (-1);
3519
3520         while ((error = zfs_ioctl(hdl, ZFS_IOC_CLEAR, &zc)) != 0 &&
3521             errno == ENOMEM) {
3522                 if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
3523                         zcmd_free_nvlists(&zc);
3524                         return (-1);
3525                 }
3526         }
3527
3528         if (!error || ((policy.zlp_rewind & ZPOOL_TRY_REWIND) &&
3529             errno != EPERM && errno != EACCES)) {
3530                 if (policy.zlp_rewind &
3531                     (ZPOOL_DO_REWIND | ZPOOL_TRY_REWIND)) {
3532                         (void) zcmd_read_dst_nvlist(hdl, &zc, &nvi);
3533                         zpool_rewind_exclaim(hdl, zc.zc_name,
3534                             ((policy.zlp_rewind & ZPOOL_TRY_REWIND) != 0),
3535                             nvi);
3536                         nvlist_free(nvi);
3537                 }
3538                 zcmd_free_nvlists(&zc);
3539                 return (0);
3540         }
3541
3542         zcmd_free_nvlists(&zc);
3543         return (zpool_standard_error(hdl, errno, msg));
3544 }
3545
3546 /*
3547  * Similar to zpool_clear(), but takes a GUID (used by fmd).
3548  */
3549 int
3550 zpool_vdev_clear(zpool_handle_t *zhp, uint64_t guid)
3551 {
3552         zfs_cmd_t zc = {"\0"};
3553         char msg[1024];
3554         libzfs_handle_t *hdl = zhp->zpool_hdl;
3555
3556         (void) snprintf(msg, sizeof (msg),
3557             dgettext(TEXT_DOMAIN, "cannot clear errors for %llx"),
3558             (u_longlong_t)guid);
3559
3560         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3561         zc.zc_guid = guid;
3562         zc.zc_cookie = ZPOOL_NO_REWIND;
3563
3564         if (ioctl(hdl->libzfs_fd, ZFS_IOC_CLEAR, &zc) == 0)
3565                 return (0);
3566
3567         return (zpool_standard_error(hdl, errno, msg));
3568 }
3569
3570 /*
3571  * Change the GUID for a pool.
3572  */
3573 int
3574 zpool_reguid(zpool_handle_t *zhp)
3575 {
3576         char msg[1024];
3577         libzfs_handle_t *hdl = zhp->zpool_hdl;
3578         zfs_cmd_t zc = {"\0"};
3579
3580         (void) snprintf(msg, sizeof (msg),
3581             dgettext(TEXT_DOMAIN, "cannot reguid '%s'"), zhp->zpool_name);
3582
3583         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3584         if (zfs_ioctl(hdl, ZFS_IOC_POOL_REGUID, &zc) == 0)
3585                 return (0);
3586
3587         return (zpool_standard_error(hdl, errno, msg));
3588 }
3589
3590 /*
3591  * Reopen the pool.
3592  */
3593 int
3594 zpool_reopen_one(zpool_handle_t *zhp, void *data)
3595 {
3596         libzfs_handle_t *hdl = zpool_get_handle(zhp);
3597         const char *pool_name = zpool_get_name(zhp);
3598         boolean_t *scrub_restart = data;
3599         int error;
3600
3601         error = lzc_reopen(pool_name, *scrub_restart);
3602         if (error) {
3603                 return (zpool_standard_error_fmt(hdl, error,
3604                     dgettext(TEXT_DOMAIN, "cannot reopen '%s'"), pool_name));
3605         }
3606
3607         return (0);
3608 }
3609
3610 /* call into libzfs_core to execute the sync IOCTL per pool */
3611 int
3612 zpool_sync_one(zpool_handle_t *zhp, void *data)
3613 {
3614         int ret;
3615         libzfs_handle_t *hdl = zpool_get_handle(zhp);
3616         const char *pool_name = zpool_get_name(zhp);
3617         boolean_t *force = data;
3618         nvlist_t *innvl = fnvlist_alloc();
3619
3620         fnvlist_add_boolean_value(innvl, "force", *force);
3621         if ((ret = lzc_sync(pool_name, innvl, NULL)) != 0) {
3622                 nvlist_free(innvl);
3623                 return (zpool_standard_error_fmt(hdl, ret,
3624                     dgettext(TEXT_DOMAIN, "sync '%s' failed"), pool_name));
3625         }
3626         nvlist_free(innvl);
3627
3628         return (0);
3629 }
3630
3631 #if defined(__sun__) || defined(__sun)
3632 /*
3633  * Convert from a devid string to a path.
3634  */
3635 static char *
3636 devid_to_path(char *devid_str)
3637 {
3638         ddi_devid_t devid;
3639         char *minor;
3640         char *path;
3641         devid_nmlist_t *list = NULL;
3642         int ret;
3643
3644         if (devid_str_decode(devid_str, &devid, &minor) != 0)
3645                 return (NULL);
3646
3647         ret = devid_deviceid_to_nmlist("/dev", devid, minor, &list);
3648
3649         devid_str_free(minor);
3650         devid_free(devid);
3651
3652         if (ret != 0)
3653                 return (NULL);
3654
3655         /*
3656          * In a case the strdup() fails, we will just return NULL below.
3657          */
3658         path = strdup(list[0].devname);
3659
3660         devid_free_nmlist(list);
3661
3662         return (path);
3663 }
3664
3665 /*
3666  * Convert from a path to a devid string.
3667  */
3668 static char *
3669 path_to_devid(const char *path)
3670 {
3671         int fd;
3672         ddi_devid_t devid;
3673         char *minor, *ret;
3674
3675         if ((fd = open(path, O_RDONLY)) < 0)
3676                 return (NULL);
3677
3678         minor = NULL;
3679         ret = NULL;
3680         if (devid_get(fd, &devid) == 0) {
3681                 if (devid_get_minor_name(fd, &minor) == 0)
3682                         ret = devid_str_encode(devid, minor);
3683                 if (minor != NULL)
3684                         devid_str_free(minor);
3685                 devid_free(devid);
3686         }
3687         (void) close(fd);
3688
3689         return (ret);
3690 }
3691
3692 /*
3693  * Issue the necessary ioctl() to update the stored path value for the vdev.  We
3694  * ignore any failure here, since a common case is for an unprivileged user to
3695  * type 'zpool status', and we'll display the correct information anyway.
3696  */
3697 static void
3698 set_path(zpool_handle_t *zhp, nvlist_t *nv, const char *path)
3699 {
3700         zfs_cmd_t zc = {"\0"};
3701
3702         (void) strncpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3703         (void) strncpy(zc.zc_value, path, sizeof (zc.zc_value));
3704         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
3705             &zc.zc_guid) == 0);
3706
3707         (void) ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_VDEV_SETPATH, &zc);
3708 }
3709 #endif /* sun */
3710
3711 #define PATH_BUF_LEN    64
3712
3713 /*
3714  * Given a vdev, return the name to display in iostat.  If the vdev has a path,
3715  * we use that, stripping off any leading "/dev/dsk/"; if not, we use the type.
3716  * We also check if this is a whole disk, in which case we strip off the
3717  * trailing 's0' slice name.
3718  *
3719  * This routine is also responsible for identifying when disks have been
3720  * reconfigured in a new location.  The kernel will have opened the device by
3721  * devid, but the path will still refer to the old location.  To catch this, we
3722  * first do a path -> devid translation (which is fast for the common case).  If
3723  * the devid matches, we're done.  If not, we do a reverse devid -> path
3724  * translation and issue the appropriate ioctl() to update the path of the vdev.
3725  * If 'zhp' is NULL, then this is an exported pool, and we don't need to do any
3726  * of these checks.
3727  */
3728 char *
3729 zpool_vdev_name(libzfs_handle_t *hdl, zpool_handle_t *zhp, nvlist_t *nv,
3730     int name_flags)
3731 {
3732         char *path, *type, *env;
3733         uint64_t value;
3734         char buf[PATH_BUF_LEN];
3735         char tmpbuf[PATH_BUF_LEN];
3736
3737         /*
3738          * vdev_name will be "root"/"root-0" for the root vdev, but it is the
3739          * zpool name that will be displayed to the user.
3740          */
3741         verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
3742         if (zhp != NULL && strcmp(type, "root") == 0)
3743                 return (zfs_strdup(hdl, zpool_get_name(zhp)));
3744
3745         env = getenv("ZPOOL_VDEV_NAME_PATH");
3746         if (env && (strtoul(env, NULL, 0) > 0 ||
3747             !strncasecmp(env, "YES", 3) || !strncasecmp(env, "ON", 2)))
3748                 name_flags |= VDEV_NAME_PATH;
3749
3750         env = getenv("ZPOOL_VDEV_NAME_GUID");
3751         if (env && (strtoul(env, NULL, 0) > 0 ||
3752             !strncasecmp(env, "YES", 3) || !strncasecmp(env, "ON", 2)))
3753                 name_flags |= VDEV_NAME_GUID;
3754
3755         env = getenv("ZPOOL_VDEV_NAME_FOLLOW_LINKS");
3756         if (env && (strtoul(env, NULL, 0) > 0 ||
3757             !strncasecmp(env, "YES", 3) || !strncasecmp(env, "ON", 2)))
3758                 name_flags |= VDEV_NAME_FOLLOW_LINKS;
3759
3760         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, &value) == 0 ||
3761             name_flags & VDEV_NAME_GUID) {
3762                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &value);
3763                 (void) snprintf(buf, sizeof (buf), "%llu", (u_longlong_t)value);
3764                 path = buf;
3765         } else if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
3766 #if defined(__sun__) || defined(__sun)
3767                 /*
3768                  * Live VDEV path updates to a kernel VDEV during a
3769                  * zpool_vdev_name lookup are not supported on Linux.
3770                  */
3771                 char *devid;
3772                 vdev_stat_t *vs;
3773                 uint_t vsc;
3774
3775                 /*
3776                  * If the device is dead (faulted, offline, etc) then don't
3777                  * bother opening it.  Otherwise we may be forcing the user to
3778                  * open a misbehaving device, which can have undesirable
3779                  * effects.
3780                  */
3781                 if ((nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
3782                     (uint64_t **)&vs, &vsc) != 0 ||
3783                     vs->vs_state >= VDEV_STATE_DEGRADED) &&
3784                     zhp != NULL &&
3785                     nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &devid) == 0) {
3786                         /*
3787                          * Determine if the current path is correct.
3788                          */
3789                         char *newdevid = path_to_devid(path);
3790
3791                         if (newdevid == NULL ||
3792                             strcmp(devid, newdevid) != 0) {
3793                                 char *newpath;
3794
3795                                 if ((newpath = devid_to_path(devid)) != NULL) {
3796                                         /*
3797                                          * Update the path appropriately.
3798                                          */
3799                                         set_path(zhp, nv, newpath);
3800                                         if (nvlist_add_string(nv,
3801                                             ZPOOL_CONFIG_PATH, newpath) == 0)
3802                                                 verify(nvlist_lookup_string(nv,
3803                                                     ZPOOL_CONFIG_PATH,
3804                                                     &path) == 0);
3805                                         free(newpath);
3806                                 }
3807                         }
3808
3809                         if (newdevid)
3810                                 devid_str_free(newdevid);
3811                 }
3812 #endif /* sun */
3813
3814                 if (name_flags & VDEV_NAME_FOLLOW_LINKS) {
3815                         char *rp = realpath(path, NULL);
3816                         if (rp) {
3817                                 strlcpy(buf, rp, sizeof (buf));
3818                                 path = buf;
3819                                 free(rp);
3820                         }
3821                 }
3822
3823                 /*
3824                  * For a block device only use the name.
3825                  */
3826                 if ((strcmp(type, VDEV_TYPE_DISK) == 0) &&
3827                     !(name_flags & VDEV_NAME_PATH)) {
3828                         path = strrchr(path, '/');
3829                         path++;
3830                 }
3831
3832                 /*
3833                  * Remove the partition from the path it this is a whole disk.
3834                  */
3835                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK, &value)
3836                     == 0 && value && !(name_flags & VDEV_NAME_PATH)) {
3837                         return (zfs_strip_partition(path));
3838                 }
3839         } else {
3840                 path = type;
3841
3842                 /*
3843                  * If it's a raidz device, we need to stick in the parity level.
3844                  */
3845                 if (strcmp(path, VDEV_TYPE_RAIDZ) == 0) {
3846                         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
3847                             &value) == 0);
3848                         (void) snprintf(buf, sizeof (buf), "%s%llu", path,
3849                             (u_longlong_t)value);
3850                         path = buf;
3851                 }
3852
3853                 /*
3854                  * We identify each top-level vdev by using a <type-id>
3855                  * naming convention.
3856                  */
3857                 if (name_flags & VDEV_NAME_TYPE_ID) {
3858                         uint64_t id;
3859                         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID,
3860                             &id) == 0);
3861                         (void) snprintf(tmpbuf, sizeof (tmpbuf), "%s-%llu",
3862                             path, (u_longlong_t)id);
3863                         path = tmpbuf;
3864                 }
3865         }
3866
3867         return (zfs_strdup(hdl, path));
3868 }
3869
3870 static int
3871 zbookmark_mem_compare(const void *a, const void *b)
3872 {
3873         return (memcmp(a, b, sizeof (zbookmark_phys_t)));
3874 }
3875
3876 /*
3877  * Retrieve the persistent error log, uniquify the members, and return to the
3878  * caller.
3879  */
3880 int
3881 zpool_get_errlog(zpool_handle_t *zhp, nvlist_t **nverrlistp)
3882 {
3883         zfs_cmd_t zc = {"\0"};
3884         libzfs_handle_t *hdl = zhp->zpool_hdl;
3885         uint64_t count;
3886         zbookmark_phys_t *zb = NULL;
3887         int i;
3888
3889         /*
3890          * Retrieve the raw error list from the kernel.  If the number of errors
3891          * has increased, allocate more space and continue until we get the
3892          * entire list.
3893          */
3894         verify(nvlist_lookup_uint64(zhp->zpool_config, ZPOOL_CONFIG_ERRCOUNT,
3895             &count) == 0);
3896         if (count == 0)
3897                 return (0);
3898         zc.zc_nvlist_dst = (uintptr_t)zfs_alloc(zhp->zpool_hdl,
3899             count * sizeof (zbookmark_phys_t));
3900         zc.zc_nvlist_dst_size = count;
3901         (void) strcpy(zc.zc_name, zhp->zpool_name);
3902         for (;;) {
3903                 if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_ERROR_LOG,
3904                     &zc) != 0) {
3905                         free((void *)(uintptr_t)zc.zc_nvlist_dst);
3906                         if (errno == ENOMEM) {
3907                                 void *dst;
3908
3909                                 count = zc.zc_nvlist_dst_size;
3910                                 dst = zfs_alloc(zhp->zpool_hdl, count *
3911                                     sizeof (zbookmark_phys_t));
3912                                 zc.zc_nvlist_dst = (uintptr_t)dst;
3913                         } else {
3914                                 return (zpool_standard_error_fmt(hdl, errno,
3915                                     dgettext(TEXT_DOMAIN, "errors: List of "
3916                                     "errors unavailable")));
3917                         }
3918                 } else {
3919                         break;
3920                 }
3921         }
3922
3923         /*
3924          * Sort the resulting bookmarks.  This is a little confusing due to the
3925          * implementation of ZFS_IOC_ERROR_LOG.  The bookmarks are copied last
3926          * to first, and 'zc_nvlist_dst_size' indicates the number of boomarks
3927          * _not_ copied as part of the process.  So we point the start of our
3928          * array appropriate and decrement the total number of elements.
3929          */
3930         zb = ((zbookmark_phys_t *)(uintptr_t)zc.zc_nvlist_dst) +
3931             zc.zc_nvlist_dst_size;
3932         count -= zc.zc_nvlist_dst_size;
3933
3934         qsort(zb, count, sizeof (zbookmark_phys_t), zbookmark_mem_compare);
3935
3936         verify(nvlist_alloc(nverrlistp, 0, KM_SLEEP) == 0);
3937
3938         /*
3939          * Fill in the nverrlistp with nvlist's of dataset and object numbers.
3940          */
3941         for (i = 0; i < count; i++) {
3942                 nvlist_t *nv;
3943
3944                 /* ignoring zb_blkid and zb_level for now */
3945                 if (i > 0 && zb[i-1].zb_objset == zb[i].zb_objset &&
3946                     zb[i-1].zb_object == zb[i].zb_object)
3947                         continue;
3948
3949                 if (nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) != 0)
3950                         goto nomem;
3951                 if (nvlist_add_uint64(nv, ZPOOL_ERR_DATASET,
3952                     zb[i].zb_objset) != 0) {
3953                         nvlist_free(nv);
3954                         goto nomem;
3955                 }
3956                 if (nvlist_add_uint64(nv, ZPOOL_ERR_OBJECT,
3957                     zb[i].zb_object) != 0) {
3958                         nvlist_free(nv);
3959                         goto nomem;
3960                 }
3961                 if (nvlist_add_nvlist(*nverrlistp, "ejk", nv) != 0) {
3962                         nvlist_free(nv);
3963                         goto nomem;
3964                 }
3965                 nvlist_free(nv);
3966         }
3967
3968         free((void *)(uintptr_t)zc.zc_nvlist_dst);
3969         return (0);
3970
3971 nomem:
3972         free((void *)(uintptr_t)zc.zc_nvlist_dst);
3973         return (no_memory(zhp->zpool_hdl));
3974 }
3975
3976 /*
3977  * Upgrade a ZFS pool to the latest on-disk version.
3978  */
3979 int
3980 zpool_upgrade(zpool_handle_t *zhp, uint64_t new_version)
3981 {
3982         zfs_cmd_t zc = {"\0"};
3983         libzfs_handle_t *hdl = zhp->zpool_hdl;
3984
3985         (void) strcpy(zc.zc_name, zhp->zpool_name);
3986         zc.zc_cookie = new_version;
3987
3988         if (zfs_ioctl(hdl, ZFS_IOC_POOL_UPGRADE, &zc) != 0)
3989                 return (zpool_standard_error_fmt(hdl, errno,
3990                     dgettext(TEXT_DOMAIN, "cannot upgrade '%s'"),
3991                     zhp->zpool_name));
3992         return (0);
3993 }
3994
3995 void
3996 zfs_save_arguments(int argc, char **argv, char *string, int len)
3997 {
3998         int i;
3999
4000         (void) strlcpy(string, basename(argv[0]), len);
4001         for (i = 1; i < argc; i++) {
4002                 (void) strlcat(string, " ", len);
4003                 (void) strlcat(string, argv[i], len);
4004         }
4005 }
4006
4007 int
4008 zpool_log_history(libzfs_handle_t *hdl, const char *message)
4009 {
4010         zfs_cmd_t zc = {"\0"};
4011         nvlist_t *args;
4012         int err;
4013
4014         args = fnvlist_alloc();
4015         fnvlist_add_string(args, "message", message);
4016         err = zcmd_write_src_nvlist(hdl, &zc, args);
4017         if (err == 0)
4018                 err = ioctl(hdl->libzfs_fd, ZFS_IOC_LOG_HISTORY, &zc);
4019         nvlist_free(args);
4020         zcmd_free_nvlists(&zc);
4021         return (err);
4022 }
4023
4024 /*
4025  * Perform ioctl to get some command history of a pool.
4026  *
4027  * 'buf' is the buffer to fill up to 'len' bytes.  'off' is the
4028  * logical offset of the history buffer to start reading from.
4029  *
4030  * Upon return, 'off' is the next logical offset to read from and
4031  * 'len' is the actual amount of bytes read into 'buf'.
4032  */
4033 static int
4034 get_history(zpool_handle_t *zhp, char *buf, uint64_t *off, uint64_t *len)
4035 {
4036         zfs_cmd_t zc = {"\0"};
4037         libzfs_handle_t *hdl = zhp->zpool_hdl;
4038
4039         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
4040
4041         zc.zc_history = (uint64_t)(uintptr_t)buf;
4042         zc.zc_history_len = *len;
4043         zc.zc_history_offset = *off;
4044
4045         if (ioctl(hdl->libzfs_fd, ZFS_IOC_POOL_GET_HISTORY, &zc) != 0) {
4046                 switch (errno) {
4047                 case EPERM:
4048                         return (zfs_error_fmt(hdl, EZFS_PERM,
4049                             dgettext(TEXT_DOMAIN,
4050                             "cannot show history for pool '%s'"),
4051                             zhp->zpool_name));
4052                 case ENOENT:
4053                         return (zfs_error_fmt(hdl, EZFS_NOHISTORY,
4054                             dgettext(TEXT_DOMAIN, "cannot get history for pool "
4055                             "'%s'"), zhp->zpool_name));
4056                 case ENOTSUP:
4057                         return (zfs_error_fmt(hdl, EZFS_BADVERSION,
4058                             dgettext(TEXT_DOMAIN, "cannot get history for pool "
4059                             "'%s', pool must be upgraded"), zhp->zpool_name));
4060                 default:
4061                         return (zpool_standard_error_fmt(hdl, errno,
4062                             dgettext(TEXT_DOMAIN,
4063                             "cannot get history for '%s'"), zhp->zpool_name));
4064                 }
4065         }
4066
4067         *len = zc.zc_history_len;
4068         *off = zc.zc_history_offset;
4069
4070         return (0);
4071 }
4072
4073 /*
4074  * Retrieve the command history of a pool.
4075  */
4076 int
4077 zpool_get_history(zpool_handle_t *zhp, nvlist_t **nvhisp)
4078 {
4079         char *buf;
4080         int buflen = 128 * 1024;
4081         uint64_t off = 0;
4082         nvlist_t **records = NULL;
4083         uint_t numrecords = 0;
4084         int err, i;
4085
4086         buf = malloc(buflen);
4087         if (buf == NULL)
4088                 return (ENOMEM);
4089         do {
4090                 uint64_t bytes_read = buflen;
4091                 uint64_t leftover;
4092
4093                 if ((err = get_history(zhp, buf, &off, &bytes_read)) != 0)
4094                         break;
4095
4096                 /* if nothing else was read in, we're at EOF, just return */
4097                 if (!bytes_read)
4098                         break;
4099
4100                 if ((err = zpool_history_unpack(buf, bytes_read,
4101                     &leftover, &records, &numrecords)) != 0)
4102                         break;
4103                 off -= leftover;
4104                 if (leftover == bytes_read) {
4105                         /*
4106                          * no progress made, because buffer is not big enough
4107                          * to hold this record; resize and retry.
4108                          */
4109                         buflen *= 2;
4110                         free(buf);
4111                         buf = malloc(buflen);
4112                         if (buf == NULL)
4113                                 return (ENOMEM);
4114                 }
4115
4116                 /* CONSTCOND */
4117         } while (1);
4118
4119         free(buf);
4120
4121         if (!err) {
4122                 verify(nvlist_alloc(nvhisp, NV_UNIQUE_NAME, 0) == 0);
4123                 verify(nvlist_add_nvlist_array(*nvhisp, ZPOOL_HIST_RECORD,
4124                     records, numrecords) == 0);
4125         }
4126         for (i = 0; i < numrecords; i++)
4127                 nvlist_free(records[i]);
4128         free(records);
4129
4130         return (err);
4131 }
4132
4133 /*
4134  * Retrieve the next event given the passed 'zevent_fd' file descriptor.
4135  * If there is a new event available 'nvp' will contain a newly allocated
4136  * nvlist and 'dropped' will be set to the number of missed events since
4137  * the last call to this function.  When 'nvp' is set to NULL it indicates
4138  * no new events are available.  In either case the function returns 0 and
4139  * it is up to the caller to free 'nvp'.  In the case of a fatal error the
4140  * function will return a non-zero value.  When the function is called in
4141  * blocking mode (the default, unless the ZEVENT_NONBLOCK flag is passed),
4142  * it will not return until a new event is available.
4143  */
4144 int
4145 zpool_events_next(libzfs_handle_t *hdl, nvlist_t **nvp,
4146     int *dropped, unsigned flags, int zevent_fd)
4147 {
4148         zfs_cmd_t zc = {"\0"};
4149         int error = 0;
4150
4151         *nvp = NULL;
4152         *dropped = 0;
4153         zc.zc_cleanup_fd = zevent_fd;
4154
4155         if (flags & ZEVENT_NONBLOCK)
4156                 zc.zc_guid = ZEVENT_NONBLOCK;
4157
4158         if (zcmd_alloc_dst_nvlist(hdl, &zc, ZEVENT_SIZE) != 0)
4159                 return (-1);
4160
4161 retry:
4162         if (zfs_ioctl(hdl, ZFS_IOC_EVENTS_NEXT, &zc) != 0) {
4163                 switch (errno) {
4164                 case ESHUTDOWN:
4165                         error = zfs_error_fmt(hdl, EZFS_POOLUNAVAIL,
4166                             dgettext(TEXT_DOMAIN, "zfs shutdown"));
4167                         goto out;
4168                 case ENOENT:
4169                         /* Blocking error case should not occur */
4170                         if (!(flags & ZEVENT_NONBLOCK))
4171                                 error = zpool_standard_error_fmt(hdl, errno,
4172                                     dgettext(TEXT_DOMAIN, "cannot get event"));
4173
4174                         goto out;
4175                 case ENOMEM:
4176                         if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
4177                                 error = zfs_error_fmt(hdl, EZFS_NOMEM,
4178                                     dgettext(TEXT_DOMAIN, "cannot get event"));
4179                                 goto out;
4180                         } else {
4181                                 goto retry;
4182                         }
4183                 default:
4184                         error = zpool_standard_error_fmt(hdl, errno,
4185                             dgettext(TEXT_DOMAIN, "cannot get event"));
4186                         goto out;
4187                 }
4188         }
4189
4190         error = zcmd_read_dst_nvlist(hdl, &zc, nvp);
4191         if (error != 0)
4192                 goto out;
4193
4194         *dropped = (int)zc.zc_cookie;
4195 out:
4196         zcmd_free_nvlists(&zc);
4197
4198         return (error);
4199 }
4200
4201 /*
4202  * Clear all events.
4203  */
4204 int
4205 zpool_events_clear(libzfs_handle_t *hdl, int *count)
4206 {
4207         zfs_cmd_t zc = {"\0"};
4208         char msg[1024];
4209
4210         (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
4211             "cannot clear events"));
4212
4213         if (zfs_ioctl(hdl, ZFS_IOC_EVENTS_CLEAR, &zc) != 0)
4214                 return (zpool_standard_error_fmt(hdl, errno, msg));
4215
4216         if (count != NULL)
4217                 *count = (int)zc.zc_cookie; /* # of events cleared */
4218
4219         return (0);
4220 }
4221
4222 /*
4223  * Seek to a specific EID, ZEVENT_SEEK_START, or ZEVENT_SEEK_END for
4224  * the passed zevent_fd file handle.  On success zero is returned,
4225  * otherwise -1 is returned and hdl->libzfs_error is set to the errno.
4226  */
4227 int
4228 zpool_events_seek(libzfs_handle_t *hdl, uint64_t eid, int zevent_fd)
4229 {
4230         zfs_cmd_t zc = {"\0"};
4231         int error = 0;
4232
4233         zc.zc_guid = eid;
4234         zc.zc_cleanup_fd = zevent_fd;
4235
4236         if (zfs_ioctl(hdl, ZFS_IOC_EVENTS_SEEK, &zc) != 0) {
4237                 switch (errno) {
4238                 case ENOENT:
4239                         error = zfs_error_fmt(hdl, EZFS_NOENT,
4240                             dgettext(TEXT_DOMAIN, "cannot get event"));
4241                         break;
4242
4243                 case ENOMEM:
4244                         error = zfs_error_fmt(hdl, EZFS_NOMEM,
4245                             dgettext(TEXT_DOMAIN, "cannot get event"));
4246                         break;
4247
4248                 default:
4249                         error = zpool_standard_error_fmt(hdl, errno,
4250                             dgettext(TEXT_DOMAIN, "cannot get event"));
4251                         break;
4252                 }
4253         }
4254
4255         return (error);
4256 }
4257
4258 void
4259 zpool_obj_to_path(zpool_handle_t *zhp, uint64_t dsobj, uint64_t obj,
4260     char *pathname, size_t len)
4261 {
4262         zfs_cmd_t zc = {"\0"};
4263         boolean_t mounted = B_FALSE;
4264         char *mntpnt = NULL;
4265         char dsname[ZFS_MAX_DATASET_NAME_LEN];
4266
4267         if (dsobj == 0) {
4268                 /* special case for the MOS */
4269                 (void) snprintf(pathname, len, "<metadata>:<0x%llx>",
4270                     (longlong_t)obj);
4271                 return;
4272         }
4273
4274         /* get the dataset's name */
4275         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
4276         zc.zc_obj = dsobj;
4277         if (ioctl(zhp->zpool_hdl->libzfs_fd,
4278             ZFS_IOC_DSOBJ_TO_DSNAME, &zc) != 0) {
4279                 /* just write out a path of two object numbers */
4280                 (void) snprintf(pathname, len, "<0x%llx>:<0x%llx>",
4281                     (longlong_t)dsobj, (longlong_t)obj);
4282                 return;
4283         }
4284         (void) strlcpy(dsname, zc.zc_value, sizeof (dsname));
4285
4286         /* find out if the dataset is mounted */
4287         mounted = is_mounted(zhp->zpool_hdl, dsname, &mntpnt);
4288
4289         /* get the corrupted object's path */
4290         (void) strlcpy(zc.zc_name, dsname, sizeof (zc.zc_name));
4291         zc.zc_obj = obj;
4292         if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_OBJ_TO_PATH,
4293             &zc) == 0) {
4294                 if (mounted) {
4295                         (void) snprintf(pathname, len, "%s%s", mntpnt,
4296                             zc.zc_value);
4297                 } else {
4298                         (void) snprintf(pathname, len, "%s:%s",
4299                             dsname, zc.zc_value);
4300                 }
4301         } else {
4302                 (void) snprintf(pathname, len, "%s:<0x%llx>", dsname,
4303                     (longlong_t)obj);
4304         }
4305         free(mntpnt);
4306 }
4307
4308 /*
4309  * Read the EFI label from the config, if a label does not exist then
4310  * pass back the error to the caller. If the caller has passed a non-NULL
4311  * diskaddr argument then we set it to the starting address of the EFI
4312  * partition.
4313  */
4314 static int
4315 read_efi_label(nvlist_t *config, diskaddr_t *sb)
4316 {
4317         char *path;
4318         int fd;
4319         char diskname[MAXPATHLEN];
4320         int err = -1;
4321
4322         if (nvlist_lookup_string(config, ZPOOL_CONFIG_PATH, &path) != 0)
4323                 return (err);
4324
4325         (void) snprintf(diskname, sizeof (diskname), "%s%s", DISK_ROOT,
4326             strrchr(path, '/'));
4327         if ((fd = open(diskname, O_RDONLY|O_DIRECT)) >= 0) {
4328                 struct dk_gpt *vtoc;
4329
4330                 if ((err = efi_alloc_and_read(fd, &vtoc)) >= 0) {
4331                         if (sb != NULL)
4332                                 *sb = vtoc->efi_parts[0].p_start;
4333                         efi_free(vtoc);
4334                 }
4335                 (void) close(fd);
4336         }
4337         return (err);
4338 }
4339
4340 /*
4341  * determine where a partition starts on a disk in the current
4342  * configuration
4343  */
4344 static diskaddr_t
4345 find_start_block(nvlist_t *config)
4346 {
4347         nvlist_t **child;
4348         uint_t c, children;
4349         diskaddr_t sb = MAXOFFSET_T;
4350         uint64_t wholedisk;
4351
4352         if (nvlist_lookup_nvlist_array(config,
4353             ZPOOL_CONFIG_CHILDREN, &child, &children) != 0) {
4354                 if (nvlist_lookup_uint64(config,
4355                     ZPOOL_CONFIG_WHOLE_DISK,
4356                     &wholedisk) != 0 || !wholedisk) {
4357                         return (MAXOFFSET_T);
4358                 }
4359                 if (read_efi_label(config, &sb) < 0)
4360                         sb = MAXOFFSET_T;
4361                 return (sb);
4362         }
4363
4364         for (c = 0; c < children; c++) {
4365                 sb = find_start_block(child[c]);
4366                 if (sb != MAXOFFSET_T) {
4367                         return (sb);
4368                 }
4369         }
4370         return (MAXOFFSET_T);
4371 }
4372
4373 static int
4374 zpool_label_disk_check(char *path)
4375 {
4376         struct dk_gpt *vtoc;
4377         int fd, err;
4378
4379         if ((fd = open(path, O_RDONLY|O_DIRECT)) < 0)
4380                 return (errno);
4381
4382         if ((err = efi_alloc_and_read(fd, &vtoc)) != 0) {
4383                 (void) close(fd);
4384                 return (err);
4385         }
4386
4387         if (vtoc->efi_flags & EFI_GPT_PRIMARY_CORRUPT) {
4388                 efi_free(vtoc);
4389                 (void) close(fd);
4390                 return (EIDRM);
4391         }
4392
4393         efi_free(vtoc);
4394         (void) close(fd);
4395         return (0);
4396 }
4397
4398 /*
4399  * Generate a unique partition name for the ZFS member.  Partitions must
4400  * have unique names to ensure udev will be able to create symlinks under
4401  * /dev/disk/by-partlabel/ for all pool members.  The partition names are
4402  * of the form <pool>-<unique-id>.
4403  */
4404 static void
4405 zpool_label_name(char *label_name, int label_size)
4406 {
4407         uint64_t id = 0;
4408         int fd;
4409
4410         fd = open("/dev/urandom", O_RDONLY);
4411         if (fd >= 0) {
4412                 if (read(fd, &id, sizeof (id)) != sizeof (id))
4413                         id = 0;
4414
4415                 close(fd);
4416         }
4417
4418         if (id == 0)
4419                 id = (((uint64_t)rand()) << 32) | (uint64_t)rand();
4420
4421         snprintf(label_name, label_size, "zfs-%016llx", (u_longlong_t)id);
4422 }
4423
4424 /*
4425  * Label an individual disk.  The name provided is the short name,
4426  * stripped of any leading /dev path.
4427  */
4428 int
4429 zpool_label_disk(libzfs_handle_t *hdl, zpool_handle_t *zhp, char *name)
4430 {
4431         char path[MAXPATHLEN];
4432         struct dk_gpt *vtoc;
4433         int rval, fd;
4434         size_t resv = EFI_MIN_RESV_SIZE;
4435         uint64_t slice_size;
4436         diskaddr_t start_block;
4437         char errbuf[1024];
4438
4439         /* prepare an error message just in case */
4440         (void) snprintf(errbuf, sizeof (errbuf),
4441             dgettext(TEXT_DOMAIN, "cannot label '%s'"), name);
4442
4443         if (zhp) {
4444                 nvlist_t *nvroot;
4445
4446                 verify(nvlist_lookup_nvlist(zhp->zpool_config,
4447                     ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4448
4449                 if (zhp->zpool_start_block == 0)
4450                         start_block = find_start_block(nvroot);
4451                 else
4452                         start_block = zhp->zpool_start_block;
4453                 zhp->zpool_start_block = start_block;
4454         } else {
4455                 /* new pool */
4456                 start_block = NEW_START_BLOCK;
4457         }
4458
4459         (void) snprintf(path, sizeof (path), "%s/%s", DISK_ROOT, name);
4460
4461         if ((fd = open(path, O_RDWR|O_DIRECT|O_EXCL)) < 0) {
4462                 /*
4463                  * This shouldn't happen.  We've long since verified that this
4464                  * is a valid device.
4465                  */
4466                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot "
4467                     "label '%s': unable to open device: %d"), path, errno);
4468                 return (zfs_error(hdl, EZFS_OPENFAILED, errbuf));
4469         }
4470
4471         if (efi_alloc_and_init(fd, EFI_NUMPAR, &vtoc) != 0) {
4472                 /*
4473                  * The only way this can fail is if we run out of memory, or we
4474                  * were unable to read the disk's capacity
4475                  */
4476                 if (errno == ENOMEM)
4477                         (void) no_memory(hdl);
4478
4479                 (void) close(fd);
4480                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot "
4481                     "label '%s': unable to read disk capacity"), path);
4482
4483                 return (zfs_error(hdl, EZFS_NOCAP, errbuf));
4484         }
4485
4486         slice_size = vtoc->efi_last_u_lba + 1;
4487         slice_size -= EFI_MIN_RESV_SIZE;
4488         if (start_block == MAXOFFSET_T)
4489                 start_block = NEW_START_BLOCK;
4490         slice_size -= start_block;
4491         slice_size = P2ALIGN(slice_size, PARTITION_END_ALIGNMENT);
4492
4493         vtoc->efi_parts[0].p_start = start_block;
4494         vtoc->efi_parts[0].p_size = slice_size;
4495
4496         /*
4497          * Why we use V_USR: V_BACKUP confuses users, and is considered
4498          * disposable by some EFI utilities (since EFI doesn't have a backup
4499          * slice).  V_UNASSIGNED is supposed to be used only for zero size
4500          * partitions, and efi_write() will fail if we use it.  V_ROOT, V_BOOT,
4501          * etc. were all pretty specific.  V_USR is as close to reality as we
4502          * can get, in the absence of V_OTHER.
4503          */
4504         vtoc->efi_parts[0].p_tag = V_USR;
4505         zpool_label_name(vtoc->efi_parts[0].p_name, EFI_PART_NAME_LEN);
4506
4507         vtoc->efi_parts[8].p_start = slice_size + start_block;
4508         vtoc->efi_parts[8].p_size = resv;
4509         vtoc->efi_parts[8].p_tag = V_RESERVED;
4510
4511         rval = efi_write(fd, vtoc);
4512
4513         /* Flush the buffers to disk and invalidate the page cache. */
4514         (void) fsync(fd);
4515         (void) ioctl(fd, BLKFLSBUF);
4516
4517         if (rval == 0)
4518                 rval = efi_rescan(fd);
4519
4520         /*
4521          * Some block drivers (like pcata) may not support EFI GPT labels.
4522          * Print out a helpful error message directing the user to manually
4523          * label the disk and give a specific slice.
4524          */
4525         if (rval != 0) {
4526                 (void) close(fd);
4527                 efi_free(vtoc);
4528
4529                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "try using "
4530                     "parted(8) and then provide a specific slice: %d"), rval);
4531                 return (zfs_error(hdl, EZFS_LABELFAILED, errbuf));
4532         }
4533
4534         (void) close(fd);
4535         efi_free(vtoc);
4536
4537         (void) snprintf(path, sizeof (path), "%s/%s", DISK_ROOT, name);
4538         (void) zfs_append_partition(path, MAXPATHLEN);
4539
4540         /* Wait to udev to signal use the device has settled. */
4541         rval = zpool_label_disk_wait(path, DISK_LABEL_WAIT);
4542         if (rval) {
4543                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "failed to "
4544                     "detect device partitions on '%s': %d"), path, rval);
4545                 return (zfs_error(hdl, EZFS_LABELFAILED, errbuf));
4546         }
4547
4548         /* We can't be to paranoid.  Read the label back and verify it. */
4549         (void) snprintf(path, sizeof (path), "%s/%s", DISK_ROOT, name);
4550         rval = zpool_label_disk_check(path);
4551         if (rval) {
4552                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "freshly written "
4553                     "EFI label on '%s' is damaged.  Ensure\nthis device "
4554                     "is not in in use, and is functioning properly: %d"),
4555                     path, rval);
4556                 return (zfs_error(hdl, EZFS_LABELFAILED, errbuf));
4557         }
4558
4559         return (0);
4560 }