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