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