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