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