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