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