]> CyberLeo.Net >> Repos - FreeBSD/releng/8.0.git/blob - cddl/contrib/opensolaris/lib/libzfs/common/libzfs_pool.c
Adjust to reflect 8.0-RELEASE.
[FreeBSD/releng/8.0.git] / cddl / contrib / opensolaris / lib / libzfs / common / libzfs_pool.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <assert.h>
30 #include <ctype.h>
31 #include <errno.h>
32 #include <devid.h>
33 #include <dirent.h>
34 #include <fcntl.h>
35 #include <libintl.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <strings.h>
39 #include <unistd.h>
40 #include <zone.h>
41 #include <sys/zfs_ioctl.h>
42 #include <sys/zio.h>
43 #include <strings.h>
44 #include <umem.h>
45
46 #include "zfs_namecheck.h"
47 #include "zfs_prop.h"
48 #include "libzfs_impl.h"
49
50 static int read_efi_label(nvlist_t *config, diskaddr_t *sb);
51
52 /*
53  * ====================================================================
54  *   zpool property functions
55  * ====================================================================
56  */
57
58 static int
59 zpool_get_all_props(zpool_handle_t *zhp)
60 {
61         zfs_cmd_t zc = { 0 };
62         libzfs_handle_t *hdl = zhp->zpool_hdl;
63
64         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
65
66         if (zcmd_alloc_dst_nvlist(hdl, &zc, 0) != 0)
67                 return (-1);
68
69         while (ioctl(hdl->libzfs_fd, ZFS_IOC_POOL_GET_PROPS, &zc) != 0) {
70                 if (errno == ENOMEM) {
71                         if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
72                                 zcmd_free_nvlists(&zc);
73                                 return (-1);
74                         }
75                 } else {
76                         zcmd_free_nvlists(&zc);
77                         return (-1);
78                 }
79         }
80
81         if (zcmd_read_dst_nvlist(hdl, &zc, &zhp->zpool_props) != 0) {
82                 zcmd_free_nvlists(&zc);
83                 return (-1);
84         }
85
86         zcmd_free_nvlists(&zc);
87
88         return (0);
89 }
90
91 static int
92 zpool_props_refresh(zpool_handle_t *zhp)
93 {
94         nvlist_t *old_props;
95
96         old_props = zhp->zpool_props;
97
98         if (zpool_get_all_props(zhp) != 0)
99                 return (-1);
100
101         nvlist_free(old_props);
102         return (0);
103 }
104
105 static char *
106 zpool_get_prop_string(zpool_handle_t *zhp, zpool_prop_t prop,
107     zprop_source_t *src)
108 {
109         nvlist_t *nv, *nvl;
110         uint64_t ival;
111         char *value;
112         zprop_source_t source;
113
114         nvl = zhp->zpool_props;
115         if (nvlist_lookup_nvlist(nvl, zpool_prop_to_name(prop), &nv) == 0) {
116                 verify(nvlist_lookup_uint64(nv, ZPROP_SOURCE, &ival) == 0);
117                 source = ival;
118                 verify(nvlist_lookup_string(nv, ZPROP_VALUE, &value) == 0);
119         } else {
120                 source = ZPROP_SRC_DEFAULT;
121                 if ((value = (char *)zpool_prop_default_string(prop)) == NULL)
122                         value = "-";
123         }
124
125         if (src)
126                 *src = source;
127
128         return (value);
129 }
130
131 uint64_t
132 zpool_get_prop_int(zpool_handle_t *zhp, zpool_prop_t prop, zprop_source_t *src)
133 {
134         nvlist_t *nv, *nvl;
135         uint64_t value;
136         zprop_source_t source;
137
138         if (zhp->zpool_props == NULL && zpool_get_all_props(zhp)) {
139                 /*
140                  * zpool_get_all_props() has most likely failed because
141                  * the pool is faulted, but if all we need is the top level
142                  * vdev's guid then get it from the zhp config nvlist.
143                  */
144                 if ((prop == ZPOOL_PROP_GUID) &&
145                     (nvlist_lookup_nvlist(zhp->zpool_config,
146                     ZPOOL_CONFIG_VDEV_TREE, &nv) == 0) &&
147                     (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &value)
148                     == 0)) {
149                         return (value);
150                 }
151                 return (zpool_prop_default_numeric(prop));
152         }
153
154         nvl = zhp->zpool_props;
155         if (nvlist_lookup_nvlist(nvl, zpool_prop_to_name(prop), &nv) == 0) {
156                 verify(nvlist_lookup_uint64(nv, ZPROP_SOURCE, &value) == 0);
157                 source = value;
158                 verify(nvlist_lookup_uint64(nv, ZPROP_VALUE, &value) == 0);
159         } else {
160                 source = ZPROP_SRC_DEFAULT;
161                 value = zpool_prop_default_numeric(prop);
162         }
163
164         if (src)
165                 *src = source;
166
167         return (value);
168 }
169
170 /*
171  * Map VDEV STATE to printed strings.
172  */
173 char *
174 zpool_state_to_name(vdev_state_t state, vdev_aux_t aux)
175 {
176         switch (state) {
177         case VDEV_STATE_CLOSED:
178         case VDEV_STATE_OFFLINE:
179                 return (gettext("OFFLINE"));
180         case VDEV_STATE_REMOVED:
181                 return (gettext("REMOVED"));
182         case VDEV_STATE_CANT_OPEN:
183                 if (aux == VDEV_AUX_CORRUPT_DATA || aux == VDEV_AUX_BAD_LOG)
184                         return (gettext("FAULTED"));
185                 else
186                         return (gettext("UNAVAIL"));
187         case VDEV_STATE_FAULTED:
188                 return (gettext("FAULTED"));
189         case VDEV_STATE_DEGRADED:
190                 return (gettext("DEGRADED"));
191         case VDEV_STATE_HEALTHY:
192                 return (gettext("ONLINE"));
193         }
194
195         return (gettext("UNKNOWN"));
196 }
197
198 /*
199  * Get a zpool property value for 'prop' and return the value in
200  * a pre-allocated buffer.
201  */
202 int
203 zpool_get_prop(zpool_handle_t *zhp, zpool_prop_t prop, char *buf, size_t len,
204     zprop_source_t *srctype)
205 {
206         uint64_t intval;
207         const char *strval;
208         zprop_source_t src = ZPROP_SRC_NONE;
209         nvlist_t *nvroot;
210         vdev_stat_t *vs;
211         uint_t vsc;
212
213         if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
214                 if (prop == ZPOOL_PROP_NAME)
215                         (void) strlcpy(buf, zpool_get_name(zhp), len);
216                 else if (prop == ZPOOL_PROP_HEALTH)
217                         (void) strlcpy(buf, "FAULTED", len);
218                 else
219                         (void) strlcpy(buf, "-", len);
220                 return (0);
221         }
222
223         if (zhp->zpool_props == NULL && zpool_get_all_props(zhp) &&
224             prop != ZPOOL_PROP_NAME)
225                 return (-1);
226
227         switch (zpool_prop_get_type(prop)) {
228         case PROP_TYPE_STRING:
229                 (void) strlcpy(buf, zpool_get_prop_string(zhp, prop, &src),
230                     len);
231                 break;
232
233         case PROP_TYPE_NUMBER:
234                 intval = zpool_get_prop_int(zhp, prop, &src);
235
236                 switch (prop) {
237                 case ZPOOL_PROP_SIZE:
238                 case ZPOOL_PROP_USED:
239                 case ZPOOL_PROP_AVAILABLE:
240                         (void) zfs_nicenum(intval, buf, len);
241                         break;
242
243                 case ZPOOL_PROP_CAPACITY:
244                         (void) snprintf(buf, len, "%llu%%",
245                             (u_longlong_t)intval);
246                         break;
247
248                 case ZPOOL_PROP_HEALTH:
249                         verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
250                             ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
251                         verify(nvlist_lookup_uint64_array(nvroot,
252                             ZPOOL_CONFIG_STATS, (uint64_t **)&vs, &vsc) == 0);
253
254                         (void) strlcpy(buf, zpool_state_to_name(intval,
255                             vs->vs_aux), len);
256                         break;
257                 default:
258                         (void) snprintf(buf, len, "%llu", intval);
259                 }
260                 break;
261
262         case PROP_TYPE_INDEX:
263                 intval = zpool_get_prop_int(zhp, prop, &src);
264                 if (zpool_prop_index_to_string(prop, intval, &strval)
265                     != 0)
266                         return (-1);
267                 (void) strlcpy(buf, strval, len);
268                 break;
269
270         default:
271                 abort();
272         }
273
274         if (srctype)
275                 *srctype = src;
276
277         return (0);
278 }
279
280 /*
281  * Check if the bootfs name has the same pool name as it is set to.
282  * Assuming bootfs is a valid dataset name.
283  */
284 static boolean_t
285 bootfs_name_valid(const char *pool, char *bootfs)
286 {
287         int len = strlen(pool);
288
289         if (!zfs_name_valid(bootfs, ZFS_TYPE_FILESYSTEM|ZFS_TYPE_SNAPSHOT))
290                 return (B_FALSE);
291
292         if (strncmp(pool, bootfs, len) == 0 &&
293             (bootfs[len] == '/' || bootfs[len] == '\0'))
294                 return (B_TRUE);
295
296         return (B_FALSE);
297 }
298
299 #if defined(sun)
300 /*
301  * Inspect the configuration to determine if any of the devices contain
302  * an EFI label.
303  */
304 static boolean_t
305 pool_uses_efi(nvlist_t *config)
306 {
307         nvlist_t **child;
308         uint_t c, children;
309
310         if (nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_CHILDREN,
311             &child, &children) != 0)
312                 return (read_efi_label(config, NULL) >= 0);
313
314         for (c = 0; c < children; c++) {
315                 if (pool_uses_efi(child[c]))
316                         return (B_TRUE);
317         }
318         return (B_FALSE);
319 }
320 #endif
321
322 /*
323  * Given an nvlist of zpool properties to be set, validate that they are
324  * correct, and parse any numeric properties (index, boolean, etc) if they are
325  * specified as strings.
326  */
327 static nvlist_t *
328 zpool_valid_proplist(libzfs_handle_t *hdl, const char *poolname,
329     nvlist_t *props, uint64_t version, boolean_t create_or_import, char *errbuf)
330 {
331         nvpair_t *elem;
332         nvlist_t *retprops;
333         zpool_prop_t prop;
334         char *strval;
335         uint64_t intval;
336         char *slash;
337         struct stat64 statbuf;
338         zpool_handle_t *zhp;
339         nvlist_t *nvroot;
340
341         if (nvlist_alloc(&retprops, NV_UNIQUE_NAME, 0) != 0) {
342                 (void) no_memory(hdl);
343                 return (NULL);
344         }
345
346         elem = NULL;
347         while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
348                 const char *propname = nvpair_name(elem);
349
350                 /*
351                  * Make sure this property is valid and applies to this type.
352                  */
353                 if ((prop = zpool_name_to_prop(propname)) == ZPROP_INVAL) {
354                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
355                             "invalid property '%s'"), propname);
356                         (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
357                         goto error;
358                 }
359
360                 if (zpool_prop_readonly(prop)) {
361                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' "
362                             "is readonly"), propname);
363                         (void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
364                         goto error;
365                 }
366
367                 if (zprop_parse_value(hdl, elem, prop, ZFS_TYPE_POOL, retprops,
368                     &strval, &intval, errbuf) != 0)
369                         goto error;
370
371                 /*
372                  * Perform additional checking for specific properties.
373                  */
374                 switch (prop) {
375                 case ZPOOL_PROP_VERSION:
376                         if (intval < version || intval > SPA_VERSION) {
377                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
378                                     "property '%s' number %d is invalid."),
379                                     propname, intval);
380                                 (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
381                                 goto error;
382                         }
383                         break;
384
385                 case ZPOOL_PROP_BOOTFS:
386                         if (create_or_import) {
387                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
388                                     "property '%s' cannot be set at creation "
389                                     "or import time"), propname);
390                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
391                                 goto error;
392                         }
393
394                         if (version < SPA_VERSION_BOOTFS) {
395                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
396                                     "pool must be upgraded to support "
397                                     "'%s' property"), propname);
398                                 (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
399                                 goto error;
400                         }
401
402                         /*
403                          * bootfs property value has to be a dataset name and
404                          * the dataset has to be in the same pool as it sets to.
405                          */
406                         if (strval[0] != '\0' && !bootfs_name_valid(poolname,
407                             strval)) {
408                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' "
409                                     "is an invalid name"), strval);
410                                 (void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
411                                 goto error;
412                         }
413
414                         if ((zhp = zpool_open_canfail(hdl, poolname)) == NULL) {
415                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
416                                     "could not open pool '%s'"), poolname);
417                                 (void) zfs_error(hdl, EZFS_OPENFAILED, errbuf);
418                                 goto error;
419                         }
420                         verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
421                             ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
422
423 #if defined(sun)
424                         /*
425                          * bootfs property cannot be set on a disk which has
426                          * been EFI labeled.
427                          */
428                         if (pool_uses_efi(nvroot)) {
429                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
430                                     "property '%s' not supported on "
431                                     "EFI labeled devices"), propname);
432                                 (void) zfs_error(hdl, EZFS_POOL_NOTSUP, errbuf);
433                                 zpool_close(zhp);
434                                 goto error;
435                         }
436 #endif
437                         zpool_close(zhp);
438                         break;
439
440                 case ZPOOL_PROP_ALTROOT:
441                         if (!create_or_import) {
442                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
443                                     "property '%s' can only be set during pool "
444                                     "creation or import"), propname);
445                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
446                                 goto error;
447                         }
448
449                         if (strval[0] != '/') {
450                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
451                                     "bad alternate root '%s'"), strval);
452                                 (void) zfs_error(hdl, EZFS_BADPATH, errbuf);
453                                 goto error;
454                         }
455                         break;
456
457                 case ZPOOL_PROP_CACHEFILE:
458                         if (strval[0] == '\0')
459                                 break;
460
461                         if (strcmp(strval, "none") == 0)
462                                 break;
463
464                         if (strval[0] != '/') {
465                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
466                                     "property '%s' must be empty, an "
467                                     "absolute path, or 'none'"), propname);
468                                 (void) zfs_error(hdl, EZFS_BADPATH, errbuf);
469                                 goto error;
470                         }
471
472                         slash = strrchr(strval, '/');
473
474                         if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
475                             strcmp(slash, "/..") == 0) {
476                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
477                                     "'%s' is not a valid file"), strval);
478                                 (void) zfs_error(hdl, EZFS_BADPATH, errbuf);
479                                 goto error;
480                         }
481
482                         *slash = '\0';
483
484                         if (strval[0] != '\0' &&
485                             (stat64(strval, &statbuf) != 0 ||
486                             !S_ISDIR(statbuf.st_mode))) {
487                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
488                                     "'%s' is not a valid directory"),
489                                     strval);
490                                 (void) zfs_error(hdl, EZFS_BADPATH, errbuf);
491                                 goto error;
492                         }
493
494                         *slash = '/';
495                         break;
496                 }
497         }
498
499         return (retprops);
500 error:
501         nvlist_free(retprops);
502         return (NULL);
503 }
504
505 /*
506  * Set zpool property : propname=propval.
507  */
508 int
509 zpool_set_prop(zpool_handle_t *zhp, const char *propname, const char *propval)
510 {
511         zfs_cmd_t zc = { 0 };
512         int ret = -1;
513         char errbuf[1024];
514         nvlist_t *nvl = NULL;
515         nvlist_t *realprops;
516         uint64_t version;
517
518         (void) snprintf(errbuf, sizeof (errbuf),
519             dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
520             zhp->zpool_name);
521
522         if (zhp->zpool_props == NULL && zpool_get_all_props(zhp))
523                 return (zfs_error(zhp->zpool_hdl, EZFS_POOLPROPS, errbuf));
524
525         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
526                 return (no_memory(zhp->zpool_hdl));
527
528         if (nvlist_add_string(nvl, propname, propval) != 0) {
529                 nvlist_free(nvl);
530                 return (no_memory(zhp->zpool_hdl));
531         }
532
533         version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
534         if ((realprops = zpool_valid_proplist(zhp->zpool_hdl,
535             zhp->zpool_name, nvl, version, B_FALSE, errbuf)) == NULL) {
536                 nvlist_free(nvl);
537                 return (-1);
538         }
539
540         nvlist_free(nvl);
541         nvl = realprops;
542
543         /*
544          * Execute the corresponding ioctl() to set this property.
545          */
546         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
547
548         if (zcmd_write_src_nvlist(zhp->zpool_hdl, &zc, nvl) != 0) {
549                 nvlist_free(nvl);
550                 return (-1);
551         }
552
553         ret = zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_SET_PROPS, &zc);
554
555         zcmd_free_nvlists(&zc);
556         nvlist_free(nvl);
557
558         if (ret)
559                 (void) zpool_standard_error(zhp->zpool_hdl, errno, errbuf);
560         else
561                 (void) zpool_props_refresh(zhp);
562
563         return (ret);
564 }
565
566 int
567 zpool_expand_proplist(zpool_handle_t *zhp, zprop_list_t **plp)
568 {
569         libzfs_handle_t *hdl = zhp->zpool_hdl;
570         zprop_list_t *entry;
571         char buf[ZFS_MAXPROPLEN];
572
573         if (zprop_expand_list(hdl, plp, ZFS_TYPE_POOL) != 0)
574                 return (-1);
575
576         for (entry = *plp; entry != NULL; entry = entry->pl_next) {
577
578                 if (entry->pl_fixed)
579                         continue;
580
581                 if (entry->pl_prop != ZPROP_INVAL &&
582                     zpool_get_prop(zhp, entry->pl_prop, buf, sizeof (buf),
583                     NULL) == 0) {
584                         if (strlen(buf) > entry->pl_width)
585                                 entry->pl_width = strlen(buf);
586                 }
587         }
588
589         return (0);
590 }
591
592
593 /*
594  * Validate the given pool name, optionally putting an extended error message in
595  * 'buf'.
596  */
597 boolean_t
598 zpool_name_valid(libzfs_handle_t *hdl, boolean_t isopen, const char *pool)
599 {
600         namecheck_err_t why;
601         char what;
602         int ret;
603
604         ret = pool_namecheck(pool, &why, &what);
605
606         /*
607          * The rules for reserved pool names were extended at a later point.
608          * But we need to support users with existing pools that may now be
609          * invalid.  So we only check for this expanded set of names during a
610          * create (or import), and only in userland.
611          */
612         if (ret == 0 && !isopen &&
613             (strncmp(pool, "mirror", 6) == 0 ||
614             strncmp(pool, "raidz", 5) == 0 ||
615             strncmp(pool, "spare", 5) == 0 ||
616             strcmp(pool, "log") == 0)) {
617                 if (hdl != NULL)
618                         zfs_error_aux(hdl,
619                             dgettext(TEXT_DOMAIN, "name is reserved"));
620                 return (B_FALSE);
621         }
622
623
624         if (ret != 0) {
625                 if (hdl != NULL) {
626                         switch (why) {
627                         case NAME_ERR_TOOLONG:
628                                 zfs_error_aux(hdl,
629                                     dgettext(TEXT_DOMAIN, "name is too long"));
630                                 break;
631
632                         case NAME_ERR_INVALCHAR:
633                                 zfs_error_aux(hdl,
634                                     dgettext(TEXT_DOMAIN, "invalid character "
635                                     "'%c' in pool name"), what);
636                                 break;
637
638                         case NAME_ERR_NOLETTER:
639                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
640                                     "name must begin with a letter"));
641                                 break;
642
643                         case NAME_ERR_RESERVED:
644                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
645                                     "name is reserved"));
646                                 break;
647
648                         case NAME_ERR_DISKLIKE:
649                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
650                                     "pool name is reserved"));
651                                 break;
652
653                         case NAME_ERR_LEADING_SLASH:
654                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
655                                     "leading slash in name"));
656                                 break;
657
658                         case NAME_ERR_EMPTY_COMPONENT:
659                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
660                                     "empty component in name"));
661                                 break;
662
663                         case NAME_ERR_TRAILING_SLASH:
664                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
665                                     "trailing slash in name"));
666                                 break;
667
668                         case NAME_ERR_MULTIPLE_AT:
669                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
670                                     "multiple '@' delimiters in name"));
671                                 break;
672
673                         }
674                 }
675                 return (B_FALSE);
676         }
677
678         return (B_TRUE);
679 }
680
681 /*
682  * Open a handle to the given pool, even if the pool is currently in the FAULTED
683  * state.
684  */
685 zpool_handle_t *
686 zpool_open_canfail(libzfs_handle_t *hdl, const char *pool)
687 {
688         zpool_handle_t *zhp;
689         boolean_t missing;
690
691         /*
692          * Make sure the pool name is valid.
693          */
694         if (!zpool_name_valid(hdl, B_TRUE, pool)) {
695                 (void) zfs_error_fmt(hdl, EZFS_INVALIDNAME,
696                     dgettext(TEXT_DOMAIN, "cannot open '%s'"),
697                     pool);
698                 return (NULL);
699         }
700
701         if ((zhp = zfs_alloc(hdl, sizeof (zpool_handle_t))) == NULL)
702                 return (NULL);
703
704         zhp->zpool_hdl = hdl;
705         (void) strlcpy(zhp->zpool_name, pool, sizeof (zhp->zpool_name));
706
707         if (zpool_refresh_stats(zhp, &missing) != 0) {
708                 zpool_close(zhp);
709                 return (NULL);
710         }
711
712         if (missing) {
713                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "no such pool"));
714                 (void) zfs_error_fmt(hdl, EZFS_NOENT,
715                     dgettext(TEXT_DOMAIN, "cannot open '%s'"), pool);
716                 zpool_close(zhp);
717                 return (NULL);
718         }
719
720         return (zhp);
721 }
722
723 /*
724  * Like the above, but silent on error.  Used when iterating over pools (because
725  * the configuration cache may be out of date).
726  */
727 int
728 zpool_open_silent(libzfs_handle_t *hdl, const char *pool, zpool_handle_t **ret)
729 {
730         zpool_handle_t *zhp;
731         boolean_t missing;
732
733         if ((zhp = zfs_alloc(hdl, sizeof (zpool_handle_t))) == NULL)
734                 return (-1);
735
736         zhp->zpool_hdl = hdl;
737         (void) strlcpy(zhp->zpool_name, pool, sizeof (zhp->zpool_name));
738
739         if (zpool_refresh_stats(zhp, &missing) != 0) {
740                 zpool_close(zhp);
741                 return (-1);
742         }
743
744         if (missing) {
745                 zpool_close(zhp);
746                 *ret = NULL;
747                 return (0);
748         }
749
750         *ret = zhp;
751         return (0);
752 }
753
754 /*
755  * Similar to zpool_open_canfail(), but refuses to open pools in the faulted
756  * state.
757  */
758 zpool_handle_t *
759 zpool_open(libzfs_handle_t *hdl, const char *pool)
760 {
761         zpool_handle_t *zhp;
762
763         if ((zhp = zpool_open_canfail(hdl, pool)) == NULL)
764                 return (NULL);
765
766         if (zhp->zpool_state == POOL_STATE_UNAVAIL) {
767                 (void) zfs_error_fmt(hdl, EZFS_POOLUNAVAIL,
768                     dgettext(TEXT_DOMAIN, "cannot open '%s'"), zhp->zpool_name);
769                 zpool_close(zhp);
770                 return (NULL);
771         }
772
773         return (zhp);
774 }
775
776 /*
777  * Close the handle.  Simply frees the memory associated with the handle.
778  */
779 void
780 zpool_close(zpool_handle_t *zhp)
781 {
782         if (zhp->zpool_config)
783                 nvlist_free(zhp->zpool_config);
784         if (zhp->zpool_old_config)
785                 nvlist_free(zhp->zpool_old_config);
786         if (zhp->zpool_props)
787                 nvlist_free(zhp->zpool_props);
788         free(zhp);
789 }
790
791 /*
792  * Return the name of the pool.
793  */
794 const char *
795 zpool_get_name(zpool_handle_t *zhp)
796 {
797         return (zhp->zpool_name);
798 }
799
800
801 /*
802  * Return the state of the pool (ACTIVE or UNAVAILABLE)
803  */
804 int
805 zpool_get_state(zpool_handle_t *zhp)
806 {
807         return (zhp->zpool_state);
808 }
809
810 /*
811  * Create the named pool, using the provided vdev list.  It is assumed
812  * that the consumer has already validated the contents of the nvlist, so we
813  * don't have to worry about error semantics.
814  */
815 int
816 zpool_create(libzfs_handle_t *hdl, const char *pool, nvlist_t *nvroot,
817     nvlist_t *props, nvlist_t *fsprops)
818 {
819         zfs_cmd_t zc = { 0 };
820         nvlist_t *zc_fsprops = NULL;
821         nvlist_t *zc_props = NULL;
822         char msg[1024];
823         char *altroot;
824         int ret = -1;
825
826         (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
827             "cannot create '%s'"), pool);
828
829         if (!zpool_name_valid(hdl, B_FALSE, pool))
830                 return (zfs_error(hdl, EZFS_INVALIDNAME, msg));
831
832         if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
833                 return (-1);
834
835         if (props) {
836                 if ((zc_props = zpool_valid_proplist(hdl, pool, props,
837                     SPA_VERSION_1, B_TRUE, msg)) == NULL) {
838                         goto create_failed;
839                 }
840         }
841
842         if (fsprops) {
843                 uint64_t zoned;
844                 char *zonestr;
845
846                 zoned = ((nvlist_lookup_string(fsprops,
847                     zfs_prop_to_name(ZFS_PROP_ZONED), &zonestr) == 0) &&
848                     strcmp(zonestr, "on") == 0);
849
850                 if ((zc_fsprops = zfs_valid_proplist(hdl,
851                     ZFS_TYPE_FILESYSTEM, fsprops, zoned, NULL, msg)) == NULL) {
852                         goto create_failed;
853                 }
854                 if (!zc_props &&
855                     (nvlist_alloc(&zc_props, NV_UNIQUE_NAME, 0) != 0)) {
856                         goto create_failed;
857                 }
858                 if (nvlist_add_nvlist(zc_props,
859                     ZPOOL_ROOTFS_PROPS, zc_fsprops) != 0) {
860                         goto create_failed;
861                 }
862         }
863
864         if (zc_props && zcmd_write_src_nvlist(hdl, &zc, zc_props) != 0)
865                 goto create_failed;
866
867         (void) strlcpy(zc.zc_name, pool, sizeof (zc.zc_name));
868
869         if ((ret = zfs_ioctl(hdl, ZFS_IOC_POOL_CREATE, &zc)) != 0) {
870
871                 zcmd_free_nvlists(&zc);
872                 nvlist_free(zc_props);
873                 nvlist_free(zc_fsprops);
874
875                 switch (errno) {
876                 case EBUSY:
877                         /*
878                          * This can happen if the user has specified the same
879                          * device multiple times.  We can't reliably detect this
880                          * until we try to add it and see we already have a
881                          * label.
882                          */
883                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
884                             "one or more vdevs refer to the same device"));
885                         return (zfs_error(hdl, EZFS_BADDEV, msg));
886
887                 case EOVERFLOW:
888                         /*
889                          * This occurs when one of the devices is below
890                          * SPA_MINDEVSIZE.  Unfortunately, we can't detect which
891                          * device was the problem device since there's no
892                          * reliable way to determine device size from userland.
893                          */
894                         {
895                                 char buf[64];
896
897                                 zfs_nicenum(SPA_MINDEVSIZE, buf, sizeof (buf));
898
899                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
900                                     "one or more devices is less than the "
901                                     "minimum size (%s)"), buf);
902                         }
903                         return (zfs_error(hdl, EZFS_BADDEV, msg));
904
905                 case ENOSPC:
906                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
907                             "one or more devices is out of space"));
908                         return (zfs_error(hdl, EZFS_BADDEV, msg));
909
910                 case ENOTBLK:
911                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
912                             "cache device must be a disk or disk slice"));
913                         return (zfs_error(hdl, EZFS_BADDEV, msg));
914
915                 default:
916                         return (zpool_standard_error(hdl, errno, msg));
917                 }
918         }
919
920         /*
921          * If this is an alternate root pool, then we automatically set the
922          * mountpoint of the root dataset to be '/'.
923          */
924         if (nvlist_lookup_string(props, zpool_prop_to_name(ZPOOL_PROP_ALTROOT),
925             &altroot) == 0) {
926                 zfs_handle_t *zhp;
927
928                 verify((zhp = zfs_open(hdl, pool, ZFS_TYPE_DATASET)) != NULL);
929                 verify(zfs_prop_set(zhp, zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
930                     "/") == 0);
931
932                 zfs_close(zhp);
933         }
934
935 create_failed:
936         zcmd_free_nvlists(&zc);
937         nvlist_free(zc_props);
938         nvlist_free(zc_fsprops);
939         return (ret);
940 }
941
942 /*
943  * Destroy the given pool.  It is up to the caller to ensure that there are no
944  * datasets left in the pool.
945  */
946 int
947 zpool_destroy(zpool_handle_t *zhp)
948 {
949         zfs_cmd_t zc = { 0 };
950         zfs_handle_t *zfp = NULL;
951         libzfs_handle_t *hdl = zhp->zpool_hdl;
952         char msg[1024];
953
954         if (zhp->zpool_state == POOL_STATE_ACTIVE &&
955             (zfp = zfs_open(zhp->zpool_hdl, zhp->zpool_name,
956             ZFS_TYPE_FILESYSTEM)) == NULL)
957                 return (-1);
958
959         if (zpool_remove_zvol_links(zhp) != 0)
960                 return (-1);
961
962         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
963
964         if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_DESTROY, &zc) != 0) {
965                 (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
966                     "cannot destroy '%s'"), zhp->zpool_name);
967
968                 if (errno == EROFS) {
969                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
970                             "one or more devices is read only"));
971                         (void) zfs_error(hdl, EZFS_BADDEV, msg);
972                 } else {
973                         (void) zpool_standard_error(hdl, errno, msg);
974                 }
975
976                 if (zfp)
977                         zfs_close(zfp);
978                 return (-1);
979         }
980
981         if (zfp) {
982                 remove_mountpoint(zfp);
983                 zfs_close(zfp);
984         }
985
986         return (0);
987 }
988
989 /*
990  * Add the given vdevs to the pool.  The caller must have already performed the
991  * necessary verification to ensure that the vdev specification is well-formed.
992  */
993 int
994 zpool_add(zpool_handle_t *zhp, nvlist_t *nvroot)
995 {
996         zfs_cmd_t zc = { 0 };
997         int ret;
998         libzfs_handle_t *hdl = zhp->zpool_hdl;
999         char msg[1024];
1000         nvlist_t **spares, **l2cache;
1001         uint_t nspares, nl2cache;
1002
1003         (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1004             "cannot add to '%s'"), zhp->zpool_name);
1005
1006         if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) <
1007             SPA_VERSION_SPARES &&
1008             nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1009             &spares, &nspares) == 0) {
1010                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be "
1011                     "upgraded to add hot spares"));
1012                 return (zfs_error(hdl, EZFS_BADVERSION, msg));
1013         }
1014
1015         if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) <
1016             SPA_VERSION_L2CACHE &&
1017             nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1018             &l2cache, &nl2cache) == 0) {
1019                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be "
1020                     "upgraded to add cache devices"));
1021                 return (zfs_error(hdl, EZFS_BADVERSION, msg));
1022         }
1023
1024         if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
1025                 return (-1);
1026         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1027
1028         if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_VDEV_ADD, &zc) != 0) {
1029                 switch (errno) {
1030                 case EBUSY:
1031                         /*
1032                          * This can happen if the user has specified the same
1033                          * device multiple times.  We can't reliably detect this
1034                          * until we try to add it and see we already have a
1035                          * label.
1036                          */
1037                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1038                             "one or more vdevs refer to the same device"));
1039                         (void) zfs_error(hdl, EZFS_BADDEV, msg);
1040                         break;
1041
1042                 case EOVERFLOW:
1043                         /*
1044                          * This occurrs when one of the devices is below
1045                          * SPA_MINDEVSIZE.  Unfortunately, we can't detect which
1046                          * device was the problem device since there's no
1047                          * reliable way to determine device size from userland.
1048                          */
1049                         {
1050                                 char buf[64];
1051
1052                                 zfs_nicenum(SPA_MINDEVSIZE, buf, sizeof (buf));
1053
1054                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1055                                     "device is less than the minimum "
1056                                     "size (%s)"), buf);
1057                         }
1058                         (void) zfs_error(hdl, EZFS_BADDEV, msg);
1059                         break;
1060
1061                 case ENOTSUP:
1062                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1063                             "pool must be upgraded to add these vdevs"));
1064                         (void) zfs_error(hdl, EZFS_BADVERSION, msg);
1065                         break;
1066
1067                 case EDOM:
1068                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1069                             "root pool can not have multiple vdevs"
1070                             " or separate logs"));
1071                         (void) zfs_error(hdl, EZFS_POOL_NOTSUP, msg);
1072                         break;
1073
1074                 case ENOTBLK:
1075                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1076                             "cache device must be a disk or disk slice"));
1077                         (void) zfs_error(hdl, EZFS_BADDEV, msg);
1078                         break;
1079
1080                 default:
1081                         (void) zpool_standard_error(hdl, errno, msg);
1082                 }
1083
1084                 ret = -1;
1085         } else {
1086                 ret = 0;
1087         }
1088
1089         zcmd_free_nvlists(&zc);
1090
1091         return (ret);
1092 }
1093
1094 /*
1095  * Exports the pool from the system.  The caller must ensure that there are no
1096  * mounted datasets in the pool.
1097  */
1098 int
1099 zpool_export(zpool_handle_t *zhp, boolean_t force)
1100 {
1101         zfs_cmd_t zc = { 0 };
1102         char msg[1024];
1103
1104         if (zpool_remove_zvol_links(zhp) != 0)
1105                 return (-1);
1106
1107         (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1108             "cannot export '%s'"), zhp->zpool_name);
1109
1110         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1111         zc.zc_cookie = force;
1112
1113         if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_EXPORT, &zc) != 0) {
1114                 switch (errno) {
1115                 case EXDEV:
1116                         zfs_error_aux(zhp->zpool_hdl, dgettext(TEXT_DOMAIN,
1117                             "use '-f' to override the following errors:\n"
1118                             "'%s' has an active shared spare which could be"
1119                             " used by other pools once '%s' is exported."),
1120                             zhp->zpool_name, zhp->zpool_name);
1121                         return (zfs_error(zhp->zpool_hdl, EZFS_ACTIVE_SPARE,
1122                             msg));
1123                 default:
1124                         return (zpool_standard_error_fmt(zhp->zpool_hdl, errno,
1125                             msg));
1126                 }
1127         }
1128
1129         return (0);
1130 }
1131
1132 /*
1133  * zpool_import() is a contracted interface. Should be kept the same
1134  * if possible.
1135  *
1136  * Applications should use zpool_import_props() to import a pool with
1137  * new properties value to be set.
1138  */
1139 int
1140 zpool_import(libzfs_handle_t *hdl, nvlist_t *config, const char *newname,
1141     char *altroot)
1142 {
1143         nvlist_t *props = NULL;
1144         int ret;
1145
1146         if (altroot != NULL) {
1147                 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
1148                         return (zfs_error_fmt(hdl, EZFS_NOMEM,
1149                             dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1150                             newname));
1151                 }
1152
1153                 if (nvlist_add_string(props,
1154                     zpool_prop_to_name(ZPOOL_PROP_ALTROOT), altroot) != 0) {
1155                         nvlist_free(props);
1156                         return (zfs_error_fmt(hdl, EZFS_NOMEM,
1157                             dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1158                             newname));
1159                 }
1160         }
1161
1162         ret = zpool_import_props(hdl, config, newname, props, B_FALSE);
1163         if (props)
1164                 nvlist_free(props);
1165         return (ret);
1166 }
1167
1168 /*
1169  * Import the given pool using the known configuration and a list of
1170  * properties to be set. The configuration should have come from
1171  * zpool_find_import(). The 'newname' parameters control whether the pool
1172  * is imported with a different name.
1173  */
1174 int
1175 zpool_import_props(libzfs_handle_t *hdl, nvlist_t *config, const char *newname,
1176     nvlist_t *props, boolean_t importfaulted)
1177 {
1178         zfs_cmd_t zc = { 0 };
1179         char *thename;
1180         char *origname;
1181         int ret;
1182         char errbuf[1024];
1183
1184         verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1185             &origname) == 0);
1186
1187         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1188             "cannot import pool '%s'"), origname);
1189
1190         if (newname != NULL) {
1191                 if (!zpool_name_valid(hdl, B_FALSE, newname))
1192                         return (zfs_error_fmt(hdl, EZFS_INVALIDNAME,
1193                             dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1194                             newname));
1195                 thename = (char *)newname;
1196         } else {
1197                 thename = origname;
1198         }
1199
1200         if (props) {
1201                 uint64_t version;
1202
1203                 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
1204                     &version) == 0);
1205
1206                 if ((props = zpool_valid_proplist(hdl, origname,
1207                     props, version, B_TRUE, errbuf)) == NULL) {
1208                         return (-1);
1209                 } else if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
1210                         nvlist_free(props);
1211                         return (-1);
1212                 }
1213         }
1214
1215         (void) strlcpy(zc.zc_name, thename, sizeof (zc.zc_name));
1216
1217         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1218             &zc.zc_guid) == 0);
1219
1220         if (zcmd_write_conf_nvlist(hdl, &zc, config) != 0) {
1221                 nvlist_free(props);
1222                 return (-1);
1223         }
1224
1225         zc.zc_cookie = (uint64_t)importfaulted;
1226         ret = 0;
1227         if (zfs_ioctl(hdl, ZFS_IOC_POOL_IMPORT, &zc) != 0) {
1228                 char desc[1024];
1229                 if (newname == NULL)
1230                         (void) snprintf(desc, sizeof (desc),
1231                             dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1232                             thename);
1233                 else
1234                         (void) snprintf(desc, sizeof (desc),
1235                             dgettext(TEXT_DOMAIN, "cannot import '%s' as '%s'"),
1236                             origname, thename);
1237
1238                 switch (errno) {
1239                 case ENOTSUP:
1240                         /*
1241                          * Unsupported version.
1242                          */
1243                         (void) zfs_error(hdl, EZFS_BADVERSION, desc);
1244                         break;
1245
1246                 case EINVAL:
1247                         (void) zfs_error(hdl, EZFS_INVALCONFIG, desc);
1248                         break;
1249
1250                 default:
1251                         (void) zpool_standard_error(hdl, errno, desc);
1252                 }
1253
1254                 ret = -1;
1255         } else {
1256                 zpool_handle_t *zhp;
1257
1258                 /*
1259                  * This should never fail, but play it safe anyway.
1260                  */
1261                 if (zpool_open_silent(hdl, thename, &zhp) != 0) {
1262                         ret = -1;
1263                 } else if (zhp != NULL) {
1264                         ret = zpool_create_zvol_links(zhp);
1265                         zpool_close(zhp);
1266                 }
1267
1268         }
1269
1270         zcmd_free_nvlists(&zc);
1271         nvlist_free(props);
1272
1273         return (ret);
1274 }
1275
1276 /*
1277  * Scrub the pool.
1278  */
1279 int
1280 zpool_scrub(zpool_handle_t *zhp, pool_scrub_type_t type)
1281 {
1282         zfs_cmd_t zc = { 0 };
1283         char msg[1024];
1284         libzfs_handle_t *hdl = zhp->zpool_hdl;
1285
1286         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1287         zc.zc_cookie = type;
1288
1289         if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_SCRUB, &zc) == 0)
1290                 return (0);
1291
1292         (void) snprintf(msg, sizeof (msg),
1293             dgettext(TEXT_DOMAIN, "cannot scrub %s"), zc.zc_name);
1294
1295         if (errno == EBUSY)
1296                 return (zfs_error(hdl, EZFS_RESILVERING, msg));
1297         else
1298                 return (zpool_standard_error(hdl, errno, msg));
1299 }
1300
1301 /*
1302  * 'avail_spare' is set to TRUE if the provided guid refers to an AVAIL
1303  * spare; but FALSE if its an INUSE spare.
1304  */
1305 static nvlist_t *
1306 vdev_to_nvlist_iter(nvlist_t *nv, const char *search, uint64_t guid,
1307     boolean_t *avail_spare, boolean_t *l2cache, boolean_t *log)
1308 {
1309         uint_t c, children;
1310         nvlist_t **child;
1311         uint64_t theguid, present;
1312         char *path;
1313         uint64_t wholedisk = 0;
1314         nvlist_t *ret;
1315         uint64_t is_log;
1316
1317         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &theguid) == 0);
1318
1319         if (search == NULL &&
1320             nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, &present) == 0) {
1321                 /*
1322                  * If the device has never been present since import, the only
1323                  * reliable way to match the vdev is by GUID.
1324                  */
1325                 if (theguid == guid)
1326                         return (nv);
1327         } else if (search != NULL &&
1328             nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
1329                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
1330                     &wholedisk);
1331                 if (wholedisk) {
1332                         /*
1333                          * For whole disks, the internal path has 's0', but the
1334                          * path passed in by the user doesn't.
1335                          */
1336                         if (strlen(search) == strlen(path) - 2 &&
1337                             strncmp(search, path, strlen(search)) == 0)
1338                                 return (nv);
1339                 } else if (strcmp(search, path) == 0) {
1340                         return (nv);
1341                 }
1342         }
1343
1344         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1345             &child, &children) != 0)
1346                 return (NULL);
1347
1348         for (c = 0; c < children; c++) {
1349                 if ((ret = vdev_to_nvlist_iter(child[c], search, guid,
1350                     avail_spare, l2cache, NULL)) != NULL) {
1351                         /*
1352                          * The 'is_log' value is only set for the toplevel
1353                          * vdev, not the leaf vdevs.  So we always lookup the
1354                          * log device from the root of the vdev tree (where
1355                          * 'log' is non-NULL).
1356                          */
1357                         if (log != NULL &&
1358                             nvlist_lookup_uint64(child[c],
1359                             ZPOOL_CONFIG_IS_LOG, &is_log) == 0 &&
1360                             is_log) {
1361                                 *log = B_TRUE;
1362                         }
1363                         return (ret);
1364                 }
1365         }
1366
1367         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1368             &child, &children) == 0) {
1369                 for (c = 0; c < children; c++) {
1370                         if ((ret = vdev_to_nvlist_iter(child[c], search, guid,
1371                             avail_spare, l2cache, NULL)) != NULL) {
1372                                 *avail_spare = B_TRUE;
1373                                 return (ret);
1374                         }
1375                 }
1376         }
1377
1378         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1379             &child, &children) == 0) {
1380                 for (c = 0; c < children; c++) {
1381                         if ((ret = vdev_to_nvlist_iter(child[c], search, guid,
1382                             avail_spare, l2cache, NULL)) != NULL) {
1383                                 *l2cache = B_TRUE;
1384                                 return (ret);
1385                         }
1386                 }
1387         }
1388
1389         return (NULL);
1390 }
1391
1392 nvlist_t *
1393 zpool_find_vdev(zpool_handle_t *zhp, const char *path, boolean_t *avail_spare,
1394     boolean_t *l2cache, boolean_t *log)
1395 {
1396         char buf[MAXPATHLEN];
1397         const char *search;
1398         char *end;
1399         nvlist_t *nvroot;
1400         uint64_t guid;
1401
1402         guid = strtoull(path, &end, 10);
1403         if (guid != 0 && *end == '\0') {
1404                 search = NULL;
1405         } else if (path[0] != '/') {
1406                 (void) snprintf(buf, sizeof (buf), "%s%s", _PATH_DEV, path);
1407                 search = buf;
1408         } else {
1409                 search = path;
1410         }
1411
1412         verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
1413             &nvroot) == 0);
1414
1415         *avail_spare = B_FALSE;
1416         *l2cache = B_FALSE;
1417         if (log != NULL)
1418                 *log = B_FALSE;
1419         return (vdev_to_nvlist_iter(nvroot, search, guid, avail_spare,
1420             l2cache, log));
1421 }
1422
1423 static int
1424 vdev_online(nvlist_t *nv)
1425 {
1426         uint64_t ival;
1427
1428         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE, &ival) == 0 ||
1429             nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED, &ival) == 0 ||
1430             nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED, &ival) == 0)
1431                 return (0);
1432
1433         return (1);
1434 }
1435
1436 /*
1437  * Get phys_path for a root pool
1438  * Return 0 on success; non-zeron on failure.
1439  */
1440 int
1441 zpool_get_physpath(zpool_handle_t *zhp, char *physpath)
1442 {
1443         char bootfs[ZPOOL_MAXNAMELEN];
1444         nvlist_t *vdev_root;
1445         nvlist_t **child;
1446         uint_t count;
1447         int i;
1448
1449         /*
1450          * Make sure this is a root pool, as phys_path doesn't mean
1451          * anything to a non-root pool.
1452          */
1453         if (zpool_get_prop(zhp, ZPOOL_PROP_BOOTFS, bootfs,
1454             sizeof (bootfs), NULL) != 0)
1455                 return (-1);
1456
1457         verify(nvlist_lookup_nvlist(zhp->zpool_config,
1458             ZPOOL_CONFIG_VDEV_TREE, &vdev_root) == 0);
1459
1460         if (nvlist_lookup_nvlist_array(vdev_root, ZPOOL_CONFIG_CHILDREN,
1461             &child, &count) != 0)
1462                 return (-2);
1463
1464         for (i = 0; i < count; i++) {
1465                 nvlist_t **child2;
1466                 uint_t count2;
1467                 char *type;
1468                 char *tmppath;
1469                 int j;
1470
1471                 if (nvlist_lookup_string(child[i], ZPOOL_CONFIG_TYPE, &type)
1472                     != 0)
1473                         return (-3);
1474
1475                 if (strcmp(type, VDEV_TYPE_DISK) == 0) {
1476                         if (!vdev_online(child[i]))
1477                                 return (-8);
1478                         verify(nvlist_lookup_string(child[i],
1479                             ZPOOL_CONFIG_PHYS_PATH, &tmppath) == 0);
1480                         (void) strncpy(physpath, tmppath, strlen(tmppath));
1481                 } else if (strcmp(type, VDEV_TYPE_MIRROR) == 0) {
1482                         if (nvlist_lookup_nvlist_array(child[i],
1483                             ZPOOL_CONFIG_CHILDREN, &child2, &count2) != 0)
1484                                 return (-4);
1485
1486                         for (j = 0; j < count2; j++) {
1487                                 if (!vdev_online(child2[j]))
1488                                         return (-8);
1489                                 if (nvlist_lookup_string(child2[j],
1490                                     ZPOOL_CONFIG_PHYS_PATH, &tmppath) != 0)
1491                                         return (-5);
1492
1493                                 if ((strlen(physpath) + strlen(tmppath)) >
1494                                     MAXNAMELEN)
1495                                         return (-6);
1496
1497                                 if (strlen(physpath) == 0) {
1498                                         (void) strncpy(physpath, tmppath,
1499                                             strlen(tmppath));
1500                                 } else {
1501                                         (void) strcat(physpath, " ");
1502                                         (void) strcat(physpath, tmppath);
1503                                 }
1504                         }
1505                 } else {
1506                         return (-7);
1507                 }
1508         }
1509
1510         return (0);
1511 }
1512
1513 /*
1514  * Returns TRUE if the given guid corresponds to the given type.
1515  * This is used to check for hot spares (INUSE or not), and level 2 cache
1516  * devices.
1517  */
1518 static boolean_t
1519 is_guid_type(zpool_handle_t *zhp, uint64_t guid, const char *type)
1520 {
1521         uint64_t target_guid;
1522         nvlist_t *nvroot;
1523         nvlist_t **list;
1524         uint_t count;
1525         int i;
1526
1527         verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
1528             &nvroot) == 0);
1529         if (nvlist_lookup_nvlist_array(nvroot, type, &list, &count) == 0) {
1530                 for (i = 0; i < count; i++) {
1531                         verify(nvlist_lookup_uint64(list[i], ZPOOL_CONFIG_GUID,
1532                             &target_guid) == 0);
1533                         if (guid == target_guid)
1534                                 return (B_TRUE);
1535                 }
1536         }
1537
1538         return (B_FALSE);
1539 }
1540
1541 /*
1542  * Bring the specified vdev online.   The 'flags' parameter is a set of the
1543  * ZFS_ONLINE_* flags.
1544  */
1545 int
1546 zpool_vdev_online(zpool_handle_t *zhp, const char *path, int flags,
1547     vdev_state_t *newstate)
1548 {
1549         zfs_cmd_t zc = { 0 };
1550         char msg[1024];
1551         nvlist_t *tgt;
1552         boolean_t avail_spare, l2cache;
1553         libzfs_handle_t *hdl = zhp->zpool_hdl;
1554
1555         (void) snprintf(msg, sizeof (msg),
1556             dgettext(TEXT_DOMAIN, "cannot online %s"), path);
1557
1558         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1559         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
1560             NULL)) == NULL)
1561                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
1562
1563         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
1564
1565         if (avail_spare ||
1566             is_guid_type(zhp, zc.zc_guid, ZPOOL_CONFIG_SPARES) == B_TRUE)
1567                 return (zfs_error(hdl, EZFS_ISSPARE, msg));
1568
1569         zc.zc_cookie = VDEV_STATE_ONLINE;
1570         zc.zc_obj = flags;
1571
1572         if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_VDEV_SET_STATE, &zc) != 0)
1573                 return (zpool_standard_error(hdl, errno, msg));
1574
1575         *newstate = zc.zc_cookie;
1576         return (0);
1577 }
1578
1579 /*
1580  * Take the specified vdev offline
1581  */
1582 int
1583 zpool_vdev_offline(zpool_handle_t *zhp, const char *path, boolean_t istmp)
1584 {
1585         zfs_cmd_t zc = { 0 };
1586         char msg[1024];
1587         nvlist_t *tgt;
1588         boolean_t avail_spare, l2cache;
1589         libzfs_handle_t *hdl = zhp->zpool_hdl;
1590
1591         (void) snprintf(msg, sizeof (msg),
1592             dgettext(TEXT_DOMAIN, "cannot offline %s"), path);
1593
1594         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1595         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
1596             NULL)) == NULL)
1597                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
1598
1599         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
1600
1601         if (avail_spare ||
1602             is_guid_type(zhp, zc.zc_guid, ZPOOL_CONFIG_SPARES) == B_TRUE)
1603                 return (zfs_error(hdl, EZFS_ISSPARE, msg));
1604
1605         zc.zc_cookie = VDEV_STATE_OFFLINE;
1606         zc.zc_obj = istmp ? ZFS_OFFLINE_TEMPORARY : 0;
1607
1608         if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
1609                 return (0);
1610
1611         switch (errno) {
1612         case EBUSY:
1613
1614                 /*
1615                  * There are no other replicas of this device.
1616                  */
1617                 return (zfs_error(hdl, EZFS_NOREPLICAS, msg));
1618
1619         default:
1620                 return (zpool_standard_error(hdl, errno, msg));
1621         }
1622 }
1623
1624 /*
1625  * Mark the given vdev faulted.
1626  */
1627 int
1628 zpool_vdev_fault(zpool_handle_t *zhp, uint64_t guid)
1629 {
1630         zfs_cmd_t zc = { 0 };
1631         char msg[1024];
1632         libzfs_handle_t *hdl = zhp->zpool_hdl;
1633
1634         (void) snprintf(msg, sizeof (msg),
1635             dgettext(TEXT_DOMAIN, "cannot fault %llu"), guid);
1636
1637         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1638         zc.zc_guid = guid;
1639         zc.zc_cookie = VDEV_STATE_FAULTED;
1640
1641         if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
1642                 return (0);
1643
1644         switch (errno) {
1645         case EBUSY:
1646
1647                 /*
1648                  * There are no other replicas of this device.
1649                  */
1650                 return (zfs_error(hdl, EZFS_NOREPLICAS, msg));
1651
1652         default:
1653                 return (zpool_standard_error(hdl, errno, msg));
1654         }
1655
1656 }
1657
1658 /*
1659  * Mark the given vdev degraded.
1660  */
1661 int
1662 zpool_vdev_degrade(zpool_handle_t *zhp, uint64_t guid)
1663 {
1664         zfs_cmd_t zc = { 0 };
1665         char msg[1024];
1666         libzfs_handle_t *hdl = zhp->zpool_hdl;
1667
1668         (void) snprintf(msg, sizeof (msg),
1669             dgettext(TEXT_DOMAIN, "cannot degrade %llu"), guid);
1670
1671         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1672         zc.zc_guid = guid;
1673         zc.zc_cookie = VDEV_STATE_DEGRADED;
1674
1675         if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
1676                 return (0);
1677
1678         return (zpool_standard_error(hdl, errno, msg));
1679 }
1680
1681 /*
1682  * Returns TRUE if the given nvlist is a vdev that was originally swapped in as
1683  * a hot spare.
1684  */
1685 static boolean_t
1686 is_replacing_spare(nvlist_t *search, nvlist_t *tgt, int which)
1687 {
1688         nvlist_t **child;
1689         uint_t c, children;
1690         char *type;
1691
1692         if (nvlist_lookup_nvlist_array(search, ZPOOL_CONFIG_CHILDREN, &child,
1693             &children) == 0) {
1694                 verify(nvlist_lookup_string(search, ZPOOL_CONFIG_TYPE,
1695                     &type) == 0);
1696
1697                 if (strcmp(type, VDEV_TYPE_SPARE) == 0 &&
1698                     children == 2 && child[which] == tgt)
1699                         return (B_TRUE);
1700
1701                 for (c = 0; c < children; c++)
1702                         if (is_replacing_spare(child[c], tgt, which))
1703                                 return (B_TRUE);
1704         }
1705
1706         return (B_FALSE);
1707 }
1708
1709 /*
1710  * Attach new_disk (fully described by nvroot) to old_disk.
1711  * If 'replacing' is specified, the new disk will replace the old one.
1712  */
1713 int
1714 zpool_vdev_attach(zpool_handle_t *zhp,
1715     const char *old_disk, const char *new_disk, nvlist_t *nvroot, int replacing)
1716 {
1717         zfs_cmd_t zc = { 0 };
1718         char msg[1024];
1719         int ret;
1720         nvlist_t *tgt;
1721         boolean_t avail_spare, l2cache, islog;
1722         uint64_t val;
1723         char *path, *newname;
1724         nvlist_t **child;
1725         uint_t children;
1726         nvlist_t *config_root;
1727         libzfs_handle_t *hdl = zhp->zpool_hdl;
1728
1729         if (replacing)
1730                 (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1731                     "cannot replace %s with %s"), old_disk, new_disk);
1732         else
1733                 (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1734                     "cannot attach %s to %s"), new_disk, old_disk);
1735
1736         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1737         if ((tgt = zpool_find_vdev(zhp, old_disk, &avail_spare, &l2cache,
1738             &islog)) == 0)
1739                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
1740
1741         if (avail_spare)
1742                 return (zfs_error(hdl, EZFS_ISSPARE, msg));
1743
1744         if (l2cache)
1745                 return (zfs_error(hdl, EZFS_ISL2CACHE, msg));
1746
1747         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
1748         zc.zc_cookie = replacing;
1749
1750         if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
1751             &child, &children) != 0 || children != 1) {
1752                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1753                     "new device must be a single disk"));
1754                 return (zfs_error(hdl, EZFS_INVALCONFIG, msg));
1755         }
1756
1757         verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
1758             ZPOOL_CONFIG_VDEV_TREE, &config_root) == 0);
1759
1760         if ((newname = zpool_vdev_name(NULL, NULL, child[0])) == NULL)
1761                 return (-1);
1762
1763         /*
1764          * If the target is a hot spare that has been swapped in, we can only
1765          * replace it with another hot spare.
1766          */
1767         if (replacing &&
1768             nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_IS_SPARE, &val) == 0 &&
1769             (zpool_find_vdev(zhp, newname, &avail_spare, &l2cache,
1770             NULL) == NULL || !avail_spare) &&
1771             is_replacing_spare(config_root, tgt, 1)) {
1772                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1773                     "can only be replaced by another hot spare"));
1774                 free(newname);
1775                 return (zfs_error(hdl, EZFS_BADTARGET, msg));
1776         }
1777
1778         /*
1779          * If we are attempting to replace a spare, it canot be applied to an
1780          * already spared device.
1781          */
1782         if (replacing &&
1783             nvlist_lookup_string(child[0], ZPOOL_CONFIG_PATH, &path) == 0 &&
1784             zpool_find_vdev(zhp, newname, &avail_spare,
1785             &l2cache, NULL) != NULL && avail_spare &&
1786             is_replacing_spare(config_root, tgt, 0)) {
1787                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1788                     "device has already been replaced with a spare"));
1789                 free(newname);
1790                 return (zfs_error(hdl, EZFS_BADTARGET, msg));
1791         }
1792
1793         free(newname);
1794
1795         if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
1796                 return (-1);
1797
1798         ret = zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_VDEV_ATTACH, &zc);
1799
1800         zcmd_free_nvlists(&zc);
1801
1802         if (ret == 0)
1803                 return (0);
1804
1805         switch (errno) {
1806         case ENOTSUP:
1807                 /*
1808                  * Can't attach to or replace this type of vdev.
1809                  */
1810                 if (replacing) {
1811                         if (islog)
1812                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1813                                     "cannot replace a log with a spare"));
1814                         else
1815                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1816                                     "cannot replace a replacing device"));
1817                 } else {
1818                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1819                             "can only attach to mirrors and top-level "
1820                             "disks"));
1821                 }
1822                 (void) zfs_error(hdl, EZFS_BADTARGET, msg);
1823                 break;
1824
1825         case EINVAL:
1826                 /*
1827                  * The new device must be a single disk.
1828                  */
1829                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1830                     "new device must be a single disk"));
1831                 (void) zfs_error(hdl, EZFS_INVALCONFIG, msg);
1832                 break;
1833
1834         case EBUSY:
1835                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "%s is busy"),
1836                     new_disk);
1837                 (void) zfs_error(hdl, EZFS_BADDEV, msg);
1838                 break;
1839
1840         case EOVERFLOW:
1841                 /*
1842                  * The new device is too small.
1843                  */
1844                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1845                     "device is too small"));
1846                 (void) zfs_error(hdl, EZFS_BADDEV, msg);
1847                 break;
1848
1849         case EDOM:
1850                 /*
1851                  * The new device has a different alignment requirement.
1852                  */
1853                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1854                     "devices have different sector alignment"));
1855                 (void) zfs_error(hdl, EZFS_BADDEV, msg);
1856                 break;
1857
1858         case ENAMETOOLONG:
1859                 /*
1860                  * The resulting top-level vdev spec won't fit in the label.
1861                  */
1862                 (void) zfs_error(hdl, EZFS_DEVOVERFLOW, msg);
1863                 break;
1864
1865         default:
1866                 (void) zpool_standard_error(hdl, errno, msg);
1867         }
1868
1869         return (-1);
1870 }
1871
1872 /*
1873  * Detach the specified device.
1874  */
1875 int
1876 zpool_vdev_detach(zpool_handle_t *zhp, const char *path)
1877 {
1878         zfs_cmd_t zc = { 0 };
1879         char msg[1024];
1880         nvlist_t *tgt;
1881         boolean_t avail_spare, l2cache;
1882         libzfs_handle_t *hdl = zhp->zpool_hdl;
1883
1884         (void) snprintf(msg, sizeof (msg),
1885             dgettext(TEXT_DOMAIN, "cannot detach %s"), path);
1886
1887         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1888         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
1889             NULL)) == 0)
1890                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
1891
1892         if (avail_spare)
1893                 return (zfs_error(hdl, EZFS_ISSPARE, msg));
1894
1895         if (l2cache)
1896                 return (zfs_error(hdl, EZFS_ISL2CACHE, msg));
1897
1898         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
1899
1900         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_DETACH, &zc) == 0)
1901                 return (0);
1902
1903         switch (errno) {
1904
1905         case ENOTSUP:
1906                 /*
1907                  * Can't detach from this type of vdev.
1908                  */
1909                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "only "
1910                     "applicable to mirror and replacing vdevs"));
1911                 (void) zfs_error(zhp->zpool_hdl, EZFS_BADTARGET, msg);
1912                 break;
1913
1914         case EBUSY:
1915                 /*
1916                  * There are no other replicas of this device.
1917                  */
1918                 (void) zfs_error(hdl, EZFS_NOREPLICAS, msg);
1919                 break;
1920
1921         default:
1922                 (void) zpool_standard_error(hdl, errno, msg);
1923         }
1924
1925         return (-1);
1926 }
1927
1928 /*
1929  * Remove the given device.  Currently, this is supported only for hot spares
1930  * and level 2 cache devices.
1931  */
1932 int
1933 zpool_vdev_remove(zpool_handle_t *zhp, const char *path)
1934 {
1935         zfs_cmd_t zc = { 0 };
1936         char msg[1024];
1937         nvlist_t *tgt;
1938         boolean_t avail_spare, l2cache;
1939         libzfs_handle_t *hdl = zhp->zpool_hdl;
1940
1941         (void) snprintf(msg, sizeof (msg),
1942             dgettext(TEXT_DOMAIN, "cannot remove %s"), path);
1943
1944         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1945         if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
1946             NULL)) == 0)
1947                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
1948
1949         if (!avail_spare && !l2cache) {
1950                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1951                     "only inactive hot spares or cache devices "
1952                     "can be removed"));
1953                 return (zfs_error(hdl, EZFS_NODEVICE, msg));
1954         }
1955
1956         verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
1957
1958         if (zfs_ioctl(hdl, ZFS_IOC_VDEV_REMOVE, &zc) == 0)
1959                 return (0);
1960
1961         return (zpool_standard_error(hdl, errno, msg));
1962 }
1963
1964 /*
1965  * Clear the errors for the pool, or the particular device if specified.
1966  */
1967 int
1968 zpool_clear(zpool_handle_t *zhp, const char *path)
1969 {
1970         zfs_cmd_t zc = { 0 };
1971         char msg[1024];
1972         nvlist_t *tgt;
1973         boolean_t avail_spare, l2cache;
1974         libzfs_handle_t *hdl = zhp->zpool_hdl;
1975
1976         if (path)
1977                 (void) snprintf(msg, sizeof (msg),
1978                     dgettext(TEXT_DOMAIN, "cannot clear errors for %s"),
1979                     path);
1980         else
1981                 (void) snprintf(msg, sizeof (msg),
1982                     dgettext(TEXT_DOMAIN, "cannot clear errors for %s"),
1983                     zhp->zpool_name);
1984
1985         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1986         if (path) {
1987                 if ((tgt = zpool_find_vdev(zhp, path, &avail_spare,
1988                     &l2cache, NULL)) == 0)
1989                         return (zfs_error(hdl, EZFS_NODEVICE, msg));
1990
1991                 /*
1992                  * Don't allow error clearing for hot spares.  Do allow
1993                  * error clearing for l2cache devices.
1994                  */
1995                 if (avail_spare)
1996                         return (zfs_error(hdl, EZFS_ISSPARE, msg));
1997
1998                 verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID,
1999                     &zc.zc_guid) == 0);
2000         }
2001
2002         if (zfs_ioctl(hdl, ZFS_IOC_CLEAR, &zc) == 0)
2003                 return (0);
2004
2005         return (zpool_standard_error(hdl, errno, msg));
2006 }
2007
2008 /*
2009  * Similar to zpool_clear(), but takes a GUID (used by fmd).
2010  */
2011 int
2012 zpool_vdev_clear(zpool_handle_t *zhp, uint64_t guid)
2013 {
2014         zfs_cmd_t zc = { 0 };
2015         char msg[1024];
2016         libzfs_handle_t *hdl = zhp->zpool_hdl;
2017
2018         (void) snprintf(msg, sizeof (msg),
2019             dgettext(TEXT_DOMAIN, "cannot clear errors for %llx"),
2020             guid);
2021
2022         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2023         zc.zc_guid = guid;
2024
2025         if (ioctl(hdl->libzfs_fd, ZFS_IOC_CLEAR, &zc) == 0)
2026                 return (0);
2027
2028         return (zpool_standard_error(hdl, errno, msg));
2029 }
2030
2031 /*
2032  * Iterate over all zvols in a given pool by walking the /dev/zvol/dsk/<pool>
2033  * hierarchy.
2034  */
2035 int
2036 zpool_iter_zvol(zpool_handle_t *zhp, int (*cb)(const char *, void *),
2037     void *data)
2038 {
2039         libzfs_handle_t *hdl = zhp->zpool_hdl;
2040         char (*paths)[MAXPATHLEN];
2041         char path[MAXPATHLEN];
2042         size_t size = 4;
2043         int curr, fd, base, ret = 0;
2044         DIR *dirp;
2045         struct dirent *dp;
2046         struct stat st;
2047
2048         if ((base = open(ZVOL_FULL_DEV_DIR, O_RDONLY)) < 0)
2049                 return (errno == ENOENT ? 0 : -1);
2050
2051         snprintf(path, sizeof(path), "%s/%s", ZVOL_FULL_DEV_DIR,
2052             zhp->zpool_name);
2053         if (stat(path, &st) != 0) {
2054                 int err = errno;
2055                 (void) close(base);
2056                 return (err == ENOENT ? 0 : -1);
2057         }
2058
2059         /*
2060          * Oddly this wasn't a directory -- ignore that failure since we
2061          * know there are no links lower in the (non-existant) hierarchy.
2062          */
2063         if (!S_ISDIR(st.st_mode)) {
2064                 (void) close(base);
2065                 return (0);
2066         }
2067
2068         if ((paths = zfs_alloc(hdl, size * sizeof (paths[0]))) == NULL) {
2069                 (void) close(base);
2070                 return (-1);
2071         }
2072
2073         (void) strlcpy(paths[0], zhp->zpool_name, sizeof (paths[0]));
2074         curr = 0;
2075
2076         while (curr >= 0) {
2077                 snprintf(path, sizeof(path), "%s/%s", ZVOL_FULL_DEV_DIR,
2078                     paths[curr]);
2079                 if (lstat(path, &st) != 0)
2080                         goto err;
2081
2082                 if (S_ISDIR(st.st_mode)) {
2083                         if ((dirp = opendir(path)) == NULL) {
2084                                 goto err;
2085                         }
2086
2087                         while ((dp = readdir(dirp)) != NULL) {
2088                                 if (dp->d_name[0] == '.')
2089                                         continue;
2090
2091                                 if (curr + 1 == size) {
2092                                         paths = zfs_realloc(hdl, paths,
2093                                             size * sizeof (paths[0]),
2094                                             size * 2 * sizeof (paths[0]));
2095                                         if (paths == NULL) {
2096                                                 (void) closedir(dirp);
2097                                                 goto err;
2098                                         }
2099
2100                                         size *= 2;
2101                                 }
2102
2103                                 (void) strlcpy(paths[curr + 1], paths[curr],
2104                                     sizeof (paths[curr + 1]));
2105                                 (void) strlcat(paths[curr], "/",
2106                                     sizeof (paths[curr]));
2107                                 (void) strlcat(paths[curr], dp->d_name,
2108                                     sizeof (paths[curr]));
2109                                 curr++;
2110                         }
2111
2112                         (void) closedir(dirp);
2113
2114                 } else {
2115                         if ((ret = cb(paths[curr], data)) != 0)
2116                                 break;
2117                 }
2118
2119                 curr--;
2120         }
2121
2122         free(paths);
2123         (void) close(base);
2124
2125         return (ret);
2126
2127 err:
2128         free(paths);
2129         (void) close(base);
2130         return (-1);
2131 }
2132
2133 typedef struct zvol_cb {
2134         zpool_handle_t *zcb_pool;
2135         boolean_t zcb_create;
2136 } zvol_cb_t;
2137
2138 /*ARGSUSED*/
2139 static int
2140 do_zvol_create(zfs_handle_t *zhp, void *data)
2141 {
2142         int ret = 0;
2143
2144         if (ZFS_IS_VOLUME(zhp)) {
2145                 (void) zvol_create_link(zhp->zfs_hdl, zhp->zfs_name);
2146                 ret = zfs_iter_snapshots(zhp, do_zvol_create, NULL);
2147         }
2148
2149         if (ret == 0)
2150                 ret = zfs_iter_filesystems(zhp, do_zvol_create, NULL);
2151
2152         zfs_close(zhp);
2153
2154         return (ret);
2155 }
2156
2157 /*
2158  * Iterate over all zvols in the pool and make any necessary minor nodes.
2159  */
2160 int
2161 zpool_create_zvol_links(zpool_handle_t *zhp)
2162 {
2163         zfs_handle_t *zfp;
2164         int ret;
2165
2166         /*
2167          * If the pool is unavailable, just return success.
2168          */
2169         if ((zfp = make_dataset_handle(zhp->zpool_hdl,
2170             zhp->zpool_name)) == NULL)
2171                 return (0);
2172
2173         ret = zfs_iter_filesystems(zfp, do_zvol_create, NULL);
2174
2175         zfs_close(zfp);
2176         return (ret);
2177 }
2178
2179 static int
2180 do_zvol_remove(const char *dataset, void *data)
2181 {
2182         zpool_handle_t *zhp = data;
2183
2184         return (zvol_remove_link(zhp->zpool_hdl, dataset));
2185 }
2186
2187 /*
2188  * Iterate over all zvols in the pool and remove any minor nodes.  We iterate
2189  * by examining the /dev links so that a corrupted pool doesn't impede this
2190  * operation.
2191  */
2192 int
2193 zpool_remove_zvol_links(zpool_handle_t *zhp)
2194 {
2195         return (zpool_iter_zvol(zhp, do_zvol_remove, zhp));
2196 }
2197
2198 /*
2199  * Convert from a devid string to a path.
2200  */
2201 static char *
2202 devid_to_path(char *devid_str)
2203 {
2204         ddi_devid_t devid;
2205         char *minor;
2206         char *path;
2207         devid_nmlist_t *list = NULL;
2208         int ret;
2209
2210         if (devid_str_decode(devid_str, &devid, &minor) != 0)
2211                 return (NULL);
2212
2213         ret = devid_deviceid_to_nmlist("/dev", devid, minor, &list);
2214
2215         devid_str_free(minor);
2216         devid_free(devid);
2217
2218         if (ret != 0)
2219                 return (NULL);
2220
2221         if ((path = strdup(list[0].devname)) == NULL)
2222                 return (NULL);
2223
2224         devid_free_nmlist(list);
2225
2226         return (path);
2227 }
2228
2229 /*
2230  * Convert from a path to a devid string.
2231  */
2232 static char *
2233 path_to_devid(const char *path)
2234 {
2235         int fd;
2236         ddi_devid_t devid;
2237         char *minor, *ret;
2238
2239         if ((fd = open(path, O_RDONLY)) < 0)
2240                 return (NULL);
2241
2242         minor = NULL;
2243         ret = NULL;
2244         if (devid_get(fd, &devid) == 0) {
2245                 if (devid_get_minor_name(fd, &minor) == 0)
2246                         ret = devid_str_encode(devid, minor);
2247                 if (minor != NULL)
2248                         devid_str_free(minor);
2249                 devid_free(devid);
2250         }
2251         (void) close(fd);
2252
2253         return (ret);
2254 }
2255
2256 /*
2257  * Issue the necessary ioctl() to update the stored path value for the vdev.  We
2258  * ignore any failure here, since a common case is for an unprivileged user to
2259  * type 'zpool status', and we'll display the correct information anyway.
2260  */
2261 static void
2262 set_path(zpool_handle_t *zhp, nvlist_t *nv, const char *path)
2263 {
2264         zfs_cmd_t zc = { 0 };
2265
2266         (void) strncpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2267         (void) strncpy(zc.zc_value, path, sizeof (zc.zc_value));
2268         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
2269             &zc.zc_guid) == 0);
2270
2271         (void) ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_VDEV_SETPATH, &zc);
2272 }
2273
2274 /*
2275  * Given a vdev, return the name to display in iostat.  If the vdev has a path,
2276  * we use that, stripping off any leading "/dev/dsk/"; if not, we use the type.
2277  * We also check if this is a whole disk, in which case we strip off the
2278  * trailing 's0' slice name.
2279  *
2280  * This routine is also responsible for identifying when disks have been
2281  * reconfigured in a new location.  The kernel will have opened the device by
2282  * devid, but the path will still refer to the old location.  To catch this, we
2283  * first do a path -> devid translation (which is fast for the common case).  If
2284  * the devid matches, we're done.  If not, we do a reverse devid -> path
2285  * translation and issue the appropriate ioctl() to update the path of the vdev.
2286  * If 'zhp' is NULL, then this is an exported pool, and we don't need to do any
2287  * of these checks.
2288  */
2289 char *
2290 zpool_vdev_name(libzfs_handle_t *hdl, zpool_handle_t *zhp, nvlist_t *nv)
2291 {
2292         char *path, *devid;
2293         uint64_t value;
2294         char buf[64];
2295         vdev_stat_t *vs;
2296         uint_t vsc;
2297
2298         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
2299             &value) == 0) {
2300                 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
2301                     &value) == 0);
2302                 (void) snprintf(buf, sizeof (buf), "%llu",
2303                     (u_longlong_t)value);
2304                 path = buf;
2305         } else if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
2306
2307                 /*
2308                  * If the device is dead (faulted, offline, etc) then don't
2309                  * bother opening it.  Otherwise we may be forcing the user to
2310                  * open a misbehaving device, which can have undesirable
2311                  * effects.
2312                  */
2313                 if ((nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_STATS,
2314                     (uint64_t **)&vs, &vsc) != 0 ||
2315                     vs->vs_state >= VDEV_STATE_DEGRADED) &&
2316                     zhp != NULL &&
2317                     nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &devid) == 0) {
2318                         /*
2319                          * Determine if the current path is correct.
2320                          */
2321                         char *newdevid = path_to_devid(path);
2322
2323                         if (newdevid == NULL ||
2324                             strcmp(devid, newdevid) != 0) {
2325                                 char *newpath;
2326
2327                                 if ((newpath = devid_to_path(devid)) != NULL) {
2328                                         /*
2329                                          * Update the path appropriately.
2330                                          */
2331                                         set_path(zhp, nv, newpath);
2332                                         if (nvlist_add_string(nv,
2333                                             ZPOOL_CONFIG_PATH, newpath) == 0)
2334                                                 verify(nvlist_lookup_string(nv,
2335                                                     ZPOOL_CONFIG_PATH,
2336                                                     &path) == 0);
2337                                         free(newpath);
2338                                 }
2339                         }
2340
2341                         if (newdevid)
2342                                 devid_str_free(newdevid);
2343                 }
2344
2345                 if (strncmp(path, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
2346                         path += sizeof(_PATH_DEV) - 1;
2347
2348                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
2349                     &value) == 0 && value) {
2350                         char *tmp = zfs_strdup(hdl, path);
2351                         if (tmp == NULL)
2352                                 return (NULL);
2353                         tmp[strlen(path) - 2] = '\0';
2354                         return (tmp);
2355                 }
2356         } else {
2357                 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &path) == 0);
2358
2359                 /*
2360                  * If it's a raidz device, we need to stick in the parity level.
2361                  */
2362                 if (strcmp(path, VDEV_TYPE_RAIDZ) == 0) {
2363                         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
2364                             &value) == 0);
2365                         (void) snprintf(buf, sizeof (buf), "%s%llu", path,
2366                             (u_longlong_t)value);
2367                         path = buf;
2368                 }
2369         }
2370
2371         return (zfs_strdup(hdl, path));
2372 }
2373
2374 static int
2375 zbookmark_compare(const void *a, const void *b)
2376 {
2377         return (memcmp(a, b, sizeof (zbookmark_t)));
2378 }
2379
2380 /*
2381  * Retrieve the persistent error log, uniquify the members, and return to the
2382  * caller.
2383  */
2384 int
2385 zpool_get_errlog(zpool_handle_t *zhp, nvlist_t **nverrlistp)
2386 {
2387         zfs_cmd_t zc = { 0 };
2388         uint64_t count;
2389         zbookmark_t *zb = NULL;
2390         int i;
2391
2392         /*
2393          * Retrieve the raw error list from the kernel.  If the number of errors
2394          * has increased, allocate more space and continue until we get the
2395          * entire list.
2396          */
2397         verify(nvlist_lookup_uint64(zhp->zpool_config, ZPOOL_CONFIG_ERRCOUNT,
2398             &count) == 0);
2399         if (count == 0)
2400                 return (0);
2401         if ((zc.zc_nvlist_dst = (uintptr_t)zfs_alloc(zhp->zpool_hdl,
2402             count * sizeof (zbookmark_t))) == (uintptr_t)NULL)
2403                 return (-1);
2404         zc.zc_nvlist_dst_size = count;
2405         (void) strcpy(zc.zc_name, zhp->zpool_name);
2406         for (;;) {
2407                 if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_ERROR_LOG,
2408                     &zc) != 0) {
2409                         free((void *)(uintptr_t)zc.zc_nvlist_dst);
2410                         if (errno == ENOMEM) {
2411                                 count = zc.zc_nvlist_dst_size;
2412                                 if ((zc.zc_nvlist_dst = (uintptr_t)
2413                                     zfs_alloc(zhp->zpool_hdl, count *
2414                                     sizeof (zbookmark_t))) == (uintptr_t)NULL)
2415                                         return (-1);
2416                         } else {
2417                                 return (-1);
2418                         }
2419                 } else {
2420                         break;
2421                 }
2422         }
2423
2424         /*
2425          * Sort the resulting bookmarks.  This is a little confusing due to the
2426          * implementation of ZFS_IOC_ERROR_LOG.  The bookmarks are copied last
2427          * to first, and 'zc_nvlist_dst_size' indicates the number of boomarks
2428          * _not_ copied as part of the process.  So we point the start of our
2429          * array appropriate and decrement the total number of elements.
2430          */
2431         zb = ((zbookmark_t *)(uintptr_t)zc.zc_nvlist_dst) +
2432             zc.zc_nvlist_dst_size;
2433         count -= zc.zc_nvlist_dst_size;
2434
2435         qsort(zb, count, sizeof (zbookmark_t), zbookmark_compare);
2436
2437         verify(nvlist_alloc(nverrlistp, 0, KM_SLEEP) == 0);
2438
2439         /*
2440          * Fill in the nverrlistp with nvlist's of dataset and object numbers.
2441          */
2442         for (i = 0; i < count; i++) {
2443                 nvlist_t *nv;
2444
2445                 /* ignoring zb_blkid and zb_level for now */
2446                 if (i > 0 && zb[i-1].zb_objset == zb[i].zb_objset &&
2447                     zb[i-1].zb_object == zb[i].zb_object)
2448                         continue;
2449
2450                 if (nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) != 0)
2451                         goto nomem;
2452                 if (nvlist_add_uint64(nv, ZPOOL_ERR_DATASET,
2453                     zb[i].zb_objset) != 0) {
2454                         nvlist_free(nv);
2455                         goto nomem;
2456                 }
2457                 if (nvlist_add_uint64(nv, ZPOOL_ERR_OBJECT,
2458                     zb[i].zb_object) != 0) {
2459                         nvlist_free(nv);
2460                         goto nomem;
2461                 }
2462                 if (nvlist_add_nvlist(*nverrlistp, "ejk", nv) != 0) {
2463                         nvlist_free(nv);
2464                         goto nomem;
2465                 }
2466                 nvlist_free(nv);
2467         }
2468
2469         free((void *)(uintptr_t)zc.zc_nvlist_dst);
2470         return (0);
2471
2472 nomem:
2473         free((void *)(uintptr_t)zc.zc_nvlist_dst);
2474         return (no_memory(zhp->zpool_hdl));
2475 }
2476
2477 /*
2478  * Upgrade a ZFS pool to the latest on-disk version.
2479  */
2480 int
2481 zpool_upgrade(zpool_handle_t *zhp, uint64_t new_version)
2482 {
2483         zfs_cmd_t zc = { 0 };
2484         libzfs_handle_t *hdl = zhp->zpool_hdl;
2485
2486         (void) strcpy(zc.zc_name, zhp->zpool_name);
2487         zc.zc_cookie = new_version;
2488
2489         if (zfs_ioctl(hdl, ZFS_IOC_POOL_UPGRADE, &zc) != 0)
2490                 return (zpool_standard_error_fmt(hdl, errno,
2491                     dgettext(TEXT_DOMAIN, "cannot upgrade '%s'"),
2492                     zhp->zpool_name));
2493         return (0);
2494 }
2495
2496 void
2497 zpool_set_history_str(const char *subcommand, int argc, char **argv,
2498     char *history_str)
2499 {
2500         int i;
2501
2502         (void) strlcpy(history_str, subcommand, HIS_MAX_RECORD_LEN);
2503         for (i = 1; i < argc; i++) {
2504                 if (strlen(history_str) + 1 + strlen(argv[i]) >
2505                     HIS_MAX_RECORD_LEN)
2506                         break;
2507                 (void) strlcat(history_str, " ", HIS_MAX_RECORD_LEN);
2508                 (void) strlcat(history_str, argv[i], HIS_MAX_RECORD_LEN);
2509         }
2510 }
2511
2512 /*
2513  * Stage command history for logging.
2514  */
2515 int
2516 zpool_stage_history(libzfs_handle_t *hdl, const char *history_str)
2517 {
2518         if (history_str == NULL)
2519                 return (EINVAL);
2520
2521         if (strlen(history_str) > HIS_MAX_RECORD_LEN)
2522                 return (EINVAL);
2523
2524         if (hdl->libzfs_log_str != NULL)
2525                 free(hdl->libzfs_log_str);
2526
2527         if ((hdl->libzfs_log_str = strdup(history_str)) == NULL)
2528                 return (no_memory(hdl));
2529
2530         return (0);
2531 }
2532
2533 /*
2534  * Perform ioctl to get some command history of a pool.
2535  *
2536  * 'buf' is the buffer to fill up to 'len' bytes.  'off' is the
2537  * logical offset of the history buffer to start reading from.
2538  *
2539  * Upon return, 'off' is the next logical offset to read from and
2540  * 'len' is the actual amount of bytes read into 'buf'.
2541  */
2542 static int
2543 get_history(zpool_handle_t *zhp, char *buf, uint64_t *off, uint64_t *len)
2544 {
2545         zfs_cmd_t zc = { 0 };
2546         libzfs_handle_t *hdl = zhp->zpool_hdl;
2547
2548         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2549
2550         zc.zc_history = (uint64_t)(uintptr_t)buf;
2551         zc.zc_history_len = *len;
2552         zc.zc_history_offset = *off;
2553
2554         if (ioctl(hdl->libzfs_fd, ZFS_IOC_POOL_GET_HISTORY, &zc) != 0) {
2555                 switch (errno) {
2556                 case EPERM:
2557                         return (zfs_error_fmt(hdl, EZFS_PERM,
2558                             dgettext(TEXT_DOMAIN,
2559                             "cannot show history for pool '%s'"),
2560                             zhp->zpool_name));
2561                 case ENOENT:
2562                         return (zfs_error_fmt(hdl, EZFS_NOHISTORY,
2563                             dgettext(TEXT_DOMAIN, "cannot get history for pool "
2564                             "'%s'"), zhp->zpool_name));
2565                 case ENOTSUP:
2566                         return (zfs_error_fmt(hdl, EZFS_BADVERSION,
2567                             dgettext(TEXT_DOMAIN, "cannot get history for pool "
2568                             "'%s', pool must be upgraded"), zhp->zpool_name));
2569                 default:
2570                         return (zpool_standard_error_fmt(hdl, errno,
2571                             dgettext(TEXT_DOMAIN,
2572                             "cannot get history for '%s'"), zhp->zpool_name));
2573                 }
2574         }
2575
2576         *len = zc.zc_history_len;
2577         *off = zc.zc_history_offset;
2578
2579         return (0);
2580 }
2581
2582 /*
2583  * Process the buffer of nvlists, unpacking and storing each nvlist record
2584  * into 'records'.  'leftover' is set to the number of bytes that weren't
2585  * processed as there wasn't a complete record.
2586  */
2587 static int
2588 zpool_history_unpack(char *buf, uint64_t bytes_read, uint64_t *leftover,
2589     nvlist_t ***records, uint_t *numrecords)
2590 {
2591         uint64_t reclen;
2592         nvlist_t *nv;
2593         int i;
2594
2595         while (bytes_read > sizeof (reclen)) {
2596
2597                 /* get length of packed record (stored as little endian) */
2598                 for (i = 0, reclen = 0; i < sizeof (reclen); i++)
2599                         reclen += (uint64_t)(((uchar_t *)buf)[i]) << (8*i);
2600
2601                 if (bytes_read < sizeof (reclen) + reclen)
2602                         break;
2603
2604                 /* unpack record */
2605                 if (nvlist_unpack(buf + sizeof (reclen), reclen, &nv, 0) != 0)
2606                         return (ENOMEM);
2607                 bytes_read -= sizeof (reclen) + reclen;
2608                 buf += sizeof (reclen) + reclen;
2609
2610                 /* add record to nvlist array */
2611                 (*numrecords)++;
2612                 if (ISP2(*numrecords + 1)) {
2613                         *records = realloc(*records,
2614                             *numrecords * 2 * sizeof (nvlist_t *));
2615                 }
2616                 (*records)[*numrecords - 1] = nv;
2617         }
2618
2619         *leftover = bytes_read;
2620         return (0);
2621 }
2622
2623 #define HIS_BUF_LEN     (128*1024)
2624
2625 /*
2626  * Retrieve the command history of a pool.
2627  */
2628 int
2629 zpool_get_history(zpool_handle_t *zhp, nvlist_t **nvhisp)
2630 {
2631         char buf[HIS_BUF_LEN];
2632         uint64_t off = 0;
2633         nvlist_t **records = NULL;
2634         uint_t numrecords = 0;
2635         int err, i;
2636
2637         do {
2638                 uint64_t bytes_read = sizeof (buf);
2639                 uint64_t leftover;
2640
2641                 if ((err = get_history(zhp, buf, &off, &bytes_read)) != 0)
2642                         break;
2643
2644                 /* if nothing else was read in, we're at EOF, just return */
2645                 if (!bytes_read)
2646                         break;
2647
2648                 if ((err = zpool_history_unpack(buf, bytes_read,
2649                     &leftover, &records, &numrecords)) != 0)
2650                         break;
2651                 off -= leftover;
2652
2653                 /* CONSTCOND */
2654         } while (1);
2655
2656         if (!err) {
2657                 verify(nvlist_alloc(nvhisp, NV_UNIQUE_NAME, 0) == 0);
2658                 verify(nvlist_add_nvlist_array(*nvhisp, ZPOOL_HIST_RECORD,
2659                     records, numrecords) == 0);
2660         }
2661         for (i = 0; i < numrecords; i++)
2662                 nvlist_free(records[i]);
2663         free(records);
2664
2665         return (err);
2666 }
2667
2668 void
2669 zpool_obj_to_path(zpool_handle_t *zhp, uint64_t dsobj, uint64_t obj,
2670     char *pathname, size_t len)
2671 {
2672         zfs_cmd_t zc = { 0 };
2673         boolean_t mounted = B_FALSE;
2674         char *mntpnt = NULL;
2675         char dsname[MAXNAMELEN];
2676
2677         if (dsobj == 0) {
2678                 /* special case for the MOS */
2679                 (void) snprintf(pathname, len, "<metadata>:<0x%llx>", obj);
2680                 return;
2681         }
2682
2683         /* get the dataset's name */
2684         (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2685         zc.zc_obj = dsobj;
2686         if (ioctl(zhp->zpool_hdl->libzfs_fd,
2687             ZFS_IOC_DSOBJ_TO_DSNAME, &zc) != 0) {
2688                 /* just write out a path of two object numbers */
2689                 (void) snprintf(pathname, len, "<0x%llx>:<0x%llx>",
2690                     dsobj, obj);
2691                 return;
2692         }
2693         (void) strlcpy(dsname, zc.zc_value, sizeof (dsname));
2694
2695         /* find out if the dataset is mounted */
2696         mounted = is_mounted(zhp->zpool_hdl, dsname, &mntpnt);
2697
2698         /* get the corrupted object's path */
2699         (void) strlcpy(zc.zc_name, dsname, sizeof (zc.zc_name));
2700         zc.zc_obj = obj;
2701         if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_OBJ_TO_PATH,
2702             &zc) == 0) {
2703                 if (mounted) {
2704                         (void) snprintf(pathname, len, "%s%s", mntpnt,
2705                             zc.zc_value);
2706                 } else {
2707                         (void) snprintf(pathname, len, "%s:%s",
2708                             dsname, zc.zc_value);
2709                 }
2710         } else {
2711                 (void) snprintf(pathname, len, "%s:<0x%llx>", dsname, obj);
2712         }
2713         free(mntpnt);
2714 }
2715
2716 #define RDISK_ROOT      "/dev/rdsk"
2717 #define BACKUP_SLICE    "s2"
2718 /*
2719  * Don't start the slice at the default block of 34; many storage
2720  * devices will use a stripe width of 128k, so start there instead.
2721  */
2722 #define NEW_START_BLOCK 256
2723
2724 #if defined(sun)
2725 /*
2726  * Read the EFI label from the config, if a label does not exist then
2727  * pass back the error to the caller. If the caller has passed a non-NULL
2728  * diskaddr argument then we set it to the starting address of the EFI
2729  * partition.
2730  */
2731 static int
2732 read_efi_label(nvlist_t *config, diskaddr_t *sb)
2733 {
2734         char *path;
2735         int fd;
2736         char diskname[MAXPATHLEN];
2737         int err = -1;
2738
2739         if (nvlist_lookup_string(config, ZPOOL_CONFIG_PATH, &path) != 0)
2740                 return (err);
2741
2742         (void) snprintf(diskname, sizeof (diskname), "%s%s", RDISK_ROOT,
2743             strrchr(path, '/'));
2744         if ((fd = open(diskname, O_RDONLY|O_NDELAY)) >= 0) {
2745                 struct dk_gpt *vtoc;
2746
2747                 if ((err = efi_alloc_and_read(fd, &vtoc)) >= 0) {
2748                         if (sb != NULL)
2749                                 *sb = vtoc->efi_parts[0].p_start;
2750                         efi_free(vtoc);
2751                 }
2752                 (void) close(fd);
2753         }
2754         return (err);
2755 }
2756
2757 /*
2758  * determine where a partition starts on a disk in the current
2759  * configuration
2760  */
2761 static diskaddr_t
2762 find_start_block(nvlist_t *config)
2763 {
2764         nvlist_t **child;
2765         uint_t c, children;
2766         diskaddr_t sb = MAXOFFSET_T;
2767         uint64_t wholedisk;
2768
2769         if (nvlist_lookup_nvlist_array(config,
2770             ZPOOL_CONFIG_CHILDREN, &child, &children) != 0) {
2771                 if (nvlist_lookup_uint64(config,
2772                     ZPOOL_CONFIG_WHOLE_DISK,
2773                     &wholedisk) != 0 || !wholedisk) {
2774                         return (MAXOFFSET_T);
2775                 }
2776                 if (read_efi_label(config, &sb) < 0)
2777                         sb = MAXOFFSET_T;
2778                 return (sb);
2779         }
2780
2781         for (c = 0; c < children; c++) {
2782                 sb = find_start_block(child[c]);
2783                 if (sb != MAXOFFSET_T) {
2784                         return (sb);
2785                 }
2786         }
2787         return (MAXOFFSET_T);
2788 }
2789 #endif /* sun */
2790
2791 /*
2792  * Label an individual disk.  The name provided is the short name,
2793  * stripped of any leading /dev path.
2794  */
2795 int
2796 zpool_label_disk(libzfs_handle_t *hdl, zpool_handle_t *zhp, char *name)
2797 {
2798 #if defined(sun)
2799         char path[MAXPATHLEN];
2800         struct dk_gpt *vtoc;
2801         int fd;
2802         size_t resv = EFI_MIN_RESV_SIZE;
2803         uint64_t slice_size;
2804         diskaddr_t start_block;
2805         char errbuf[1024];
2806
2807         /* prepare an error message just in case */
2808         (void) snprintf(errbuf, sizeof (errbuf),
2809             dgettext(TEXT_DOMAIN, "cannot label '%s'"), name);
2810
2811         if (zhp) {
2812                 nvlist_t *nvroot;
2813
2814                 verify(nvlist_lookup_nvlist(zhp->zpool_config,
2815                     ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
2816
2817                 if (zhp->zpool_start_block == 0)
2818                         start_block = find_start_block(nvroot);
2819                 else
2820                         start_block = zhp->zpool_start_block;
2821                 zhp->zpool_start_block = start_block;
2822         } else {
2823                 /* new pool */
2824                 start_block = NEW_START_BLOCK;
2825         }
2826
2827         (void) snprintf(path, sizeof (path), "%s/%s%s", RDISK_ROOT, name,
2828             BACKUP_SLICE);
2829
2830         if ((fd = open(path, O_RDWR | O_NDELAY)) < 0) {
2831                 /*
2832                  * This shouldn't happen.  We've long since verified that this
2833                  * is a valid device.
2834                  */
2835                 zfs_error_aux(hdl,
2836                     dgettext(TEXT_DOMAIN, "unable to open device"));
2837                 return (zfs_error(hdl, EZFS_OPENFAILED, errbuf));
2838         }
2839
2840         if (efi_alloc_and_init(fd, EFI_NUMPAR, &vtoc) != 0) {
2841                 /*
2842                  * The only way this can fail is if we run out of memory, or we
2843                  * were unable to read the disk's capacity
2844                  */
2845                 if (errno == ENOMEM)
2846                         (void) no_memory(hdl);
2847
2848                 (void) close(fd);
2849                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2850                     "unable to read disk capacity"), name);
2851
2852                 return (zfs_error(hdl, EZFS_NOCAP, errbuf));
2853         }
2854
2855         slice_size = vtoc->efi_last_u_lba + 1;
2856         slice_size -= EFI_MIN_RESV_SIZE;
2857         if (start_block == MAXOFFSET_T)
2858                 start_block = NEW_START_BLOCK;
2859         slice_size -= start_block;
2860
2861         vtoc->efi_parts[0].p_start = start_block;
2862         vtoc->efi_parts[0].p_size = slice_size;
2863
2864         /*
2865          * Why we use V_USR: V_BACKUP confuses users, and is considered
2866          * disposable by some EFI utilities (since EFI doesn't have a backup
2867          * slice).  V_UNASSIGNED is supposed to be used only for zero size
2868          * partitions, and efi_write() will fail if we use it.  V_ROOT, V_BOOT,
2869          * etc. were all pretty specific.  V_USR is as close to reality as we
2870          * can get, in the absence of V_OTHER.
2871          */
2872         vtoc->efi_parts[0].p_tag = V_USR;
2873         (void) strcpy(vtoc->efi_parts[0].p_name, "zfs");
2874
2875         vtoc->efi_parts[8].p_start = slice_size + start_block;
2876         vtoc->efi_parts[8].p_size = resv;
2877         vtoc->efi_parts[8].p_tag = V_RESERVED;
2878
2879         if (efi_write(fd, vtoc) != 0) {
2880                 /*
2881                  * Some block drivers (like pcata) may not support EFI
2882                  * GPT labels.  Print out a helpful error message dir-
2883                  * ecting the user to manually label the disk and give
2884                  * a specific slice.
2885                  */
2886                 (void) close(fd);
2887                 efi_free(vtoc);
2888
2889                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2890                     "try using fdisk(1M) and then provide a specific slice"));
2891                 return (zfs_error(hdl, EZFS_LABELFAILED, errbuf));
2892         }
2893
2894         (void) close(fd);
2895         efi_free(vtoc);
2896 #endif /* sun */
2897         return (0);
2898 }
2899
2900 static boolean_t
2901 supported_dump_vdev_type(libzfs_handle_t *hdl, nvlist_t *config, char *errbuf)
2902 {
2903         char *type;
2904         nvlist_t **child;
2905         uint_t children, c;
2906
2907         verify(nvlist_lookup_string(config, ZPOOL_CONFIG_TYPE, &type) == 0);
2908         if (strcmp(type, VDEV_TYPE_RAIDZ) == 0 ||
2909             strcmp(type, VDEV_TYPE_FILE) == 0 ||
2910             strcmp(type, VDEV_TYPE_LOG) == 0 ||
2911             strcmp(type, VDEV_TYPE_MISSING) == 0) {
2912                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2913                     "vdev type '%s' is not supported"), type);
2914                 (void) zfs_error(hdl, EZFS_VDEVNOTSUP, errbuf);
2915                 return (B_FALSE);
2916         }
2917         if (nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_CHILDREN,
2918             &child, &children) == 0) {
2919                 for (c = 0; c < children; c++) {
2920                         if (!supported_dump_vdev_type(hdl, child[c], errbuf))
2921                                 return (B_FALSE);
2922                 }
2923         }
2924         return (B_TRUE);
2925 }
2926
2927 /*
2928  * check if this zvol is allowable for use as a dump device; zero if
2929  * it is, > 0 if it isn't, < 0 if it isn't a zvol
2930  */
2931 int
2932 zvol_check_dump_config(char *arg)
2933 {
2934         zpool_handle_t *zhp = NULL;
2935         nvlist_t *config, *nvroot;
2936         char *p, *volname;
2937         nvlist_t **top;
2938         uint_t toplevels;
2939         libzfs_handle_t *hdl;
2940         char errbuf[1024];
2941         char poolname[ZPOOL_MAXNAMELEN];
2942         int pathlen = strlen(ZVOL_FULL_DEV_DIR);
2943         int ret = 1;
2944
2945         if (strncmp(arg, ZVOL_FULL_DEV_DIR, pathlen)) {
2946                 return (-1);
2947         }
2948
2949         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2950             "dump is not supported on device '%s'"), arg);
2951
2952         if ((hdl = libzfs_init()) == NULL)
2953                 return (1);
2954         libzfs_print_on_error(hdl, B_TRUE);
2955
2956         volname = arg + pathlen;
2957
2958         /* check the configuration of the pool */
2959         if ((p = strchr(volname, '/')) == NULL) {
2960                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2961                     "malformed dataset name"));
2962                 (void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
2963                 return (1);
2964         } else if (p - volname >= ZFS_MAXNAMELEN) {
2965                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2966                     "dataset name is too long"));
2967                 (void) zfs_error(hdl, EZFS_NAMETOOLONG, errbuf);
2968                 return (1);
2969         } else {
2970                 (void) strncpy(poolname, volname, p - volname);
2971                 poolname[p - volname] = '\0';
2972         }
2973
2974         if ((zhp = zpool_open(hdl, poolname)) == NULL) {
2975                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2976                     "could not open pool '%s'"), poolname);
2977                 (void) zfs_error(hdl, EZFS_OPENFAILED, errbuf);
2978                 goto out;
2979         }
2980         config = zpool_get_config(zhp, NULL);
2981         if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2982             &nvroot) != 0) {
2983                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2984                     "could not obtain vdev configuration for  '%s'"), poolname);
2985                 (void) zfs_error(hdl, EZFS_INVALCONFIG, errbuf);
2986                 goto out;
2987         }
2988
2989         verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
2990             &top, &toplevels) == 0);
2991         if (toplevels != 1) {
2992                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2993                     "'%s' has multiple top level vdevs"), poolname);
2994                 (void) zfs_error(hdl, EZFS_DEVOVERFLOW, errbuf);
2995                 goto out;
2996         }
2997
2998         if (!supported_dump_vdev_type(hdl, top[0], errbuf)) {
2999                 goto out;
3000         }
3001         ret = 0;
3002
3003 out:
3004         if (zhp)
3005                 zpool_close(zhp);
3006         libzfs_fini(hdl);
3007         return (ret);
3008 }