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