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