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