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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
25 * Copyright (c) 2018, Nexenta Systems, Inc. All rights reserved.
26 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
27 * Copyright 2013 Saso Kiselkov. All rights reserved.
28 * Copyright (c) 2014 Integros [integros.com]
29 * Copyright 2016 Toomas Soome <[email protected]>
30 * Copyright (c) 2016 Actifio, Inc. All rights reserved.
31 * Copyright 2018 Joyent, Inc.
32 * Copyright (c) 2017, 2019, Datto Inc. All rights reserved.
33 * Copyright 2017 Joyent, Inc.
34 * Copyright (c) 2017, Intel Corporation.
35 * Copyright (c) 2021, Colm Buckley <[email protected]>
36 */
37
38 /*
39 * SPA: Storage Pool Allocator
40 *
41 * This file contains all the routines used when modifying on-disk SPA state.
42 * This includes opening, importing, destroying, exporting a pool, and syncing a
43 * pool.
44 */
45
46 #include <sys/zfs_context.h>
47 #include <sys/fm/fs/zfs.h>
48 #include <sys/spa_impl.h>
49 #include <sys/zio.h>
50 #include <sys/zio_checksum.h>
51 #include <sys/dmu.h>
52 #include <sys/dmu_tx.h>
53 #include <sys/zap.h>
54 #include <sys/zil.h>
55 #include <sys/ddt.h>
56 #include <sys/vdev_impl.h>
57 #include <sys/vdev_removal.h>
58 #include <sys/vdev_indirect_mapping.h>
59 #include <sys/vdev_indirect_births.h>
60 #include <sys/vdev_initialize.h>
61 #include <sys/vdev_rebuild.h>
62 #include <sys/vdev_trim.h>
63 #include <sys/vdev_disk.h>
64 #include <sys/vdev_draid.h>
65 #include <sys/metaslab.h>
66 #include <sys/metaslab_impl.h>
67 #include <sys/mmp.h>
68 #include <sys/uberblock_impl.h>
69 #include <sys/txg.h>
70 #include <sys/avl.h>
71 #include <sys/bpobj.h>
72 #include <sys/dmu_traverse.h>
73 #include <sys/dmu_objset.h>
74 #include <sys/unique.h>
75 #include <sys/dsl_pool.h>
76 #include <sys/dsl_dataset.h>
77 #include <sys/dsl_dir.h>
78 #include <sys/dsl_prop.h>
79 #include <sys/dsl_synctask.h>
80 #include <sys/fs/zfs.h>
81 #include <sys/arc.h>
82 #include <sys/callb.h>
83 #include <sys/systeminfo.h>
84 #include <sys/spa_boot.h>
85 #include <sys/zfs_ioctl.h>
86 #include <sys/dsl_scan.h>
87 #include <sys/zfeature.h>
88 #include <sys/dsl_destroy.h>
89 #include <sys/zvol.h>
90
91 #ifdef _KERNEL
92 #include <sys/fm/protocol.h>
93 #include <sys/fm/util.h>
94 #include <sys/callb.h>
95 #include <sys/zone.h>
96 #include <sys/vmsystm.h>
97 #endif /* _KERNEL */
98
99 #include "zfs_prop.h"
100 #include "zfs_comutil.h"
101
102 /*
103 * The interval, in seconds, at which failed configuration cache file writes
104 * should be retried.
105 */
106 int zfs_ccw_retry_interval = 300;
107
108 typedef enum zti_modes {
109 ZTI_MODE_FIXED, /* value is # of threads (min 1) */
110 ZTI_MODE_BATCH, /* cpu-intensive; value is ignored */
111 ZTI_MODE_SCALE, /* Taskqs scale with CPUs. */
112 ZTI_MODE_NULL, /* don't create a taskq */
113 ZTI_NMODES
114 } zti_modes_t;
115
116 #define ZTI_P(n, q) { ZTI_MODE_FIXED, (n), (q) }
117 #define ZTI_PCT(n) { ZTI_MODE_ONLINE_PERCENT, (n), 1 }
118 #define ZTI_BATCH { ZTI_MODE_BATCH, 0, 1 }
119 #define ZTI_SCALE { ZTI_MODE_SCALE, 0, 1 }
120 #define ZTI_NULL { ZTI_MODE_NULL, 0, 0 }
121
122 #define ZTI_N(n) ZTI_P(n, 1)
123 #define ZTI_ONE ZTI_N(1)
124
125 typedef struct zio_taskq_info {
126 zti_modes_t zti_mode;
127 uint_t zti_value;
128 uint_t zti_count;
129 } zio_taskq_info_t;
130
131 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
132 "iss", "iss_h", "int", "int_h"
133 };
134
135 /*
136 * This table defines the taskq settings for each ZFS I/O type. When
137 * initializing a pool, we use this table to create an appropriately sized
138 * taskq. Some operations are low volume and therefore have a small, static
139 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
140 * macros. Other operations process a large amount of data; the ZTI_BATCH
141 * macro causes us to create a taskq oriented for throughput. Some operations
142 * are so high frequency and short-lived that the taskq itself can become a
143 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
144 * additional degree of parallelism specified by the number of threads per-
145 * taskq and the number of taskqs; when dispatching an event in this case, the
146 * particular taskq is chosen at random. ZTI_SCALE is similar to ZTI_BATCH,
147 * but with number of taskqs also scaling with number of CPUs.
148 *
149 * The different taskq priorities are to handle the different contexts (issue
150 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
151 * need to be handled with minimum delay.
152 */
153 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
154 /* ISSUE ISSUE_HIGH INTR INTR_HIGH */
155 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* NULL */
156 { ZTI_N(8), ZTI_NULL, ZTI_SCALE, ZTI_NULL }, /* READ */
157 { ZTI_BATCH, ZTI_N(5), ZTI_SCALE, ZTI_N(5) }, /* WRITE */
158 { ZTI_SCALE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* FREE */
159 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* CLAIM */
160 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* IOCTL */
161 { ZTI_N(4), ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* TRIM */
162 };
163
164 static void spa_sync_version(void *arg, dmu_tx_t *tx);
165 static void spa_sync_props(void *arg, dmu_tx_t *tx);
166 static boolean_t spa_has_active_shared_spare(spa_t *spa);
167 static int spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport);
168 static void spa_vdev_resilver_done(spa_t *spa);
169
170 uint_t zio_taskq_batch_pct = 80; /* 1 thread per cpu in pset */
171 uint_t zio_taskq_batch_tpq; /* threads per taskq */
172 boolean_t zio_taskq_sysdc = B_TRUE; /* use SDC scheduling class */
173 uint_t zio_taskq_basedc = 80; /* base duty cycle */
174
175 boolean_t spa_create_process = B_TRUE; /* no process ==> no sysdc */
176
177 /*
178 * Report any spa_load_verify errors found, but do not fail spa_load.
179 * This is used by zdb to analyze non-idle pools.
180 */
181 boolean_t spa_load_verify_dryrun = B_FALSE;
182
183 /*
184 * This (illegal) pool name is used when temporarily importing a spa_t in order
185 * to get the vdev stats associated with the imported devices.
186 */
187 #define TRYIMPORT_NAME "$import"
188
189 /*
190 * For debugging purposes: print out vdev tree during pool import.
191 */
192 int spa_load_print_vdev_tree = B_FALSE;
193
194 /*
195 * A non-zero value for zfs_max_missing_tvds means that we allow importing
196 * pools with missing top-level vdevs. This is strictly intended for advanced
197 * pool recovery cases since missing data is almost inevitable. Pools with
198 * missing devices can only be imported read-only for safety reasons, and their
199 * fail-mode will be automatically set to "continue".
200 *
201 * With 1 missing vdev we should be able to import the pool and mount all
202 * datasets. User data that was not modified after the missing device has been
203 * added should be recoverable. This means that snapshots created prior to the
204 * addition of that device should be completely intact.
205 *
206 * With 2 missing vdevs, some datasets may fail to mount since there are
207 * dataset statistics that are stored as regular metadata. Some data might be
208 * recoverable if those vdevs were added recently.
209 *
210 * With 3 or more missing vdevs, the pool is severely damaged and MOS entries
211 * may be missing entirely. Chances of data recovery are very low. Note that
212 * there are also risks of performing an inadvertent rewind as we might be
213 * missing all the vdevs with the latest uberblocks.
214 */
215 unsigned long zfs_max_missing_tvds = 0;
216
217 /*
218 * The parameters below are similar to zfs_max_missing_tvds but are only
219 * intended for a preliminary open of the pool with an untrusted config which
220 * might be incomplete or out-dated.
221 *
222 * We are more tolerant for pools opened from a cachefile since we could have
223 * an out-dated cachefile where a device removal was not registered.
224 * We could have set the limit arbitrarily high but in the case where devices
225 * are really missing we would want to return the proper error codes; we chose
226 * SPA_DVAS_PER_BP - 1 so that some copies of the MOS would still be available
227 * and we get a chance to retrieve the trusted config.
228 */
229 uint64_t zfs_max_missing_tvds_cachefile = SPA_DVAS_PER_BP - 1;
230
231 /*
232 * In the case where config was assembled by scanning device paths (/dev/dsks
233 * by default) we are less tolerant since all the existing devices should have
234 * been detected and we want spa_load to return the right error codes.
235 */
236 uint64_t zfs_max_missing_tvds_scan = 0;
237
238 /*
239 * Debugging aid that pauses spa_sync() towards the end.
240 */
241 boolean_t zfs_pause_spa_sync = B_FALSE;
242
243 /*
244 * Variables to indicate the livelist condense zthr func should wait at certain
245 * points for the livelist to be removed - used to test condense/destroy races
246 */
247 int zfs_livelist_condense_zthr_pause = 0;
248 int zfs_livelist_condense_sync_pause = 0;
249
250 /*
251 * Variables to track whether or not condense cancellation has been
252 * triggered in testing.
253 */
254 int zfs_livelist_condense_sync_cancel = 0;
255 int zfs_livelist_condense_zthr_cancel = 0;
256
257 /*
258 * Variable to track whether or not extra ALLOC blkptrs were added to a
259 * livelist entry while it was being condensed (caused by the way we track
260 * remapped blkptrs in dbuf_remap_impl)
261 */
262 int zfs_livelist_condense_new_alloc = 0;
263
264 /*
265 * ==========================================================================
266 * SPA properties routines
267 * ==========================================================================
268 */
269
270 /*
271 * Add a (source=src, propname=propval) list to an nvlist.
272 */
273 static void
spa_prop_add_list(nvlist_t * nvl,zpool_prop_t prop,char * strval,uint64_t intval,zprop_source_t src)274 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
275 uint64_t intval, zprop_source_t src)
276 {
277 const char *propname = zpool_prop_to_name(prop);
278 nvlist_t *propval;
279
280 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
281 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
282
283 if (strval != NULL)
284 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
285 else
286 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
287
288 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
289 nvlist_free(propval);
290 }
291
292 /*
293 * Get property values from the spa configuration.
294 */
295 static void
spa_prop_get_config(spa_t * spa,nvlist_t ** nvp)296 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
297 {
298 vdev_t *rvd = spa->spa_root_vdev;
299 dsl_pool_t *pool = spa->spa_dsl_pool;
300 uint64_t size, alloc, cap, version;
301 const zprop_source_t src = ZPROP_SRC_NONE;
302 spa_config_dirent_t *dp;
303 metaslab_class_t *mc = spa_normal_class(spa);
304
305 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
306
307 if (rvd != NULL) {
308 alloc = metaslab_class_get_alloc(mc);
309 alloc += metaslab_class_get_alloc(spa_special_class(spa));
310 alloc += metaslab_class_get_alloc(spa_dedup_class(spa));
311 alloc += metaslab_class_get_alloc(spa_embedded_log_class(spa));
312
313 size = metaslab_class_get_space(mc);
314 size += metaslab_class_get_space(spa_special_class(spa));
315 size += metaslab_class_get_space(spa_dedup_class(spa));
316 size += metaslab_class_get_space(spa_embedded_log_class(spa));
317
318 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
319 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
320 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
321 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
322 size - alloc, src);
323 spa_prop_add_list(*nvp, ZPOOL_PROP_CHECKPOINT, NULL,
324 spa->spa_checkpoint_info.sci_dspace, src);
325
326 spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
327 metaslab_class_fragmentation(mc), src);
328 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
329 metaslab_class_expandable_space(mc), src);
330 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
331 (spa_mode(spa) == SPA_MODE_READ), src);
332
333 cap = (size == 0) ? 0 : (alloc * 100 / size);
334 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
335
336 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
337 ddt_get_pool_dedup_ratio(spa), src);
338
339 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
340 rvd->vdev_state, src);
341
342 version = spa_version(spa);
343 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION)) {
344 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL,
345 version, ZPROP_SRC_DEFAULT);
346 } else {
347 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL,
348 version, ZPROP_SRC_LOCAL);
349 }
350 spa_prop_add_list(*nvp, ZPOOL_PROP_LOAD_GUID,
351 NULL, spa_load_guid(spa), src);
352 }
353
354 if (pool != NULL) {
355 /*
356 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
357 * when opening pools before this version freedir will be NULL.
358 */
359 if (pool->dp_free_dir != NULL) {
360 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
361 dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
362 src);
363 } else {
364 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
365 NULL, 0, src);
366 }
367
368 if (pool->dp_leak_dir != NULL) {
369 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
370 dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
371 src);
372 } else {
373 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
374 NULL, 0, src);
375 }
376 }
377
378 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
379
380 if (spa->spa_comment != NULL) {
381 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
382 0, ZPROP_SRC_LOCAL);
383 }
384
385 if (spa->spa_compatibility != NULL) {
386 spa_prop_add_list(*nvp, ZPOOL_PROP_COMPATIBILITY,
387 spa->spa_compatibility, 0, ZPROP_SRC_LOCAL);
388 }
389
390 if (spa->spa_root != NULL)
391 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
392 0, ZPROP_SRC_LOCAL);
393
394 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
395 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
396 MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
397 } else {
398 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
399 SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
400 }
401
402 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE)) {
403 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
404 DNODE_MAX_SIZE, ZPROP_SRC_NONE);
405 } else {
406 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
407 DNODE_MIN_SIZE, ZPROP_SRC_NONE);
408 }
409
410 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
411 if (dp->scd_path == NULL) {
412 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
413 "none", 0, ZPROP_SRC_LOCAL);
414 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
415 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
416 dp->scd_path, 0, ZPROP_SRC_LOCAL);
417 }
418 }
419 }
420
421 /*
422 * Get zpool property values.
423 */
424 int
spa_prop_get(spa_t * spa,nvlist_t ** nvp)425 spa_prop_get(spa_t *spa, nvlist_t **nvp)
426 {
427 objset_t *mos = spa->spa_meta_objset;
428 zap_cursor_t zc;
429 zap_attribute_t za;
430 dsl_pool_t *dp;
431 int err;
432
433 err = nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP);
434 if (err)
435 return (err);
436
437 dp = spa_get_dsl(spa);
438 dsl_pool_config_enter(dp, FTAG);
439 mutex_enter(&spa->spa_props_lock);
440
441 /*
442 * Get properties from the spa config.
443 */
444 spa_prop_get_config(spa, nvp);
445
446 /* If no pool property object, no more prop to get. */
447 if (mos == NULL || spa->spa_pool_props_object == 0)
448 goto out;
449
450 /*
451 * Get properties from the MOS pool property object.
452 */
453 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
454 (err = zap_cursor_retrieve(&zc, &za)) == 0;
455 zap_cursor_advance(&zc)) {
456 uint64_t intval = 0;
457 char *strval = NULL;
458 zprop_source_t src = ZPROP_SRC_DEFAULT;
459 zpool_prop_t prop;
460
461 if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
462 continue;
463
464 switch (za.za_integer_length) {
465 case 8:
466 /* integer property */
467 if (za.za_first_integer !=
468 zpool_prop_default_numeric(prop))
469 src = ZPROP_SRC_LOCAL;
470
471 if (prop == ZPOOL_PROP_BOOTFS) {
472 dsl_dataset_t *ds = NULL;
473
474 err = dsl_dataset_hold_obj(dp,
475 za.za_first_integer, FTAG, &ds);
476 if (err != 0)
477 break;
478
479 strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
480 KM_SLEEP);
481 dsl_dataset_name(ds, strval);
482 dsl_dataset_rele(ds, FTAG);
483 } else {
484 strval = NULL;
485 intval = za.za_first_integer;
486 }
487
488 spa_prop_add_list(*nvp, prop, strval, intval, src);
489
490 if (strval != NULL)
491 kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
492
493 break;
494
495 case 1:
496 /* string property */
497 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
498 err = zap_lookup(mos, spa->spa_pool_props_object,
499 za.za_name, 1, za.za_num_integers, strval);
500 if (err) {
501 kmem_free(strval, za.za_num_integers);
502 break;
503 }
504 spa_prop_add_list(*nvp, prop, strval, 0, src);
505 kmem_free(strval, za.za_num_integers);
506 break;
507
508 default:
509 break;
510 }
511 }
512 zap_cursor_fini(&zc);
513 out:
514 mutex_exit(&spa->spa_props_lock);
515 dsl_pool_config_exit(dp, FTAG);
516 if (err && err != ENOENT) {
517 nvlist_free(*nvp);
518 *nvp = NULL;
519 return (err);
520 }
521
522 return (0);
523 }
524
525 /*
526 * Validate the given pool properties nvlist and modify the list
527 * for the property values to be set.
528 */
529 static int
spa_prop_validate(spa_t * spa,nvlist_t * props)530 spa_prop_validate(spa_t *spa, nvlist_t *props)
531 {
532 nvpair_t *elem;
533 int error = 0, reset_bootfs = 0;
534 uint64_t objnum = 0;
535 boolean_t has_feature = B_FALSE;
536
537 elem = NULL;
538 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
539 uint64_t intval;
540 char *strval, *slash, *check, *fname;
541 const char *propname = nvpair_name(elem);
542 zpool_prop_t prop = zpool_name_to_prop(propname);
543
544 switch (prop) {
545 case ZPOOL_PROP_INVAL:
546 if (!zpool_prop_feature(propname)) {
547 error = SET_ERROR(EINVAL);
548 break;
549 }
550
551 /*
552 * Sanitize the input.
553 */
554 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
555 error = SET_ERROR(EINVAL);
556 break;
557 }
558
559 if (nvpair_value_uint64(elem, &intval) != 0) {
560 error = SET_ERROR(EINVAL);
561 break;
562 }
563
564 if (intval != 0) {
565 error = SET_ERROR(EINVAL);
566 break;
567 }
568
569 fname = strchr(propname, '@') + 1;
570 if (zfeature_lookup_name(fname, NULL) != 0) {
571 error = SET_ERROR(EINVAL);
572 break;
573 }
574
575 has_feature = B_TRUE;
576 break;
577
578 case ZPOOL_PROP_VERSION:
579 error = nvpair_value_uint64(elem, &intval);
580 if (!error &&
581 (intval < spa_version(spa) ||
582 intval > SPA_VERSION_BEFORE_FEATURES ||
583 has_feature))
584 error = SET_ERROR(EINVAL);
585 break;
586
587 case ZPOOL_PROP_DELEGATION:
588 case ZPOOL_PROP_AUTOREPLACE:
589 case ZPOOL_PROP_LISTSNAPS:
590 case ZPOOL_PROP_AUTOEXPAND:
591 case ZPOOL_PROP_AUTOTRIM:
592 error = nvpair_value_uint64(elem, &intval);
593 if (!error && intval > 1)
594 error = SET_ERROR(EINVAL);
595 break;
596
597 case ZPOOL_PROP_MULTIHOST:
598 error = nvpair_value_uint64(elem, &intval);
599 if (!error && intval > 1)
600 error = SET_ERROR(EINVAL);
601
602 if (!error) {
603 uint32_t hostid = zone_get_hostid(NULL);
604 if (hostid)
605 spa->spa_hostid = hostid;
606 else
607 error = SET_ERROR(ENOTSUP);
608 }
609
610 break;
611
612 case ZPOOL_PROP_BOOTFS:
613 /*
614 * If the pool version is less than SPA_VERSION_BOOTFS,
615 * or the pool is still being created (version == 0),
616 * the bootfs property cannot be set.
617 */
618 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
619 error = SET_ERROR(ENOTSUP);
620 break;
621 }
622
623 /*
624 * Make sure the vdev config is bootable
625 */
626 if (!vdev_is_bootable(spa->spa_root_vdev)) {
627 error = SET_ERROR(ENOTSUP);
628 break;
629 }
630
631 reset_bootfs = 1;
632
633 error = nvpair_value_string(elem, &strval);
634
635 if (!error) {
636 objset_t *os;
637
638 if (strval == NULL || strval[0] == '\0') {
639 objnum = zpool_prop_default_numeric(
640 ZPOOL_PROP_BOOTFS);
641 break;
642 }
643
644 error = dmu_objset_hold(strval, FTAG, &os);
645 if (error != 0)
646 break;
647
648 /* Must be ZPL. */
649 if (dmu_objset_type(os) != DMU_OST_ZFS) {
650 error = SET_ERROR(ENOTSUP);
651 } else {
652 objnum = dmu_objset_id(os);
653 }
654 dmu_objset_rele(os, FTAG);
655 }
656 break;
657
658 case ZPOOL_PROP_FAILUREMODE:
659 error = nvpair_value_uint64(elem, &intval);
660 if (!error && intval > ZIO_FAILURE_MODE_PANIC)
661 error = SET_ERROR(EINVAL);
662
663 /*
664 * This is a special case which only occurs when
665 * the pool has completely failed. This allows
666 * the user to change the in-core failmode property
667 * without syncing it out to disk (I/Os might
668 * currently be blocked). We do this by returning
669 * EIO to the caller (spa_prop_set) to trick it
670 * into thinking we encountered a property validation
671 * error.
672 */
673 if (!error && spa_suspended(spa)) {
674 spa->spa_failmode = intval;
675 error = SET_ERROR(EIO);
676 }
677 break;
678
679 case ZPOOL_PROP_CACHEFILE:
680 if ((error = nvpair_value_string(elem, &strval)) != 0)
681 break;
682
683 if (strval[0] == '\0')
684 break;
685
686 if (strcmp(strval, "none") == 0)
687 break;
688
689 if (strval[0] != '/') {
690 error = SET_ERROR(EINVAL);
691 break;
692 }
693
694 slash = strrchr(strval, '/');
695 ASSERT(slash != NULL);
696
697 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
698 strcmp(slash, "/..") == 0)
699 error = SET_ERROR(EINVAL);
700 break;
701
702 case ZPOOL_PROP_COMMENT:
703 if ((error = nvpair_value_string(elem, &strval)) != 0)
704 break;
705 for (check = strval; *check != '\0'; check++) {
706 if (!isprint(*check)) {
707 error = SET_ERROR(EINVAL);
708 break;
709 }
710 }
711 if (strlen(strval) > ZPROP_MAX_COMMENT)
712 error = SET_ERROR(E2BIG);
713 break;
714
715 default:
716 break;
717 }
718
719 if (error)
720 break;
721 }
722
723 (void) nvlist_remove_all(props,
724 zpool_prop_to_name(ZPOOL_PROP_DEDUPDITTO));
725
726 if (!error && reset_bootfs) {
727 error = nvlist_remove(props,
728 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
729
730 if (!error) {
731 error = nvlist_add_uint64(props,
732 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
733 }
734 }
735
736 return (error);
737 }
738
739 void
spa_configfile_set(spa_t * spa,nvlist_t * nvp,boolean_t need_sync)740 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
741 {
742 char *cachefile;
743 spa_config_dirent_t *dp;
744
745 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
746 &cachefile) != 0)
747 return;
748
749 dp = kmem_alloc(sizeof (spa_config_dirent_t),
750 KM_SLEEP);
751
752 if (cachefile[0] == '\0')
753 dp->scd_path = spa_strdup(spa_config_path);
754 else if (strcmp(cachefile, "none") == 0)
755 dp->scd_path = NULL;
756 else
757 dp->scd_path = spa_strdup(cachefile);
758
759 list_insert_head(&spa->spa_config_list, dp);
760 if (need_sync)
761 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
762 }
763
764 int
spa_prop_set(spa_t * spa,nvlist_t * nvp)765 spa_prop_set(spa_t *spa, nvlist_t *nvp)
766 {
767 int error;
768 nvpair_t *elem = NULL;
769 boolean_t need_sync = B_FALSE;
770
771 if ((error = spa_prop_validate(spa, nvp)) != 0)
772 return (error);
773
774 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
775 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
776
777 if (prop == ZPOOL_PROP_CACHEFILE ||
778 prop == ZPOOL_PROP_ALTROOT ||
779 prop == ZPOOL_PROP_READONLY)
780 continue;
781
782 if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
783 uint64_t ver;
784
785 if (prop == ZPOOL_PROP_VERSION) {
786 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
787 } else {
788 ASSERT(zpool_prop_feature(nvpair_name(elem)));
789 ver = SPA_VERSION_FEATURES;
790 need_sync = B_TRUE;
791 }
792
793 /* Save time if the version is already set. */
794 if (ver == spa_version(spa))
795 continue;
796
797 /*
798 * In addition to the pool directory object, we might
799 * create the pool properties object, the features for
800 * read object, the features for write object, or the
801 * feature descriptions object.
802 */
803 error = dsl_sync_task(spa->spa_name, NULL,
804 spa_sync_version, &ver,
805 6, ZFS_SPACE_CHECK_RESERVED);
806 if (error)
807 return (error);
808 continue;
809 }
810
811 need_sync = B_TRUE;
812 break;
813 }
814
815 if (need_sync) {
816 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
817 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
818 }
819
820 return (0);
821 }
822
823 /*
824 * If the bootfs property value is dsobj, clear it.
825 */
826 void
spa_prop_clear_bootfs(spa_t * spa,uint64_t dsobj,dmu_tx_t * tx)827 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
828 {
829 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
830 VERIFY(zap_remove(spa->spa_meta_objset,
831 spa->spa_pool_props_object,
832 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
833 spa->spa_bootfs = 0;
834 }
835 }
836
837 static int
spa_change_guid_check(void * arg,dmu_tx_t * tx)838 spa_change_guid_check(void *arg, dmu_tx_t *tx)
839 {
840 uint64_t *newguid __maybe_unused = arg;
841 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
842 vdev_t *rvd = spa->spa_root_vdev;
843 uint64_t vdev_state;
844
845 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
846 int error = (spa_has_checkpoint(spa)) ?
847 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
848 return (SET_ERROR(error));
849 }
850
851 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
852 vdev_state = rvd->vdev_state;
853 spa_config_exit(spa, SCL_STATE, FTAG);
854
855 if (vdev_state != VDEV_STATE_HEALTHY)
856 return (SET_ERROR(ENXIO));
857
858 ASSERT3U(spa_guid(spa), !=, *newguid);
859
860 return (0);
861 }
862
863 static void
spa_change_guid_sync(void * arg,dmu_tx_t * tx)864 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
865 {
866 uint64_t *newguid = arg;
867 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
868 uint64_t oldguid;
869 vdev_t *rvd = spa->spa_root_vdev;
870
871 oldguid = spa_guid(spa);
872
873 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
874 rvd->vdev_guid = *newguid;
875 rvd->vdev_guid_sum += (*newguid - oldguid);
876 vdev_config_dirty(rvd);
877 spa_config_exit(spa, SCL_STATE, FTAG);
878
879 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
880 (u_longlong_t)oldguid, (u_longlong_t)*newguid);
881 }
882
883 /*
884 * Change the GUID for the pool. This is done so that we can later
885 * re-import a pool built from a clone of our own vdevs. We will modify
886 * the root vdev's guid, our own pool guid, and then mark all of our
887 * vdevs dirty. Note that we must make sure that all our vdevs are
888 * online when we do this, or else any vdevs that weren't present
889 * would be orphaned from our pool. We are also going to issue a
890 * sysevent to update any watchers.
891 */
892 int
spa_change_guid(spa_t * spa)893 spa_change_guid(spa_t *spa)
894 {
895 int error;
896 uint64_t guid;
897
898 mutex_enter(&spa->spa_vdev_top_lock);
899 mutex_enter(&spa_namespace_lock);
900 guid = spa_generate_guid(NULL);
901
902 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
903 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
904
905 if (error == 0) {
906 spa_write_cachefile(spa, B_FALSE, B_TRUE);
907 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
908 }
909
910 mutex_exit(&spa_namespace_lock);
911 mutex_exit(&spa->spa_vdev_top_lock);
912
913 return (error);
914 }
915
916 /*
917 * ==========================================================================
918 * SPA state manipulation (open/create/destroy/import/export)
919 * ==========================================================================
920 */
921
922 static int
spa_error_entry_compare(const void * a,const void * b)923 spa_error_entry_compare(const void *a, const void *b)
924 {
925 const spa_error_entry_t *sa = (const spa_error_entry_t *)a;
926 const spa_error_entry_t *sb = (const spa_error_entry_t *)b;
927 int ret;
928
929 ret = memcmp(&sa->se_bookmark, &sb->se_bookmark,
930 sizeof (zbookmark_phys_t));
931
932 return (TREE_ISIGN(ret));
933 }
934
935 /*
936 * Utility function which retrieves copies of the current logs and
937 * re-initializes them in the process.
938 */
939 void
spa_get_errlists(spa_t * spa,avl_tree_t * last,avl_tree_t * scrub)940 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
941 {
942 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
943
944 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
945 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
946
947 avl_create(&spa->spa_errlist_scrub,
948 spa_error_entry_compare, sizeof (spa_error_entry_t),
949 offsetof(spa_error_entry_t, se_avl));
950 avl_create(&spa->spa_errlist_last,
951 spa_error_entry_compare, sizeof (spa_error_entry_t),
952 offsetof(spa_error_entry_t, se_avl));
953 }
954
955 static void
spa_taskqs_init(spa_t * spa,zio_type_t t,zio_taskq_type_t q)956 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
957 {
958 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
959 enum zti_modes mode = ztip->zti_mode;
960 uint_t value = ztip->zti_value;
961 uint_t count = ztip->zti_count;
962 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
963 uint_t cpus, flags = TASKQ_DYNAMIC;
964 boolean_t batch = B_FALSE;
965
966 switch (mode) {
967 case ZTI_MODE_FIXED:
968 ASSERT3U(value, >, 0);
969 break;
970
971 case ZTI_MODE_BATCH:
972 batch = B_TRUE;
973 flags |= TASKQ_THREADS_CPU_PCT;
974 value = MIN(zio_taskq_batch_pct, 100);
975 break;
976
977 case ZTI_MODE_SCALE:
978 flags |= TASKQ_THREADS_CPU_PCT;
979 /*
980 * We want more taskqs to reduce lock contention, but we want
981 * less for better request ordering and CPU utilization.
982 */
983 cpus = MAX(1, boot_ncpus * zio_taskq_batch_pct / 100);
984 if (zio_taskq_batch_tpq > 0) {
985 count = MAX(1, (cpus + zio_taskq_batch_tpq / 2) /
986 zio_taskq_batch_tpq);
987 } else {
988 /*
989 * Prefer 6 threads per taskq, but no more taskqs
990 * than threads in them on large systems. For 80%:
991 *
992 * taskq taskq total
993 * cpus taskqs percent threads threads
994 * ------- ------- ------- ------- -------
995 * 1 1 80% 1 1
996 * 2 1 80% 1 1
997 * 4 1 80% 3 3
998 * 8 2 40% 3 6
999 * 16 3 27% 4 12
1000 * 32 5 16% 5 25
1001 * 64 7 11% 7 49
1002 * 128 10 8% 10 100
1003 * 256 14 6% 15 210
1004 */
1005 count = 1 + cpus / 6;
1006 while (count * count > cpus)
1007 count--;
1008 }
1009 /* Limit each taskq within 100% to not trigger assertion. */
1010 count = MAX(count, (zio_taskq_batch_pct + 99) / 100);
1011 value = (zio_taskq_batch_pct + count / 2) / count;
1012 break;
1013
1014 case ZTI_MODE_NULL:
1015 tqs->stqs_count = 0;
1016 tqs->stqs_taskq = NULL;
1017 return;
1018
1019 default:
1020 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
1021 "spa_activate()",
1022 zio_type_name[t], zio_taskq_types[q], mode, value);
1023 break;
1024 }
1025
1026 ASSERT3U(count, >, 0);
1027 tqs->stqs_count = count;
1028 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
1029
1030 for (uint_t i = 0; i < count; i++) {
1031 taskq_t *tq;
1032 char name[32];
1033
1034 if (count > 1)
1035 (void) snprintf(name, sizeof (name), "%s_%s_%u",
1036 zio_type_name[t], zio_taskq_types[q], i);
1037 else
1038 (void) snprintf(name, sizeof (name), "%s_%s",
1039 zio_type_name[t], zio_taskq_types[q]);
1040
1041 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
1042 if (batch)
1043 flags |= TASKQ_DC_BATCH;
1044
1045 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
1046 spa->spa_proc, zio_taskq_basedc, flags);
1047 } else {
1048 pri_t pri = maxclsyspri;
1049 /*
1050 * The write issue taskq can be extremely CPU
1051 * intensive. Run it at slightly less important
1052 * priority than the other taskqs.
1053 *
1054 * Under Linux and FreeBSD this means incrementing
1055 * the priority value as opposed to platforms like
1056 * illumos where it should be decremented.
1057 *
1058 * On FreeBSD, if priorities divided by four (RQ_PPQ)
1059 * are equal then a difference between them is
1060 * insignificant.
1061 */
1062 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE) {
1063 #if defined(__linux__)
1064 pri++;
1065 #elif defined(__FreeBSD__)
1066 pri += 4;
1067 #else
1068 #error "unknown OS"
1069 #endif
1070 }
1071 tq = taskq_create_proc(name, value, pri, 50,
1072 INT_MAX, spa->spa_proc, flags);
1073 }
1074
1075 tqs->stqs_taskq[i] = tq;
1076 }
1077 }
1078
1079 static void
spa_taskqs_fini(spa_t * spa,zio_type_t t,zio_taskq_type_t q)1080 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1081 {
1082 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1083
1084 if (tqs->stqs_taskq == NULL) {
1085 ASSERT3U(tqs->stqs_count, ==, 0);
1086 return;
1087 }
1088
1089 for (uint_t i = 0; i < tqs->stqs_count; i++) {
1090 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1091 taskq_destroy(tqs->stqs_taskq[i]);
1092 }
1093
1094 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1095 tqs->stqs_taskq = NULL;
1096 }
1097
1098 /*
1099 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1100 * Note that a type may have multiple discrete taskqs to avoid lock contention
1101 * on the taskq itself. In that case we choose which taskq at random by using
1102 * the low bits of gethrtime().
1103 */
1104 void
spa_taskq_dispatch_ent(spa_t * spa,zio_type_t t,zio_taskq_type_t q,task_func_t * func,void * arg,uint_t flags,taskq_ent_t * ent)1105 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1106 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1107 {
1108 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1109 taskq_t *tq;
1110
1111 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1112 ASSERT3U(tqs->stqs_count, !=, 0);
1113
1114 if (tqs->stqs_count == 1) {
1115 tq = tqs->stqs_taskq[0];
1116 } else {
1117 tq = tqs->stqs_taskq[((uint64_t)gethrtime()) % tqs->stqs_count];
1118 }
1119
1120 taskq_dispatch_ent(tq, func, arg, flags, ent);
1121 }
1122
1123 /*
1124 * Same as spa_taskq_dispatch_ent() but block on the task until completion.
1125 */
1126 void
spa_taskq_dispatch_sync(spa_t * spa,zio_type_t t,zio_taskq_type_t q,task_func_t * func,void * arg,uint_t flags)1127 spa_taskq_dispatch_sync(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1128 task_func_t *func, void *arg, uint_t flags)
1129 {
1130 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1131 taskq_t *tq;
1132 taskqid_t id;
1133
1134 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1135 ASSERT3U(tqs->stqs_count, !=, 0);
1136
1137 if (tqs->stqs_count == 1) {
1138 tq = tqs->stqs_taskq[0];
1139 } else {
1140 tq = tqs->stqs_taskq[((uint64_t)gethrtime()) % tqs->stqs_count];
1141 }
1142
1143 id = taskq_dispatch(tq, func, arg, flags);
1144 if (id)
1145 taskq_wait_id(tq, id);
1146 }
1147
1148 static void
spa_create_zio_taskqs(spa_t * spa)1149 spa_create_zio_taskqs(spa_t *spa)
1150 {
1151 for (int t = 0; t < ZIO_TYPES; t++) {
1152 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1153 spa_taskqs_init(spa, t, q);
1154 }
1155 }
1156 }
1157
1158 /*
1159 * Disabled until spa_thread() can be adapted for Linux.
1160 */
1161 #undef HAVE_SPA_THREAD
1162
1163 #if defined(_KERNEL) && defined(HAVE_SPA_THREAD)
1164 static void
spa_thread(void * arg)1165 spa_thread(void *arg)
1166 {
1167 psetid_t zio_taskq_psrset_bind = PS_NONE;
1168 callb_cpr_t cprinfo;
1169
1170 spa_t *spa = arg;
1171 user_t *pu = PTOU(curproc);
1172
1173 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1174 spa->spa_name);
1175
1176 ASSERT(curproc != &p0);
1177 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1178 "zpool-%s", spa->spa_name);
1179 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1180
1181 /* bind this thread to the requested psrset */
1182 if (zio_taskq_psrset_bind != PS_NONE) {
1183 pool_lock();
1184 mutex_enter(&cpu_lock);
1185 mutex_enter(&pidlock);
1186 mutex_enter(&curproc->p_lock);
1187
1188 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1189 0, NULL, NULL) == 0) {
1190 curthread->t_bind_pset = zio_taskq_psrset_bind;
1191 } else {
1192 cmn_err(CE_WARN,
1193 "Couldn't bind process for zfs pool \"%s\" to "
1194 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1195 }
1196
1197 mutex_exit(&curproc->p_lock);
1198 mutex_exit(&pidlock);
1199 mutex_exit(&cpu_lock);
1200 pool_unlock();
1201 }
1202
1203 if (zio_taskq_sysdc) {
1204 sysdc_thread_enter(curthread, 100, 0);
1205 }
1206
1207 spa->spa_proc = curproc;
1208 spa->spa_did = curthread->t_did;
1209
1210 spa_create_zio_taskqs(spa);
1211
1212 mutex_enter(&spa->spa_proc_lock);
1213 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1214
1215 spa->spa_proc_state = SPA_PROC_ACTIVE;
1216 cv_broadcast(&spa->spa_proc_cv);
1217
1218 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1219 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1220 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1221 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1222
1223 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1224 spa->spa_proc_state = SPA_PROC_GONE;
1225 spa->spa_proc = &p0;
1226 cv_broadcast(&spa->spa_proc_cv);
1227 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1228
1229 mutex_enter(&curproc->p_lock);
1230 lwp_exit();
1231 }
1232 #endif
1233
1234 /*
1235 * Activate an uninitialized pool.
1236 */
1237 static void
spa_activate(spa_t * spa,spa_mode_t mode)1238 spa_activate(spa_t *spa, spa_mode_t mode)
1239 {
1240 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1241
1242 spa->spa_state = POOL_STATE_ACTIVE;
1243 spa->spa_mode = mode;
1244
1245 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1246 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1247 spa->spa_embedded_log_class =
1248 metaslab_class_create(spa, zfs_metaslab_ops);
1249 spa->spa_special_class = metaslab_class_create(spa, zfs_metaslab_ops);
1250 spa->spa_dedup_class = metaslab_class_create(spa, zfs_metaslab_ops);
1251
1252 /* Try to create a covering process */
1253 mutex_enter(&spa->spa_proc_lock);
1254 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1255 ASSERT(spa->spa_proc == &p0);
1256 spa->spa_did = 0;
1257
1258 #ifdef HAVE_SPA_THREAD
1259 /* Only create a process if we're going to be around a while. */
1260 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1261 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1262 NULL, 0) == 0) {
1263 spa->spa_proc_state = SPA_PROC_CREATED;
1264 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1265 cv_wait(&spa->spa_proc_cv,
1266 &spa->spa_proc_lock);
1267 }
1268 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1269 ASSERT(spa->spa_proc != &p0);
1270 ASSERT(spa->spa_did != 0);
1271 } else {
1272 #ifdef _KERNEL
1273 cmn_err(CE_WARN,
1274 "Couldn't create process for zfs pool \"%s\"\n",
1275 spa->spa_name);
1276 #endif
1277 }
1278 }
1279 #endif /* HAVE_SPA_THREAD */
1280 mutex_exit(&spa->spa_proc_lock);
1281
1282 /* If we didn't create a process, we need to create our taskqs. */
1283 if (spa->spa_proc == &p0) {
1284 spa_create_zio_taskqs(spa);
1285 }
1286
1287 for (size_t i = 0; i < TXG_SIZE; i++) {
1288 spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL,
1289 ZIO_FLAG_CANFAIL);
1290 }
1291
1292 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1293 offsetof(vdev_t, vdev_config_dirty_node));
1294 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1295 offsetof(objset_t, os_evicting_node));
1296 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1297 offsetof(vdev_t, vdev_state_dirty_node));
1298
1299 txg_list_create(&spa->spa_vdev_txg_list, spa,
1300 offsetof(struct vdev, vdev_txg_node));
1301
1302 avl_create(&spa->spa_errlist_scrub,
1303 spa_error_entry_compare, sizeof (spa_error_entry_t),
1304 offsetof(spa_error_entry_t, se_avl));
1305 avl_create(&spa->spa_errlist_last,
1306 spa_error_entry_compare, sizeof (spa_error_entry_t),
1307 offsetof(spa_error_entry_t, se_avl));
1308
1309 spa_keystore_init(&spa->spa_keystore);
1310
1311 /*
1312 * This taskq is used to perform zvol-minor-related tasks
1313 * asynchronously. This has several advantages, including easy
1314 * resolution of various deadlocks.
1315 *
1316 * The taskq must be single threaded to ensure tasks are always
1317 * processed in the order in which they were dispatched.
1318 *
1319 * A taskq per pool allows one to keep the pools independent.
1320 * This way if one pool is suspended, it will not impact another.
1321 *
1322 * The preferred location to dispatch a zvol minor task is a sync
1323 * task. In this context, there is easy access to the spa_t and minimal
1324 * error handling is required because the sync task must succeed.
1325 */
1326 spa->spa_zvol_taskq = taskq_create("z_zvol", 1, defclsyspri,
1327 1, INT_MAX, 0);
1328
1329 /*
1330 * Taskq dedicated to prefetcher threads: this is used to prevent the
1331 * pool traverse code from monopolizing the global (and limited)
1332 * system_taskq by inappropriately scheduling long running tasks on it.
1333 */
1334 spa->spa_prefetch_taskq = taskq_create("z_prefetch", 100,
1335 defclsyspri, 1, INT_MAX, TASKQ_DYNAMIC | TASKQ_THREADS_CPU_PCT);
1336
1337 /*
1338 * The taskq to upgrade datasets in this pool. Currently used by
1339 * feature SPA_FEATURE_USEROBJ_ACCOUNTING/SPA_FEATURE_PROJECT_QUOTA.
1340 */
1341 spa->spa_upgrade_taskq = taskq_create("z_upgrade", 100,
1342 defclsyspri, 1, INT_MAX, TASKQ_DYNAMIC | TASKQ_THREADS_CPU_PCT);
1343 }
1344
1345 /*
1346 * Opposite of spa_activate().
1347 */
1348 static void
spa_deactivate(spa_t * spa)1349 spa_deactivate(spa_t *spa)
1350 {
1351 ASSERT(spa->spa_sync_on == B_FALSE);
1352 ASSERT(spa->spa_dsl_pool == NULL);
1353 ASSERT(spa->spa_root_vdev == NULL);
1354 ASSERT(spa->spa_async_zio_root == NULL);
1355 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1356
1357 spa_evicting_os_wait(spa);
1358
1359 if (spa->spa_zvol_taskq) {
1360 taskq_destroy(spa->spa_zvol_taskq);
1361 spa->spa_zvol_taskq = NULL;
1362 }
1363
1364 if (spa->spa_prefetch_taskq) {
1365 taskq_destroy(spa->spa_prefetch_taskq);
1366 spa->spa_prefetch_taskq = NULL;
1367 }
1368
1369 if (spa->spa_upgrade_taskq) {
1370 taskq_destroy(spa->spa_upgrade_taskq);
1371 spa->spa_upgrade_taskq = NULL;
1372 }
1373
1374 txg_list_destroy(&spa->spa_vdev_txg_list);
1375
1376 list_destroy(&spa->spa_config_dirty_list);
1377 list_destroy(&spa->spa_evicting_os_list);
1378 list_destroy(&spa->spa_state_dirty_list);
1379
1380 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
1381
1382 for (int t = 0; t < ZIO_TYPES; t++) {
1383 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1384 spa_taskqs_fini(spa, t, q);
1385 }
1386 }
1387
1388 for (size_t i = 0; i < TXG_SIZE; i++) {
1389 ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1390 VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1391 spa->spa_txg_zio[i] = NULL;
1392 }
1393
1394 metaslab_class_destroy(spa->spa_normal_class);
1395 spa->spa_normal_class = NULL;
1396
1397 metaslab_class_destroy(spa->spa_log_class);
1398 spa->spa_log_class = NULL;
1399
1400 metaslab_class_destroy(spa->spa_embedded_log_class);
1401 spa->spa_embedded_log_class = NULL;
1402
1403 metaslab_class_destroy(spa->spa_special_class);
1404 spa->spa_special_class = NULL;
1405
1406 metaslab_class_destroy(spa->spa_dedup_class);
1407 spa->spa_dedup_class = NULL;
1408
1409 /*
1410 * If this was part of an import or the open otherwise failed, we may
1411 * still have errors left in the queues. Empty them just in case.
1412 */
1413 spa_errlog_drain(spa);
1414 avl_destroy(&spa->spa_errlist_scrub);
1415 avl_destroy(&spa->spa_errlist_last);
1416
1417 spa_keystore_fini(&spa->spa_keystore);
1418
1419 spa->spa_state = POOL_STATE_UNINITIALIZED;
1420
1421 mutex_enter(&spa->spa_proc_lock);
1422 if (spa->spa_proc_state != SPA_PROC_NONE) {
1423 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1424 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1425 cv_broadcast(&spa->spa_proc_cv);
1426 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1427 ASSERT(spa->spa_proc != &p0);
1428 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1429 }
1430 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1431 spa->spa_proc_state = SPA_PROC_NONE;
1432 }
1433 ASSERT(spa->spa_proc == &p0);
1434 mutex_exit(&spa->spa_proc_lock);
1435
1436 /*
1437 * We want to make sure spa_thread() has actually exited the ZFS
1438 * module, so that the module can't be unloaded out from underneath
1439 * it.
1440 */
1441 if (spa->spa_did != 0) {
1442 thread_join(spa->spa_did);
1443 spa->spa_did = 0;
1444 }
1445 }
1446
1447 /*
1448 * Verify a pool configuration, and construct the vdev tree appropriately. This
1449 * will create all the necessary vdevs in the appropriate layout, with each vdev
1450 * in the CLOSED state. This will prep the pool before open/creation/import.
1451 * All vdev validation is done by the vdev_alloc() routine.
1452 */
1453 int
spa_config_parse(spa_t * spa,vdev_t ** vdp,nvlist_t * nv,vdev_t * parent,uint_t id,int atype)1454 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1455 uint_t id, int atype)
1456 {
1457 nvlist_t **child;
1458 uint_t children;
1459 int error;
1460
1461 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1462 return (error);
1463
1464 if ((*vdp)->vdev_ops->vdev_op_leaf)
1465 return (0);
1466
1467 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1468 &child, &children);
1469
1470 if (error == ENOENT)
1471 return (0);
1472
1473 if (error) {
1474 vdev_free(*vdp);
1475 *vdp = NULL;
1476 return (SET_ERROR(EINVAL));
1477 }
1478
1479 for (int c = 0; c < children; c++) {
1480 vdev_t *vd;
1481 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1482 atype)) != 0) {
1483 vdev_free(*vdp);
1484 *vdp = NULL;
1485 return (error);
1486 }
1487 }
1488
1489 ASSERT(*vdp != NULL);
1490
1491 return (0);
1492 }
1493
1494 static boolean_t
spa_should_flush_logs_on_unload(spa_t * spa)1495 spa_should_flush_logs_on_unload(spa_t *spa)
1496 {
1497 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
1498 return (B_FALSE);
1499
1500 if (!spa_writeable(spa))
1501 return (B_FALSE);
1502
1503 if (!spa->spa_sync_on)
1504 return (B_FALSE);
1505
1506 if (spa_state(spa) != POOL_STATE_EXPORTED)
1507 return (B_FALSE);
1508
1509 if (zfs_keep_log_spacemaps_at_export)
1510 return (B_FALSE);
1511
1512 return (B_TRUE);
1513 }
1514
1515 /*
1516 * Opens a transaction that will set the flag that will instruct
1517 * spa_sync to attempt to flush all the metaslabs for that txg.
1518 */
1519 static void
spa_unload_log_sm_flush_all(spa_t * spa)1520 spa_unload_log_sm_flush_all(spa_t *spa)
1521 {
1522 dmu_tx_t *tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
1523 VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
1524
1525 ASSERT3U(spa->spa_log_flushall_txg, ==, 0);
1526 spa->spa_log_flushall_txg = dmu_tx_get_txg(tx);
1527
1528 dmu_tx_commit(tx);
1529 txg_wait_synced(spa_get_dsl(spa), spa->spa_log_flushall_txg);
1530 }
1531
1532 static void
spa_unload_log_sm_metadata(spa_t * spa)1533 spa_unload_log_sm_metadata(spa_t *spa)
1534 {
1535 void *cookie = NULL;
1536 spa_log_sm_t *sls;
1537 while ((sls = avl_destroy_nodes(&spa->spa_sm_logs_by_txg,
1538 &cookie)) != NULL) {
1539 VERIFY0(sls->sls_mscount);
1540 kmem_free(sls, sizeof (spa_log_sm_t));
1541 }
1542
1543 for (log_summary_entry_t *e = list_head(&spa->spa_log_summary);
1544 e != NULL; e = list_head(&spa->spa_log_summary)) {
1545 VERIFY0(e->lse_mscount);
1546 list_remove(&spa->spa_log_summary, e);
1547 kmem_free(e, sizeof (log_summary_entry_t));
1548 }
1549
1550 spa->spa_unflushed_stats.sus_nblocks = 0;
1551 spa->spa_unflushed_stats.sus_memused = 0;
1552 spa->spa_unflushed_stats.sus_blocklimit = 0;
1553 }
1554
1555 static void
spa_destroy_aux_threads(spa_t * spa)1556 spa_destroy_aux_threads(spa_t *spa)
1557 {
1558 if (spa->spa_condense_zthr != NULL) {
1559 zthr_destroy(spa->spa_condense_zthr);
1560 spa->spa_condense_zthr = NULL;
1561 }
1562 if (spa->spa_checkpoint_discard_zthr != NULL) {
1563 zthr_destroy(spa->spa_checkpoint_discard_zthr);
1564 spa->spa_checkpoint_discard_zthr = NULL;
1565 }
1566 if (spa->spa_livelist_delete_zthr != NULL) {
1567 zthr_destroy(spa->spa_livelist_delete_zthr);
1568 spa->spa_livelist_delete_zthr = NULL;
1569 }
1570 if (spa->spa_livelist_condense_zthr != NULL) {
1571 zthr_destroy(spa->spa_livelist_condense_zthr);
1572 spa->spa_livelist_condense_zthr = NULL;
1573 }
1574 }
1575
1576 /*
1577 * Opposite of spa_load().
1578 */
1579 static void
spa_unload(spa_t * spa)1580 spa_unload(spa_t *spa)
1581 {
1582 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1583 ASSERT(spa_state(spa) != POOL_STATE_UNINITIALIZED);
1584
1585 spa_import_progress_remove(spa_guid(spa));
1586 spa_load_note(spa, "UNLOADING");
1587
1588 spa_wake_waiters(spa);
1589
1590 /*
1591 * If we have set the spa_final_txg, we have already performed the
1592 * tasks below in spa_export_common(). We should not redo it here since
1593 * we delay the final TXGs beyond what spa_final_txg is set at.
1594 */
1595 if (spa->spa_final_txg == UINT64_MAX) {
1596 /*
1597 * If the log space map feature is enabled and the pool is
1598 * getting exported (but not destroyed), we want to spend some
1599 * time flushing as many metaslabs as we can in an attempt to
1600 * destroy log space maps and save import time.
1601 */
1602 if (spa_should_flush_logs_on_unload(spa))
1603 spa_unload_log_sm_flush_all(spa);
1604
1605 /*
1606 * Stop async tasks.
1607 */
1608 spa_async_suspend(spa);
1609
1610 if (spa->spa_root_vdev) {
1611 vdev_t *root_vdev = spa->spa_root_vdev;
1612 vdev_initialize_stop_all(root_vdev,
1613 VDEV_INITIALIZE_ACTIVE);
1614 vdev_trim_stop_all(root_vdev, VDEV_TRIM_ACTIVE);
1615 vdev_autotrim_stop_all(spa);
1616 vdev_rebuild_stop_all(spa);
1617 }
1618 }
1619
1620 /*
1621 * Stop syncing.
1622 */
1623 if (spa->spa_sync_on) {
1624 txg_sync_stop(spa->spa_dsl_pool);
1625 spa->spa_sync_on = B_FALSE;
1626 }
1627
1628 /*
1629 * This ensures that there is no async metaslab prefetching
1630 * while we attempt to unload the spa.
1631 */
1632 if (spa->spa_root_vdev != NULL) {
1633 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++) {
1634 vdev_t *vc = spa->spa_root_vdev->vdev_child[c];
1635 if (vc->vdev_mg != NULL)
1636 taskq_wait(vc->vdev_mg->mg_taskq);
1637 }
1638 }
1639
1640 if (spa->spa_mmp.mmp_thread)
1641 mmp_thread_stop(spa);
1642
1643 /*
1644 * Wait for any outstanding async I/O to complete.
1645 */
1646 if (spa->spa_async_zio_root != NULL) {
1647 for (int i = 0; i < max_ncpus; i++)
1648 (void) zio_wait(spa->spa_async_zio_root[i]);
1649 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1650 spa->spa_async_zio_root = NULL;
1651 }
1652
1653 if (spa->spa_vdev_removal != NULL) {
1654 spa_vdev_removal_destroy(spa->spa_vdev_removal);
1655 spa->spa_vdev_removal = NULL;
1656 }
1657
1658 spa_destroy_aux_threads(spa);
1659
1660 spa_condense_fini(spa);
1661
1662 bpobj_close(&spa->spa_deferred_bpobj);
1663
1664 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1665
1666 /*
1667 * Close all vdevs.
1668 */
1669 if (spa->spa_root_vdev)
1670 vdev_free(spa->spa_root_vdev);
1671 ASSERT(spa->spa_root_vdev == NULL);
1672
1673 /*
1674 * Close the dsl pool.
1675 */
1676 if (spa->spa_dsl_pool) {
1677 dsl_pool_close(spa->spa_dsl_pool);
1678 spa->spa_dsl_pool = NULL;
1679 spa->spa_meta_objset = NULL;
1680 }
1681
1682 ddt_unload(spa);
1683 spa_unload_log_sm_metadata(spa);
1684
1685 /*
1686 * Drop and purge level 2 cache
1687 */
1688 spa_l2cache_drop(spa);
1689
1690 for (int i = 0; i < spa->spa_spares.sav_count; i++)
1691 vdev_free(spa->spa_spares.sav_vdevs[i]);
1692 if (spa->spa_spares.sav_vdevs) {
1693 kmem_free(spa->spa_spares.sav_vdevs,
1694 spa->spa_spares.sav_count * sizeof (void *));
1695 spa->spa_spares.sav_vdevs = NULL;
1696 }
1697 if (spa->spa_spares.sav_config) {
1698 nvlist_free(spa->spa_spares.sav_config);
1699 spa->spa_spares.sav_config = NULL;
1700 }
1701 spa->spa_spares.sav_count = 0;
1702
1703 for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
1704 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1705 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1706 }
1707 if (spa->spa_l2cache.sav_vdevs) {
1708 kmem_free(spa->spa_l2cache.sav_vdevs,
1709 spa->spa_l2cache.sav_count * sizeof (void *));
1710 spa->spa_l2cache.sav_vdevs = NULL;
1711 }
1712 if (spa->spa_l2cache.sav_config) {
1713 nvlist_free(spa->spa_l2cache.sav_config);
1714 spa->spa_l2cache.sav_config = NULL;
1715 }
1716 spa->spa_l2cache.sav_count = 0;
1717
1718 spa->spa_async_suspended = 0;
1719
1720 spa->spa_indirect_vdevs_loaded = B_FALSE;
1721
1722 if (spa->spa_comment != NULL) {
1723 spa_strfree(spa->spa_comment);
1724 spa->spa_comment = NULL;
1725 }
1726 if (spa->spa_compatibility != NULL) {
1727 spa_strfree(spa->spa_compatibility);
1728 spa->spa_compatibility = NULL;
1729 }
1730
1731 spa_config_exit(spa, SCL_ALL, spa);
1732 }
1733
1734 /*
1735 * Load (or re-load) the current list of vdevs describing the active spares for
1736 * this pool. When this is called, we have some form of basic information in
1737 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1738 * then re-generate a more complete list including status information.
1739 */
1740 void
spa_load_spares(spa_t * spa)1741 spa_load_spares(spa_t *spa)
1742 {
1743 nvlist_t **spares;
1744 uint_t nspares;
1745 int i;
1746 vdev_t *vd, *tvd;
1747
1748 #ifndef _KERNEL
1749 /*
1750 * zdb opens both the current state of the pool and the
1751 * checkpointed state (if present), with a different spa_t.
1752 *
1753 * As spare vdevs are shared among open pools, we skip loading
1754 * them when we load the checkpointed state of the pool.
1755 */
1756 if (!spa_writeable(spa))
1757 return;
1758 #endif
1759
1760 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1761
1762 /*
1763 * First, close and free any existing spare vdevs.
1764 */
1765 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1766 vd = spa->spa_spares.sav_vdevs[i];
1767
1768 /* Undo the call to spa_activate() below */
1769 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1770 B_FALSE)) != NULL && tvd->vdev_isspare)
1771 spa_spare_remove(tvd);
1772 vdev_close(vd);
1773 vdev_free(vd);
1774 }
1775
1776 if (spa->spa_spares.sav_vdevs)
1777 kmem_free(spa->spa_spares.sav_vdevs,
1778 spa->spa_spares.sav_count * sizeof (void *));
1779
1780 if (spa->spa_spares.sav_config == NULL)
1781 nspares = 0;
1782 else
1783 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1784 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1785
1786 spa->spa_spares.sav_count = (int)nspares;
1787 spa->spa_spares.sav_vdevs = NULL;
1788
1789 if (nspares == 0)
1790 return;
1791
1792 /*
1793 * Construct the array of vdevs, opening them to get status in the
1794 * process. For each spare, there is potentially two different vdev_t
1795 * structures associated with it: one in the list of spares (used only
1796 * for basic validation purposes) and one in the active vdev
1797 * configuration (if it's spared in). During this phase we open and
1798 * validate each vdev on the spare list. If the vdev also exists in the
1799 * active configuration, then we also mark this vdev as an active spare.
1800 */
1801 spa->spa_spares.sav_vdevs = kmem_zalloc(nspares * sizeof (void *),
1802 KM_SLEEP);
1803 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1804 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1805 VDEV_ALLOC_SPARE) == 0);
1806 ASSERT(vd != NULL);
1807
1808 spa->spa_spares.sav_vdevs[i] = vd;
1809
1810 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1811 B_FALSE)) != NULL) {
1812 if (!tvd->vdev_isspare)
1813 spa_spare_add(tvd);
1814
1815 /*
1816 * We only mark the spare active if we were successfully
1817 * able to load the vdev. Otherwise, importing a pool
1818 * with a bad active spare would result in strange
1819 * behavior, because multiple pool would think the spare
1820 * is actively in use.
1821 *
1822 * There is a vulnerability here to an equally bizarre
1823 * circumstance, where a dead active spare is later
1824 * brought back to life (onlined or otherwise). Given
1825 * the rarity of this scenario, and the extra complexity
1826 * it adds, we ignore the possibility.
1827 */
1828 if (!vdev_is_dead(tvd))
1829 spa_spare_activate(tvd);
1830 }
1831
1832 vd->vdev_top = vd;
1833 vd->vdev_aux = &spa->spa_spares;
1834
1835 if (vdev_open(vd) != 0)
1836 continue;
1837
1838 if (vdev_validate_aux(vd) == 0)
1839 spa_spare_add(vd);
1840 }
1841
1842 /*
1843 * Recompute the stashed list of spares, with status information
1844 * this time.
1845 */
1846 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1847 DATA_TYPE_NVLIST_ARRAY) == 0);
1848
1849 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1850 KM_SLEEP);
1851 for (i = 0; i < spa->spa_spares.sav_count; i++)
1852 spares[i] = vdev_config_generate(spa,
1853 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1854 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1855 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1856 for (i = 0; i < spa->spa_spares.sav_count; i++)
1857 nvlist_free(spares[i]);
1858 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1859 }
1860
1861 /*
1862 * Load (or re-load) the current list of vdevs describing the active l2cache for
1863 * this pool. When this is called, we have some form of basic information in
1864 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1865 * then re-generate a more complete list including status information.
1866 * Devices which are already active have their details maintained, and are
1867 * not re-opened.
1868 */
1869 void
spa_load_l2cache(spa_t * spa)1870 spa_load_l2cache(spa_t *spa)
1871 {
1872 nvlist_t **l2cache = NULL;
1873 uint_t nl2cache;
1874 int i, j, oldnvdevs;
1875 uint64_t guid;
1876 vdev_t *vd, **oldvdevs, **newvdevs;
1877 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1878
1879 #ifndef _KERNEL
1880 /*
1881 * zdb opens both the current state of the pool and the
1882 * checkpointed state (if present), with a different spa_t.
1883 *
1884 * As L2 caches are part of the ARC which is shared among open
1885 * pools, we skip loading them when we load the checkpointed
1886 * state of the pool.
1887 */
1888 if (!spa_writeable(spa))
1889 return;
1890 #endif
1891
1892 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1893
1894 oldvdevs = sav->sav_vdevs;
1895 oldnvdevs = sav->sav_count;
1896 sav->sav_vdevs = NULL;
1897 sav->sav_count = 0;
1898
1899 if (sav->sav_config == NULL) {
1900 nl2cache = 0;
1901 newvdevs = NULL;
1902 goto out;
1903 }
1904
1905 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1906 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1907 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1908
1909 /*
1910 * Process new nvlist of vdevs.
1911 */
1912 for (i = 0; i < nl2cache; i++) {
1913 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1914 &guid) == 0);
1915
1916 newvdevs[i] = NULL;
1917 for (j = 0; j < oldnvdevs; j++) {
1918 vd = oldvdevs[j];
1919 if (vd != NULL && guid == vd->vdev_guid) {
1920 /*
1921 * Retain previous vdev for add/remove ops.
1922 */
1923 newvdevs[i] = vd;
1924 oldvdevs[j] = NULL;
1925 break;
1926 }
1927 }
1928
1929 if (newvdevs[i] == NULL) {
1930 /*
1931 * Create new vdev
1932 */
1933 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1934 VDEV_ALLOC_L2CACHE) == 0);
1935 ASSERT(vd != NULL);
1936 newvdevs[i] = vd;
1937
1938 /*
1939 * Commit this vdev as an l2cache device,
1940 * even if it fails to open.
1941 */
1942 spa_l2cache_add(vd);
1943
1944 vd->vdev_top = vd;
1945 vd->vdev_aux = sav;
1946
1947 spa_l2cache_activate(vd);
1948
1949 if (vdev_open(vd) != 0)
1950 continue;
1951
1952 (void) vdev_validate_aux(vd);
1953
1954 if (!vdev_is_dead(vd))
1955 l2arc_add_vdev(spa, vd);
1956
1957 /*
1958 * Upon cache device addition to a pool or pool
1959 * creation with a cache device or if the header
1960 * of the device is invalid we issue an async
1961 * TRIM command for the whole device which will
1962 * execute if l2arc_trim_ahead > 0.
1963 */
1964 spa_async_request(spa, SPA_ASYNC_L2CACHE_TRIM);
1965 }
1966 }
1967
1968 sav->sav_vdevs = newvdevs;
1969 sav->sav_count = (int)nl2cache;
1970
1971 /*
1972 * Recompute the stashed list of l2cache devices, with status
1973 * information this time.
1974 */
1975 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1976 DATA_TYPE_NVLIST_ARRAY) == 0);
1977
1978 if (sav->sav_count > 0)
1979 l2cache = kmem_alloc(sav->sav_count * sizeof (void *),
1980 KM_SLEEP);
1981 for (i = 0; i < sav->sav_count; i++)
1982 l2cache[i] = vdev_config_generate(spa,
1983 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1984 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1985 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1986
1987 out:
1988 /*
1989 * Purge vdevs that were dropped
1990 */
1991 for (i = 0; i < oldnvdevs; i++) {
1992 uint64_t pool;
1993
1994 vd = oldvdevs[i];
1995 if (vd != NULL) {
1996 ASSERT(vd->vdev_isl2cache);
1997
1998 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1999 pool != 0ULL && l2arc_vdev_present(vd))
2000 l2arc_remove_vdev(vd);
2001 vdev_clear_stats(vd);
2002 vdev_free(vd);
2003 }
2004 }
2005
2006 if (oldvdevs)
2007 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
2008
2009 for (i = 0; i < sav->sav_count; i++)
2010 nvlist_free(l2cache[i]);
2011 if (sav->sav_count)
2012 kmem_free(l2cache, sav->sav_count * sizeof (void *));
2013 }
2014
2015 static int
load_nvlist(spa_t * spa,uint64_t obj,nvlist_t ** value)2016 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
2017 {
2018 dmu_buf_t *db;
2019 char *packed = NULL;
2020 size_t nvsize = 0;
2021 int error;
2022 *value = NULL;
2023
2024 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
2025 if (error)
2026 return (error);
2027
2028 nvsize = *(uint64_t *)db->db_data;
2029 dmu_buf_rele(db, FTAG);
2030
2031 packed = vmem_alloc(nvsize, KM_SLEEP);
2032 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
2033 DMU_READ_PREFETCH);
2034 if (error == 0)
2035 error = nvlist_unpack(packed, nvsize, value, 0);
2036 vmem_free(packed, nvsize);
2037
2038 return (error);
2039 }
2040
2041 /*
2042 * Concrete top-level vdevs that are not missing and are not logs. At every
2043 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
2044 */
2045 static uint64_t
spa_healthy_core_tvds(spa_t * spa)2046 spa_healthy_core_tvds(spa_t *spa)
2047 {
2048 vdev_t *rvd = spa->spa_root_vdev;
2049 uint64_t tvds = 0;
2050
2051 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
2052 vdev_t *vd = rvd->vdev_child[i];
2053 if (vd->vdev_islog)
2054 continue;
2055 if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
2056 tvds++;
2057 }
2058
2059 return (tvds);
2060 }
2061
2062 /*
2063 * Checks to see if the given vdev could not be opened, in which case we post a
2064 * sysevent to notify the autoreplace code that the device has been removed.
2065 */
2066 static void
spa_check_removed(vdev_t * vd)2067 spa_check_removed(vdev_t *vd)
2068 {
2069 for (uint64_t c = 0; c < vd->vdev_children; c++)
2070 spa_check_removed(vd->vdev_child[c]);
2071
2072 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
2073 vdev_is_concrete(vd)) {
2074 zfs_post_autoreplace(vd->vdev_spa, vd);
2075 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
2076 }
2077 }
2078
2079 static int
spa_check_for_missing_logs(spa_t * spa)2080 spa_check_for_missing_logs(spa_t *spa)
2081 {
2082 vdev_t *rvd = spa->spa_root_vdev;
2083
2084 /*
2085 * If we're doing a normal import, then build up any additional
2086 * diagnostic information about missing log devices.
2087 * We'll pass this up to the user for further processing.
2088 */
2089 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
2090 nvlist_t **child, *nv;
2091 uint64_t idx = 0;
2092
2093 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t *),
2094 KM_SLEEP);
2095 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2096
2097 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
2098 vdev_t *tvd = rvd->vdev_child[c];
2099
2100 /*
2101 * We consider a device as missing only if it failed
2102 * to open (i.e. offline or faulted is not considered
2103 * as missing).
2104 */
2105 if (tvd->vdev_islog &&
2106 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
2107 child[idx++] = vdev_config_generate(spa, tvd,
2108 B_FALSE, VDEV_CONFIG_MISSING);
2109 }
2110 }
2111
2112 if (idx > 0) {
2113 fnvlist_add_nvlist_array(nv,
2114 ZPOOL_CONFIG_CHILDREN, child, idx);
2115 fnvlist_add_nvlist(spa->spa_load_info,
2116 ZPOOL_CONFIG_MISSING_DEVICES, nv);
2117
2118 for (uint64_t i = 0; i < idx; i++)
2119 nvlist_free(child[i]);
2120 }
2121 nvlist_free(nv);
2122 kmem_free(child, rvd->vdev_children * sizeof (char **));
2123
2124 if (idx > 0) {
2125 spa_load_failed(spa, "some log devices are missing");
2126 vdev_dbgmsg_print_tree(rvd, 2);
2127 return (SET_ERROR(ENXIO));
2128 }
2129 } else {
2130 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
2131 vdev_t *tvd = rvd->vdev_child[c];
2132
2133 if (tvd->vdev_islog &&
2134 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
2135 spa_set_log_state(spa, SPA_LOG_CLEAR);
2136 spa_load_note(spa, "some log devices are "
2137 "missing, ZIL is dropped.");
2138 vdev_dbgmsg_print_tree(rvd, 2);
2139 break;
2140 }
2141 }
2142 }
2143
2144 return (0);
2145 }
2146
2147 /*
2148 * Check for missing log devices
2149 */
2150 static boolean_t
spa_check_logs(spa_t * spa)2151 spa_check_logs(spa_t *spa)
2152 {
2153 boolean_t rv = B_FALSE;
2154 dsl_pool_t *dp = spa_get_dsl(spa);
2155
2156 switch (spa->spa_log_state) {
2157 default:
2158 break;
2159 case SPA_LOG_MISSING:
2160 /* need to recheck in case slog has been restored */
2161 case SPA_LOG_UNKNOWN:
2162 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2163 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
2164 if (rv)
2165 spa_set_log_state(spa, SPA_LOG_MISSING);
2166 break;
2167 }
2168 return (rv);
2169 }
2170
2171 /*
2172 * Passivate any log vdevs (note, does not apply to embedded log metaslabs).
2173 */
2174 static boolean_t
spa_passivate_log(spa_t * spa)2175 spa_passivate_log(spa_t *spa)
2176 {
2177 vdev_t *rvd = spa->spa_root_vdev;
2178 boolean_t slog_found = B_FALSE;
2179
2180 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
2181
2182 for (int c = 0; c < rvd->vdev_children; c++) {
2183 vdev_t *tvd = rvd->vdev_child[c];
2184
2185 if (tvd->vdev_islog) {
2186 ASSERT3P(tvd->vdev_log_mg, ==, NULL);
2187 metaslab_group_passivate(tvd->vdev_mg);
2188 slog_found = B_TRUE;
2189 }
2190 }
2191
2192 return (slog_found);
2193 }
2194
2195 /*
2196 * Activate any log vdevs (note, does not apply to embedded log metaslabs).
2197 */
2198 static void
spa_activate_log(spa_t * spa)2199 spa_activate_log(spa_t *spa)
2200 {
2201 vdev_t *rvd = spa->spa_root_vdev;
2202
2203 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
2204
2205 for (int c = 0; c < rvd->vdev_children; c++) {
2206 vdev_t *tvd = rvd->vdev_child[c];
2207
2208 if (tvd->vdev_islog) {
2209 ASSERT3P(tvd->vdev_log_mg, ==, NULL);
2210 metaslab_group_activate(tvd->vdev_mg);
2211 }
2212 }
2213 }
2214
2215 int
spa_reset_logs(spa_t * spa)2216 spa_reset_logs(spa_t *spa)
2217 {
2218 int error;
2219
2220 error = dmu_objset_find(spa_name(spa), zil_reset,
2221 NULL, DS_FIND_CHILDREN);
2222 if (error == 0) {
2223 /*
2224 * We successfully offlined the log device, sync out the
2225 * current txg so that the "stubby" block can be removed
2226 * by zil_sync().
2227 */
2228 txg_wait_synced(spa->spa_dsl_pool, 0);
2229 }
2230 return (error);
2231 }
2232
2233 static void
spa_aux_check_removed(spa_aux_vdev_t * sav)2234 spa_aux_check_removed(spa_aux_vdev_t *sav)
2235 {
2236 for (int i = 0; i < sav->sav_count; i++)
2237 spa_check_removed(sav->sav_vdevs[i]);
2238 }
2239
2240 void
spa_claim_notify(zio_t * zio)2241 spa_claim_notify(zio_t *zio)
2242 {
2243 spa_t *spa = zio->io_spa;
2244
2245 if (zio->io_error)
2246 return;
2247
2248 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
2249 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
2250 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
2251 mutex_exit(&spa->spa_props_lock);
2252 }
2253
2254 typedef struct spa_load_error {
2255 uint64_t sle_meta_count;
2256 uint64_t sle_data_count;
2257 } spa_load_error_t;
2258
2259 static void
spa_load_verify_done(zio_t * zio)2260 spa_load_verify_done(zio_t *zio)
2261 {
2262 blkptr_t *bp = zio->io_bp;
2263 spa_load_error_t *sle = zio->io_private;
2264 dmu_object_type_t type = BP_GET_TYPE(bp);
2265 int error = zio->io_error;
2266 spa_t *spa = zio->io_spa;
2267
2268 abd_free(zio->io_abd);
2269 if (error) {
2270 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
2271 type != DMU_OT_INTENT_LOG)
2272 atomic_inc_64(&sle->sle_meta_count);
2273 else
2274 atomic_inc_64(&sle->sle_data_count);
2275 }
2276
2277 mutex_enter(&spa->spa_scrub_lock);
2278 spa->spa_load_verify_bytes -= BP_GET_PSIZE(bp);
2279 cv_broadcast(&spa->spa_scrub_io_cv);
2280 mutex_exit(&spa->spa_scrub_lock);
2281 }
2282
2283 /*
2284 * Maximum number of inflight bytes is the log2 fraction of the arc size.
2285 * By default, we set it to 1/16th of the arc.
2286 */
2287 int spa_load_verify_shift = 4;
2288 int spa_load_verify_metadata = B_TRUE;
2289 int spa_load_verify_data = B_TRUE;
2290
2291 static int
spa_load_verify_cb(spa_t * spa,zilog_t * zilog,const blkptr_t * bp,const zbookmark_phys_t * zb,const dnode_phys_t * dnp,void * arg)2292 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2293 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2294 {
2295 (void) zilog, (void) dnp;
2296
2297 if (zb->zb_level == ZB_DNODE_LEVEL || BP_IS_HOLE(bp) ||
2298 BP_IS_EMBEDDED(bp) || BP_IS_REDACTED(bp))
2299 return (0);
2300 /*
2301 * Note: normally this routine will not be called if
2302 * spa_load_verify_metadata is not set. However, it may be useful
2303 * to manually set the flag after the traversal has begun.
2304 */
2305 if (!spa_load_verify_metadata)
2306 return (0);
2307 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2308 return (0);
2309
2310 uint64_t maxinflight_bytes =
2311 arc_target_bytes() >> spa_load_verify_shift;
2312 zio_t *rio = arg;
2313 size_t size = BP_GET_PSIZE(bp);
2314
2315 mutex_enter(&spa->spa_scrub_lock);
2316 while (spa->spa_load_verify_bytes >= maxinflight_bytes)
2317 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2318 spa->spa_load_verify_bytes += size;
2319 mutex_exit(&spa->spa_scrub_lock);
2320
2321 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2322 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2323 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2324 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2325 return (0);
2326 }
2327
2328 static int
verify_dataset_name_len(dsl_pool_t * dp,dsl_dataset_t * ds,void * arg)2329 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2330 {
2331 (void) dp, (void) arg;
2332
2333 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2334 return (SET_ERROR(ENAMETOOLONG));
2335
2336 return (0);
2337 }
2338
2339 static int
spa_load_verify(spa_t * spa)2340 spa_load_verify(spa_t *spa)
2341 {
2342 zio_t *rio;
2343 spa_load_error_t sle = { 0 };
2344 zpool_load_policy_t policy;
2345 boolean_t verify_ok = B_FALSE;
2346 int error = 0;
2347
2348 zpool_get_load_policy(spa->spa_config, &policy);
2349
2350 if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2351 return (0);
2352
2353 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2354 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2355 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2356 DS_FIND_CHILDREN);
2357 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2358 if (error != 0)
2359 return (error);
2360
2361 rio = zio_root(spa, NULL, &sle,
2362 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2363
2364 if (spa_load_verify_metadata) {
2365 if (spa->spa_extreme_rewind) {
2366 spa_load_note(spa, "performing a complete scan of the "
2367 "pool since extreme rewind is on. This may take "
2368 "a very long time.\n (spa_load_verify_data=%u, "
2369 "spa_load_verify_metadata=%u)",
2370 spa_load_verify_data, spa_load_verify_metadata);
2371 }
2372
2373 error = traverse_pool(spa, spa->spa_verify_min_txg,
2374 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
2375 TRAVERSE_NO_DECRYPT, spa_load_verify_cb, rio);
2376 }
2377
2378 (void) zio_wait(rio);
2379 ASSERT0(spa->spa_load_verify_bytes);
2380
2381 spa->spa_load_meta_errors = sle.sle_meta_count;
2382 spa->spa_load_data_errors = sle.sle_data_count;
2383
2384 if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2385 spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2386 "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2387 (u_longlong_t)sle.sle_data_count);
2388 }
2389
2390 if (spa_load_verify_dryrun ||
2391 (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2392 sle.sle_data_count <= policy.zlp_maxdata)) {
2393 int64_t loss = 0;
2394
2395 verify_ok = B_TRUE;
2396 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2397 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2398
2399 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2400 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2401 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2402 VERIFY(nvlist_add_int64(spa->spa_load_info,
2403 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2404 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2405 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2406 } else {
2407 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2408 }
2409
2410 if (spa_load_verify_dryrun)
2411 return (0);
2412
2413 if (error) {
2414 if (error != ENXIO && error != EIO)
2415 error = SET_ERROR(EIO);
2416 return (error);
2417 }
2418
2419 return (verify_ok ? 0 : EIO);
2420 }
2421
2422 /*
2423 * Find a value in the pool props object.
2424 */
2425 static void
spa_prop_find(spa_t * spa,zpool_prop_t prop,uint64_t * val)2426 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2427 {
2428 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2429 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2430 }
2431
2432 /*
2433 * Find a value in the pool directory object.
2434 */
2435 static int
spa_dir_prop(spa_t * spa,const char * name,uint64_t * val,boolean_t log_enoent)2436 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2437 {
2438 int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2439 name, sizeof (uint64_t), 1, val);
2440
2441 if (error != 0 && (error != ENOENT || log_enoent)) {
2442 spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2443 "[error=%d]", name, error);
2444 }
2445
2446 return (error);
2447 }
2448
2449 static int
spa_vdev_err(vdev_t * vdev,vdev_aux_t aux,int err)2450 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2451 {
2452 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2453 return (SET_ERROR(err));
2454 }
2455
2456 boolean_t
spa_livelist_delete_check(spa_t * spa)2457 spa_livelist_delete_check(spa_t *spa)
2458 {
2459 return (spa->spa_livelists_to_delete != 0);
2460 }
2461
2462 static boolean_t
spa_livelist_delete_cb_check(void * arg,zthr_t * z)2463 spa_livelist_delete_cb_check(void *arg, zthr_t *z)
2464 {
2465 (void) z;
2466 spa_t *spa = arg;
2467 return (spa_livelist_delete_check(spa));
2468 }
2469
2470 static int
delete_blkptr_cb(void * arg,const blkptr_t * bp,dmu_tx_t * tx)2471 delete_blkptr_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2472 {
2473 spa_t *spa = arg;
2474 zio_free(spa, tx->tx_txg, bp);
2475 dsl_dir_diduse_space(tx->tx_pool->dp_free_dir, DD_USED_HEAD,
2476 -bp_get_dsize_sync(spa, bp),
2477 -BP_GET_PSIZE(bp), -BP_GET_UCSIZE(bp), tx);
2478 return (0);
2479 }
2480
2481 static int
dsl_get_next_livelist_obj(objset_t * os,uint64_t zap_obj,uint64_t * llp)2482 dsl_get_next_livelist_obj(objset_t *os, uint64_t zap_obj, uint64_t *llp)
2483 {
2484 int err;
2485 zap_cursor_t zc;
2486 zap_attribute_t za;
2487 zap_cursor_init(&zc, os, zap_obj);
2488 err = zap_cursor_retrieve(&zc, &za);
2489 zap_cursor_fini(&zc);
2490 if (err == 0)
2491 *llp = za.za_first_integer;
2492 return (err);
2493 }
2494
2495 /*
2496 * Components of livelist deletion that must be performed in syncing
2497 * context: freeing block pointers and updating the pool-wide data
2498 * structures to indicate how much work is left to do
2499 */
2500 typedef struct sublist_delete_arg {
2501 spa_t *spa;
2502 dsl_deadlist_t *ll;
2503 uint64_t key;
2504 bplist_t *to_free;
2505 } sublist_delete_arg_t;
2506
2507 static void
sublist_delete_sync(void * arg,dmu_tx_t * tx)2508 sublist_delete_sync(void *arg, dmu_tx_t *tx)
2509 {
2510 sublist_delete_arg_t *sda = arg;
2511 spa_t *spa = sda->spa;
2512 dsl_deadlist_t *ll = sda->ll;
2513 uint64_t key = sda->key;
2514 bplist_t *to_free = sda->to_free;
2515
2516 bplist_iterate(to_free, delete_blkptr_cb, spa, tx);
2517 dsl_deadlist_remove_entry(ll, key, tx);
2518 }
2519
2520 typedef struct livelist_delete_arg {
2521 spa_t *spa;
2522 uint64_t ll_obj;
2523 uint64_t zap_obj;
2524 } livelist_delete_arg_t;
2525
2526 static void
livelist_delete_sync(void * arg,dmu_tx_t * tx)2527 livelist_delete_sync(void *arg, dmu_tx_t *tx)
2528 {
2529 livelist_delete_arg_t *lda = arg;
2530 spa_t *spa = lda->spa;
2531 uint64_t ll_obj = lda->ll_obj;
2532 uint64_t zap_obj = lda->zap_obj;
2533 objset_t *mos = spa->spa_meta_objset;
2534 uint64_t count;
2535
2536 /* free the livelist and decrement the feature count */
2537 VERIFY0(zap_remove_int(mos, zap_obj, ll_obj, tx));
2538 dsl_deadlist_free(mos, ll_obj, tx);
2539 spa_feature_decr(spa, SPA_FEATURE_LIVELIST, tx);
2540 VERIFY0(zap_count(mos, zap_obj, &count));
2541 if (count == 0) {
2542 /* no more livelists to delete */
2543 VERIFY0(zap_remove(mos, DMU_POOL_DIRECTORY_OBJECT,
2544 DMU_POOL_DELETED_CLONES, tx));
2545 VERIFY0(zap_destroy(mos, zap_obj, tx));
2546 spa->spa_livelists_to_delete = 0;
2547 spa_notify_waiters(spa);
2548 }
2549 }
2550
2551 /*
2552 * Load in the value for the livelist to be removed and open it. Then,
2553 * load its first sublist and determine which block pointers should actually
2554 * be freed. Then, call a synctask which performs the actual frees and updates
2555 * the pool-wide livelist data.
2556 */
2557 static void
spa_livelist_delete_cb(void * arg,zthr_t * z)2558 spa_livelist_delete_cb(void *arg, zthr_t *z)
2559 {
2560 spa_t *spa = arg;
2561 uint64_t ll_obj = 0, count;
2562 objset_t *mos = spa->spa_meta_objset;
2563 uint64_t zap_obj = spa->spa_livelists_to_delete;
2564 /*
2565 * Determine the next livelist to delete. This function should only
2566 * be called if there is at least one deleted clone.
2567 */
2568 VERIFY0(dsl_get_next_livelist_obj(mos, zap_obj, &ll_obj));
2569 VERIFY0(zap_count(mos, ll_obj, &count));
2570 if (count > 0) {
2571 dsl_deadlist_t *ll;
2572 dsl_deadlist_entry_t *dle;
2573 bplist_t to_free;
2574 ll = kmem_zalloc(sizeof (dsl_deadlist_t), KM_SLEEP);
2575 dsl_deadlist_open(ll, mos, ll_obj);
2576 dle = dsl_deadlist_first(ll);
2577 ASSERT3P(dle, !=, NULL);
2578 bplist_create(&to_free);
2579 int err = dsl_process_sub_livelist(&dle->dle_bpobj, &to_free,
2580 z, NULL);
2581 if (err == 0) {
2582 sublist_delete_arg_t sync_arg = {
2583 .spa = spa,
2584 .ll = ll,
2585 .key = dle->dle_mintxg,
2586 .to_free = &to_free
2587 };
2588 zfs_dbgmsg("deleting sublist (id %llu) from"
2589 " livelist %llu, %lld remaining",
2590 (u_longlong_t)dle->dle_bpobj.bpo_object,
2591 (u_longlong_t)ll_obj, (longlong_t)count - 1);
2592 VERIFY0(dsl_sync_task(spa_name(spa), NULL,
2593 sublist_delete_sync, &sync_arg, 0,
2594 ZFS_SPACE_CHECK_DESTROY));
2595 } else {
2596 VERIFY3U(err, ==, EINTR);
2597 }
2598 bplist_clear(&to_free);
2599 bplist_destroy(&to_free);
2600 dsl_deadlist_close(ll);
2601 kmem_free(ll, sizeof (dsl_deadlist_t));
2602 } else {
2603 livelist_delete_arg_t sync_arg = {
2604 .spa = spa,
2605 .ll_obj = ll_obj,
2606 .zap_obj = zap_obj
2607 };
2608 zfs_dbgmsg("deletion of livelist %llu completed",
2609 (u_longlong_t)ll_obj);
2610 VERIFY0(dsl_sync_task(spa_name(spa), NULL, livelist_delete_sync,
2611 &sync_arg, 0, ZFS_SPACE_CHECK_DESTROY));
2612 }
2613 }
2614
2615 static void
spa_start_livelist_destroy_thread(spa_t * spa)2616 spa_start_livelist_destroy_thread(spa_t *spa)
2617 {
2618 ASSERT3P(spa->spa_livelist_delete_zthr, ==, NULL);
2619 spa->spa_livelist_delete_zthr =
2620 zthr_create("z_livelist_destroy",
2621 spa_livelist_delete_cb_check, spa_livelist_delete_cb, spa,
2622 minclsyspri);
2623 }
2624
2625 typedef struct livelist_new_arg {
2626 bplist_t *allocs;
2627 bplist_t *frees;
2628 } livelist_new_arg_t;
2629
2630 static int
livelist_track_new_cb(void * arg,const blkptr_t * bp,boolean_t bp_freed,dmu_tx_t * tx)2631 livelist_track_new_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
2632 dmu_tx_t *tx)
2633 {
2634 ASSERT(tx == NULL);
2635 livelist_new_arg_t *lna = arg;
2636 if (bp_freed) {
2637 bplist_append(lna->frees, bp);
2638 } else {
2639 bplist_append(lna->allocs, bp);
2640 zfs_livelist_condense_new_alloc++;
2641 }
2642 return (0);
2643 }
2644
2645 typedef struct livelist_condense_arg {
2646 spa_t *spa;
2647 bplist_t to_keep;
2648 uint64_t first_size;
2649 uint64_t next_size;
2650 } livelist_condense_arg_t;
2651
2652 static void
spa_livelist_condense_sync(void * arg,dmu_tx_t * tx)2653 spa_livelist_condense_sync(void *arg, dmu_tx_t *tx)
2654 {
2655 livelist_condense_arg_t *lca = arg;
2656 spa_t *spa = lca->spa;
2657 bplist_t new_frees;
2658 dsl_dataset_t *ds = spa->spa_to_condense.ds;
2659
2660 /* Have we been cancelled? */
2661 if (spa->spa_to_condense.cancelled) {
2662 zfs_livelist_condense_sync_cancel++;
2663 goto out;
2664 }
2665
2666 dsl_deadlist_entry_t *first = spa->spa_to_condense.first;
2667 dsl_deadlist_entry_t *next = spa->spa_to_condense.next;
2668 dsl_deadlist_t *ll = &ds->ds_dir->dd_livelist;
2669
2670 /*
2671 * It's possible that the livelist was changed while the zthr was
2672 * running. Therefore, we need to check for new blkptrs in the two
2673 * entries being condensed and continue to track them in the livelist.
2674 * Because of the way we handle remapped blkptrs (see dbuf_remap_impl),
2675 * it's possible that the newly added blkptrs are FREEs or ALLOCs so
2676 * we need to sort them into two different bplists.
2677 */
2678 uint64_t first_obj = first->dle_bpobj.bpo_object;
2679 uint64_t next_obj = next->dle_bpobj.bpo_object;
2680 uint64_t cur_first_size = first->dle_bpobj.bpo_phys->bpo_num_blkptrs;
2681 uint64_t cur_next_size = next->dle_bpobj.bpo_phys->bpo_num_blkptrs;
2682
2683 bplist_create(&new_frees);
2684 livelist_new_arg_t new_bps = {
2685 .allocs = &lca->to_keep,
2686 .frees = &new_frees,
2687 };
2688
2689 if (cur_first_size > lca->first_size) {
2690 VERIFY0(livelist_bpobj_iterate_from_nofree(&first->dle_bpobj,
2691 livelist_track_new_cb, &new_bps, lca->first_size));
2692 }
2693 if (cur_next_size > lca->next_size) {
2694 VERIFY0(livelist_bpobj_iterate_from_nofree(&next->dle_bpobj,
2695 livelist_track_new_cb, &new_bps, lca->next_size));
2696 }
2697
2698 dsl_deadlist_clear_entry(first, ll, tx);
2699 ASSERT(bpobj_is_empty(&first->dle_bpobj));
2700 dsl_deadlist_remove_entry(ll, next->dle_mintxg, tx);
2701
2702 bplist_iterate(&lca->to_keep, dsl_deadlist_insert_alloc_cb, ll, tx);
2703 bplist_iterate(&new_frees, dsl_deadlist_insert_free_cb, ll, tx);
2704 bplist_destroy(&new_frees);
2705
2706 char dsname[ZFS_MAX_DATASET_NAME_LEN];
2707 dsl_dataset_name(ds, dsname);
2708 zfs_dbgmsg("txg %llu condensing livelist of %s (id %llu), bpobj %llu "
2709 "(%llu blkptrs) and bpobj %llu (%llu blkptrs) -> bpobj %llu "
2710 "(%llu blkptrs)", (u_longlong_t)tx->tx_txg, dsname,
2711 (u_longlong_t)ds->ds_object, (u_longlong_t)first_obj,
2712 (u_longlong_t)cur_first_size, (u_longlong_t)next_obj,
2713 (u_longlong_t)cur_next_size,
2714 (u_longlong_t)first->dle_bpobj.bpo_object,
2715 (u_longlong_t)first->dle_bpobj.bpo_phys->bpo_num_blkptrs);
2716 out:
2717 dmu_buf_rele(ds->ds_dbuf, spa);
2718 spa->spa_to_condense.ds = NULL;
2719 bplist_clear(&lca->to_keep);
2720 bplist_destroy(&lca->to_keep);
2721 kmem_free(lca, sizeof (livelist_condense_arg_t));
2722 spa->spa_to_condense.syncing = B_FALSE;
2723 }
2724
2725 static void
spa_livelist_condense_cb(void * arg,zthr_t * t)2726 spa_livelist_condense_cb(void *arg, zthr_t *t)
2727 {
2728 while (zfs_livelist_condense_zthr_pause &&
2729 !(zthr_has_waiters(t) || zthr_iscancelled(t)))
2730 delay(1);
2731
2732 spa_t *spa = arg;
2733 dsl_deadlist_entry_t *first = spa->spa_to_condense.first;
2734 dsl_deadlist_entry_t *next = spa->spa_to_condense.next;
2735 uint64_t first_size, next_size;
2736
2737 livelist_condense_arg_t *lca =
2738 kmem_alloc(sizeof (livelist_condense_arg_t), KM_SLEEP);
2739 bplist_create(&lca->to_keep);
2740
2741 /*
2742 * Process the livelists (matching FREEs and ALLOCs) in open context
2743 * so we have minimal work in syncing context to condense.
2744 *
2745 * We save bpobj sizes (first_size and next_size) to use later in
2746 * syncing context to determine if entries were added to these sublists
2747 * while in open context. This is possible because the clone is still
2748 * active and open for normal writes and we want to make sure the new,
2749 * unprocessed blockpointers are inserted into the livelist normally.
2750 *
2751 * Note that dsl_process_sub_livelist() both stores the size number of
2752 * blockpointers and iterates over them while the bpobj's lock held, so
2753 * the sizes returned to us are consistent which what was actually
2754 * processed.
2755 */
2756 int err = dsl_process_sub_livelist(&first->dle_bpobj, &lca->to_keep, t,
2757 &first_size);
2758 if (err == 0)
2759 err = dsl_process_sub_livelist(&next->dle_bpobj, &lca->to_keep,
2760 t, &next_size);
2761
2762 if (err == 0) {
2763 while (zfs_livelist_condense_sync_pause &&
2764 !(zthr_has_waiters(t) || zthr_iscancelled(t)))
2765 delay(1);
2766
2767 dmu_tx_t *tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
2768 dmu_tx_mark_netfree(tx);
2769 dmu_tx_hold_space(tx, 1);
2770 err = dmu_tx_assign(tx, TXG_NOWAIT | TXG_NOTHROTTLE);
2771 if (err == 0) {
2772 /*
2773 * Prevent the condense zthr restarting before
2774 * the synctask completes.
2775 */
2776 spa->spa_to_condense.syncing = B_TRUE;
2777 lca->spa = spa;
2778 lca->first_size = first_size;
2779 lca->next_size = next_size;
2780 dsl_sync_task_nowait(spa_get_dsl(spa),
2781 spa_livelist_condense_sync, lca, tx);
2782 dmu_tx_commit(tx);
2783 return;
2784 }
2785 }
2786 /*
2787 * Condensing can not continue: either it was externally stopped or
2788 * we were unable to assign to a tx because the pool has run out of
2789 * space. In the second case, we'll just end up trying to condense
2790 * again in a later txg.
2791 */
2792 ASSERT(err != 0);
2793 bplist_clear(&lca->to_keep);
2794 bplist_destroy(&lca->to_keep);
2795 kmem_free(lca, sizeof (livelist_condense_arg_t));
2796 dmu_buf_rele(spa->spa_to_condense.ds->ds_dbuf, spa);
2797 spa->spa_to_condense.ds = NULL;
2798 if (err == EINTR)
2799 zfs_livelist_condense_zthr_cancel++;
2800 }
2801
2802 /*
2803 * Check that there is something to condense but that a condense is not
2804 * already in progress and that condensing has not been cancelled.
2805 */
2806 static boolean_t
spa_livelist_condense_cb_check(void * arg,zthr_t * z)2807 spa_livelist_condense_cb_check(void *arg, zthr_t *z)
2808 {
2809 (void) z;
2810 spa_t *spa = arg;
2811 if ((spa->spa_to_condense.ds != NULL) &&
2812 (spa->spa_to_condense.syncing == B_FALSE) &&
2813 (spa->spa_to_condense.cancelled == B_FALSE)) {
2814 return (B_TRUE);
2815 }
2816 return (B_FALSE);
2817 }
2818
2819 static void
spa_start_livelist_condensing_thread(spa_t * spa)2820 spa_start_livelist_condensing_thread(spa_t *spa)
2821 {
2822 spa->spa_to_condense.ds = NULL;
2823 spa->spa_to_condense.first = NULL;
2824 spa->spa_to_condense.next = NULL;
2825 spa->spa_to_condense.syncing = B_FALSE;
2826 spa->spa_to_condense.cancelled = B_FALSE;
2827
2828 ASSERT3P(spa->spa_livelist_condense_zthr, ==, NULL);
2829 spa->spa_livelist_condense_zthr =
2830 zthr_create("z_livelist_condense",
2831 spa_livelist_condense_cb_check,
2832 spa_livelist_condense_cb, spa, minclsyspri);
2833 }
2834
2835 static void
spa_spawn_aux_threads(spa_t * spa)2836 spa_spawn_aux_threads(spa_t *spa)
2837 {
2838 ASSERT(spa_writeable(spa));
2839
2840 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2841
2842 spa_start_indirect_condensing_thread(spa);
2843 spa_start_livelist_destroy_thread(spa);
2844 spa_start_livelist_condensing_thread(spa);
2845
2846 ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2847 spa->spa_checkpoint_discard_zthr =
2848 zthr_create("z_checkpoint_discard",
2849 spa_checkpoint_discard_thread_check,
2850 spa_checkpoint_discard_thread, spa, minclsyspri);
2851 }
2852
2853 /*
2854 * Fix up config after a partly-completed split. This is done with the
2855 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2856 * pool have that entry in their config, but only the splitting one contains
2857 * a list of all the guids of the vdevs that are being split off.
2858 *
2859 * This function determines what to do with that list: either rejoin
2860 * all the disks to the pool, or complete the splitting process. To attempt
2861 * the rejoin, each disk that is offlined is marked online again, and
2862 * we do a reopen() call. If the vdev label for every disk that was
2863 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2864 * then we call vdev_split() on each disk, and complete the split.
2865 *
2866 * Otherwise we leave the config alone, with all the vdevs in place in
2867 * the original pool.
2868 */
2869 static void
spa_try_repair(spa_t * spa,nvlist_t * config)2870 spa_try_repair(spa_t *spa, nvlist_t *config)
2871 {
2872 uint_t extracted;
2873 uint64_t *glist;
2874 uint_t i, gcount;
2875 nvlist_t *nvl;
2876 vdev_t **vd;
2877 boolean_t attempt_reopen;
2878
2879 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2880 return;
2881
2882 /* check that the config is complete */
2883 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2884 &glist, &gcount) != 0)
2885 return;
2886
2887 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2888
2889 /* attempt to online all the vdevs & validate */
2890 attempt_reopen = B_TRUE;
2891 for (i = 0; i < gcount; i++) {
2892 if (glist[i] == 0) /* vdev is hole */
2893 continue;
2894
2895 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2896 if (vd[i] == NULL) {
2897 /*
2898 * Don't bother attempting to reopen the disks;
2899 * just do the split.
2900 */
2901 attempt_reopen = B_FALSE;
2902 } else {
2903 /* attempt to re-online it */
2904 vd[i]->vdev_offline = B_FALSE;
2905 }
2906 }
2907
2908 if (attempt_reopen) {
2909 vdev_reopen(spa->spa_root_vdev);
2910
2911 /* check each device to see what state it's in */
2912 for (extracted = 0, i = 0; i < gcount; i++) {
2913 if (vd[i] != NULL &&
2914 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2915 break;
2916 ++extracted;
2917 }
2918 }
2919
2920 /*
2921 * If every disk has been moved to the new pool, or if we never
2922 * even attempted to look at them, then we split them off for
2923 * good.
2924 */
2925 if (!attempt_reopen || gcount == extracted) {
2926 for (i = 0; i < gcount; i++)
2927 if (vd[i] != NULL)
2928 vdev_split(vd[i]);
2929 vdev_reopen(spa->spa_root_vdev);
2930 }
2931
2932 kmem_free(vd, gcount * sizeof (vdev_t *));
2933 }
2934
2935 static int
spa_load(spa_t * spa,spa_load_state_t state,spa_import_type_t type)2936 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2937 {
2938 char *ereport = FM_EREPORT_ZFS_POOL;
2939 int error;
2940
2941 spa->spa_load_state = state;
2942 (void) spa_import_progress_set_state(spa_guid(spa),
2943 spa_load_state(spa));
2944
2945 gethrestime(&spa->spa_loaded_ts);
2946 error = spa_load_impl(spa, type, &ereport);
2947
2948 /*
2949 * Don't count references from objsets that are already closed
2950 * and are making their way through the eviction process.
2951 */
2952 spa_evicting_os_wait(spa);
2953 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
2954 if (error) {
2955 if (error != EEXIST) {
2956 spa->spa_loaded_ts.tv_sec = 0;
2957 spa->spa_loaded_ts.tv_nsec = 0;
2958 }
2959 if (error != EBADF) {
2960 (void) zfs_ereport_post(ereport, spa,
2961 NULL, NULL, NULL, 0);
2962 }
2963 }
2964 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2965 spa->spa_ena = 0;
2966
2967 (void) spa_import_progress_set_state(spa_guid(spa),
2968 spa_load_state(spa));
2969
2970 return (error);
2971 }
2972
2973 #ifdef ZFS_DEBUG
2974 /*
2975 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2976 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2977 * spa's per-vdev ZAP list.
2978 */
2979 static uint64_t
vdev_count_verify_zaps(vdev_t * vd)2980 vdev_count_verify_zaps(vdev_t *vd)
2981 {
2982 spa_t *spa = vd->vdev_spa;
2983 uint64_t total = 0;
2984
2985 if (vd->vdev_top_zap != 0) {
2986 total++;
2987 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2988 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2989 }
2990 if (vd->vdev_leaf_zap != 0) {
2991 total++;
2992 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2993 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2994 }
2995
2996 for (uint64_t i = 0; i < vd->vdev_children; i++) {
2997 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2998 }
2999
3000 return (total);
3001 }
3002 #endif
3003
3004 /*
3005 * Determine whether the activity check is required.
3006 */
3007 static boolean_t
spa_activity_check_required(spa_t * spa,uberblock_t * ub,nvlist_t * label,nvlist_t * config)3008 spa_activity_check_required(spa_t *spa, uberblock_t *ub, nvlist_t *label,
3009 nvlist_t *config)
3010 {
3011 uint64_t state = 0;
3012 uint64_t hostid = 0;
3013 uint64_t tryconfig_txg = 0;
3014 uint64_t tryconfig_timestamp = 0;
3015 uint16_t tryconfig_mmp_seq = 0;
3016 nvlist_t *nvinfo;
3017
3018 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
3019 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3020 (void) nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG,
3021 &tryconfig_txg);
3022 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
3023 &tryconfig_timestamp);
3024 (void) nvlist_lookup_uint16(nvinfo, ZPOOL_CONFIG_MMP_SEQ,
3025 &tryconfig_mmp_seq);
3026 }
3027
3028 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE, &state);
3029
3030 /*
3031 * Disable the MMP activity check - This is used by zdb which
3032 * is intended to be used on potentially active pools.
3033 */
3034 if (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP)
3035 return (B_FALSE);
3036
3037 /*
3038 * Skip the activity check when the MMP feature is disabled.
3039 */
3040 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay == 0)
3041 return (B_FALSE);
3042
3043 /*
3044 * If the tryconfig_ values are nonzero, they are the results of an
3045 * earlier tryimport. If they all match the uberblock we just found,
3046 * then the pool has not changed and we return false so we do not test
3047 * a second time.
3048 */
3049 if (tryconfig_txg && tryconfig_txg == ub->ub_txg &&
3050 tryconfig_timestamp && tryconfig_timestamp == ub->ub_timestamp &&
3051 tryconfig_mmp_seq && tryconfig_mmp_seq ==
3052 (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0))
3053 return (B_FALSE);
3054
3055 /*
3056 * Allow the activity check to be skipped when importing the pool
3057 * on the same host which last imported it. Since the hostid from
3058 * configuration may be stale use the one read from the label.
3059 */
3060 if (nvlist_exists(label, ZPOOL_CONFIG_HOSTID))
3061 hostid = fnvlist_lookup_uint64(label, ZPOOL_CONFIG_HOSTID);
3062
3063 if (hostid == spa_get_hostid(spa))
3064 return (B_FALSE);
3065
3066 /*
3067 * Skip the activity test when the pool was cleanly exported.
3068 */
3069 if (state != POOL_STATE_ACTIVE)
3070 return (B_FALSE);
3071
3072 return (B_TRUE);
3073 }
3074
3075 /*
3076 * Nanoseconds the activity check must watch for changes on-disk.
3077 */
3078 static uint64_t
spa_activity_check_duration(spa_t * spa,uberblock_t * ub)3079 spa_activity_check_duration(spa_t *spa, uberblock_t *ub)
3080 {
3081 uint64_t import_intervals = MAX(zfs_multihost_import_intervals, 1);
3082 uint64_t multihost_interval = MSEC2NSEC(
3083 MMP_INTERVAL_OK(zfs_multihost_interval));
3084 uint64_t import_delay = MAX(NANOSEC, import_intervals *
3085 multihost_interval);
3086
3087 /*
3088 * Local tunables determine a minimum duration except for the case
3089 * where we know when the remote host will suspend the pool if MMP
3090 * writes do not land.
3091 *
3092 * See Big Theory comment at the top of mmp.c for the reasoning behind
3093 * these cases and times.
3094 */
3095
3096 ASSERT(MMP_IMPORT_SAFETY_FACTOR >= 100);
3097
3098 if (MMP_INTERVAL_VALID(ub) && MMP_FAIL_INT_VALID(ub) &&
3099 MMP_FAIL_INT(ub) > 0) {
3100
3101 /* MMP on remote host will suspend pool after failed writes */
3102 import_delay = MMP_FAIL_INT(ub) * MSEC2NSEC(MMP_INTERVAL(ub)) *
3103 MMP_IMPORT_SAFETY_FACTOR / 100;
3104
3105 zfs_dbgmsg("fail_intvals>0 import_delay=%llu ub_mmp "
3106 "mmp_fails=%llu ub_mmp mmp_interval=%llu "
3107 "import_intervals=%llu", (u_longlong_t)import_delay,
3108 (u_longlong_t)MMP_FAIL_INT(ub),
3109 (u_longlong_t)MMP_INTERVAL(ub),
3110 (u_longlong_t)import_intervals);
3111
3112 } else if (MMP_INTERVAL_VALID(ub) && MMP_FAIL_INT_VALID(ub) &&
3113 MMP_FAIL_INT(ub) == 0) {
3114
3115 /* MMP on remote host will never suspend pool */
3116 import_delay = MAX(import_delay, (MSEC2NSEC(MMP_INTERVAL(ub)) +
3117 ub->ub_mmp_delay) * import_intervals);
3118
3119 zfs_dbgmsg("fail_intvals=0 import_delay=%llu ub_mmp "
3120 "mmp_interval=%llu ub_mmp_delay=%llu "
3121 "import_intervals=%llu", (u_longlong_t)import_delay,
3122 (u_longlong_t)MMP_INTERVAL(ub),
3123 (u_longlong_t)ub->ub_mmp_delay,
3124 (u_longlong_t)import_intervals);
3125
3126 } else if (MMP_VALID(ub)) {
3127 /*
3128 * zfs-0.7 compatibility case
3129 */
3130
3131 import_delay = MAX(import_delay, (multihost_interval +
3132 ub->ub_mmp_delay) * import_intervals);
3133
3134 zfs_dbgmsg("import_delay=%llu ub_mmp_delay=%llu "
3135 "import_intervals=%llu leaves=%u",
3136 (u_longlong_t)import_delay,
3137 (u_longlong_t)ub->ub_mmp_delay,
3138 (u_longlong_t)import_intervals,
3139 vdev_count_leaves(spa));
3140 } else {
3141 /* Using local tunings is the only reasonable option */
3142 zfs_dbgmsg("pool last imported on non-MMP aware "
3143 "host using import_delay=%llu multihost_interval=%llu "
3144 "import_intervals=%llu", (u_longlong_t)import_delay,
3145 (u_longlong_t)multihost_interval,
3146 (u_longlong_t)import_intervals);
3147 }
3148
3149 return (import_delay);
3150 }
3151
3152 /*
3153 * Perform the import activity check. If the user canceled the import or
3154 * we detected activity then fail.
3155 */
3156 static int
spa_activity_check(spa_t * spa,uberblock_t * ub,nvlist_t * config)3157 spa_activity_check(spa_t *spa, uberblock_t *ub, nvlist_t *config)
3158 {
3159 uint64_t txg = ub->ub_txg;
3160 uint64_t timestamp = ub->ub_timestamp;
3161 uint64_t mmp_config = ub->ub_mmp_config;
3162 uint16_t mmp_seq = MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0;
3163 uint64_t import_delay;
3164 hrtime_t import_expire;
3165 nvlist_t *mmp_label = NULL;
3166 vdev_t *rvd = spa->spa_root_vdev;
3167 kcondvar_t cv;
3168 kmutex_t mtx;
3169 int error = 0;
3170
3171 cv_init(&cv, NULL, CV_DEFAULT, NULL);
3172 mutex_init(&mtx, NULL, MUTEX_DEFAULT, NULL);
3173 mutex_enter(&mtx);
3174
3175 /*
3176 * If ZPOOL_CONFIG_MMP_TXG is present an activity check was performed
3177 * during the earlier tryimport. If the txg recorded there is 0 then
3178 * the pool is known to be active on another host.
3179 *
3180 * Otherwise, the pool might be in use on another host. Check for
3181 * changes in the uberblocks on disk if necessary.
3182 */
3183 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
3184 nvlist_t *nvinfo = fnvlist_lookup_nvlist(config,
3185 ZPOOL_CONFIG_LOAD_INFO);
3186
3187 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_TXG) &&
3188 fnvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG) == 0) {
3189 vdev_uberblock_load(rvd, ub, &mmp_label);
3190 error = SET_ERROR(EREMOTEIO);
3191 goto out;
3192 }
3193 }
3194
3195 import_delay = spa_activity_check_duration(spa, ub);
3196
3197 /* Add a small random factor in case of simultaneous imports (0-25%) */
3198 import_delay += import_delay * random_in_range(250) / 1000;
3199
3200 import_expire = gethrtime() + import_delay;
3201
3202 while (gethrtime() < import_expire) {
3203 (void) spa_import_progress_set_mmp_check(spa_guid(spa),
3204 NSEC2SEC(import_expire - gethrtime()));
3205
3206 vdev_uberblock_load(rvd, ub, &mmp_label);
3207
3208 if (txg != ub->ub_txg || timestamp != ub->ub_timestamp ||
3209 mmp_seq != (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0)) {
3210 zfs_dbgmsg("multihost activity detected "
3211 "txg %llu ub_txg %llu "
3212 "timestamp %llu ub_timestamp %llu "
3213 "mmp_config %#llx ub_mmp_config %#llx",
3214 (u_longlong_t)txg, (u_longlong_t)ub->ub_txg,
3215 (u_longlong_t)timestamp,
3216 (u_longlong_t)ub->ub_timestamp,
3217 (u_longlong_t)mmp_config,
3218 (u_longlong_t)ub->ub_mmp_config);
3219
3220 error = SET_ERROR(EREMOTEIO);
3221 break;
3222 }
3223
3224 if (mmp_label) {
3225 nvlist_free(mmp_label);
3226 mmp_label = NULL;
3227 }
3228
3229 error = cv_timedwait_sig(&cv, &mtx, ddi_get_lbolt() + hz);
3230 if (error != -1) {
3231 error = SET_ERROR(EINTR);
3232 break;
3233 }
3234 error = 0;
3235 }
3236
3237 out:
3238 mutex_exit(&mtx);
3239 mutex_destroy(&mtx);
3240 cv_destroy(&cv);
3241
3242 /*
3243 * If the pool is determined to be active store the status in the
3244 * spa->spa_load_info nvlist. If the remote hostname or hostid are
3245 * available from configuration read from disk store them as well.
3246 * This allows 'zpool import' to generate a more useful message.
3247 *
3248 * ZPOOL_CONFIG_MMP_STATE - observed pool status (mandatory)
3249 * ZPOOL_CONFIG_MMP_HOSTNAME - hostname from the active pool
3250 * ZPOOL_CONFIG_MMP_HOSTID - hostid from the active pool
3251 */
3252 if (error == EREMOTEIO) {
3253 char *hostname = "<unknown>";
3254 uint64_t hostid = 0;
3255
3256 if (mmp_label) {
3257 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTNAME)) {
3258 hostname = fnvlist_lookup_string(mmp_label,
3259 ZPOOL_CONFIG_HOSTNAME);
3260 fnvlist_add_string(spa->spa_load_info,
3261 ZPOOL_CONFIG_MMP_HOSTNAME, hostname);
3262 }
3263
3264 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTID)) {
3265 hostid = fnvlist_lookup_uint64(mmp_label,
3266 ZPOOL_CONFIG_HOSTID);
3267 fnvlist_add_uint64(spa->spa_load_info,
3268 ZPOOL_CONFIG_MMP_HOSTID, hostid);
3269 }
3270 }
3271
3272 fnvlist_add_uint64(spa->spa_load_info,
3273 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_ACTIVE);
3274 fnvlist_add_uint64(spa->spa_load_info,
3275 ZPOOL_CONFIG_MMP_TXG, 0);
3276
3277 error = spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO);
3278 }
3279
3280 if (mmp_label)
3281 nvlist_free(mmp_label);
3282
3283 return (error);
3284 }
3285
3286 static int
spa_verify_host(spa_t * spa,nvlist_t * mos_config)3287 spa_verify_host(spa_t *spa, nvlist_t *mos_config)
3288 {
3289 uint64_t hostid;
3290 char *hostname;
3291 uint64_t myhostid = 0;
3292
3293 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
3294 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
3295 hostname = fnvlist_lookup_string(mos_config,
3296 ZPOOL_CONFIG_HOSTNAME);
3297
3298 myhostid = zone_get_hostid(NULL);
3299
3300 if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
3301 cmn_err(CE_WARN, "pool '%s' could not be "
3302 "loaded as it was last accessed by "
3303 "another system (host: %s hostid: 0x%llx). "
3304 "See: https://openzfs.github.io/openzfs-docs/msg/"
3305 "ZFS-8000-EY",
3306 spa_name(spa), hostname, (u_longlong_t)hostid);
3307 spa_load_failed(spa, "hostid verification failed: pool "
3308 "last accessed by host: %s (hostid: 0x%llx)",
3309 hostname, (u_longlong_t)hostid);
3310 return (SET_ERROR(EBADF));
3311 }
3312 }
3313
3314 return (0);
3315 }
3316
3317 static int
spa_ld_parse_config(spa_t * spa,spa_import_type_t type)3318 spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
3319 {
3320 int error = 0;
3321 nvlist_t *nvtree, *nvl, *config = spa->spa_config;
3322 int parse;
3323 vdev_t *rvd;
3324 uint64_t pool_guid;
3325 char *comment;
3326 char *compatibility;
3327
3328 /*
3329 * Versioning wasn't explicitly added to the label until later, so if
3330 * it's not present treat it as the initial version.
3331 */
3332 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
3333 &spa->spa_ubsync.ub_version) != 0)
3334 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
3335
3336 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
3337 spa_load_failed(spa, "invalid config provided: '%s' missing",
3338 ZPOOL_CONFIG_POOL_GUID);
3339 return (SET_ERROR(EINVAL));
3340 }
3341
3342 /*
3343 * If we are doing an import, ensure that the pool is not already
3344 * imported by checking if its pool guid already exists in the
3345 * spa namespace.
3346 *
3347 * The only case that we allow an already imported pool to be
3348 * imported again, is when the pool is checkpointed and we want to
3349 * look at its checkpointed state from userland tools like zdb.
3350 */
3351 #ifdef _KERNEL
3352 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
3353 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
3354 spa_guid_exists(pool_guid, 0)) {
3355 #else
3356 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
3357 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
3358 spa_guid_exists(pool_guid, 0) &&
3359 !spa_importing_readonly_checkpoint(spa)) {
3360 #endif
3361 spa_load_failed(spa, "a pool with guid %llu is already open",
3362 (u_longlong_t)pool_guid);
3363 return (SET_ERROR(EEXIST));
3364 }
3365
3366 spa->spa_config_guid = pool_guid;
3367
3368 nvlist_free(spa->spa_load_info);
3369 spa->spa_load_info = fnvlist_alloc();
3370
3371 ASSERT(spa->spa_comment == NULL);
3372 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
3373 spa->spa_comment = spa_strdup(comment);
3374
3375 ASSERT(spa->spa_compatibility == NULL);
3376 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMPATIBILITY,
3377 &compatibility) == 0)
3378 spa->spa_compatibility = spa_strdup(compatibility);
3379
3380 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
3381 &spa->spa_config_txg);
3382
3383 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
3384 spa->spa_config_splitting = fnvlist_dup(nvl);
3385
3386 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
3387 spa_load_failed(spa, "invalid config provided: '%s' missing",
3388 ZPOOL_CONFIG_VDEV_TREE);
3389 return (SET_ERROR(EINVAL));
3390 }
3391
3392 /*
3393 * Create "The Godfather" zio to hold all async IOs
3394 */
3395 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
3396 KM_SLEEP);
3397 for (int i = 0; i < max_ncpus; i++) {
3398 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
3399 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
3400 ZIO_FLAG_GODFATHER);
3401 }
3402
3403 /*
3404 * Parse the configuration into a vdev tree. We explicitly set the
3405 * value that will be returned by spa_version() since parsing the
3406 * configuration requires knowing the version number.
3407 */
3408 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3409 parse = (type == SPA_IMPORT_EXISTING ?
3410 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
3411 error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
3412 spa_config_exit(spa, SCL_ALL, FTAG);
3413
3414 if (error != 0) {
3415 spa_load_failed(spa, "unable to parse config [error=%d]",
3416 error);
3417 return (error);
3418 }
3419
3420 ASSERT(spa->spa_root_vdev == rvd);
3421 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
3422 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
3423
3424 if (type != SPA_IMPORT_ASSEMBLE) {
3425 ASSERT(spa_guid(spa) == pool_guid);
3426 }
3427
3428 return (0);
3429 }
3430
3431 /*
3432 * Recursively open all vdevs in the vdev tree. This function is called twice:
3433 * first with the untrusted config, then with the trusted config.
3434 */
3435 static int
3436 spa_ld_open_vdevs(spa_t *spa)
3437 {
3438 int error = 0;
3439
3440 /*
3441 * spa_missing_tvds_allowed defines how many top-level vdevs can be
3442 * missing/unopenable for the root vdev to be still considered openable.
3443 */
3444 if (spa->spa_trust_config) {
3445 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
3446 } else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
3447 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
3448 } else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
3449 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
3450 } else {
3451 spa->spa_missing_tvds_allowed = 0;
3452 }
3453
3454 spa->spa_missing_tvds_allowed =
3455 MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
3456
3457 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3458 error = vdev_open(spa->spa_root_vdev);
3459 spa_config_exit(spa, SCL_ALL, FTAG);
3460
3461 if (spa->spa_missing_tvds != 0) {
3462 spa_load_note(spa, "vdev tree has %lld missing top-level "
3463 "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
3464 if (spa->spa_trust_config && (spa->spa_mode & SPA_MODE_WRITE)) {
3465 /*
3466 * Although theoretically we could allow users to open
3467 * incomplete pools in RW mode, we'd need to add a lot
3468 * of extra logic (e.g. adjust pool space to account
3469 * for missing vdevs).
3470 * This limitation also prevents users from accidentally
3471 * opening the pool in RW mode during data recovery and
3472 * damaging it further.
3473 */
3474 spa_load_note(spa, "pools with missing top-level "
3475 "vdevs can only be opened in read-only mode.");
3476 error = SET_ERROR(ENXIO);
3477 } else {
3478 spa_load_note(spa, "current settings allow for maximum "
3479 "%lld missing top-level vdevs at this stage.",
3480 (u_longlong_t)spa->spa_missing_tvds_allowed);
3481 }
3482 }
3483 if (error != 0) {
3484 spa_load_failed(spa, "unable to open vdev tree [error=%d]",
3485 error);
3486 }
3487 if (spa->spa_missing_tvds != 0 || error != 0)
3488 vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
3489
3490 return (error);
3491 }
3492
3493 /*
3494 * We need to validate the vdev labels against the configuration that
3495 * we have in hand. This function is called twice: first with an untrusted
3496 * config, then with a trusted config. The validation is more strict when the
3497 * config is trusted.
3498 */
3499 static int
3500 spa_ld_validate_vdevs(spa_t *spa)
3501 {
3502 int error = 0;
3503 vdev_t *rvd = spa->spa_root_vdev;
3504
3505 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3506 error = vdev_validate(rvd);
3507 spa_config_exit(spa, SCL_ALL, FTAG);
3508
3509 if (error != 0) {
3510 spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
3511 return (error);
3512 }
3513
3514 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
3515 spa_load_failed(spa, "cannot open vdev tree after invalidating "
3516 "some vdevs");
3517 vdev_dbgmsg_print_tree(rvd, 2);
3518 return (SET_ERROR(ENXIO));
3519 }
3520
3521 return (0);
3522 }
3523
3524 static void
3525 spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
3526 {
3527 spa->spa_state = POOL_STATE_ACTIVE;
3528 spa->spa_ubsync = spa->spa_uberblock;
3529 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
3530 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
3531 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
3532 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
3533 spa->spa_claim_max_txg = spa->spa_first_txg;
3534 spa->spa_prev_software_version = ub->ub_software_version;
3535 }
3536
3537 static int
3538 spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
3539 {
3540 vdev_t *rvd = spa->spa_root_vdev;
3541 nvlist_t *label;
3542 uberblock_t *ub = &spa->spa_uberblock;
3543 boolean_t activity_check = B_FALSE;
3544
3545 /*
3546 * If we are opening the checkpointed state of the pool by
3547 * rewinding to it, at this point we will have written the
3548 * checkpointed uberblock to the vdev labels, so searching
3549 * the labels will find the right uberblock. However, if
3550 * we are opening the checkpointed state read-only, we have
3551 * not modified the labels. Therefore, we must ignore the
3552 * labels and continue using the spa_uberblock that was set
3553 * by spa_ld_checkpoint_rewind.
3554 *
3555 * Note that it would be fine to ignore the labels when
3556 * rewinding (opening writeable) as well. However, if we
3557 * crash just after writing the labels, we will end up
3558 * searching the labels. Doing so in the common case means
3559 * that this code path gets exercised normally, rather than
3560 * just in the edge case.
3561 */
3562 if (ub->ub_checkpoint_txg != 0 &&
3563 spa_importing_readonly_checkpoint(spa)) {
3564 spa_ld_select_uberblock_done(spa, ub);
3565 return (0);
3566 }
3567
3568 /*
3569 * Find the best uberblock.
3570 */
3571 vdev_uberblock_load(rvd, ub, &label);
3572
3573 /*
3574 * If we weren't able to find a single valid uberblock, return failure.
3575 */
3576 if (ub->ub_txg == 0) {
3577 nvlist_free(label);
3578 spa_load_failed(spa, "no valid uberblock found");
3579 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
3580 }
3581
3582 if (spa->spa_load_max_txg != UINT64_MAX) {
3583 (void) spa_import_progress_set_max_txg(spa_guid(spa),
3584 (u_longlong_t)spa->spa_load_max_txg);
3585 }
3586 spa_load_note(spa, "using uberblock with txg=%llu",
3587 (u_longlong_t)ub->ub_txg);
3588
3589
3590 /*
3591 * For pools which have the multihost property on determine if the
3592 * pool is truly inactive and can be safely imported. Prevent
3593 * hosts which don't have a hostid set from importing the pool.
3594 */
3595 activity_check = spa_activity_check_required(spa, ub, label,
3596 spa->spa_config);
3597 if (activity_check) {
3598 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay &&
3599 spa_get_hostid(spa) == 0) {
3600 nvlist_free(label);
3601 fnvlist_add_uint64(spa->spa_load_info,
3602 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3603 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3604 }
3605
3606 int error = spa_activity_check(spa, ub, spa->spa_config);
3607 if (error) {
3608 nvlist_free(label);
3609 return (error);
3610 }
3611
3612 fnvlist_add_uint64(spa->spa_load_info,
3613 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_INACTIVE);
3614 fnvlist_add_uint64(spa->spa_load_info,
3615 ZPOOL_CONFIG_MMP_TXG, ub->ub_txg);
3616 fnvlist_add_uint16(spa->spa_load_info,
3617 ZPOOL_CONFIG_MMP_SEQ,
3618 (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0));
3619 }
3620
3621 /*
3622 * If the pool has an unsupported version we can't open it.
3623 */
3624 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
3625 nvlist_free(label);
3626 spa_load_failed(spa, "version %llu is not supported",
3627 (u_longlong_t)ub->ub_version);
3628 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
3629 }
3630
3631 if (ub->ub_version >= SPA_VERSION_FEATURES) {
3632 nvlist_t *features;
3633
3634 /*
3635 * If we weren't able to find what's necessary for reading the
3636 * MOS in the label, return failure.
3637 */
3638 if (label == NULL) {
3639 spa_load_failed(spa, "label config unavailable");
3640 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3641 ENXIO));
3642 }
3643
3644 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
3645 &features) != 0) {
3646 nvlist_free(label);
3647 spa_load_failed(spa, "invalid label: '%s' missing",
3648 ZPOOL_CONFIG_FEATURES_FOR_READ);
3649 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3650 ENXIO));
3651 }
3652
3653 /*
3654 * Update our in-core representation with the definitive values
3655 * from the label.
3656 */
3657 nvlist_free(spa->spa_label_features);
3658 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
3659 }
3660
3661 nvlist_free(label);
3662
3663 /*
3664 * Look through entries in the label nvlist's features_for_read. If
3665 * there is a feature listed there which we don't understand then we
3666 * cannot open a pool.
3667 */
3668 if (ub->ub_version >= SPA_VERSION_FEATURES) {
3669 nvlist_t *unsup_feat;
3670
3671 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
3672 0);
3673
3674 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
3675 NULL); nvp != NULL;
3676 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
3677 if (!zfeature_is_supported(nvpair_name(nvp))) {
3678 VERIFY(nvlist_add_string(unsup_feat,
3679 nvpair_name(nvp), "") == 0);
3680 }
3681 }
3682
3683 if (!nvlist_empty(unsup_feat)) {
3684 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
3685 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
3686 nvlist_free(unsup_feat);
3687 spa_load_failed(spa, "some features are unsupported");
3688 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3689 ENOTSUP));
3690 }
3691
3692 nvlist_free(unsup_feat);
3693 }
3694
3695 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
3696 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3697 spa_try_repair(spa, spa->spa_config);
3698 spa_config_exit(spa, SCL_ALL, FTAG);
3699 nvlist_free(spa->spa_config_splitting);
3700 spa->spa_config_splitting = NULL;
3701 }
3702
3703 /*
3704 * Initialize internal SPA structures.
3705 */
3706 spa_ld_select_uberblock_done(spa, ub);
3707
3708 return (0);
3709 }
3710
3711 static int
3712 spa_ld_open_rootbp(spa_t *spa)
3713 {
3714 int error = 0;
3715 vdev_t *rvd = spa->spa_root_vdev;
3716
3717 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
3718 if (error != 0) {
3719 spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
3720 "[error=%d]", error);
3721 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3722 }
3723 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
3724
3725 return (0);
3726 }
3727
3728 static int
3729 spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
3730 boolean_t reloading)
3731 {
3732 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
3733 nvlist_t *nv, *mos_config, *policy;
3734 int error = 0, copy_error;
3735 uint64_t healthy_tvds, healthy_tvds_mos;
3736 uint64_t mos_config_txg;
3737
3738 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
3739 != 0)
3740 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3741
3742 /*
3743 * If we're assembling a pool from a split, the config provided is
3744 * already trusted so there is nothing to do.
3745 */
3746 if (type == SPA_IMPORT_ASSEMBLE)
3747 return (0);
3748
3749 healthy_tvds = spa_healthy_core_tvds(spa);
3750
3751 if (load_nvlist(spa, spa->spa_config_object, &mos_config)
3752 != 0) {
3753 spa_load_failed(spa, "unable to retrieve MOS config");
3754 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3755 }
3756
3757 /*
3758 * If we are doing an open, pool owner wasn't verified yet, thus do
3759 * the verification here.
3760 */
3761 if (spa->spa_load_state == SPA_LOAD_OPEN) {
3762 error = spa_verify_host(spa, mos_config);
3763 if (error != 0) {
3764 nvlist_free(mos_config);
3765 return (error);
3766 }
3767 }
3768
3769 nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
3770
3771 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3772
3773 /*
3774 * Build a new vdev tree from the trusted config
3775 */
3776 error = spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD);
3777 if (error != 0) {
3778 nvlist_free(mos_config);
3779 spa_config_exit(spa, SCL_ALL, FTAG);
3780 spa_load_failed(spa, "spa_config_parse failed [error=%d]",
3781 error);
3782 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3783 }
3784
3785 /*
3786 * Vdev paths in the MOS may be obsolete. If the untrusted config was
3787 * obtained by scanning /dev/dsk, then it will have the right vdev
3788 * paths. We update the trusted MOS config with this information.
3789 * We first try to copy the paths with vdev_copy_path_strict, which
3790 * succeeds only when both configs have exactly the same vdev tree.
3791 * If that fails, we fall back to a more flexible method that has a
3792 * best effort policy.
3793 */
3794 copy_error = vdev_copy_path_strict(rvd, mrvd);
3795 if (copy_error != 0 || spa_load_print_vdev_tree) {
3796 spa_load_note(spa, "provided vdev tree:");
3797 vdev_dbgmsg_print_tree(rvd, 2);
3798 spa_load_note(spa, "MOS vdev tree:");
3799 vdev_dbgmsg_print_tree(mrvd, 2);
3800 }
3801 if (copy_error != 0) {
3802 spa_load_note(spa, "vdev_copy_path_strict failed, falling "
3803 "back to vdev_copy_path_relaxed");
3804 vdev_copy_path_relaxed(rvd, mrvd);
3805 }
3806
3807 vdev_close(rvd);
3808 vdev_free(rvd);
3809 spa->spa_root_vdev = mrvd;
3810 rvd = mrvd;
3811 spa_config_exit(spa, SCL_ALL, FTAG);
3812
3813 /*
3814 * We will use spa_config if we decide to reload the spa or if spa_load
3815 * fails and we rewind. We must thus regenerate the config using the
3816 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
3817 * pass settings on how to load the pool and is not stored in the MOS.
3818 * We copy it over to our new, trusted config.
3819 */
3820 mos_config_txg = fnvlist_lookup_uint64(mos_config,
3821 ZPOOL_CONFIG_POOL_TXG);
3822 nvlist_free(mos_config);
3823 mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
3824 if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
3825 &policy) == 0)
3826 fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
3827 spa_config_set(spa, mos_config);
3828 spa->spa_config_source = SPA_CONFIG_SRC_MOS;
3829
3830 /*
3831 * Now that we got the config from the MOS, we should be more strict
3832 * in checking blkptrs and can make assumptions about the consistency
3833 * of the vdev tree. spa_trust_config must be set to true before opening
3834 * vdevs in order for them to be writeable.
3835 */
3836 spa->spa_trust_config = B_TRUE;
3837
3838 /*
3839 * Open and validate the new vdev tree
3840 */
3841 error = spa_ld_open_vdevs(spa);
3842 if (error != 0)
3843 return (error);
3844
3845 error = spa_ld_validate_vdevs(spa);
3846 if (error != 0)
3847 return (error);
3848
3849 if (copy_error != 0 || spa_load_print_vdev_tree) {
3850 spa_load_note(spa, "final vdev tree:");
3851 vdev_dbgmsg_print_tree(rvd, 2);
3852 }
3853
3854 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
3855 !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
3856 /*
3857 * Sanity check to make sure that we are indeed loading the
3858 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
3859 * in the config provided and they happened to be the only ones
3860 * to have the latest uberblock, we could involuntarily perform
3861 * an extreme rewind.
3862 */
3863 healthy_tvds_mos = spa_healthy_core_tvds(spa);
3864 if (healthy_tvds_mos - healthy_tvds >=
3865 SPA_SYNC_MIN_VDEVS) {
3866 spa_load_note(spa, "config provided misses too many "
3867 "top-level vdevs compared to MOS (%lld vs %lld). ",
3868 (u_longlong_t)healthy_tvds,
3869 (u_longlong_t)healthy_tvds_mos);
3870 spa_load_note(spa, "vdev tree:");
3871 vdev_dbgmsg_print_tree(rvd, 2);
3872 if (reloading) {
3873 spa_load_failed(spa, "config was already "
3874 "provided from MOS. Aborting.");
3875 return (spa_vdev_err(rvd,
3876 VDEV_AUX_CORRUPT_DATA, EIO));
3877 }
3878 spa_load_note(spa, "spa must be reloaded using MOS "
3879 "config");
3880 return (SET_ERROR(EAGAIN));
3881 }
3882 }
3883
3884 error = spa_check_for_missing_logs(spa);
3885 if (error != 0)
3886 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
3887
3888 if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
3889 spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
3890 "guid sum (%llu != %llu)",
3891 (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
3892 (u_longlong_t)rvd->vdev_guid_sum);
3893 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
3894 ENXIO));
3895 }
3896
3897 return (0);
3898 }
3899
3900 static int
3901 spa_ld_open_indirect_vdev_metadata(spa_t *spa)
3902 {
3903 int error = 0;
3904 vdev_t *rvd = spa->spa_root_vdev;
3905
3906 /*
3907 * Everything that we read before spa_remove_init() must be stored
3908 * on concreted vdevs. Therefore we do this as early as possible.
3909 */
3910 error = spa_remove_init(spa);
3911 if (error != 0) {
3912 spa_load_failed(spa, "spa_remove_init failed [error=%d]",
3913 error);
3914 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3915 }
3916
3917 /*
3918 * Retrieve information needed to condense indirect vdev mappings.
3919 */
3920 error = spa_condense_init(spa);
3921 if (error != 0) {
3922 spa_load_failed(spa, "spa_condense_init failed [error=%d]",
3923 error);
3924 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3925 }
3926
3927 return (0);
3928 }
3929
3930 static int
3931 spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
3932 {
3933 int error = 0;
3934 vdev_t *rvd = spa->spa_root_vdev;
3935
3936 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
3937 boolean_t missing_feat_read = B_FALSE;
3938 nvlist_t *unsup_feat, *enabled_feat;
3939
3940 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
3941 &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
3942 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3943 }
3944
3945 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
3946 &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
3947 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3948 }
3949
3950 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
3951 &spa->spa_feat_desc_obj, B_TRUE) != 0) {
3952 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3953 }
3954
3955 enabled_feat = fnvlist_alloc();
3956 unsup_feat = fnvlist_alloc();
3957
3958 if (!spa_features_check(spa, B_FALSE,
3959 unsup_feat, enabled_feat))
3960 missing_feat_read = B_TRUE;
3961
3962 if (spa_writeable(spa) ||
3963 spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
3964 if (!spa_features_check(spa, B_TRUE,
3965 unsup_feat, enabled_feat)) {
3966 *missing_feat_writep = B_TRUE;
3967 }
3968 }
3969
3970 fnvlist_add_nvlist(spa->spa_load_info,
3971 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3972
3973 if (!nvlist_empty(unsup_feat)) {
3974 fnvlist_add_nvlist(spa->spa_load_info,
3975 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
3976 }
3977
3978 fnvlist_free(enabled_feat);
3979 fnvlist_free(unsup_feat);
3980
3981 if (!missing_feat_read) {
3982 fnvlist_add_boolean(spa->spa_load_info,
3983 ZPOOL_CONFIG_CAN_RDONLY);
3984 }
3985
3986 /*
3987 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3988 * twofold: to determine whether the pool is available for
3989 * import in read-write mode and (if it is not) whether the
3990 * pool is available for import in read-only mode. If the pool
3991 * is available for import in read-write mode, it is displayed
3992 * as available in userland; if it is not available for import
3993 * in read-only mode, it is displayed as unavailable in
3994 * userland. If the pool is available for import in read-only
3995 * mode but not read-write mode, it is displayed as unavailable
3996 * in userland with a special note that the pool is actually
3997 * available for open in read-only mode.
3998 *
3999 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
4000 * missing a feature for write, we must first determine whether
4001 * the pool can be opened read-only before returning to
4002 * userland in order to know whether to display the
4003 * abovementioned note.
4004 */
4005 if (missing_feat_read || (*missing_feat_writep &&
4006 spa_writeable(spa))) {
4007 spa_load_failed(spa, "pool uses unsupported features");
4008 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
4009 ENOTSUP));
4010 }
4011
4012 /*
4013 * Load refcounts for ZFS features from disk into an in-memory
4014 * cache during SPA initialization.
4015 */
4016 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
4017 uint64_t refcount;
4018
4019 error = feature_get_refcount_from_disk(spa,
4020 &spa_feature_table[i], &refcount);
4021 if (error == 0) {
4022 spa->spa_feat_refcount_cache[i] = refcount;
4023 } else if (error == ENOTSUP) {
4024 spa->spa_feat_refcount_cache[i] =
4025 SPA_FEATURE_DISABLED;
4026 } else {
4027 spa_load_failed(spa, "error getting refcount "
4028 "for feature %s [error=%d]",
4029 spa_feature_table[i].fi_guid, error);
4030 return (spa_vdev_err(rvd,
4031 VDEV_AUX_CORRUPT_DATA, EIO));
4032 }
4033 }
4034 }
4035
4036 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
4037 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
4038 &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
4039 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4040 }
4041
4042 /*
4043 * Encryption was added before bookmark_v2, even though bookmark_v2
4044 * is now a dependency. If this pool has encryption enabled without
4045 * bookmark_v2, trigger an errata message.
4046 */
4047 if (spa_feature_is_enabled(spa, SPA_FEATURE_ENCRYPTION) &&
4048 !spa_feature_is_enabled(spa, SPA_FEATURE_BOOKMARK_V2)) {
4049 spa->spa_errata = ZPOOL_ERRATA_ZOL_8308_ENCRYPTION;
4050 }
4051
4052 return (0);
4053 }
4054
4055 static int
4056 spa_ld_load_special_directories(spa_t *spa)
4057 {
4058 int error = 0;
4059 vdev_t *rvd = spa->spa_root_vdev;
4060
4061 spa->spa_is_initializing = B_TRUE;
4062 error = dsl_pool_open(spa->spa_dsl_pool);
4063 spa->spa_is_initializing = B_FALSE;
4064 if (error != 0) {
4065 spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
4066 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4067 }
4068
4069 return (0);
4070 }
4071
4072 static int
4073 spa_ld_get_props(spa_t *spa)
4074 {
4075 int error = 0;
4076 uint64_t obj;
4077 vdev_t *rvd = spa->spa_root_vdev;
4078
4079 /* Grab the checksum salt from the MOS. */
4080 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
4081 DMU_POOL_CHECKSUM_SALT, 1,
4082 sizeof (spa->spa_cksum_salt.zcs_bytes),
4083 spa->spa_cksum_salt.zcs_bytes);
4084 if (error == ENOENT) {
4085 /* Generate a new salt for subsequent use */
4086 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
4087 sizeof (spa->spa_cksum_salt.zcs_bytes));
4088 } else if (error != 0) {
4089 spa_load_failed(spa, "unable to retrieve checksum salt from "
4090 "MOS [error=%d]", error);
4091 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4092 }
4093
4094 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
4095 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4096 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
4097 if (error != 0) {
4098 spa_load_failed(spa, "error opening deferred-frees bpobj "
4099 "[error=%d]", error);
4100 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4101 }
4102
4103 /*
4104 * Load the bit that tells us to use the new accounting function
4105 * (raid-z deflation). If we have an older pool, this will not
4106 * be present.
4107 */
4108 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
4109 if (error != 0 && error != ENOENT)
4110 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4111
4112 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
4113 &spa->spa_creation_version, B_FALSE);
4114 if (error != 0 && error != ENOENT)
4115 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4116
4117 /*
4118 * Load the persistent error log. If we have an older pool, this will
4119 * not be present.
4120 */
4121 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
4122 B_FALSE);
4123 if (error != 0 && error != ENOENT)
4124 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4125
4126 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
4127 &spa->spa_errlog_scrub, B_FALSE);
4128 if (error != 0 && error != ENOENT)
4129 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4130
4131 /*
4132 * Load the livelist deletion field. If a livelist is queued for
4133 * deletion, indicate that in the spa
4134 */
4135 error = spa_dir_prop(spa, DMU_POOL_DELETED_CLONES,
4136 &spa->spa_livelists_to_delete, B_FALSE);
4137 if (error != 0 && error != ENOENT)
4138 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4139
4140 /*
4141 * Load the history object. If we have an older pool, this
4142 * will not be present.
4143 */
4144 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
4145 if (error != 0 && error != ENOENT)
4146 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4147
4148 /*
4149 * Load the per-vdev ZAP map. If we have an older pool, this will not
4150 * be present; in this case, defer its creation to a later time to
4151 * avoid dirtying the MOS this early / out of sync context. See
4152 * spa_sync_config_object.
4153 */
4154
4155 /* The sentinel is only available in the MOS config. */
4156 nvlist_t *mos_config;
4157 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
4158 spa_load_failed(spa, "unable to retrieve MOS config");
4159 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4160 }
4161
4162 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
4163 &spa->spa_all_vdev_zaps, B_FALSE);
4164
4165 if (error == ENOENT) {
4166 VERIFY(!nvlist_exists(mos_config,
4167 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
4168 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
4169 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
4170 } else if (error != 0) {
4171 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4172 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
4173 /*
4174 * An older version of ZFS overwrote the sentinel value, so
4175 * we have orphaned per-vdev ZAPs in the MOS. Defer their
4176 * destruction to later; see spa_sync_config_object.
4177 */
4178 spa->spa_avz_action = AVZ_ACTION_DESTROY;
4179 /*
4180 * We're assuming that no vdevs have had their ZAPs created
4181 * before this. Better be sure of it.
4182 */
4183 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
4184 }
4185 nvlist_free(mos_config);
4186
4187 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
4188
4189 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
4190 B_FALSE);
4191 if (error && error != ENOENT)
4192 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4193
4194 if (error == 0) {
4195 uint64_t autoreplace = 0;
4196
4197 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
4198 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
4199 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
4200 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
4201 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
4202 spa_prop_find(spa, ZPOOL_PROP_MULTIHOST, &spa->spa_multihost);
4203 spa_prop_find(spa, ZPOOL_PROP_AUTOTRIM, &spa->spa_autotrim);
4204 spa->spa_autoreplace = (autoreplace != 0);
4205 }
4206
4207 /*
4208 * If we are importing a pool with missing top-level vdevs,
4209 * we enforce that the pool doesn't panic or get suspended on
4210 * error since the likelihood of missing data is extremely high.
4211 */
4212 if (spa->spa_missing_tvds > 0 &&
4213 spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
4214 spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
4215 spa_load_note(spa, "forcing failmode to 'continue' "
4216 "as some top level vdevs are missing");
4217 spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
4218 }
4219
4220 return (0);
4221 }
4222
4223 static int
4224 spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
4225 {
4226 int error = 0;
4227 vdev_t *rvd = spa->spa_root_vdev;
4228
4229 /*
4230 * If we're assembling the pool from the split-off vdevs of
4231 * an existing pool, we don't want to attach the spares & cache
4232 * devices.
4233 */
4234
4235 /*
4236 * Load any hot spares for this pool.
4237 */
4238 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
4239 B_FALSE);
4240 if (error != 0 && error != ENOENT)
4241 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4242 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
4243 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
4244 if (load_nvlist(spa, spa->spa_spares.sav_object,
4245 &spa->spa_spares.sav_config) != 0) {
4246 spa_load_failed(spa, "error loading spares nvlist");
4247 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4248 }
4249
4250 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4251 spa_load_spares(spa);
4252 spa_config_exit(spa, SCL_ALL, FTAG);
4253 } else if (error == 0) {
4254 spa->spa_spares.sav_sync = B_TRUE;
4255 }
4256
4257 /*
4258 * Load any level 2 ARC devices for this pool.
4259 */
4260 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
4261 &spa->spa_l2cache.sav_object, B_FALSE);
4262 if (error != 0 && error != ENOENT)
4263 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4264 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
4265 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
4266 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
4267 &spa->spa_l2cache.sav_config) != 0) {
4268 spa_load_failed(spa, "error loading l2cache nvlist");
4269 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4270 }
4271
4272 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4273 spa_load_l2cache(spa);
4274 spa_config_exit(spa, SCL_ALL, FTAG);
4275 } else if (error == 0) {
4276 spa->spa_l2cache.sav_sync = B_TRUE;
4277 }
4278
4279 return (0);
4280 }
4281
4282 static int
4283 spa_ld_load_vdev_metadata(spa_t *spa)
4284 {
4285 int error = 0;
4286 vdev_t *rvd = spa->spa_root_vdev;
4287
4288 /*
4289 * If the 'multihost' property is set, then never allow a pool to
4290 * be imported when the system hostid is zero. The exception to
4291 * this rule is zdb which is always allowed to access pools.
4292 */
4293 if (spa_multihost(spa) && spa_get_hostid(spa) == 0 &&
4294 (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP) == 0) {
4295 fnvlist_add_uint64(spa->spa_load_info,
4296 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
4297 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
4298 }
4299
4300 /*
4301 * If the 'autoreplace' property is set, then post a resource notifying
4302 * the ZFS DE that it should not issue any faults for unopenable
4303 * devices. We also iterate over the vdevs, and post a sysevent for any
4304 * unopenable vdevs so that the normal autoreplace handler can take
4305 * over.
4306 */
4307 if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
4308 spa_check_removed(spa->spa_root_vdev);
4309 /*
4310 * For the import case, this is done in spa_import(), because
4311 * at this point we're using the spare definitions from
4312 * the MOS config, not necessarily from the userland config.
4313 */
4314 if (spa->spa_load_state != SPA_LOAD_IMPORT) {
4315 spa_aux_check_removed(&spa->spa_spares);
4316 spa_aux_check_removed(&spa->spa_l2cache);
4317 }
4318 }
4319
4320 /*
4321 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
4322 */
4323 error = vdev_load(rvd);
4324 if (error != 0) {
4325 spa_load_failed(spa, "vdev_load failed [error=%d]", error);
4326 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
4327 }
4328
4329 error = spa_ld_log_spacemaps(spa);
4330 if (error != 0) {
4331 spa_load_failed(spa, "spa_ld_log_sm_data failed [error=%d]",
4332 error);
4333 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
4334 }
4335
4336 /*
4337 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
4338 */
4339 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4340 vdev_dtl_reassess(rvd, 0, 0, B_FALSE, B_FALSE);
4341 spa_config_exit(spa, SCL_ALL, FTAG);
4342
4343 return (0);
4344 }
4345
4346 static int
4347 spa_ld_load_dedup_tables(spa_t *spa)
4348 {
4349 int error = 0;
4350 vdev_t *rvd = spa->spa_root_vdev;
4351
4352 error = ddt_load(spa);
4353 if (error != 0) {
4354 spa_load_failed(spa, "ddt_load failed [error=%d]", error);
4355 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
4356 }
4357
4358 return (0);
4359 }
4360
4361 static int
4362 spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
4363 {
4364 vdev_t *rvd = spa->spa_root_vdev;
4365
4366 if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
4367 boolean_t missing = spa_check_logs(spa);
4368 if (missing) {
4369 if (spa->spa_missing_tvds != 0) {
4370 spa_load_note(spa, "spa_check_logs failed "
4371 "so dropping the logs");
4372 } else {
4373 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
4374 spa_load_failed(spa, "spa_check_logs failed");
4375 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
4376 ENXIO));
4377 }
4378 }
4379 }
4380
4381 return (0);
4382 }
4383
4384 static int
4385 spa_ld_verify_pool_data(spa_t *spa)
4386 {
4387 int error = 0;
4388 vdev_t *rvd = spa->spa_root_vdev;
4389
4390 /*
4391 * We've successfully opened the pool, verify that we're ready
4392 * to start pushing transactions.
4393 */
4394 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
4395 error = spa_load_verify(spa);
4396 if (error != 0) {
4397 spa_load_failed(spa, "spa_load_verify failed "
4398 "[error=%d]", error);
4399 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
4400 error));
4401 }
4402 }
4403
4404 return (0);
4405 }
4406
4407 static void
4408 spa_ld_claim_log_blocks(spa_t *spa)
4409 {
4410 dmu_tx_t *tx;
4411 dsl_pool_t *dp = spa_get_dsl(spa);
4412
4413 /*
4414 * Claim log blocks that haven't been committed yet.
4415 * This must all happen in a single txg.
4416 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
4417 * invoked from zil_claim_log_block()'s i/o done callback.
4418 * Price of rollback is that we abandon the log.
4419 */
4420 spa->spa_claiming = B_TRUE;
4421
4422 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
4423 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
4424 zil_claim, tx, DS_FIND_CHILDREN);
4425 dmu_tx_commit(tx);
4426
4427 spa->spa_claiming = B_FALSE;
4428
4429 spa_set_log_state(spa, SPA_LOG_GOOD);
4430 }
4431
4432 static void
4433 spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
4434 boolean_t update_config_cache)
4435 {
4436 vdev_t *rvd = spa->spa_root_vdev;
4437 int need_update = B_FALSE;
4438
4439 /*
4440 * If the config cache is stale, or we have uninitialized
4441 * metaslabs (see spa_vdev_add()), then update the config.
4442 *
4443 * If this is a verbatim import, trust the current
4444 * in-core spa_config and update the disk labels.
4445 */
4446 if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
4447 spa->spa_load_state == SPA_LOAD_IMPORT ||
4448 spa->spa_load_state == SPA_LOAD_RECOVER ||
4449 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
4450 need_update = B_TRUE;
4451
4452 for (int c = 0; c < rvd->vdev_children; c++)
4453 if (rvd->vdev_child[c]->vdev_ms_array == 0)
4454 need_update = B_TRUE;
4455
4456 /*
4457 * Update the config cache asynchronously in case we're the
4458 * root pool, in which case the config cache isn't writable yet.
4459 */
4460 if (need_update)
4461 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
4462 }
4463
4464 static void
4465 spa_ld_prepare_for_reload(spa_t *spa)
4466 {
4467 spa_mode_t mode = spa->spa_mode;
4468 int async_suspended = spa->spa_async_suspended;
4469
4470 spa_unload(spa);
4471 spa_deactivate(spa);
4472 spa_activate(spa, mode);
4473
4474 /*
4475 * We save the value of spa_async_suspended as it gets reset to 0 by
4476 * spa_unload(). We want to restore it back to the original value before
4477 * returning as we might be calling spa_async_resume() later.
4478 */
4479 spa->spa_async_suspended = async_suspended;
4480 }
4481
4482 static int
4483 spa_ld_read_checkpoint_txg(spa_t *spa)
4484 {
4485 uberblock_t checkpoint;
4486 int error = 0;
4487
4488 ASSERT0(spa->spa_checkpoint_txg);
4489 ASSERT(MUTEX_HELD(&spa_namespace_lock));
4490
4491 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
4492 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
4493 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
4494
4495 if (error == ENOENT)
4496 return (0);
4497
4498 if (error != 0)
4499 return (error);
4500
4501 ASSERT3U(checkpoint.ub_txg, !=, 0);
4502 ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
4503 ASSERT3U(checkpoint.ub_timestamp, !=, 0);
4504 spa->spa_checkpoint_txg = checkpoint.ub_txg;
4505 spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
4506
4507 return (0);
4508 }
4509
4510 static int
4511 spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
4512 {
4513 int error = 0;
4514
4515 ASSERT(MUTEX_HELD(&spa_namespace_lock));
4516 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
4517
4518 /*
4519 * Never trust the config that is provided unless we are assembling
4520 * a pool following a split.
4521 * This means don't trust blkptrs and the vdev tree in general. This
4522 * also effectively puts the spa in read-only mode since
4523 * spa_writeable() checks for spa_trust_config to be true.
4524 * We will later load a trusted config from the MOS.
4525 */
4526 if (type != SPA_IMPORT_ASSEMBLE)
4527 spa->spa_trust_config = B_FALSE;
4528
4529 /*
4530 * Parse the config provided to create a vdev tree.
4531 */
4532 error = spa_ld_parse_config(spa, type);
4533 if (error != 0)
4534 return (error);
4535
4536 spa_import_progress_add(spa);
4537
4538 /*
4539 * Now that we have the vdev tree, try to open each vdev. This involves
4540 * opening the underlying physical device, retrieving its geometry and
4541 * probing the vdev with a dummy I/O. The state of each vdev will be set
4542 * based on the success of those operations. After this we'll be ready
4543 * to read from the vdevs.
4544 */
4545 error = spa_ld_open_vdevs(spa);
4546 if (error != 0)
4547 return (error);
4548
4549 /*
4550 * Read the label of each vdev and make sure that the GUIDs stored
4551 * there match the GUIDs in the config provided.
4552 * If we're assembling a new pool that's been split off from an
4553 * existing pool, the labels haven't yet been updated so we skip
4554 * validation for now.
4555 */
4556 if (type != SPA_IMPORT_ASSEMBLE) {
4557 error = spa_ld_validate_vdevs(spa);
4558 if (error != 0)
4559 return (error);
4560 }
4561
4562 /*
4563 * Read all vdev labels to find the best uberblock (i.e. latest,
4564 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
4565 * get the list of features required to read blkptrs in the MOS from
4566 * the vdev label with the best uberblock and verify that our version
4567 * of zfs supports them all.
4568 */
4569 error = spa_ld_select_uberblock(spa, type);
4570 if (error != 0)
4571 return (error);
4572
4573 /*
4574 * Pass that uberblock to the dsl_pool layer which will open the root
4575 * blkptr. This blkptr points to the latest version of the MOS and will
4576 * allow us to read its contents.
4577 */
4578 error = spa_ld_open_rootbp(spa);
4579 if (error != 0)
4580 return (error);
4581
4582 return (0);
4583 }
4584
4585 static int
4586 spa_ld_checkpoint_rewind(spa_t *spa)
4587 {
4588 uberblock_t checkpoint;
4589 int error = 0;
4590
4591 ASSERT(MUTEX_HELD(&spa_namespace_lock));
4592 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4593
4594 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
4595 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
4596 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
4597
4598 if (error != 0) {
4599 spa_load_failed(spa, "unable to retrieve checkpointed "
4600 "uberblock from the MOS config [error=%d]", error);
4601
4602 if (error == ENOENT)
4603 error = ZFS_ERR_NO_CHECKPOINT;
4604
4605 return (error);
4606 }
4607
4608 ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
4609 ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
4610
4611 /*
4612 * We need to update the txg and timestamp of the checkpointed
4613 * uberblock to be higher than the latest one. This ensures that
4614 * the checkpointed uberblock is selected if we were to close and
4615 * reopen the pool right after we've written it in the vdev labels.
4616 * (also see block comment in vdev_uberblock_compare)
4617 */
4618 checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
4619 checkpoint.ub_timestamp = gethrestime_sec();
4620
4621 /*
4622 * Set current uberblock to be the checkpointed uberblock.
4623 */
4624 spa->spa_uberblock = checkpoint;
4625
4626 /*
4627 * If we are doing a normal rewind, then the pool is open for
4628 * writing and we sync the "updated" checkpointed uberblock to
4629 * disk. Once this is done, we've basically rewound the whole
4630 * pool and there is no way back.
4631 *
4632 * There are cases when we don't want to attempt and sync the
4633 * checkpointed uberblock to disk because we are opening a
4634 * pool as read-only. Specifically, verifying the checkpointed
4635 * state with zdb, and importing the checkpointed state to get
4636 * a "preview" of its content.
4637 */
4638 if (spa_writeable(spa)) {
4639 vdev_t *rvd = spa->spa_root_vdev;
4640
4641 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4642 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
4643 int svdcount = 0;
4644 int children = rvd->vdev_children;
4645 int c0 = random_in_range(children);
4646
4647 for (int c = 0; c < children; c++) {
4648 vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
4649
4650 /* Stop when revisiting the first vdev */
4651 if (c > 0 && svd[0] == vd)
4652 break;
4653
4654 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
4655 !vdev_is_concrete(vd))
4656 continue;
4657
4658 svd[svdcount++] = vd;
4659 if (svdcount == SPA_SYNC_MIN_VDEVS)
4660 break;
4661 }
4662 error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
4663 if (error == 0)
4664 spa->spa_last_synced_guid = rvd->vdev_guid;
4665 spa_config_exit(spa, SCL_ALL, FTAG);
4666
4667 if (error != 0) {
4668 spa_load_failed(spa, "failed to write checkpointed "
4669 "uberblock to the vdev labels [error=%d]", error);
4670 return (error);
4671 }
4672 }
4673
4674 return (0);
4675 }
4676
4677 static int
4678 spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
4679 boolean_t *update_config_cache)
4680 {
4681 int error;
4682
4683 /*
4684 * Parse the config for pool, open and validate vdevs,
4685 * select an uberblock, and use that uberblock to open
4686 * the MOS.
4687 */
4688 error = spa_ld_mos_init(spa, type);
4689 if (error != 0)
4690 return (error);
4691
4692 /*
4693 * Retrieve the trusted config stored in the MOS and use it to create
4694 * a new, exact version of the vdev tree, then reopen all vdevs.
4695 */
4696 error = spa_ld_trusted_config(spa, type, B_FALSE);
4697 if (error == EAGAIN) {
4698 if (update_config_cache != NULL)
4699 *update_config_cache = B_TRUE;
4700
4701 /*
4702 * Redo the loading process with the trusted config if it is
4703 * too different from the untrusted config.
4704 */
4705 spa_ld_prepare_for_reload(spa);
4706 spa_load_note(spa, "RELOADING");
4707 error = spa_ld_mos_init(spa, type);
4708 if (error != 0)
4709 return (error);
4710
4711 error = spa_ld_trusted_config(spa, type, B_TRUE);
4712 if (error != 0)
4713 return (error);
4714
4715 } else if (error != 0) {
4716 return (error);
4717 }
4718
4719 return (0);
4720 }
4721
4722 /*
4723 * Load an existing storage pool, using the config provided. This config
4724 * describes which vdevs are part of the pool and is later validated against
4725 * partial configs present in each vdev's label and an entire copy of the
4726 * config stored in the MOS.
4727 */
4728 static int
4729 spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
4730 {
4731 int error = 0;
4732 boolean_t missing_feat_write = B_FALSE;
4733 boolean_t checkpoint_rewind =
4734 (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4735 boolean_t update_config_cache = B_FALSE;
4736
4737 ASSERT(MUTEX_HELD(&spa_namespace_lock));
4738 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
4739
4740 spa_load_note(spa, "LOADING");
4741
4742 error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
4743 if (error != 0)
4744 return (error);
4745
4746 /*
4747 * If we are rewinding to the checkpoint then we need to repeat
4748 * everything we've done so far in this function but this time
4749 * selecting the checkpointed uberblock and using that to open
4750 * the MOS.
4751 */
4752 if (checkpoint_rewind) {
4753 /*
4754 * If we are rewinding to the checkpoint update config cache
4755 * anyway.
4756 */
4757 update_config_cache = B_TRUE;
4758
4759 /*
4760 * Extract the checkpointed uberblock from the current MOS
4761 * and use this as the pool's uberblock from now on. If the
4762 * pool is imported as writeable we also write the checkpoint
4763 * uberblock to the labels, making the rewind permanent.
4764 */
4765 error = spa_ld_checkpoint_rewind(spa);
4766 if (error != 0)
4767 return (error);
4768
4769 /*
4770 * Redo the loading process again with the
4771 * checkpointed uberblock.
4772 */
4773 spa_ld_prepare_for_reload(spa);
4774 spa_load_note(spa, "LOADING checkpointed uberblock");
4775 error = spa_ld_mos_with_trusted_config(spa, type, NULL);
4776 if (error != 0)
4777 return (error);
4778 }
4779
4780 /*
4781 * Retrieve the checkpoint txg if the pool has a checkpoint.
4782 */
4783 error = spa_ld_read_checkpoint_txg(spa);
4784 if (error != 0)
4785 return (error);
4786
4787 /*
4788 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
4789 * from the pool and their contents were re-mapped to other vdevs. Note
4790 * that everything that we read before this step must have been
4791 * rewritten on concrete vdevs after the last device removal was
4792 * initiated. Otherwise we could be reading from indirect vdevs before
4793 * we have loaded their mappings.
4794 */
4795 error = spa_ld_open_indirect_vdev_metadata(spa);
4796 if (error != 0)
4797 return (error);
4798
4799 /*
4800 * Retrieve the full list of active features from the MOS and check if
4801 * they are all supported.
4802 */
4803 error = spa_ld_check_features(spa, &missing_feat_write);
4804 if (error != 0)
4805 return (error);
4806
4807 /*
4808 * Load several special directories from the MOS needed by the dsl_pool
4809 * layer.
4810 */
4811 error = spa_ld_load_special_directories(spa);
4812 if (error != 0)
4813 return (error);
4814
4815 /*
4816 * Retrieve pool properties from the MOS.
4817 */
4818 error = spa_ld_get_props(spa);
4819 if (error != 0)
4820 return (error);
4821
4822 /*
4823 * Retrieve the list of auxiliary devices - cache devices and spares -
4824 * and open them.
4825 */
4826 error = spa_ld_open_aux_vdevs(spa, type);
4827 if (error != 0)
4828 return (error);
4829
4830 /*
4831 * Load the metadata for all vdevs. Also check if unopenable devices
4832 * should be autoreplaced.
4833 */
4834 error = spa_ld_load_vdev_metadata(spa);
4835 if (error != 0)
4836 return (error);
4837
4838 error = spa_ld_load_dedup_tables(spa);
4839 if (error != 0)
4840 return (error);
4841
4842 /*
4843 * Verify the logs now to make sure we don't have any unexpected errors
4844 * when we claim log blocks later.
4845 */
4846 error = spa_ld_verify_logs(spa, type, ereport);
4847 if (error != 0)
4848 return (error);
4849
4850 if (missing_feat_write) {
4851 ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
4852
4853 /*
4854 * At this point, we know that we can open the pool in
4855 * read-only mode but not read-write mode. We now have enough
4856 * information and can return to userland.
4857 */
4858 return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
4859 ENOTSUP));
4860 }
4861
4862 /*
4863 * Traverse the last txgs to make sure the pool was left off in a safe
4864 * state. When performing an extreme rewind, we verify the whole pool,
4865 * which can take a very long time.
4866 */
4867 error = spa_ld_verify_pool_data(spa);
4868 if (error != 0)
4869 return (error);
4870
4871 /*
4872 * Calculate the deflated space for the pool. This must be done before
4873 * we write anything to the pool because we'd need to update the space
4874 * accounting using the deflated sizes.
4875 */
4876 spa_update_dspace(spa);
4877
4878 /*
4879 * We have now retrieved all the information we needed to open the
4880 * pool. If we are importing the pool in read-write mode, a few
4881 * additional steps must be performed to finish the import.
4882 */
4883 if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
4884 spa->spa_load_max_txg == UINT64_MAX)) {
4885 uint64_t config_cache_txg = spa->spa_config_txg;
4886
4887 ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
4888
4889 /*
4890 * In case of a checkpoint rewind, log the original txg
4891 * of the checkpointed uberblock.
4892 */
4893 if (checkpoint_rewind) {
4894 spa_history_log_internal(spa, "checkpoint rewind",
4895 NULL, "rewound state to txg=%llu",
4896 (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
4897 }
4898
4899 /*
4900 * Traverse the ZIL and claim all blocks.
4901 */
4902 spa_ld_claim_log_blocks(spa);
4903
4904 /*
4905 * Kick-off the syncing thread.
4906 */
4907 spa->spa_sync_on = B_TRUE;
4908 txg_sync_start(spa->spa_dsl_pool);
4909 mmp_thread_start(spa);
4910
4911 /*
4912 * Wait for all claims to sync. We sync up to the highest
4913 * claimed log block birth time so that claimed log blocks
4914 * don't appear to be from the future. spa_claim_max_txg
4915 * will have been set for us by ZIL traversal operations
4916 * performed above.
4917 */
4918 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
4919
4920 /*
4921 * Check if we need to request an update of the config. On the
4922 * next sync, we would update the config stored in vdev labels
4923 * and the cachefile (by default /etc/zfs/zpool.cache).
4924 */
4925 spa_ld_check_for_config_update(spa, config_cache_txg,
4926 update_config_cache);
4927
4928 /*
4929 * Check if a rebuild was in progress and if so resume it.
4930 * Then check all DTLs to see if anything needs resilvering.
4931 * The resilver will be deferred if a rebuild was started.
4932 */
4933 if (vdev_rebuild_active(spa->spa_root_vdev)) {
4934 vdev_rebuild_restart(spa);
4935 } else if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
4936 vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
4937 spa_async_request(spa, SPA_ASYNC_RESILVER);
4938 }
4939
4940 /*
4941 * Log the fact that we booted up (so that we can detect if
4942 * we rebooted in the middle of an operation).
4943 */
4944 spa_history_log_version(spa, "open", NULL);
4945
4946 spa_restart_removal(spa);
4947 spa_spawn_aux_threads(spa);
4948
4949 /*
4950 * Delete any inconsistent datasets.
4951 *
4952 * Note:
4953 * Since we may be issuing deletes for clones here,
4954 * we make sure to do so after we've spawned all the
4955 * auxiliary threads above (from which the livelist
4956 * deletion zthr is part of).
4957 */
4958 (void) dmu_objset_find(spa_name(spa),
4959 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
4960
4961 /*
4962 * Clean up any stale temporary dataset userrefs.
4963 */
4964 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
4965
4966 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4967 vdev_initialize_restart(spa->spa_root_vdev);
4968 vdev_trim_restart(spa->spa_root_vdev);
4969 vdev_autotrim_restart(spa);
4970 spa_config_exit(spa, SCL_CONFIG, FTAG);
4971 }
4972
4973 spa_import_progress_remove(spa_guid(spa));
4974 spa_async_request(spa, SPA_ASYNC_L2CACHE_REBUILD);
4975
4976 spa_load_note(spa, "LOADED");
4977
4978 return (0);
4979 }
4980
4981 static int
4982 spa_load_retry(spa_t *spa, spa_load_state_t state)
4983 {
4984 spa_mode_t mode = spa->spa_mode;
4985
4986 spa_unload(spa);
4987 spa_deactivate(spa);
4988
4989 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
4990
4991 spa_activate(spa, mode);
4992 spa_async_suspend(spa);
4993
4994 spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
4995 (u_longlong_t)spa->spa_load_max_txg);
4996
4997 return (spa_load(spa, state, SPA_IMPORT_EXISTING));
4998 }
4999
5000 /*
5001 * If spa_load() fails this function will try loading prior txg's. If
5002 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
5003 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
5004 * function will not rewind the pool and will return the same error as
5005 * spa_load().
5006 */
5007 static int
5008 spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
5009 int rewind_flags)
5010 {
5011 nvlist_t *loadinfo = NULL;
5012 nvlist_t *config = NULL;
5013 int load_error, rewind_error;
5014 uint64_t safe_rewind_txg;
5015 uint64_t min_txg;
5016
5017 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
5018 spa->spa_load_max_txg = spa->spa_load_txg;
5019 spa_set_log_state(spa, SPA_LOG_CLEAR);
5020 } else {
5021 spa->spa_load_max_txg = max_request;
5022 if (max_request != UINT64_MAX)
5023 spa->spa_extreme_rewind = B_TRUE;
5024 }
5025
5026 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
5027 if (load_error == 0)
5028 return (0);
5029 if (load_error == ZFS_ERR_NO_CHECKPOINT) {
5030 /*
5031 * When attempting checkpoint-rewind on a pool with no
5032 * checkpoint, we should not attempt to load uberblocks
5033 * from previous txgs when spa_load fails.
5034 */
5035 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
5036 spa_import_progress_remove(spa_guid(spa));
5037 return (load_error);
5038 }
5039
5040 if (spa->spa_root_vdev != NULL)
5041 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
5042
5043 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
5044 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
5045
5046 if (rewind_flags & ZPOOL_NEVER_REWIND) {
5047 nvlist_free(config);
5048 spa_import_progress_remove(spa_guid(spa));
5049 return (load_error);
5050 }
5051
5052 if (state == SPA_LOAD_RECOVER) {
5053 /* Price of rolling back is discarding txgs, including log */
5054 spa_set_log_state(spa, SPA_LOG_CLEAR);
5055 } else {
5056 /*
5057 * If we aren't rolling back save the load info from our first
5058 * import attempt so that we can restore it after attempting
5059 * to rewind.
5060 */
5061 loadinfo = spa->spa_load_info;
5062 spa->spa_load_info = fnvlist_alloc();
5063 }
5064
5065 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
5066 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
5067 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
5068 TXG_INITIAL : safe_rewind_txg;
5069
5070 /*
5071 * Continue as long as we're finding errors, we're still within
5072 * the acceptable rewind range, and we're still finding uberblocks
5073 */
5074 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
5075 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
5076 if (spa->spa_load_max_txg < safe_rewind_txg)
5077 spa->spa_extreme_rewind = B_TRUE;
5078 rewind_error = spa_load_retry(spa, state);
5079 }
5080
5081 spa->spa_extreme_rewind = B_FALSE;
5082 spa->spa_load_max_txg = UINT64_MAX;
5083
5084 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
5085 spa_config_set(spa, config);
5086 else
5087 nvlist_free(config);
5088
5089 if (state == SPA_LOAD_RECOVER) {
5090 ASSERT3P(loadinfo, ==, NULL);
5091 spa_import_progress_remove(spa_guid(spa));
5092 return (rewind_error);
5093 } else {
5094 /* Store the rewind info as part of the initial load info */
5095 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
5096 spa->spa_load_info);
5097
5098 /* Restore the initial load info */
5099 fnvlist_free(spa->spa_load_info);
5100 spa->spa_load_info = loadinfo;
5101
5102 spa_import_progress_remove(spa_guid(spa));
5103 return (load_error);
5104 }
5105 }
5106
5107 /*
5108 * Pool Open/Import
5109 *
5110 * The import case is identical to an open except that the configuration is sent
5111 * down from userland, instead of grabbed from the configuration cache. For the
5112 * case of an open, the pool configuration will exist in the
5113 * POOL_STATE_UNINITIALIZED state.
5114 *
5115 * The stats information (gen/count/ustats) is used to gather vdev statistics at
5116 * the same time open the pool, without having to keep around the spa_t in some
5117 * ambiguous state.
5118 */
5119 static int
5120 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
5121 nvlist_t **config)
5122 {
5123 spa_t *spa;
5124 spa_load_state_t state = SPA_LOAD_OPEN;
5125 int error;
5126 int locked = B_FALSE;
5127 int firstopen = B_FALSE;
5128
5129 *spapp = NULL;
5130
5131 /*
5132 * As disgusting as this is, we need to support recursive calls to this
5133 * function because dsl_dir_open() is called during spa_load(), and ends
5134 * up calling spa_open() again. The real fix is to figure out how to
5135 * avoid dsl_dir_open() calling this in the first place.
5136 */
5137 if (MUTEX_NOT_HELD(&spa_namespace_lock)) {
5138 mutex_enter(&spa_namespace_lock);
5139 locked = B_TRUE;
5140 }
5141
5142 if ((spa = spa_lookup(pool)) == NULL) {
5143 if (locked)
5144 mutex_exit(&spa_namespace_lock);
5145 return (SET_ERROR(ENOENT));
5146 }
5147
5148 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
5149 zpool_load_policy_t policy;
5150
5151 firstopen = B_TRUE;
5152
5153 zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
5154 &policy);
5155 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
5156 state = SPA_LOAD_RECOVER;
5157
5158 spa_activate(spa, spa_mode_global);
5159
5160 if (state != SPA_LOAD_RECOVER)
5161 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5162 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
5163
5164 zfs_dbgmsg("spa_open_common: opening %s", pool);
5165 error = spa_load_best(spa, state, policy.zlp_txg,
5166 policy.zlp_rewind);
5167
5168 if (error == EBADF) {
5169 /*
5170 * If vdev_validate() returns failure (indicated by
5171 * EBADF), it indicates that one of the vdevs indicates
5172 * that the pool has been exported or destroyed. If
5173 * this is the case, the config cache is out of sync and
5174 * we should remove the pool from the namespace.
5175 */
5176 spa_unload(spa);
5177 spa_deactivate(spa);
5178 spa_write_cachefile(spa, B_TRUE, B_TRUE);
5179 spa_remove(spa);
5180 if (locked)
5181 mutex_exit(&spa_namespace_lock);
5182 return (SET_ERROR(ENOENT));
5183 }
5184
5185 if (error) {
5186 /*
5187 * We can't open the pool, but we still have useful
5188 * information: the state of each vdev after the
5189 * attempted vdev_open(). Return this to the user.
5190 */
5191 if (config != NULL && spa->spa_config) {
5192 VERIFY(nvlist_dup(spa->spa_config, config,
5193 KM_SLEEP) == 0);
5194 VERIFY(nvlist_add_nvlist(*config,
5195 ZPOOL_CONFIG_LOAD_INFO,
5196 spa->spa_load_info) == 0);
5197 }
5198 spa_unload(spa);
5199 spa_deactivate(spa);
5200 spa->spa_last_open_failed = error;
5201 if (locked)
5202 mutex_exit(&spa_namespace_lock);
5203 *spapp = NULL;
5204 return (error);
5205 }
5206 }
5207
5208 spa_open_ref(spa, tag);
5209
5210 if (config != NULL)
5211 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
5212
5213 /*
5214 * If we've recovered the pool, pass back any information we
5215 * gathered while doing the load.
5216 */
5217 if (state == SPA_LOAD_RECOVER) {
5218 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
5219 spa->spa_load_info) == 0);
5220 }
5221
5222 if (locked) {
5223 spa->spa_last_open_failed = 0;
5224 spa->spa_last_ubsync_txg = 0;
5225 spa->spa_load_txg = 0;
5226 mutex_exit(&spa_namespace_lock);
5227 }
5228
5229 if (firstopen)
5230 zvol_create_minors_recursive(spa_name(spa));
5231
5232 *spapp = spa;
5233
5234 return (0);
5235 }
5236
5237 int
5238 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
5239 nvlist_t **config)
5240 {
5241 return (spa_open_common(name, spapp, tag, policy, config));
5242 }
5243
5244 int
5245 spa_open(const char *name, spa_t **spapp, void *tag)
5246 {
5247 return (spa_open_common(name, spapp, tag, NULL, NULL));
5248 }
5249
5250 /*
5251 * Lookup the given spa_t, incrementing the inject count in the process,
5252 * preventing it from being exported or destroyed.
5253 */
5254 spa_t *
5255 spa_inject_addref(char *name)
5256 {
5257 spa_t *spa;
5258
5259 mutex_enter(&spa_namespace_lock);
5260 if ((spa = spa_lookup(name)) == NULL) {
5261 mutex_exit(&spa_namespace_lock);
5262 return (NULL);
5263 }
5264 spa->spa_inject_ref++;
5265 mutex_exit(&spa_namespace_lock);
5266
5267 return (spa);
5268 }
5269
5270 void
5271 spa_inject_delref(spa_t *spa)
5272 {
5273 mutex_enter(&spa_namespace_lock);
5274 spa->spa_inject_ref--;
5275 mutex_exit(&spa_namespace_lock);
5276 }
5277
5278 /*
5279 * Add spares device information to the nvlist.
5280 */
5281 static void
5282 spa_add_spares(spa_t *spa, nvlist_t *config)
5283 {
5284 nvlist_t **spares;
5285 uint_t i, nspares;
5286 nvlist_t *nvroot;
5287 uint64_t guid;
5288 vdev_stat_t *vs;
5289 uint_t vsc;
5290 uint64_t pool;
5291
5292 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
5293
5294 if (spa->spa_spares.sav_count == 0)
5295 return;
5296
5297 VERIFY(nvlist_lookup_nvlist(config,
5298 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
5299 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
5300 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
5301 if (nspares != 0) {
5302 VERIFY(nvlist_add_nvlist_array(nvroot,
5303 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5304 VERIFY(nvlist_lookup_nvlist_array(nvroot,
5305 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
5306
5307 /*
5308 * Go through and find any spares which have since been
5309 * repurposed as an active spare. If this is the case, update
5310 * their status appropriately.
5311 */
5312 for (i = 0; i < nspares; i++) {
5313 VERIFY(nvlist_lookup_uint64(spares[i],
5314 ZPOOL_CONFIG_GUID, &guid) == 0);
5315 if (spa_spare_exists(guid, &pool, NULL) &&
5316 pool != 0ULL) {
5317 VERIFY(nvlist_lookup_uint64_array(
5318 spares[i], ZPOOL_CONFIG_VDEV_STATS,
5319 (uint64_t **)&vs, &vsc) == 0);
5320 vs->vs_state = VDEV_STATE_CANT_OPEN;
5321 vs->vs_aux = VDEV_AUX_SPARED;
5322 }
5323 }
5324 }
5325 }
5326
5327 /*
5328 * Add l2cache device information to the nvlist, including vdev stats.
5329 */
5330 static void
5331 spa_add_l2cache(spa_t *spa, nvlist_t *config)
5332 {
5333 nvlist_t **l2cache;
5334 uint_t i, j, nl2cache;
5335 nvlist_t *nvroot;
5336 uint64_t guid;
5337 vdev_t *vd;
5338 vdev_stat_t *vs;
5339 uint_t vsc;
5340
5341 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
5342
5343 if (spa->spa_l2cache.sav_count == 0)
5344 return;
5345
5346 VERIFY(nvlist_lookup_nvlist(config,
5347 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
5348 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
5349 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
5350 if (nl2cache != 0) {
5351 VERIFY(nvlist_add_nvlist_array(nvroot,
5352 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5353 VERIFY(nvlist_lookup_nvlist_array(nvroot,
5354 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
5355
5356 /*
5357 * Update level 2 cache device stats.
5358 */
5359
5360 for (i = 0; i < nl2cache; i++) {
5361 VERIFY(nvlist_lookup_uint64(l2cache[i],
5362 ZPOOL_CONFIG_GUID, &guid) == 0);
5363
5364 vd = NULL;
5365 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
5366 if (guid ==
5367 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
5368 vd = spa->spa_l2cache.sav_vdevs[j];
5369 break;
5370 }
5371 }
5372 ASSERT(vd != NULL);
5373
5374 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
5375 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
5376 == 0);
5377 vdev_get_stats(vd, vs);
5378 vdev_config_generate_stats(vd, l2cache[i]);
5379
5380 }
5381 }
5382 }
5383
5384 static void
5385 spa_feature_stats_from_disk(spa_t *spa, nvlist_t *features)
5386 {
5387 zap_cursor_t zc;
5388 zap_attribute_t za;
5389
5390 if (spa->spa_feat_for_read_obj != 0) {
5391 for (zap_cursor_init(&zc, spa->spa_meta_objset,
5392 spa->spa_feat_for_read_obj);
5393 zap_cursor_retrieve(&zc, &za) == 0;
5394 zap_cursor_advance(&zc)) {
5395 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
5396 za.za_num_integers == 1);
5397 VERIFY0(nvlist_add_uint64(features, za.za_name,
5398 za.za_first_integer));
5399 }
5400 zap_cursor_fini(&zc);
5401 }
5402
5403 if (spa->spa_feat_for_write_obj != 0) {
5404 for (zap_cursor_init(&zc, spa->spa_meta_objset,
5405 spa->spa_feat_for_write_obj);
5406 zap_cursor_retrieve(&zc, &za) == 0;
5407 zap_cursor_advance(&zc)) {
5408 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
5409 za.za_num_integers == 1);
5410 VERIFY0(nvlist_add_uint64(features, za.za_name,
5411 za.za_first_integer));
5412 }
5413 zap_cursor_fini(&zc);
5414 }
5415 }
5416
5417 static void
5418 spa_feature_stats_from_cache(spa_t *spa, nvlist_t *features)
5419 {
5420 int i;
5421
5422 for (i = 0; i < SPA_FEATURES; i++) {
5423 zfeature_info_t feature = spa_feature_table[i];
5424 uint64_t refcount;
5425
5426 if (feature_get_refcount(spa, &feature, &refcount) != 0)
5427 continue;
5428
5429 VERIFY0(nvlist_add_uint64(features, feature.fi_guid, refcount));
5430 }
5431 }
5432
5433 /*
5434 * Store a list of pool features and their reference counts in the
5435 * config.
5436 *
5437 * The first time this is called on a spa, allocate a new nvlist, fetch
5438 * the pool features and reference counts from disk, then save the list
5439 * in the spa. In subsequent calls on the same spa use the saved nvlist
5440 * and refresh its values from the cached reference counts. This
5441 * ensures we don't block here on I/O on a suspended pool so 'zpool
5442 * clear' can resume the pool.
5443 */
5444 static void
5445 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
5446 {
5447 nvlist_t *features;
5448
5449 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
5450
5451 mutex_enter(&spa->spa_feat_stats_lock);
5452 features = spa->spa_feat_stats;
5453
5454 if (features != NULL) {
5455 spa_feature_stats_from_cache(spa, features);
5456 } else {
5457 VERIFY0(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP));
5458 spa->spa_feat_stats = features;
5459 spa_feature_stats_from_disk(spa, features);
5460 }
5461
5462 VERIFY0(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
5463 features));
5464
5465 mutex_exit(&spa->spa_feat_stats_lock);
5466 }
5467
5468 int
5469 spa_get_stats(const char *name, nvlist_t **config,
5470 char *altroot, size_t buflen)
5471 {
5472 int error;
5473 spa_t *spa;
5474
5475 *config = NULL;
5476 error = spa_open_common(name, &spa, FTAG, NULL, config);
5477
5478 if (spa != NULL) {
5479 /*
5480 * This still leaves a window of inconsistency where the spares
5481 * or l2cache devices could change and the config would be
5482 * self-inconsistent.
5483 */
5484 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5485
5486 if (*config != NULL) {
5487 uint64_t loadtimes[2];
5488
5489 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
5490 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
5491 VERIFY(nvlist_add_uint64_array(*config,
5492 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
5493
5494 VERIFY(nvlist_add_uint64(*config,
5495 ZPOOL_CONFIG_ERRCOUNT,
5496 spa_get_errlog_size(spa)) == 0);
5497
5498 if (spa_suspended(spa)) {
5499 VERIFY(nvlist_add_uint64(*config,
5500 ZPOOL_CONFIG_SUSPENDED,
5501 spa->spa_failmode) == 0);
5502 VERIFY(nvlist_add_uint64(*config,
5503 ZPOOL_CONFIG_SUSPENDED_REASON,
5504 spa->spa_suspended) == 0);
5505 }
5506
5507 spa_add_spares(spa, *config);
5508 spa_add_l2cache(spa, *config);
5509 spa_add_feature_stats(spa, *config);
5510 }
5511 }
5512
5513 /*
5514 * We want to get the alternate root even for faulted pools, so we cheat
5515 * and call spa_lookup() directly.
5516 */
5517 if (altroot) {
5518 if (spa == NULL) {
5519 mutex_enter(&spa_namespace_lock);
5520 spa = spa_lookup(name);
5521 if (spa)
5522 spa_altroot(spa, altroot, buflen);
5523 else
5524 altroot[0] = '\0';
5525 spa = NULL;
5526 mutex_exit(&spa_namespace_lock);
5527 } else {
5528 spa_altroot(spa, altroot, buflen);
5529 }
5530 }
5531
5532 if (spa != NULL) {
5533 spa_config_exit(spa, SCL_CONFIG, FTAG);
5534 spa_close(spa, FTAG);
5535 }
5536
5537 return (error);
5538 }
5539
5540 /*
5541 * Validate that the auxiliary device array is well formed. We must have an
5542 * array of nvlists, each which describes a valid leaf vdev. If this is an
5543 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
5544 * specified, as long as they are well-formed.
5545 */
5546 static int
5547 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
5548 spa_aux_vdev_t *sav, const char *config, uint64_t version,
5549 vdev_labeltype_t label)
5550 {
5551 nvlist_t **dev;
5552 uint_t i, ndev;
5553 vdev_t *vd;
5554 int error;
5555
5556 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5557
5558 /*
5559 * It's acceptable to have no devs specified.
5560 */
5561 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
5562 return (0);
5563
5564 if (ndev == 0)
5565 return (SET_ERROR(EINVAL));
5566
5567 /*
5568 * Make sure the pool is formatted with a version that supports this
5569 * device type.
5570 */
5571 if (spa_version(spa) < version)
5572 return (SET_ERROR(ENOTSUP));
5573
5574 /*
5575 * Set the pending device list so we correctly handle device in-use
5576 * checking.
5577 */
5578 sav->sav_pending = dev;
5579 sav->sav_npending = ndev;
5580
5581 for (i = 0; i < ndev; i++) {
5582 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
5583 mode)) != 0)
5584 goto out;
5585
5586 if (!vd->vdev_ops->vdev_op_leaf) {
5587 vdev_free(vd);
5588 error = SET_ERROR(EINVAL);
5589 goto out;
5590 }
5591
5592 vd->vdev_top = vd;
5593
5594 if ((error = vdev_open(vd)) == 0 &&
5595 (error = vdev_label_init(vd, crtxg, label)) == 0) {
5596 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
5597 vd->vdev_guid) == 0);
5598 }
5599
5600 vdev_free(vd);
5601
5602 if (error &&
5603 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
5604 goto out;
5605 else
5606 error = 0;
5607 }
5608
5609 out:
5610 sav->sav_pending = NULL;
5611 sav->sav_npending = 0;
5612 return (error);
5613 }
5614
5615 static int
5616 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
5617 {
5618 int error;
5619
5620 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5621
5622 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
5623 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
5624 VDEV_LABEL_SPARE)) != 0) {
5625 return (error);
5626 }
5627
5628 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
5629 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
5630 VDEV_LABEL_L2CACHE));
5631 }
5632
5633 static void
5634 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
5635 const char *config)
5636 {
5637 int i;
5638
5639 if (sav->sav_config != NULL) {
5640 nvlist_t **olddevs;
5641 uint_t oldndevs;
5642 nvlist_t **newdevs;
5643
5644 /*
5645 * Generate new dev list by concatenating with the
5646 * current dev list.
5647 */
5648 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
5649 &olddevs, &oldndevs) == 0);
5650
5651 newdevs = kmem_alloc(sizeof (void *) *
5652 (ndevs + oldndevs), KM_SLEEP);
5653 for (i = 0; i < oldndevs; i++)
5654 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
5655 KM_SLEEP) == 0);
5656 for (i = 0; i < ndevs; i++)
5657 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
5658 KM_SLEEP) == 0);
5659
5660 VERIFY(nvlist_remove(sav->sav_config, config,
5661 DATA_TYPE_NVLIST_ARRAY) == 0);
5662
5663 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
5664 config, newdevs, ndevs + oldndevs) == 0);
5665 for (i = 0; i < oldndevs + ndevs; i++)
5666 nvlist_free(newdevs[i]);
5667 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
5668 } else {
5669 /*
5670 * Generate a new dev list.
5671 */
5672 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
5673 KM_SLEEP) == 0);
5674 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
5675 devs, ndevs) == 0);
5676 }
5677 }
5678
5679 /*
5680 * Stop and drop level 2 ARC devices
5681 */
5682 void
5683 spa_l2cache_drop(spa_t *spa)
5684 {
5685 vdev_t *vd;
5686 int i;
5687 spa_aux_vdev_t *sav = &spa->spa_l2cache;
5688
5689 for (i = 0; i < sav->sav_count; i++) {
5690 uint64_t pool;
5691
5692 vd = sav->sav_vdevs[i];
5693 ASSERT(vd != NULL);
5694
5695 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
5696 pool != 0ULL && l2arc_vdev_present(vd))
5697 l2arc_remove_vdev(vd);
5698 }
5699 }
5700
5701 /*
5702 * Verify encryption parameters for spa creation. If we are encrypting, we must
5703 * have the encryption feature flag enabled.
5704 */
5705 static int
5706 spa_create_check_encryption_params(dsl_crypto_params_t *dcp,
5707 boolean_t has_encryption)
5708 {
5709 if (dcp->cp_crypt != ZIO_CRYPT_OFF &&
5710 dcp->cp_crypt != ZIO_CRYPT_INHERIT &&
5711 !has_encryption)
5712 return (SET_ERROR(ENOTSUP));
5713
5714 return (dmu_objset_create_crypt_check(NULL, dcp, NULL));
5715 }
5716
5717 /*
5718 * Pool Creation
5719 */
5720 int
5721 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
5722 nvlist_t *zplprops, dsl_crypto_params_t *dcp)
5723 {
5724 spa_t *spa;
5725 char *altroot = NULL;
5726 vdev_t *rvd;
5727 dsl_pool_t *dp;
5728 dmu_tx_t *tx;
5729 int error = 0;
5730 uint64_t txg = TXG_INITIAL;
5731 nvlist_t **spares, **l2cache;
5732 uint_t nspares, nl2cache;
5733 uint64_t version, obj, ndraid = 0;
5734 boolean_t has_features;
5735 boolean_t has_encryption;
5736 boolean_t has_allocclass;
5737 spa_feature_t feat;
5738 char *feat_name;
5739 char *poolname;
5740 nvlist_t *nvl;
5741
5742 if (props == NULL ||
5743 nvlist_lookup_string(props, "tname", &poolname) != 0)
5744 poolname = (char *)pool;
5745
5746 /*
5747 * If this pool already exists, return failure.
5748 */
5749 mutex_enter(&spa_namespace_lock);
5750 if (spa_lookup(poolname) != NULL) {
5751 mutex_exit(&spa_namespace_lock);
5752 return (SET_ERROR(EEXIST));
5753 }
5754
5755 /*
5756 * Allocate a new spa_t structure.
5757 */
5758 nvl = fnvlist_alloc();
5759 fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
5760 (void) nvlist_lookup_string(props,
5761 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5762 spa = spa_add(poolname, nvl, altroot);
5763 fnvlist_free(nvl);
5764 spa_activate(spa, spa_mode_global);
5765
5766 if (props && (error = spa_prop_validate(spa, props))) {
5767 spa_deactivate(spa);
5768 spa_remove(spa);
5769 mutex_exit(&spa_namespace_lock);
5770 return (error);
5771 }
5772
5773 /*
5774 * Temporary pool names should never be written to disk.
5775 */
5776 if (poolname != pool)
5777 spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
5778
5779 has_features = B_FALSE;
5780 has_encryption = B_FALSE;
5781 has_allocclass = B_FALSE;
5782 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
5783 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
5784 if (zpool_prop_feature(nvpair_name(elem))) {
5785 has_features = B_TRUE;
5786
5787 feat_name = strchr(nvpair_name(elem), '@') + 1;
5788 VERIFY0(zfeature_lookup_name(feat_name, &feat));
5789 if (feat == SPA_FEATURE_ENCRYPTION)
5790 has_encryption = B_TRUE;
5791 if (feat == SPA_FEATURE_ALLOCATION_CLASSES)
5792 has_allocclass = B_TRUE;
5793 }
5794 }
5795
5796 /* verify encryption params, if they were provided */
5797 if (dcp != NULL) {
5798 error = spa_create_check_encryption_params(dcp, has_encryption);
5799 if (error != 0) {
5800 spa_deactivate(spa);
5801 spa_remove(spa);
5802 mutex_exit(&spa_namespace_lock);
5803 return (error);
5804 }
5805 }
5806 if (!has_allocclass && zfs_special_devs(nvroot, NULL)) {
5807 spa_deactivate(spa);
5808 spa_remove(spa);
5809 mutex_exit(&spa_namespace_lock);
5810 return (ENOTSUP);
5811 }
5812
5813 if (has_features || nvlist_lookup_uint64(props,
5814 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
5815 version = SPA_VERSION;
5816 }
5817 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
5818
5819 spa->spa_first_txg = txg;
5820 spa->spa_uberblock.ub_txg = txg - 1;
5821 spa->spa_uberblock.ub_version = version;
5822 spa->spa_ubsync = spa->spa_uberblock;
5823 spa->spa_load_state = SPA_LOAD_CREATE;
5824 spa->spa_removing_phys.sr_state = DSS_NONE;
5825 spa->spa_removing_phys.sr_removing_vdev = -1;
5826 spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
5827 spa->spa_indirect_vdevs_loaded = B_TRUE;
5828
5829 /*
5830 * Create "The Godfather" zio to hold all async IOs
5831 */
5832 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
5833 KM_SLEEP);
5834 for (int i = 0; i < max_ncpus; i++) {
5835 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
5836 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
5837 ZIO_FLAG_GODFATHER);
5838 }
5839
5840 /*
5841 * Create the root vdev.
5842 */
5843 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5844
5845 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
5846
5847 ASSERT(error != 0 || rvd != NULL);
5848 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
5849
5850 if (error == 0 && !zfs_allocatable_devs(nvroot))
5851 error = SET_ERROR(EINVAL);
5852
5853 if (error == 0 &&
5854 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
5855 (error = vdev_draid_spare_create(nvroot, rvd, &ndraid, 0)) == 0 &&
5856 (error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) == 0) {
5857 /*
5858 * instantiate the metaslab groups (this will dirty the vdevs)
5859 * we can no longer error exit past this point
5860 */
5861 for (int c = 0; error == 0 && c < rvd->vdev_children; c++) {
5862 vdev_t *vd = rvd->vdev_child[c];
5863
5864 vdev_metaslab_set_size(vd);
5865 vdev_expand(vd, txg);
5866 }
5867 }
5868
5869 spa_config_exit(spa, SCL_ALL, FTAG);
5870
5871 if (error != 0) {
5872 spa_unload(spa);
5873 spa_deactivate(spa);
5874 spa_remove(spa);
5875 mutex_exit(&spa_namespace_lock);
5876 return (error);
5877 }
5878
5879 /*
5880 * Get the list of spares, if specified.
5881 */
5882 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5883 &spares, &nspares) == 0) {
5884 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
5885 KM_SLEEP) == 0);
5886 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5887 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5888 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5889 spa_load_spares(spa);
5890 spa_config_exit(spa, SCL_ALL, FTAG);
5891 spa->spa_spares.sav_sync = B_TRUE;
5892 }
5893
5894 /*
5895 * Get the list of level 2 cache devices, if specified.
5896 */
5897 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5898 &l2cache, &nl2cache) == 0) {
5899 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5900 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5901 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5902 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5903 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5904 spa_load_l2cache(spa);
5905 spa_config_exit(spa, SCL_ALL, FTAG);
5906 spa->spa_l2cache.sav_sync = B_TRUE;
5907 }
5908
5909 spa->spa_is_initializing = B_TRUE;
5910 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, dcp, txg);
5911 spa->spa_is_initializing = B_FALSE;
5912
5913 /*
5914 * Create DDTs (dedup tables).
5915 */
5916 ddt_create(spa);
5917
5918 spa_update_dspace(spa);
5919
5920 tx = dmu_tx_create_assigned(dp, txg);
5921
5922 /*
5923 * Create the pool's history object.
5924 */
5925 if (version >= SPA_VERSION_ZPOOL_HISTORY && !spa->spa_history)
5926 spa_history_create_obj(spa, tx);
5927
5928 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
5929 spa_history_log_version(spa, "create", tx);
5930
5931 /*
5932 * Create the pool config object.
5933 */
5934 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
5935 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
5936 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
5937
5938 if (zap_add(spa->spa_meta_objset,
5939 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
5940 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
5941 cmn_err(CE_PANIC, "failed to add pool config");
5942 }
5943
5944 if (zap_add(spa->spa_meta_objset,
5945 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
5946 sizeof (uint64_t), 1, &version, tx) != 0) {
5947 cmn_err(CE_PANIC, "failed to add pool version");
5948 }
5949
5950 /* Newly created pools with the right version are always deflated. */
5951 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
5952 spa->spa_deflate = TRUE;
5953 if (zap_add(spa->spa_meta_objset,
5954 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
5955 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
5956 cmn_err(CE_PANIC, "failed to add deflate");
5957 }
5958 }
5959
5960 /*
5961 * Create the deferred-free bpobj. Turn off compression
5962 * because sync-to-convergence takes longer if the blocksize
5963 * keeps changing.
5964 */
5965 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
5966 dmu_object_set_compress(spa->spa_meta_objset, obj,
5967 ZIO_COMPRESS_OFF, tx);
5968 if (zap_add(spa->spa_meta_objset,
5969 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
5970 sizeof (uint64_t), 1, &obj, tx) != 0) {
5971 cmn_err(CE_PANIC, "failed to add bpobj");
5972 }
5973 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
5974 spa->spa_meta_objset, obj));
5975
5976 /*
5977 * Generate some random noise for salted checksums to operate on.
5978 */
5979 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
5980 sizeof (spa->spa_cksum_salt.zcs_bytes));
5981
5982 /*
5983 * Set pool properties.
5984 */
5985 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
5986 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
5987 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
5988 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
5989 spa->spa_multihost = zpool_prop_default_numeric(ZPOOL_PROP_MULTIHOST);
5990 spa->spa_autotrim = zpool_prop_default_numeric(ZPOOL_PROP_AUTOTRIM);
5991
5992 if (props != NULL) {
5993 spa_configfile_set(spa, props, B_FALSE);
5994 spa_sync_props(props, tx);
5995 }
5996
5997 for (int i = 0; i < ndraid; i++)
5998 spa_feature_incr(spa, SPA_FEATURE_DRAID, tx);
5999
6000 dmu_tx_commit(tx);
6001
6002 spa->spa_sync_on = B_TRUE;
6003 txg_sync_start(dp);
6004 mmp_thread_start(spa);
6005 txg_wait_synced(dp, txg);
6006
6007 spa_spawn_aux_threads(spa);
6008
6009 spa_write_cachefile(spa, B_FALSE, B_TRUE);
6010
6011 /*
6012 * Don't count references from objsets that are already closed
6013 * and are making their way through the eviction process.
6014 */
6015 spa_evicting_os_wait(spa);
6016 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
6017 spa->spa_load_state = SPA_LOAD_NONE;
6018
6019 mutex_exit(&spa_namespace_lock);
6020
6021 return (0);
6022 }
6023
6024 /*
6025 * Import a non-root pool into the system.
6026 */
6027 int
6028 spa_import(char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
6029 {
6030 spa_t *spa;
6031 char *altroot = NULL;
6032 spa_load_state_t state = SPA_LOAD_IMPORT;
6033 zpool_load_policy_t policy;
6034 spa_mode_t mode = spa_mode_global;
6035 uint64_t readonly = B_FALSE;
6036 int error;
6037 nvlist_t *nvroot;
6038 nvlist_t **spares, **l2cache;
6039 uint_t nspares, nl2cache;
6040
6041 /*
6042 * If a pool with this name exists, return failure.
6043 */
6044 mutex_enter(&spa_namespace_lock);
6045 if (spa_lookup(pool) != NULL) {
6046 mutex_exit(&spa_namespace_lock);
6047 return (SET_ERROR(EEXIST));
6048 }
6049
6050 /*
6051 * Create and initialize the spa structure.
6052 */
6053 (void) nvlist_lookup_string(props,
6054 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
6055 (void) nvlist_lookup_uint64(props,
6056 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
6057 if (readonly)
6058 mode = SPA_MODE_READ;
6059 spa = spa_add(pool, config, altroot);
6060 spa->spa_import_flags = flags;
6061
6062 /*
6063 * Verbatim import - Take a pool and insert it into the namespace
6064 * as if it had been loaded at boot.
6065 */
6066 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
6067 if (props != NULL)
6068 spa_configfile_set(spa, props, B_FALSE);
6069
6070 spa_write_cachefile(spa, B_FALSE, B_TRUE);
6071 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
6072 zfs_dbgmsg("spa_import: verbatim import of %s", pool);
6073 mutex_exit(&spa_namespace_lock);
6074 return (0);
6075 }
6076
6077 spa_activate(spa, mode);
6078
6079 /*
6080 * Don't start async tasks until we know everything is healthy.
6081 */
6082 spa_async_suspend(spa);
6083
6084 zpool_get_load_policy(config, &policy);
6085 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
6086 state = SPA_LOAD_RECOVER;
6087
6088 spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
6089
6090 if (state != SPA_LOAD_RECOVER) {
6091 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
6092 zfs_dbgmsg("spa_import: importing %s", pool);
6093 } else {
6094 zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
6095 "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
6096 }
6097 error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
6098
6099 /*
6100 * Propagate anything learned while loading the pool and pass it
6101 * back to caller (i.e. rewind info, missing devices, etc).
6102 */
6103 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
6104 spa->spa_load_info) == 0);
6105
6106 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6107 /*
6108 * Toss any existing sparelist, as it doesn't have any validity
6109 * anymore, and conflicts with spa_has_spare().
6110 */
6111 if (spa->spa_spares.sav_config) {
6112 nvlist_free(spa->spa_spares.sav_config);
6113 spa->spa_spares.sav_config = NULL;
6114 spa_load_spares(spa);
6115 }
6116 if (spa->spa_l2cache.sav_config) {
6117 nvlist_free(spa->spa_l2cache.sav_config);
6118 spa->spa_l2cache.sav_config = NULL;
6119 spa_load_l2cache(spa);
6120 }
6121
6122 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
6123 &nvroot) == 0);
6124 spa_config_exit(spa, SCL_ALL, FTAG);
6125
6126 if (props != NULL)
6127 spa_configfile_set(spa, props, B_FALSE);
6128
6129 if (error != 0 || (props && spa_writeable(spa) &&
6130 (error = spa_prop_set(spa, props)))) {
6131 spa_unload(spa);
6132 spa_deactivate(spa);
6133 spa_remove(spa);
6134 mutex_exit(&spa_namespace_lock);
6135 return (error);
6136 }
6137
6138 spa_async_resume(spa);
6139
6140 /*
6141 * Override any spares and level 2 cache devices as specified by
6142 * the user, as these may have correct device names/devids, etc.
6143 */
6144 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
6145 &spares, &nspares) == 0) {
6146 if (spa->spa_spares.sav_config)
6147 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
6148 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
6149 else
6150 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
6151 NV_UNIQUE_NAME, KM_SLEEP) == 0);
6152 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
6153 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
6154 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6155 spa_load_spares(spa);
6156 spa_config_exit(spa, SCL_ALL, FTAG);
6157 spa->spa_spares.sav_sync = B_TRUE;
6158 }
6159 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
6160 &l2cache, &nl2cache) == 0) {
6161 if (spa->spa_l2cache.sav_config)
6162 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
6163 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
6164 else
6165 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
6166 NV_UNIQUE_NAME, KM_SLEEP) == 0);
6167 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
6168 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
6169 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6170 spa_load_l2cache(spa);
6171 spa_config_exit(spa, SCL_ALL, FTAG);
6172 spa->spa_l2cache.sav_sync = B_TRUE;
6173 }
6174
6175 /*
6176 * Check for any removed devices.
6177 */
6178 if (spa->spa_autoreplace) {
6179 spa_aux_check_removed(&spa->spa_spares);
6180 spa_aux_check_removed(&spa->spa_l2cache);
6181 }
6182
6183 if (spa_writeable(spa)) {
6184 /*
6185 * Update the config cache to include the newly-imported pool.
6186 */
6187 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
6188 }
6189
6190 /*
6191 * It's possible that the pool was expanded while it was exported.
6192 * We kick off an async task to handle this for us.
6193 */
6194 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
6195
6196 spa_history_log_version(spa, "import", NULL);
6197
6198 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
6199
6200 mutex_exit(&spa_namespace_lock);
6201
6202 zvol_create_minors_recursive(pool);
6203
6204 return (0);
6205 }
6206
6207 nvlist_t *
6208 spa_tryimport(nvlist_t *tryconfig)
6209 {
6210 nvlist_t *config = NULL;
6211 char *poolname, *cachefile;
6212 spa_t *spa;
6213 uint64_t state;
6214 int error;
6215 zpool_load_policy_t policy;
6216
6217 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
6218 return (NULL);
6219
6220 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
6221 return (NULL);
6222
6223 /*
6224 * Create and initialize the spa structure.
6225 */
6226 mutex_enter(&spa_namespace_lock);
6227 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
6228 spa_activate(spa, SPA_MODE_READ);
6229
6230 /*
6231 * Rewind pool if a max txg was provided.
6232 */
6233 zpool_get_load_policy(spa->spa_config, &policy);
6234 if (policy.zlp_txg != UINT64_MAX) {
6235 spa->spa_load_max_txg = policy.zlp_txg;
6236 spa->spa_extreme_rewind = B_TRUE;
6237 zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
6238 poolname, (longlong_t)policy.zlp_txg);
6239 } else {
6240 zfs_dbgmsg("spa_tryimport: importing %s", poolname);
6241 }
6242
6243 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
6244 == 0) {
6245 zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
6246 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
6247 } else {
6248 spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
6249 }
6250
6251 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
6252
6253 /*
6254 * If 'tryconfig' was at least parsable, return the current config.
6255 */
6256 if (spa->spa_root_vdev != NULL) {
6257 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
6258 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
6259 poolname) == 0);
6260 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
6261 state) == 0);
6262 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
6263 spa->spa_uberblock.ub_timestamp) == 0);
6264 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
6265 spa->spa_load_info) == 0);
6266 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_ERRATA,
6267 spa->spa_errata) == 0);
6268
6269 /*
6270 * If the bootfs property exists on this pool then we
6271 * copy it out so that external consumers can tell which
6272 * pools are bootable.
6273 */
6274 if ((!error || error == EEXIST) && spa->spa_bootfs) {
6275 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
6276
6277 /*
6278 * We have to play games with the name since the
6279 * pool was opened as TRYIMPORT_NAME.
6280 */
6281 if (dsl_dsobj_to_dsname(spa_name(spa),
6282 spa->spa_bootfs, tmpname) == 0) {
6283 char *cp;
6284 char *dsname;
6285
6286 dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
6287
6288 cp = strchr(tmpname, '/');
6289 if (cp == NULL) {
6290 (void) strlcpy(dsname, tmpname,
6291 MAXPATHLEN);
6292 } else {
6293 (void) snprintf(dsname, MAXPATHLEN,
6294 "%s/%s", poolname, ++cp);
6295 }
6296 VERIFY(nvlist_add_string(config,
6297 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
6298 kmem_free(dsname, MAXPATHLEN);
6299 }
6300 kmem_free(tmpname, MAXPATHLEN);
6301 }
6302
6303 /*
6304 * Add the list of hot spares and level 2 cache devices.
6305 */
6306 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6307 spa_add_spares(spa, config);
6308 spa_add_l2cache(spa, config);
6309 spa_config_exit(spa, SCL_CONFIG, FTAG);
6310 }
6311
6312 spa_unload(spa);
6313 spa_deactivate(spa);
6314 spa_remove(spa);
6315 mutex_exit(&spa_namespace_lock);
6316
6317 return (config);
6318 }
6319
6320 /*
6321 * Pool export/destroy
6322 *
6323 * The act of destroying or exporting a pool is very simple. We make sure there
6324 * is no more pending I/O and any references to the pool are gone. Then, we
6325 * update the pool state and sync all the labels to disk, removing the
6326 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
6327 * we don't sync the labels or remove the configuration cache.
6328 */
6329 static int
6330 spa_export_common(const char *pool, int new_state, nvlist_t **oldconfig,
6331 boolean_t force, boolean_t hardforce)
6332 {
6333 int error;
6334 spa_t *spa;
6335
6336 if (oldconfig)
6337 *oldconfig = NULL;
6338
6339 if (!(spa_mode_global & SPA_MODE_WRITE))
6340 return (SET_ERROR(EROFS));
6341
6342 mutex_enter(&spa_namespace_lock);
6343 if ((spa = spa_lookup(pool)) == NULL) {
6344 mutex_exit(&spa_namespace_lock);
6345 return (SET_ERROR(ENOENT));
6346 }
6347
6348 if (spa->spa_is_exporting) {
6349 /* the pool is being exported by another thread */
6350 mutex_exit(&spa_namespace_lock);
6351 return (SET_ERROR(ZFS_ERR_EXPORT_IN_PROGRESS));
6352 }
6353 spa->spa_is_exporting = B_TRUE;
6354
6355 /*
6356 * Put a hold on the pool, drop the namespace lock, stop async tasks,
6357 * reacquire the namespace lock, and see if we can export.
6358 */
6359 spa_open_ref(spa, FTAG);
6360 mutex_exit(&spa_namespace_lock);
6361 spa_async_suspend(spa);
6362 if (spa->spa_zvol_taskq) {
6363 zvol_remove_minors(spa, spa_name(spa), B_TRUE);
6364 taskq_wait(spa->spa_zvol_taskq);
6365 }
6366 mutex_enter(&spa_namespace_lock);
6367 spa_close(spa, FTAG);
6368
6369 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
6370 goto export_spa;
6371 /*
6372 * The pool will be in core if it's openable, in which case we can
6373 * modify its state. Objsets may be open only because they're dirty,
6374 * so we have to force it to sync before checking spa_refcnt.
6375 */
6376 if (spa->spa_sync_on) {
6377 txg_wait_synced(spa->spa_dsl_pool, 0);
6378 spa_evicting_os_wait(spa);
6379 }
6380
6381 /*
6382 * A pool cannot be exported or destroyed if there are active
6383 * references. If we are resetting a pool, allow references by
6384 * fault injection handlers.
6385 */
6386 if (!spa_refcount_zero(spa) || (spa->spa_inject_ref != 0)) {
6387 error = SET_ERROR(EBUSY);
6388 goto fail;
6389 }
6390
6391 if (spa->spa_sync_on) {
6392 /*
6393 * A pool cannot be exported if it has an active shared spare.
6394 * This is to prevent other pools stealing the active spare
6395 * from an exported pool. At user's own will, such pool can
6396 * be forcedly exported.
6397 */
6398 if (!force && new_state == POOL_STATE_EXPORTED &&
6399 spa_has_active_shared_spare(spa)) {
6400 error = SET_ERROR(EXDEV);
6401 goto fail;
6402 }
6403
6404 /*
6405 * We're about to export or destroy this pool. Make sure
6406 * we stop all initialization and trim activity here before
6407 * we set the spa_final_txg. This will ensure that all
6408 * dirty data resulting from the initialization is
6409 * committed to disk before we unload the pool.
6410 */
6411 if (spa->spa_root_vdev != NULL) {
6412 vdev_t *rvd = spa->spa_root_vdev;
6413 vdev_initialize_stop_all(rvd, VDEV_INITIALIZE_ACTIVE);
6414 vdev_trim_stop_all(rvd, VDEV_TRIM_ACTIVE);
6415 vdev_autotrim_stop_all(spa);
6416 vdev_rebuild_stop_all(spa);
6417 }
6418
6419 /*
6420 * We want this to be reflected on every label,
6421 * so mark them all dirty. spa_unload() will do the
6422 * final sync that pushes these changes out.
6423 */
6424 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
6425 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6426 spa->spa_state = new_state;
6427 vdev_config_dirty(spa->spa_root_vdev);
6428 spa_config_exit(spa, SCL_ALL, FTAG);
6429 }
6430
6431 /*
6432 * If the log space map feature is enabled and the pool is
6433 * getting exported (but not destroyed), we want to spend some
6434 * time flushing as many metaslabs as we can in an attempt to
6435 * destroy log space maps and save import time. This has to be
6436 * done before we set the spa_final_txg, otherwise
6437 * spa_sync() -> spa_flush_metaslabs() may dirty the final TXGs.
6438 * spa_should_flush_logs_on_unload() should be called after
6439 * spa_state has been set to the new_state.
6440 */
6441 if (spa_should_flush_logs_on_unload(spa))
6442 spa_unload_log_sm_flush_all(spa);
6443
6444 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
6445 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6446 spa->spa_final_txg = spa_last_synced_txg(spa) +
6447 TXG_DEFER_SIZE + 1;
6448 spa_config_exit(spa, SCL_ALL, FTAG);
6449 }
6450 }
6451
6452 export_spa:
6453 if (new_state == POOL_STATE_DESTROYED)
6454 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
6455 else if (new_state == POOL_STATE_EXPORTED)
6456 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_EXPORT);
6457
6458 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
6459 spa_unload(spa);
6460 spa_deactivate(spa);
6461 }
6462
6463 if (oldconfig && spa->spa_config)
6464 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
6465
6466 if (new_state != POOL_STATE_UNINITIALIZED) {
6467 if (!hardforce)
6468 spa_write_cachefile(spa, B_TRUE, B_TRUE);
6469 spa_remove(spa);
6470 } else {
6471 /*
6472 * If spa_remove() is not called for this spa_t and
6473 * there is any possibility that it can be reused,
6474 * we make sure to reset the exporting flag.
6475 */
6476 spa->spa_is_exporting = B_FALSE;
6477 }
6478
6479 mutex_exit(&spa_namespace_lock);
6480 return (0);
6481
6482 fail:
6483 spa->spa_is_exporting = B_FALSE;
6484 spa_async_resume(spa);
6485 mutex_exit(&spa_namespace_lock);
6486 return (error);
6487 }
6488
6489 /*
6490 * Destroy a storage pool.
6491 */
6492 int
6493 spa_destroy(const char *pool)
6494 {
6495 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
6496 B_FALSE, B_FALSE));
6497 }
6498
6499 /*
6500 * Export a storage pool.
6501 */
6502 int
6503 spa_export(const char *pool, nvlist_t **oldconfig, boolean_t force,
6504 boolean_t hardforce)
6505 {
6506 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
6507 force, hardforce));
6508 }
6509
6510 /*
6511 * Similar to spa_export(), this unloads the spa_t without actually removing it
6512 * from the namespace in any way.
6513 */
6514 int
6515 spa_reset(const char *pool)
6516 {
6517 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
6518 B_FALSE, B_FALSE));
6519 }
6520
6521 /*
6522 * ==========================================================================
6523 * Device manipulation
6524 * ==========================================================================
6525 */
6526
6527 /*
6528 * This is called as a synctask to increment the draid feature flag
6529 */
6530 static void
6531 spa_draid_feature_incr(void *arg, dmu_tx_t *tx)
6532 {
6533 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
6534 int draid = (int)(uintptr_t)arg;
6535
6536 for (int c = 0; c < draid; c++)
6537 spa_feature_incr(spa, SPA_FEATURE_DRAID, tx);
6538 }
6539
6540 /*
6541 * Add a device to a storage pool.
6542 */
6543 int
6544 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
6545 {
6546 uint64_t txg, ndraid = 0;
6547 int error;
6548 vdev_t *rvd = spa->spa_root_vdev;
6549 vdev_t *vd, *tvd;
6550 nvlist_t **spares, **l2cache;
6551 uint_t nspares, nl2cache;
6552
6553 ASSERT(spa_writeable(spa));
6554
6555 txg = spa_vdev_enter(spa);
6556
6557 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
6558 VDEV_ALLOC_ADD)) != 0)
6559 return (spa_vdev_exit(spa, NULL, txg, error));
6560
6561 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
6562
6563 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
6564 &nspares) != 0)
6565 nspares = 0;
6566
6567 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
6568 &nl2cache) != 0)
6569 nl2cache = 0;
6570
6571 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
6572 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6573
6574 if (vd->vdev_children != 0 &&
6575 (error = vdev_create(vd, txg, B_FALSE)) != 0) {
6576 return (spa_vdev_exit(spa, vd, txg, error));
6577 }
6578
6579 /*
6580 * The virtual dRAID spares must be added after vdev tree is created
6581 * and the vdev guids are generated. The guid of their associated
6582 * dRAID is stored in the config and used when opening the spare.
6583 */
6584 if ((error = vdev_draid_spare_create(nvroot, vd, &ndraid,
6585 rvd->vdev_children)) == 0) {
6586 if (ndraid > 0 && nvlist_lookup_nvlist_array(nvroot,
6587 ZPOOL_CONFIG_SPARES, &spares, &nspares) != 0)
6588 nspares = 0;
6589 } else {
6590 return (spa_vdev_exit(spa, vd, txg, error));
6591 }
6592
6593 /*
6594 * We must validate the spares and l2cache devices after checking the
6595 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
6596 */
6597 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
6598 return (spa_vdev_exit(spa, vd, txg, error));
6599
6600 /*
6601 * If we are in the middle of a device removal, we can only add
6602 * devices which match the existing devices in the pool.
6603 * If we are in the middle of a removal, or have some indirect
6604 * vdevs, we can not add raidz or dRAID top levels.
6605 */
6606 if (spa->spa_vdev_removal != NULL ||
6607 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
6608 for (int c = 0; c < vd->vdev_children; c++) {
6609 tvd = vd->vdev_child[c];
6610 if (spa->spa_vdev_removal != NULL &&
6611 tvd->vdev_ashift != spa->spa_max_ashift) {
6612 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6613 }
6614 /* Fail if top level vdev is raidz or a dRAID */
6615 if (vdev_get_nparity(tvd) != 0)
6616 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6617
6618 /*
6619 * Need the top level mirror to be
6620 * a mirror of leaf vdevs only
6621 */
6622 if (tvd->vdev_ops == &vdev_mirror_ops) {
6623 for (uint64_t cid = 0;
6624 cid < tvd->vdev_children; cid++) {
6625 vdev_t *cvd = tvd->vdev_child[cid];
6626 if (!cvd->vdev_ops->vdev_op_leaf) {
6627 return (spa_vdev_exit(spa, vd,
6628 txg, EINVAL));
6629 }
6630 }
6631 }
6632 }
6633 }
6634
6635 for (int c = 0; c < vd->vdev_children; c++) {
6636 tvd = vd->vdev_child[c];
6637 vdev_remove_child(vd, tvd);
6638 tvd->vdev_id = rvd->vdev_children;
6639 vdev_add_child(rvd, tvd);
6640 vdev_config_dirty(tvd);
6641 }
6642
6643 if (nspares != 0) {
6644 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
6645 ZPOOL_CONFIG_SPARES);
6646 spa_load_spares(spa);
6647 spa->spa_spares.sav_sync = B_TRUE;
6648 }
6649
6650 if (nl2cache != 0) {
6651 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
6652 ZPOOL_CONFIG_L2CACHE);
6653 spa_load_l2cache(spa);
6654 spa->spa_l2cache.sav_sync = B_TRUE;
6655 }
6656
6657 /*
6658 * We can't increment a feature while holding spa_vdev so we
6659 * have to do it in a synctask.
6660 */
6661 if (ndraid != 0) {
6662 dmu_tx_t *tx;
6663
6664 tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
6665 dsl_sync_task_nowait(spa->spa_dsl_pool, spa_draid_feature_incr,
6666 (void *)(uintptr_t)ndraid, tx);
6667 dmu_tx_commit(tx);
6668 }
6669
6670 /*
6671 * We have to be careful when adding new vdevs to an existing pool.
6672 * If other threads start allocating from these vdevs before we
6673 * sync the config cache, and we lose power, then upon reboot we may
6674 * fail to open the pool because there are DVAs that the config cache
6675 * can't translate. Therefore, we first add the vdevs without
6676 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
6677 * and then let spa_config_update() initialize the new metaslabs.
6678 *
6679 * spa_load() checks for added-but-not-initialized vdevs, so that
6680 * if we lose power at any point in this sequence, the remaining
6681 * steps will be completed the next time we load the pool.
6682 */
6683 (void) spa_vdev_exit(spa, vd, txg, 0);
6684
6685 mutex_enter(&spa_namespace_lock);
6686 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
6687 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
6688 mutex_exit(&spa_namespace_lock);
6689
6690 return (0);
6691 }
6692
6693 /*
6694 * Attach a device to a mirror. The arguments are the path to any device
6695 * in the mirror, and the nvroot for the new device. If the path specifies
6696 * a device that is not mirrored, we automatically insert the mirror vdev.
6697 *
6698 * If 'replacing' is specified, the new device is intended to replace the
6699 * existing device; in this case the two devices are made into their own
6700 * mirror using the 'replacing' vdev, which is functionally identical to
6701 * the mirror vdev (it actually reuses all the same ops) but has a few
6702 * extra rules: you can't attach to it after it's been created, and upon
6703 * completion of resilvering, the first disk (the one being replaced)
6704 * is automatically detached.
6705 *
6706 * If 'rebuild' is specified, then sequential reconstruction (a.ka. rebuild)
6707 * should be performed instead of traditional healing reconstruction. From
6708 * an administrators perspective these are both resilver operations.
6709 */
6710 int
6711 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing,
6712 int rebuild)
6713 {
6714 uint64_t txg, dtl_max_txg;
6715 vdev_t *rvd = spa->spa_root_vdev;
6716 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
6717 vdev_ops_t *pvops;
6718 char *oldvdpath, *newvdpath;
6719 int newvd_isspare;
6720 int error;
6721
6722 ASSERT(spa_writeable(spa));
6723
6724 txg = spa_vdev_enter(spa);
6725
6726 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
6727
6728 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6729 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6730 error = (spa_has_checkpoint(spa)) ?
6731 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6732 return (spa_vdev_exit(spa, NULL, txg, error));
6733 }
6734
6735 if (rebuild) {
6736 if (!spa_feature_is_enabled(spa, SPA_FEATURE_DEVICE_REBUILD))
6737 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6738
6739 if (dsl_scan_resilvering(spa_get_dsl(spa)))
6740 return (spa_vdev_exit(spa, NULL, txg,
6741 ZFS_ERR_RESILVER_IN_PROGRESS));
6742 } else {
6743 if (vdev_rebuild_active(rvd))
6744 return (spa_vdev_exit(spa, NULL, txg,
6745 ZFS_ERR_REBUILD_IN_PROGRESS));
6746 }
6747
6748 if (spa->spa_vdev_removal != NULL)
6749 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6750
6751 if (oldvd == NULL)
6752 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6753
6754 if (!oldvd->vdev_ops->vdev_op_leaf)
6755 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6756
6757 pvd = oldvd->vdev_parent;
6758
6759 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
6760 VDEV_ALLOC_ATTACH)) != 0)
6761 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6762
6763 if (newrootvd->vdev_children != 1)
6764 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6765
6766 newvd = newrootvd->vdev_child[0];
6767
6768 if (!newvd->vdev_ops->vdev_op_leaf)
6769 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6770
6771 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
6772 return (spa_vdev_exit(spa, newrootvd, txg, error));
6773
6774 /*
6775 * Spares can't replace logs
6776 */
6777 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
6778 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6779
6780 /*
6781 * A dRAID spare can only replace a child of its parent dRAID vdev.
6782 */
6783 if (newvd->vdev_ops == &vdev_draid_spare_ops &&
6784 oldvd->vdev_top != vdev_draid_spare_get_parent(newvd)) {
6785 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6786 }
6787
6788 if (rebuild) {
6789 /*
6790 * For rebuilds, the top vdev must support reconstruction
6791 * using only space maps. This means the only allowable
6792 * vdevs types are the root vdev, a mirror, or dRAID.
6793 */
6794 tvd = pvd;
6795 if (pvd->vdev_top != NULL)
6796 tvd = pvd->vdev_top;
6797
6798 if (tvd->vdev_ops != &vdev_mirror_ops &&
6799 tvd->vdev_ops != &vdev_root_ops &&
6800 tvd->vdev_ops != &vdev_draid_ops) {
6801 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6802 }
6803 }
6804
6805 if (!replacing) {
6806 /*
6807 * For attach, the only allowable parent is a mirror or the root
6808 * vdev.
6809 */
6810 if (pvd->vdev_ops != &vdev_mirror_ops &&
6811 pvd->vdev_ops != &vdev_root_ops)
6812 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6813
6814 pvops = &vdev_mirror_ops;
6815 } else {
6816 /*
6817 * Active hot spares can only be replaced by inactive hot
6818 * spares.
6819 */
6820 if (pvd->vdev_ops == &vdev_spare_ops &&
6821 oldvd->vdev_isspare &&
6822 !spa_has_spare(spa, newvd->vdev_guid))
6823 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6824
6825 /*
6826 * If the source is a hot spare, and the parent isn't already a
6827 * spare, then we want to create a new hot spare. Otherwise, we
6828 * want to create a replacing vdev. The user is not allowed to
6829 * attach to a spared vdev child unless the 'isspare' state is
6830 * the same (spare replaces spare, non-spare replaces
6831 * non-spare).
6832 */
6833 if (pvd->vdev_ops == &vdev_replacing_ops &&
6834 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
6835 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6836 } else if (pvd->vdev_ops == &vdev_spare_ops &&
6837 newvd->vdev_isspare != oldvd->vdev_isspare) {
6838 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6839 }
6840
6841 if (newvd->vdev_isspare)
6842 pvops = &vdev_spare_ops;
6843 else
6844 pvops = &vdev_replacing_ops;
6845 }
6846
6847 /*
6848 * Make sure the new device is big enough.
6849 */
6850 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
6851 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6852
6853 /*
6854 * The new device cannot have a higher alignment requirement
6855 * than the top-level vdev.
6856 */
6857 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6858 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6859
6860 /*
6861 * If this is an in-place replacement, update oldvd's path and devid
6862 * to make it distinguishable from newvd, and unopenable from now on.
6863 */
6864 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6865 spa_strfree(oldvd->vdev_path);
6866 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6867 KM_SLEEP);
6868 (void) snprintf(oldvd->vdev_path, strlen(newvd->vdev_path) + 5,
6869 "%s/%s", newvd->vdev_path, "old");
6870 if (oldvd->vdev_devid != NULL) {
6871 spa_strfree(oldvd->vdev_devid);
6872 oldvd->vdev_devid = NULL;
6873 }
6874 }
6875
6876 /*
6877 * If the parent is not a mirror, or if we're replacing, insert the new
6878 * mirror/replacing/spare vdev above oldvd.
6879 */
6880 if (pvd->vdev_ops != pvops)
6881 pvd = vdev_add_parent(oldvd, pvops);
6882
6883 ASSERT(pvd->vdev_top->vdev_parent == rvd);
6884 ASSERT(pvd->vdev_ops == pvops);
6885 ASSERT(oldvd->vdev_parent == pvd);
6886
6887 /*
6888 * Extract the new device from its root and add it to pvd.
6889 */
6890 vdev_remove_child(newrootvd, newvd);
6891 newvd->vdev_id = pvd->vdev_children;
6892 newvd->vdev_crtxg = oldvd->vdev_crtxg;
6893 vdev_add_child(pvd, newvd);
6894
6895 /*
6896 * Reevaluate the parent vdev state.
6897 */
6898 vdev_propagate_state(pvd);
6899
6900 tvd = newvd->vdev_top;
6901 ASSERT(pvd->vdev_top == tvd);
6902 ASSERT(tvd->vdev_parent == rvd);
6903
6904 vdev_config_dirty(tvd);
6905
6906 /*
6907 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6908 * for any dmu_sync-ed blocks. It will propagate upward when
6909 * spa_vdev_exit() calls vdev_dtl_reassess().
6910 */
6911 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6912
6913 vdev_dtl_dirty(newvd, DTL_MISSING,
6914 TXG_INITIAL, dtl_max_txg - TXG_INITIAL);
6915
6916 if (newvd->vdev_isspare) {
6917 spa_spare_activate(newvd);
6918 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6919 }
6920
6921 oldvdpath = spa_strdup(oldvd->vdev_path);
6922 newvdpath = spa_strdup(newvd->vdev_path);
6923 newvd_isspare = newvd->vdev_isspare;
6924
6925 /*
6926 * Mark newvd's DTL dirty in this txg.
6927 */
6928 vdev_dirty(tvd, VDD_DTL, newvd, txg);
6929
6930 /*
6931 * Schedule the resilver or rebuild to restart in the future. We do
6932 * this to ensure that dmu_sync-ed blocks have been stitched into the
6933 * respective datasets.
6934 */
6935 if (rebuild) {
6936 newvd->vdev_rebuild_txg = txg;
6937
6938 vdev_rebuild(tvd);
6939 } else {
6940 newvd->vdev_resilver_txg = txg;
6941
6942 if (dsl_scan_resilvering(spa_get_dsl(spa)) &&
6943 spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER)) {
6944 vdev_defer_resilver(newvd);
6945 } else {
6946 dsl_scan_restart_resilver(spa->spa_dsl_pool,
6947 dtl_max_txg);
6948 }
6949 }
6950
6951 if (spa->spa_bootfs)
6952 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6953
6954 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6955
6956 /*
6957 * Commit the config
6958 */
6959 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6960
6961 spa_history_log_internal(spa, "vdev attach", NULL,
6962 "%s vdev=%s %s vdev=%s",
6963 replacing && newvd_isspare ? "spare in" :
6964 replacing ? "replace" : "attach", newvdpath,
6965 replacing ? "for" : "to", oldvdpath);
6966
6967 spa_strfree(oldvdpath);
6968 spa_strfree(newvdpath);
6969
6970 return (0);
6971 }
6972
6973 /*
6974 * Detach a device from a mirror or replacing vdev.
6975 *
6976 * If 'replace_done' is specified, only detach if the parent
6977 * is a replacing vdev.
6978 */
6979 int
6980 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6981 {
6982 uint64_t txg;
6983 int error;
6984 vdev_t *rvd __maybe_unused = spa->spa_root_vdev;
6985 vdev_t *vd, *pvd, *cvd, *tvd;
6986 boolean_t unspare = B_FALSE;
6987 uint64_t unspare_guid = 0;
6988 char *vdpath;
6989
6990 ASSERT(spa_writeable(spa));
6991
6992 txg = spa_vdev_detach_enter(spa, guid);
6993
6994 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6995
6996 /*
6997 * Besides being called directly from the userland through the
6998 * ioctl interface, spa_vdev_detach() can be potentially called
6999 * at the end of spa_vdev_resilver_done().
7000 *
7001 * In the regular case, when we have a checkpoint this shouldn't
7002 * happen as we never empty the DTLs of a vdev during the scrub
7003 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
7004 * should never get here when we have a checkpoint.
7005 *
7006 * That said, even in a case when we checkpoint the pool exactly
7007 * as spa_vdev_resilver_done() calls this function everything
7008 * should be fine as the resilver will return right away.
7009 */
7010 ASSERT(MUTEX_HELD(&spa_namespace_lock));
7011 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
7012 error = (spa_has_checkpoint(spa)) ?
7013 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
7014 return (spa_vdev_exit(spa, NULL, txg, error));
7015 }
7016
7017 if (vd == NULL)
7018 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
7019
7020 if (!vd->vdev_ops->vdev_op_leaf)
7021 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
7022
7023 pvd = vd->vdev_parent;
7024
7025 /*
7026 * If the parent/child relationship is not as expected, don't do it.
7027 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
7028 * vdev that's replacing B with C. The user's intent in replacing
7029 * is to go from M(A,B) to M(A,C). If the user decides to cancel
7030 * the replace by detaching C, the expected behavior is to end up
7031 * M(A,B). But suppose that right after deciding to detach C,
7032 * the replacement of B completes. We would have M(A,C), and then
7033 * ask to detach C, which would leave us with just A -- not what
7034 * the user wanted. To prevent this, we make sure that the
7035 * parent/child relationship hasn't changed -- in this example,
7036 * that C's parent is still the replacing vdev R.
7037 */
7038 if (pvd->vdev_guid != pguid && pguid != 0)
7039 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
7040
7041 /*
7042 * Only 'replacing' or 'spare' vdevs can be replaced.
7043 */
7044 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
7045 pvd->vdev_ops != &vdev_spare_ops)
7046 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
7047
7048 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
7049 spa_version(spa) >= SPA_VERSION_SPARES);
7050
7051 /*
7052 * Only mirror, replacing, and spare vdevs support detach.
7053 */
7054 if (pvd->vdev_ops != &vdev_replacing_ops &&
7055 pvd->vdev_ops != &vdev_mirror_ops &&
7056 pvd->vdev_ops != &vdev_spare_ops)
7057 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
7058
7059 /*
7060 * If this device has the only valid copy of some data,
7061 * we cannot safely detach it.
7062 */
7063 if (vdev_dtl_required(vd))
7064 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
7065
7066 ASSERT(pvd->vdev_children >= 2);
7067
7068 /*
7069 * If we are detaching the second disk from a replacing vdev, then
7070 * check to see if we changed the original vdev's path to have "/old"
7071 * at the end in spa_vdev_attach(). If so, undo that change now.
7072 */
7073 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
7074 vd->vdev_path != NULL) {
7075 size_t len = strlen(vd->vdev_path);
7076
7077 for (int c = 0; c < pvd->vdev_children; c++) {
7078 cvd = pvd->vdev_child[c];
7079
7080 if (cvd == vd || cvd->vdev_path == NULL)
7081 continue;
7082
7083 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
7084 strcmp(cvd->vdev_path + len, "/old") == 0) {
7085 spa_strfree(cvd->vdev_path);
7086 cvd->vdev_path = spa_strdup(vd->vdev_path);
7087 break;
7088 }
7089 }
7090 }
7091
7092 /*
7093 * If we are detaching the original disk from a normal spare, then it
7094 * implies that the spare should become a real disk, and be removed
7095 * from the active spare list for the pool. dRAID spares on the
7096 * other hand are coupled to the pool and thus should never be removed
7097 * from the spares list.
7098 */
7099 if (pvd->vdev_ops == &vdev_spare_ops && vd->vdev_id == 0) {
7100 vdev_t *last_cvd = pvd->vdev_child[pvd->vdev_children - 1];
7101
7102 if (last_cvd->vdev_isspare &&
7103 last_cvd->vdev_ops != &vdev_draid_spare_ops) {
7104 unspare = B_TRUE;
7105 }
7106 }
7107
7108 /*
7109 * Erase the disk labels so the disk can be used for other things.
7110 * This must be done after all other error cases are handled,
7111 * but before we disembowel vd (so we can still do I/O to it).
7112 * But if we can't do it, don't treat the error as fatal --
7113 * it may be that the unwritability of the disk is the reason
7114 * it's being detached!
7115 */
7116 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
7117
7118 /*
7119 * Remove vd from its parent and compact the parent's children.
7120 */
7121 vdev_remove_child(pvd, vd);
7122 vdev_compact_children(pvd);
7123
7124 /*
7125 * Remember one of the remaining children so we can get tvd below.
7126 */
7127 cvd = pvd->vdev_child[pvd->vdev_children - 1];
7128
7129 /*
7130 * If we need to remove the remaining child from the list of hot spares,
7131 * do it now, marking the vdev as no longer a spare in the process.
7132 * We must do this before vdev_remove_parent(), because that can
7133 * change the GUID if it creates a new toplevel GUID. For a similar
7134 * reason, we must remove the spare now, in the same txg as the detach;
7135 * otherwise someone could attach a new sibling, change the GUID, and
7136 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
7137 */
7138 if (unspare) {
7139 ASSERT(cvd->vdev_isspare);
7140 spa_spare_remove(cvd);
7141 unspare_guid = cvd->vdev_guid;
7142 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
7143 cvd->vdev_unspare = B_TRUE;
7144 }
7145
7146 /*
7147 * If the parent mirror/replacing vdev only has one child,
7148 * the parent is no longer needed. Remove it from the tree.
7149 */
7150 if (pvd->vdev_children == 1) {
7151 if (pvd->vdev_ops == &vdev_spare_ops)
7152 cvd->vdev_unspare = B_FALSE;
7153 vdev_remove_parent(cvd);
7154 }
7155
7156 /*
7157 * We don't set tvd until now because the parent we just removed
7158 * may have been the previous top-level vdev.
7159 */
7160 tvd = cvd->vdev_top;
7161 ASSERT(tvd->vdev_parent == rvd);
7162
7163 /*
7164 * Reevaluate the parent vdev state.
7165 */
7166 vdev_propagate_state(cvd);
7167
7168 /*
7169 * If the 'autoexpand' property is set on the pool then automatically
7170 * try to expand the size of the pool. For example if the device we
7171 * just detached was smaller than the others, it may be possible to
7172 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
7173 * first so that we can obtain the updated sizes of the leaf vdevs.
7174 */
7175 if (spa->spa_autoexpand) {
7176 vdev_reopen(tvd);
7177 vdev_expand(tvd, txg);
7178 }
7179
7180 vdev_config_dirty(tvd);
7181
7182 /*
7183 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
7184 * vd->vdev_detached is set and free vd's DTL object in syncing context.
7185 * But first make sure we're not on any *other* txg's DTL list, to
7186 * prevent vd from being accessed after it's freed.
7187 */
7188 vdpath = spa_strdup(vd->vdev_path ? vd->vdev_path : "none");
7189 for (int t = 0; t < TXG_SIZE; t++)
7190 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
7191 vd->vdev_detached = B_TRUE;
7192 vdev_dirty(tvd, VDD_DTL, vd, txg);
7193
7194 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
7195 spa_notify_waiters(spa);
7196
7197 /* hang on to the spa before we release the lock */
7198 spa_open_ref(spa, FTAG);
7199
7200 error = spa_vdev_exit(spa, vd, txg, 0);
7201
7202 spa_history_log_internal(spa, "detach", NULL,
7203 "vdev=%s", vdpath);
7204 spa_strfree(vdpath);
7205
7206 /*
7207 * If this was the removal of the original device in a hot spare vdev,
7208 * then we want to go through and remove the device from the hot spare
7209 * list of every other pool.
7210 */
7211 if (unspare) {
7212 spa_t *altspa = NULL;
7213
7214 mutex_enter(&spa_namespace_lock);
7215 while ((altspa = spa_next(altspa)) != NULL) {
7216 if (altspa->spa_state != POOL_STATE_ACTIVE ||
7217 altspa == spa)
7218 continue;
7219
7220 spa_open_ref(altspa, FTAG);
7221 mutex_exit(&spa_namespace_lock);
7222 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
7223 mutex_enter(&spa_namespace_lock);
7224 spa_close(altspa, FTAG);
7225 }
7226 mutex_exit(&spa_namespace_lock);
7227
7228 /* search the rest of the vdevs for spares to remove */
7229 spa_vdev_resilver_done(spa);
7230 }
7231
7232 /* all done with the spa; OK to release */
7233 mutex_enter(&spa_namespace_lock);
7234 spa_close(spa, FTAG);
7235 mutex_exit(&spa_namespace_lock);
7236
7237 return (error);
7238 }
7239
7240 static int
7241 spa_vdev_initialize_impl(spa_t *spa, uint64_t guid, uint64_t cmd_type,
7242 list_t *vd_list)
7243 {
7244 ASSERT(MUTEX_HELD(&spa_namespace_lock));
7245
7246 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
7247
7248 /* Look up vdev and ensure it's a leaf. */
7249 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
7250 if (vd == NULL || vd->vdev_detached) {
7251 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7252 return (SET_ERROR(ENODEV));
7253 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
7254 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7255 return (SET_ERROR(EINVAL));
7256 } else if (!vdev_writeable(vd)) {
7257 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7258 return (SET_ERROR(EROFS));
7259 }
7260 mutex_enter(&vd->vdev_initialize_lock);
7261 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7262
7263 /*
7264 * When we activate an initialize action we check to see
7265 * if the vdev_initialize_thread is NULL. We do this instead
7266 * of using the vdev_initialize_state since there might be
7267 * a previous initialization process which has completed but
7268 * the thread is not exited.
7269 */
7270 if (cmd_type == POOL_INITIALIZE_START &&
7271 (vd->vdev_initialize_thread != NULL ||
7272 vd->vdev_top->vdev_removing)) {
7273 mutex_exit(&vd->vdev_initialize_lock);
7274 return (SET_ERROR(EBUSY));
7275 } else if (cmd_type == POOL_INITIALIZE_CANCEL &&
7276 (vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE &&
7277 vd->vdev_initialize_state != VDEV_INITIALIZE_SUSPENDED)) {
7278 mutex_exit(&vd->vdev_initialize_lock);
7279 return (SET_ERROR(ESRCH));
7280 } else if (cmd_type == POOL_INITIALIZE_SUSPEND &&
7281 vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE) {
7282 mutex_exit(&vd->vdev_initialize_lock);
7283 return (SET_ERROR(ESRCH));
7284 }
7285
7286 switch (cmd_type) {
7287 case POOL_INITIALIZE_START:
7288 vdev_initialize(vd);
7289 break;
7290 case POOL_INITIALIZE_CANCEL:
7291 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED, vd_list);
7292 break;
7293 case POOL_INITIALIZE_SUSPEND:
7294 vdev_initialize_stop(vd, VDEV_INITIALIZE_SUSPENDED, vd_list);
7295 break;
7296 default:
7297 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
7298 }
7299 mutex_exit(&vd->vdev_initialize_lock);
7300
7301 return (0);
7302 }
7303
7304 int
7305 spa_vdev_initialize(spa_t *spa, nvlist_t *nv, uint64_t cmd_type,
7306 nvlist_t *vdev_errlist)
7307 {
7308 int total_errors = 0;
7309 list_t vd_list;
7310
7311 list_create(&vd_list, sizeof (vdev_t),
7312 offsetof(vdev_t, vdev_initialize_node));
7313
7314 /*
7315 * We hold the namespace lock through the whole function
7316 * to prevent any changes to the pool while we're starting or
7317 * stopping initialization. The config and state locks are held so that
7318 * we can properly assess the vdev state before we commit to
7319 * the initializing operation.
7320 */
7321 mutex_enter(&spa_namespace_lock);
7322
7323 for (nvpair_t *pair = nvlist_next_nvpair(nv, NULL);
7324 pair != NULL; pair = nvlist_next_nvpair(nv, pair)) {
7325 uint64_t vdev_guid = fnvpair_value_uint64(pair);
7326
7327 int error = spa_vdev_initialize_impl(spa, vdev_guid, cmd_type,
7328 &vd_list);
7329 if (error != 0) {
7330 char guid_as_str[MAXNAMELEN];
7331
7332 (void) snprintf(guid_as_str, sizeof (guid_as_str),
7333 "%llu", (unsigned long long)vdev_guid);
7334 fnvlist_add_int64(vdev_errlist, guid_as_str, error);
7335 total_errors++;
7336 }
7337 }
7338
7339 /* Wait for all initialize threads to stop. */
7340 vdev_initialize_stop_wait(spa, &vd_list);
7341
7342 /* Sync out the initializing state */
7343 txg_wait_synced(spa->spa_dsl_pool, 0);
7344 mutex_exit(&spa_namespace_lock);
7345
7346 list_destroy(&vd_list);
7347
7348 return (total_errors);
7349 }
7350
7351 static int
7352 spa_vdev_trim_impl(spa_t *spa, uint64_t guid, uint64_t cmd_type,
7353 uint64_t rate, boolean_t partial, boolean_t secure, list_t *vd_list)
7354 {
7355 ASSERT(MUTEX_HELD(&spa_namespace_lock));
7356
7357 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
7358
7359 /* Look up vdev and ensure it's a leaf. */
7360 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
7361 if (vd == NULL || vd->vdev_detached) {
7362 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7363 return (SET_ERROR(ENODEV));
7364 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
7365 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7366 return (SET_ERROR(EINVAL));
7367 } else if (!vdev_writeable(vd)) {
7368 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7369 return (SET_ERROR(EROFS));
7370 } else if (!vd->vdev_has_trim) {
7371 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7372 return (SET_ERROR(EOPNOTSUPP));
7373 } else if (secure && !vd->vdev_has_securetrim) {
7374 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7375 return (SET_ERROR(EOPNOTSUPP));
7376 }
7377 mutex_enter(&vd->vdev_trim_lock);
7378 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7379
7380 /*
7381 * When we activate a TRIM action we check to see if the
7382 * vdev_trim_thread is NULL. We do this instead of using the
7383 * vdev_trim_state since there might be a previous TRIM process
7384 * which has completed but the thread is not exited.
7385 */
7386 if (cmd_type == POOL_TRIM_START &&
7387 (vd->vdev_trim_thread != NULL || vd->vdev_top->vdev_removing)) {
7388 mutex_exit(&vd->vdev_trim_lock);
7389 return (SET_ERROR(EBUSY));
7390 } else if (cmd_type == POOL_TRIM_CANCEL &&
7391 (vd->vdev_trim_state != VDEV_TRIM_ACTIVE &&
7392 vd->vdev_trim_state != VDEV_TRIM_SUSPENDED)) {
7393 mutex_exit(&vd->vdev_trim_lock);
7394 return (SET_ERROR(ESRCH));
7395 } else if (cmd_type == POOL_TRIM_SUSPEND &&
7396 vd->vdev_trim_state != VDEV_TRIM_ACTIVE) {
7397 mutex_exit(&vd->vdev_trim_lock);
7398 return (SET_ERROR(ESRCH));
7399 }
7400
7401 switch (cmd_type) {
7402 case POOL_TRIM_START:
7403 vdev_trim(vd, rate, partial, secure);
7404 break;
7405 case POOL_TRIM_CANCEL:
7406 vdev_trim_stop(vd, VDEV_TRIM_CANCELED, vd_list);
7407 break;
7408 case POOL_TRIM_SUSPEND:
7409 vdev_trim_stop(vd, VDEV_TRIM_SUSPENDED, vd_list);
7410 break;
7411 default:
7412 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
7413 }
7414 mutex_exit(&vd->vdev_trim_lock);
7415
7416 return (0);
7417 }
7418
7419 /*
7420 * Initiates a manual TRIM for the requested vdevs. This kicks off individual
7421 * TRIM threads for each child vdev. These threads pass over all of the free
7422 * space in the vdev's metaslabs and issues TRIM commands for that space.
7423 */
7424 int
7425 spa_vdev_trim(spa_t *spa, nvlist_t *nv, uint64_t cmd_type, uint64_t rate,
7426 boolean_t partial, boolean_t secure, nvlist_t *vdev_errlist)
7427 {
7428 int total_errors = 0;
7429 list_t vd_list;
7430
7431 list_create(&vd_list, sizeof (vdev_t),
7432 offsetof(vdev_t, vdev_trim_node));
7433
7434 /*
7435 * We hold the namespace lock through the whole function
7436 * to prevent any changes to the pool while we're starting or
7437 * stopping TRIM. The config and state locks are held so that
7438 * we can properly assess the vdev state before we commit to
7439 * the TRIM operation.
7440 */
7441 mutex_enter(&spa_namespace_lock);
7442
7443 for (nvpair_t *pair = nvlist_next_nvpair(nv, NULL);
7444 pair != NULL; pair = nvlist_next_nvpair(nv, pair)) {
7445 uint64_t vdev_guid = fnvpair_value_uint64(pair);
7446
7447 int error = spa_vdev_trim_impl(spa, vdev_guid, cmd_type,
7448 rate, partial, secure, &vd_list);
7449 if (error != 0) {
7450 char guid_as_str[MAXNAMELEN];
7451
7452 (void) snprintf(guid_as_str, sizeof (guid_as_str),
7453 "%llu", (unsigned long long)vdev_guid);
7454 fnvlist_add_int64(vdev_errlist, guid_as_str, error);
7455 total_errors++;
7456 }
7457 }
7458
7459 /* Wait for all TRIM threads to stop. */
7460 vdev_trim_stop_wait(spa, &vd_list);
7461
7462 /* Sync out the TRIM state */
7463 txg_wait_synced(spa->spa_dsl_pool, 0);
7464 mutex_exit(&spa_namespace_lock);
7465
7466 list_destroy(&vd_list);
7467
7468 return (total_errors);
7469 }
7470
7471 /*
7472 * Split a set of devices from their mirrors, and create a new pool from them.
7473 */
7474 int
7475 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
7476 nvlist_t *props, boolean_t exp)
7477 {
7478 int error = 0;
7479 uint64_t txg, *glist;
7480 spa_t *newspa;
7481 uint_t c, children, lastlog;
7482 nvlist_t **child, *nvl, *tmp;
7483 dmu_tx_t *tx;
7484 char *altroot = NULL;
7485 vdev_t *rvd, **vml = NULL; /* vdev modify list */
7486 boolean_t activate_slog;
7487
7488 ASSERT(spa_writeable(spa));
7489
7490 txg = spa_vdev_enter(spa);
7491
7492 ASSERT(MUTEX_HELD(&spa_namespace_lock));
7493 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
7494 error = (spa_has_checkpoint(spa)) ?
7495 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
7496 return (spa_vdev_exit(spa, NULL, txg, error));
7497 }
7498
7499 /* clear the log and flush everything up to now */
7500 activate_slog = spa_passivate_log(spa);
7501 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
7502 error = spa_reset_logs(spa);
7503 txg = spa_vdev_config_enter(spa);
7504
7505 if (activate_slog)
7506 spa_activate_log(spa);
7507
7508 if (error != 0)
7509 return (spa_vdev_exit(spa, NULL, txg, error));
7510
7511 /* check new spa name before going any further */
7512 if (spa_lookup(newname) != NULL)
7513 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
7514
7515 /*
7516 * scan through all the children to ensure they're all mirrors
7517 */
7518 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
7519 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
7520 &children) != 0)
7521 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
7522
7523 /* first, check to ensure we've got the right child count */
7524 rvd = spa->spa_root_vdev;
7525 lastlog = 0;
7526 for (c = 0; c < rvd->vdev_children; c++) {
7527 vdev_t *vd = rvd->vdev_child[c];
7528
7529 /* don't count the holes & logs as children */
7530 if (vd->vdev_islog || (vd->vdev_ops != &vdev_indirect_ops &&
7531 !vdev_is_concrete(vd))) {
7532 if (lastlog == 0)
7533 lastlog = c;
7534 continue;
7535 }
7536
7537 lastlog = 0;
7538 }
7539 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
7540 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
7541
7542 /* next, ensure no spare or cache devices are part of the split */
7543 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
7544 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
7545 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
7546
7547 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
7548 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
7549
7550 /* then, loop over each vdev and validate it */
7551 for (c = 0; c < children; c++) {
7552 uint64_t is_hole = 0;
7553
7554 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
7555 &is_hole);
7556
7557 if (is_hole != 0) {
7558 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
7559 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
7560 continue;
7561 } else {
7562 error = SET_ERROR(EINVAL);
7563 break;
7564 }
7565 }
7566
7567 /* deal with indirect vdevs */
7568 if (spa->spa_root_vdev->vdev_child[c]->vdev_ops ==
7569 &vdev_indirect_ops)
7570 continue;
7571
7572 /* which disk is going to be split? */
7573 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
7574 &glist[c]) != 0) {
7575 error = SET_ERROR(EINVAL);
7576 break;
7577 }
7578
7579 /* look it up in the spa */
7580 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
7581 if (vml[c] == NULL) {
7582 error = SET_ERROR(ENODEV);
7583 break;
7584 }
7585
7586 /* make sure there's nothing stopping the split */
7587 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
7588 vml[c]->vdev_islog ||
7589 !vdev_is_concrete(vml[c]) ||
7590 vml[c]->vdev_isspare ||
7591 vml[c]->vdev_isl2cache ||
7592 !vdev_writeable(vml[c]) ||
7593 vml[c]->vdev_children != 0 ||
7594 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
7595 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
7596 error = SET_ERROR(EINVAL);
7597 break;
7598 }
7599
7600 if (vdev_dtl_required(vml[c]) ||
7601 vdev_resilver_needed(vml[c], NULL, NULL)) {
7602 error = SET_ERROR(EBUSY);
7603 break;
7604 }
7605
7606 /* we need certain info from the top level */
7607 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
7608 vml[c]->vdev_top->vdev_ms_array) == 0);
7609 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
7610 vml[c]->vdev_top->vdev_ms_shift) == 0);
7611 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
7612 vml[c]->vdev_top->vdev_asize) == 0);
7613 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
7614 vml[c]->vdev_top->vdev_ashift) == 0);
7615
7616 /* transfer per-vdev ZAPs */
7617 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
7618 VERIFY0(nvlist_add_uint64(child[c],
7619 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
7620
7621 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
7622 VERIFY0(nvlist_add_uint64(child[c],
7623 ZPOOL_CONFIG_VDEV_TOP_ZAP,
7624 vml[c]->vdev_parent->vdev_top_zap));
7625 }
7626
7627 if (error != 0) {
7628 kmem_free(vml, children * sizeof (vdev_t *));
7629 kmem_free(glist, children * sizeof (uint64_t));
7630 return (spa_vdev_exit(spa, NULL, txg, error));
7631 }
7632
7633 /* stop writers from using the disks */
7634 for (c = 0; c < children; c++) {
7635 if (vml[c] != NULL)
7636 vml[c]->vdev_offline = B_TRUE;
7637 }
7638 vdev_reopen(spa->spa_root_vdev);
7639
7640 /*
7641 * Temporarily record the splitting vdevs in the spa config. This
7642 * will disappear once the config is regenerated.
7643 */
7644 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7645 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
7646 glist, children) == 0);
7647 kmem_free(glist, children * sizeof (uint64_t));
7648
7649 mutex_enter(&spa->spa_props_lock);
7650 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
7651 nvl) == 0);
7652 mutex_exit(&spa->spa_props_lock);
7653 spa->spa_config_splitting = nvl;
7654 vdev_config_dirty(spa->spa_root_vdev);
7655
7656 /* configure and create the new pool */
7657 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
7658 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
7659 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
7660 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7661 spa_version(spa)) == 0);
7662 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
7663 spa->spa_config_txg) == 0);
7664 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
7665 spa_generate_guid(NULL)) == 0);
7666 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
7667 (void) nvlist_lookup_string(props,
7668 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
7669
7670 /* add the new pool to the namespace */
7671 newspa = spa_add(newname, config, altroot);
7672 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
7673 newspa->spa_config_txg = spa->spa_config_txg;
7674 spa_set_log_state(newspa, SPA_LOG_CLEAR);
7675
7676 /* release the spa config lock, retaining the namespace lock */
7677 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
7678
7679 if (zio_injection_enabled)
7680 zio_handle_panic_injection(spa, FTAG, 1);
7681
7682 spa_activate(newspa, spa_mode_global);
7683 spa_async_suspend(newspa);
7684
7685 /*
7686 * Temporarily stop the initializing and TRIM activity. We set the
7687 * state to ACTIVE so that we know to resume initializing or TRIM
7688 * once the split has completed.
7689 */
7690 list_t vd_initialize_list;
7691 list_create(&vd_initialize_list, sizeof (vdev_t),
7692 offsetof(vdev_t, vdev_initialize_node));
7693
7694 list_t vd_trim_list;
7695 list_create(&vd_trim_list, sizeof (vdev_t),
7696 offsetof(vdev_t, vdev_trim_node));
7697
7698 for (c = 0; c < children; c++) {
7699 if (vml[c] != NULL && vml[c]->vdev_ops != &vdev_indirect_ops) {
7700 mutex_enter(&vml[c]->vdev_initialize_lock);
7701 vdev_initialize_stop(vml[c],
7702 VDEV_INITIALIZE_ACTIVE, &vd_initialize_list);
7703 mutex_exit(&vml[c]->vdev_initialize_lock);
7704
7705 mutex_enter(&vml[c]->vdev_trim_lock);
7706 vdev_trim_stop(vml[c], VDEV_TRIM_ACTIVE, &vd_trim_list);
7707 mutex_exit(&vml[c]->vdev_trim_lock);
7708 }
7709 }
7710
7711 vdev_initialize_stop_wait(spa, &vd_initialize_list);
7712 vdev_trim_stop_wait(spa, &vd_trim_list);
7713
7714 list_destroy(&vd_initialize_list);
7715 list_destroy(&vd_trim_list);
7716
7717 newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
7718 newspa->spa_is_splitting = B_TRUE;
7719
7720 /* create the new pool from the disks of the original pool */
7721 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
7722 if (error)
7723 goto out;
7724
7725 /* if that worked, generate a real config for the new pool */
7726 if (newspa->spa_root_vdev != NULL) {
7727 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
7728 NV_UNIQUE_NAME, KM_SLEEP) == 0);
7729 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
7730 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
7731 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
7732 B_TRUE));
7733 }
7734
7735 /* set the props */
7736 if (props != NULL) {
7737 spa_configfile_set(newspa, props, B_FALSE);
7738 error = spa_prop_set(newspa, props);
7739 if (error)
7740 goto out;
7741 }
7742
7743 /* flush everything */
7744 txg = spa_vdev_config_enter(newspa);
7745 vdev_config_dirty(newspa->spa_root_vdev);
7746 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
7747
7748 if (zio_injection_enabled)
7749 zio_handle_panic_injection(spa, FTAG, 2);
7750
7751 spa_async_resume(newspa);
7752
7753 /* finally, update the original pool's config */
7754 txg = spa_vdev_config_enter(spa);
7755 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
7756 error = dmu_tx_assign(tx, TXG_WAIT);
7757 if (error != 0)
7758 dmu_tx_abort(tx);
7759 for (c = 0; c < children; c++) {
7760 if (vml[c] != NULL && vml[c]->vdev_ops != &vdev_indirect_ops) {
7761 vdev_t *tvd = vml[c]->vdev_top;
7762
7763 /*
7764 * Need to be sure the detachable VDEV is not
7765 * on any *other* txg's DTL list to prevent it
7766 * from being accessed after it's freed.
7767 */
7768 for (int t = 0; t < TXG_SIZE; t++) {
7769 (void) txg_list_remove_this(
7770 &tvd->vdev_dtl_list, vml[c], t);
7771 }
7772
7773 vdev_split(vml[c]);
7774 if (error == 0)
7775 spa_history_log_internal(spa, "detach", tx,
7776 "vdev=%s", vml[c]->vdev_path);
7777
7778 vdev_free(vml[c]);
7779 }
7780 }
7781 spa->spa_avz_action = AVZ_ACTION_REBUILD;
7782 vdev_config_dirty(spa->spa_root_vdev);
7783 spa->spa_config_splitting = NULL;
7784 nvlist_free(nvl);
7785 if (error == 0)
7786 dmu_tx_commit(tx);
7787 (void) spa_vdev_exit(spa, NULL, txg, 0);
7788
7789 if (zio_injection_enabled)
7790 zio_handle_panic_injection(spa, FTAG, 3);
7791
7792 /* split is complete; log a history record */
7793 spa_history_log_internal(newspa, "split", NULL,
7794 "from pool %s", spa_name(spa));
7795
7796 newspa->spa_is_splitting = B_FALSE;
7797 kmem_free(vml, children * sizeof (vdev_t *));
7798
7799 /* if we're not going to mount the filesystems in userland, export */
7800 if (exp)
7801 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
7802 B_FALSE, B_FALSE);
7803
7804 return (error);
7805
7806 out:
7807 spa_unload(newspa);
7808 spa_deactivate(newspa);
7809 spa_remove(newspa);
7810
7811 txg = spa_vdev_config_enter(spa);
7812
7813 /* re-online all offlined disks */
7814 for (c = 0; c < children; c++) {
7815 if (vml[c] != NULL)
7816 vml[c]->vdev_offline = B_FALSE;
7817 }
7818
7819 /* restart initializing or trimming disks as necessary */
7820 spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
7821 spa_async_request(spa, SPA_ASYNC_TRIM_RESTART);
7822 spa_async_request(spa, SPA_ASYNC_AUTOTRIM_RESTART);
7823
7824 vdev_reopen(spa->spa_root_vdev);
7825
7826 nvlist_free(spa->spa_config_splitting);
7827 spa->spa_config_splitting = NULL;
7828 (void) spa_vdev_exit(spa, NULL, txg, error);
7829
7830 kmem_free(vml, children * sizeof (vdev_t *));
7831 return (error);
7832 }
7833
7834 /*
7835 * Find any device that's done replacing, or a vdev marked 'unspare' that's
7836 * currently spared, so we can detach it.
7837 */
7838 static vdev_t *
7839 spa_vdev_resilver_done_hunt(vdev_t *vd)
7840 {
7841 vdev_t *newvd, *oldvd;
7842
7843 for (int c = 0; c < vd->vdev_children; c++) {
7844 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
7845 if (oldvd != NULL)
7846 return (oldvd);
7847 }
7848
7849 /*
7850 * Check for a completed replacement. We always consider the first
7851 * vdev in the list to be the oldest vdev, and the last one to be
7852 * the newest (see spa_vdev_attach() for how that works). In
7853 * the case where the newest vdev is faulted, we will not automatically
7854 * remove it after a resilver completes. This is OK as it will require
7855 * user intervention to determine which disk the admin wishes to keep.
7856 */
7857 if (vd->vdev_ops == &vdev_replacing_ops) {
7858 ASSERT(vd->vdev_children > 1);
7859
7860 newvd = vd->vdev_child[vd->vdev_children - 1];
7861 oldvd = vd->vdev_child[0];
7862
7863 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
7864 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
7865 !vdev_dtl_required(oldvd))
7866 return (oldvd);
7867 }
7868
7869 /*
7870 * Check for a completed resilver with the 'unspare' flag set.
7871 * Also potentially update faulted state.
7872 */
7873 if (vd->vdev_ops == &vdev_spare_ops) {
7874 vdev_t *first = vd->vdev_child[0];
7875 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
7876
7877 if (last->vdev_unspare) {
7878 oldvd = first;
7879 newvd = last;
7880 } else if (first->vdev_unspare) {
7881 oldvd = last;
7882 newvd = first;
7883 } else {
7884 oldvd = NULL;
7885 }
7886
7887 if (oldvd != NULL &&
7888 vdev_dtl_empty(newvd, DTL_MISSING) &&
7889 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
7890 !vdev_dtl_required(oldvd))
7891 return (oldvd);
7892
7893 vdev_propagate_state(vd);
7894
7895 /*
7896 * If there are more than two spares attached to a disk,
7897 * and those spares are not required, then we want to
7898 * attempt to free them up now so that they can be used
7899 * by other pools. Once we're back down to a single
7900 * disk+spare, we stop removing them.
7901 */
7902 if (vd->vdev_children > 2) {
7903 newvd = vd->vdev_child[1];
7904
7905 if (newvd->vdev_isspare && last->vdev_isspare &&
7906 vdev_dtl_empty(last, DTL_MISSING) &&
7907 vdev_dtl_empty(last, DTL_OUTAGE) &&
7908 !vdev_dtl_required(newvd))
7909 return (newvd);
7910 }
7911 }
7912
7913 return (NULL);
7914 }
7915
7916 static void
7917 spa_vdev_resilver_done(spa_t *spa)
7918 {
7919 vdev_t *vd, *pvd, *ppvd;
7920 uint64_t guid, sguid, pguid, ppguid;
7921
7922 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7923
7924 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
7925 pvd = vd->vdev_parent;
7926 ppvd = pvd->vdev_parent;
7927 guid = vd->vdev_guid;
7928 pguid = pvd->vdev_guid;
7929 ppguid = ppvd->vdev_guid;
7930 sguid = 0;
7931 /*
7932 * If we have just finished replacing a hot spared device, then
7933 * we need to detach the parent's first child (the original hot
7934 * spare) as well.
7935 */
7936 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
7937 ppvd->vdev_children == 2) {
7938 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
7939 sguid = ppvd->vdev_child[1]->vdev_guid;
7940 }
7941 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
7942
7943 spa_config_exit(spa, SCL_ALL, FTAG);
7944 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
7945 return;
7946 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
7947 return;
7948 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7949 }
7950
7951 spa_config_exit(spa, SCL_ALL, FTAG);
7952
7953 /*
7954 * If a detach was not performed above replace waiters will not have
7955 * been notified. In which case we must do so now.
7956 */
7957 spa_notify_waiters(spa);
7958 }
7959
7960 /*
7961 * Update the stored path or FRU for this vdev.
7962 */
7963 static int
7964 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
7965 boolean_t ispath)
7966 {
7967 vdev_t *vd;
7968 boolean_t sync = B_FALSE;
7969
7970 ASSERT(spa_writeable(spa));
7971
7972 spa_vdev_state_enter(spa, SCL_ALL);
7973
7974 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
7975 return (spa_vdev_state_exit(spa, NULL, ENOENT));
7976
7977 if (!vd->vdev_ops->vdev_op_leaf)
7978 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
7979
7980 if (ispath) {
7981 if (strcmp(value, vd->vdev_path) != 0) {
7982 spa_strfree(vd->vdev_path);
7983 vd->vdev_path = spa_strdup(value);
7984 sync = B_TRUE;
7985 }
7986 } else {
7987 if (vd->vdev_fru == NULL) {
7988 vd->vdev_fru = spa_strdup(value);
7989 sync = B_TRUE;
7990 } else if (strcmp(value, vd->vdev_fru) != 0) {
7991 spa_strfree(vd->vdev_fru);
7992 vd->vdev_fru = spa_strdup(value);
7993 sync = B_TRUE;
7994 }
7995 }
7996
7997 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
7998 }
7999
8000 int
8001 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
8002 {
8003 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
8004 }
8005
8006 int
8007 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
8008 {
8009 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
8010 }
8011
8012 /*
8013 * ==========================================================================
8014 * SPA Scanning
8015 * ==========================================================================
8016 */
8017 int
8018 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
8019 {
8020 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
8021
8022 if (dsl_scan_resilvering(spa->spa_dsl_pool))
8023 return (SET_ERROR(EBUSY));
8024
8025 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
8026 }
8027
8028 int
8029 spa_scan_stop(spa_t *spa)
8030 {
8031 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
8032 if (dsl_scan_resilvering(spa->spa_dsl_pool))
8033 return (SET_ERROR(EBUSY));
8034 return (dsl_scan_cancel(spa->spa_dsl_pool));
8035 }
8036
8037 int
8038 spa_scan(spa_t *spa, pool_scan_func_t func)
8039 {
8040 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
8041
8042 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
8043 return (SET_ERROR(ENOTSUP));
8044
8045 if (func == POOL_SCAN_RESILVER &&
8046 !spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER))
8047 return (SET_ERROR(ENOTSUP));
8048
8049 /*
8050 * If a resilver was requested, but there is no DTL on a
8051 * writeable leaf device, we have nothing to do.
8052 */
8053 if (func == POOL_SCAN_RESILVER &&
8054 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
8055 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
8056 return (0);
8057 }
8058
8059 return (dsl_scan(spa->spa_dsl_pool, func));
8060 }
8061
8062 /*
8063 * ==========================================================================
8064 * SPA async task processing
8065 * ==========================================================================
8066 */
8067
8068 static void
8069 spa_async_remove(spa_t *spa, vdev_t *vd)
8070 {
8071 if (vd->vdev_remove_wanted) {
8072 vd->vdev_remove_wanted = B_FALSE;
8073 vd->vdev_delayed_close = B_FALSE;
8074 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
8075
8076 /*
8077 * We want to clear the stats, but we don't want to do a full
8078 * vdev_clear() as that will cause us to throw away
8079 * degraded/faulted state as well as attempt to reopen the
8080 * device, all of which is a waste.
8081 */
8082 vd->vdev_stat.vs_read_errors = 0;
8083 vd->vdev_stat.vs_write_errors = 0;
8084 vd->vdev_stat.vs_checksum_errors = 0;
8085
8086 vdev_state_dirty(vd->vdev_top);
8087
8088 /* Tell userspace that the vdev is gone. */
8089 zfs_post_remove(spa, vd);
8090 }
8091
8092 for (int c = 0; c < vd->vdev_children; c++)
8093 spa_async_remove(spa, vd->vdev_child[c]);
8094 }
8095
8096 static void
8097 spa_async_probe(spa_t *spa, vdev_t *vd)
8098 {
8099 if (vd->vdev_probe_wanted) {
8100 vd->vdev_probe_wanted = B_FALSE;
8101 vdev_reopen(vd); /* vdev_open() does the actual probe */
8102 }
8103
8104 for (int c = 0; c < vd->vdev_children; c++)
8105 spa_async_probe(spa, vd->vdev_child[c]);
8106 }
8107
8108 static void
8109 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
8110 {
8111 if (!spa->spa_autoexpand)
8112 return;
8113
8114 for (int c = 0; c < vd->vdev_children; c++) {
8115 vdev_t *cvd = vd->vdev_child[c];
8116 spa_async_autoexpand(spa, cvd);
8117 }
8118
8119 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
8120 return;
8121
8122 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_AUTOEXPAND);
8123 }
8124
8125 static void
8126 spa_async_thread(void *arg)
8127 {
8128 spa_t *spa = (spa_t *)arg;
8129 dsl_pool_t *dp = spa->spa_dsl_pool;
8130 int tasks;
8131
8132 ASSERT(spa->spa_sync_on);
8133
8134 mutex_enter(&spa->spa_async_lock);
8135 tasks = spa->spa_async_tasks;
8136 spa->spa_async_tasks = 0;
8137 mutex_exit(&spa->spa_async_lock);
8138
8139 /*
8140 * See if the config needs to be updated.
8141 */
8142 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
8143 uint64_t old_space, new_space;
8144
8145 mutex_enter(&spa_namespace_lock);
8146 old_space = metaslab_class_get_space(spa_normal_class(spa));
8147 old_space += metaslab_class_get_space(spa_special_class(spa));
8148 old_space += metaslab_class_get_space(spa_dedup_class(spa));
8149 old_space += metaslab_class_get_space(
8150 spa_embedded_log_class(spa));
8151
8152 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
8153
8154 new_space = metaslab_class_get_space(spa_normal_class(spa));
8155 new_space += metaslab_class_get_space(spa_special_class(spa));
8156 new_space += metaslab_class_get_space(spa_dedup_class(spa));
8157 new_space += metaslab_class_get_space(
8158 spa_embedded_log_class(spa));
8159 mutex_exit(&spa_namespace_lock);
8160
8161 /*
8162 * If the pool grew as a result of the config update,
8163 * then log an internal history event.
8164 */
8165 if (new_space != old_space) {
8166 spa_history_log_internal(spa, "vdev online", NULL,
8167 "pool '%s' size: %llu(+%llu)",
8168 spa_name(spa), (u_longlong_t)new_space,
8169 (u_longlong_t)(new_space - old_space));
8170 }
8171 }
8172
8173 /*
8174 * See if any devices need to be marked REMOVED.
8175 */
8176 if (tasks & SPA_ASYNC_REMOVE) {
8177 spa_vdev_state_enter(spa, SCL_NONE);
8178 spa_async_remove(spa, spa->spa_root_vdev);
8179 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
8180 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
8181 for (int i = 0; i < spa->spa_spares.sav_count; i++)
8182 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
8183 (void) spa_vdev_state_exit(spa, NULL, 0);
8184 }
8185
8186 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
8187 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8188 spa_async_autoexpand(spa, spa->spa_root_vdev);
8189 spa_config_exit(spa, SCL_CONFIG, FTAG);
8190 }
8191
8192 /*
8193 * See if any devices need to be probed.
8194 */
8195 if (tasks & SPA_ASYNC_PROBE) {
8196 spa_vdev_state_enter(spa, SCL_NONE);
8197 spa_async_probe(spa, spa->spa_root_vdev);
8198 (void) spa_vdev_state_exit(spa, NULL, 0);
8199 }
8200
8201 /*
8202 * If any devices are done replacing, detach them.
8203 */
8204 if (tasks & SPA_ASYNC_RESILVER_DONE ||
8205 tasks & SPA_ASYNC_REBUILD_DONE) {
8206 spa_vdev_resilver_done(spa);
8207 }
8208
8209 /*
8210 * Kick off a resilver.
8211 */
8212 if (tasks & SPA_ASYNC_RESILVER &&
8213 !vdev_rebuild_active(spa->spa_root_vdev) &&
8214 (!dsl_scan_resilvering(dp) ||
8215 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_RESILVER_DEFER)))
8216 dsl_scan_restart_resilver(dp, 0);
8217
8218 if (tasks & SPA_ASYNC_INITIALIZE_RESTART) {
8219 mutex_enter(&spa_namespace_lock);
8220 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8221 vdev_initialize_restart(spa->spa_root_vdev);
8222 spa_config_exit(spa, SCL_CONFIG, FTAG);
8223 mutex_exit(&spa_namespace_lock);
8224 }
8225
8226 if (tasks & SPA_ASYNC_TRIM_RESTART) {
8227 mutex_enter(&spa_namespace_lock);
8228 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8229 vdev_trim_restart(spa->spa_root_vdev);
8230 spa_config_exit(spa, SCL_CONFIG, FTAG);
8231 mutex_exit(&spa_namespace_lock);
8232 }
8233
8234 if (tasks & SPA_ASYNC_AUTOTRIM_RESTART) {
8235 mutex_enter(&spa_namespace_lock);
8236 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8237 vdev_autotrim_restart(spa);
8238 spa_config_exit(spa, SCL_CONFIG, FTAG);
8239 mutex_exit(&spa_namespace_lock);
8240 }
8241
8242 /*
8243 * Kick off L2 cache whole device TRIM.
8244 */
8245 if (tasks & SPA_ASYNC_L2CACHE_TRIM) {
8246 mutex_enter(&spa_namespace_lock);
8247 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8248 vdev_trim_l2arc(spa);
8249 spa_config_exit(spa, SCL_CONFIG, FTAG);
8250 mutex_exit(&spa_namespace_lock);
8251 }
8252
8253 /*
8254 * Kick off L2 cache rebuilding.
8255 */
8256 if (tasks & SPA_ASYNC_L2CACHE_REBUILD) {
8257 mutex_enter(&spa_namespace_lock);
8258 spa_config_enter(spa, SCL_L2ARC, FTAG, RW_READER);
8259 l2arc_spa_rebuild_start(spa);
8260 spa_config_exit(spa, SCL_L2ARC, FTAG);
8261 mutex_exit(&spa_namespace_lock);
8262 }
8263
8264 /*
8265 * Let the world know that we're done.
8266 */
8267 mutex_enter(&spa->spa_async_lock);
8268 spa->spa_async_thread = NULL;
8269 cv_broadcast(&spa->spa_async_cv);
8270 mutex_exit(&spa->spa_async_lock);
8271 thread_exit();
8272 }
8273
8274 void
8275 spa_async_suspend(spa_t *spa)
8276 {
8277 mutex_enter(&spa->spa_async_lock);
8278 spa->spa_async_suspended++;
8279 while (spa->spa_async_thread != NULL)
8280 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
8281 mutex_exit(&spa->spa_async_lock);
8282
8283 spa_vdev_remove_suspend(spa);
8284
8285 zthr_t *condense_thread = spa->spa_condense_zthr;
8286 if (condense_thread != NULL)
8287 zthr_cancel(condense_thread);
8288
8289 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
8290 if (discard_thread != NULL)
8291 zthr_cancel(discard_thread);
8292
8293 zthr_t *ll_delete_thread = spa->spa_livelist_delete_zthr;
8294 if (ll_delete_thread != NULL)
8295 zthr_cancel(ll_delete_thread);
8296
8297 zthr_t *ll_condense_thread = spa->spa_livelist_condense_zthr;
8298 if (ll_condense_thread != NULL)
8299 zthr_cancel(ll_condense_thread);
8300 }
8301
8302 void
8303 spa_async_resume(spa_t *spa)
8304 {
8305 mutex_enter(&spa->spa_async_lock);
8306 ASSERT(spa->spa_async_suspended != 0);
8307 spa->spa_async_suspended--;
8308 mutex_exit(&spa->spa_async_lock);
8309 spa_restart_removal(spa);
8310
8311 zthr_t *condense_thread = spa->spa_condense_zthr;
8312 if (condense_thread != NULL)
8313 zthr_resume(condense_thread);
8314
8315 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
8316 if (discard_thread != NULL)
8317 zthr_resume(discard_thread);
8318
8319 zthr_t *ll_delete_thread = spa->spa_livelist_delete_zthr;
8320 if (ll_delete_thread != NULL)
8321 zthr_resume(ll_delete_thread);
8322
8323 zthr_t *ll_condense_thread = spa->spa_livelist_condense_zthr;
8324 if (ll_condense_thread != NULL)
8325 zthr_resume(ll_condense_thread);
8326 }
8327
8328 static boolean_t
8329 spa_async_tasks_pending(spa_t *spa)
8330 {
8331 uint_t non_config_tasks;
8332 uint_t config_task;
8333 boolean_t config_task_suspended;
8334
8335 non_config_tasks = spa->spa_async_tasks & ~SPA_ASYNC_CONFIG_UPDATE;
8336 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
8337 if (spa->spa_ccw_fail_time == 0) {
8338 config_task_suspended = B_FALSE;
8339 } else {
8340 config_task_suspended =
8341 (gethrtime() - spa->spa_ccw_fail_time) <
8342 ((hrtime_t)zfs_ccw_retry_interval * NANOSEC);
8343 }
8344
8345 return (non_config_tasks || (config_task && !config_task_suspended));
8346 }
8347
8348 static void
8349 spa_async_dispatch(spa_t *spa)
8350 {
8351 mutex_enter(&spa->spa_async_lock);
8352 if (spa_async_tasks_pending(spa) &&
8353 !spa->spa_async_suspended &&
8354 spa->spa_async_thread == NULL)
8355 spa->spa_async_thread = thread_create(NULL, 0,
8356 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
8357 mutex_exit(&spa->spa_async_lock);
8358 }
8359
8360 void
8361 spa_async_request(spa_t *spa, int task)
8362 {
8363 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
8364 mutex_enter(&spa->spa_async_lock);
8365 spa->spa_async_tasks |= task;
8366 mutex_exit(&spa->spa_async_lock);
8367 }
8368
8369 int
8370 spa_async_tasks(spa_t *spa)
8371 {
8372 return (spa->spa_async_tasks);
8373 }
8374
8375 /*
8376 * ==========================================================================
8377 * SPA syncing routines
8378 * ==========================================================================
8379 */
8380
8381
8382 static int
8383 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
8384 dmu_tx_t *tx)
8385 {
8386 bpobj_t *bpo = arg;
8387 bpobj_enqueue(bpo, bp, bp_freed, tx);
8388 return (0);
8389 }
8390
8391 int
8392 bpobj_enqueue_alloc_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
8393 {
8394 return (bpobj_enqueue_cb(arg, bp, B_FALSE, tx));
8395 }
8396
8397 int
8398 bpobj_enqueue_free_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
8399 {
8400 return (bpobj_enqueue_cb(arg, bp, B_TRUE, tx));
8401 }
8402
8403 static int
8404 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
8405 {
8406 zio_t *pio = arg;
8407
8408 zio_nowait(zio_free_sync(pio, pio->io_spa, dmu_tx_get_txg(tx), bp,
8409 pio->io_flags));
8410 return (0);
8411 }
8412
8413 static int
8414 bpobj_spa_free_sync_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
8415 dmu_tx_t *tx)
8416 {
8417 ASSERT(!bp_freed);
8418 return (spa_free_sync_cb(arg, bp, tx));
8419 }
8420
8421 /*
8422 * Note: this simple function is not inlined to make it easier to dtrace the
8423 * amount of time spent syncing frees.
8424 */
8425 static void
8426 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
8427 {
8428 zio_t *zio = zio_root(spa, NULL, NULL, 0);
8429 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
8430 VERIFY(zio_wait(zio) == 0);
8431 }
8432
8433 /*
8434 * Note: this simple function is not inlined to make it easier to dtrace the
8435 * amount of time spent syncing deferred frees.
8436 */
8437 static void
8438 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
8439 {
8440 if (spa_sync_pass(spa) != 1)
8441 return;
8442
8443 /*
8444 * Note:
8445 * If the log space map feature is active, we stop deferring
8446 * frees to the next TXG and therefore running this function
8447 * would be considered a no-op as spa_deferred_bpobj should
8448 * not have any entries.
8449 *
8450 * That said we run this function anyway (instead of returning
8451 * immediately) for the edge-case scenario where we just
8452 * activated the log space map feature in this TXG but we have
8453 * deferred frees from the previous TXG.
8454 */
8455 zio_t *zio = zio_root(spa, NULL, NULL, 0);
8456 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
8457 bpobj_spa_free_sync_cb, zio, tx), ==, 0);
8458 VERIFY0(zio_wait(zio));
8459 }
8460
8461 static void
8462 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
8463 {
8464 char *packed = NULL;
8465 size_t bufsize;
8466 size_t nvsize = 0;
8467 dmu_buf_t *db;
8468
8469 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
8470
8471 /*
8472 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
8473 * information. This avoids the dmu_buf_will_dirty() path and
8474 * saves us a pre-read to get data we don't actually care about.
8475 */
8476 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
8477 packed = vmem_alloc(bufsize, KM_SLEEP);
8478
8479 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
8480 KM_SLEEP) == 0);
8481 bzero(packed + nvsize, bufsize - nvsize);
8482
8483 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
8484
8485 vmem_free(packed, bufsize);
8486
8487 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
8488 dmu_buf_will_dirty(db, tx);
8489 *(uint64_t *)db->db_data = nvsize;
8490 dmu_buf_rele(db, FTAG);
8491 }
8492
8493 static void
8494 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
8495 const char *config, const char *entry)
8496 {
8497 nvlist_t *nvroot;
8498 nvlist_t **list;
8499 int i;
8500
8501 if (!sav->sav_sync)
8502 return;
8503
8504 /*
8505 * Update the MOS nvlist describing the list of available devices.
8506 * spa_validate_aux() will have already made sure this nvlist is
8507 * valid and the vdevs are labeled appropriately.
8508 */
8509 if (sav->sav_object == 0) {
8510 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
8511 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
8512 sizeof (uint64_t), tx);
8513 VERIFY(zap_update(spa->spa_meta_objset,
8514 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
8515 &sav->sav_object, tx) == 0);
8516 }
8517
8518 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
8519 if (sav->sav_count == 0) {
8520 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
8521 } else {
8522 list = kmem_alloc(sav->sav_count*sizeof (void *), KM_SLEEP);
8523 for (i = 0; i < sav->sav_count; i++)
8524 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
8525 B_FALSE, VDEV_CONFIG_L2CACHE);
8526 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
8527 sav->sav_count) == 0);
8528 for (i = 0; i < sav->sav_count; i++)
8529 nvlist_free(list[i]);
8530 kmem_free(list, sav->sav_count * sizeof (void *));
8531 }
8532
8533 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
8534 nvlist_free(nvroot);
8535
8536 sav->sav_sync = B_FALSE;
8537 }
8538
8539 /*
8540 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
8541 * The all-vdev ZAP must be empty.
8542 */
8543 static void
8544 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
8545 {
8546 spa_t *spa = vd->vdev_spa;
8547
8548 if (vd->vdev_top_zap != 0) {
8549 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
8550 vd->vdev_top_zap, tx));
8551 }
8552 if (vd->vdev_leaf_zap != 0) {
8553 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
8554 vd->vdev_leaf_zap, tx));
8555 }
8556 for (uint64_t i = 0; i < vd->vdev_children; i++) {
8557 spa_avz_build(vd->vdev_child[i], avz, tx);
8558 }
8559 }
8560
8561 static void
8562 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
8563 {
8564 nvlist_t *config;
8565
8566 /*
8567 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
8568 * its config may not be dirty but we still need to build per-vdev ZAPs.
8569 * Similarly, if the pool is being assembled (e.g. after a split), we
8570 * need to rebuild the AVZ although the config may not be dirty.
8571 */
8572 if (list_is_empty(&spa->spa_config_dirty_list) &&
8573 spa->spa_avz_action == AVZ_ACTION_NONE)
8574 return;
8575
8576 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8577
8578 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
8579 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
8580 spa->spa_all_vdev_zaps != 0);
8581
8582 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
8583 /* Make and build the new AVZ */
8584 uint64_t new_avz = zap_create(spa->spa_meta_objset,
8585 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
8586 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
8587
8588 /* Diff old AVZ with new one */
8589 zap_cursor_t zc;
8590 zap_attribute_t za;
8591
8592 for (zap_cursor_init(&zc, spa->spa_meta_objset,
8593 spa->spa_all_vdev_zaps);
8594 zap_cursor_retrieve(&zc, &za) == 0;
8595 zap_cursor_advance(&zc)) {
8596 uint64_t vdzap = za.za_first_integer;
8597 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
8598 vdzap) == ENOENT) {
8599 /*
8600 * ZAP is listed in old AVZ but not in new one;
8601 * destroy it
8602 */
8603 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
8604 tx));
8605 }
8606 }
8607
8608 zap_cursor_fini(&zc);
8609
8610 /* Destroy the old AVZ */
8611 VERIFY0(zap_destroy(spa->spa_meta_objset,
8612 spa->spa_all_vdev_zaps, tx));
8613
8614 /* Replace the old AVZ in the dir obj with the new one */
8615 VERIFY0(zap_update(spa->spa_meta_objset,
8616 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
8617 sizeof (new_avz), 1, &new_avz, tx));
8618
8619 spa->spa_all_vdev_zaps = new_avz;
8620 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
8621 zap_cursor_t zc;
8622 zap_attribute_t za;
8623
8624 /* Walk through the AVZ and destroy all listed ZAPs */
8625 for (zap_cursor_init(&zc, spa->spa_meta_objset,
8626 spa->spa_all_vdev_zaps);
8627 zap_cursor_retrieve(&zc, &za) == 0;
8628 zap_cursor_advance(&zc)) {
8629 uint64_t zap = za.za_first_integer;
8630 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
8631 }
8632
8633 zap_cursor_fini(&zc);
8634
8635 /* Destroy and unlink the AVZ itself */
8636 VERIFY0(zap_destroy(spa->spa_meta_objset,
8637 spa->spa_all_vdev_zaps, tx));
8638 VERIFY0(zap_remove(spa->spa_meta_objset,
8639 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
8640 spa->spa_all_vdev_zaps = 0;
8641 }
8642
8643 if (spa->spa_all_vdev_zaps == 0) {
8644 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
8645 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
8646 DMU_POOL_VDEV_ZAP_MAP, tx);
8647 }
8648 spa->spa_avz_action = AVZ_ACTION_NONE;
8649
8650 /* Create ZAPs for vdevs that don't have them. */
8651 vdev_construct_zaps(spa->spa_root_vdev, tx);
8652
8653 config = spa_config_generate(spa, spa->spa_root_vdev,
8654 dmu_tx_get_txg(tx), B_FALSE);
8655
8656 /*
8657 * If we're upgrading the spa version then make sure that
8658 * the config object gets updated with the correct version.
8659 */
8660 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
8661 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
8662 spa->spa_uberblock.ub_version);
8663
8664 spa_config_exit(spa, SCL_STATE, FTAG);
8665
8666 nvlist_free(spa->spa_config_syncing);
8667 spa->spa_config_syncing = config;
8668
8669 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
8670 }
8671
8672 static void
8673 spa_sync_version(void *arg, dmu_tx_t *tx)
8674 {
8675 uint64_t *versionp = arg;
8676 uint64_t version = *versionp;
8677 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
8678
8679 /*
8680 * Setting the version is special cased when first creating the pool.
8681 */
8682 ASSERT(tx->tx_txg != TXG_INITIAL);
8683
8684 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
8685 ASSERT(version >= spa_version(spa));
8686
8687 spa->spa_uberblock.ub_version = version;
8688 vdev_config_dirty(spa->spa_root_vdev);
8689 spa_history_log_internal(spa, "set", tx, "version=%lld",
8690 (longlong_t)version);
8691 }
8692
8693 /*
8694 * Set zpool properties.
8695 */
8696 static void
8697 spa_sync_props(void *arg, dmu_tx_t *tx)
8698 {
8699 nvlist_t *nvp = arg;
8700 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
8701 objset_t *mos = spa->spa_meta_objset;
8702 nvpair_t *elem = NULL;
8703
8704 mutex_enter(&spa->spa_props_lock);
8705
8706 while ((elem = nvlist_next_nvpair(nvp, elem))) {
8707 uint64_t intval;
8708 char *strval, *fname;
8709 zpool_prop_t prop;
8710 const char *propname;
8711 zprop_type_t proptype;
8712 spa_feature_t fid;
8713
8714 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
8715 case ZPOOL_PROP_INVAL:
8716 /*
8717 * We checked this earlier in spa_prop_validate().
8718 */
8719 ASSERT(zpool_prop_feature(nvpair_name(elem)));
8720
8721 fname = strchr(nvpair_name(elem), '@') + 1;
8722 VERIFY0(zfeature_lookup_name(fname, &fid));
8723
8724 spa_feature_enable(spa, fid, tx);
8725 spa_history_log_internal(spa, "set", tx,
8726 "%s=enabled", nvpair_name(elem));
8727 break;
8728
8729 case ZPOOL_PROP_VERSION:
8730 intval = fnvpair_value_uint64(elem);
8731 /*
8732 * The version is synced separately before other
8733 * properties and should be correct by now.
8734 */
8735 ASSERT3U(spa_version(spa), >=, intval);
8736 break;
8737
8738 case ZPOOL_PROP_ALTROOT:
8739 /*
8740 * 'altroot' is a non-persistent property. It should
8741 * have been set temporarily at creation or import time.
8742 */
8743 ASSERT(spa->spa_root != NULL);
8744 break;
8745
8746 case ZPOOL_PROP_READONLY:
8747 case ZPOOL_PROP_CACHEFILE:
8748 /*
8749 * 'readonly' and 'cachefile' are also non-persistent
8750 * properties.
8751 */
8752 break;
8753 case ZPOOL_PROP_COMMENT:
8754 strval = fnvpair_value_string(elem);
8755 if (spa->spa_comment != NULL)
8756 spa_strfree(spa->spa_comment);
8757 spa->spa_comment = spa_strdup(strval);
8758 /*
8759 * We need to dirty the configuration on all the vdevs
8760 * so that their labels get updated. We also need to
8761 * update the cache file to keep it in sync with the
8762 * MOS version. It's unnecessary to do this for pool
8763 * creation since the vdev's configuration has already
8764 * been dirtied.
8765 */
8766 if (tx->tx_txg != TXG_INITIAL) {
8767 vdev_config_dirty(spa->spa_root_vdev);
8768 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
8769 }
8770 spa_history_log_internal(spa, "set", tx,
8771 "%s=%s", nvpair_name(elem), strval);
8772 break;
8773 case ZPOOL_PROP_COMPATIBILITY:
8774 strval = fnvpair_value_string(elem);
8775 if (spa->spa_compatibility != NULL)
8776 spa_strfree(spa->spa_compatibility);
8777 spa->spa_compatibility = spa_strdup(strval);
8778 /*
8779 * Dirty the configuration on vdevs as above.
8780 */
8781 if (tx->tx_txg != TXG_INITIAL) {
8782 vdev_config_dirty(spa->spa_root_vdev);
8783 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
8784 }
8785
8786 spa_history_log_internal(spa, "set", tx,
8787 "%s=%s", nvpair_name(elem), strval);
8788 break;
8789
8790 default:
8791 /*
8792 * Set pool property values in the poolprops mos object.
8793 */
8794 if (spa->spa_pool_props_object == 0) {
8795 spa->spa_pool_props_object =
8796 zap_create_link(mos, DMU_OT_POOL_PROPS,
8797 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
8798 tx);
8799 }
8800
8801 /* normalize the property name */
8802 propname = zpool_prop_to_name(prop);
8803 proptype = zpool_prop_get_type(prop);
8804
8805 if (nvpair_type(elem) == DATA_TYPE_STRING) {
8806 ASSERT(proptype == PROP_TYPE_STRING);
8807 strval = fnvpair_value_string(elem);
8808 VERIFY0(zap_update(mos,
8809 spa->spa_pool_props_object, propname,
8810 1, strlen(strval) + 1, strval, tx));
8811 spa_history_log_internal(spa, "set", tx,
8812 "%s=%s", nvpair_name(elem), strval);
8813 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
8814 intval = fnvpair_value_uint64(elem);
8815
8816 if (proptype == PROP_TYPE_INDEX) {
8817 const char *unused;
8818 VERIFY0(zpool_prop_index_to_string(
8819 prop, intval, &unused));
8820 }
8821 VERIFY0(zap_update(mos,
8822 spa->spa_pool_props_object, propname,
8823 8, 1, &intval, tx));
8824 spa_history_log_internal(spa, "set", tx,
8825 "%s=%lld", nvpair_name(elem),
8826 (longlong_t)intval);
8827 } else {
8828 ASSERT(0); /* not allowed */
8829 }
8830
8831 switch (prop) {
8832 case ZPOOL_PROP_DELEGATION:
8833 spa->spa_delegation = intval;
8834 break;
8835 case ZPOOL_PROP_BOOTFS:
8836 spa->spa_bootfs = intval;
8837 break;
8838 case ZPOOL_PROP_FAILUREMODE:
8839 spa->spa_failmode = intval;
8840 break;
8841 case ZPOOL_PROP_AUTOTRIM:
8842 spa->spa_autotrim = intval;
8843 spa_async_request(spa,
8844 SPA_ASYNC_AUTOTRIM_RESTART);
8845 break;
8846 case ZPOOL_PROP_AUTOEXPAND:
8847 spa->spa_autoexpand = intval;
8848 if (tx->tx_txg != TXG_INITIAL)
8849 spa_async_request(spa,
8850 SPA_ASYNC_AUTOEXPAND);
8851 break;
8852 case ZPOOL_PROP_MULTIHOST:
8853 spa->spa_multihost = intval;
8854 break;
8855 default:
8856 break;
8857 }
8858 }
8859
8860 }
8861
8862 mutex_exit(&spa->spa_props_lock);
8863 }
8864
8865 /*
8866 * Perform one-time upgrade on-disk changes. spa_version() does not
8867 * reflect the new version this txg, so there must be no changes this
8868 * txg to anything that the upgrade code depends on after it executes.
8869 * Therefore this must be called after dsl_pool_sync() does the sync
8870 * tasks.
8871 */
8872 static void
8873 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
8874 {
8875 if (spa_sync_pass(spa) != 1)
8876 return;
8877
8878 dsl_pool_t *dp = spa->spa_dsl_pool;
8879 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
8880
8881 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
8882 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
8883 dsl_pool_create_origin(dp, tx);
8884
8885 /* Keeping the origin open increases spa_minref */
8886 spa->spa_minref += 3;
8887 }
8888
8889 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
8890 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
8891 dsl_pool_upgrade_clones(dp, tx);
8892 }
8893
8894 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
8895 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
8896 dsl_pool_upgrade_dir_clones(dp, tx);
8897
8898 /* Keeping the freedir open increases spa_minref */
8899 spa->spa_minref += 3;
8900 }
8901
8902 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
8903 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
8904 spa_feature_create_zap_objects(spa, tx);
8905 }
8906
8907 /*
8908 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
8909 * when possibility to use lz4 compression for metadata was added
8910 * Old pools that have this feature enabled must be upgraded to have
8911 * this feature active
8912 */
8913 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
8914 boolean_t lz4_en = spa_feature_is_enabled(spa,
8915 SPA_FEATURE_LZ4_COMPRESS);
8916 boolean_t lz4_ac = spa_feature_is_active(spa,
8917 SPA_FEATURE_LZ4_COMPRESS);
8918
8919 if (lz4_en && !lz4_ac)
8920 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
8921 }
8922
8923 /*
8924 * If we haven't written the salt, do so now. Note that the
8925 * feature may not be activated yet, but that's fine since
8926 * the presence of this ZAP entry is backwards compatible.
8927 */
8928 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
8929 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
8930 VERIFY0(zap_add(spa->spa_meta_objset,
8931 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
8932 sizeof (spa->spa_cksum_salt.zcs_bytes),
8933 spa->spa_cksum_salt.zcs_bytes, tx));
8934 }
8935
8936 rrw_exit(&dp->dp_config_rwlock, FTAG);
8937 }
8938
8939 static void
8940 vdev_indirect_state_sync_verify(vdev_t *vd)
8941 {
8942 vdev_indirect_mapping_t *vim __maybe_unused = vd->vdev_indirect_mapping;
8943 vdev_indirect_births_t *vib __maybe_unused = vd->vdev_indirect_births;
8944
8945 if (vd->vdev_ops == &vdev_indirect_ops) {
8946 ASSERT(vim != NULL);
8947 ASSERT(vib != NULL);
8948 }
8949
8950 uint64_t obsolete_sm_object = 0;
8951 ASSERT0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
8952 if (obsolete_sm_object != 0) {
8953 ASSERT(vd->vdev_obsolete_sm != NULL);
8954 ASSERT(vd->vdev_removing ||
8955 vd->vdev_ops == &vdev_indirect_ops);
8956 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
8957 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
8958 ASSERT3U(obsolete_sm_object, ==,
8959 space_map_object(vd->vdev_obsolete_sm));
8960 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
8961 space_map_allocated(vd->vdev_obsolete_sm));
8962 }
8963 ASSERT(vd->vdev_obsolete_segments != NULL);
8964
8965 /*
8966 * Since frees / remaps to an indirect vdev can only
8967 * happen in syncing context, the obsolete segments
8968 * tree must be empty when we start syncing.
8969 */
8970 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
8971 }
8972
8973 /*
8974 * Set the top-level vdev's max queue depth. Evaluate each top-level's
8975 * async write queue depth in case it changed. The max queue depth will
8976 * not change in the middle of syncing out this txg.
8977 */
8978 static void
8979 spa_sync_adjust_vdev_max_queue_depth(spa_t *spa)
8980 {
8981 ASSERT(spa_writeable(spa));
8982
8983 vdev_t *rvd = spa->spa_root_vdev;
8984 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
8985 zfs_vdev_queue_depth_pct / 100;
8986 metaslab_class_t *normal = spa_normal_class(spa);
8987 metaslab_class_t *special = spa_special_class(spa);
8988 metaslab_class_t *dedup = spa_dedup_class(spa);
8989
8990 uint64_t slots_per_allocator = 0;
8991 for (int c = 0; c < rvd->vdev_children; c++) {
8992 vdev_t *tvd = rvd->vdev_child[c];
8993
8994 metaslab_group_t *mg = tvd->vdev_mg;
8995 if (mg == NULL || !metaslab_group_initialized(mg))
8996 continue;
8997
8998 metaslab_class_t *mc = mg->mg_class;
8999 if (mc != normal && mc != special && mc != dedup)
9000 continue;
9001
9002 /*
9003 * It is safe to do a lock-free check here because only async
9004 * allocations look at mg_max_alloc_queue_depth, and async
9005 * allocations all happen from spa_sync().
9006 */
9007 for (int i = 0; i < mg->mg_allocators; i++) {
9008 ASSERT0(zfs_refcount_count(
9009 &(mg->mg_allocator[i].mga_alloc_queue_depth)));
9010 }
9011 mg->mg_max_alloc_queue_depth = max_queue_depth;
9012
9013 for (int i = 0; i < mg->mg_allocators; i++) {
9014 mg->mg_allocator[i].mga_cur_max_alloc_queue_depth =
9015 zfs_vdev_def_queue_depth;
9016 }
9017 slots_per_allocator += zfs_vdev_def_queue_depth;
9018 }
9019
9020 for (int i = 0; i < spa->spa_alloc_count; i++) {
9021 ASSERT0(zfs_refcount_count(&normal->mc_allocator[i].
9022 mca_alloc_slots));
9023 ASSERT0(zfs_refcount_count(&special->mc_allocator[i].
9024 mca_alloc_slots));
9025 ASSERT0(zfs_refcount_count(&dedup->mc_allocator[i].
9026 mca_alloc_slots));
9027 normal->mc_allocator[i].mca_alloc_max_slots =
9028 slots_per_allocator;
9029 special->mc_allocator[i].mca_alloc_max_slots =
9030 slots_per_allocator;
9031 dedup->mc_allocator[i].mca_alloc_max_slots =
9032 slots_per_allocator;
9033 }
9034 normal->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
9035 special->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
9036 dedup->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
9037 }
9038
9039 static void
9040 spa_sync_condense_indirect(spa_t *spa, dmu_tx_t *tx)
9041 {
9042 ASSERT(spa_writeable(spa));
9043
9044 vdev_t *rvd = spa->spa_root_vdev;
9045 for (int c = 0; c < rvd->vdev_children; c++) {
9046 vdev_t *vd = rvd->vdev_child[c];
9047 vdev_indirect_state_sync_verify(vd);
9048
9049 if (vdev_indirect_should_condense(vd)) {
9050 spa_condense_indirect_start_sync(vd, tx);
9051 break;
9052 }
9053 }
9054 }
9055
9056 static void
9057 spa_sync_iterate_to_convergence(spa_t *spa, dmu_tx_t *tx)
9058 {
9059 objset_t *mos = spa->spa_meta_objset;
9060 dsl_pool_t *dp = spa->spa_dsl_pool;
9061 uint64_t txg = tx->tx_txg;
9062 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
9063
9064 do {
9065 int pass = ++spa->spa_sync_pass;
9066
9067 spa_sync_config_object(spa, tx);
9068 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
9069 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
9070 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
9071 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
9072 spa_errlog_sync(spa, txg);
9073 dsl_pool_sync(dp, txg);
9074
9075 if (pass < zfs_sync_pass_deferred_free ||
9076 spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) {
9077 /*
9078 * If the log space map feature is active we don't
9079 * care about deferred frees and the deferred bpobj
9080 * as the log space map should effectively have the
9081 * same results (i.e. appending only to one object).
9082 */
9083 spa_sync_frees(spa, free_bpl, tx);
9084 } else {
9085 /*
9086 * We can not defer frees in pass 1, because
9087 * we sync the deferred frees later in pass 1.
9088 */
9089 ASSERT3U(pass, >, 1);
9090 bplist_iterate(free_bpl, bpobj_enqueue_alloc_cb,
9091 &spa->spa_deferred_bpobj, tx);
9092 }
9093
9094 ddt_sync(spa, txg);
9095 dsl_scan_sync(dp, tx);
9096 svr_sync(spa, tx);
9097 spa_sync_upgrades(spa, tx);
9098
9099 spa_flush_metaslabs(spa, tx);
9100
9101 vdev_t *vd = NULL;
9102 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
9103 != NULL)
9104 vdev_sync(vd, txg);
9105
9106 /*
9107 * Note: We need to check if the MOS is dirty because we could
9108 * have marked the MOS dirty without updating the uberblock
9109 * (e.g. if we have sync tasks but no dirty user data). We need
9110 * to check the uberblock's rootbp because it is updated if we
9111 * have synced out dirty data (though in this case the MOS will
9112 * most likely also be dirty due to second order effects, we
9113 * don't want to rely on that here).
9114 */
9115 if (pass == 1 &&
9116 spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
9117 !dmu_objset_is_dirty(mos, txg)) {
9118 /*
9119 * Nothing changed on the first pass, therefore this
9120 * TXG is a no-op. Avoid syncing deferred frees, so
9121 * that we can keep this TXG as a no-op.
9122 */
9123 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
9124 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
9125 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
9126 ASSERT(txg_list_empty(&dp->dp_early_sync_tasks, txg));
9127 break;
9128 }
9129
9130 spa_sync_deferred_frees(spa, tx);
9131 } while (dmu_objset_is_dirty(mos, txg));
9132 }
9133
9134 /*
9135 * Rewrite the vdev configuration (which includes the uberblock) to
9136 * commit the transaction group.
9137 *
9138 * If there are no dirty vdevs, we sync the uberblock to a few random
9139 * top-level vdevs that are known to be visible in the config cache
9140 * (see spa_vdev_add() for a complete description). If there *are* dirty
9141 * vdevs, sync the uberblock to all vdevs.
9142 */
9143 static void
9144 spa_sync_rewrite_vdev_config(spa_t *spa, dmu_tx_t *tx)
9145 {
9146 vdev_t *rvd = spa->spa_root_vdev;
9147 uint64_t txg = tx->tx_txg;
9148
9149 for (;;) {
9150 int error = 0;
9151
9152 /*
9153 * We hold SCL_STATE to prevent vdev open/close/etc.
9154 * while we're attempting to write the vdev labels.
9155 */
9156 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
9157
9158 if (list_is_empty(&spa->spa_config_dirty_list)) {
9159 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
9160 int svdcount = 0;
9161 int children = rvd->vdev_children;
9162 int c0 = random_in_range(children);
9163
9164 for (int c = 0; c < children; c++) {
9165 vdev_t *vd =
9166 rvd->vdev_child[(c0 + c) % children];
9167
9168 /* Stop when revisiting the first vdev */
9169 if (c > 0 && svd[0] == vd)
9170 break;
9171
9172 if (vd->vdev_ms_array == 0 ||
9173 vd->vdev_islog ||
9174 !vdev_is_concrete(vd))
9175 continue;
9176
9177 svd[svdcount++] = vd;
9178 if (svdcount == SPA_SYNC_MIN_VDEVS)
9179 break;
9180 }
9181 error = vdev_config_sync(svd, svdcount, txg);
9182 } else {
9183 error = vdev_config_sync(rvd->vdev_child,
9184 rvd->vdev_children, txg);
9185 }
9186
9187 if (error == 0)
9188 spa->spa_last_synced_guid = rvd->vdev_guid;
9189
9190 spa_config_exit(spa, SCL_STATE, FTAG);
9191
9192 if (error == 0)
9193 break;
9194 zio_suspend(spa, NULL, ZIO_SUSPEND_IOERR);
9195 zio_resume_wait(spa);
9196 }
9197 }
9198
9199 /*
9200 * Sync the specified transaction group. New blocks may be dirtied as
9201 * part of the process, so we iterate until it converges.
9202 */
9203 void
9204 spa_sync(spa_t *spa, uint64_t txg)
9205 {
9206 vdev_t *vd = NULL;
9207
9208 VERIFY(spa_writeable(spa));
9209
9210 /*
9211 * Wait for i/os issued in open context that need to complete
9212 * before this txg syncs.
9213 */
9214 (void) zio_wait(spa->spa_txg_zio[txg & TXG_MASK]);
9215 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL,
9216 ZIO_FLAG_CANFAIL);
9217
9218 /*
9219 * Lock out configuration changes.
9220 */
9221 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
9222
9223 spa->spa_syncing_txg = txg;
9224 spa->spa_sync_pass = 0;
9225
9226 for (int i = 0; i < spa->spa_alloc_count; i++) {
9227 mutex_enter(&spa->spa_allocs[i].spaa_lock);
9228 VERIFY0(avl_numnodes(&spa->spa_allocs[i].spaa_tree));
9229 mutex_exit(&spa->spa_allocs[i].spaa_lock);
9230 }
9231
9232 /*
9233 * If there are any pending vdev state changes, convert them
9234 * into config changes that go out with this transaction group.
9235 */
9236 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
9237 while (list_head(&spa->spa_state_dirty_list) != NULL) {
9238 /*
9239 * We need the write lock here because, for aux vdevs,
9240 * calling vdev_config_dirty() modifies sav_config.
9241 * This is ugly and will become unnecessary when we
9242 * eliminate the aux vdev wart by integrating all vdevs
9243 * into the root vdev tree.
9244 */
9245 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
9246 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
9247 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
9248 vdev_state_clean(vd);
9249 vdev_config_dirty(vd);
9250 }
9251 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
9252 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
9253 }
9254 spa_config_exit(spa, SCL_STATE, FTAG);
9255
9256 dsl_pool_t *dp = spa->spa_dsl_pool;
9257 dmu_tx_t *tx = dmu_tx_create_assigned(dp, txg);
9258
9259 spa->spa_sync_starttime = gethrtime();
9260 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
9261 spa->spa_deadman_tqid = taskq_dispatch_delay(system_delay_taskq,
9262 spa_deadman, spa, TQ_SLEEP, ddi_get_lbolt() +
9263 NSEC_TO_TICK(spa->spa_deadman_synctime));
9264
9265 /*
9266 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
9267 * set spa_deflate if we have no raid-z vdevs.
9268 */
9269 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
9270 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
9271 vdev_t *rvd = spa->spa_root_vdev;
9272
9273 int i;
9274 for (i = 0; i < rvd->vdev_children; i++) {
9275 vd = rvd->vdev_child[i];
9276 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
9277 break;
9278 }
9279 if (i == rvd->vdev_children) {
9280 spa->spa_deflate = TRUE;
9281 VERIFY0(zap_add(spa->spa_meta_objset,
9282 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
9283 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
9284 }
9285 }
9286
9287 spa_sync_adjust_vdev_max_queue_depth(spa);
9288
9289 spa_sync_condense_indirect(spa, tx);
9290
9291 spa_sync_iterate_to_convergence(spa, tx);
9292
9293 #ifdef ZFS_DEBUG
9294 if (!list_is_empty(&spa->spa_config_dirty_list)) {
9295 /*
9296 * Make sure that the number of ZAPs for all the vdevs matches
9297 * the number of ZAPs in the per-vdev ZAP list. This only gets
9298 * called if the config is dirty; otherwise there may be
9299 * outstanding AVZ operations that weren't completed in
9300 * spa_sync_config_object.
9301 */
9302 uint64_t all_vdev_zap_entry_count;
9303 ASSERT0(zap_count(spa->spa_meta_objset,
9304 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
9305 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
9306 all_vdev_zap_entry_count);
9307 }
9308 #endif
9309
9310 if (spa->spa_vdev_removal != NULL) {
9311 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
9312 }
9313
9314 spa_sync_rewrite_vdev_config(spa, tx);
9315 dmu_tx_commit(tx);
9316
9317 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
9318 spa->spa_deadman_tqid = 0;
9319
9320 /*
9321 * Clear the dirty config list.
9322 */
9323 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
9324 vdev_config_clean(vd);
9325
9326 /*
9327 * Now that the new config has synced transactionally,
9328 * let it become visible to the config cache.
9329 */
9330 if (spa->spa_config_syncing != NULL) {
9331 spa_config_set(spa, spa->spa_config_syncing);
9332 spa->spa_config_txg = txg;
9333 spa->spa_config_syncing = NULL;
9334 }
9335
9336 dsl_pool_sync_done(dp, txg);
9337
9338 for (int i = 0; i < spa->spa_alloc_count; i++) {
9339 mutex_enter(&spa->spa_allocs[i].spaa_lock);
9340 VERIFY0(avl_numnodes(&spa->spa_allocs[i].spaa_tree));
9341 mutex_exit(&spa->spa_allocs[i].spaa_lock);
9342 }
9343
9344 /*
9345 * Update usable space statistics.
9346 */
9347 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
9348 != NULL)
9349 vdev_sync_done(vd, txg);
9350
9351 metaslab_class_evict_old(spa->spa_normal_class, txg);
9352 metaslab_class_evict_old(spa->spa_log_class, txg);
9353
9354 spa_sync_close_syncing_log_sm(spa);
9355
9356 spa_update_dspace(spa);
9357
9358 /*
9359 * It had better be the case that we didn't dirty anything
9360 * since vdev_config_sync().
9361 */
9362 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
9363 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
9364 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
9365
9366 while (zfs_pause_spa_sync)
9367 delay(1);
9368
9369 spa->spa_sync_pass = 0;
9370
9371 /*
9372 * Update the last synced uberblock here. We want to do this at
9373 * the end of spa_sync() so that consumers of spa_last_synced_txg()
9374 * will be guaranteed that all the processing associated with
9375 * that txg has been completed.
9376 */
9377 spa->spa_ubsync = spa->spa_uberblock;
9378 spa_config_exit(spa, SCL_CONFIG, FTAG);
9379
9380 spa_handle_ignored_writes(spa);
9381
9382 /*
9383 * If any async tasks have been requested, kick them off.
9384 */
9385 spa_async_dispatch(spa);
9386 }
9387
9388 /*
9389 * Sync all pools. We don't want to hold the namespace lock across these
9390 * operations, so we take a reference on the spa_t and drop the lock during the
9391 * sync.
9392 */
9393 void
9394 spa_sync_allpools(void)
9395 {
9396 spa_t *spa = NULL;
9397 mutex_enter(&spa_namespace_lock);
9398 while ((spa = spa_next(spa)) != NULL) {
9399 if (spa_state(spa) != POOL_STATE_ACTIVE ||
9400 !spa_writeable(spa) || spa_suspended(spa))
9401 continue;
9402 spa_open_ref(spa, FTAG);
9403 mutex_exit(&spa_namespace_lock);
9404 txg_wait_synced(spa_get_dsl(spa), 0);
9405 mutex_enter(&spa_namespace_lock);
9406 spa_close(spa, FTAG);
9407 }
9408 mutex_exit(&spa_namespace_lock);
9409 }
9410
9411 /*
9412 * ==========================================================================
9413 * Miscellaneous routines
9414 * ==========================================================================
9415 */
9416
9417 /*
9418 * Remove all pools in the system.
9419 */
9420 void
9421 spa_evict_all(void)
9422 {
9423 spa_t *spa;
9424
9425 /*
9426 * Remove all cached state. All pools should be closed now,
9427 * so every spa in the AVL tree should be unreferenced.
9428 */
9429 mutex_enter(&spa_namespace_lock);
9430 while ((spa = spa_next(NULL)) != NULL) {
9431 /*
9432 * Stop async tasks. The async thread may need to detach
9433 * a device that's been replaced, which requires grabbing
9434 * spa_namespace_lock, so we must drop it here.
9435 */
9436 spa_open_ref(spa, FTAG);
9437 mutex_exit(&spa_namespace_lock);
9438 spa_async_suspend(spa);
9439 mutex_enter(&spa_namespace_lock);
9440 spa_close(spa, FTAG);
9441
9442 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
9443 spa_unload(spa);
9444 spa_deactivate(spa);
9445 }
9446 spa_remove(spa);
9447 }
9448 mutex_exit(&spa_namespace_lock);
9449 }
9450
9451 vdev_t *
9452 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
9453 {
9454 vdev_t *vd;
9455 int i;
9456
9457 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
9458 return (vd);
9459
9460 if (aux) {
9461 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
9462 vd = spa->spa_l2cache.sav_vdevs[i];
9463 if (vd->vdev_guid == guid)
9464 return (vd);
9465 }
9466
9467 for (i = 0; i < spa->spa_spares.sav_count; i++) {
9468 vd = spa->spa_spares.sav_vdevs[i];
9469 if (vd->vdev_guid == guid)
9470 return (vd);
9471 }
9472 }
9473
9474 return (NULL);
9475 }
9476
9477 void
9478 spa_upgrade(spa_t *spa, uint64_t version)
9479 {
9480 ASSERT(spa_writeable(spa));
9481
9482 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
9483
9484 /*
9485 * This should only be called for a non-faulted pool, and since a
9486 * future version would result in an unopenable pool, this shouldn't be
9487 * possible.
9488 */
9489 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
9490 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
9491
9492 spa->spa_uberblock.ub_version = version;
9493 vdev_config_dirty(spa->spa_root_vdev);
9494
9495 spa_config_exit(spa, SCL_ALL, FTAG);
9496
9497 txg_wait_synced(spa_get_dsl(spa), 0);
9498 }
9499
9500 boolean_t
9501 spa_has_spare(spa_t *spa, uint64_t guid)
9502 {
9503 (void) spa;
9504 int i;
9505 uint64_t spareguid;
9506 spa_aux_vdev_t *sav = &spa->spa_spares;
9507
9508 for (i = 0; i < sav->sav_count; i++)
9509 if (sav->sav_vdevs[i]->vdev_guid == guid)
9510 return (B_TRUE);
9511
9512 for (i = 0; i < sav->sav_npending; i++) {
9513 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
9514 &spareguid) == 0 && spareguid == guid)
9515 return (B_TRUE);
9516 }
9517
9518 return (B_FALSE);
9519 }
9520
9521 /*
9522 * Check if a pool has an active shared spare device.
9523 * Note: reference count of an active spare is 2, as a spare and as a replace
9524 */
9525 static boolean_t
9526 spa_has_active_shared_spare(spa_t *spa)
9527 {
9528 int i, refcnt;
9529 uint64_t pool;
9530 spa_aux_vdev_t *sav = &spa->spa_spares;
9531
9532 for (i = 0; i < sav->sav_count; i++) {
9533 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
9534 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
9535 refcnt > 2)
9536 return (B_TRUE);
9537 }
9538
9539 return (B_FALSE);
9540 }
9541
9542 uint64_t
9543 spa_total_metaslabs(spa_t *spa)
9544 {
9545 vdev_t *rvd = spa->spa_root_vdev;
9546
9547 uint64_t m = 0;
9548 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
9549 vdev_t *vd = rvd->vdev_child[c];
9550 if (!vdev_is_concrete(vd))
9551 continue;
9552 m += vd->vdev_ms_count;
9553 }
9554 return (m);
9555 }
9556
9557 /*
9558 * Notify any waiting threads that some activity has switched from being in-
9559 * progress to not-in-progress so that the thread can wake up and determine
9560 * whether it is finished waiting.
9561 */
9562 void
9563 spa_notify_waiters(spa_t *spa)
9564 {
9565 /*
9566 * Acquiring spa_activities_lock here prevents the cv_broadcast from
9567 * happening between the waiting thread's check and cv_wait.
9568 */
9569 mutex_enter(&spa->spa_activities_lock);
9570 cv_broadcast(&spa->spa_activities_cv);
9571 mutex_exit(&spa->spa_activities_lock);
9572 }
9573
9574 /*
9575 * Notify any waiting threads that the pool is exporting, and then block until
9576 * they are finished using the spa_t.
9577 */
9578 void
9579 spa_wake_waiters(spa_t *spa)
9580 {
9581 mutex_enter(&spa->spa_activities_lock);
9582 spa->spa_waiters_cancel = B_TRUE;
9583 cv_broadcast(&spa->spa_activities_cv);
9584 while (spa->spa_waiters != 0)
9585 cv_wait(&spa->spa_waiters_cv, &spa->spa_activities_lock);
9586 spa->spa_waiters_cancel = B_FALSE;
9587 mutex_exit(&spa->spa_activities_lock);
9588 }
9589
9590 /* Whether the vdev or any of its descendants are being initialized/trimmed. */
9591 static boolean_t
9592 spa_vdev_activity_in_progress_impl(vdev_t *vd, zpool_wait_activity_t activity)
9593 {
9594 spa_t *spa = vd->vdev_spa;
9595
9596 ASSERT(spa_config_held(spa, SCL_CONFIG | SCL_STATE, RW_READER));
9597 ASSERT(MUTEX_HELD(&spa->spa_activities_lock));
9598 ASSERT(activity == ZPOOL_WAIT_INITIALIZE ||
9599 activity == ZPOOL_WAIT_TRIM);
9600
9601 kmutex_t *lock = activity == ZPOOL_WAIT_INITIALIZE ?
9602 &vd->vdev_initialize_lock : &vd->vdev_trim_lock;
9603
9604 mutex_exit(&spa->spa_activities_lock);
9605 mutex_enter(lock);
9606 mutex_enter(&spa->spa_activities_lock);
9607
9608 boolean_t in_progress = (activity == ZPOOL_WAIT_INITIALIZE) ?
9609 (vd->vdev_initialize_state == VDEV_INITIALIZE_ACTIVE) :
9610 (vd->vdev_trim_state == VDEV_TRIM_ACTIVE);
9611 mutex_exit(lock);
9612
9613 if (in_progress)
9614 return (B_TRUE);
9615
9616 for (int i = 0; i < vd->vdev_children; i++) {
9617 if (spa_vdev_activity_in_progress_impl(vd->vdev_child[i],
9618 activity))
9619 return (B_TRUE);
9620 }
9621
9622 return (B_FALSE);
9623 }
9624
9625 /*
9626 * If use_guid is true, this checks whether the vdev specified by guid is
9627 * being initialized/trimmed. Otherwise, it checks whether any vdev in the pool
9628 * is being initialized/trimmed. The caller must hold the config lock and
9629 * spa_activities_lock.
9630 */
9631 static int
9632 spa_vdev_activity_in_progress(spa_t *spa, boolean_t use_guid, uint64_t guid,
9633 zpool_wait_activity_t activity, boolean_t *in_progress)
9634 {
9635 mutex_exit(&spa->spa_activities_lock);
9636 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
9637 mutex_enter(&spa->spa_activities_lock);
9638
9639 vdev_t *vd;
9640 if (use_guid) {
9641 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
9642 if (vd == NULL || !vd->vdev_ops->vdev_op_leaf) {
9643 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
9644 return (EINVAL);
9645 }
9646 } else {
9647 vd = spa->spa_root_vdev;
9648 }
9649
9650 *in_progress = spa_vdev_activity_in_progress_impl(vd, activity);
9651
9652 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
9653 return (0);
9654 }
9655
9656 /*
9657 * Locking for waiting threads
9658 * ---------------------------
9659 *
9660 * Waiting threads need a way to check whether a given activity is in progress,
9661 * and then, if it is, wait for it to complete. Each activity will have some
9662 * in-memory representation of the relevant on-disk state which can be used to
9663 * determine whether or not the activity is in progress. The in-memory state and
9664 * the locking used to protect it will be different for each activity, and may
9665 * not be suitable for use with a cvar (e.g., some state is protected by the
9666 * config lock). To allow waiting threads to wait without any races, another
9667 * lock, spa_activities_lock, is used.
9668 *
9669 * When the state is checked, both the activity-specific lock (if there is one)
9670 * and spa_activities_lock are held. In some cases, the activity-specific lock
9671 * is acquired explicitly (e.g. the config lock). In others, the locking is
9672 * internal to some check (e.g. bpobj_is_empty). After checking, the waiting
9673 * thread releases the activity-specific lock and, if the activity is in
9674 * progress, then cv_waits using spa_activities_lock.
9675 *
9676 * The waiting thread is woken when another thread, one completing some
9677 * activity, updates the state of the activity and then calls
9678 * spa_notify_waiters, which will cv_broadcast. This 'completing' thread only
9679 * needs to hold its activity-specific lock when updating the state, and this
9680 * lock can (but doesn't have to) be dropped before calling spa_notify_waiters.
9681 *
9682 * Because spa_notify_waiters acquires spa_activities_lock before broadcasting,
9683 * and because it is held when the waiting thread checks the state of the
9684 * activity, it can never be the case that the completing thread both updates
9685 * the activity state and cv_broadcasts in between the waiting thread's check
9686 * and cv_wait. Thus, a waiting thread can never miss a wakeup.
9687 *
9688 * In order to prevent deadlock, when the waiting thread does its check, in some
9689 * cases it will temporarily drop spa_activities_lock in order to acquire the
9690 * activity-specific lock. The order in which spa_activities_lock and the
9691 * activity specific lock are acquired in the waiting thread is determined by
9692 * the order in which they are acquired in the completing thread; if the
9693 * completing thread calls spa_notify_waiters with the activity-specific lock
9694 * held, then the waiting thread must also acquire the activity-specific lock
9695 * first.
9696 */
9697
9698 static int
9699 spa_activity_in_progress(spa_t *spa, zpool_wait_activity_t activity,
9700 boolean_t use_tag, uint64_t tag, boolean_t *in_progress)
9701 {
9702 int error = 0;
9703
9704 ASSERT(MUTEX_HELD(&spa->spa_activities_lock));
9705
9706 switch (activity) {
9707 case ZPOOL_WAIT_CKPT_DISCARD:
9708 *in_progress =
9709 (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT) &&
9710 zap_contains(spa_meta_objset(spa),
9711 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_ZPOOL_CHECKPOINT) ==
9712 ENOENT);
9713 break;
9714 case ZPOOL_WAIT_FREE:
9715 *in_progress = ((spa_version(spa) >= SPA_VERSION_DEADLISTS &&
9716 !bpobj_is_empty(&spa->spa_dsl_pool->dp_free_bpobj)) ||
9717 spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY) ||
9718 spa_livelist_delete_check(spa));
9719 break;
9720 case ZPOOL_WAIT_INITIALIZE:
9721 case ZPOOL_WAIT_TRIM:
9722 error = spa_vdev_activity_in_progress(spa, use_tag, tag,
9723 activity, in_progress);
9724 break;
9725 case ZPOOL_WAIT_REPLACE:
9726 mutex_exit(&spa->spa_activities_lock);
9727 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
9728 mutex_enter(&spa->spa_activities_lock);
9729
9730 *in_progress = vdev_replace_in_progress(spa->spa_root_vdev);
9731 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
9732 break;
9733 case ZPOOL_WAIT_REMOVE:
9734 *in_progress = (spa->spa_removing_phys.sr_state ==
9735 DSS_SCANNING);
9736 break;
9737 case ZPOOL_WAIT_RESILVER:
9738 if ((*in_progress = vdev_rebuild_active(spa->spa_root_vdev)))
9739 break;
9740 fallthrough;
9741 case ZPOOL_WAIT_SCRUB:
9742 {
9743 boolean_t scanning, paused, is_scrub;
9744 dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
9745
9746 is_scrub = (scn->scn_phys.scn_func == POOL_SCAN_SCRUB);
9747 scanning = (scn->scn_phys.scn_state == DSS_SCANNING);
9748 paused = dsl_scan_is_paused_scrub(scn);
9749 *in_progress = (scanning && !paused &&
9750 is_scrub == (activity == ZPOOL_WAIT_SCRUB));
9751 break;
9752 }
9753 default:
9754 panic("unrecognized value for activity %d", activity);
9755 }
9756
9757 return (error);
9758 }
9759
9760 static int
9761 spa_wait_common(const char *pool, zpool_wait_activity_t activity,
9762 boolean_t use_tag, uint64_t tag, boolean_t *waited)
9763 {
9764 /*
9765 * The tag is used to distinguish between instances of an activity.
9766 * 'initialize' and 'trim' are the only activities that we use this for.
9767 * The other activities can only have a single instance in progress in a
9768 * pool at one time, making the tag unnecessary.
9769 *
9770 * There can be multiple devices being replaced at once, but since they
9771 * all finish once resilvering finishes, we don't bother keeping track
9772 * of them individually, we just wait for them all to finish.
9773 */
9774 if (use_tag && activity != ZPOOL_WAIT_INITIALIZE &&
9775 activity != ZPOOL_WAIT_TRIM)
9776 return (EINVAL);
9777
9778 if (activity < 0 || activity >= ZPOOL_WAIT_NUM_ACTIVITIES)
9779 return (EINVAL);
9780
9781 spa_t *spa;
9782 int error = spa_open(pool, &spa, FTAG);
9783 if (error != 0)
9784 return (error);
9785
9786 /*
9787 * Increment the spa's waiter count so that we can call spa_close and
9788 * still ensure that the spa_t doesn't get freed before this thread is
9789 * finished with it when the pool is exported. We want to call spa_close
9790 * before we start waiting because otherwise the additional ref would
9791 * prevent the pool from being exported or destroyed throughout the
9792 * potentially long wait.
9793 */
9794 mutex_enter(&spa->spa_activities_lock);
9795 spa->spa_waiters++;
9796 spa_close(spa, FTAG);
9797
9798 *waited = B_FALSE;
9799 for (;;) {
9800 boolean_t in_progress;
9801 error = spa_activity_in_progress(spa, activity, use_tag, tag,
9802 &in_progress);
9803
9804 if (error || !in_progress || spa->spa_waiters_cancel)
9805 break;
9806
9807 *waited = B_TRUE;
9808
9809 if (cv_wait_sig(&spa->spa_activities_cv,
9810 &spa->spa_activities_lock) == 0) {
9811 error = EINTR;
9812 break;
9813 }
9814 }
9815
9816 spa->spa_waiters--;
9817 cv_signal(&spa->spa_waiters_cv);
9818 mutex_exit(&spa->spa_activities_lock);
9819
9820 return (error);
9821 }
9822
9823 /*
9824 * Wait for a particular instance of the specified activity to complete, where
9825 * the instance is identified by 'tag'
9826 */
9827 int
9828 spa_wait_tag(const char *pool, zpool_wait_activity_t activity, uint64_t tag,
9829 boolean_t *waited)
9830 {
9831 return (spa_wait_common(pool, activity, B_TRUE, tag, waited));
9832 }
9833
9834 /*
9835 * Wait for all instances of the specified activity complete
9836 */
9837 int
9838 spa_wait(const char *pool, zpool_wait_activity_t activity, boolean_t *waited)
9839 {
9840
9841 return (spa_wait_common(pool, activity, B_FALSE, 0, waited));
9842 }
9843
9844 sysevent_t *
9845 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
9846 {
9847 sysevent_t *ev = NULL;
9848 #ifdef _KERNEL
9849 nvlist_t *resource;
9850
9851 resource = zfs_event_create(spa, vd, FM_SYSEVENT_CLASS, name, hist_nvl);
9852 if (resource) {
9853 ev = kmem_alloc(sizeof (sysevent_t), KM_SLEEP);
9854 ev->resource = resource;
9855 }
9856 #else
9857 (void) spa, (void) vd, (void) hist_nvl, (void) name;
9858 #endif
9859 return (ev);
9860 }
9861
9862 void
9863 spa_event_post(sysevent_t *ev)
9864 {
9865 #ifdef _KERNEL
9866 if (ev) {
9867 zfs_zevent_post(ev->resource, NULL, zfs_zevent_post_cb);
9868 kmem_free(ev, sizeof (*ev));
9869 }
9870 #else
9871 (void) ev;
9872 #endif
9873 }
9874
9875 /*
9876 * Post a zevent corresponding to the given sysevent. The 'name' must be one
9877 * of the event definitions in sys/sysevent/eventdefs.h. The payload will be
9878 * filled in from the spa and (optionally) the vdev. This doesn't do anything
9879 * in the userland libzpool, as we don't want consumers to misinterpret ztest
9880 * or zdb as real changes.
9881 */
9882 void
9883 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
9884 {
9885 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));
9886 }
9887
9888 /* state manipulation functions */
9889 EXPORT_SYMBOL(spa_open);
9890 EXPORT_SYMBOL(spa_open_rewind);
9891 EXPORT_SYMBOL(spa_get_stats);
9892 EXPORT_SYMBOL(spa_create);
9893 EXPORT_SYMBOL(spa_import);
9894 EXPORT_SYMBOL(spa_tryimport);
9895 EXPORT_SYMBOL(spa_destroy);
9896 EXPORT_SYMBOL(spa_export);
9897 EXPORT_SYMBOL(spa_reset);
9898 EXPORT_SYMBOL(spa_async_request);
9899 EXPORT_SYMBOL(spa_async_suspend);
9900 EXPORT_SYMBOL(spa_async_resume);
9901 EXPORT_SYMBOL(spa_inject_addref);
9902 EXPORT_SYMBOL(spa_inject_delref);
9903 EXPORT_SYMBOL(spa_scan_stat_init);
9904 EXPORT_SYMBOL(spa_scan_get_stats);
9905
9906 /* device manipulation */
9907 EXPORT_SYMBOL(spa_vdev_add);
9908 EXPORT_SYMBOL(spa_vdev_attach);
9909 EXPORT_SYMBOL(spa_vdev_detach);
9910 EXPORT_SYMBOL(spa_vdev_setpath);
9911 EXPORT_SYMBOL(spa_vdev_setfru);
9912 EXPORT_SYMBOL(spa_vdev_split_mirror);
9913
9914 /* spare statech is global across all pools) */
9915 EXPORT_SYMBOL(spa_spare_add);
9916 EXPORT_SYMBOL(spa_spare_remove);
9917 EXPORT_SYMBOL(spa_spare_exists);
9918 EXPORT_SYMBOL(spa_spare_activate);
9919
9920 /* L2ARC statech is global across all pools) */
9921 EXPORT_SYMBOL(spa_l2cache_add);
9922 EXPORT_SYMBOL(spa_l2cache_remove);
9923 EXPORT_SYMBOL(spa_l2cache_exists);
9924 EXPORT_SYMBOL(spa_l2cache_activate);
9925 EXPORT_SYMBOL(spa_l2cache_drop);
9926
9927 /* scanning */
9928 EXPORT_SYMBOL(spa_scan);
9929 EXPORT_SYMBOL(spa_scan_stop);
9930
9931 /* spa syncing */
9932 EXPORT_SYMBOL(spa_sync); /* only for DMU use */
9933 EXPORT_SYMBOL(spa_sync_allpools);
9934
9935 /* properties */
9936 EXPORT_SYMBOL(spa_prop_set);
9937 EXPORT_SYMBOL(spa_prop_get);
9938 EXPORT_SYMBOL(spa_prop_clear_bootfs);
9939
9940 /* asynchronous event notification */
9941 EXPORT_SYMBOL(spa_event_notify);
9942
9943 /* BEGIN CSTYLED */
9944 ZFS_MODULE_PARAM(zfs_spa, spa_, load_verify_shift, INT, ZMOD_RW,
9945 "log2 fraction of arc that can be used by inflight I/Os when "
9946 "verifying pool during import");
9947
9948 ZFS_MODULE_PARAM(zfs_spa, spa_, load_verify_metadata, INT, ZMOD_RW,
9949 "Set to traverse metadata on pool import");
9950
9951 ZFS_MODULE_PARAM(zfs_spa, spa_, load_verify_data, INT, ZMOD_RW,
9952 "Set to traverse data on pool import");
9953
9954 ZFS_MODULE_PARAM(zfs_spa, spa_, load_print_vdev_tree, INT, ZMOD_RW,
9955 "Print vdev tree to zfs_dbgmsg during pool import");
9956
9957 ZFS_MODULE_PARAM(zfs_zio, zio_, taskq_batch_pct, UINT, ZMOD_RD,
9958 "Percentage of CPUs to run an IO worker thread");
9959
9960 ZFS_MODULE_PARAM(zfs_zio, zio_, taskq_batch_tpq, UINT, ZMOD_RD,
9961 "Number of threads per IO worker taskqueue");
9962
9963 ZFS_MODULE_PARAM(zfs, zfs_, max_missing_tvds, ULONG, ZMOD_RW,
9964 "Allow importing pool with up to this number of missing top-level "
9965 "vdevs (in read-only mode)");
9966
9967 ZFS_MODULE_PARAM(zfs_livelist_condense, zfs_livelist_condense_, zthr_pause, INT, ZMOD_RW,
9968 "Set the livelist condense zthr to pause");
9969
9970 ZFS_MODULE_PARAM(zfs_livelist_condense, zfs_livelist_condense_, sync_pause, INT, ZMOD_RW,
9971 "Set the livelist condense synctask to pause");
9972
9973 ZFS_MODULE_PARAM(zfs_livelist_condense, zfs_livelist_condense_, sync_cancel, INT, ZMOD_RW,
9974 "Whether livelist condensing was canceled in the synctask");
9975
9976 ZFS_MODULE_PARAM(zfs_livelist_condense, zfs_livelist_condense_, zthr_cancel, INT, ZMOD_RW,
9977 "Whether livelist condensing was canceled in the zthr function");
9978
9979 ZFS_MODULE_PARAM(zfs_livelist_condense, zfs_livelist_condense_, new_alloc, INT, ZMOD_RW,
9980 "Whether extra ALLOC blkptrs were added to a livelist entry while it "
9981 "was being condensed");
9982 /* END CSTYLED */
9983