xref: /freebsd/sys/contrib/openzfs/module/zfs/vdev_indirect.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 
13 /*
14  * Copyright (c) 2014, 2017 by Delphix. All rights reserved.
15  * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
16  * Copyright (c) 2014, 2020 by Delphix. All rights reserved.
17  */
18 
19 #include <sys/zfs_context.h>
20 #include <sys/spa.h>
21 #include <sys/spa_impl.h>
22 #include <sys/vdev_impl.h>
23 #include <sys/fs/zfs.h>
24 #include <sys/zio.h>
25 #include <sys/zio_checksum.h>
26 #include <sys/metaslab.h>
27 #include <sys/dmu.h>
28 #include <sys/vdev_indirect_mapping.h>
29 #include <sys/dmu_tx.h>
30 #include <sys/dsl_synctask.h>
31 #include <sys/zap.h>
32 #include <sys/abd.h>
33 #include <sys/zthr.h>
34 #include <sys/fm/fs/zfs.h>
35 
36 /*
37  * An indirect vdev corresponds to a vdev that has been removed.  Since
38  * we cannot rewrite block pointers of snapshots, etc., we keep a
39  * mapping from old location on the removed device to the new location
40  * on another device in the pool and use this mapping whenever we need
41  * to access the DVA.  Unfortunately, this mapping did not respect
42  * logical block boundaries when it was first created, and so a DVA on
43  * this indirect vdev may be "split" into multiple sections that each
44  * map to a different location.  As a consequence, not all DVAs can be
45  * translated to an equivalent new DVA.  Instead we must provide a
46  * "vdev_remap" operation that executes a callback on each contiguous
47  * segment of the new location.  This function is used in multiple ways:
48  *
49  *  - I/Os to this vdev use the callback to determine where the
50  *    data is now located, and issue child I/Os for each segment's new
51  *    location.
52  *
53  *  - frees and claims to this vdev use the callback to free or claim
54  *    each mapped segment.  (Note that we don't actually need to claim
55  *    log blocks on indirect vdevs, because we don't allocate to
56  *    removing vdevs.  However, zdb uses zio_claim() for its leak
57  *    detection.)
58  */
59 
60 /*
61  * "Big theory statement" for how we mark blocks obsolete.
62  *
63  * When a block on an indirect vdev is freed or remapped, a section of
64  * that vdev's mapping may no longer be referenced (aka "obsolete").  We
65  * keep track of how much of each mapping entry is obsolete.  When
66  * an entry becomes completely obsolete, we can remove it, thus reducing
67  * the memory used by the mapping.  The complete picture of obsolescence
68  * is given by the following data structures, described below:
69  *  - the entry-specific obsolete count
70  *  - the vdev-specific obsolete spacemap
71  *  - the pool-specific obsolete bpobj
72  *
73  * == On disk data structures used ==
74  *
75  * We track the obsolete space for the pool using several objects.  Each
76  * of these objects is created on demand and freed when no longer
77  * needed, and is assumed to be empty if it does not exist.
78  * SPA_FEATURE_OBSOLETE_COUNTS includes the count of these objects.
79  *
80  *  - Each vic_mapping_object (associated with an indirect vdev) can
81  *    have a vimp_counts_object.  This is an array of uint32_t's
82  *    with the same number of entries as the vic_mapping_object.  When
83  *    the mapping is condensed, entries from the vic_obsolete_sm_object
84  *    (see below) are folded into the counts.  Therefore, each
85  *    obsolete_counts entry tells us the number of bytes in the
86  *    corresponding mapping entry that were not referenced when the
87  *    mapping was last condensed.
88  *
89  *  - Each indirect or removing vdev can have a vic_obsolete_sm_object.
90  *    This is a space map containing an alloc entry for every DVA that
91  *    has been obsoleted since the last time this indirect vdev was
92  *    condensed.  We use this object in order to improve performance
93  *    when marking a DVA as obsolete.  Instead of modifying an arbitrary
94  *    offset of the vimp_counts_object, we only need to append an entry
95  *    to the end of this object.  When a DVA becomes obsolete, it is
96  *    added to the obsolete space map.  This happens when the DVA is
97  *    freed, remapped and not referenced by a snapshot, or the last
98  *    snapshot referencing it is destroyed.
99  *
100  *  - Each dataset can have a ds_remap_deadlist object.  This is a
101  *    deadlist object containing all blocks that were remapped in this
102  *    dataset but referenced in a previous snapshot.  Blocks can *only*
103  *    appear on this list if they were remapped (dsl_dataset_block_remapped);
104  *    blocks that were killed in a head dataset are put on the normal
105  *    ds_deadlist and marked obsolete when they are freed.
106  *
107  *  - The pool can have a dp_obsolete_bpobj.  This is a list of blocks
108  *    in the pool that need to be marked obsolete.  When a snapshot is
109  *    destroyed, we move some of the ds_remap_deadlist to the obsolete
110  *    bpobj (see dsl_destroy_snapshot_handle_remaps()).  We then
111  *    asynchronously process the obsolete bpobj, moving its entries to
112  *    the specific vdevs' obsolete space maps.
113  *
114  * == Summary of how we mark blocks as obsolete ==
115  *
116  * - When freeing a block: if any DVA is on an indirect vdev, append to
117  *   vic_obsolete_sm_object.
118  * - When remapping a block, add dva to ds_remap_deadlist (if prev snap
119  *   references; otherwise append to vic_obsolete_sm_object).
120  * - When freeing a snapshot: move parts of ds_remap_deadlist to
121  *   dp_obsolete_bpobj (same algorithm as ds_deadlist).
122  * - When syncing the spa: process dp_obsolete_bpobj, moving ranges to
123  *   individual vdev's vic_obsolete_sm_object.
124  */
125 
126 /*
127  * "Big theory statement" for how we condense indirect vdevs.
128  *
129  * Condensing an indirect vdev's mapping is the process of determining
130  * the precise counts of obsolete space for each mapping entry (by
131  * integrating the obsolete spacemap into the obsolete counts) and
132  * writing out a new mapping that contains only referenced entries.
133  *
134  * We condense a vdev when we expect the mapping to shrink (see
135  * vdev_indirect_should_condense()), but only perform one condense at a
136  * time to limit the memory usage.  In addition, we use a separate
137  * open-context thread (spa_condense_indirect_thread) to incrementally
138  * create the new mapping object in a way that minimizes the impact on
139  * the rest of the system.
140  *
141  * == Generating a new mapping ==
142  *
143  * To generate a new mapping, we follow these steps:
144  *
145  * 1. Save the old obsolete space map and create a new mapping object
146  *    (see spa_condense_indirect_start_sync()).  This initializes the
147  *    spa_condensing_indirect_phys with the "previous obsolete space map",
148  *    which is now read only.  Newly obsolete DVAs will be added to a
149  *    new (initially empty) obsolete space map, and will not be
150  *    considered as part of this condense operation.
151  *
152  * 2. Construct in memory the precise counts of obsolete space for each
153  *    mapping entry, by incorporating the obsolete space map into the
154  *    counts.  (See vdev_indirect_mapping_load_obsolete_{counts,spacemap}().)
155  *
156  * 3. Iterate through each mapping entry, writing to the new mapping any
157  *    entries that are not completely obsolete (i.e. which don't have
158  *    obsolete count == mapping length).  (See
159  *    spa_condense_indirect_generate_new_mapping().)
160  *
161  * 4. Destroy the old mapping object and switch over to the new one
162  *    (spa_condense_indirect_complete_sync).
163  *
164  * == Restarting from failure ==
165  *
166  * To restart the condense when we import/open the pool, we must start
167  * at the 2nd step above: reconstruct the precise counts in memory,
168  * based on the space map + counts.  Then in the 3rd step, we start
169  * iterating where we left off: at vimp_max_offset of the new mapping
170  * object.
171  */
172 
173 static int zfs_condense_indirect_vdevs_enable = B_TRUE;
174 
175 /*
176  * Condense if at least this percent of the bytes in the mapping is
177  * obsolete.  With the default of 25%, the amount of space mapped
178  * will be reduced to 1% of its original size after at most 16
179  * condenses.  Higher values will condense less often (causing less
180  * i/o); lower values will reduce the mapping size more quickly.
181  */
182 static uint_t zfs_condense_indirect_obsolete_pct = 25;
183 
184 /*
185  * Condense if the obsolete space map takes up more than this amount of
186  * space on disk (logically).  This limits the amount of disk space
187  * consumed by the obsolete space map; the default of 1GB is small enough
188  * that we typically don't mind "wasting" it.
189  */
190 static uint64_t zfs_condense_max_obsolete_bytes = 1024 * 1024 * 1024;
191 
192 /*
193  * Don't bother condensing if the mapping uses less than this amount of
194  * memory.  The default of 128KB is considered a "trivial" amount of
195  * memory and not worth reducing.
196  */
197 static uint64_t zfs_condense_min_mapping_bytes = 128 * 1024;
198 
199 /*
200  * This is used by the test suite so that it can ensure that certain
201  * actions happen while in the middle of a condense (which might otherwise
202  * complete too quickly).  If used to reduce the performance impact of
203  * condensing in production, a maximum value of 1 should be sufficient.
204  */
205 static uint_t zfs_condense_indirect_commit_entry_delay_ms = 0;
206 
207 /*
208  * If an indirect split block contains more than this many possible unique
209  * combinations when being reconstructed, consider it too computationally
210  * expensive to check them all. Instead, try at most 100 randomly-selected
211  * combinations each time the block is accessed.  This allows all segment
212  * copies to participate fairly in the reconstruction when all combinations
213  * cannot be checked and prevents repeated use of one bad copy.
214  */
215 uint_t zfs_reconstruct_indirect_combinations_max = 4096;
216 
217 /*
218  * Enable to simulate damaged segments and validate reconstruction.  This
219  * is intentionally not exposed as a module parameter.
220  */
221 unsigned long zfs_reconstruct_indirect_damage_fraction = 0;
222 
223 /*
224  * The indirect_child_t represents the vdev that we will read from, when we
225  * need to read all copies of the data (e.g. for scrub or reconstruction).
226  * For plain (non-mirror) top-level vdevs (i.e. is_vdev is not a mirror),
227  * ic_vdev is the same as is_vdev.  However, for mirror top-level vdevs,
228  * ic_vdev is a child of the mirror.
229  */
230 typedef struct indirect_child {
231 	abd_t *ic_data;
232 	vdev_t *ic_vdev;
233 
234 	/*
235 	 * ic_duplicate is NULL when the ic_data contents are unique, when it
236 	 * is determined to be a duplicate it references the primary child.
237 	 */
238 	struct indirect_child *ic_duplicate;
239 	list_node_t ic_node; /* node on is_unique_child */
240 	int ic_error; /* set when a child does not contain the data */
241 } indirect_child_t;
242 
243 /*
244  * The indirect_split_t represents one mapped segment of an i/o to the
245  * indirect vdev. For non-split (contiguously-mapped) blocks, there will be
246  * only one indirect_split_t, with is_split_offset==0 and is_size==io_size.
247  * For split blocks, there will be several of these.
248  */
249 typedef struct indirect_split {
250 	list_node_t is_node; /* link on iv_splits */
251 
252 	/*
253 	 * is_split_offset is the offset into the i/o.
254 	 * This is the sum of the previous splits' is_size's.
255 	 */
256 	uint64_t is_split_offset;
257 
258 	vdev_t *is_vdev; /* top-level vdev */
259 	uint64_t is_target_offset; /* offset on is_vdev */
260 	uint64_t is_size;
261 	int is_children; /* number of entries in is_child[] */
262 	int is_unique_children; /* number of entries in is_unique_child */
263 	list_t is_unique_child;
264 
265 	/*
266 	 * is_good_child is the child that we are currently using to
267 	 * attempt reconstruction.
268 	 */
269 	indirect_child_t *is_good_child;
270 
271 	indirect_child_t is_child[];
272 } indirect_split_t;
273 
274 /*
275  * The indirect_vsd_t is associated with each i/o to the indirect vdev.
276  * It is the "Vdev-Specific Data" in the zio_t's io_vsd.
277  */
278 typedef struct indirect_vsd {
279 	boolean_t iv_split_block;
280 	boolean_t iv_reconstruct;
281 	uint64_t iv_unique_combinations;
282 	uint64_t iv_attempts;
283 	uint64_t iv_attempts_max;
284 
285 	list_t iv_splits; /* list of indirect_split_t's */
286 } indirect_vsd_t;
287 
288 static void
vdev_indirect_map_free(zio_t * zio)289 vdev_indirect_map_free(zio_t *zio)
290 {
291 	indirect_vsd_t *iv = zio->io_vsd;
292 
293 	indirect_split_t *is;
294 	while ((is = list_remove_head(&iv->iv_splits)) != NULL) {
295 		for (int c = 0; c < is->is_children; c++) {
296 			indirect_child_t *ic = &is->is_child[c];
297 			if (ic->ic_data != NULL)
298 				abd_free(ic->ic_data);
299 		}
300 
301 		indirect_child_t *ic;
302 		while ((ic = list_remove_head(&is->is_unique_child)) != NULL)
303 			;
304 
305 		list_destroy(&is->is_unique_child);
306 
307 		kmem_free(is,
308 		    offsetof(indirect_split_t, is_child[is->is_children]));
309 	}
310 	kmem_free(iv, sizeof (*iv));
311 }
312 
313 static const zio_vsd_ops_t vdev_indirect_vsd_ops = {
314 	.vsd_free = vdev_indirect_map_free,
315 };
316 
317 /*
318  * Mark the given offset and size as being obsolete.
319  */
320 void
vdev_indirect_mark_obsolete(vdev_t * vd,uint64_t offset,uint64_t size)321 vdev_indirect_mark_obsolete(vdev_t *vd, uint64_t offset, uint64_t size)
322 {
323 	spa_t *spa = vd->vdev_spa;
324 
325 	ASSERT3U(vd->vdev_indirect_config.vic_mapping_object, !=, 0);
326 	ASSERT(vd->vdev_removing || vd->vdev_ops == &vdev_indirect_ops);
327 	ASSERT(size > 0);
328 	VERIFY(vdev_indirect_mapping_entry_for_offset(
329 	    vd->vdev_indirect_mapping, offset) != NULL);
330 
331 	if (spa_feature_is_enabled(spa, SPA_FEATURE_OBSOLETE_COUNTS)) {
332 		mutex_enter(&vd->vdev_obsolete_lock);
333 		zfs_range_tree_add(vd->vdev_obsolete_segments, offset, size);
334 		mutex_exit(&vd->vdev_obsolete_lock);
335 		vdev_dirty(vd, 0, NULL, spa_syncing_txg(spa));
336 	}
337 }
338 
339 /*
340  * Mark the DVA vdev_id:offset:size as being obsolete in the given tx. This
341  * wrapper is provided because the DMU does not know about vdev_t's and
342  * cannot directly call vdev_indirect_mark_obsolete.
343  */
344 void
spa_vdev_indirect_mark_obsolete(spa_t * spa,uint64_t vdev_id,uint64_t offset,uint64_t size,dmu_tx_t * tx)345 spa_vdev_indirect_mark_obsolete(spa_t *spa, uint64_t vdev_id, uint64_t offset,
346     uint64_t size, dmu_tx_t *tx)
347 {
348 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
349 	ASSERT(dmu_tx_is_syncing(tx));
350 
351 	/* The DMU can only remap indirect vdevs. */
352 	ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
353 	vdev_indirect_mark_obsolete(vd, offset, size);
354 }
355 
356 static spa_condensing_indirect_t *
spa_condensing_indirect_create(spa_t * spa)357 spa_condensing_indirect_create(spa_t *spa)
358 {
359 	spa_condensing_indirect_phys_t *scip =
360 	    &spa->spa_condensing_indirect_phys;
361 	spa_condensing_indirect_t *sci = kmem_zalloc(sizeof (*sci), KM_SLEEP);
362 	objset_t *mos = spa->spa_meta_objset;
363 
364 	for (int i = 0; i < TXG_SIZE; i++) {
365 		list_create(&sci->sci_new_mapping_entries[i],
366 		    sizeof (vdev_indirect_mapping_entry_t),
367 		    offsetof(vdev_indirect_mapping_entry_t, vime_node));
368 	}
369 
370 	sci->sci_new_mapping =
371 	    vdev_indirect_mapping_open(mos, scip->scip_next_mapping_object);
372 
373 	return (sci);
374 }
375 
376 static void
spa_condensing_indirect_destroy(spa_condensing_indirect_t * sci)377 spa_condensing_indirect_destroy(spa_condensing_indirect_t *sci)
378 {
379 	for (int i = 0; i < TXG_SIZE; i++)
380 		list_destroy(&sci->sci_new_mapping_entries[i]);
381 
382 	if (sci->sci_new_mapping != NULL)
383 		vdev_indirect_mapping_close(sci->sci_new_mapping);
384 
385 	kmem_free(sci, sizeof (*sci));
386 }
387 
388 boolean_t
vdev_indirect_should_condense(vdev_t * vd)389 vdev_indirect_should_condense(vdev_t *vd)
390 {
391 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
392 	spa_t *spa = vd->vdev_spa;
393 
394 	ASSERT(dsl_pool_sync_context(spa->spa_dsl_pool));
395 
396 	if (!zfs_condense_indirect_vdevs_enable)
397 		return (B_FALSE);
398 
399 	/*
400 	 * We can only condense one indirect vdev at a time.
401 	 */
402 	if (spa->spa_condensing_indirect != NULL)
403 		return (B_FALSE);
404 
405 	if (spa_shutting_down(spa))
406 		return (B_FALSE);
407 
408 	/*
409 	 * The mapping object size must not change while we are
410 	 * condensing, so we can only condense indirect vdevs
411 	 * (not vdevs that are still in the middle of being removed).
412 	 */
413 	if (vd->vdev_ops != &vdev_indirect_ops)
414 		return (B_FALSE);
415 
416 	/*
417 	 * If nothing new has been marked obsolete, there is no
418 	 * point in condensing.
419 	 */
420 	uint64_t obsolete_sm_obj __maybe_unused;
421 	ASSERT0(vdev_obsolete_sm_object(vd, &obsolete_sm_obj));
422 	if (vd->vdev_obsolete_sm == NULL) {
423 		ASSERT0(obsolete_sm_obj);
424 		return (B_FALSE);
425 	}
426 
427 	ASSERT(vd->vdev_obsolete_sm != NULL);
428 
429 	ASSERT3U(obsolete_sm_obj, ==, space_map_object(vd->vdev_obsolete_sm));
430 
431 	uint64_t bytes_mapped = vdev_indirect_mapping_bytes_mapped(vim);
432 	uint64_t bytes_obsolete = space_map_allocated(vd->vdev_obsolete_sm);
433 	uint64_t mapping_size = vdev_indirect_mapping_size(vim);
434 	uint64_t obsolete_sm_size = space_map_length(vd->vdev_obsolete_sm);
435 
436 	ASSERT3U(bytes_obsolete, <=, bytes_mapped);
437 
438 	/*
439 	 * If a high percentage of the bytes that are mapped have become
440 	 * obsolete, condense (unless the mapping is already small enough).
441 	 * This has a good chance of reducing the amount of memory used
442 	 * by the mapping.
443 	 */
444 	if (bytes_obsolete * 100 / bytes_mapped >=
445 	    zfs_condense_indirect_obsolete_pct &&
446 	    mapping_size > zfs_condense_min_mapping_bytes) {
447 		zfs_dbgmsg("should condense vdev %llu because obsolete "
448 		    "spacemap covers %d%% of %lluMB mapping",
449 		    (u_longlong_t)vd->vdev_id,
450 		    (int)(bytes_obsolete * 100 / bytes_mapped),
451 		    (u_longlong_t)bytes_mapped / 1024 / 1024);
452 		return (B_TRUE);
453 	}
454 
455 	/*
456 	 * If the obsolete space map takes up too much space on disk,
457 	 * condense in order to free up this disk space.
458 	 */
459 	if (obsolete_sm_size >= zfs_condense_max_obsolete_bytes) {
460 		zfs_dbgmsg("should condense vdev %llu because obsolete sm "
461 		    "length %lluMB >= max size %lluMB",
462 		    (u_longlong_t)vd->vdev_id,
463 		    (u_longlong_t)obsolete_sm_size / 1024 / 1024,
464 		    (u_longlong_t)zfs_condense_max_obsolete_bytes /
465 		    1024 / 1024);
466 		return (B_TRUE);
467 	}
468 
469 	return (B_FALSE);
470 }
471 
472 /*
473  * This sync task completes (finishes) a condense, deleting the old
474  * mapping and replacing it with the new one.
475  */
476 static void
spa_condense_indirect_complete_sync(void * arg,dmu_tx_t * tx)477 spa_condense_indirect_complete_sync(void *arg, dmu_tx_t *tx)
478 {
479 	spa_condensing_indirect_t *sci = arg;
480 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
481 	spa_condensing_indirect_phys_t *scip =
482 	    &spa->spa_condensing_indirect_phys;
483 	vdev_t *vd = vdev_lookup_top(spa, scip->scip_vdev);
484 	vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
485 	objset_t *mos = spa->spa_meta_objset;
486 	vdev_indirect_mapping_t *old_mapping = vd->vdev_indirect_mapping;
487 	uint64_t old_count = vdev_indirect_mapping_num_entries(old_mapping);
488 	uint64_t new_count =
489 	    vdev_indirect_mapping_num_entries(sci->sci_new_mapping);
490 
491 	ASSERT(dmu_tx_is_syncing(tx));
492 	ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
493 	ASSERT3P(sci, ==, spa->spa_condensing_indirect);
494 	for (int i = 0; i < TXG_SIZE; i++) {
495 		ASSERT(list_is_empty(&sci->sci_new_mapping_entries[i]));
496 	}
497 	ASSERT(vic->vic_mapping_object != 0);
498 	ASSERT3U(vd->vdev_id, ==, scip->scip_vdev);
499 	ASSERT(scip->scip_next_mapping_object != 0);
500 	ASSERT(scip->scip_prev_obsolete_sm_object != 0);
501 
502 	/*
503 	 * Reset vdev_indirect_mapping to refer to the new object.
504 	 */
505 	rw_enter(&vd->vdev_indirect_rwlock, RW_WRITER);
506 	vdev_indirect_mapping_close(vd->vdev_indirect_mapping);
507 	vd->vdev_indirect_mapping = sci->sci_new_mapping;
508 	rw_exit(&vd->vdev_indirect_rwlock);
509 
510 	sci->sci_new_mapping = NULL;
511 	vdev_indirect_mapping_free(mos, vic->vic_mapping_object, tx);
512 	vic->vic_mapping_object = scip->scip_next_mapping_object;
513 	scip->scip_next_mapping_object = 0;
514 
515 	space_map_free_obj(mos, scip->scip_prev_obsolete_sm_object, tx);
516 	spa_feature_decr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
517 	scip->scip_prev_obsolete_sm_object = 0;
518 
519 	scip->scip_vdev = 0;
520 
521 	VERIFY0(zap_remove(mos, DMU_POOL_DIRECTORY_OBJECT,
522 	    DMU_POOL_CONDENSING_INDIRECT, tx));
523 	spa_condensing_indirect_destroy(spa->spa_condensing_indirect);
524 	spa->spa_condensing_indirect = NULL;
525 
526 	zfs_dbgmsg("finished condense of vdev %llu in txg %llu: "
527 	    "new mapping object %llu has %llu entries "
528 	    "(was %llu entries)",
529 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)dmu_tx_get_txg(tx),
530 	    (u_longlong_t)vic->vic_mapping_object,
531 	    (u_longlong_t)new_count, (u_longlong_t)old_count);
532 
533 	vdev_config_dirty(spa->spa_root_vdev);
534 }
535 
536 /*
537  * This sync task appends entries to the new mapping object.
538  */
539 static void
spa_condense_indirect_commit_sync(void * arg,dmu_tx_t * tx)540 spa_condense_indirect_commit_sync(void *arg, dmu_tx_t *tx)
541 {
542 	spa_condensing_indirect_t *sci = arg;
543 	uint64_t txg = dmu_tx_get_txg(tx);
544 	spa_t *spa __maybe_unused = dmu_tx_pool(tx)->dp_spa;
545 
546 	ASSERT(dmu_tx_is_syncing(tx));
547 	ASSERT3P(sci, ==, spa->spa_condensing_indirect);
548 
549 	vdev_indirect_mapping_add_entries(sci->sci_new_mapping,
550 	    &sci->sci_new_mapping_entries[txg & TXG_MASK], tx);
551 	ASSERT(list_is_empty(&sci->sci_new_mapping_entries[txg & TXG_MASK]));
552 }
553 
554 /*
555  * Open-context function to add one entry to the new mapping.  The new
556  * entry will be remembered and written from syncing context.
557  */
558 static void
spa_condense_indirect_commit_entry(spa_t * spa,vdev_indirect_mapping_entry_phys_t * vimep,uint32_t count)559 spa_condense_indirect_commit_entry(spa_t *spa,
560     vdev_indirect_mapping_entry_phys_t *vimep, uint32_t count)
561 {
562 	spa_condensing_indirect_t *sci = spa->spa_condensing_indirect;
563 
564 	ASSERT3U(count, <, DVA_GET_ASIZE(&vimep->vimep_dst));
565 
566 	dmu_tx_t *tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
567 	dmu_tx_hold_space(tx, sizeof (*vimep) + sizeof (count));
568 	VERIFY0(dmu_tx_assign(tx, DMU_TX_WAIT | DMU_TX_SUSPEND));
569 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
570 
571 	/*
572 	 * If we are the first entry committed this txg, kick off the sync
573 	 * task to write to the MOS on our behalf.
574 	 */
575 	if (list_is_empty(&sci->sci_new_mapping_entries[txgoff])) {
576 		dsl_sync_task_nowait(dmu_tx_pool(tx),
577 		    spa_condense_indirect_commit_sync, sci, tx);
578 	}
579 
580 	vdev_indirect_mapping_entry_t *vime =
581 	    kmem_alloc(sizeof (*vime), KM_SLEEP);
582 	vime->vime_mapping = *vimep;
583 	vime->vime_obsolete_count = count;
584 	list_insert_tail(&sci->sci_new_mapping_entries[txgoff], vime);
585 
586 	dmu_tx_commit(tx);
587 }
588 
589 static void
spa_condense_indirect_generate_new_mapping(vdev_t * vd,uint32_t * obsolete_counts,uint64_t start_index,zthr_t * zthr)590 spa_condense_indirect_generate_new_mapping(vdev_t *vd,
591     uint32_t *obsolete_counts, uint64_t start_index, zthr_t *zthr)
592 {
593 	spa_t *spa = vd->vdev_spa;
594 	uint64_t mapi = start_index;
595 	vdev_indirect_mapping_t *old_mapping = vd->vdev_indirect_mapping;
596 	uint64_t old_num_entries =
597 	    vdev_indirect_mapping_num_entries(old_mapping);
598 
599 	ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
600 	ASSERT3U(vd->vdev_id, ==, spa->spa_condensing_indirect_phys.scip_vdev);
601 
602 	zfs_dbgmsg("starting condense of vdev %llu from index %llu",
603 	    (u_longlong_t)vd->vdev_id,
604 	    (u_longlong_t)mapi);
605 
606 	while (mapi < old_num_entries) {
607 
608 		if (zthr_iscancelled(zthr)) {
609 			zfs_dbgmsg("pausing condense of vdev %llu "
610 			    "at index %llu", (u_longlong_t)vd->vdev_id,
611 			    (u_longlong_t)mapi);
612 			break;
613 		}
614 
615 		vdev_indirect_mapping_entry_phys_t *entry =
616 		    &old_mapping->vim_entries[mapi];
617 		uint64_t entry_size = DVA_GET_ASIZE(&entry->vimep_dst);
618 		ASSERT3U(obsolete_counts[mapi], <=, entry_size);
619 		if (obsolete_counts[mapi] < entry_size) {
620 			spa_condense_indirect_commit_entry(spa, entry,
621 			    obsolete_counts[mapi]);
622 
623 			/*
624 			 * This delay may be requested for testing, debugging,
625 			 * or performance reasons.
626 			 */
627 			hrtime_t now = gethrtime();
628 			hrtime_t sleep_until = now + MSEC2NSEC(
629 			    zfs_condense_indirect_commit_entry_delay_ms);
630 			zfs_sleep_until(sleep_until);
631 		}
632 
633 		mapi++;
634 	}
635 }
636 
637 static boolean_t
spa_condense_indirect_thread_check(void * arg,zthr_t * zthr)638 spa_condense_indirect_thread_check(void *arg, zthr_t *zthr)
639 {
640 	(void) zthr;
641 	spa_t *spa = arg;
642 
643 	return (spa->spa_condensing_indirect != NULL);
644 }
645 
646 static void
spa_condense_indirect_thread(void * arg,zthr_t * zthr)647 spa_condense_indirect_thread(void *arg, zthr_t *zthr)
648 {
649 	spa_t *spa = arg;
650 	vdev_t *vd;
651 
652 	ASSERT3P(spa->spa_condensing_indirect, !=, NULL);
653 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
654 	vd = vdev_lookup_top(spa, spa->spa_condensing_indirect_phys.scip_vdev);
655 	ASSERT3P(vd, !=, NULL);
656 	spa_config_exit(spa, SCL_VDEV, FTAG);
657 
658 	spa_condensing_indirect_t *sci = spa->spa_condensing_indirect;
659 	spa_condensing_indirect_phys_t *scip =
660 	    &spa->spa_condensing_indirect_phys;
661 	uint32_t *counts;
662 	uint64_t start_index;
663 	vdev_indirect_mapping_t *old_mapping = vd->vdev_indirect_mapping;
664 	space_map_t *prev_obsolete_sm = NULL;
665 
666 	ASSERT3U(vd->vdev_id, ==, scip->scip_vdev);
667 	ASSERT(scip->scip_next_mapping_object != 0);
668 	ASSERT(scip->scip_prev_obsolete_sm_object != 0);
669 	ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
670 
671 	for (int i = 0; i < TXG_SIZE; i++) {
672 		/*
673 		 * The list must start out empty in order for the
674 		 * _commit_sync() sync task to be properly registered
675 		 * on the first call to _commit_entry(); so it's wise
676 		 * to double check and ensure we actually are starting
677 		 * with empty lists.
678 		 */
679 		ASSERT(list_is_empty(&sci->sci_new_mapping_entries[i]));
680 	}
681 
682 	VERIFY0(space_map_open(&prev_obsolete_sm, spa->spa_meta_objset,
683 	    scip->scip_prev_obsolete_sm_object, 0, vd->vdev_asize, 0));
684 	counts = vdev_indirect_mapping_load_obsolete_counts(old_mapping);
685 	if (prev_obsolete_sm != NULL) {
686 		vdev_indirect_mapping_load_obsolete_spacemap(old_mapping,
687 		    counts, prev_obsolete_sm);
688 	}
689 	space_map_close(prev_obsolete_sm);
690 
691 	/*
692 	 * Generate new mapping.  Determine what index to continue from
693 	 * based on the max offset that we've already written in the
694 	 * new mapping.
695 	 */
696 	uint64_t max_offset =
697 	    vdev_indirect_mapping_max_offset(sci->sci_new_mapping);
698 	if (max_offset == 0) {
699 		/* We haven't written anything to the new mapping yet. */
700 		start_index = 0;
701 	} else {
702 		/*
703 		 * Pick up from where we left off. _entry_for_offset()
704 		 * returns a pointer into the vim_entries array. If
705 		 * max_offset is greater than any of the mappings
706 		 * contained in the table  NULL will be returned and
707 		 * that indicates we've exhausted our iteration of the
708 		 * old_mapping.
709 		 */
710 
711 		vdev_indirect_mapping_entry_phys_t *entry =
712 		    vdev_indirect_mapping_entry_for_offset_or_next(old_mapping,
713 		    max_offset);
714 
715 		if (entry == NULL) {
716 			/*
717 			 * We've already written the whole new mapping.
718 			 * This special value will cause us to skip the
719 			 * generate_new_mapping step and just do the sync
720 			 * task to complete the condense.
721 			 */
722 			start_index = UINT64_MAX;
723 		} else {
724 			start_index = entry - old_mapping->vim_entries;
725 			ASSERT3U(start_index, <,
726 			    vdev_indirect_mapping_num_entries(old_mapping));
727 		}
728 	}
729 
730 	spa_condense_indirect_generate_new_mapping(vd, counts,
731 	    start_index, zthr);
732 
733 	vdev_indirect_mapping_free_obsolete_counts(old_mapping, counts);
734 
735 	/*
736 	 * If the zthr has received a cancellation signal while running
737 	 * in generate_new_mapping() or at any point after that, then bail
738 	 * early. We don't want to complete the condense if the spa is
739 	 * shutting down.
740 	 */
741 	if (zthr_iscancelled(zthr))
742 		return;
743 
744 	VERIFY0(dsl_sync_task(spa_name(spa), NULL,
745 	    spa_condense_indirect_complete_sync, sci, 0,
746 	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
747 }
748 
749 /*
750  * Sync task to begin the condensing process.
751  */
752 void
spa_condense_indirect_start_sync(vdev_t * vd,dmu_tx_t * tx)753 spa_condense_indirect_start_sync(vdev_t *vd, dmu_tx_t *tx)
754 {
755 	spa_t *spa = vd->vdev_spa;
756 	spa_condensing_indirect_phys_t *scip =
757 	    &spa->spa_condensing_indirect_phys;
758 
759 	ASSERT0(scip->scip_next_mapping_object);
760 	ASSERT0(scip->scip_prev_obsolete_sm_object);
761 	ASSERT0(scip->scip_vdev);
762 	ASSERT(dmu_tx_is_syncing(tx));
763 	ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
764 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_OBSOLETE_COUNTS));
765 	ASSERT(vdev_indirect_mapping_num_entries(vd->vdev_indirect_mapping));
766 
767 	uint64_t obsolete_sm_obj;
768 	VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_obj));
769 	ASSERT3U(obsolete_sm_obj, !=, 0);
770 
771 	scip->scip_vdev = vd->vdev_id;
772 	scip->scip_next_mapping_object =
773 	    vdev_indirect_mapping_alloc(spa->spa_meta_objset, tx);
774 
775 	scip->scip_prev_obsolete_sm_object = obsolete_sm_obj;
776 
777 	/*
778 	 * We don't need to allocate a new space map object, since
779 	 * vdev_indirect_sync_obsolete will allocate one when needed.
780 	 */
781 	space_map_close(vd->vdev_obsolete_sm);
782 	vd->vdev_obsolete_sm = NULL;
783 	VERIFY0(zap_remove(spa->spa_meta_objset, vd->vdev_top_zap,
784 	    VDEV_TOP_ZAP_INDIRECT_OBSOLETE_SM, tx));
785 
786 	VERIFY0(zap_add(spa->spa_dsl_pool->dp_meta_objset,
787 	    DMU_POOL_DIRECTORY_OBJECT,
788 	    DMU_POOL_CONDENSING_INDIRECT, sizeof (uint64_t),
789 	    sizeof (*scip) / sizeof (uint64_t), scip, tx));
790 
791 	ASSERT0P(spa->spa_condensing_indirect);
792 	spa->spa_condensing_indirect = spa_condensing_indirect_create(spa);
793 
794 	zfs_dbgmsg("starting condense of vdev %llu in txg %llu: "
795 	    "posm=%llu nm=%llu",
796 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)dmu_tx_get_txg(tx),
797 	    (u_longlong_t)scip->scip_prev_obsolete_sm_object,
798 	    (u_longlong_t)scip->scip_next_mapping_object);
799 
800 	zthr_wakeup(spa->spa_condense_zthr);
801 }
802 
803 /*
804  * Sync to the given vdev's obsolete space map any segments that are no longer
805  * referenced as of the given txg.
806  *
807  * If the obsolete space map doesn't exist yet, create and open it.
808  */
809 void
vdev_indirect_sync_obsolete(vdev_t * vd,dmu_tx_t * tx)810 vdev_indirect_sync_obsolete(vdev_t *vd, dmu_tx_t *tx)
811 {
812 	spa_t *spa = vd->vdev_spa;
813 	vdev_indirect_config_t *vic __maybe_unused = &vd->vdev_indirect_config;
814 
815 	ASSERT3U(vic->vic_mapping_object, !=, 0);
816 	ASSERT(zfs_range_tree_space(vd->vdev_obsolete_segments) > 0);
817 	ASSERT(vd->vdev_removing || vd->vdev_ops == &vdev_indirect_ops);
818 	ASSERT(spa_feature_is_enabled(spa, SPA_FEATURE_OBSOLETE_COUNTS));
819 
820 	uint64_t obsolete_sm_object;
821 	VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
822 	if (obsolete_sm_object == 0) {
823 		obsolete_sm_object = space_map_alloc(spa->spa_meta_objset,
824 		    zfs_vdev_standard_sm_blksz, tx);
825 
826 		ASSERT(vd->vdev_top_zap != 0);
827 		VERIFY0(zap_add(vd->vdev_spa->spa_meta_objset, vd->vdev_top_zap,
828 		    VDEV_TOP_ZAP_INDIRECT_OBSOLETE_SM,
829 		    sizeof (obsolete_sm_object), 1, &obsolete_sm_object, tx));
830 		ASSERT0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
831 		ASSERT3U(obsolete_sm_object, !=, 0);
832 
833 		spa_feature_incr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
834 		VERIFY0(space_map_open(&vd->vdev_obsolete_sm,
835 		    spa->spa_meta_objset, obsolete_sm_object,
836 		    0, vd->vdev_asize, 0));
837 	}
838 
839 	ASSERT(vd->vdev_obsolete_sm != NULL);
840 	ASSERT3U(obsolete_sm_object, ==,
841 	    space_map_object(vd->vdev_obsolete_sm));
842 
843 	space_map_write(vd->vdev_obsolete_sm,
844 	    vd->vdev_obsolete_segments, SM_ALLOC, SM_NO_VDEVID, tx);
845 	zfs_range_tree_vacate(vd->vdev_obsolete_segments, NULL, NULL);
846 }
847 
848 int
spa_condense_init(spa_t * spa)849 spa_condense_init(spa_t *spa)
850 {
851 	int error = zap_lookup(spa->spa_meta_objset,
852 	    DMU_POOL_DIRECTORY_OBJECT,
853 	    DMU_POOL_CONDENSING_INDIRECT, sizeof (uint64_t),
854 	    sizeof (spa->spa_condensing_indirect_phys) / sizeof (uint64_t),
855 	    &spa->spa_condensing_indirect_phys);
856 	if (error == 0) {
857 		if (spa_writeable(spa)) {
858 			spa->spa_condensing_indirect =
859 			    spa_condensing_indirect_create(spa);
860 		}
861 		return (0);
862 	} else if (error == ENOENT) {
863 		return (0);
864 	} else {
865 		return (error);
866 	}
867 }
868 
869 void
spa_condense_fini(spa_t * spa)870 spa_condense_fini(spa_t *spa)
871 {
872 	if (spa->spa_condensing_indirect != NULL) {
873 		spa_condensing_indirect_destroy(spa->spa_condensing_indirect);
874 		spa->spa_condensing_indirect = NULL;
875 	}
876 }
877 
878 void
spa_start_indirect_condensing_thread(spa_t * spa)879 spa_start_indirect_condensing_thread(spa_t *spa)
880 {
881 	ASSERT0P(spa->spa_condense_zthr);
882 	spa->spa_condense_zthr = zthr_create("z_indirect_condense",
883 	    spa_condense_indirect_thread_check,
884 	    spa_condense_indirect_thread, spa, minclsyspri);
885 }
886 
887 /*
888  * Gets the obsolete spacemap object from the vdev's ZAP.  On success sm_obj
889  * will contain either the obsolete spacemap object or zero if none exists.
890  * All other errors are returned to the caller.
891  */
892 int
vdev_obsolete_sm_object(vdev_t * vd,uint64_t * sm_obj)893 vdev_obsolete_sm_object(vdev_t *vd, uint64_t *sm_obj)
894 {
895 	ASSERT0(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER));
896 
897 	if (vd->vdev_top_zap == 0) {
898 		*sm_obj = 0;
899 		return (0);
900 	}
901 
902 	int error = zap_lookup(vd->vdev_spa->spa_meta_objset, vd->vdev_top_zap,
903 	    VDEV_TOP_ZAP_INDIRECT_OBSOLETE_SM, sizeof (uint64_t), 1, sm_obj);
904 	if (error == ENOENT) {
905 		*sm_obj = 0;
906 		error = 0;
907 	}
908 
909 	return (error);
910 }
911 
912 /*
913  * Gets the obsolete count are precise spacemap object from the vdev's ZAP.
914  * On success are_precise will be set to reflect if the counts are precise.
915  * All other errors are returned to the caller.
916  */
917 int
vdev_obsolete_counts_are_precise(vdev_t * vd,boolean_t * are_precise)918 vdev_obsolete_counts_are_precise(vdev_t *vd, boolean_t *are_precise)
919 {
920 	ASSERT0(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER));
921 
922 	if (vd->vdev_top_zap == 0) {
923 		*are_precise = B_FALSE;
924 		return (0);
925 	}
926 
927 	uint64_t val = 0;
928 	int error = zap_lookup(vd->vdev_spa->spa_meta_objset, vd->vdev_top_zap,
929 	    VDEV_TOP_ZAP_OBSOLETE_COUNTS_ARE_PRECISE, sizeof (val), 1, &val);
930 	if (error == 0) {
931 		*are_precise = (val != 0);
932 	} else if (error == ENOENT) {
933 		*are_precise = B_FALSE;
934 		error = 0;
935 	}
936 
937 	return (error);
938 }
939 
940 static void
vdev_indirect_close(vdev_t * vd)941 vdev_indirect_close(vdev_t *vd)
942 {
943 	(void) vd;
944 }
945 
946 static int
vdev_indirect_open(vdev_t * vd,uint64_t * psize,uint64_t * max_psize,uint64_t * logical_ashift,uint64_t * physical_ashift,cred_t * cr)947 vdev_indirect_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize,
948     uint64_t *logical_ashift, uint64_t *physical_ashift, cred_t *cr)
949 {
950 	(void) cr;
951 	*psize = *max_psize = vd->vdev_asize +
952 	    VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE;
953 	*logical_ashift = vd->vdev_ashift;
954 	*physical_ashift = vd->vdev_physical_ashift;
955 	return (0);
956 }
957 
958 typedef struct remap_segment {
959 	vdev_t *rs_vd;
960 	uint64_t rs_offset;
961 	uint64_t rs_asize;
962 	uint64_t rs_split_offset;
963 	list_node_t rs_node;
964 } remap_segment_t;
965 
966 static remap_segment_t *
rs_alloc(vdev_t * vd,uint64_t offset,uint64_t asize,uint64_t split_offset)967 rs_alloc(vdev_t *vd, uint64_t offset, uint64_t asize, uint64_t split_offset)
968 {
969 	remap_segment_t *rs = kmem_alloc(sizeof (remap_segment_t), KM_SLEEP);
970 	rs->rs_vd = vd;
971 	rs->rs_offset = offset;
972 	rs->rs_asize = asize;
973 	rs->rs_split_offset = split_offset;
974 	return (rs);
975 }
976 
977 /*
978  * Given an indirect vdev and an extent on that vdev, it duplicates the
979  * physical entries of the indirect mapping that correspond to the extent
980  * to a new array and returns a pointer to it. In addition, copied_entries
981  * is populated with the number of mapping entries that were duplicated.
982  *
983  * Note that the function assumes that the caller holds vdev_indirect_rwlock.
984  * This ensures that the mapping won't change due to condensing as we
985  * copy over its contents.
986  *
987  * Finally, since we are doing an allocation, it is up to the caller to
988  * free the array allocated in this function.
989  */
990 static vdev_indirect_mapping_entry_phys_t *
vdev_indirect_mapping_duplicate_adjacent_entries(vdev_t * vd,uint64_t offset,uint64_t asize,uint64_t * copied_entries)991 vdev_indirect_mapping_duplicate_adjacent_entries(vdev_t *vd, uint64_t offset,
992     uint64_t asize, uint64_t *copied_entries)
993 {
994 	vdev_indirect_mapping_entry_phys_t *duplicate_mappings = NULL;
995 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
996 	uint64_t entries = 0;
997 
998 	ASSERT(RW_READ_HELD(&vd->vdev_indirect_rwlock));
999 
1000 	vdev_indirect_mapping_entry_phys_t *first_mapping =
1001 	    vdev_indirect_mapping_entry_for_offset(vim, offset);
1002 	ASSERT3P(first_mapping, !=, NULL);
1003 
1004 	vdev_indirect_mapping_entry_phys_t *m = first_mapping;
1005 	while (asize > 0) {
1006 		uint64_t size = DVA_GET_ASIZE(&m->vimep_dst);
1007 
1008 		ASSERT3U(offset, >=, DVA_MAPPING_GET_SRC_OFFSET(m));
1009 		ASSERT3U(offset, <, DVA_MAPPING_GET_SRC_OFFSET(m) + size);
1010 
1011 		uint64_t inner_offset = offset - DVA_MAPPING_GET_SRC_OFFSET(m);
1012 		uint64_t inner_size = MIN(asize, size - inner_offset);
1013 
1014 		offset += inner_size;
1015 		asize -= inner_size;
1016 		entries++;
1017 		m++;
1018 	}
1019 
1020 	size_t copy_length = entries * sizeof (*first_mapping);
1021 	duplicate_mappings = kmem_alloc(copy_length, KM_SLEEP);
1022 	memcpy(duplicate_mappings, first_mapping, copy_length);
1023 	*copied_entries = entries;
1024 
1025 	return (duplicate_mappings);
1026 }
1027 
1028 /*
1029  * Goes through the relevant indirect mappings until it hits a concrete vdev
1030  * and issues the callback. On the way to the concrete vdev, if any other
1031  * indirect vdevs are encountered, then the callback will also be called on
1032  * each of those indirect vdevs. For example, if the segment is mapped to
1033  * segment A on indirect vdev 1, and then segment A on indirect vdev 1 is
1034  * mapped to segment B on concrete vdev 2, then the callback will be called on
1035  * both vdev 1 and vdev 2.
1036  *
1037  * While the callback passed to vdev_indirect_remap() is called on every vdev
1038  * the function encounters, certain callbacks only care about concrete vdevs.
1039  * These types of callbacks should return immediately and explicitly when they
1040  * are called on an indirect vdev.
1041  *
1042  * Because there is a possibility that a DVA section in the indirect device
1043  * has been split into multiple sections in our mapping, we keep track
1044  * of the relevant contiguous segments of the new location (remap_segment_t)
1045  * in a stack. This way we can call the callback for each of the new sections
1046  * created by a single section of the indirect device. Note though, that in
1047  * this scenario the callbacks in each split block won't occur in-order in
1048  * terms of offset, so callers should not make any assumptions about that.
1049  *
1050  * For callbacks that don't handle split blocks and immediately return when
1051  * they encounter them (as is the case for remap_blkptr_cb), the caller can
1052  * assume that its callback will be applied from the first indirect vdev
1053  * encountered to the last one and then the concrete vdev, in that order.
1054  */
1055 static void
vdev_indirect_remap(vdev_t * vd,uint64_t offset,uint64_t asize,void (* func)(uint64_t,vdev_t *,uint64_t,uint64_t,void *),void * arg)1056 vdev_indirect_remap(vdev_t *vd, uint64_t offset, uint64_t asize,
1057     void (*func)(uint64_t, vdev_t *, uint64_t, uint64_t, void *), void *arg)
1058 {
1059 	list_t stack;
1060 	spa_t *spa = vd->vdev_spa;
1061 
1062 	list_create(&stack, sizeof (remap_segment_t),
1063 	    offsetof(remap_segment_t, rs_node));
1064 
1065 	for (remap_segment_t *rs = rs_alloc(vd, offset, asize, 0);
1066 	    rs != NULL; rs = list_remove_head(&stack)) {
1067 		vdev_t *v = rs->rs_vd;
1068 		uint64_t num_entries = 0;
1069 
1070 		ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1071 		ASSERT(rs->rs_asize > 0);
1072 
1073 		/*
1074 		 * Note: As this function can be called from open context
1075 		 * (e.g. zio_read()), we need the following rwlock to
1076 		 * prevent the mapping from being changed by condensing.
1077 		 *
1078 		 * So we grab the lock and we make a copy of the entries
1079 		 * that are relevant to the extent that we are working on.
1080 		 * Once that is done, we drop the lock and iterate over
1081 		 * our copy of the mapping. Once we are done with the with
1082 		 * the remap segment and we free it, we also free our copy
1083 		 * of the indirect mapping entries that are relevant to it.
1084 		 *
1085 		 * This way we don't need to wait until the function is
1086 		 * finished with a segment, to condense it. In addition, we
1087 		 * don't need a recursive rwlock for the case that a call to
1088 		 * vdev_indirect_remap() needs to call itself (through the
1089 		 * codepath of its callback) for the same vdev in the middle
1090 		 * of its execution.
1091 		 */
1092 		rw_enter(&v->vdev_indirect_rwlock, RW_READER);
1093 		ASSERT3P(v->vdev_indirect_mapping, !=, NULL);
1094 
1095 		vdev_indirect_mapping_entry_phys_t *mapping =
1096 		    vdev_indirect_mapping_duplicate_adjacent_entries(v,
1097 		    rs->rs_offset, rs->rs_asize, &num_entries);
1098 		ASSERT3P(mapping, !=, NULL);
1099 		ASSERT3U(num_entries, >, 0);
1100 		rw_exit(&v->vdev_indirect_rwlock);
1101 
1102 		for (uint64_t i = 0; i < num_entries; i++) {
1103 			/*
1104 			 * Note: the vdev_indirect_mapping can not change
1105 			 * while we are running.  It only changes while the
1106 			 * removal is in progress, and then only from syncing
1107 			 * context. While a removal is in progress, this
1108 			 * function is only called for frees, which also only
1109 			 * happen from syncing context.
1110 			 */
1111 			vdev_indirect_mapping_entry_phys_t *m = &mapping[i];
1112 
1113 			ASSERT3P(m, !=, NULL);
1114 			ASSERT3U(rs->rs_asize, >, 0);
1115 
1116 			uint64_t size = DVA_GET_ASIZE(&m->vimep_dst);
1117 			uint64_t dst_offset = DVA_GET_OFFSET(&m->vimep_dst);
1118 			uint64_t dst_vdev = DVA_GET_VDEV(&m->vimep_dst);
1119 
1120 			ASSERT3U(rs->rs_offset, >=,
1121 			    DVA_MAPPING_GET_SRC_OFFSET(m));
1122 			ASSERT3U(rs->rs_offset, <,
1123 			    DVA_MAPPING_GET_SRC_OFFSET(m) + size);
1124 			ASSERT3U(dst_vdev, !=, v->vdev_id);
1125 
1126 			uint64_t inner_offset = rs->rs_offset -
1127 			    DVA_MAPPING_GET_SRC_OFFSET(m);
1128 			uint64_t inner_size =
1129 			    MIN(rs->rs_asize, size - inner_offset);
1130 
1131 			vdev_t *dst_v = vdev_lookup_top(spa, dst_vdev);
1132 			ASSERT3P(dst_v, !=, NULL);
1133 
1134 			if (dst_v->vdev_ops == &vdev_indirect_ops) {
1135 				list_insert_head(&stack,
1136 				    rs_alloc(dst_v, dst_offset + inner_offset,
1137 				    inner_size, rs->rs_split_offset));
1138 
1139 			}
1140 
1141 			if ((zfs_flags & ZFS_DEBUG_INDIRECT_REMAP) &&
1142 			    IS_P2ALIGNED(inner_size, 2 * SPA_MINBLOCKSIZE)) {
1143 				/*
1144 				 * Note: This clause exists only solely for
1145 				 * testing purposes. We use it to ensure that
1146 				 * split blocks work and that the callbacks
1147 				 * using them yield the same result if issued
1148 				 * in reverse order.
1149 				 */
1150 				uint64_t inner_half = inner_size / 2;
1151 
1152 				func(rs->rs_split_offset + inner_half, dst_v,
1153 				    dst_offset + inner_offset + inner_half,
1154 				    inner_half, arg);
1155 
1156 				func(rs->rs_split_offset, dst_v,
1157 				    dst_offset + inner_offset,
1158 				    inner_half, arg);
1159 			} else {
1160 				func(rs->rs_split_offset, dst_v,
1161 				    dst_offset + inner_offset,
1162 				    inner_size, arg);
1163 			}
1164 
1165 			rs->rs_offset += inner_size;
1166 			rs->rs_asize -= inner_size;
1167 			rs->rs_split_offset += inner_size;
1168 		}
1169 		VERIFY0(rs->rs_asize);
1170 
1171 		kmem_free(mapping, num_entries * sizeof (*mapping));
1172 		kmem_free(rs, sizeof (remap_segment_t));
1173 	}
1174 	list_destroy(&stack);
1175 }
1176 
1177 static void
vdev_indirect_child_io_done(zio_t * zio)1178 vdev_indirect_child_io_done(zio_t *zio)
1179 {
1180 	zio_t *pio = zio->io_private;
1181 
1182 	mutex_enter(&pio->io_lock);
1183 	pio->io_error = zio_worst_error(pio->io_error, zio->io_error);
1184 	mutex_exit(&pio->io_lock);
1185 
1186 	abd_free(zio->io_abd);
1187 }
1188 
1189 /*
1190  * This is a callback for vdev_indirect_remap() which allocates an
1191  * indirect_split_t for each split segment and adds it to iv_splits.
1192  */
1193 static void
vdev_indirect_gather_splits(uint64_t split_offset,vdev_t * vd,uint64_t offset,uint64_t size,void * arg)1194 vdev_indirect_gather_splits(uint64_t split_offset, vdev_t *vd, uint64_t offset,
1195     uint64_t size, void *arg)
1196 {
1197 	zio_t *zio = arg;
1198 	indirect_vsd_t *iv = zio->io_vsd;
1199 
1200 	ASSERT3P(vd, !=, NULL);
1201 
1202 	if (vd->vdev_ops == &vdev_indirect_ops)
1203 		return;
1204 
1205 	int n = 1;
1206 	if (vd->vdev_ops == &vdev_mirror_ops)
1207 		n = vd->vdev_children;
1208 
1209 	indirect_split_t *is =
1210 	    kmem_zalloc(offsetof(indirect_split_t, is_child[n]), KM_SLEEP);
1211 
1212 	is->is_children = n;
1213 	is->is_size = size;
1214 	is->is_split_offset = split_offset;
1215 	is->is_target_offset = offset;
1216 	is->is_vdev = vd;
1217 	list_create(&is->is_unique_child, sizeof (indirect_child_t),
1218 	    offsetof(indirect_child_t, ic_node));
1219 
1220 	/*
1221 	 * Note that we only consider multiple copies of the data for
1222 	 * *mirror* vdevs.  We don't for "replacing" or "spare" vdevs, even
1223 	 * though they use the same ops as mirror, because there's only one
1224 	 * "good" copy under the replacing/spare.
1225 	 */
1226 	if (vd->vdev_ops == &vdev_mirror_ops) {
1227 		for (int i = 0; i < n; i++) {
1228 			is->is_child[i].ic_vdev = vd->vdev_child[i];
1229 			list_link_init(&is->is_child[i].ic_node);
1230 		}
1231 	} else {
1232 		is->is_child[0].ic_vdev = vd;
1233 	}
1234 
1235 	list_insert_tail(&iv->iv_splits, is);
1236 }
1237 
1238 static void
vdev_indirect_read_split_done(zio_t * zio)1239 vdev_indirect_read_split_done(zio_t *zio)
1240 {
1241 	indirect_child_t *ic = zio->io_private;
1242 
1243 	if (zio->io_error != 0) {
1244 		/*
1245 		 * Clear ic_data to indicate that we do not have data for this
1246 		 * child.
1247 		 */
1248 		abd_free(ic->ic_data);
1249 		ic->ic_data = NULL;
1250 	}
1251 }
1252 
1253 /*
1254  * Issue reads for all copies (mirror children) of all splits.
1255  */
1256 static void
vdev_indirect_read_all(zio_t * zio)1257 vdev_indirect_read_all(zio_t *zio)
1258 {
1259 	indirect_vsd_t *iv = zio->io_vsd;
1260 
1261 	ASSERT3U(zio->io_type, ==, ZIO_TYPE_READ);
1262 
1263 	for (indirect_split_t *is = list_head(&iv->iv_splits);
1264 	    is != NULL; is = list_next(&iv->iv_splits, is)) {
1265 		for (int i = 0; i < is->is_children; i++) {
1266 			indirect_child_t *ic = &is->is_child[i];
1267 
1268 			if (!vdev_readable(ic->ic_vdev))
1269 				continue;
1270 
1271 			/*
1272 			 * If a child is missing the data, set ic_error. Used
1273 			 * in vdev_indirect_repair(). We perform the read
1274 			 * nevertheless which provides the opportunity to
1275 			 * reconstruct the split block if at all possible.
1276 			 */
1277 			if (vdev_dtl_contains(ic->ic_vdev, DTL_MISSING,
1278 			    zio->io_txg, 1))
1279 				ic->ic_error = SET_ERROR(ESTALE);
1280 
1281 			ic->ic_data = abd_alloc_sametype(zio->io_abd,
1282 			    is->is_size);
1283 			ic->ic_duplicate = NULL;
1284 
1285 			zio_nowait(zio_vdev_child_io(zio, NULL,
1286 			    ic->ic_vdev, is->is_target_offset, ic->ic_data,
1287 			    is->is_size, zio->io_type, zio->io_priority, 0,
1288 			    vdev_indirect_read_split_done, ic));
1289 		}
1290 	}
1291 	iv->iv_reconstruct = B_TRUE;
1292 }
1293 
1294 static void
vdev_indirect_io_start(zio_t * zio)1295 vdev_indirect_io_start(zio_t *zio)
1296 {
1297 	spa_t *spa __maybe_unused = zio->io_spa;
1298 	indirect_vsd_t *iv = kmem_zalloc(sizeof (*iv), KM_SLEEP);
1299 	list_create(&iv->iv_splits,
1300 	    sizeof (indirect_split_t), offsetof(indirect_split_t, is_node));
1301 
1302 	zio->io_vsd = iv;
1303 	zio->io_vsd_ops = &vdev_indirect_vsd_ops;
1304 
1305 	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1306 	if (zio->io_type != ZIO_TYPE_READ) {
1307 		ASSERT3U(zio->io_type, ==, ZIO_TYPE_WRITE);
1308 		/*
1309 		 * Note: this code can handle other kinds of writes,
1310 		 * but we don't expect them.
1311 		 */
1312 		ASSERT((zio->io_flags & (ZIO_FLAG_SELF_HEAL |
1313 		    ZIO_FLAG_RESILVER | ZIO_FLAG_INDUCE_DAMAGE)) != 0);
1314 	}
1315 
1316 	vdev_indirect_remap(zio->io_vd, zio->io_offset, zio->io_size,
1317 	    vdev_indirect_gather_splits, zio);
1318 
1319 	indirect_split_t *first = list_head(&iv->iv_splits);
1320 	ASSERT3P(first, !=, NULL);
1321 	if (first->is_size == zio->io_size) {
1322 		/*
1323 		 * This is not a split block; we are pointing to the entire
1324 		 * data, which will checksum the same as the original data.
1325 		 * Pass the BP down so that the child i/o can verify the
1326 		 * checksum, and try a different location if available
1327 		 * (e.g. on a mirror).
1328 		 *
1329 		 * While this special case could be handled the same as the
1330 		 * general (split block) case, doing it this way ensures
1331 		 * that the vast majority of blocks on indirect vdevs
1332 		 * (which are not split) are handled identically to blocks
1333 		 * on non-indirect vdevs.  This allows us to be less strict
1334 		 * about performance in the general (but rare) case.
1335 		 */
1336 		ASSERT0(first->is_split_offset);
1337 		ASSERT3P(list_next(&iv->iv_splits, first), ==, NULL);
1338 		zio_nowait(zio_vdev_child_io(zio, zio->io_bp,
1339 		    first->is_vdev, first->is_target_offset,
1340 		    abd_get_offset(zio->io_abd, 0),
1341 		    zio->io_size, zio->io_type, zio->io_priority, 0,
1342 		    vdev_indirect_child_io_done, zio));
1343 	} else {
1344 		iv->iv_split_block = B_TRUE;
1345 		if (zio->io_type == ZIO_TYPE_READ &&
1346 		    zio->io_flags & (ZIO_FLAG_SCRUB | ZIO_FLAG_RESILVER)) {
1347 			/*
1348 			 * Read all copies.  Note that for simplicity,
1349 			 * we don't bother consulting the DTL in the
1350 			 * resilver case.
1351 			 */
1352 			vdev_indirect_read_all(zio);
1353 		} else {
1354 			/*
1355 			 * If this is a read zio, we read one copy of each
1356 			 * split segment, from the top-level vdev.  Since
1357 			 * we don't know the checksum of each split
1358 			 * individually, the child zio can't ensure that
1359 			 * we get the right data. E.g. if it's a mirror,
1360 			 * it will just read from a random (healthy) leaf
1361 			 * vdev. We have to verify the checksum in
1362 			 * vdev_indirect_io_done().
1363 			 *
1364 			 * For write zios, the vdev code will ensure we write
1365 			 * to all children.
1366 			 */
1367 			for (indirect_split_t *is = list_head(&iv->iv_splits);
1368 			    is != NULL; is = list_next(&iv->iv_splits, is)) {
1369 				zio_nowait(zio_vdev_child_io(zio, NULL,
1370 				    is->is_vdev, is->is_target_offset,
1371 				    abd_get_offset_size(zio->io_abd,
1372 				    is->is_split_offset, is->is_size),
1373 				    is->is_size, zio->io_type,
1374 				    zio->io_priority, 0,
1375 				    vdev_indirect_child_io_done, zio));
1376 			}
1377 
1378 		}
1379 	}
1380 
1381 	zio_execute(zio);
1382 }
1383 
1384 /*
1385  * Report a checksum error for a child.
1386  */
1387 static void
vdev_indirect_checksum_error(zio_t * zio,indirect_split_t * is,indirect_child_t * ic)1388 vdev_indirect_checksum_error(zio_t *zio,
1389     indirect_split_t *is, indirect_child_t *ic)
1390 {
1391 	vdev_t *vd = ic->ic_vdev;
1392 
1393 	if (zio->io_flags & ZIO_FLAG_SPECULATIVE)
1394 		return;
1395 
1396 	mutex_enter(&vd->vdev_stat_lock);
1397 	vd->vdev_stat.vs_checksum_errors++;
1398 	mutex_exit(&vd->vdev_stat_lock);
1399 
1400 	zio_bad_cksum_t zbc = { 0 };
1401 	abd_t *bad_abd = ic->ic_data;
1402 	abd_t *good_abd = is->is_good_child->ic_data;
1403 	(void) zfs_ereport_post_checksum(zio->io_spa, vd, NULL, zio,
1404 	    is->is_target_offset, is->is_size, good_abd, bad_abd, &zbc);
1405 }
1406 
1407 /*
1408  * Issue repair i/os for any incorrect copies.  We do this by comparing
1409  * each split segment's correct data (is_good_child's ic_data) with each
1410  * other copy of the data.  If they differ, then we overwrite the bad data
1411  * with the good copy.  The DTL is checked in vdev_indirect_read_all() and
1412  * if a vdev is missing a copy of the data we set ic_error and the read is
1413  * performed. This provides the opportunity to reconstruct the split block
1414  * if at all possible. ic_error is checked here and if set it suppresses
1415  * incrementing the checksum counter. Aside from this DTLs are not checked,
1416  * which simplifies this code and also issues the optimal number of writes
1417  * (based on which copies actually read bad data, as opposed to which we
1418  * think might be wrong).  For the same reason, we always use
1419  * ZIO_FLAG_SELF_HEAL, to bypass the DTL check in zio_vdev_io_start().
1420  */
1421 static void
vdev_indirect_repair(zio_t * zio)1422 vdev_indirect_repair(zio_t *zio)
1423 {
1424 	indirect_vsd_t *iv = zio->io_vsd;
1425 
1426 	if (!spa_writeable(zio->io_spa))
1427 		return;
1428 
1429 	for (indirect_split_t *is = list_head(&iv->iv_splits);
1430 	    is != NULL; is = list_next(&iv->iv_splits, is)) {
1431 		for (int c = 0; c < is->is_children; c++) {
1432 			indirect_child_t *ic = &is->is_child[c];
1433 			if (ic == is->is_good_child)
1434 				continue;
1435 			if (ic->ic_data == NULL)
1436 				continue;
1437 			if (ic->ic_duplicate == is->is_good_child)
1438 				continue;
1439 
1440 			zio_nowait(zio_vdev_child_io(zio, NULL,
1441 			    ic->ic_vdev, is->is_target_offset,
1442 			    is->is_good_child->ic_data, is->is_size,
1443 			    ZIO_TYPE_WRITE, ZIO_PRIORITY_ASYNC_WRITE,
1444 			    ZIO_FLAG_IO_REPAIR | ZIO_FLAG_SELF_HEAL,
1445 			    NULL, NULL));
1446 
1447 			/*
1448 			 * If ic_error is set the current child does not have
1449 			 * a copy of the data, so suppress incrementing the
1450 			 * checksum counter.
1451 			 */
1452 			if (ic->ic_error == ESTALE)
1453 				continue;
1454 
1455 			vdev_indirect_checksum_error(zio, is, ic);
1456 		}
1457 	}
1458 }
1459 
1460 /*
1461  * Report checksum errors on all children that we read from.
1462  */
1463 static void
vdev_indirect_all_checksum_errors(zio_t * zio)1464 vdev_indirect_all_checksum_errors(zio_t *zio)
1465 {
1466 	indirect_vsd_t *iv = zio->io_vsd;
1467 
1468 	if (zio->io_flags & ZIO_FLAG_SPECULATIVE)
1469 		return;
1470 
1471 	for (indirect_split_t *is = list_head(&iv->iv_splits);
1472 	    is != NULL; is = list_next(&iv->iv_splits, is)) {
1473 		for (int c = 0; c < is->is_children; c++) {
1474 			indirect_child_t *ic = &is->is_child[c];
1475 
1476 			if (ic->ic_data == NULL)
1477 				continue;
1478 
1479 			vdev_t *vd = ic->ic_vdev;
1480 
1481 			mutex_enter(&vd->vdev_stat_lock);
1482 			vd->vdev_stat.vs_checksum_errors++;
1483 			mutex_exit(&vd->vdev_stat_lock);
1484 			(void) zfs_ereport_post_checksum(zio->io_spa, vd,
1485 			    NULL, zio, is->is_target_offset, is->is_size,
1486 			    NULL, NULL, NULL);
1487 		}
1488 	}
1489 }
1490 
1491 /*
1492  * Copy data from all the splits to a main zio then validate the checksum.
1493  * If then checksum is successfully validated return success.
1494  */
1495 static int
vdev_indirect_splits_checksum_validate(indirect_vsd_t * iv,zio_t * zio)1496 vdev_indirect_splits_checksum_validate(indirect_vsd_t *iv, zio_t *zio)
1497 {
1498 	zio_bad_cksum_t zbc;
1499 
1500 	for (indirect_split_t *is = list_head(&iv->iv_splits);
1501 	    is != NULL; is = list_next(&iv->iv_splits, is)) {
1502 
1503 		ASSERT3P(is->is_good_child->ic_data, !=, NULL);
1504 		ASSERT0P(is->is_good_child->ic_duplicate);
1505 
1506 		abd_copy_off(zio->io_abd, is->is_good_child->ic_data,
1507 		    is->is_split_offset, 0, is->is_size);
1508 	}
1509 
1510 	return (zio_checksum_error(zio, &zbc));
1511 }
1512 
1513 /*
1514  * There are relatively few possible combinations making it feasible to
1515  * deterministically check them all.  We do this by setting the good_child
1516  * to the next unique split version.  If we reach the end of the list then
1517  * "carry over" to the next unique split version (like counting in base
1518  * is_unique_children, but each digit can have a different base).
1519  */
1520 static int
vdev_indirect_splits_enumerate_all(indirect_vsd_t * iv,zio_t * zio)1521 vdev_indirect_splits_enumerate_all(indirect_vsd_t *iv, zio_t *zio)
1522 {
1523 	boolean_t more = B_TRUE;
1524 
1525 	iv->iv_attempts = 0;
1526 
1527 	for (indirect_split_t *is = list_head(&iv->iv_splits);
1528 	    is != NULL; is = list_next(&iv->iv_splits, is))
1529 		is->is_good_child = list_head(&is->is_unique_child);
1530 
1531 	while (more == B_TRUE) {
1532 		iv->iv_attempts++;
1533 		more = B_FALSE;
1534 
1535 		if (vdev_indirect_splits_checksum_validate(iv, zio) == 0)
1536 			return (0);
1537 
1538 		for (indirect_split_t *is = list_head(&iv->iv_splits);
1539 		    is != NULL; is = list_next(&iv->iv_splits, is)) {
1540 			is->is_good_child = list_next(&is->is_unique_child,
1541 			    is->is_good_child);
1542 			if (is->is_good_child != NULL) {
1543 				more = B_TRUE;
1544 				break;
1545 			}
1546 
1547 			is->is_good_child = list_head(&is->is_unique_child);
1548 		}
1549 	}
1550 
1551 	ASSERT3S(iv->iv_attempts, <=, iv->iv_unique_combinations);
1552 
1553 	return (SET_ERROR(ECKSUM));
1554 }
1555 
1556 /*
1557  * There are too many combinations to try all of them in a reasonable amount
1558  * of time.  So try a fixed number of random combinations from the unique
1559  * split versions, after which we'll consider the block unrecoverable.
1560  */
1561 static int
vdev_indirect_splits_enumerate_randomly(indirect_vsd_t * iv,zio_t * zio)1562 vdev_indirect_splits_enumerate_randomly(indirect_vsd_t *iv, zio_t *zio)
1563 {
1564 	iv->iv_attempts = 0;
1565 
1566 	while (iv->iv_attempts < iv->iv_attempts_max) {
1567 		iv->iv_attempts++;
1568 
1569 		for (indirect_split_t *is = list_head(&iv->iv_splits);
1570 		    is != NULL; is = list_next(&iv->iv_splits, is)) {
1571 			indirect_child_t *ic = list_head(&is->is_unique_child);
1572 			int children = is->is_unique_children;
1573 
1574 			for (int i = random_in_range(children); i > 0; i--)
1575 				ic = list_next(&is->is_unique_child, ic);
1576 
1577 			ASSERT3P(ic, !=, NULL);
1578 			is->is_good_child = ic;
1579 		}
1580 
1581 		if (vdev_indirect_splits_checksum_validate(iv, zio) == 0)
1582 			return (0);
1583 	}
1584 
1585 	return (SET_ERROR(ECKSUM));
1586 }
1587 
1588 /*
1589  * This is a validation function for reconstruction.  It randomly selects
1590  * a good combination, if one can be found, and then it intentionally
1591  * damages all other segment copes by zeroing them.  This forces the
1592  * reconstruction algorithm to locate the one remaining known good copy.
1593  */
1594 static int
vdev_indirect_splits_damage(indirect_vsd_t * iv,zio_t * zio)1595 vdev_indirect_splits_damage(indirect_vsd_t *iv, zio_t *zio)
1596 {
1597 	int error;
1598 
1599 	/* Presume all the copies are unique for initial selection. */
1600 	for (indirect_split_t *is = list_head(&iv->iv_splits);
1601 	    is != NULL; is = list_next(&iv->iv_splits, is)) {
1602 		is->is_unique_children = 0;
1603 
1604 		for (int i = 0; i < is->is_children; i++) {
1605 			indirect_child_t *ic = &is->is_child[i];
1606 			if (ic->ic_data != NULL) {
1607 				is->is_unique_children++;
1608 				list_insert_tail(&is->is_unique_child, ic);
1609 			}
1610 		}
1611 
1612 		if (list_is_empty(&is->is_unique_child)) {
1613 			error = SET_ERROR(EIO);
1614 			goto out;
1615 		}
1616 	}
1617 
1618 	/*
1619 	 * Set each is_good_child to a randomly-selected child which
1620 	 * is known to contain validated data.
1621 	 */
1622 	error = vdev_indirect_splits_enumerate_randomly(iv, zio);
1623 	if (error)
1624 		goto out;
1625 
1626 	/*
1627 	 * Damage all but the known good copy by zeroing it.  This will
1628 	 * result in two or less unique copies per indirect_child_t.
1629 	 * Both may need to be checked in order to reconstruct the block.
1630 	 * Set iv->iv_attempts_max such that all unique combinations will
1631 	 * enumerated, but limit the damage to at most 12 indirect splits.
1632 	 */
1633 	iv->iv_attempts_max = 1;
1634 
1635 	for (indirect_split_t *is = list_head(&iv->iv_splits);
1636 	    is != NULL; is = list_next(&iv->iv_splits, is)) {
1637 		for (int c = 0; c < is->is_children; c++) {
1638 			indirect_child_t *ic = &is->is_child[c];
1639 
1640 			if (ic == is->is_good_child)
1641 				continue;
1642 			if (ic->ic_data == NULL)
1643 				continue;
1644 
1645 			abd_zero(ic->ic_data, abd_get_size(ic->ic_data));
1646 		}
1647 
1648 		iv->iv_attempts_max *= 2;
1649 		if (iv->iv_attempts_max >= (1ULL << 12)) {
1650 			iv->iv_attempts_max = UINT64_MAX;
1651 			break;
1652 		}
1653 	}
1654 
1655 out:
1656 	/* Empty the unique children lists so they can be reconstructed. */
1657 	for (indirect_split_t *is = list_head(&iv->iv_splits);
1658 	    is != NULL; is = list_next(&iv->iv_splits, is)) {
1659 		indirect_child_t *ic;
1660 		while ((ic = list_remove_head(&is->is_unique_child)) != NULL)
1661 			;
1662 
1663 		is->is_unique_children = 0;
1664 	}
1665 
1666 	return (error);
1667 }
1668 
1669 /*
1670  * This function is called when we have read all copies of the data and need
1671  * to try to find a combination of copies that gives us the right checksum.
1672  *
1673  * If we pointed to any mirror vdevs, this effectively does the job of the
1674  * mirror.  The mirror vdev code can't do its own job because we don't know
1675  * the checksum of each split segment individually.
1676  *
1677  * We have to try every unique combination of copies of split segments, until
1678  * we find one that checksums correctly.  Duplicate segment copies are first
1679  * identified and latter skipped during reconstruction.  This optimization
1680  * reduces the search space and ensures that of the remaining combinations
1681  * at most one is correct.
1682  *
1683  * When the total number of combinations is small they can all be checked.
1684  * For example, if we have 3 segments in the split, and each points to a
1685  * 2-way mirror with unique copies, we will have the following pieces of data:
1686  *
1687  *       |     mirror child
1688  * split |     [0]        [1]
1689  * ======|=====================
1690  *   A   |  data_A_0   data_A_1
1691  *   B   |  data_B_0   data_B_1
1692  *   C   |  data_C_0   data_C_1
1693  *
1694  * We will try the following (mirror children)^(number of splits) (2^3=8)
1695  * combinations, which is similar to bitwise-little-endian counting in
1696  * binary.  In general each "digit" corresponds to a split segment, and the
1697  * base of each digit is is_children, which can be different for each
1698  * digit.
1699  *
1700  * "low bit"        "high bit"
1701  *        v                 v
1702  * data_A_0 data_B_0 data_C_0
1703  * data_A_1 data_B_0 data_C_0
1704  * data_A_0 data_B_1 data_C_0
1705  * data_A_1 data_B_1 data_C_0
1706  * data_A_0 data_B_0 data_C_1
1707  * data_A_1 data_B_0 data_C_1
1708  * data_A_0 data_B_1 data_C_1
1709  * data_A_1 data_B_1 data_C_1
1710  *
1711  * Note that the split segments may be on the same or different top-level
1712  * vdevs. In either case, we may need to try lots of combinations (see
1713  * zfs_reconstruct_indirect_combinations_max).  This ensures that if a mirror
1714  * has small silent errors on all of its children, we can still reconstruct
1715  * the correct data, as long as those errors are at sufficiently-separated
1716  * offsets (specifically, separated by the largest block size - default of
1717  * 128KB, but up to 16MB).
1718  */
1719 static void
vdev_indirect_reconstruct_io_done(zio_t * zio)1720 vdev_indirect_reconstruct_io_done(zio_t *zio)
1721 {
1722 	indirect_vsd_t *iv = zio->io_vsd;
1723 	boolean_t known_good = B_FALSE;
1724 	int error;
1725 
1726 	iv->iv_unique_combinations = 1;
1727 	iv->iv_attempts_max = UINT64_MAX;
1728 
1729 	if (zfs_reconstruct_indirect_combinations_max > 0)
1730 		iv->iv_attempts_max = zfs_reconstruct_indirect_combinations_max;
1731 
1732 	/*
1733 	 * If nonzero, every 1/x blocks will be damaged, in order to validate
1734 	 * reconstruction when there are split segments with damaged copies.
1735 	 * Known_good will be TRUE when reconstruction is known to be possible.
1736 	 */
1737 	if (zfs_reconstruct_indirect_damage_fraction != 0 &&
1738 	    random_in_range(zfs_reconstruct_indirect_damage_fraction) == 0)
1739 		known_good = (vdev_indirect_splits_damage(iv, zio) == 0);
1740 
1741 	/*
1742 	 * Determine the unique children for a split segment and add them
1743 	 * to the is_unique_child list.  By restricting reconstruction
1744 	 * to these children, only unique combinations will be considered.
1745 	 * This can vastly reduce the search space when there are a large
1746 	 * number of indirect splits.
1747 	 */
1748 	for (indirect_split_t *is = list_head(&iv->iv_splits);
1749 	    is != NULL; is = list_next(&iv->iv_splits, is)) {
1750 		is->is_unique_children = 0;
1751 
1752 		for (int i = 0; i < is->is_children; i++) {
1753 			indirect_child_t *ic_i = &is->is_child[i];
1754 
1755 			if (ic_i->ic_data == NULL ||
1756 			    ic_i->ic_duplicate != NULL)
1757 				continue;
1758 
1759 			for (int j = i + 1; j < is->is_children; j++) {
1760 				indirect_child_t *ic_j = &is->is_child[j];
1761 
1762 				if (ic_j->ic_data == NULL ||
1763 				    ic_j->ic_duplicate != NULL)
1764 					continue;
1765 
1766 				if (abd_cmp(ic_i->ic_data, ic_j->ic_data) == 0)
1767 					ic_j->ic_duplicate = ic_i;
1768 			}
1769 
1770 			is->is_unique_children++;
1771 			list_insert_tail(&is->is_unique_child, ic_i);
1772 		}
1773 
1774 		/* Reconstruction is impossible, no valid children */
1775 		EQUIV(list_is_empty(&is->is_unique_child),
1776 		    is->is_unique_children == 0);
1777 		if (list_is_empty(&is->is_unique_child)) {
1778 			zio->io_error = EIO;
1779 			vdev_indirect_all_checksum_errors(zio);
1780 			zio_checksum_verified(zio);
1781 			return;
1782 		}
1783 
1784 		iv->iv_unique_combinations *= is->is_unique_children;
1785 	}
1786 
1787 	if (iv->iv_unique_combinations <= iv->iv_attempts_max)
1788 		error = vdev_indirect_splits_enumerate_all(iv, zio);
1789 	else
1790 		error = vdev_indirect_splits_enumerate_randomly(iv, zio);
1791 
1792 	if (error != 0) {
1793 		/* All attempted combinations failed. */
1794 		ASSERT3B(known_good, ==, B_FALSE);
1795 		zio->io_error = error;
1796 		vdev_indirect_all_checksum_errors(zio);
1797 	} else {
1798 		/*
1799 		 * The checksum has been successfully validated.  Issue
1800 		 * repair I/Os to any copies of splits which don't match
1801 		 * the validated version.
1802 		 */
1803 		ASSERT0(vdev_indirect_splits_checksum_validate(iv, zio));
1804 		vdev_indirect_repair(zio);
1805 		zio_checksum_verified(zio);
1806 	}
1807 }
1808 
1809 static void
vdev_indirect_io_done(zio_t * zio)1810 vdev_indirect_io_done(zio_t *zio)
1811 {
1812 	indirect_vsd_t *iv = zio->io_vsd;
1813 
1814 	if (iv->iv_reconstruct) {
1815 		/*
1816 		 * We have read all copies of the data (e.g. from mirrors),
1817 		 * either because this was a scrub/resilver, or because the
1818 		 * one-copy read didn't checksum correctly.
1819 		 */
1820 		vdev_indirect_reconstruct_io_done(zio);
1821 		return;
1822 	}
1823 
1824 	if (!iv->iv_split_block) {
1825 		/*
1826 		 * This was not a split block, so we passed the BP down,
1827 		 * and the checksum was handled by the (one) child zio.
1828 		 */
1829 		return;
1830 	}
1831 
1832 	zio_bad_cksum_t zbc;
1833 	int ret = zio_checksum_error(zio, &zbc);
1834 	/*
1835 	 * Any Direct I/O read that has a checksum error must be treated as
1836 	 * suspicious as the contents of the buffer could be getting
1837 	 * manipulated while the I/O is taking place. The checksum verify error
1838 	 * will be reported to the top-level VDEV.
1839 	 */
1840 	if (zio->io_flags & ZIO_FLAG_DIO_READ && ret == ECKSUM) {
1841 		zio->io_error = ret;
1842 		zio->io_post |= ZIO_POST_DIO_CHKSUM_ERR;
1843 		zio_dio_chksum_verify_error_report(zio);
1844 		ret = 0;
1845 	}
1846 
1847 	if (ret == 0) {
1848 		zio_checksum_verified(zio);
1849 		return;
1850 	}
1851 
1852 	/*
1853 	 * The checksum didn't match.  Read all copies of all splits, and
1854 	 * then we will try to reconstruct.  The next time
1855 	 * vdev_indirect_io_done() is called, iv_reconstruct will be set.
1856 	 */
1857 	vdev_indirect_read_all(zio);
1858 
1859 	zio_vdev_io_redone(zio);
1860 }
1861 
1862 vdev_ops_t vdev_indirect_ops = {
1863 	.vdev_op_init = NULL,
1864 	.vdev_op_fini = NULL,
1865 	.vdev_op_open = vdev_indirect_open,
1866 	.vdev_op_close = vdev_indirect_close,
1867 	.vdev_op_psize_to_asize = vdev_default_asize,
1868 	.vdev_op_asize_to_psize = vdev_default_psize,
1869 	.vdev_op_min_asize = vdev_default_min_asize,
1870 	.vdev_op_min_alloc = NULL,
1871 	.vdev_op_io_start = vdev_indirect_io_start,
1872 	.vdev_op_io_done = vdev_indirect_io_done,
1873 	.vdev_op_state_change = NULL,
1874 	.vdev_op_need_resilver = NULL,
1875 	.vdev_op_hold = NULL,
1876 	.vdev_op_rele = NULL,
1877 	.vdev_op_remap = vdev_indirect_remap,
1878 	.vdev_op_xlate = NULL,
1879 	.vdev_op_rebuild_asize = NULL,
1880 	.vdev_op_metaslab_init = NULL,
1881 	.vdev_op_config_generate = NULL,
1882 	.vdev_op_nparity = NULL,
1883 	.vdev_op_ndisks = NULL,
1884 	.vdev_op_type = VDEV_TYPE_INDIRECT,	/* name of this vdev type */
1885 	.vdev_op_leaf = B_FALSE			/* leaf vdev */
1886 };
1887 
1888 EXPORT_SYMBOL(spa_condense_fini);
1889 EXPORT_SYMBOL(spa_start_indirect_condensing_thread);
1890 EXPORT_SYMBOL(spa_condense_indirect_start_sync);
1891 EXPORT_SYMBOL(spa_condense_init);
1892 EXPORT_SYMBOL(spa_vdev_indirect_mark_obsolete);
1893 EXPORT_SYMBOL(vdev_indirect_mark_obsolete);
1894 EXPORT_SYMBOL(vdev_indirect_should_condense);
1895 EXPORT_SYMBOL(vdev_indirect_sync_obsolete);
1896 EXPORT_SYMBOL(vdev_obsolete_counts_are_precise);
1897 EXPORT_SYMBOL(vdev_obsolete_sm_object);
1898 
1899 ZFS_MODULE_PARAM(zfs_condense, zfs_condense_, indirect_vdevs_enable, INT,
1900 	ZMOD_RW, "Whether to attempt condensing indirect vdev mappings");
1901 
1902 ZFS_MODULE_PARAM(zfs_condense, zfs_condense_, indirect_obsolete_pct, UINT,
1903 	ZMOD_RW,
1904 	"Minimum obsolete percent of bytes in the mapping "
1905 	"to attempt condensing");
1906 
1907 ZFS_MODULE_PARAM(zfs_condense, zfs_condense_, min_mapping_bytes, U64, ZMOD_RW,
1908 	"Don't bother condensing if the mapping uses less than this amount of "
1909 	"memory");
1910 
1911 ZFS_MODULE_PARAM(zfs_condense, zfs_condense_, max_obsolete_bytes, U64,
1912 	ZMOD_RW,
1913 	"Minimum size obsolete spacemap to attempt condensing");
1914 
1915 ZFS_MODULE_PARAM(zfs_condense, zfs_condense_, indirect_commit_entry_delay_ms,
1916 	UINT, ZMOD_RW,
1917 	"Used by tests to ensure certain actions happen in the middle of a "
1918 	"condense. A maximum value of 1 should be sufficient.");
1919 
1920 ZFS_MODULE_PARAM(zfs_reconstruct, zfs_reconstruct_, indirect_combinations_max,
1921 	UINT, ZMOD_RW,
1922 	"Maximum number of combinations when reconstructing split segments");
1923