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