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 <ctype.h>
  32 #include <errno.h>
  33 #include <devid.h>
  34 #include <fcntl.h>
  35 #include <libintl.h>
  36 #include <stdio.h>
  37 #include <stdlib.h>
  38 #include <strings.h>
  39 #include <unistd.h>
  40 #include <libgen.h>
  41 #include <sys/efi_partition.h>
  42 #include <sys/vtoc.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, "FAULTED", len);
 264                         break;
 265 
 266                 case ZPOOL_PROP_GUID:
 267                         intval = zpool_get_prop_int(zhp, prop, &src);
 268                         (void) snprintf(buf, len, "%llu", intval);
 269                         break;
 270 
 271                 case ZPOOL_PROP_ALTROOT:
 272                 case ZPOOL_PROP_CACHEFILE:
 273                 case ZPOOL_PROP_COMMENT:
 274                         if (zhp->zpool_props != NULL ||
 275                             zpool_get_all_props(zhp) == 0) {
 276                                 (void) strlcpy(buf,
 277                                     zpool_get_prop_string(zhp, prop, &src),
 278                                     len);
 279                                 break;
 280                         }
 281                         /* FALLTHROUGH */
 282                 default:
 283                         (void) strlcpy(buf, "-", len);
 284                         break;
 285                 }
 286 
 287                 if (srctype != NULL)
 288                         *srctype = src;
 289                 return (0);
 290         }
 291 
 292         if (zhp->zpool_props == NULL && zpool_get_all_props(zhp) &&
 293             prop != ZPOOL_PROP_NAME)
 294                 return (-1);
 295 
 296         switch (zpool_prop_get_type(prop)) {
 297         case PROP_TYPE_STRING:
 298                 (void) strlcpy(buf, zpool_get_prop_string(zhp, prop, &src),
 299                     len);
 300                 break;
 301 
 302         case PROP_TYPE_NUMBER:
 303                 intval = zpool_get_prop_int(zhp, prop, &src);
 304 
 305                 switch (prop) {
 306                 case ZPOOL_PROP_SIZE:
 307                 case ZPOOL_PROP_ALLOCATED:
 308                 case ZPOOL_PROP_FREE:
 309                 case ZPOOL_PROP_FREEING:
 310                 case ZPOOL_PROP_LEAKED:
 311                         if (literal) {
 312                                 (void) snprintf(buf, len, "%llu",
 313                                     (u_longlong_t)intval);
 314                         } else {
 315                                 (void) zfs_nicenum(intval, buf, len);
 316                         }
 317                         break;
 318                 case ZPOOL_PROP_BOOTSIZE:
 319                 case ZPOOL_PROP_EXPANDSZ:
 320                 case ZPOOL_PROP_CHECKPOINT:
 321                         if (intval == 0) {
 322                                 (void) strlcpy(buf, "-", len);
 323                         } else if (literal) {
 324                                 (void) snprintf(buf, len, "%llu",
 325                                     (u_longlong_t)intval);
 326                         } else {
 327                                 (void) zfs_nicenum(intval, buf, len);
 328                         }
 329                         break;
 330                 case ZPOOL_PROP_CAPACITY:
 331                         if (literal) {
 332                                 (void) snprintf(buf, len, "%llu",
 333                                     (u_longlong_t)intval);
 334                         } else {
 335                                 (void) snprintf(buf, len, "%llu%%",
 336                                     (u_longlong_t)intval);
 337                         }
 338                         break;
 339                 case ZPOOL_PROP_FRAGMENTATION:
 340                         if (intval == UINT64_MAX) {
 341                                 (void) strlcpy(buf, "-", len);
 342                         } else {
 343                                 (void) snprintf(buf, len, "%llu%%",
 344                                     (u_longlong_t)intval);
 345                         }
 346                         break;
 347                 case ZPOOL_PROP_DEDUPRATIO:
 348                         (void) snprintf(buf, len, "%llu.%02llux",
 349                             (u_longlong_t)(intval / 100),
 350                             (u_longlong_t)(intval % 100));
 351                         break;
 352                 case ZPOOL_PROP_HEALTH:
 353                         verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
 354                             ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
 355                         verify(nvlist_lookup_uint64_array(nvroot,
 356                             ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
 357                             == 0);
 358 
 359                         (void) strlcpy(buf, zpool_state_to_name(intval,
 360                             vs->vs_aux), len);
 361                         break;
 362                 case ZPOOL_PROP_VERSION:
 363                         if (intval >= SPA_VERSION_FEATURES) {
 364                                 (void) snprintf(buf, len, "-");
 365                                 break;
 366                         }
 367                         /* FALLTHROUGH */
 368                 default:
 369                         (void) snprintf(buf, len, "%llu", intval);
 370                 }
 371                 break;
 372 
 373         case PROP_TYPE_INDEX:
 374                 intval = zpool_get_prop_int(zhp, prop, &src);
 375                 if (zpool_prop_index_to_string(prop, intval, &strval)
 376                     != 0)
 377                         return (-1);
 378                 (void) strlcpy(buf, strval, len);
 379                 break;
 380 
 381         default:
 382                 abort();
 383         }
 384 
 385         if (srctype)
 386                 *srctype = src;
 387 
 388         return (0);
 389 }
 390 
 391 /*
 392  * Check if the bootfs name has the same pool name as it is set to.
 393  * Assuming bootfs is a valid dataset name.
 394  */
 395 static boolean_t
 396 bootfs_name_valid(const char *pool, char *bootfs)
 397 {
 398         int len = strlen(pool);
 399         if (bootfs[0] == '\0')
 400                 return (B_TRUE);
 401 
 402         if (!zfs_name_valid(bootfs, ZFS_TYPE_FILESYSTEM|ZFS_TYPE_SNAPSHOT))
 403                 return (B_FALSE);
 404 
 405         if (strncmp(pool, bootfs, len) == 0 &&
 406             (bootfs[len] == '/' || bootfs[len] == '\0'))
 407                 return (B_TRUE);
 408 
 409         return (B_FALSE);
 410 }
 411 
 412 boolean_t
 413 zpool_is_bootable(zpool_handle_t *zhp)
 414 {
 415         char bootfs[ZFS_MAX_DATASET_NAME_LEN];
 416 
 417         return (zpool_get_prop(zhp, ZPOOL_PROP_BOOTFS, bootfs,
 418             sizeof (bootfs), NULL, B_FALSE) == 0 && strncmp(bootfs, "-",
 419             sizeof (bootfs)) != 0);
 420 }
 421 
 422 
 423 /*
 424  * Given an nvlist of zpool properties to be set, validate that they are
 425  * correct, and parse any numeric properties (index, boolean, etc) if they are
 426  * specified as strings.
 427  */
 428 static nvlist_t *
 429 zpool_valid_proplist(libzfs_handle_t *hdl, const char *poolname,
 430     nvlist_t *props, uint64_t version, prop_flags_t flags, char *errbuf)
 431 {
 432         nvpair_t *elem;
 433         nvlist_t *retprops;
 434         zpool_prop_t prop;
 435         char *strval;
 436         uint64_t intval;
 437         char *slash, *check;
 438         struct stat64 statbuf;
 439         zpool_handle_t *zhp;
 440 
 441         if (nvlist_alloc(&retprops, NV_UNIQUE_NAME, 0) != 0) {
 442                 (void) no_memory(hdl);
 443                 return (NULL);
 444         }
 445 
 446         elem = NULL;
 447         while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
 448                 const char *propname = nvpair_name(elem);
 449 
 450                 prop = zpool_name_to_prop(propname);
 451                 if (prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname)) {
 452                         int err;
 453                         char *fname = strchr(propname, '@') + 1;
 454 
 455                         err = zfeature_lookup_name(fname, NULL);
 456                         if (err != 0) {
 457                                 ASSERT3U(err, ==, ENOENT);
 458                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 459                                     "invalid feature '%s'"), fname);
 460                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
 461                                 goto error;
 462                         }
 463 
 464                         if (nvpair_type(elem) != DATA_TYPE_STRING) {
 465                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 466                                     "'%s' must be a string"), propname);
 467                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
 468                                 goto error;
 469                         }
 470 
 471                         (void) nvpair_value_string(elem, &strval);
 472                         if (strcmp(strval, ZFS_FEATURE_ENABLED) != 0) {
 473                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 474                                     "property '%s' can only be set to "
 475                                     "'enabled'"), propname);
 476                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
 477                                 goto error;
 478                         }
 479 
 480                         if (nvlist_add_uint64(retprops, propname, 0) != 0) {
 481                                 (void) no_memory(hdl);
 482                                 goto error;
 483                         }
 484                         continue;
 485                 }
 486 
 487                 /*
 488                  * Make sure this property is valid and applies to this type.
 489                  */
 490                 if (prop == ZPOOL_PROP_INVAL) {
 491                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 492                             "invalid property '%s'"), propname);
 493                         (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
 494                         goto error;
 495                 }
 496 
 497                 if (zpool_prop_readonly(prop)) {
 498                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' "
 499                             "is readonly"), propname);
 500                         (void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
 501                         goto error;
 502                 }
 503 
 504                 if (zprop_parse_value(hdl, elem, prop, ZFS_TYPE_POOL, retprops,
 505                     &strval, &intval, errbuf) != 0)
 506                         goto error;
 507 
 508                 /*
 509                  * Perform additional checking for specific properties.
 510                  */
 511                 switch (prop) {
 512                 case ZPOOL_PROP_VERSION:
 513                         if (intval < version ||
 514                             !SPA_VERSION_IS_SUPPORTED(intval)) {
 515                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 516                                     "property '%s' number %d is invalid."),
 517                                     propname, intval);
 518                                 (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
 519                                 goto error;
 520                         }
 521                         break;
 522 
 523                 case ZPOOL_PROP_BOOTSIZE:
 524                         if (!flags.create) {
 525                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 526                                     "property '%s' can only be set during pool "
 527                                     "creation"), propname);
 528                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
 529                                 goto error;
 530                         }
 531                         break;
 532 
 533                 case ZPOOL_PROP_BOOTFS:
 534                         if (flags.create || flags.import) {
 535                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 536                                     "property '%s' cannot be set at creation "
 537                                     "or import time"), propname);
 538                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
 539                                 goto error;
 540                         }
 541 
 542                         if (version < SPA_VERSION_BOOTFS) {
 543                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 544                                     "pool must be upgraded to support "
 545                                     "'%s' property"), propname);
 546                                 (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
 547                                 goto error;
 548                         }
 549 
 550                         /*
 551                          * bootfs property value has to be a dataset name and
 552                          * the dataset has to be in the same pool as it sets to.
 553                          */
 554                         if (!bootfs_name_valid(poolname, 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 static int
1985 xlate_init_err(int err)
1986 {
1987         switch (err) {
1988         case ENODEV:
1989                 return (EZFS_NODEVICE);
1990         case EINVAL:
1991         case EROFS:
1992                 return (EZFS_BADDEV);
1993         case EBUSY:
1994                 return (EZFS_INITIALIZING);
1995         case ESRCH:
1996                 return (EZFS_NO_INITIALIZE);
1997         }
1998         return (err);
1999 }
2000 
2001 /*
2002  * Begin, suspend, or cancel the initialization (initializing of all free
2003  * blocks) for the given vdevs in the given pool.
2004  */
2005 int
2006 zpool_initialize(zpool_handle_t *zhp, pool_initialize_func_t cmd_type,
2007     nvlist_t *vds)
2008 {
2009         char msg[1024];
2010         libzfs_handle_t *hdl = zhp->zpool_hdl;
2011 
2012         nvlist_t *errlist;
2013 
2014         /* translate vdev names to guids */
2015         nvlist_t *vdev_guids = fnvlist_alloc();
2016         nvlist_t *guids_to_paths = fnvlist_alloc();
2017         boolean_t spare, cache;
2018         nvlist_t *tgt;
2019         nvpair_t *elem;
2020 
2021         for (elem = nvlist_next_nvpair(vds, NULL); elem != NULL;
2022             elem = nvlist_next_nvpair(vds, elem)) {
2023                 char *vd_path = nvpair_name(elem);
2024                 tgt = zpool_find_vdev(zhp, vd_path, &spare, &cache, NULL);
2025 
2026                 if ((tgt == NULL) || cache || spare) {
2027                         (void) snprintf(msg, sizeof (msg),
2028                             dgettext(TEXT_DOMAIN, "cannot initialize '%s'"),
2029                             vd_path);
2030                         int err = (tgt == NULL) ? EZFS_NODEVICE :
2031                             (spare ? EZFS_ISSPARE : EZFS_ISL2CACHE);
2032                         fnvlist_free(vdev_guids);
2033                         fnvlist_free(guids_to_paths);
2034                         return (zfs_error(hdl, err, msg));
2035                 }
2036 
2037                 uint64_t guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
2038                 fnvlist_add_uint64(vdev_guids, vd_path, guid);
2039 
2040                 (void) snprintf(msg, sizeof (msg), "%llu", guid);
2041                 fnvlist_add_string(guids_to_paths, msg, vd_path);
2042         }
2043 
2044         int err = lzc_initialize(zhp->zpool_name, cmd_type, vdev_guids,
2045             &errlist);
2046         fnvlist_free(vdev_guids);
2047 
2048         if (err == 0) {
2049                 fnvlist_free(guids_to_paths);
2050                 return (0);
2051         }
2052 
2053         nvlist_t *vd_errlist = NULL;
2054         if (errlist != NULL) {
2055                 vd_errlist = fnvlist_lookup_nvlist(errlist,
2056                     ZPOOL_INITIALIZE_VDEVS);
2057         }
2058 
2059         (void) snprintf(msg, sizeof (msg),
2060             dgettext(TEXT_DOMAIN, "operation failed"));
2061 
2062         for (elem = nvlist_next_nvpair(vd_errlist, NULL); elem != NULL;
2063             elem = nvlist_next_nvpair(vd_errlist, elem)) {
2064                 int64_t vd_error = xlate_init_err(fnvpair_value_int64(elem));
2065                 char *path = fnvlist_lookup_string(guids_to_paths,
2066                     nvpair_name(elem));
2067                 (void) zfs_error_fmt(hdl, vd_error, "cannot initialize '%s'",
2068                     path);
2069         }
2070 
2071         fnvlist_free(guids_to_paths);
2072         if (vd_errlist != NULL)
2073                 return (-1);
2074 
2075         return (zpool_standard_error(hdl, err, msg));
2076 }
2077 
2078 /*
2079  * This provides a very minimal check whether a given string is likely a
2080  * c#t#d# style string.  Users of this are expected to do their own
2081  * verification of the s# part.
2082  */
2083 #define CTD_CHECK(str)  (str && str[0] == 'c' && isdigit(str[1]))
2084 
2085 /*
2086  * More elaborate version for ones which may start with "/dev/dsk/"
2087  * and the like.
2088  */
2089 static int
2090 ctd_check_path(char *str)
2091 {
2092         /*
2093          * If it starts with a slash, check the last component.
2094          */
2095         if (str && str[0] == '/') {
2096                 char *tmp = strrchr(str, '/');
2097 
2098                 /*
2099                  * If it ends in "/old", check the second-to-last
2100                  * component of the string instead.
2101                  */
2102                 if (tmp != str && strcmp(tmp, "/old") == 0) {
2103                         for (tmp--; *tmp != '/'; tmp--)
2104                                 ;
2105                 }
2106                 str = tmp + 1;
2107         }
2108         return (CTD_CHECK(str));
2109 }
2110 
2111 /*
2112  * Find a vdev that matches the search criteria specified. We use the
2113  * the nvpair name to determine how we should look for the device.
2114  * 'avail_spare' is set to TRUE if the provided guid refers to an AVAIL
2115  * spare; but FALSE if its an INUSE spare.
2116  */
2117 static nvlist_t *
2118 vdev_to_nvlist_iter(nvlist_t *nv, nvlist_t *search, boolean_t *avail_spare,
2119     boolean_t *l2cache, boolean_t *log)
2120 {
2121         uint_t c, children;
2122         nvlist_t **child;
2123         nvlist_t *ret;
2124         uint64_t is_log;
2125         char *srchkey;
2126         nvpair_t *pair = nvlist_next_nvpair(search, NULL);
2127 
2128         /* Nothing to look for */
2129         if (search == NULL || pair == NULL)
2130                 return (NULL);
2131 
2132         /* Obtain the key we will use to search */
2133         srchkey = nvpair_name(pair);
2134 
2135         switch (nvpair_type(pair)) {
2136         case DATA_TYPE_UINT64:
2137                 if (strcmp(srchkey, ZPOOL_CONFIG_GUID) == 0) {
2138                         uint64_t srchval, theguid;
2139 
2140                         verify(nvpair_value_uint64(pair, &srchval) == 0);
2141                         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
2142                             &theguid) == 0);
2143                         if (theguid == srchval)
2144                                 return (nv);
2145                 }
2146                 break;
2147 
2148         case DATA_TYPE_STRING: {
2149                 char *srchval, *val;
2150 
2151                 verify(nvpair_value_string(pair, &srchval) == 0);
2152                 if (nvlist_lookup_string(nv, srchkey, &val) != 0)
2153                         break;
2154 
2155                 /*
2156                  * Search for the requested value. Special cases:
2157                  *
2158                  * - ZPOOL_CONFIG_PATH for whole disk entries. To support
2159                  *   UEFI boot, these end in "s0" or "s0/old" or "s1" or
2160                  *   "s1/old".   The "s0" or "s1" part is hidden from the user,
2161                  *   but included in the string, so this matches around it.
2162                  * - looking for a top-level vdev name (i.e. ZPOOL_CONFIG_TYPE).
2163                  *
2164                  * Otherwise, all other searches are simple string compares.
2165                  */
2166                 if (strcmp(srchkey, ZPOOL_CONFIG_PATH) == 0 &&
2167                     ctd_check_path(val)) {
2168                         uint64_t wholedisk = 0;
2169 
2170                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
2171                             &wholedisk);
2172                         if (wholedisk) {
2173                                 int slen = strlen(srchval);
2174                                 int vlen = strlen(val);
2175 
2176                                 if (slen != vlen - 2)
2177                                         break;
2178 
2179                                 /*
2180                                  * make_leaf_vdev() should only set
2181                                  * wholedisk for ZPOOL_CONFIG_PATHs which
2182                                  * will include "/dev/dsk/", giving plenty of
2183                                  * room for the indices used next.
2184                                  */
2185                                 ASSERT(vlen >= 6);
2186 
2187                                 /*
2188                                  * strings identical except trailing "s0"
2189                                  */
2190                                 if ((strcmp(&val[vlen - 2], "s0") == 0 ||
2191                                     strcmp(&val[vlen - 2], "s1") == 0) &&
2192                                     strncmp(srchval, val, slen) == 0)
2193                                         return (nv);
2194 
2195                                 /*
2196                                  * strings identical except trailing "s0/old"
2197                                  */
2198                                 if ((strcmp(&val[vlen - 6], "s0/old") == 0 ||
2199                                     strcmp(&val[vlen - 6], "s1/old") == 0) &&
2200                                     strcmp(&srchval[slen - 4], "/old") == 0 &&
2201                                     strncmp(srchval, val, slen - 4) == 0)
2202                                         return (nv);
2203 
2204                                 break;
2205                         }
2206                 } else if (strcmp(srchkey, ZPOOL_CONFIG_TYPE) == 0 && val) {
2207                         char *type, *idx, *end, *p;
2208                         uint64_t id, vdev_id;
2209 
2210                         /*
2211                          * Determine our vdev type, keeping in mind
2212                          * that the srchval is composed of a type and
2213                          * vdev id pair (i.e. mirror-4).
2214                          */
2215                         if ((type = strdup(srchval)) == NULL)
2216                                 return (NULL);
2217 
2218                         if ((p = strrchr(type, '-')) == NULL) {
2219                                 free(type);
2220                                 break;
2221                         }
2222                         idx = p + 1;
2223                         *p = '\0';
2224 
2225                         /*
2226                          * If the types don't match then keep looking.
2227                          */
2228                         if (strncmp(val, type, strlen(val)) != 0) {
2229                                 free(type);
2230                                 break;
2231                         }
2232 
2233                         verify(zpool_vdev_is_interior(type));
2234                         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID,
2235                             &id) == 0);
2236 
2237                         errno = 0;
2238                         vdev_id = strtoull(idx, &end, 10);
2239 
2240                         free(type);
2241                         if (errno != 0)
2242                                 return (NULL);
2243 
2244                         /*
2245                          * Now verify that we have the correct vdev id.
2246                          */
2247                         if (vdev_id == id)
2248                                 return (nv);
2249                 }
2250 
2251                 /*
2252                  * Common case
2253                  */
2254                 if (strcmp(srchval, val) == 0)
2255                         return (nv);
2256                 break;
2257         }
2258 
2259         default:
2260                 break;
2261         }
2262 
2263         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2264             &child, &children) != 0)
2265                 return (NULL);
2266 
2267         for (c = 0; c < children; c++) {
2268                 if ((ret = vdev_to_nvlist_iter(child[c], search,
2269                     avail_spare, l2cache, NULL)) != NULL) {
2270                         /*
2271                          * The 'is_log' value is only set for the toplevel
2272                          * vdev, not the leaf vdevs.  So we always lookup the
2273                          * log device from the root of the vdev tree (where
2274                          * 'log' is non-NULL).
2275                          */
2276                         if (log != NULL &&
2277                             nvlist_lookup_uint64(child[c],
2278                             ZPOOL_CONFIG_IS_LOG, &is_log) == 0 &&
2279                             is_log) {
2280                                 *log = B_TRUE;
2281                         }
2282                         return (ret);
2283                 }
2284         }
2285 
2286         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
2287             &child, &children) == 0) {
2288                 for (c = 0; c < children; c++) {
2289                         if ((ret = vdev_to_nvlist_iter(child[c], search,
2290                             avail_spare, l2cache, NULL)) != NULL) {
2291                                 *avail_spare = B_TRUE;
2292                                 return (ret);
2293                         }
2294                 }
2295         }
2296 
2297         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
2298             &child, &children) == 0) {
2299                 for (c = 0; c < children; c++) {
2300                         if ((ret = vdev_to_nvlist_iter(child[c], search,
2301                             avail_spare, l2cache, NULL)) != NULL) {
2302                                 *l2cache = B_TRUE;
2303                                 return (ret);
2304                         }
2305                 }
2306         }
2307 
2308         return (NULL);
2309 }
2310 
2311 /*
2312  * Given a physical path (minus the "/devices" prefix), find the
2313  * associated vdev.
2314  */
2315 nvlist_t *
2316 zpool_find_vdev_by_physpath(zpool_handle_t *zhp, const char *ppath,
2317     boolean_t *avail_spare, boolean_t *l2cache, boolean_t *log)
2318 {
2319         nvlist_t *search, *nvroot, *ret;
2320 
2321         verify(nvlist_alloc(&search, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2322         verify(nvlist_add_string(search, ZPOOL_CONFIG_PHYS_PATH, ppath) == 0);
2323 
2324         verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
2325             &nvroot) == 0);
2326 
2327         *avail_spare = B_FALSE;
2328         *l2cache = B_FALSE;
2329         if (log != NULL)
2330                 *log = B_FALSE;
2331         ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log);
2332         nvlist_free(search);
2333 
2334         return (ret);
2335 }
2336 
2337 /*
2338  * Determine if we have an "interior" top-level vdev (i.e mirror/raidz).
2339  */
2340 static boolean_t
2341 zpool_vdev_is_interior(const char *name)
2342 {
2343         if (strncmp(name, VDEV_TYPE_RAIDZ, strlen(VDEV_TYPE_RAIDZ)) == 0 ||
2344             strncmp(name, VDEV_TYPE_SPARE, strlen(VDEV_TYPE_SPARE)) == 0 ||
2345             strncmp(name,
2346             VDEV_TYPE_REPLACING, strlen(VDEV_TYPE_REPLACING)) == 0 ||
2347             strncmp(name, VDEV_TYPE_MIRROR, strlen(VDEV_TYPE_MIRROR)) == 0)
2348                 return (B_TRUE);
2349         return (B_FALSE);
2350 }
2351 
2352 nvlist_t *
2353 zpool_find_vdev(zpool_handle_t *zhp, const char *path, boolean_t *avail_spare,
2354     boolean_t *l2cache, boolean_t *log)
2355 {
2356         char buf[MAXPATHLEN];
2357         char *end;
2358         nvlist_t *nvroot, *search, *ret;
2359         uint64_t guid;
2360 
2361         verify(nvlist_alloc(&search, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2362 
2363         guid = strtoull(path, &end, 10);
2364         if (guid != 0 && *end == '\0') {
2365                 verify(nvlist_add_uint64(search, ZPOOL_CONFIG_GUID, guid) == 0);
2366         } else if (zpool_vdev_is_interior(path)) {
2367                 verify(nvlist_add_string(search, ZPOOL_CONFIG_TYPE, path) == 0);
2368         } else if (path[0] != '/') {
2369                 (void) snprintf(buf, sizeof (buf), "%s/%s", ZFS_DISK_ROOT,
2370                     path);
2371                 verify(nvlist_add_string(search, ZPOOL_CONFIG_PATH, buf) == 0);
2372         } else {
2373                 verify(nvlist_add_string(search, ZPOOL_CONFIG_PATH, path) == 0);
2374         }
2375 
2376         verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
2377             &nvroot) == 0);
2378 
2379         *avail_spare = B_FALSE;
2380         *l2cache = B_FALSE;
2381         if (log != NULL)
2382                 *log = B_FALSE;
2383         ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log);
2384         nvlist_free(search);
2385 
2386         return (ret);
2387 }
2388 
2389 static int
2390 vdev_online(nvlist_t *nv)
2391 {
2392         uint64_t ival;
2393 
2394         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE, &ival) == 0 ||
2395             nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED, &ival) == 0 ||
2396             nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED, &ival) == 0)
2397                 return (0);
2398 
2399         return (1);
2400 }
2401 
2402 /*
2403  * Helper function for zpool_get_physpaths().
2404  */
2405 static int
2406 vdev_get_one_physpath(nvlist_t *config, char *physpath, size_t physpath_size,
2407     size_t *bytes_written)
2408 {
2409         size_t bytes_left, pos, rsz;
2410         char *tmppath;
2411         const char *format;
2412 
2413         if (nvlist_lookup_string(config, ZPOOL_CONFIG_PHYS_PATH,
2414             &tmppath) != 0)
2415                 return (EZFS_NODEVICE);
2416 
2417         pos = *bytes_written;
2418         bytes_left = physpath_size - pos;
2419         format = (pos == 0) ? "%s" : " %s";
2420 
2421         rsz = snprintf(physpath + pos, bytes_left, format, tmppath);
2422         *bytes_written += rsz;
2423 
2424         if (rsz >= bytes_left) {
2425                 /* if physpath was not copied properly, clear it */
2426                 if (bytes_left != 0) {
2427                         physpath[pos] = 0;
2428                 }
2429                 return (EZFS_NOSPC);
2430         }
2431         return (0);
2432 }
2433 
2434 static int
2435 vdev_get_physpaths(nvlist_t *nv, char *physpath, size_t phypath_size,
2436     size_t *rsz, boolean_t is_spare)
2437 {
2438         char *type;
2439         int ret;
2440 
2441         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
2442                 return (EZFS_INVALCONFIG);
2443 
2444         if (strcmp(type, VDEV_TYPE_DISK) == 0) {
2445                 /*
2446                  * An active spare device has ZPOOL_CONFIG_IS_SPARE set.
2447                  * For a spare vdev, we only want to boot from the active
2448                  * spare device.
2449                  */
2450                 if (is_spare) {
2451                         uint64_t spare = 0;
2452                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
2453                             &spare);
2454                         if (!spare)
2455                                 return (EZFS_INVALCONFIG);
2456                 }
2457 
2458                 if (vdev_online(nv)) {
2459                         if ((ret = vdev_get_one_physpath(nv, physpath,
2460                             phypath_size, rsz)) != 0)
2461                                 return (ret);
2462                 }
2463         } else if (strcmp(type, VDEV_TYPE_MIRROR) == 0 ||
2464             strcmp(type, VDEV_TYPE_RAIDZ) == 0 ||
2465             strcmp(type, VDEV_TYPE_REPLACING) == 0 ||
2466             (is_spare = (strcmp(type, VDEV_TYPE_SPARE) == 0))) {
2467                 nvlist_t **child;
2468                 uint_t count;
2469                 int i, ret;
2470 
2471                 if (nvlist_lookup_nvlist_array(nv,
2472                     ZPOOL_CONFIG_CHILDREN, &child, &count) != 0)
2473                         return (EZFS_INVALCONFIG);
2474 
2475                 for (i = 0; i < count; i++) {
2476                         ret = vdev_get_physpaths(child[i], physpath,
2477                             phypath_size, rsz, is_spare);
2478                         if (ret == EZFS_NOSPC)
2479                                 return (ret);
2480                 }
2481         }
2482 
2483         return (EZFS_POOL_INVALARG);
2484 }
2485 
2486 /*
2487  * Get phys_path for a root pool config.
2488  * Return 0 on success; non-zero on failure.
2489  */
2490 static int
2491 zpool_get_config_physpath(nvlist_t *config, char *physpath, size_t phypath_size)
2492 {
2493         size_t rsz;
2494         nvlist_t *vdev_root;
2495         nvlist_t **child;
2496         uint_t count;
2497         char *type;
2498 
2499         rsz = 0;
2500 
2501         if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2502             &vdev_root) != 0)
2503                 return (EZFS_INVALCONFIG);
2504 
2505         if (nvlist_lookup_string(vdev_root, ZPOOL_CONFIG_TYPE, &type) != 0 ||
2506             nvlist_lookup_nvlist_array(vdev_root, ZPOOL_CONFIG_CHILDREN,
2507             &child, &count) != 0)
2508                 return (EZFS_INVALCONFIG);
2509 
2510         /*
2511          * root pool can only have a single top-level vdev.
2512          */
2513         if (strcmp(type, VDEV_TYPE_ROOT) != 0 || count != 1)
2514                 return (EZFS_POOL_INVALARG);
2515 
2516         (void) vdev_get_physpaths(child[0], physpath, phypath_size, &rsz,
2517             B_FALSE);
2518 
2519         /* No online devices */
2520         if (rsz == 0)
2521                 return (EZFS_NODEVICE);
2522 
2523         return (0);
2524 }
2525 
2526 /*
2527  * Get phys_path for a root pool
2528  * Return 0 on success; non-zero on failure.
2529  */
2530 int
2531 zpool_get_physpath(zpool_handle_t *zhp, char *physpath, size_t phypath_size)
2532 {
2533         return (zpool_get_config_physpath(zhp->zpool_config, physpath,
2534             phypath_size));
2535 }
2536 
2537 /*
2538  * If the device has being dynamically expanded then we need to relabel
2539  * the disk to use the new unallocated space.
2540  */
2541 static int
2542 zpool_relabel_disk(libzfs_handle_t *hdl, const char *name)
2543 {
2544         char path[MAXPATHLEN];
2545         char errbuf[1024];
2546         int fd, error;
2547         int (*_efi_use_whole_disk)(int);
2548 
2549         if ((_efi_use_whole_disk = (int (*)(int))dlsym(RTLD_DEFAULT,
2550             "efi_use_whole_disk")) == NULL)
2551                 return (-1);
2552 
2553         (void) snprintf(path, sizeof (path), "%s/%s", ZFS_RDISK_ROOT, name);
2554 
2555         if ((fd = open(path, O_RDWR | O_NDELAY)) < 0) {
2556                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot "
2557                     "relabel '%s': unable to open device"), name);
2558                 return (zfs_error(hdl, EZFS_OPENFAILED, errbuf));
2559         }
2560 
2561         /*
2562          * It's possible that we might encounter an error if the device
2563          * does not have any unallocated space left. If so, we simply
2564          * ignore that error and continue on.
2565          */
2566         error = _efi_use_whole_disk(fd);
2567         (void) close(fd);
2568         if (error && error != VT_ENOSPC) {
2569                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot "
2570                     "relabel '%s': unable to read disk capacity"), name);
2571                 return (zfs_error(hdl, EZFS_NOCAP, errbuf));
2572         }
2573         return (0);
2574 }
2575 
2576 /*
2577  * Bring the specified vdev online.   The 'flags' parameter is a set of the
2578  * ZFS_ONLINE_* flags.
2579  */
2580 int
2581 zpool_vdev_online(zpool_handle_t *zhp, const char *path, int flags,
2582     vdev_state_t *newstate)
2583 {
2584         zfs_cmd_t zc = { 0 };
2585         char msg[1024];
2586         char *pathname;
2587         nvlist_t *tgt;
2588         boolean_t avail_spare, l2cache, islog;
2589         libzfs_handle_t *hdl = zhp->zpool_hdl;
2590 
2591         if (flags & ZFS_ONLINE_EXPAND) {
2592                 (void) snprintf(msg, sizeof (msg),
2593                     dgettext(TEXT_DOMAIN, "cannot expand %s"), path);
2594         } else {
2595                 (void) snprintf(msg, sizeof (msg),
2596                     dgettext(TEXT_DOMAIN, "cannot online %s"), path);
2597         }
2598 
2599         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2600         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2601             &islog)) == NULL)
2602                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
2603 
2604         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2605 
2606         if (avail_spare)
2607                 return (zfs_error(hdl, EZFS_ISSPARE, msg));
2608 
2609         if ((flags & ZFS_ONLINE_EXPAND ||
2610             zpool_get_prop_int(zhp, ZPOOL_PROP_AUTOEXPAND, NULL)) &&
2611             nvlist_lookup_string(tgt, ZPOOL_CONFIG_PATH, &pathname) == 0) {
2612                 uint64_t wholedisk = 0;
2613 
2614                 (void) nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_WHOLE_DISK,
2615                     &wholedisk);
2616 
2617                 /*
2618                  * XXX - L2ARC 1.0 devices can't support expansion.
2619                  */
2620                 if (l2cache) {
2621                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2622                             "cannot expand cache devices"));
2623                         return (zfs_error(hdl, EZFS_VDEVNOTSUP, msg));
2624                 }
2625 
2626                 if (wholedisk) {
2627                         pathname += strlen(ZFS_DISK_ROOT) + 1;
2628                         (void) zpool_relabel_disk(hdl, pathname);
2629                 }
2630         }
2631 
2632         zc.zc_cookie = VDEV_STATE_ONLINE;
2633         zc.zc_obj = flags;
2634 
2635         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) != 0) {
2636                 if (errno == EINVAL) {
2637                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "was split "
2638                             "from this pool into a new one.  Use '%s' "
2639                             "instead"), "zpool detach");
2640                         return (zfs_error(hdl, EZFS_POSTSPLIT_ONLINE, msg));
2641                 }
2642                 return (zpool_standard_error(hdl, errno, msg));
2643         }
2644 
2645         *newstate = zc.zc_cookie;
2646         return (0);
2647 }
2648 
2649 /*
2650  * Take the specified vdev offline
2651  */
2652 int
2653 zpool_vdev_offline(zpool_handle_t *zhp, const char *path, boolean_t istmp)
2654 {
2655         zfs_cmd_t zc = { 0 };
2656         char msg[1024];
2657         nvlist_t *tgt;
2658         boolean_t avail_spare, l2cache;
2659         libzfs_handle_t *hdl = zhp->zpool_hdl;
2660 
2661         (void) snprintf(msg, sizeof (msg),
2662             dgettext(TEXT_DOMAIN, "cannot offline %s"), path);
2663 
2664         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2665         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2666             NULL)) == NULL)
2667                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
2668 
2669         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2670 
2671         if (avail_spare)
2672                 return (zfs_error(hdl, EZFS_ISSPARE, msg));
2673 
2674         zc.zc_cookie = VDEV_STATE_OFFLINE;
2675         zc.zc_obj = istmp ? ZFS_OFFLINE_TEMPORARY : 0;
2676 
2677         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2678                 return (0);
2679 
2680         switch (errno) {
2681         case EBUSY:
2682 
2683                 /*
2684                  * There are no other replicas of this device.
2685                  */
2686                 return (zfs_error(hdl, EZFS_NOREPLICAS, msg));
2687 
2688         case EEXIST:
2689                 /*
2690                  * The log device has unplayed logs
2691                  */
2692                 return (zfs_error(hdl, EZFS_UNPLAYED_LOGS, msg));
2693 
2694         default:
2695                 return (zpool_standard_error(hdl, errno, msg));
2696         }
2697 }
2698 
2699 /*
2700  * Mark the given vdev faulted.
2701  */
2702 int
2703 zpool_vdev_fault(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux)
2704 {
2705         zfs_cmd_t zc = { 0 };
2706         char msg[1024];
2707         libzfs_handle_t *hdl = zhp->zpool_hdl;
2708 
2709         (void) snprintf(msg, sizeof (msg),
2710             dgettext(TEXT_DOMAIN, "cannot fault %llu"), guid);
2711 
2712         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2713         zc.zc_guid = guid;
2714         zc.zc_cookie = VDEV_STATE_FAULTED;
2715         zc.zc_obj = aux;
2716 
2717         if (ioctl(hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2718                 return (0);
2719 
2720         switch (errno) {
2721         case EBUSY:
2722 
2723                 /*
2724                  * There are no other replicas of this device.
2725                  */
2726                 return (zfs_error(hdl, EZFS_NOREPLICAS, msg));
2727 
2728         default:
2729                 return (zpool_standard_error(hdl, errno, msg));
2730         }
2731 
2732 }
2733 
2734 /*
2735  * Mark the given vdev degraded.
2736  */
2737 int
2738 zpool_vdev_degrade(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux)
2739 {
2740         zfs_cmd_t zc = { 0 };
2741         char msg[1024];
2742         libzfs_handle_t *hdl = zhp->zpool_hdl;
2743 
2744         (void) snprintf(msg, sizeof (msg),
2745             dgettext(TEXT_DOMAIN, "cannot degrade %llu"), guid);
2746 
2747         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2748         zc.zc_guid = guid;
2749         zc.zc_cookie = VDEV_STATE_DEGRADED;
2750         zc.zc_obj = aux;
2751 
2752         if (ioctl(hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2753                 return (0);
2754 
2755         return (zpool_standard_error(hdl, errno, msg));
2756 }
2757 
2758 /*
2759  * Returns TRUE if the given nvlist is a vdev that was originally swapped in as
2760  * a hot spare.
2761  */
2762 static boolean_t
2763 is_replacing_spare(nvlist_t *search, nvlist_t *tgt, int which)
2764 {
2765         nvlist_t **child;
2766         uint_t c, children;
2767         char *type;
2768 
2769         if (nvlist_lookup_nvlist_array(search, ZPOOL_CONFIG_CHILDREN, &child,
2770             &children) == 0) {
2771                 verify(nvlist_lookup_string(search, ZPOOL_CONFIG_TYPE,
2772                     &type) == 0);
2773 
2774                 if (strcmp(type, VDEV_TYPE_SPARE) == 0 &&
2775                     children == 2 && child[which] == tgt)
2776                         return (B_TRUE);
2777 
2778                 for (c = 0; c < children; c++)
2779                         if (is_replacing_spare(child[c], tgt, which))
2780                                 return (B_TRUE);
2781         }
2782 
2783         return (B_FALSE);
2784 }
2785 
2786 /*
2787  * Attach new_disk (fully described by nvroot) to old_disk.
2788  * If 'replacing' is specified, the new disk will replace the old one.
2789  */
2790 int
2791 zpool_vdev_attach(zpool_handle_t *zhp,
2792     const char *old_disk, const char *new_disk, nvlist_t *nvroot, int replacing)
2793 {
2794         zfs_cmd_t zc = { 0 };
2795         char msg[1024];
2796         int ret;
2797         nvlist_t *tgt;
2798         boolean_t avail_spare, l2cache, islog;
2799         uint64_t val;
2800         char *newname;
2801         nvlist_t **child;
2802         uint_t children;
2803         nvlist_t *config_root;
2804         libzfs_handle_t *hdl = zhp->zpool_hdl;
2805         boolean_t rootpool = zpool_is_bootable(zhp);
2806 
2807         if (replacing)
2808                 (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2809                     "cannot replace %s with %s"), old_disk, new_disk);
2810         else
2811                 (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2812                     "cannot attach %s to %s"), new_disk, old_disk);
2813 
2814         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2815         if ((tgt = zpool_find_vdev(zhp, old_disk, &avail_spare, &l2cache,
2816             &islog)) == NULL)
2817                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
2818 
2819         if (avail_spare)
2820                 return (zfs_error(hdl, EZFS_ISSPARE, msg));
2821 
2822         if (l2cache)
2823                 return (zfs_error(hdl, EZFS_ISL2CACHE, msg));
2824 
2825         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2826         zc.zc_cookie = replacing;
2827 
2828         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
2829             &child, &children) != 0 || children != 1) {
2830                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2831                     "new device must be a single disk"));
2832                 return (zfs_error(hdl, EZFS_INVALCONFIG, msg));
2833         }
2834 
2835         verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
2836             ZPOOL_CONFIG_VDEV_TREE, &config_root) == 0);
2837 
2838         if ((newname = zpool_vdev_name(NULL, NULL, child[0], B_FALSE)) == NULL)
2839                 return (-1);
2840 
2841         /*
2842          * If the target is a hot spare that has been swapped in, we can only
2843          * replace it with another hot spare.
2844          */
2845         if (replacing &&
2846             nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_IS_SPARE, &val) == 0 &&
2847             (zpool_find_vdev(zhp, newname, &avail_spare, &l2cache,
2848             NULL) == NULL || !avail_spare) &&
2849             is_replacing_spare(config_root, tgt, 1)) {
2850                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2851                     "can only be replaced by another hot spare"));
2852                 free(newname);
2853                 return (zfs_error(hdl, EZFS_BADTARGET, msg));
2854         }
2855 
2856         free(newname);
2857 
2858         if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
2859                 return (-1);
2860 
2861         ret = zfs_ioctl(hdl, ZFS_IOC_VDEV_ATTACH, &zc);
2862 
2863         zcmd_free_nvlists(&zc);
2864 
2865         if (ret == 0) {
2866                 if (rootpool) {
2867                         /*
2868                          * XXX need a better way to prevent user from
2869                          * booting up a half-baked vdev.
2870                          */
2871                         (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Make "
2872                             "sure to wait until resilver is done "
2873                             "before rebooting.\n"));
2874                 }
2875                 return (0);
2876         }
2877 
2878         switch (errno) {
2879         case ENOTSUP:
2880                 /*
2881                  * Can't attach to or replace this type of vdev.
2882                  */
2883                 if (replacing) {
2884                         uint64_t version = zpool_get_prop_int(zhp,
2885                             ZPOOL_PROP_VERSION, NULL);
2886 
2887                         if (islog)
2888                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2889                                     "cannot replace a log with a spare"));
2890                         else if (version >= SPA_VERSION_MULTI_REPLACE)
2891                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2892                                     "already in replacing/spare config; wait "
2893                                     "for completion or use 'zpool detach'"));
2894                         else
2895                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2896                                     "cannot replace a replacing device"));
2897                 } else {
2898                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2899                             "can only attach to mirrors and top-level "
2900                             "disks"));
2901                 }
2902                 (void) zfs_error(hdl, EZFS_BADTARGET, msg);
2903                 break;
2904 
2905         case EINVAL:
2906                 /*
2907                  * The new device must be a single disk.
2908                  */
2909                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2910                     "new device must be a single disk"));
2911                 (void) zfs_error(hdl, EZFS_INVALCONFIG, msg);
2912                 break;
2913 
2914         case EBUSY:
2915                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "%s is busy, "
2916                     "or device removal is in progress"),
2917                     new_disk);
2918                 (void) zfs_error(hdl, EZFS_BADDEV, msg);
2919                 break;
2920 
2921         case EOVERFLOW:
2922                 /*
2923                  * The new device is too small.
2924                  */
2925                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2926                     "device is too small"));
2927                 (void) zfs_error(hdl, EZFS_BADDEV, msg);
2928                 break;
2929 
2930         case EDOM:
2931                 /*
2932                  * The new device has a different alignment requirement.
2933                  */
2934                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2935                     "devices have different sector alignment"));
2936                 (void) zfs_error(hdl, EZFS_BADDEV, msg);
2937                 break;
2938 
2939         case ENAMETOOLONG:
2940                 /*
2941                  * The resulting top-level vdev spec won't fit in the label.
2942                  */
2943                 (void) zfs_error(hdl, EZFS_DEVOVERFLOW, msg);
2944                 break;
2945 
2946         default:
2947                 (void) zpool_standard_error(hdl, errno, msg);
2948         }
2949 
2950         return (-1);
2951 }
2952 
2953 /*
2954  * Detach the specified device.
2955  */
2956 int
2957 zpool_vdev_detach(zpool_handle_t *zhp, const char *path)
2958 {
2959         zfs_cmd_t zc = { 0 };
2960         char msg[1024];
2961         nvlist_t *tgt;
2962         boolean_t avail_spare, l2cache;
2963         libzfs_handle_t *hdl = zhp->zpool_hdl;
2964 
2965         (void) snprintf(msg, sizeof (msg),
2966             dgettext(TEXT_DOMAIN, "cannot detach %s"), path);
2967 
2968         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2969         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2970             NULL)) == NULL)
2971                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
2972 
2973         if (avail_spare)
2974                 return (zfs_error(hdl, EZFS_ISSPARE, msg));
2975 
2976         if (l2cache)
2977                 return (zfs_error(hdl, EZFS_ISL2CACHE, msg));
2978 
2979         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2980 
2981         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_DETACH, &zc) == 0)
2982                 return (0);
2983 
2984         switch (errno) {
2985 
2986         case ENOTSUP:
2987                 /*
2988                  * Can't detach from this type of vdev.
2989                  */
2990                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "only "
2991                     "applicable to mirror and replacing vdevs"));
2992                 (void) zfs_error(hdl, EZFS_BADTARGET, msg);
2993                 break;
2994 
2995         case EBUSY:
2996                 /*
2997                  * There are no other replicas of this device.
2998                  */
2999                 (void) zfs_error(hdl, EZFS_NOREPLICAS, msg);
3000                 break;
3001 
3002         default:
3003                 (void) zpool_standard_error(hdl, errno, msg);
3004         }
3005 
3006         return (-1);
3007 }
3008 
3009 /*
3010  * Find a mirror vdev in the source nvlist.
3011  *
3012  * The mchild array contains a list of disks in one of the top-level mirrors
3013  * of the source pool.  The schild array contains a list of disks that the
3014  * user specified on the command line.  We loop over the mchild array to
3015  * see if any entry in the schild array matches.
3016  *
3017  * If a disk in the mchild array is found in the schild array, we return
3018  * the index of that entry.  Otherwise we return -1.
3019  */
3020 static int
3021 find_vdev_entry(zpool_handle_t *zhp, nvlist_t **mchild, uint_t mchildren,
3022     nvlist_t **schild, uint_t schildren)
3023 {
3024         uint_t mc;
3025 
3026         for (mc = 0; mc < mchildren; mc++) {
3027                 uint_t sc;
3028                 char *mpath = zpool_vdev_name(zhp->zpool_hdl, zhp,
3029                     mchild[mc], B_FALSE);
3030 
3031                 for (sc = 0; sc < schildren; sc++) {
3032                         char *spath = zpool_vdev_name(zhp->zpool_hdl, zhp,
3033                             schild[sc], B_FALSE);
3034                         boolean_t result = (strcmp(mpath, spath) == 0);
3035 
3036                         free(spath);
3037                         if (result) {
3038                                 free(mpath);
3039                                 return (mc);
3040                         }
3041                 }
3042 
3043                 free(mpath);
3044         }
3045 
3046         return (-1);
3047 }
3048 
3049 /*
3050  * Split a mirror pool.  If newroot points to null, then a new nvlist
3051  * is generated and it is the responsibility of the caller to free it.
3052  */
3053 int
3054 zpool_vdev_split(zpool_handle_t *zhp, char *newname, nvlist_t **newroot,
3055     nvlist_t *props, splitflags_t flags)
3056 {
3057         zfs_cmd_t zc = { 0 };
3058         char msg[1024];
3059         nvlist_t *tree, *config, **child, **newchild, *newconfig = NULL;
3060         nvlist_t **varray = NULL, *zc_props = NULL;
3061         uint_t c, children, newchildren, lastlog = 0, vcount, found = 0;
3062         libzfs_handle_t *hdl = zhp->zpool_hdl;
3063         uint64_t vers;
3064         boolean_t freelist = B_FALSE, memory_err = B_TRUE;
3065         int retval = 0;
3066 
3067         (void) snprintf(msg, sizeof (msg),
3068             dgettext(TEXT_DOMAIN, "Unable to split %s"), zhp->zpool_name);
3069 
3070         if (!zpool_name_valid(hdl, B_FALSE, newname))
3071                 return (zfs_error(hdl, EZFS_INVALIDNAME, msg));
3072 
3073         if ((config = zpool_get_config(zhp, NULL)) == NULL) {
3074                 (void) fprintf(stderr, gettext("Internal error: unable to "
3075                     "retrieve pool configuration\n"));
3076                 return (-1);
3077         }
3078 
3079         verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &tree)
3080             == 0);
3081         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION, &vers) == 0);
3082 
3083         if (props) {
3084                 prop_flags_t flags = { .create = B_FALSE, .import = B_TRUE };
3085                 if ((zc_props = zpool_valid_proplist(hdl, zhp->zpool_name,
3086                     props, vers, flags, msg)) == NULL)
3087                         return (-1);
3088         }
3089 
3090         if (nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN, &child,
3091             &children) != 0) {
3092                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3093                     "Source pool is missing vdev tree"));
3094                 nvlist_free(zc_props);
3095                 return (-1);
3096         }
3097 
3098         varray = zfs_alloc(hdl, children * sizeof (nvlist_t *));
3099         vcount = 0;
3100 
3101         if (*newroot == NULL ||
3102             nvlist_lookup_nvlist_array(*newroot, ZPOOL_CONFIG_CHILDREN,
3103             &newchild, &newchildren) != 0)
3104                 newchildren = 0;
3105 
3106         for (c = 0; c < children; c++) {
3107                 uint64_t is_log = B_FALSE, is_hole = B_FALSE;
3108                 char *type;
3109                 nvlist_t **mchild, *vdev;
3110                 uint_t mchildren;
3111                 int entry;
3112 
3113                 /*
3114                  * Unlike cache & spares, slogs are stored in the
3115                  * ZPOOL_CONFIG_CHILDREN array.  We filter them out here.
3116                  */
3117                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3118                     &is_log);
3119                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
3120                     &is_hole);
3121                 if (is_log || is_hole) {
3122                         /*
3123                          * Create a hole vdev and put it in the config.
3124                          */
3125                         if (nvlist_alloc(&vdev, NV_UNIQUE_NAME, 0) != 0)
3126                                 goto out;
3127                         if (nvlist_add_string(vdev, ZPOOL_CONFIG_TYPE,
3128                             VDEV_TYPE_HOLE) != 0)
3129                                 goto out;
3130                         if (nvlist_add_uint64(vdev, ZPOOL_CONFIG_IS_HOLE,
3131                             1) != 0)
3132                                 goto out;
3133                         if (lastlog == 0)
3134                                 lastlog = vcount;
3135                         varray[vcount++] = vdev;
3136                         continue;
3137                 }
3138                 lastlog = 0;
3139                 verify(nvlist_lookup_string(child[c], ZPOOL_CONFIG_TYPE, &type)
3140                     == 0);
3141                 if (strcmp(type, VDEV_TYPE_MIRROR) != 0) {
3142                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3143                             "Source pool must be composed only of mirrors\n"));
3144                         retval = zfs_error(hdl, EZFS_INVALCONFIG, msg);
3145                         goto out;
3146                 }
3147 
3148                 verify(nvlist_lookup_nvlist_array(child[c],
3149                     ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren) == 0);
3150 
3151                 /* find or add an entry for this top-level vdev */
3152                 if (newchildren > 0 &&
3153                     (entry = find_vdev_entry(zhp, mchild, mchildren,
3154                     newchild, newchildren)) >= 0) {
3155                         /* We found a disk that the user specified. */
3156                         vdev = mchild[entry];
3157                         ++found;
3158                 } else {
3159                         /* User didn't specify a disk for this vdev. */
3160                         vdev = mchild[mchildren - 1];
3161                 }
3162 
3163                 if (nvlist_dup(vdev, &varray[vcount++], 0) != 0)
3164                         goto out;
3165         }
3166 
3167         /* did we find every disk the user specified? */
3168         if (found != newchildren) {
3169                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Device list must "
3170                     "include at most one disk from each mirror"));
3171                 retval = zfs_error(hdl, EZFS_INVALCONFIG, msg);
3172                 goto out;
3173         }
3174 
3175         /* Prepare the nvlist for populating. */
3176         if (*newroot == NULL) {
3177                 if (nvlist_alloc(newroot, NV_UNIQUE_NAME, 0) != 0)
3178                         goto out;
3179                 freelist = B_TRUE;
3180                 if (nvlist_add_string(*newroot, ZPOOL_CONFIG_TYPE,
3181                     VDEV_TYPE_ROOT) != 0)
3182                         goto out;
3183         } else {
3184                 verify(nvlist_remove_all(*newroot, ZPOOL_CONFIG_CHILDREN) == 0);
3185         }
3186 
3187         /* Add all the children we found */
3188         if (nvlist_add_nvlist_array(*newroot, ZPOOL_CONFIG_CHILDREN, varray,
3189             lastlog == 0 ? vcount : lastlog) != 0)
3190                 goto out;
3191 
3192         /*
3193          * If we're just doing a dry run, exit now with success.
3194          */
3195         if (flags.dryrun) {
3196                 memory_err = B_FALSE;
3197                 freelist = B_FALSE;
3198                 goto out;
3199         }
3200 
3201         /* now build up the config list & call the ioctl */
3202         if (nvlist_alloc(&newconfig, NV_UNIQUE_NAME, 0) != 0)
3203                 goto out;
3204 
3205         if (nvlist_add_nvlist(newconfig,
3206             ZPOOL_CONFIG_VDEV_TREE, *newroot) != 0 ||
3207             nvlist_add_string(newconfig,
3208             ZPOOL_CONFIG_POOL_NAME, newname) != 0 ||
3209             nvlist_add_uint64(newconfig, ZPOOL_CONFIG_VERSION, vers) != 0)
3210                 goto out;
3211 
3212         /*
3213          * The new pool is automatically part of the namespace unless we
3214          * explicitly export it.
3215          */
3216         if (!flags.import)
3217                 zc.zc_cookie = ZPOOL_EXPORT_AFTER_SPLIT;
3218         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3219         (void) strlcpy(zc.zc_string, newname, sizeof (zc.zc_string));
3220         if (zcmd_write_conf_nvlist(hdl, &zc, newconfig) != 0)
3221                 goto out;
3222         if (zc_props != NULL && zcmd_write_src_nvlist(hdl, &zc, zc_props) != 0)
3223                 goto out;
3224 
3225         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SPLIT, &zc) != 0) {
3226                 retval = zpool_standard_error(hdl, errno, msg);
3227                 goto out;
3228         }
3229 
3230         freelist = B_FALSE;
3231         memory_err = B_FALSE;
3232 
3233 out:
3234         if (varray != NULL) {
3235                 int v;
3236 
3237                 for (v = 0; v < vcount; v++)
3238                         nvlist_free(varray[v]);
3239                 free(varray);
3240         }
3241         zcmd_free_nvlists(&zc);
3242         nvlist_free(zc_props);
3243         nvlist_free(newconfig);
3244         if (freelist) {
3245                 nvlist_free(*newroot);
3246                 *newroot = NULL;
3247         }
3248 
3249         if (retval != 0)
3250                 return (retval);
3251 
3252         if (memory_err)
3253                 return (no_memory(hdl));
3254 
3255         return (0);
3256 }
3257 
3258 /*
3259  * Remove the given device.
3260  */
3261 int
3262 zpool_vdev_remove(zpool_handle_t *zhp, const char *path)
3263 {
3264         zfs_cmd_t zc = { 0 };
3265         char msg[1024];
3266         nvlist_t *tgt;
3267         boolean_t avail_spare, l2cache, islog;
3268         libzfs_handle_t *hdl = zhp->zpool_hdl;
3269         uint64_t version;
3270 
3271         (void) snprintf(msg, sizeof (msg),
3272             dgettext(TEXT_DOMAIN, "cannot remove %s"), path);
3273 
3274         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3275         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3276             &islog)) == NULL)
3277                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
3278 
3279         version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
3280         if (islog && version < SPA_VERSION_HOLES) {
3281                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3282                     "pool must be upgraded to support log removal"));
3283                 return (zfs_error(hdl, EZFS_BADVERSION, msg));
3284         }
3285 
3286         if (!islog && !avail_spare && !l2cache && zpool_is_bootable(zhp)) {
3287                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3288                     "root pool can not have removed devices, "
3289                     "because GRUB does not understand them"));
3290                 return (zfs_error(hdl, EINVAL, msg));
3291         }
3292 
3293         zc.zc_guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
3294 
3295         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_REMOVE, &zc) == 0)
3296                 return (0);
3297 
3298         switch (errno) {
3299 
3300         case EINVAL:
3301                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3302                     "invalid config; all top-level vdevs must "
3303                     "have the same sector size and not be raidz."));
3304                 (void) zfs_error(hdl, EZFS_INVALCONFIG, msg);
3305                 break;
3306 
3307         case EBUSY:
3308                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3309                     "Pool busy; removal may already be in progress"));
3310                 (void) zfs_error(hdl, EZFS_BUSY, msg);
3311                 break;
3312 
3313         default:
3314                 (void) zpool_standard_error(hdl, errno, msg);
3315         }
3316         return (-1);
3317 }
3318 
3319 int
3320 zpool_vdev_remove_cancel(zpool_handle_t *zhp)
3321 {
3322         zfs_cmd_t zc = { 0 };
3323         char msg[1024];
3324         libzfs_handle_t *hdl = zhp->zpool_hdl;
3325 
3326         (void) snprintf(msg, sizeof (msg),
3327             dgettext(TEXT_DOMAIN, "cannot cancel removal"));
3328 
3329         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3330         zc.zc_cookie = 1;
3331 
3332         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_REMOVE, &zc) == 0)
3333                 return (0);
3334 
3335         return (zpool_standard_error(hdl, errno, msg));
3336 }
3337 
3338 int
3339 zpool_vdev_indirect_size(zpool_handle_t *zhp, const char *path,
3340     uint64_t *sizep)
3341 {
3342         char msg[1024];
3343         nvlist_t *tgt;
3344         boolean_t avail_spare, l2cache, islog;
3345         libzfs_handle_t *hdl = zhp->zpool_hdl;
3346 
3347         (void) snprintf(msg, sizeof (msg),
3348             dgettext(TEXT_DOMAIN, "cannot determine indirect size of %s"),
3349             path);
3350 
3351         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3352             &islog)) == NULL)
3353                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
3354 
3355         if (avail_spare || l2cache || islog) {
3356                 *sizep = 0;
3357                 return (0);
3358         }
3359 
3360         if (nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_INDIRECT_SIZE, sizep) != 0) {
3361                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3362                     "indirect size not available"));
3363                 return (zfs_error(hdl, EINVAL, msg));
3364         }
3365         return (0);
3366 }
3367 
3368 /*
3369  * Clear the errors for the pool, or the particular device if specified.
3370  */
3371 int
3372 zpool_clear(zpool_handle_t *zhp, const char *path, nvlist_t *rewindnvl)
3373 {
3374         zfs_cmd_t zc = { 0 };
3375         char msg[1024];
3376         nvlist_t *tgt;
3377         zpool_load_policy_t policy;
3378         boolean_t avail_spare, l2cache;
3379         libzfs_handle_t *hdl = zhp->zpool_hdl;
3380         nvlist_t *nvi = NULL;
3381         int error;
3382 
3383         if (path)
3384                 (void) snprintf(msg, sizeof (msg),
3385                     dgettext(TEXT_DOMAIN, "cannot clear errors for %s"),
3386                     path);
3387         else
3388                 (void) snprintf(msg, sizeof (msg),
3389                     dgettext(TEXT_DOMAIN, "cannot clear errors for %s"),
3390                     zhp->zpool_name);
3391 
3392         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3393         if (path) {
3394                 if ((tgt = zpool_find_vdev(zhp, path, &avail_spare,
3395                     &l2cache, NULL)) == NULL)
3396                         return (zfs_error(hdl, EZFS_NODEVICE, msg));
3397 
3398                 /*
3399                  * Don't allow error clearing for hot spares.  Do allow
3400                  * error clearing for l2cache devices.
3401                  */
3402                 if (avail_spare)
3403                         return (zfs_error(hdl, EZFS_ISSPARE, msg));
3404 
3405                 verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID,
3406                     &zc.zc_guid) == 0);
3407         }
3408 
3409         zpool_get_load_policy(rewindnvl, &policy);
3410         zc.zc_cookie = policy.zlp_rewind;
3411 
3412         if (zcmd_alloc_dst_nvlist(hdl, &zc, zhp->zpool_config_size * 2) != 0)
3413                 return (-1);
3414 
3415         if (zcmd_write_src_nvlist(hdl, &zc, rewindnvl) != 0)
3416                 return (-1);
3417 
3418         while ((error = zfs_ioctl(hdl, ZFS_IOC_CLEAR, &zc)) != 0 &&
3419             errno == ENOMEM) {
3420                 if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
3421                         zcmd_free_nvlists(&zc);
3422                         return (-1);
3423                 }
3424         }
3425 
3426         if (!error || ((policy.zlp_rewind & ZPOOL_TRY_REWIND) &&
3427             errno != EPERM && errno != EACCES)) {
3428                 if (policy.zlp_rewind &
3429                     (ZPOOL_DO_REWIND | ZPOOL_TRY_REWIND)) {
3430                         (void) zcmd_read_dst_nvlist(hdl, &zc, &nvi);
3431                         zpool_rewind_exclaim(hdl, zc.zc_name,
3432                             ((policy.zlp_rewind & ZPOOL_TRY_REWIND) != 0),
3433                             nvi);
3434                         nvlist_free(nvi);
3435                 }
3436                 zcmd_free_nvlists(&zc);
3437                 return (0);
3438         }
3439 
3440         zcmd_free_nvlists(&zc);
3441         return (zpool_standard_error(hdl, errno, msg));
3442 }
3443 
3444 /*
3445  * Similar to zpool_clear(), but takes a GUID (used by fmd).
3446  */
3447 int
3448 zpool_vdev_clear(zpool_handle_t *zhp, uint64_t guid)
3449 {
3450         zfs_cmd_t zc = { 0 };
3451         char msg[1024];
3452         libzfs_handle_t *hdl = zhp->zpool_hdl;
3453 
3454         (void) snprintf(msg, sizeof (msg),
3455             dgettext(TEXT_DOMAIN, "cannot clear errors for %llx"),
3456             guid);
3457 
3458         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3459         zc.zc_guid = guid;
3460         zc.zc_cookie = ZPOOL_NO_REWIND;
3461 
3462         if (ioctl(hdl->libzfs_fd, ZFS_IOC_CLEAR, &zc) == 0)
3463                 return (0);
3464 
3465         return (zpool_standard_error(hdl, errno, msg));
3466 }
3467 
3468 /*
3469  * Change the GUID for a pool.
3470  */
3471 int
3472 zpool_reguid(zpool_handle_t *zhp)
3473 {
3474         char msg[1024];
3475         libzfs_handle_t *hdl = zhp->zpool_hdl;
3476         zfs_cmd_t zc = { 0 };
3477 
3478         (void) snprintf(msg, sizeof (msg),
3479             dgettext(TEXT_DOMAIN, "cannot reguid '%s'"), zhp->zpool_name);
3480 
3481         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3482         if (zfs_ioctl(hdl, ZFS_IOC_POOL_REGUID, &zc) == 0)
3483                 return (0);
3484 
3485         return (zpool_standard_error(hdl, errno, msg));
3486 }
3487 
3488 /*
3489  * Reopen the pool.
3490  */
3491 int
3492 zpool_reopen(zpool_handle_t *zhp)
3493 {
3494         zfs_cmd_t zc = { 0 };
3495         char msg[1024];
3496         libzfs_handle_t *hdl = zhp->zpool_hdl;
3497 
3498         (void) snprintf(msg, sizeof (msg),
3499             dgettext(TEXT_DOMAIN, "cannot reopen '%s'"),
3500             zhp->zpool_name);
3501 
3502         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3503         if (zfs_ioctl(hdl, ZFS_IOC_POOL_REOPEN, &zc) == 0)
3504                 return (0);
3505         return (zpool_standard_error(hdl, errno, msg));
3506 }
3507 
3508 /*
3509  * Convert from a devid string to a path.
3510  */
3511 static char *
3512 devid_to_path(char *devid_str)
3513 {
3514         ddi_devid_t devid;
3515         char *minor;
3516         char *path;
3517         devid_nmlist_t *list = NULL;
3518         int ret;
3519 
3520         if (devid_str_decode(devid_str, &devid, &minor) != 0)
3521                 return (NULL);
3522 
3523         ret = devid_deviceid_to_nmlist("/dev", devid, minor, &list);
3524 
3525         devid_str_free(minor);
3526         devid_free(devid);
3527 
3528         if (ret != 0)
3529                 return (NULL);
3530 
3531         /*
3532          * In a case the strdup() fails, we will just return NULL below.
3533          */
3534         path = strdup(list[0].devname);
3535 
3536         devid_free_nmlist(list);
3537 
3538         return (path);
3539 }
3540 
3541 /*
3542  * Convert from a path to a devid string.
3543  */
3544 static char *
3545 path_to_devid(const char *path)
3546 {
3547         int fd;
3548         ddi_devid_t devid;
3549         char *minor, *ret;
3550 
3551         if ((fd = open(path, O_RDONLY)) < 0)
3552                 return (NULL);
3553 
3554         minor = NULL;
3555         ret = NULL;
3556         if (devid_get(fd, &devid) == 0) {
3557                 if (devid_get_minor_name(fd, &minor) == 0)
3558                         ret = devid_str_encode(devid, minor);
3559                 if (minor != NULL)
3560                         devid_str_free(minor);
3561                 devid_free(devid);
3562         }
3563         (void) close(fd);
3564 
3565         return (ret);
3566 }
3567 
3568 /*
3569  * Issue the necessary ioctl() to update the stored path value for the vdev.  We
3570  * ignore any failure here, since a common case is for an unprivileged user to
3571  * type 'zpool status', and we'll display the correct information anyway.
3572  */
3573 static void
3574 set_path(zpool_handle_t *zhp, nvlist_t *nv, const char *path)
3575 {
3576         zfs_cmd_t zc = { 0 };
3577 
3578         (void) strncpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3579         (void) strncpy(zc.zc_value, path, sizeof (zc.zc_value));
3580         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
3581             &zc.zc_guid) == 0);
3582 
3583         (void) ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_VDEV_SETPATH, &zc);
3584 }
3585 
3586 /*
3587  * Given a vdev, return the name to display in iostat.  If the vdev has a path,
3588  * we use that, stripping off any leading "/dev/dsk/"; if not, we use the type.
3589  * We also check if this is a whole disk, in which case we strip off the
3590  * trailing 's0' slice name.
3591  *
3592  * This routine is also responsible for identifying when disks have been
3593  * reconfigured in a new location.  The kernel will have opened the device by
3594  * devid, but the path will still refer to the old location.  To catch this, we
3595  * first do a path -> devid translation (which is fast for the common case).  If
3596  * the devid matches, we're done.  If not, we do a reverse devid -> path
3597  * translation and issue the appropriate ioctl() to update the path of the vdev.
3598  * If 'zhp' is NULL, then this is an exported pool, and we don't need to do any
3599  * of these checks.
3600  */
3601 char *
3602 zpool_vdev_name(libzfs_handle_t *hdl, zpool_handle_t *zhp, nvlist_t *nv,
3603     boolean_t verbose)
3604 {
3605         char *path, *devid;
3606         uint64_t value;
3607         char buf[64];
3608         vdev_stat_t *vs;
3609         uint_t vsc;
3610 
3611         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
3612             &value) == 0) {
3613                 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
3614                     &value) == 0);
3615                 (void) snprintf(buf, sizeof (buf), "%llu",
3616                     (u_longlong_t)value);
3617                 path = buf;
3618         } else if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
3619 
3620                 /*
3621                  * If the device is dead (faulted, offline, etc) then don't
3622                  * bother opening it.  Otherwise we may be forcing the user to
3623                  * open a misbehaving device, which can have undesirable
3624                  * effects.
3625                  */
3626                 if ((nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
3627                     (uint64_t **)&vs, &vsc) != 0 ||
3628                     vs->vs_state >= VDEV_STATE_DEGRADED) &&
3629                     zhp != NULL &&
3630                     nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &devid) == 0) {
3631                         /*
3632                          * Determine if the current path is correct.
3633                          */
3634                         char *newdevid = path_to_devid(path);
3635 
3636                         if (newdevid == NULL ||
3637                             strcmp(devid, newdevid) != 0) {
3638                                 char *newpath;
3639 
3640                                 if ((newpath = devid_to_path(devid)) != NULL) {
3641                                         /*
3642                                          * Update the path appropriately.
3643                                          */
3644                                         set_path(zhp, nv, newpath);
3645                                         if (nvlist_add_string(nv,
3646                                             ZPOOL_CONFIG_PATH, newpath) == 0)
3647                                                 verify(nvlist_lookup_string(nv,
3648                                                     ZPOOL_CONFIG_PATH,
3649                                                     &path) == 0);
3650                                         free(newpath);
3651                                 }
3652                         }
3653 
3654                         if (newdevid)
3655                                 devid_str_free(newdevid);
3656                 }
3657 
3658                 if (strncmp(path, ZFS_DISK_ROOTD, strlen(ZFS_DISK_ROOTD)) == 0)
3659                         path += strlen(ZFS_DISK_ROOTD);
3660 
3661                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
3662                     &value) == 0 && value) {
3663                         int pathlen = strlen(path);
3664                         char *tmp = zfs_strdup(hdl, path);
3665 
3666                         /*
3667                          * If it starts with c#, and ends with "s0" or "s1",
3668                          * chop the slice off, or if it ends with "s0/old" or
3669                          * "s1/old", remove the slice from the middle.
3670                          */
3671                         if (CTD_CHECK(tmp)) {
3672                                 if (strcmp(&tmp[pathlen - 2], "s0") == 0 ||
3673                                     strcmp(&tmp[pathlen - 2], "s1") == 0) {
3674                                         tmp[pathlen - 2] = '\0';
3675                                 } else if (pathlen > 6 &&
3676                                     (strcmp(&tmp[pathlen - 6], "s0/old") == 0 ||
3677                                     strcmp(&tmp[pathlen - 6], "s1/old") == 0)) {
3678                                         (void) strcpy(&tmp[pathlen - 6],
3679                                             "/old");
3680                                 }
3681                         }
3682                         return (tmp);
3683                 }
3684         } else {
3685                 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &path) == 0);
3686 
3687                 /*
3688                  * If it's a raidz device, we need to stick in the parity level.
3689                  */
3690                 if (strcmp(path, VDEV_TYPE_RAIDZ) == 0) {
3691                         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
3692                             &value) == 0);
3693                         (void) snprintf(buf, sizeof (buf), "%s%llu", path,
3694                             (u_longlong_t)value);
3695                         path = buf;
3696                 }
3697 
3698                 /*
3699                  * We identify each top-level vdev by using a <type-id>
3700                  * naming convention.
3701                  */
3702                 if (verbose) {
3703                         uint64_t id;
3704 
3705                         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID,
3706                             &id) == 0);
3707                         (void) snprintf(buf, sizeof (buf), "%s-%llu", path,
3708                             (u_longlong_t)id);
3709                         path = buf;
3710                 }
3711         }
3712 
3713         return (zfs_strdup(hdl, path));
3714 }
3715 
3716 static int
3717 zbookmark_mem_compare(const void *a, const void *b)
3718 {
3719         return (memcmp(a, b, sizeof (zbookmark_phys_t)));
3720 }
3721 
3722 /*
3723  * Retrieve the persistent error log, uniquify the members, and return to the
3724  * caller.
3725  */
3726 int
3727 zpool_get_errlog(zpool_handle_t *zhp, nvlist_t **nverrlistp)
3728 {
3729         zfs_cmd_t zc = { 0 };
3730         uint64_t count;
3731         zbookmark_phys_t *zb = NULL;
3732         int i;
3733 
3734         /*
3735          * Retrieve the raw error list from the kernel.  If the number of errors
3736          * has increased, allocate more space and continue until we get the
3737          * entire list.
3738          */
3739         verify(nvlist_lookup_uint64(zhp->zpool_config, ZPOOL_CONFIG_ERRCOUNT,
3740             &count) == 0);
3741         if (count == 0)
3742                 return (0);
3743         if ((zc.zc_nvlist_dst = (uintptr_t)zfs_alloc(zhp->zpool_hdl,
3744             count * sizeof (zbookmark_phys_t))) == (uintptr_t)NULL)
3745                 return (-1);
3746         zc.zc_nvlist_dst_size = count;
3747         (void) strcpy(zc.zc_name, zhp->zpool_name);
3748         for (;;) {
3749                 if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_ERROR_LOG,
3750                     &zc) != 0) {
3751                         free((void *)(uintptr_t)zc.zc_nvlist_dst);
3752                         if (errno == ENOMEM) {
3753                                 void *dst;
3754 
3755                                 count = zc.zc_nvlist_dst_size;
3756                                 dst = zfs_alloc(zhp->zpool_hdl, count *
3757                                     sizeof (zbookmark_phys_t));
3758                                 if (dst == NULL)
3759                                         return (-1);
3760                                 zc.zc_nvlist_dst = (uintptr_t)dst;
3761                         } else {
3762                                 return (-1);
3763                         }
3764                 } else {
3765                         break;
3766                 }
3767         }
3768 
3769         /*
3770          * Sort the resulting bookmarks.  This is a little confusing due to the
3771          * implementation of ZFS_IOC_ERROR_LOG.  The bookmarks are copied last
3772          * to first, and 'zc_nvlist_dst_size' indicates the number of boomarks
3773          * _not_ copied as part of the process.  So we point the start of our
3774          * array appropriate and decrement the total number of elements.
3775          */
3776         zb = ((zbookmark_phys_t *)(uintptr_t)zc.zc_nvlist_dst) +
3777             zc.zc_nvlist_dst_size;
3778         count -= zc.zc_nvlist_dst_size;
3779 
3780         qsort(zb, count, sizeof (zbookmark_phys_t), zbookmark_mem_compare);
3781 
3782         verify(nvlist_alloc(nverrlistp, 0, KM_SLEEP) == 0);
3783 
3784         /*
3785          * Fill in the nverrlistp with nvlist's of dataset and object numbers.
3786          */
3787         for (i = 0; i < count; i++) {
3788                 nvlist_t *nv;
3789 
3790                 /* ignoring zb_blkid and zb_level for now */
3791                 if (i > 0 && zb[i-1].zb_objset == zb[i].zb_objset &&
3792                     zb[i-1].zb_object == zb[i].zb_object)
3793                         continue;
3794 
3795                 if (nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) != 0)
3796                         goto nomem;
3797                 if (nvlist_add_uint64(nv, ZPOOL_ERR_DATASET,
3798                     zb[i].zb_objset) != 0) {
3799                         nvlist_free(nv);
3800                         goto nomem;
3801                 }
3802                 if (nvlist_add_uint64(nv, ZPOOL_ERR_OBJECT,
3803                     zb[i].zb_object) != 0) {
3804                         nvlist_free(nv);
3805                         goto nomem;
3806                 }
3807                 if (nvlist_add_nvlist(*nverrlistp, "ejk", nv) != 0) {
3808                         nvlist_free(nv);
3809                         goto nomem;
3810                 }
3811                 nvlist_free(nv);
3812         }
3813 
3814         free((void *)(uintptr_t)zc.zc_nvlist_dst);
3815         return (0);
3816 
3817 nomem:
3818         free((void *)(uintptr_t)zc.zc_nvlist_dst);
3819         return (no_memory(zhp->zpool_hdl));
3820 }
3821 
3822 /*
3823  * Upgrade a ZFS pool to the latest on-disk version.
3824  */
3825 int
3826 zpool_upgrade(zpool_handle_t *zhp, uint64_t new_version)
3827 {
3828         zfs_cmd_t zc = { 0 };
3829         libzfs_handle_t *hdl = zhp->zpool_hdl;
3830 
3831         (void) strcpy(zc.zc_name, zhp->zpool_name);
3832         zc.zc_cookie = new_version;
3833 
3834         if (zfs_ioctl(hdl, ZFS_IOC_POOL_UPGRADE, &zc) != 0)
3835                 return (zpool_standard_error_fmt(hdl, errno,
3836                     dgettext(TEXT_DOMAIN, "cannot upgrade '%s'"),
3837                     zhp->zpool_name));
3838         return (0);
3839 }
3840 
3841 void
3842 zfs_save_arguments(int argc, char **argv, char *string, int len)
3843 {
3844         (void) strlcpy(string, basename(argv[0]), len);
3845         for (int i = 1; i < argc; i++) {
3846                 (void) strlcat(string, " ", len);
3847                 (void) strlcat(string, argv[i], len);
3848         }
3849 }
3850 
3851 int
3852 zpool_log_history(libzfs_handle_t *hdl, const char *message)
3853 {
3854         zfs_cmd_t zc = { 0 };
3855         nvlist_t *args;
3856         int err;
3857 
3858         args = fnvlist_alloc();
3859         fnvlist_add_string(args, "message", message);
3860         err = zcmd_write_src_nvlist(hdl, &zc, args);
3861         if (err == 0)
3862                 err = ioctl(hdl->libzfs_fd, ZFS_IOC_LOG_HISTORY, &zc);
3863         nvlist_free(args);
3864         zcmd_free_nvlists(&zc);
3865         return (err);
3866 }
3867 
3868 /*
3869  * Perform ioctl to get some command history of a pool.
3870  *
3871  * 'buf' is the buffer to fill up to 'len' bytes.  'off' is the
3872  * logical offset of the history buffer to start reading from.
3873  *
3874  * Upon return, 'off' is the next logical offset to read from and
3875  * 'len' is the actual amount of bytes read into 'buf'.
3876  */
3877 static int
3878 get_history(zpool_handle_t *zhp, char *buf, uint64_t *off, uint64_t *len)
3879 {
3880         zfs_cmd_t zc = { 0 };
3881         libzfs_handle_t *hdl = zhp->zpool_hdl;
3882 
3883         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3884 
3885         zc.zc_history = (uint64_t)(uintptr_t)buf;
3886         zc.zc_history_len = *len;
3887         zc.zc_history_offset = *off;
3888 
3889         if (ioctl(hdl->libzfs_fd, ZFS_IOC_POOL_GET_HISTORY, &zc) != 0) {
3890                 switch (errno) {
3891                 case EPERM:
3892                         return (zfs_error_fmt(hdl, EZFS_PERM,
3893                             dgettext(TEXT_DOMAIN,
3894                             "cannot show history for pool '%s'"),
3895                             zhp->zpool_name));
3896                 case ENOENT:
3897                         return (zfs_error_fmt(hdl, EZFS_NOHISTORY,
3898                             dgettext(TEXT_DOMAIN, "cannot get history for pool "
3899                             "'%s'"), zhp->zpool_name));
3900                 case ENOTSUP:
3901                         return (zfs_error_fmt(hdl, EZFS_BADVERSION,
3902                             dgettext(TEXT_DOMAIN, "cannot get history for pool "
3903                             "'%s', pool must be upgraded"), zhp->zpool_name));
3904                 default:
3905                         return (zpool_standard_error_fmt(hdl, errno,
3906                             dgettext(TEXT_DOMAIN,
3907                             "cannot get history for '%s'"), zhp->zpool_name));
3908                 }
3909         }
3910 
3911         *len = zc.zc_history_len;
3912         *off = zc.zc_history_offset;
3913 
3914         return (0);
3915 }
3916 
3917 /*
3918  * Process the buffer of nvlists, unpacking and storing each nvlist record
3919  * into 'records'.  'leftover' is set to the number of bytes that weren't
3920  * processed as there wasn't a complete record.
3921  */
3922 int
3923 zpool_history_unpack(char *buf, uint64_t bytes_read, uint64_t *leftover,
3924     nvlist_t ***records, uint_t *numrecords)
3925 {
3926         uint64_t reclen;
3927         nvlist_t *nv;
3928         int i;
3929 
3930         while (bytes_read > sizeof (reclen)) {
3931 
3932                 /* get length of packed record (stored as little endian) */
3933                 for (i = 0, reclen = 0; i < sizeof (reclen); i++)
3934                         reclen += (uint64_t)(((uchar_t *)buf)[i]) << (8*i);
3935 
3936                 if (bytes_read < sizeof (reclen) + reclen)
3937                         break;
3938 
3939                 /* unpack record */
3940                 if (nvlist_unpack(buf + sizeof (reclen), reclen, &nv, 0) != 0)
3941                         return (ENOMEM);
3942                 bytes_read -= sizeof (reclen) + reclen;
3943                 buf += sizeof (reclen) + reclen;
3944 
3945                 /* add record to nvlist array */
3946                 (*numrecords)++;
3947                 if (ISP2(*numrecords + 1)) {
3948                         *records = realloc(*records,
3949                             *numrecords * 2 * sizeof (nvlist_t *));
3950                 }
3951                 (*records)[*numrecords - 1] = nv;
3952         }
3953 
3954         *leftover = bytes_read;
3955         return (0);
3956 }
3957 
3958 /*
3959  * Retrieve the command history of a pool.
3960  */
3961 int
3962 zpool_get_history(zpool_handle_t *zhp, nvlist_t **nvhisp)
3963 {
3964         char *buf;
3965         int buflen = 128 * 1024;
3966         uint64_t off = 0;
3967         nvlist_t **records = NULL;
3968         uint_t numrecords = 0;
3969         int err, i;
3970 
3971         buf = malloc(buflen);
3972         if (buf == NULL)
3973                 return (ENOMEM);
3974         do {
3975                 uint64_t bytes_read = buflen;
3976                 uint64_t leftover;
3977 
3978                 if ((err = get_history(zhp, buf, &off, &bytes_read)) != 0)
3979                         break;
3980 
3981                 /* if nothing else was read in, we're at EOF, just return */
3982                 if (!bytes_read)
3983                         break;
3984 
3985                 if ((err = zpool_history_unpack(buf, bytes_read,
3986                     &leftover, &records, &numrecords)) != 0)
3987                         break;
3988                 off -= leftover;
3989                 if (leftover == bytes_read) {
3990                         /*
3991                          * no progress made, because buffer is not big enough
3992                          * to hold this record; resize and retry.
3993                          */
3994                         buflen *= 2;
3995                         free(buf);
3996                         buf = malloc(buflen);
3997                         if (buf == NULL)
3998                                 return (ENOMEM);
3999                 }
4000 
4001                 /* CONSTCOND */
4002         } while (1);
4003 
4004         free(buf);
4005 
4006         if (!err) {
4007                 verify(nvlist_alloc(nvhisp, NV_UNIQUE_NAME, 0) == 0);
4008                 verify(nvlist_add_nvlist_array(*nvhisp, ZPOOL_HIST_RECORD,
4009                     records, numrecords) == 0);
4010         }
4011         for (i = 0; i < numrecords; i++)
4012                 nvlist_free(records[i]);
4013         free(records);
4014 
4015         return (err);
4016 }
4017 
4018 void
4019 zpool_obj_to_path(zpool_handle_t *zhp, uint64_t dsobj, uint64_t obj,
4020     char *pathname, size_t len)
4021 {
4022         zfs_cmd_t zc = { 0 };
4023         boolean_t mounted = B_FALSE;
4024         char *mntpnt = NULL;
4025         char dsname[ZFS_MAX_DATASET_NAME_LEN];
4026 
4027         if (dsobj == 0) {
4028                 /* special case for the MOS */
4029                 (void) snprintf(pathname, len, "<metadata>:<0x%llx>", obj);
4030                 return;
4031         }
4032 
4033         /* get the dataset's name */
4034         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
4035         zc.zc_obj = dsobj;
4036         if (ioctl(zhp->zpool_hdl->libzfs_fd,
4037             ZFS_IOC_DSOBJ_TO_DSNAME, &zc) != 0) {
4038                 /* just write out a path of two object numbers */
4039                 (void) snprintf(pathname, len, "<0x%llx>:<0x%llx>",
4040                     dsobj, obj);
4041                 return;
4042         }
4043         (void) strlcpy(dsname, zc.zc_value, sizeof (dsname));
4044 
4045         /* find out if the dataset is mounted */
4046         mounted = is_mounted(zhp->zpool_hdl, dsname, &mntpnt);
4047 
4048         /* get the corrupted object's path */
4049         (void) strlcpy(zc.zc_name, dsname, sizeof (zc.zc_name));
4050         zc.zc_obj = obj;
4051         if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_OBJ_TO_PATH,
4052             &zc) == 0) {
4053                 if (mounted) {
4054                         (void) snprintf(pathname, len, "%s%s", mntpnt,
4055                             zc.zc_value);
4056                 } else {
4057                         (void) snprintf(pathname, len, "%s:%s",
4058                             dsname, zc.zc_value);
4059                 }
4060         } else {
4061                 (void) snprintf(pathname, len, "%s:<0x%llx>", dsname, obj);
4062         }
4063         free(mntpnt);
4064 }
4065 
4066 /*
4067  * Read the EFI label from the config, if a label does not exist then
4068  * pass back the error to the caller. If the caller has passed a non-NULL
4069  * diskaddr argument then we set it to the starting address of the EFI
4070  * partition. If the caller has passed a non-NULL boolean argument, then
4071  * we set it to indicate if the disk does have efi system partition.
4072  */
4073 static int
4074 read_efi_label(nvlist_t *config, diskaddr_t *sb, boolean_t *system)
4075 {
4076         char *path;
4077         int fd;
4078         char diskname[MAXPATHLEN];
4079         boolean_t boot = B_FALSE;
4080         int err = -1;
4081         int slice;
4082 
4083         if (nvlist_lookup_string(config, ZPOOL_CONFIG_PATH, &path) != 0)
4084                 return (err);
4085 
4086         (void) snprintf(diskname, sizeof (diskname), "%s%s", ZFS_RDISK_ROOT,
4087             strrchr(path, '/'));
4088         if ((fd = open(diskname, O_RDONLY|O_NDELAY)) >= 0) {
4089                 struct dk_gpt *vtoc;
4090 
4091                 if ((err = efi_alloc_and_read(fd, &vtoc)) >= 0) {
4092                         for (slice = 0; slice < vtoc->efi_nparts; slice++) {
4093                                 if (vtoc->efi_parts[slice].p_tag == V_SYSTEM)
4094                                         boot = B_TRUE;
4095                                 if (vtoc->efi_parts[slice].p_tag == V_USR)
4096                                         break;
4097                         }
4098                         if (sb != NULL && vtoc->efi_parts[slice].p_tag == V_USR)
4099                                 *sb = vtoc->efi_parts[slice].p_start;
4100                         if (system != NULL)
4101                                 *system = boot;
4102                         efi_free(vtoc);
4103                 }
4104                 (void) close(fd);
4105         }
4106         return (err);
4107 }
4108 
4109 /*
4110  * determine where a partition starts on a disk in the current
4111  * configuration
4112  */
4113 static diskaddr_t
4114 find_start_block(nvlist_t *config)
4115 {
4116         nvlist_t **child;
4117         uint_t c, children;
4118         diskaddr_t sb = MAXOFFSET_T;
4119         uint64_t wholedisk;
4120 
4121         if (nvlist_lookup_nvlist_array(config,
4122             ZPOOL_CONFIG_CHILDREN, &child, &children) != 0) {
4123                 if (nvlist_lookup_uint64(config,
4124                     ZPOOL_CONFIG_WHOLE_DISK,
4125                     &wholedisk) != 0 || !wholedisk) {
4126                         return (MAXOFFSET_T);
4127                 }
4128                 if (read_efi_label(config, &sb, NULL) < 0)
4129                         sb = MAXOFFSET_T;
4130                 return (sb);
4131         }
4132 
4133         for (c = 0; c < children; c++) {
4134                 sb = find_start_block(child[c]);
4135                 if (sb != MAXOFFSET_T) {
4136                         return (sb);
4137                 }
4138         }
4139         return (MAXOFFSET_T);
4140 }
4141 
4142 /*
4143  * Label an individual disk.  The name provided is the short name,
4144  * stripped of any leading /dev path.
4145  */
4146 int
4147 zpool_label_disk(libzfs_handle_t *hdl, zpool_handle_t *zhp, const char *name,
4148     zpool_boot_label_t boot_type, uint64_t boot_size, int *slice)
4149 {
4150         char path[MAXPATHLEN];
4151         struct dk_gpt *vtoc;
4152         int fd;
4153         size_t resv = EFI_MIN_RESV_SIZE;
4154         uint64_t slice_size;
4155         diskaddr_t start_block;
4156         char errbuf[1024];
4157 
4158         /* prepare an error message just in case */
4159         (void) snprintf(errbuf, sizeof (errbuf),
4160             dgettext(TEXT_DOMAIN, "cannot label '%s'"), name);
4161 
4162         if (zhp) {
4163                 nvlist_t *nvroot;
4164 
4165                 verify(nvlist_lookup_nvlist(zhp->zpool_config,
4166                     ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4167 
4168                 if (zhp->zpool_start_block == 0)
4169                         start_block = find_start_block(nvroot);
4170                 else
4171                         start_block = zhp->zpool_start_block;
4172                 zhp->zpool_start_block = start_block;
4173         } else {
4174                 /* new pool */
4175                 start_block = NEW_START_BLOCK;
4176         }
4177 
4178         (void) snprintf(path, sizeof (path), "%s/%s%s", ZFS_RDISK_ROOT, name,
4179             BACKUP_SLICE);
4180 
4181         if ((fd = open(path, O_RDWR | O_NDELAY)) < 0) {
4182                 /*
4183                  * This shouldn't happen.  We've long since verified that this
4184                  * is a valid device.
4185                  */
4186                 zfs_error_aux(hdl,
4187                     dgettext(TEXT_DOMAIN, "unable to open device"));
4188                 return (zfs_error(hdl, EZFS_OPENFAILED, errbuf));
4189         }
4190 
4191         if (efi_alloc_and_init(fd, EFI_NUMPAR, &vtoc) != 0) {
4192                 /*
4193                  * The only way this can fail is if we run out of memory, or we
4194                  * were unable to read the disk's capacity
4195                  */
4196                 if (errno == ENOMEM)
4197                         (void) no_memory(hdl);
4198 
4199                 (void) close(fd);
4200                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4201                     "unable to read disk capacity"), name);
4202 
4203                 return (zfs_error(hdl, EZFS_NOCAP, errbuf));
4204         }
4205 
4206         /*
4207          * Why we use V_USR: V_BACKUP confuses users, and is considered
4208          * disposable by some EFI utilities (since EFI doesn't have a backup
4209          * slice).  V_UNASSIGNED is supposed to be used only for zero size
4210          * partitions, and efi_write() will fail if we use it.  V_ROOT, V_BOOT,
4211          * etc. were all pretty specific.  V_USR is as close to reality as we
4212          * can get, in the absence of V_OTHER.
4213          */
4214         /* first fix the partition start block */
4215         if (start_block == MAXOFFSET_T)
4216                 start_block = NEW_START_BLOCK;
4217 
4218         /*
4219          * EFI System partition is using slice 0.
4220          * ZFS is on slice 1 and slice 8 is reserved.
4221          * We assume the GPT partition table without system
4222          * partition has zfs p_start == NEW_START_BLOCK.
4223          * If start_block != NEW_START_BLOCK, it means we have
4224          * system partition. Correct solution would be to query/cache vtoc
4225          * from existing vdev member.
4226          */
4227         if (boot_type == ZPOOL_CREATE_BOOT_LABEL) {
4228                 if (boot_size % vtoc->efi_lbasize != 0) {
4229                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4230                             "boot partition size must be a multiple of %d"),
4231                             vtoc->efi_lbasize);
4232                         (void) close(fd);
4233                         efi_free(vtoc);
4234                         return (zfs_error(hdl, EZFS_LABELFAILED, errbuf));
4235                 }
4236                 /*
4237                  * System partition size checks.
4238                  * Note the 1MB is quite arbitrary value, since we
4239                  * are creating dedicated pool, it should be enough
4240                  * to hold fat + efi bootloader. May need to be
4241                  * adjusted if the bootloader size will grow.
4242                  */
4243                 if (boot_size < 1024 * 1024) {
4244                         char buf[64];
4245                         zfs_nicenum(boot_size, buf, sizeof (buf));
4246                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4247                             "Specified size %s for EFI System partition is too "
4248                             "small, the minimum size is 1MB."), buf);
4249                         (void) close(fd);
4250                         efi_free(vtoc);
4251                         return (zfs_error(hdl, EZFS_LABELFAILED, errbuf));
4252                 }
4253                 /* 33MB is tested with mkfs -F pcfs */
4254                 if (hdl->libzfs_printerr &&
4255                     ((vtoc->efi_lbasize == 512 &&
4256                     boot_size < 33 * 1024 * 1024) ||
4257                     (vtoc->efi_lbasize == 4096 &&
4258                     boot_size < 256 * 1024 * 1024)))  {
4259                         char buf[64];
4260                         zfs_nicenum(boot_size, buf, sizeof (buf));
4261                         (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
4262                             "Warning: EFI System partition size %s is "
4263                             "not allowing to create FAT32 file\nsystem, which "
4264                             "may result in unbootable system.\n"), buf);
4265                 }
4266                 /* Adjust zfs partition start by size of system partition. */
4267                 start_block += boot_size / vtoc->efi_lbasize;
4268         }
4269 
4270         if (start_block == NEW_START_BLOCK) {
4271                 /*
4272                  * Use default layout.
4273                  * ZFS is on slice 0 and slice 8 is reserved.
4274                  */
4275                 slice_size = vtoc->efi_last_u_lba + 1;
4276                 slice_size -= EFI_MIN_RESV_SIZE;
4277                 slice_size -= start_block;
4278                 if (slice != NULL)
4279                         *slice = 0;
4280 
4281                 vtoc->efi_parts[0].p_start = start_block;
4282                 vtoc->efi_parts[0].p_size = slice_size;
4283 
4284                 vtoc->efi_parts[0].p_tag = V_USR;
4285                 (void) strcpy(vtoc->efi_parts[0].p_name, "zfs");
4286 
4287                 vtoc->efi_parts[8].p_start = slice_size + start_block;
4288                 vtoc->efi_parts[8].p_size = resv;
4289                 vtoc->efi_parts[8].p_tag = V_RESERVED;
4290         } else {
4291                 slice_size = start_block - NEW_START_BLOCK;
4292                 vtoc->efi_parts[0].p_start = NEW_START_BLOCK;
4293                 vtoc->efi_parts[0].p_size = slice_size;
4294                 vtoc->efi_parts[0].p_tag = V_SYSTEM;
4295                 (void) strcpy(vtoc->efi_parts[0].p_name, "loader");
4296                 if (slice != NULL)
4297                         *slice = 1;
4298                 /* prepare slice 1 */
4299                 slice_size = vtoc->efi_last_u_lba + 1 - slice_size;
4300                 slice_size -= resv;
4301                 slice_size -= NEW_START_BLOCK;
4302                 vtoc->efi_parts[1].p_start = start_block;
4303                 vtoc->efi_parts[1].p_size = slice_size;
4304                 vtoc->efi_parts[1].p_tag = V_USR;
4305                 (void) strcpy(vtoc->efi_parts[1].p_name, "zfs");
4306 
4307                 vtoc->efi_parts[8].p_start = slice_size + start_block;
4308                 vtoc->efi_parts[8].p_size = resv;
4309                 vtoc->efi_parts[8].p_tag = V_RESERVED;
4310         }
4311 
4312         if (efi_write(fd, vtoc) != 0) {
4313                 /*
4314                  * Some block drivers (like pcata) may not support EFI
4315                  * GPT labels.  Print out a helpful error message dir-
4316                  * ecting the user to manually label the disk and give
4317                  * a specific slice.
4318                  */
4319                 (void) close(fd);
4320                 efi_free(vtoc);
4321 
4322                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4323                     "try using fdisk(1M) and then provide a specific slice"));
4324                 return (zfs_error(hdl, EZFS_LABELFAILED, errbuf));
4325         }
4326 
4327         (void) close(fd);
4328         efi_free(vtoc);
4329         return (0);
4330 }
4331 
4332 static boolean_t
4333 supported_dump_vdev_type(libzfs_handle_t *hdl, nvlist_t *config, char *errbuf)
4334 {
4335         char *type;
4336         nvlist_t **child;
4337         uint_t children, c;
4338 
4339         verify(nvlist_lookup_string(config, ZPOOL_CONFIG_TYPE, &type) == 0);
4340         if (strcmp(type, VDEV_TYPE_FILE) == 0 ||
4341             strcmp(type, VDEV_TYPE_HOLE) == 0 ||
4342             strcmp(type, VDEV_TYPE_MISSING) == 0) {
4343                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4344                     "vdev type '%s' is not supported"), type);
4345                 (void) zfs_error(hdl, EZFS_VDEVNOTSUP, errbuf);
4346                 return (B_FALSE);
4347         }
4348         if (nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_CHILDREN,
4349             &child, &children) == 0) {
4350                 for (c = 0; c < children; c++) {
4351                         if (!supported_dump_vdev_type(hdl, child[c], errbuf))
4352                                 return (B_FALSE);
4353                 }
4354         }
4355         return (B_TRUE);
4356 }
4357 
4358 /*
4359  * Check if this zvol is allowable for use as a dump device; zero if
4360  * it is, > 0 if it isn't, < 0 if it isn't a zvol.
4361  *
4362  * Allowable storage configurations include mirrors, all raidz variants, and
4363  * pools with log, cache, and spare devices.  Pools which are backed by files or
4364  * have missing/hole vdevs are not suitable.
4365  */
4366 int
4367 zvol_check_dump_config(char *arg)
4368 {
4369         zpool_handle_t *zhp = NULL;
4370         nvlist_t *config, *nvroot;
4371         char *p, *volname;
4372         nvlist_t **top;
4373         uint_t toplevels;
4374         libzfs_handle_t *hdl;
4375         char errbuf[1024];
4376         char poolname[ZFS_MAX_DATASET_NAME_LEN];
4377         int pathlen = strlen(ZVOL_FULL_DEV_DIR);
4378         int ret = 1;
4379 
4380         if (strncmp(arg, ZVOL_FULL_DEV_DIR, pathlen)) {
4381                 return (-1);
4382         }
4383 
4384         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4385             "dump is not supported on device '%s'"), arg);
4386 
4387         if ((hdl = libzfs_init()) == NULL)
4388                 return (1);
4389         libzfs_print_on_error(hdl, B_TRUE);
4390 
4391         volname = arg + pathlen;
4392 
4393         /* check the configuration of the pool */
4394         if ((p = strchr(volname, '/')) == NULL) {
4395                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4396                     "malformed dataset name"));
4397                 (void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
4398                 return (1);
4399         } else if (p - volname >= ZFS_MAX_DATASET_NAME_LEN) {
4400                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4401                     "dataset name is too long"));
4402                 (void) zfs_error(hdl, EZFS_NAMETOOLONG, errbuf);
4403                 return (1);
4404         } else {
4405                 (void) strncpy(poolname, volname, p - volname);
4406                 poolname[p - volname] = '\0';
4407         }
4408 
4409         if ((zhp = zpool_open(hdl, poolname)) == NULL) {
4410                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4411                     "could not open pool '%s'"), poolname);
4412                 (void) zfs_error(hdl, EZFS_OPENFAILED, errbuf);
4413                 goto out;
4414         }
4415         config = zpool_get_config(zhp, NULL);
4416         if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4417             &nvroot) != 0) {
4418                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4419                     "could not obtain vdev configuration for  '%s'"), poolname);
4420                 (void) zfs_error(hdl, EZFS_INVALCONFIG, errbuf);
4421                 goto out;
4422         }
4423 
4424         verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
4425             &top, &toplevels) == 0);
4426 
4427         if (!supported_dump_vdev_type(hdl, top[0], errbuf)) {
4428                 goto out;
4429         }
4430         ret = 0;
4431 
4432 out:
4433         if (zhp)
4434                 zpool_close(zhp);
4435         libzfs_fini(hdl);
4436         return (ret);
4437 }