xref: /freebsd/sys/contrib/openzfs/module/zfs/vdev_trim.c (revision 2f10ffc003be396f3fc23cd2888023896560252b)
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) 2016, 2024 by Delphix. All rights reserved.
15  * Copyright (c) 2019 by Lawrence Livermore National Security, LLC.
16  * Copyright (c) 2021 Hewlett Packard Enterprise Development LP
17  * Copyright 2023 RackTop Systems, Inc.
18  */
19 
20 #include <sys/spa.h>
21 #include <sys/spa_impl.h>
22 #include <sys/txg.h>
23 #include <sys/vdev_impl.h>
24 #include <sys/vdev_trim.h>
25 #include <sys/metaslab_impl.h>
26 #include <sys/dsl_synctask.h>
27 #include <sys/zap.h>
28 #include <sys/dmu_tx.h>
29 #include <sys/arc_impl.h>
30 
31 /*
32  * TRIM is a feature which is used to notify a SSD that some previously
33  * written space is no longer allocated by the pool.  This is useful because
34  * writes to a SSD must be performed to blocks which have first been erased.
35  * Ensuring the SSD always has a supply of erased blocks for new writes
36  * helps prevent the performance from deteriorating.
37  *
38  * There are two supported TRIM methods; manual and automatic.
39  *
40  * Manual TRIM:
41  *
42  * A manual TRIM is initiated by running the 'zpool trim' command.  A single
43  * 'vdev_trim' thread is created for each leaf vdev, and it is responsible for
44  * managing that vdev TRIM process.  This involves iterating over all the
45  * metaslabs, calculating the unallocated space ranges, and then issuing the
46  * required TRIM I/Os.
47  *
48  * While a metaslab is being actively trimmed it is not eligible to perform
49  * new allocations.  After traversing all of the metaslabs the thread is
50  * terminated.  Finally, both the requested options and current progress of
51  * the TRIM are regularly written to the pool.  This allows the TRIM to be
52  * suspended and resumed as needed.
53  *
54  * Automatic TRIM:
55  *
56  * An automatic TRIM is enabled by setting the 'autotrim' pool property
57  * to 'on'.  When enabled, a `vdev_autotrim' thread is created for each
58  * top-level (not leaf) vdev in the pool.  These threads perform the same
59  * core TRIM process as a manual TRIM, but with a few key differences.
60  *
61  * 1) Automatic TRIM happens continuously in the background and operates
62  *    solely on recently freed blocks (ms_trim not ms_allocatable).
63  *
64  * 2) Each thread is associated with a top-level (not leaf) vdev.  This has
65  *    the benefit of simplifying the threading model, it makes it easier
66  *    to coordinate administrative commands, and it ensures only a single
67  *    metaslab is disabled at a time.  Unlike manual TRIM, this means each
68  *    'vdev_autotrim' thread is responsible for issuing TRIM I/Os for its
69  *    children.
70  *
71  * 3) There is no automatic TRIM progress information stored on disk, nor
72  *    is it reported by 'zpool status'.
73  *
74  * While the automatic TRIM process is highly effective it is more likely
75  * than a manual TRIM to encounter tiny ranges.  Ranges less than or equal to
76  * 'zfs_trim_extent_bytes_min' (32k) are considered too small to efficiently
77  * TRIM and are skipped.  This means small amounts of freed space may not
78  * be automatically trimmed.
79  *
80  * Furthermore, devices with attached hot spares and devices being actively
81  * replaced are skipped.  This is done to avoid adding additional stress to
82  * a potentially unhealthy device and to minimize the required rebuild time.
83  *
84  * For this reason it may be beneficial to occasionally manually TRIM a pool
85  * even when automatic TRIM is enabled.
86  */
87 
88 /*
89  * Maximum size of TRIM I/O, ranges will be chunked in to 128MiB lengths.
90  */
91 static unsigned int zfs_trim_extent_bytes_max = 128 * 1024 * 1024;
92 
93 /*
94  * Minimum size of TRIM I/O, extents smaller than 32Kib will be skipped.
95  */
96 static unsigned int zfs_trim_extent_bytes_min = 32 * 1024;
97 
98 /*
99  * Skip uninitialized metaslabs during the TRIM process.  This option is
100  * useful for pools constructed from large thinly-provisioned devices where
101  * TRIM operations are slow.  As a pool ages an increasing fraction of
102  * the pools metaslabs will be initialized progressively degrading the
103  * usefulness of this option.  This setting is stored when starting a
104  * manual TRIM and will persist for the duration of the requested TRIM.
105  */
106 unsigned int zfs_trim_metaslab_skip = 0;
107 
108 /*
109  * Maximum number of queued TRIM I/Os per leaf vdev.  The number of
110  * concurrent TRIM I/Os issued to the device is controlled by the
111  * zfs_vdev_trim_min_active and zfs_vdev_trim_max_active module options.
112  */
113 static unsigned int zfs_trim_queue_limit = 10;
114 
115 /*
116  * The minimum number of transaction groups between automatic trims of a
117  * metaslab.  This setting represents a trade-off between issuing more
118  * efficient TRIM operations, by allowing them to be aggregated longer,
119  * and issuing them promptly so the trimmed space is available.  Note
120  * that this value is a minimum; metaslabs can be trimmed less frequently
121  * when there are a large number of ranges which need to be trimmed.
122  *
123  * Increasing this value will allow frees to be aggregated for a longer
124  * time.  This can result is larger TRIM operations, and increased memory
125  * usage in order to track the ranges to be trimmed.  Decreasing this value
126  * has the opposite effect.  The default value of 32 was determined though
127  * testing to be a reasonable compromise.
128  */
129 static unsigned int zfs_trim_txg_batch = 32;
130 
131 /*
132  * The trim_args are a control structure which describe how a leaf vdev
133  * should be trimmed.  The core elements are the vdev, the metaslab being
134  * trimmed and a range tree containing the extents to TRIM.  All provided
135  * ranges must be within the metaslab.
136  */
137 typedef struct trim_args {
138 	/*
139 	 * These fields are set by the caller of vdev_trim_ranges().
140 	 */
141 	vdev_t		*trim_vdev;		/* Leaf vdev to TRIM */
142 	metaslab_t	*trim_msp;		/* Disabled metaslab */
143 	zfs_range_tree_t	*trim_tree;	/* TRIM ranges (in metaslab) */
144 	trim_type_t	trim_type;		/* Manual or auto TRIM */
145 	uint64_t	trim_extent_bytes_max;	/* Maximum TRIM I/O size */
146 	uint64_t	trim_extent_bytes_min;	/* Minimum TRIM I/O size */
147 	enum trim_flag	trim_flags;		/* TRIM flags (secure) */
148 
149 	/*
150 	 * These fields are updated by vdev_trim_ranges().
151 	 */
152 	hrtime_t	trim_start_time;	/* Start time */
153 	uint64_t	trim_bytes_done;	/* Bytes trimmed */
154 } trim_args_t;
155 
156 /*
157  * Determines whether a vdev_trim_thread() should be stopped.
158  */
159 static boolean_t
160 vdev_trim_should_stop(vdev_t *vd)
161 {
162 	return (vd->vdev_trim_exit_wanted || !vdev_writeable(vd) ||
163 	    vd->vdev_detached || vd->vdev_top->vdev_removing ||
164 	    vd->vdev_top->vdev_rz_expanding);
165 }
166 
167 /*
168  * Determines whether a vdev_autotrim_thread() should be stopped.
169  */
170 static boolean_t
171 vdev_autotrim_should_stop(vdev_t *tvd)
172 {
173 	return (tvd->vdev_autotrim_exit_wanted ||
174 	    !vdev_writeable(tvd) || tvd->vdev_removing ||
175 	    tvd->vdev_rz_expanding ||
176 	    spa_get_autotrim(tvd->vdev_spa) == SPA_AUTOTRIM_OFF);
177 }
178 
179 /*
180  * Wait for given number of kicks, return true if the wait is aborted due to
181  * vdev_autotrim_exit_wanted.
182  */
183 static boolean_t
184 vdev_autotrim_wait_kick(vdev_t *vd, int num_of_kick)
185 {
186 	mutex_enter(&vd->vdev_autotrim_lock);
187 	for (int i = 0; i < num_of_kick; i++) {
188 		if (vd->vdev_autotrim_exit_wanted)
189 			break;
190 		cv_wait_idle(&vd->vdev_autotrim_kick_cv,
191 		    &vd->vdev_autotrim_lock);
192 	}
193 	boolean_t exit_wanted = vd->vdev_autotrim_exit_wanted;
194 	mutex_exit(&vd->vdev_autotrim_lock);
195 
196 	return (exit_wanted);
197 }
198 
199 /*
200  * The sync task for updating the on-disk state of a manual TRIM.  This
201  * is scheduled by vdev_trim_change_state().
202  */
203 static void
204 vdev_trim_zap_update_sync(void *arg, dmu_tx_t *tx)
205 {
206 	/*
207 	 * We pass in the guid instead of the vdev_t since the vdev may
208 	 * have been freed prior to the sync task being processed.  This
209 	 * happens when a vdev is detached as we call spa_config_vdev_exit(),
210 	 * stop the trimming thread, schedule the sync task, and free
211 	 * the vdev. Later when the scheduled sync task is invoked, it would
212 	 * find that the vdev has been freed.
213 	 */
214 	uint64_t guid = *(uint64_t *)arg;
215 	uint64_t txg = dmu_tx_get_txg(tx);
216 	kmem_free(arg, sizeof (uint64_t));
217 
218 	vdev_t *vd = spa_lookup_by_guid(tx->tx_pool->dp_spa, guid, B_FALSE);
219 	if (vd == NULL || vd->vdev_top->vdev_removing ||
220 	    !vdev_is_concrete(vd) || vd->vdev_top->vdev_rz_expanding)
221 		return;
222 
223 	uint64_t last_offset = vd->vdev_trim_offset[txg & TXG_MASK];
224 	vd->vdev_trim_offset[txg & TXG_MASK] = 0;
225 
226 	VERIFY3U(vd->vdev_leaf_zap, !=, 0);
227 
228 	objset_t *mos = vd->vdev_spa->spa_meta_objset;
229 
230 	if (last_offset > 0 || vd->vdev_trim_last_offset == UINT64_MAX) {
231 
232 		if (vd->vdev_trim_last_offset == UINT64_MAX)
233 			last_offset = 0;
234 
235 		vd->vdev_trim_last_offset = last_offset;
236 		VERIFY0(zap_update(mos, vd->vdev_leaf_zap,
237 		    VDEV_LEAF_ZAP_TRIM_LAST_OFFSET,
238 		    sizeof (last_offset), 1, &last_offset, tx));
239 	}
240 
241 	if (vd->vdev_trim_action_time > 0) {
242 		uint64_t val = (uint64_t)vd->vdev_trim_action_time;
243 		VERIFY0(zap_update(mos, vd->vdev_leaf_zap,
244 		    VDEV_LEAF_ZAP_TRIM_ACTION_TIME, sizeof (val),
245 		    1, &val, tx));
246 	}
247 
248 	if (vd->vdev_trim_rate > 0) {
249 		uint64_t rate = (uint64_t)vd->vdev_trim_rate;
250 
251 		if (rate == UINT64_MAX)
252 			rate = 0;
253 
254 		VERIFY0(zap_update(mos, vd->vdev_leaf_zap,
255 		    VDEV_LEAF_ZAP_TRIM_RATE, sizeof (rate), 1, &rate, tx));
256 	}
257 
258 	uint64_t partial = vd->vdev_trim_partial;
259 	if (partial == UINT64_MAX)
260 		partial = 0;
261 
262 	VERIFY0(zap_update(mos, vd->vdev_leaf_zap, VDEV_LEAF_ZAP_TRIM_PARTIAL,
263 	    sizeof (partial), 1, &partial, tx));
264 
265 	uint64_t secure = vd->vdev_trim_secure;
266 	if (secure == UINT64_MAX)
267 		secure = 0;
268 
269 	VERIFY0(zap_update(mos, vd->vdev_leaf_zap, VDEV_LEAF_ZAP_TRIM_SECURE,
270 	    sizeof (secure), 1, &secure, tx));
271 
272 
273 	uint64_t trim_state = vd->vdev_trim_state;
274 	VERIFY0(zap_update(mos, vd->vdev_leaf_zap, VDEV_LEAF_ZAP_TRIM_STATE,
275 	    sizeof (trim_state), 1, &trim_state, tx));
276 }
277 
278 /*
279  * Update the on-disk state of a manual TRIM.  This is called to request
280  * that a TRIM be started/suspended/canceled, or to change one of the
281  * TRIM options (partial, secure, rate).
282  */
283 static void
284 vdev_trim_change_state(vdev_t *vd, vdev_trim_state_t new_state,
285     uint64_t rate, boolean_t partial, boolean_t secure)
286 {
287 	ASSERT(MUTEX_HELD(&vd->vdev_trim_lock));
288 	spa_t *spa = vd->vdev_spa;
289 
290 	if (new_state == vd->vdev_trim_state)
291 		return;
292 
293 	/*
294 	 * Copy the vd's guid, this will be freed by the sync task.
295 	 */
296 	uint64_t *guid = kmem_zalloc(sizeof (uint64_t), KM_SLEEP);
297 	*guid = vd->vdev_guid;
298 
299 	/*
300 	 * If we're suspending, then preserve the original start time.
301 	 */
302 	if (vd->vdev_trim_state != VDEV_TRIM_SUSPENDED) {
303 		vd->vdev_trim_action_time = gethrestime_sec();
304 	}
305 
306 	/*
307 	 * If we're activating, then preserve the requested rate and trim
308 	 * method.  Setting the last offset and rate to UINT64_MAX is used
309 	 * as a sentinel to indicate they should be reset to default values.
310 	 */
311 	if (new_state == VDEV_TRIM_ACTIVE) {
312 		if (vd->vdev_trim_state == VDEV_TRIM_COMPLETE ||
313 		    vd->vdev_trim_state == VDEV_TRIM_CANCELED) {
314 			vd->vdev_trim_last_offset = UINT64_MAX;
315 			vd->vdev_trim_rate = UINT64_MAX;
316 			vd->vdev_trim_partial = UINT64_MAX;
317 			vd->vdev_trim_secure = UINT64_MAX;
318 		}
319 
320 		if (rate != 0)
321 			vd->vdev_trim_rate = rate;
322 
323 		if (partial != 0)
324 			vd->vdev_trim_partial = partial;
325 
326 		if (secure != 0)
327 			vd->vdev_trim_secure = secure;
328 	}
329 
330 	vdev_trim_state_t old_state = vd->vdev_trim_state;
331 	boolean_t resumed = (old_state == VDEV_TRIM_SUSPENDED);
332 	vd->vdev_trim_state = new_state;
333 
334 	dmu_tx_t *tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
335 	VERIFY0(dmu_tx_assign(tx, DMU_TX_WAIT | DMU_TX_SUSPEND));
336 	dsl_sync_task_nowait(spa_get_dsl(spa), vdev_trim_zap_update_sync,
337 	    guid, tx);
338 
339 	switch (new_state) {
340 	case VDEV_TRIM_ACTIVE:
341 		spa_event_notify(spa, vd, NULL,
342 		    resumed ? ESC_ZFS_TRIM_RESUME : ESC_ZFS_TRIM_START);
343 		spa_history_log_internal(spa, "trim", tx,
344 		    "vdev=%s activated", vd->vdev_path);
345 		break;
346 	case VDEV_TRIM_SUSPENDED:
347 		spa_event_notify(spa, vd, NULL, ESC_ZFS_TRIM_SUSPEND);
348 		spa_history_log_internal(spa, "trim", tx,
349 		    "vdev=%s suspended", vd->vdev_path);
350 		break;
351 	case VDEV_TRIM_CANCELED:
352 		if (old_state == VDEV_TRIM_ACTIVE ||
353 		    old_state == VDEV_TRIM_SUSPENDED) {
354 			spa_event_notify(spa, vd, NULL, ESC_ZFS_TRIM_CANCEL);
355 			spa_history_log_internal(spa, "trim", tx,
356 			    "vdev=%s canceled", vd->vdev_path);
357 		}
358 		break;
359 	case VDEV_TRIM_COMPLETE:
360 		spa_event_notify(spa, vd, NULL, ESC_ZFS_TRIM_FINISH);
361 		spa_history_log_internal(spa, "trim", tx,
362 		    "vdev=%s complete", vd->vdev_path);
363 		break;
364 	default:
365 		panic("invalid state %llu", (unsigned long long)new_state);
366 	}
367 
368 	dmu_tx_commit(tx);
369 
370 	if (new_state != VDEV_TRIM_ACTIVE)
371 		spa_notify_waiters(spa);
372 }
373 
374 /*
375  * The zio_done_func_t done callback for each manual TRIM issued.  It is
376  * responsible for updating the TRIM stats, reissuing failed TRIM I/Os,
377  * and limiting the number of in flight TRIM I/Os.
378  */
379 static void
380 vdev_trim_cb(zio_t *zio)
381 {
382 	vdev_t *vd = zio->io_vd;
383 
384 	mutex_enter(&vd->vdev_trim_io_lock);
385 	if (zio->io_error == ENXIO && !vdev_writeable(vd)) {
386 		/*
387 		 * The I/O failed because the vdev was unavailable; roll the
388 		 * last offset back. (This works because spa_sync waits on
389 		 * spa_txg_zio before it runs sync tasks.)
390 		 */
391 		uint64_t *offset =
392 		    &vd->vdev_trim_offset[zio->io_txg & TXG_MASK];
393 		*offset = MIN(*offset, zio->io_offset);
394 	} else {
395 		if (zio->io_error != 0) {
396 			vd->vdev_stat.vs_trim_errors++;
397 			spa_iostats_trim_add(vd->vdev_spa, TRIM_TYPE_MANUAL,
398 			    0, 0, 0, 0, 1, zio->io_orig_size);
399 		} else {
400 			spa_iostats_trim_add(vd->vdev_spa, TRIM_TYPE_MANUAL,
401 			    1, zio->io_orig_size, 0, 0, 0, 0);
402 		}
403 
404 		vd->vdev_trim_bytes_done += zio->io_orig_size;
405 	}
406 
407 	ASSERT3U(vd->vdev_trim_inflight[TRIM_TYPE_MANUAL], >, 0);
408 	vd->vdev_trim_inflight[TRIM_TYPE_MANUAL]--;
409 	cv_broadcast(&vd->vdev_trim_io_cv);
410 	mutex_exit(&vd->vdev_trim_io_lock);
411 
412 	spa_config_exit(vd->vdev_spa, SCL_STATE_ALL, vd);
413 }
414 
415 /*
416  * The zio_done_func_t done callback for each automatic TRIM issued.  It
417  * is responsible for updating the TRIM stats and limiting the number of
418  * in flight TRIM I/Os.  Automatic TRIM I/Os are best effort and are
419  * never reissued on failure.
420  */
421 static void
422 vdev_autotrim_cb(zio_t *zio)
423 {
424 	vdev_t *vd = zio->io_vd;
425 
426 	mutex_enter(&vd->vdev_trim_io_lock);
427 
428 	if (zio->io_error != 0) {
429 		vd->vdev_stat.vs_trim_errors++;
430 		spa_iostats_trim_add(vd->vdev_spa, TRIM_TYPE_AUTO,
431 		    0, 0, 0, 0, 1, zio->io_orig_size);
432 	} else {
433 		spa_iostats_trim_add(vd->vdev_spa, TRIM_TYPE_AUTO,
434 		    1, zio->io_orig_size, 0, 0, 0, 0);
435 	}
436 
437 	ASSERT3U(vd->vdev_trim_inflight[TRIM_TYPE_AUTO], >, 0);
438 	vd->vdev_trim_inflight[TRIM_TYPE_AUTO]--;
439 	cv_broadcast(&vd->vdev_trim_io_cv);
440 	mutex_exit(&vd->vdev_trim_io_lock);
441 
442 	spa_config_exit(vd->vdev_spa, SCL_STATE_ALL, vd);
443 }
444 
445 /*
446  * The zio_done_func_t done callback for each TRIM issued via
447  * vdev_trim_simple(). It is responsible for updating the TRIM stats and
448  * limiting the number of in flight TRIM I/Os.  Simple TRIM I/Os are best
449  * effort and are never reissued on failure.
450  */
451 static void
452 vdev_trim_simple_cb(zio_t *zio)
453 {
454 	vdev_t *vd = zio->io_vd;
455 
456 	mutex_enter(&vd->vdev_trim_io_lock);
457 
458 	if (zio->io_error != 0) {
459 		vd->vdev_stat.vs_trim_errors++;
460 		spa_iostats_trim_add(vd->vdev_spa, TRIM_TYPE_SIMPLE,
461 		    0, 0, 0, 0, 1, zio->io_orig_size);
462 	} else {
463 		spa_iostats_trim_add(vd->vdev_spa, TRIM_TYPE_SIMPLE,
464 		    1, zio->io_orig_size, 0, 0, 0, 0);
465 	}
466 
467 	ASSERT3U(vd->vdev_trim_inflight[TRIM_TYPE_SIMPLE], >, 0);
468 	vd->vdev_trim_inflight[TRIM_TYPE_SIMPLE]--;
469 	cv_broadcast(&vd->vdev_trim_io_cv);
470 	mutex_exit(&vd->vdev_trim_io_lock);
471 
472 	spa_config_exit(vd->vdev_spa, SCL_STATE_ALL, vd);
473 }
474 /*
475  * Returns the average trim rate in bytes/sec for the ta->trim_vdev.
476  */
477 static uint64_t
478 vdev_trim_calculate_rate(trim_args_t *ta)
479 {
480 	return (ta->trim_bytes_done * 1000 /
481 	    (NSEC2MSEC(gethrtime() - ta->trim_start_time) + 1));
482 }
483 
484 /*
485  * Issues a physical TRIM and takes care of rate limiting (bytes/sec)
486  * and number of concurrent TRIM I/Os.
487  */
488 static int
489 vdev_trim_range(trim_args_t *ta, uint64_t start, uint64_t size)
490 {
491 	vdev_t *vd = ta->trim_vdev;
492 	spa_t *spa = vd->vdev_spa;
493 	void *cb;
494 
495 	mutex_enter(&vd->vdev_trim_io_lock);
496 
497 	/*
498 	 * Limit manual TRIM I/Os to the requested rate.  This does not
499 	 * apply to automatic TRIM since no per vdev rate can be specified.
500 	 */
501 	if (ta->trim_type == TRIM_TYPE_MANUAL) {
502 		while (vd->vdev_trim_rate != 0 && !vdev_trim_should_stop(vd) &&
503 		    vdev_trim_calculate_rate(ta) > vd->vdev_trim_rate) {
504 			cv_timedwait_idle(&vd->vdev_trim_io_cv,
505 			    &vd->vdev_trim_io_lock, ddi_get_lbolt() +
506 			    MSEC_TO_TICK(10));
507 		}
508 	}
509 	ta->trim_bytes_done += size;
510 
511 	/* Limit in flight trimming I/Os */
512 	while (vd->vdev_trim_inflight[0] + vd->vdev_trim_inflight[1] +
513 	    vd->vdev_trim_inflight[2] >= zfs_trim_queue_limit) {
514 		cv_wait(&vd->vdev_trim_io_cv, &vd->vdev_trim_io_lock);
515 	}
516 	vd->vdev_trim_inflight[ta->trim_type]++;
517 	mutex_exit(&vd->vdev_trim_io_lock);
518 
519 	dmu_tx_t *tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
520 	VERIFY0(dmu_tx_assign(tx, DMU_TX_WAIT | DMU_TX_SUSPEND));
521 	uint64_t txg = dmu_tx_get_txg(tx);
522 
523 	spa_config_enter(spa, SCL_STATE_ALL, vd, RW_READER);
524 	mutex_enter(&vd->vdev_trim_lock);
525 
526 	if (ta->trim_type == TRIM_TYPE_MANUAL &&
527 	    vd->vdev_trim_offset[txg & TXG_MASK] == 0) {
528 		uint64_t *guid = kmem_zalloc(sizeof (uint64_t), KM_SLEEP);
529 		*guid = vd->vdev_guid;
530 
531 		/* This is the first write of this txg. */
532 		dsl_sync_task_nowait(spa_get_dsl(spa),
533 		    vdev_trim_zap_update_sync, guid, tx);
534 	}
535 
536 	/*
537 	 * We know the vdev_t will still be around since all consumers of
538 	 * vdev_free must stop the trimming first.
539 	 */
540 	if ((ta->trim_type == TRIM_TYPE_MANUAL &&
541 	    vdev_trim_should_stop(vd)) ||
542 	    (ta->trim_type == TRIM_TYPE_AUTO &&
543 	    vdev_autotrim_should_stop(vd->vdev_top))) {
544 		mutex_enter(&vd->vdev_trim_io_lock);
545 		vd->vdev_trim_inflight[ta->trim_type]--;
546 		mutex_exit(&vd->vdev_trim_io_lock);
547 		spa_config_exit(vd->vdev_spa, SCL_STATE_ALL, vd);
548 		mutex_exit(&vd->vdev_trim_lock);
549 		dmu_tx_commit(tx);
550 		return (SET_ERROR(EINTR));
551 	}
552 	mutex_exit(&vd->vdev_trim_lock);
553 
554 	if (ta->trim_type == TRIM_TYPE_MANUAL)
555 		vd->vdev_trim_offset[txg & TXG_MASK] = start + size;
556 
557 	if (ta->trim_type == TRIM_TYPE_MANUAL) {
558 		cb = vdev_trim_cb;
559 	} else if (ta->trim_type == TRIM_TYPE_AUTO) {
560 		cb = vdev_autotrim_cb;
561 	} else {
562 		cb = vdev_trim_simple_cb;
563 	}
564 
565 	zio_nowait(zio_trim(spa->spa_txg_zio[txg & TXG_MASK], vd,
566 	    start, size, cb, NULL, ZIO_PRIORITY_TRIM, ZIO_FLAG_CANFAIL,
567 	    ta->trim_flags));
568 	/* vdev_trim_cb and vdev_autotrim_cb release SCL_STATE_ALL */
569 
570 	dmu_tx_commit(tx);
571 
572 	return (0);
573 }
574 
575 /*
576  * Issues TRIM I/Os for all ranges in the provided ta->trim_tree range tree.
577  * Additional parameters describing how the TRIM should be performed must
578  * be set in the trim_args structure.  See the trim_args definition for
579  * additional information.
580  */
581 static int
582 vdev_trim_ranges(trim_args_t *ta)
583 {
584 	vdev_t *vd = ta->trim_vdev;
585 	zfs_btree_t *t = &ta->trim_tree->rt_root;
586 	zfs_btree_index_t idx;
587 	uint64_t extent_bytes_max = ta->trim_extent_bytes_max;
588 	uint64_t extent_bytes_min = ta->trim_extent_bytes_min;
589 	spa_t *spa = vd->vdev_spa;
590 	int error = 0;
591 
592 	ta->trim_start_time = gethrtime();
593 	ta->trim_bytes_done = 0;
594 
595 	for (zfs_range_seg_t *rs = zfs_btree_first(t, &idx); rs != NULL;
596 	    rs = zfs_btree_next(t, &idx, &idx)) {
597 		uint64_t size = zfs_rs_get_end(rs, ta->trim_tree) -
598 		    zfs_rs_get_start(rs, ta->trim_tree);
599 
600 		if (extent_bytes_min && size < extent_bytes_min) {
601 			spa_iostats_trim_add(spa, ta->trim_type,
602 			    0, 0, 1, size, 0, 0);
603 			continue;
604 		}
605 
606 		/* Split range into legally-sized physical chunks */
607 		uint64_t writes_required = ((size - 1) / extent_bytes_max) + 1;
608 
609 		for (uint64_t w = 0; w < writes_required; w++) {
610 			error = vdev_trim_range(ta, VDEV_LABEL_START_SIZE +
611 			    zfs_rs_get_start(rs, ta->trim_tree) +
612 			    (w *extent_bytes_max), MIN(size -
613 			    (w * extent_bytes_max), extent_bytes_max));
614 			if (error != 0) {
615 				goto done;
616 			}
617 		}
618 	}
619 
620 done:
621 	/*
622 	 * Make sure all TRIMs for this metaslab have completed before
623 	 * returning. TRIM zios have lower priority over regular or syncing
624 	 * zios, so all TRIM zios for this metaslab must complete before the
625 	 * metaslab is re-enabled. Otherwise it's possible write zios to
626 	 * this metaslab could cut ahead of still queued TRIM zios for this
627 	 * metaslab causing corruption if the ranges overlap.
628 	 */
629 	mutex_enter(&vd->vdev_trim_io_lock);
630 	while (vd->vdev_trim_inflight[0] > 0) {
631 		cv_wait(&vd->vdev_trim_io_cv, &vd->vdev_trim_io_lock);
632 	}
633 	mutex_exit(&vd->vdev_trim_io_lock);
634 
635 	return (error);
636 }
637 
638 static void
639 vdev_trim_xlate_last_rs_end(void *arg, zfs_range_seg64_t *physical_rs)
640 {
641 	uint64_t *last_rs_end = (uint64_t *)arg;
642 
643 	if (physical_rs->rs_end > *last_rs_end)
644 		*last_rs_end = physical_rs->rs_end;
645 }
646 
647 static void
648 vdev_trim_xlate_progress(void *arg, zfs_range_seg64_t *physical_rs)
649 {
650 	vdev_t *vd = (vdev_t *)arg;
651 
652 	uint64_t size = physical_rs->rs_end - physical_rs->rs_start;
653 	vd->vdev_trim_bytes_est += size;
654 
655 	if (vd->vdev_trim_last_offset >= physical_rs->rs_end) {
656 		vd->vdev_trim_bytes_done += size;
657 	} else if (vd->vdev_trim_last_offset > physical_rs->rs_start &&
658 	    vd->vdev_trim_last_offset <= physical_rs->rs_end) {
659 		vd->vdev_trim_bytes_done +=
660 		    vd->vdev_trim_last_offset - physical_rs->rs_start;
661 	}
662 }
663 
664 /*
665  * Calculates the completion percentage of a manual TRIM.
666  */
667 static void
668 vdev_trim_calculate_progress(vdev_t *vd)
669 {
670 	ASSERT(spa_config_held(vd->vdev_spa, SCL_CONFIG, RW_READER) ||
671 	    spa_config_held(vd->vdev_spa, SCL_CONFIG, RW_WRITER));
672 	ASSERT(vd->vdev_leaf_zap != 0);
673 
674 	vd->vdev_trim_bytes_est = 0;
675 	vd->vdev_trim_bytes_done = 0;
676 
677 	for (uint64_t i = 0; i < vd->vdev_top->vdev_ms_count; i++) {
678 		metaslab_t *msp = vd->vdev_top->vdev_ms[i];
679 		mutex_enter(&msp->ms_lock);
680 
681 		uint64_t ms_free = (msp->ms_size -
682 		    metaslab_allocated_space(msp)) /
683 		    vdev_get_ndisks(vd->vdev_top);
684 
685 		/*
686 		 * Convert the metaslab range to a physical range
687 		 * on our vdev. We use this to determine if we are
688 		 * in the middle of this metaslab range.
689 		 */
690 		zfs_range_seg64_t logical_rs, physical_rs, remain_rs;
691 		logical_rs.rs_start = msp->ms_start;
692 		logical_rs.rs_end = msp->ms_start + msp->ms_size;
693 
694 		/* Metaslab space after this offset has not been trimmed. */
695 		vdev_xlate(vd, &logical_rs, &physical_rs, &remain_rs);
696 		if (vd->vdev_trim_last_offset <= physical_rs.rs_start) {
697 			vd->vdev_trim_bytes_est += ms_free;
698 			mutex_exit(&msp->ms_lock);
699 			continue;
700 		}
701 
702 		/* Metaslab space before this offset has been trimmed */
703 		uint64_t last_rs_end = physical_rs.rs_end;
704 		if (!vdev_xlate_is_empty(&remain_rs)) {
705 			vdev_xlate_walk(vd, &remain_rs,
706 			    vdev_trim_xlate_last_rs_end, &last_rs_end);
707 		}
708 
709 		if (vd->vdev_trim_last_offset > last_rs_end) {
710 			vd->vdev_trim_bytes_done += ms_free;
711 			vd->vdev_trim_bytes_est += ms_free;
712 			mutex_exit(&msp->ms_lock);
713 			continue;
714 		}
715 
716 		/*
717 		 * If we get here, we're in the middle of trimming this
718 		 * metaslab.  Load it and walk the free tree for more
719 		 * accurate progress estimation.
720 		 */
721 		VERIFY0(metaslab_load(msp));
722 
723 		zfs_range_tree_t *rt = msp->ms_allocatable;
724 		zfs_btree_t *bt = &rt->rt_root;
725 		zfs_btree_index_t idx;
726 		for (zfs_range_seg_t *rs = zfs_btree_first(bt, &idx);
727 		    rs != NULL; rs = zfs_btree_next(bt, &idx, &idx)) {
728 			logical_rs.rs_start = zfs_rs_get_start(rs, rt);
729 			logical_rs.rs_end = zfs_rs_get_end(rs, rt);
730 
731 			vdev_xlate_walk(vd, &logical_rs,
732 			    vdev_trim_xlate_progress, vd);
733 		}
734 		mutex_exit(&msp->ms_lock);
735 	}
736 }
737 
738 /*
739  * Load from disk the vdev's manual TRIM information.  This includes the
740  * state, progress, and options provided when initiating the manual TRIM.
741  */
742 static int
743 vdev_trim_load(vdev_t *vd)
744 {
745 	int err = 0;
746 	ASSERT(spa_config_held(vd->vdev_spa, SCL_CONFIG, RW_READER) ||
747 	    spa_config_held(vd->vdev_spa, SCL_CONFIG, RW_WRITER));
748 	ASSERT(vd->vdev_leaf_zap != 0);
749 
750 	if (vd->vdev_trim_state == VDEV_TRIM_ACTIVE ||
751 	    vd->vdev_trim_state == VDEV_TRIM_SUSPENDED) {
752 		err = zap_lookup(vd->vdev_spa->spa_meta_objset,
753 		    vd->vdev_leaf_zap, VDEV_LEAF_ZAP_TRIM_LAST_OFFSET,
754 		    sizeof (vd->vdev_trim_last_offset), 1,
755 		    &vd->vdev_trim_last_offset);
756 		if (err == ENOENT) {
757 			vd->vdev_trim_last_offset = 0;
758 			err = 0;
759 		}
760 
761 		if (err == 0) {
762 			err = zap_lookup(vd->vdev_spa->spa_meta_objset,
763 			    vd->vdev_leaf_zap, VDEV_LEAF_ZAP_TRIM_RATE,
764 			    sizeof (vd->vdev_trim_rate), 1,
765 			    &vd->vdev_trim_rate);
766 			if (err == ENOENT) {
767 				vd->vdev_trim_rate = 0;
768 				err = 0;
769 			}
770 		}
771 
772 		if (err == 0) {
773 			err = zap_lookup(vd->vdev_spa->spa_meta_objset,
774 			    vd->vdev_leaf_zap, VDEV_LEAF_ZAP_TRIM_PARTIAL,
775 			    sizeof (vd->vdev_trim_partial), 1,
776 			    &vd->vdev_trim_partial);
777 			if (err == ENOENT) {
778 				vd->vdev_trim_partial = 0;
779 				err = 0;
780 			}
781 		}
782 
783 		if (err == 0) {
784 			err = zap_lookup(vd->vdev_spa->spa_meta_objset,
785 			    vd->vdev_leaf_zap, VDEV_LEAF_ZAP_TRIM_SECURE,
786 			    sizeof (vd->vdev_trim_secure), 1,
787 			    &vd->vdev_trim_secure);
788 			if (err == ENOENT) {
789 				vd->vdev_trim_secure = 0;
790 				err = 0;
791 			}
792 		}
793 	}
794 
795 	vdev_trim_calculate_progress(vd);
796 
797 	return (err);
798 }
799 
800 static void
801 vdev_trim_xlate_range_add(void *arg, zfs_range_seg64_t *physical_rs)
802 {
803 	trim_args_t *ta = arg;
804 	vdev_t *vd = ta->trim_vdev;
805 
806 	/*
807 	 * Only a manual trim will be traversing the vdev sequentially.
808 	 * For an auto trim all valid ranges should be added.
809 	 */
810 	if (ta->trim_type == TRIM_TYPE_MANUAL) {
811 
812 		/* Only add segments that we have not visited yet */
813 		if (physical_rs->rs_end <= vd->vdev_trim_last_offset)
814 			return;
815 
816 		/* Pick up where we left off mid-range. */
817 		if (vd->vdev_trim_last_offset > physical_rs->rs_start) {
818 			ASSERT3U(physical_rs->rs_end, >,
819 			    vd->vdev_trim_last_offset);
820 			physical_rs->rs_start = vd->vdev_trim_last_offset;
821 		}
822 	}
823 
824 	ASSERT3U(physical_rs->rs_end, >, physical_rs->rs_start);
825 
826 	zfs_range_tree_add(ta->trim_tree, physical_rs->rs_start,
827 	    physical_rs->rs_end - physical_rs->rs_start);
828 }
829 
830 /*
831  * Convert the logical range into physical ranges and add them to the
832  * range tree passed in the trim_args_t.
833  */
834 static void
835 vdev_trim_range_add(void *arg, uint64_t start, uint64_t size)
836 {
837 	trim_args_t *ta = arg;
838 	vdev_t *vd = ta->trim_vdev;
839 	zfs_range_seg64_t logical_rs;
840 	logical_rs.rs_start = start;
841 	logical_rs.rs_end = start + size;
842 
843 	/*
844 	 * Every range to be trimmed must be part of ms_allocatable.
845 	 * When ZFS_DEBUG_TRIM is set load the metaslab to verify this
846 	 * is always the case.
847 	 */
848 	if (zfs_flags & ZFS_DEBUG_TRIM) {
849 		metaslab_t *msp = ta->trim_msp;
850 		VERIFY0(metaslab_load(msp));
851 		VERIFY3B(msp->ms_loaded, ==, B_TRUE);
852 		VERIFY(zfs_range_tree_contains(msp->ms_allocatable, start,
853 		    size));
854 	}
855 
856 	ASSERT(vd->vdev_ops->vdev_op_leaf);
857 	vdev_xlate_walk(vd, &logical_rs, vdev_trim_xlate_range_add, arg);
858 }
859 
860 /*
861  * Each manual TRIM thread is responsible for trimming the unallocated
862  * space for each leaf vdev.  This is accomplished by sequentially iterating
863  * over its top-level metaslabs and issuing TRIM I/O for the space described
864  * by its ms_allocatable.  While a metaslab is undergoing trimming it is
865  * not eligible for new allocations.
866  */
867 static __attribute__((noreturn)) void
868 vdev_trim_thread(void *arg)
869 {
870 	vdev_t *vd = arg;
871 	spa_t *spa = vd->vdev_spa;
872 	trim_args_t ta;
873 	int error = 0;
874 
875 	/*
876 	 * The VDEV_LEAF_ZAP_TRIM_* entries may have been updated by
877 	 * vdev_trim().  Wait for the updated values to be reflected
878 	 * in the zap in order to start with the requested settings.
879 	 */
880 	txg_wait_synced(spa_get_dsl(vd->vdev_spa), 0);
881 
882 	ASSERT(vdev_is_concrete(vd));
883 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
884 
885 	vd->vdev_trim_last_offset = 0;
886 	vd->vdev_trim_rate = 0;
887 	vd->vdev_trim_partial = 0;
888 	vd->vdev_trim_secure = 0;
889 
890 	VERIFY0(vdev_trim_load(vd));
891 
892 	ta.trim_vdev = vd;
893 	ta.trim_extent_bytes_max = zfs_trim_extent_bytes_max;
894 	ta.trim_extent_bytes_min = zfs_trim_extent_bytes_min;
895 	ta.trim_tree = zfs_range_tree_create_flags(
896 	    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
897 	    ZFS_RT_F_DYN_NAME, vdev_rt_name(vd, "trim_tree"));
898 	ta.trim_type = TRIM_TYPE_MANUAL;
899 	ta.trim_flags = 0;
900 
901 	/*
902 	 * When a secure TRIM has been requested infer that the intent
903 	 * is that everything must be trimmed.  Override the default
904 	 * minimum TRIM size to prevent ranges from being skipped.
905 	 */
906 	if (vd->vdev_trim_secure) {
907 		ta.trim_flags |= ZIO_TRIM_SECURE;
908 		ta.trim_extent_bytes_min = SPA_MINBLOCKSIZE;
909 	}
910 
911 	uint64_t ms_count = 0;
912 	for (uint64_t i = 0; !vd->vdev_detached &&
913 	    i < vd->vdev_top->vdev_ms_count; i++) {
914 		metaslab_t *msp = vd->vdev_top->vdev_ms[i];
915 
916 		/*
917 		 * If we've expanded the top-level vdev or it's our
918 		 * first pass, calculate our progress.
919 		 */
920 		if (vd->vdev_top->vdev_ms_count != ms_count) {
921 			vdev_trim_calculate_progress(vd);
922 			ms_count = vd->vdev_top->vdev_ms_count;
923 		}
924 
925 		spa_config_exit(spa, SCL_CONFIG, FTAG);
926 		metaslab_disable(msp);
927 		mutex_enter(&msp->ms_lock);
928 		VERIFY0(metaslab_load(msp));
929 
930 		/*
931 		 * If a partial TRIM was requested skip metaslabs which have
932 		 * never been initialized and thus have never been written.
933 		 */
934 		if (msp->ms_sm == NULL && vd->vdev_trim_partial) {
935 			mutex_exit(&msp->ms_lock);
936 			metaslab_enable(msp, B_FALSE, B_FALSE);
937 			spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
938 			vdev_trim_calculate_progress(vd);
939 			continue;
940 		}
941 
942 		ta.trim_msp = msp;
943 		zfs_range_tree_walk(msp->ms_allocatable, vdev_trim_range_add,
944 		    &ta);
945 		zfs_range_tree_vacate(msp->ms_trim, NULL, NULL);
946 		mutex_exit(&msp->ms_lock);
947 
948 		error = vdev_trim_ranges(&ta);
949 		metaslab_enable(msp, B_TRUE, B_FALSE);
950 		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
951 
952 		zfs_range_tree_vacate(ta.trim_tree, NULL, NULL);
953 		if (error != 0)
954 			break;
955 	}
956 
957 	spa_config_exit(spa, SCL_CONFIG, FTAG);
958 
959 	zfs_range_tree_destroy(ta.trim_tree);
960 
961 	mutex_enter(&vd->vdev_trim_lock);
962 	if (!vd->vdev_trim_exit_wanted) {
963 		if (vdev_writeable(vd)) {
964 			vdev_trim_change_state(vd, VDEV_TRIM_COMPLETE,
965 			    vd->vdev_trim_rate, vd->vdev_trim_partial,
966 			    vd->vdev_trim_secure);
967 		} else if (vd->vdev_faulted) {
968 			vdev_trim_change_state(vd, VDEV_TRIM_CANCELED,
969 			    vd->vdev_trim_rate, vd->vdev_trim_partial,
970 			    vd->vdev_trim_secure);
971 		}
972 	}
973 	ASSERT(vd->vdev_trim_thread != NULL || vd->vdev_trim_inflight[0] == 0);
974 
975 	/*
976 	 * Drop the vdev_trim_lock while we sync out the txg since it's
977 	 * possible that a device might be trying to come online and must
978 	 * check to see if it needs to restart a trim. That thread will be
979 	 * holding the spa_config_lock which would prevent the txg_wait_synced
980 	 * from completing.
981 	 */
982 	mutex_exit(&vd->vdev_trim_lock);
983 	txg_wait_synced(spa_get_dsl(spa), 0);
984 	mutex_enter(&vd->vdev_trim_lock);
985 
986 	vd->vdev_trim_thread = NULL;
987 	cv_broadcast(&vd->vdev_trim_cv);
988 	spa_notify_waiters(spa);
989 	mutex_exit(&vd->vdev_trim_lock);
990 
991 	thread_exit();
992 }
993 
994 /*
995  * Initiates a manual TRIM for the vdev_t.  Callers must hold vdev_trim_lock,
996  * the vdev_t must be a leaf and cannot already be manually trimming.
997  */
998 void
999 vdev_trim(vdev_t *vd, uint64_t rate, boolean_t partial, boolean_t secure)
1000 {
1001 	ASSERT(MUTEX_HELD(&vd->vdev_trim_lock));
1002 	ASSERT(vd->vdev_ops->vdev_op_leaf);
1003 	ASSERT(vdev_is_concrete(vd));
1004 	ASSERT0P(vd->vdev_trim_thread);
1005 	ASSERT(!vd->vdev_detached);
1006 	ASSERT(!vd->vdev_trim_exit_wanted);
1007 	ASSERT(!vd->vdev_top->vdev_removing);
1008 	ASSERT(!vd->vdev_rz_expanding);
1009 
1010 	vdev_trim_change_state(vd, VDEV_TRIM_ACTIVE, rate, partial, secure);
1011 	vd->vdev_trim_thread = thread_create(NULL, 0,
1012 	    vdev_trim_thread, vd, 0, &p0, TS_RUN, maxclsyspri);
1013 }
1014 
1015 /*
1016  * Wait for the trimming thread to be terminated (canceled or stopped).
1017  */
1018 static void
1019 vdev_trim_stop_wait_impl(vdev_t *vd)
1020 {
1021 	ASSERT(MUTEX_HELD(&vd->vdev_trim_lock));
1022 
1023 	while (vd->vdev_trim_thread != NULL)
1024 		cv_wait(&vd->vdev_trim_cv, &vd->vdev_trim_lock);
1025 
1026 	ASSERT0P(vd->vdev_trim_thread);
1027 	vd->vdev_trim_exit_wanted = B_FALSE;
1028 }
1029 
1030 /*
1031  * Wait for vdev trim threads which were listed to cleanly exit.
1032  */
1033 void
1034 vdev_trim_stop_wait(spa_t *spa, list_t *vd_list)
1035 {
1036 	(void) spa;
1037 	vdev_t *vd;
1038 
1039 	ASSERT(spa_namespace_held() ||
1040 	    spa->spa_export_thread == curthread);
1041 
1042 	while ((vd = list_remove_head(vd_list)) != NULL) {
1043 		mutex_enter(&vd->vdev_trim_lock);
1044 		vdev_trim_stop_wait_impl(vd);
1045 		mutex_exit(&vd->vdev_trim_lock);
1046 	}
1047 }
1048 
1049 /*
1050  * Stop trimming a device, with the resultant trimming state being tgt_state.
1051  * For blocking behavior pass NULL for vd_list.  Otherwise, when a list_t is
1052  * provided the stopping vdev is inserted in to the list.  Callers are then
1053  * required to call vdev_trim_stop_wait() to block for all the trim threads
1054  * to exit.  The caller must hold vdev_trim_lock and must not be writing to
1055  * the spa config, as the trimming thread may try to enter the config as a
1056  * reader before exiting.
1057  */
1058 void
1059 vdev_trim_stop(vdev_t *vd, vdev_trim_state_t tgt_state, list_t *vd_list)
1060 {
1061 	ASSERT(!spa_config_held(vd->vdev_spa, SCL_CONFIG|SCL_STATE, RW_WRITER));
1062 	ASSERT(MUTEX_HELD(&vd->vdev_trim_lock));
1063 	ASSERT(vd->vdev_ops->vdev_op_leaf);
1064 	ASSERT(vdev_is_concrete(vd));
1065 
1066 	/*
1067 	 * Allow cancel requests to proceed even if the trim thread has
1068 	 * stopped.
1069 	 */
1070 	if (vd->vdev_trim_thread == NULL && tgt_state != VDEV_TRIM_CANCELED)
1071 		return;
1072 
1073 	vdev_trim_change_state(vd, tgt_state, 0, 0, 0);
1074 	vd->vdev_trim_exit_wanted = B_TRUE;
1075 
1076 	if (vd_list == NULL) {
1077 		vdev_trim_stop_wait_impl(vd);
1078 	} else {
1079 		ASSERT(spa_namespace_held() ||
1080 		    vd->vdev_spa->spa_export_thread == curthread);
1081 		list_insert_tail(vd_list, vd);
1082 	}
1083 }
1084 
1085 /*
1086  * Requests that all listed vdevs stop trimming.
1087  */
1088 static void
1089 vdev_trim_stop_all_impl(vdev_t *vd, vdev_trim_state_t tgt_state,
1090     list_t *vd_list)
1091 {
1092 	if (vd->vdev_ops->vdev_op_leaf && vdev_is_concrete(vd)) {
1093 		mutex_enter(&vd->vdev_trim_lock);
1094 		vdev_trim_stop(vd, tgt_state, vd_list);
1095 		mutex_exit(&vd->vdev_trim_lock);
1096 		return;
1097 	}
1098 
1099 	for (uint64_t i = 0; i < vd->vdev_children; i++) {
1100 		vdev_trim_stop_all_impl(vd->vdev_child[i], tgt_state,
1101 		    vd_list);
1102 	}
1103 }
1104 
1105 /*
1106  * Convenience function to stop trimming of a vdev tree and set all trim
1107  * thread pointers to NULL.
1108  */
1109 void
1110 vdev_trim_stop_all(vdev_t *vd, vdev_trim_state_t tgt_state)
1111 {
1112 	spa_t *spa = vd->vdev_spa;
1113 	list_t vd_list;
1114 	vdev_t *vd_l2cache;
1115 
1116 	ASSERT(spa_namespace_held() ||
1117 	    spa->spa_export_thread == curthread);
1118 
1119 	list_create(&vd_list, sizeof (vdev_t),
1120 	    offsetof(vdev_t, vdev_trim_node));
1121 
1122 	vdev_trim_stop_all_impl(vd, tgt_state, &vd_list);
1123 
1124 	/*
1125 	 * Iterate over cache devices and request stop trimming the
1126 	 * whole device in case we export the pool or remove the cache
1127 	 * device prematurely.
1128 	 */
1129 	for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
1130 		vd_l2cache = spa->spa_l2cache.sav_vdevs[i];
1131 		vdev_trim_stop_all_impl(vd_l2cache, tgt_state, &vd_list);
1132 	}
1133 
1134 	vdev_trim_stop_wait(spa, &vd_list);
1135 
1136 	if (vd->vdev_spa->spa_sync_on) {
1137 		/* Make sure that our state has been synced to disk */
1138 		txg_wait_synced(spa_get_dsl(vd->vdev_spa), 0);
1139 	}
1140 
1141 	list_destroy(&vd_list);
1142 }
1143 
1144 /*
1145  * Conditionally restarts a manual TRIM given its on-disk state.
1146  */
1147 void
1148 vdev_trim_restart(vdev_t *vd)
1149 {
1150 	ASSERT(spa_namespace_held() ||
1151 	    vd->vdev_spa->spa_load_thread == curthread);
1152 	ASSERT(!spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER));
1153 
1154 	if (vd->vdev_leaf_zap != 0) {
1155 		mutex_enter(&vd->vdev_trim_lock);
1156 		uint64_t trim_state = VDEV_TRIM_NONE;
1157 		int err = zap_lookup(vd->vdev_spa->spa_meta_objset,
1158 		    vd->vdev_leaf_zap, VDEV_LEAF_ZAP_TRIM_STATE,
1159 		    sizeof (trim_state), 1, &trim_state);
1160 		ASSERT(err == 0 || err == ENOENT);
1161 		vd->vdev_trim_state = trim_state;
1162 
1163 		uint64_t timestamp = 0;
1164 		err = zap_lookup(vd->vdev_spa->spa_meta_objset,
1165 		    vd->vdev_leaf_zap, VDEV_LEAF_ZAP_TRIM_ACTION_TIME,
1166 		    sizeof (timestamp), 1, &timestamp);
1167 		ASSERT(err == 0 || err == ENOENT);
1168 		vd->vdev_trim_action_time = timestamp;
1169 
1170 		if ((vd->vdev_trim_state == VDEV_TRIM_SUSPENDED ||
1171 		    vd->vdev_offline) && !vd->vdev_top->vdev_rz_expanding) {
1172 			/* load progress for reporting, but don't resume */
1173 			VERIFY0(vdev_trim_load(vd));
1174 		} else if (vd->vdev_trim_state == VDEV_TRIM_ACTIVE &&
1175 		    vdev_writeable(vd) && !vd->vdev_top->vdev_removing &&
1176 		    !vd->vdev_top->vdev_rz_expanding &&
1177 		    vd->vdev_trim_thread == NULL) {
1178 			VERIFY0(vdev_trim_load(vd));
1179 			vdev_trim(vd, vd->vdev_trim_rate,
1180 			    vd->vdev_trim_partial, vd->vdev_trim_secure);
1181 		}
1182 
1183 		mutex_exit(&vd->vdev_trim_lock);
1184 	}
1185 
1186 	for (uint64_t i = 0; i < vd->vdev_children; i++) {
1187 		vdev_trim_restart(vd->vdev_child[i]);
1188 	}
1189 }
1190 
1191 /*
1192  * Used by the automatic TRIM when ZFS_DEBUG_TRIM is set to verify that
1193  * every TRIM range is contained within ms_allocatable.
1194  */
1195 static void
1196 vdev_trim_range_verify(void *arg, uint64_t start, uint64_t size)
1197 {
1198 	trim_args_t *ta = arg;
1199 	metaslab_t *msp = ta->trim_msp;
1200 
1201 	VERIFY3B(msp->ms_loaded, ==, B_TRUE);
1202 	VERIFY3U(msp->ms_disabled, >, 0);
1203 	VERIFY(zfs_range_tree_contains(msp->ms_allocatable, start, size));
1204 }
1205 
1206 /*
1207  * Each automatic TRIM thread is responsible for managing the trimming of a
1208  * top-level vdev in the pool.  No automatic TRIM state is maintained on-disk.
1209  *
1210  * N.B. This behavior is different from a manual TRIM where a thread
1211  * is created for each leaf vdev, instead of each top-level vdev.
1212  */
1213 static __attribute__((noreturn)) void
1214 vdev_autotrim_thread(void *arg)
1215 {
1216 	vdev_t *vd = arg;
1217 	spa_t *spa = vd->vdev_spa;
1218 	int shift = 0;
1219 
1220 	mutex_enter(&vd->vdev_autotrim_lock);
1221 	ASSERT3P(vd->vdev_top, ==, vd);
1222 	ASSERT3P(vd->vdev_autotrim_thread, !=, NULL);
1223 	mutex_exit(&vd->vdev_autotrim_lock);
1224 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
1225 
1226 	while (!vdev_autotrim_should_stop(vd)) {
1227 		int txgs_per_trim = MAX(zfs_trim_txg_batch, 1);
1228 		uint64_t extent_bytes_max = zfs_trim_extent_bytes_max;
1229 		uint64_t extent_bytes_min = zfs_trim_extent_bytes_min;
1230 
1231 		/*
1232 		 * All of the metaslabs are divided in to groups of size
1233 		 * num_metaslabs / zfs_trim_txg_batch.  Each of these groups
1234 		 * is composed of metaslabs which are spread evenly over the
1235 		 * device.
1236 		 *
1237 		 * For example, when zfs_trim_txg_batch = 32 (default) then
1238 		 * group 0 will contain metaslabs 0, 32, 64, ...;
1239 		 * group 1 will contain metaslabs 1, 33, 65, ...;
1240 		 * group 2 will contain metaslabs 2, 34, 66, ...; and so on.
1241 		 *
1242 		 * On each pass through the while() loop one of these groups
1243 		 * is selected.  This is accomplished by using a shift value
1244 		 * to select the starting metaslab, then striding over the
1245 		 * metaslabs using the zfs_trim_txg_batch size.  This is
1246 		 * done to accomplish two things.
1247 		 *
1248 		 * 1) By dividing the metaslabs in to groups, and making sure
1249 		 *    that each group takes a minimum of one txg to process.
1250 		 *    Then zfs_trim_txg_batch controls the minimum number of
1251 		 *    txgs which must occur before a metaslab is revisited.
1252 		 *
1253 		 * 2) Selecting non-consecutive metaslabs distributes the
1254 		 *    TRIM commands for a group evenly over the entire device.
1255 		 *    This can be advantageous for certain types of devices.
1256 		 */
1257 		for (uint64_t i = shift % txgs_per_trim; i < vd->vdev_ms_count;
1258 		    i += txgs_per_trim) {
1259 			metaslab_t *msp = vd->vdev_ms[i];
1260 			zfs_range_tree_t *trim_tree;
1261 			boolean_t issued_trim = B_FALSE;
1262 			boolean_t wait_aborted = B_FALSE;
1263 
1264 			spa_config_exit(spa, SCL_CONFIG, FTAG);
1265 			metaslab_disable(msp);
1266 			spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
1267 
1268 			mutex_enter(&msp->ms_lock);
1269 
1270 			/*
1271 			 * Skip the metaslab when it has never been allocated
1272 			 * or when there are no recent frees to trim.
1273 			 */
1274 			if (msp->ms_sm == NULL ||
1275 			    zfs_range_tree_is_empty(msp->ms_trim)) {
1276 				mutex_exit(&msp->ms_lock);
1277 				metaslab_enable(msp, B_FALSE, B_FALSE);
1278 				continue;
1279 			}
1280 
1281 			/*
1282 			 * Skip the metaslab when it has already been disabled.
1283 			 * This may happen when a manual TRIM or initialize
1284 			 * operation is running concurrently.  In the case
1285 			 * of a manual TRIM, the ms_trim tree will have been
1286 			 * vacated.  Only ranges added after the manual TRIM
1287 			 * disabled the metaslab will be included in the tree.
1288 			 * These will be processed when the automatic TRIM
1289 			 * next revisits this metaslab.
1290 			 */
1291 			if (msp->ms_disabled > 1) {
1292 				mutex_exit(&msp->ms_lock);
1293 				metaslab_enable(msp, B_FALSE, B_FALSE);
1294 				continue;
1295 			}
1296 
1297 			/*
1298 			 * Allocate an empty range tree which is swapped in
1299 			 * for the existing ms_trim tree while it is processed.
1300 			 */
1301 			trim_tree = zfs_range_tree_create_flags(
1302 			    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
1303 			    ZFS_RT_F_DYN_NAME,
1304 			    vdev_rt_name(vd, "autotrim_tree"));
1305 			zfs_range_tree_swap(&msp->ms_trim, &trim_tree);
1306 			ASSERT(zfs_range_tree_is_empty(msp->ms_trim));
1307 
1308 			/*
1309 			 * There are two cases when constructing the per-vdev
1310 			 * trim trees for a metaslab.  If the top-level vdev
1311 			 * has no children then it is also a leaf and should
1312 			 * be trimmed.  Otherwise our children are the leaves
1313 			 * and a trim tree should be constructed for each.
1314 			 */
1315 			trim_args_t *tap;
1316 			uint64_t children = vd->vdev_children;
1317 			if (children == 0) {
1318 				children = 1;
1319 				tap = kmem_zalloc(sizeof (trim_args_t) *
1320 				    children, KM_SLEEP);
1321 				tap[0].trim_vdev = vd;
1322 			} else {
1323 				tap = kmem_zalloc(sizeof (trim_args_t) *
1324 				    children, KM_SLEEP);
1325 
1326 				for (uint64_t c = 0; c < children; c++) {
1327 					tap[c].trim_vdev = vd->vdev_child[c];
1328 				}
1329 			}
1330 
1331 			for (uint64_t c = 0; c < children; c++) {
1332 				trim_args_t *ta = &tap[c];
1333 				vdev_t *cvd = ta->trim_vdev;
1334 
1335 				ta->trim_msp = msp;
1336 				ta->trim_extent_bytes_max = extent_bytes_max;
1337 				ta->trim_extent_bytes_min = extent_bytes_min;
1338 				ta->trim_type = TRIM_TYPE_AUTO;
1339 				ta->trim_flags = 0;
1340 
1341 				if (cvd->vdev_detached ||
1342 				    !vdev_writeable(cvd) ||
1343 				    !cvd->vdev_has_trim ||
1344 				    cvd->vdev_trim_thread != NULL) {
1345 					continue;
1346 				}
1347 
1348 				/*
1349 				 * When a device has an attached hot spare, or
1350 				 * is being replaced it will not be trimmed.
1351 				 * This is done to avoid adding additional
1352 				 * stress to a potentially unhealthy device,
1353 				 * and to minimize the required rebuild time.
1354 				 */
1355 				if (!cvd->vdev_ops->vdev_op_leaf)
1356 					continue;
1357 
1358 				ta->trim_tree = zfs_range_tree_create_flags(
1359 				    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
1360 				    ZFS_RT_F_DYN_NAME,
1361 				    vdev_rt_name(vd, "autotrim_tree"));
1362 				zfs_range_tree_walk(trim_tree,
1363 				    vdev_trim_range_add, ta);
1364 			}
1365 
1366 			mutex_exit(&msp->ms_lock);
1367 			spa_config_exit(spa, SCL_CONFIG, FTAG);
1368 
1369 			/*
1370 			 * Issue the TRIM I/Os for all ranges covered by the
1371 			 * TRIM trees.  These ranges are safe to TRIM because
1372 			 * no new allocations will be performed until the call
1373 			 * to metaslab_enabled() below.
1374 			 */
1375 			for (uint64_t c = 0; c < children; c++) {
1376 				trim_args_t *ta = &tap[c];
1377 
1378 				/*
1379 				 * Always yield to a manual TRIM if one has
1380 				 * been started for the child vdev.
1381 				 */
1382 				if (ta->trim_tree == NULL ||
1383 				    ta->trim_vdev->vdev_trim_thread != NULL) {
1384 					continue;
1385 				}
1386 
1387 				/*
1388 				 * After this point metaslab_enable() must be
1389 				 * called with the sync flag set.  This is done
1390 				 * here because vdev_trim_ranges() is allowed
1391 				 * to be interrupted (EINTR) before issuing all
1392 				 * of the required TRIM I/Os.
1393 				 */
1394 				issued_trim = B_TRUE;
1395 
1396 				int error = vdev_trim_ranges(ta);
1397 				if (error)
1398 					break;
1399 			}
1400 
1401 			/*
1402 			 * Verify every range which was trimmed is still
1403 			 * contained within the ms_allocatable tree.
1404 			 */
1405 			if (zfs_flags & ZFS_DEBUG_TRIM) {
1406 				mutex_enter(&msp->ms_lock);
1407 				VERIFY0(metaslab_load(msp));
1408 				VERIFY3P(tap[0].trim_msp, ==, msp);
1409 				zfs_range_tree_walk(trim_tree,
1410 				    vdev_trim_range_verify, &tap[0]);
1411 				mutex_exit(&msp->ms_lock);
1412 			}
1413 
1414 			zfs_range_tree_vacate(trim_tree, NULL, NULL);
1415 			zfs_range_tree_destroy(trim_tree);
1416 
1417 			/*
1418 			 * Wait for couples of kicks, to ensure the trim io is
1419 			 * synced. If the wait is aborted due to
1420 			 * vdev_autotrim_exit_wanted, we need to signal
1421 			 * metaslab_enable() to wait for sync.
1422 			 */
1423 			if (issued_trim) {
1424 				wait_aborted = vdev_autotrim_wait_kick(vd,
1425 				    TXG_CONCURRENT_STATES + TXG_DEFER_SIZE);
1426 			}
1427 
1428 			metaslab_enable(msp, wait_aborted, B_FALSE);
1429 			spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
1430 
1431 			for (uint64_t c = 0; c < children; c++) {
1432 				trim_args_t *ta = &tap[c];
1433 
1434 				if (ta->trim_tree == NULL)
1435 					continue;
1436 
1437 				zfs_range_tree_vacate(ta->trim_tree, NULL,
1438 				    NULL);
1439 				zfs_range_tree_destroy(ta->trim_tree);
1440 			}
1441 
1442 			kmem_free(tap, sizeof (trim_args_t) * children);
1443 
1444 			if (vdev_autotrim_should_stop(vd))
1445 				break;
1446 		}
1447 
1448 		spa_config_exit(spa, SCL_CONFIG, FTAG);
1449 
1450 		vdev_autotrim_wait_kick(vd, 1);
1451 
1452 		shift++;
1453 		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
1454 	}
1455 
1456 	for (uint64_t c = 0; c < vd->vdev_children; c++) {
1457 		vdev_t *cvd = vd->vdev_child[c];
1458 		mutex_enter(&cvd->vdev_trim_io_lock);
1459 
1460 		while (cvd->vdev_trim_inflight[1] > 0) {
1461 			cv_wait(&cvd->vdev_trim_io_cv,
1462 			    &cvd->vdev_trim_io_lock);
1463 		}
1464 		mutex_exit(&cvd->vdev_trim_io_lock);
1465 	}
1466 
1467 	spa_config_exit(spa, SCL_CONFIG, FTAG);
1468 
1469 	/*
1470 	 * When exiting because the autotrim property was set to off, then
1471 	 * abandon any unprocessed ms_trim ranges to reclaim the memory.
1472 	 */
1473 	if (spa_get_autotrim(spa) == SPA_AUTOTRIM_OFF) {
1474 		for (uint64_t i = 0; i < vd->vdev_ms_count; i++) {
1475 			metaslab_t *msp = vd->vdev_ms[i];
1476 
1477 			mutex_enter(&msp->ms_lock);
1478 			zfs_range_tree_vacate(msp->ms_trim, NULL, NULL);
1479 			mutex_exit(&msp->ms_lock);
1480 		}
1481 	}
1482 
1483 	mutex_enter(&vd->vdev_autotrim_lock);
1484 	ASSERT(vd->vdev_autotrim_thread != NULL);
1485 	vd->vdev_autotrim_thread = NULL;
1486 	cv_broadcast(&vd->vdev_autotrim_cv);
1487 	mutex_exit(&vd->vdev_autotrim_lock);
1488 
1489 	thread_exit();
1490 }
1491 
1492 /*
1493  * Starts an autotrim thread, if needed, for each top-level vdev which can be
1494  * trimmed.  A top-level vdev which has been evacuated will never be trimmed.
1495  */
1496 void
1497 vdev_autotrim(spa_t *spa)
1498 {
1499 	vdev_t *root_vd = spa->spa_root_vdev;
1500 
1501 	for (uint64_t i = 0; i < root_vd->vdev_children; i++) {
1502 		vdev_t *tvd = root_vd->vdev_child[i];
1503 
1504 		mutex_enter(&tvd->vdev_autotrim_lock);
1505 		if (vdev_writeable(tvd) && !tvd->vdev_removing &&
1506 		    tvd->vdev_autotrim_thread == NULL &&
1507 		    !tvd->vdev_rz_expanding) {
1508 			ASSERT3P(tvd->vdev_top, ==, tvd);
1509 
1510 			tvd->vdev_autotrim_thread = thread_create(NULL, 0,
1511 			    vdev_autotrim_thread, tvd, 0, &p0, TS_RUN,
1512 			    maxclsyspri);
1513 			ASSERT(tvd->vdev_autotrim_thread != NULL);
1514 		}
1515 		mutex_exit(&tvd->vdev_autotrim_lock);
1516 	}
1517 }
1518 
1519 /*
1520  * Wait for the vdev_autotrim_thread associated with the passed top-level
1521  * vdev to be terminated (canceled or stopped).
1522  */
1523 void
1524 vdev_autotrim_stop_wait(vdev_t *tvd)
1525 {
1526 	mutex_enter(&tvd->vdev_autotrim_lock);
1527 	if (tvd->vdev_autotrim_thread != NULL) {
1528 		tvd->vdev_autotrim_exit_wanted = B_TRUE;
1529 		cv_broadcast(&tvd->vdev_autotrim_kick_cv);
1530 		cv_wait(&tvd->vdev_autotrim_cv,
1531 		    &tvd->vdev_autotrim_lock);
1532 
1533 		ASSERT0P(tvd->vdev_autotrim_thread);
1534 		tvd->vdev_autotrim_exit_wanted = B_FALSE;
1535 	}
1536 	mutex_exit(&tvd->vdev_autotrim_lock);
1537 }
1538 
1539 void
1540 vdev_autotrim_kick(spa_t *spa)
1541 {
1542 	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
1543 
1544 	vdev_t *root_vd = spa->spa_root_vdev;
1545 	vdev_t *tvd;
1546 
1547 	for (uint64_t i = 0; i < root_vd->vdev_children; i++) {
1548 		tvd = root_vd->vdev_child[i];
1549 
1550 		mutex_enter(&tvd->vdev_autotrim_lock);
1551 		if (tvd->vdev_autotrim_thread != NULL)
1552 			cv_broadcast(&tvd->vdev_autotrim_kick_cv);
1553 		mutex_exit(&tvd->vdev_autotrim_lock);
1554 	}
1555 }
1556 
1557 /*
1558  * Wait for all of the vdev_autotrim_thread associated with the pool to
1559  * be terminated (canceled or stopped).
1560  */
1561 void
1562 vdev_autotrim_stop_all(spa_t *spa)
1563 {
1564 	vdev_t *root_vd = spa->spa_root_vdev;
1565 
1566 	for (uint64_t i = 0; i < root_vd->vdev_children; i++)
1567 		vdev_autotrim_stop_wait(root_vd->vdev_child[i]);
1568 }
1569 
1570 /*
1571  * Conditionally restart all of the vdev_autotrim_thread's for the pool.
1572  */
1573 void
1574 vdev_autotrim_restart(spa_t *spa)
1575 {
1576 	ASSERT(spa_namespace_held() ||
1577 	    spa->spa_load_thread == curthread);
1578 	if (spa->spa_autotrim)
1579 		vdev_autotrim(spa);
1580 }
1581 
1582 static __attribute__((noreturn)) void
1583 vdev_trim_l2arc_thread(void *arg)
1584 {
1585 	vdev_t		*vd = arg;
1586 	spa_t		*spa = vd->vdev_spa;
1587 	l2arc_dev_t	*dev = l2arc_vdev_get(vd);
1588 	trim_args_t	ta = {0};
1589 	zfs_range_seg64_t 	physical_rs;
1590 
1591 	ASSERT(vdev_is_concrete(vd));
1592 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
1593 
1594 	vd->vdev_trim_last_offset = 0;
1595 	vd->vdev_trim_rate = 0;
1596 	vd->vdev_trim_partial = 0;
1597 	vd->vdev_trim_secure = 0;
1598 
1599 	ta.trim_vdev = vd;
1600 	ta.trim_tree = zfs_range_tree_create_flags(
1601 	    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
1602 	    ZFS_RT_F_DYN_NAME, vdev_rt_name(vd, "trim_tree"));
1603 	ta.trim_type = TRIM_TYPE_MANUAL;
1604 	ta.trim_extent_bytes_max = zfs_trim_extent_bytes_max;
1605 	ta.trim_extent_bytes_min = SPA_MINBLOCKSIZE;
1606 	ta.trim_flags = 0;
1607 
1608 	physical_rs.rs_start = vd->vdev_trim_bytes_done = 0;
1609 	physical_rs.rs_end = vd->vdev_trim_bytes_est =
1610 	    vdev_get_min_asize(vd);
1611 
1612 	zfs_range_tree_add(ta.trim_tree, physical_rs.rs_start,
1613 	    physical_rs.rs_end - physical_rs.rs_start);
1614 
1615 	mutex_enter(&vd->vdev_trim_lock);
1616 	vdev_trim_change_state(vd, VDEV_TRIM_ACTIVE, 0, 0, 0);
1617 	mutex_exit(&vd->vdev_trim_lock);
1618 
1619 	(void) vdev_trim_ranges(&ta);
1620 
1621 	spa_config_exit(spa, SCL_CONFIG, FTAG);
1622 	mutex_enter(&vd->vdev_trim_io_lock);
1623 	while (vd->vdev_trim_inflight[TRIM_TYPE_MANUAL] > 0) {
1624 		cv_wait(&vd->vdev_trim_io_cv, &vd->vdev_trim_io_lock);
1625 	}
1626 	mutex_exit(&vd->vdev_trim_io_lock);
1627 
1628 	zfs_range_tree_vacate(ta.trim_tree, NULL, NULL);
1629 	zfs_range_tree_destroy(ta.trim_tree);
1630 
1631 	mutex_enter(&vd->vdev_trim_lock);
1632 	if (!vd->vdev_trim_exit_wanted && vdev_writeable(vd)) {
1633 		vdev_trim_change_state(vd, VDEV_TRIM_COMPLETE,
1634 		    vd->vdev_trim_rate, vd->vdev_trim_partial,
1635 		    vd->vdev_trim_secure);
1636 	}
1637 	ASSERT(vd->vdev_trim_thread != NULL ||
1638 	    vd->vdev_trim_inflight[TRIM_TYPE_MANUAL] == 0);
1639 
1640 	/*
1641 	 * Drop the vdev_trim_lock while we sync out the txg since it's
1642 	 * possible that a device might be trying to come online and
1643 	 * must check to see if it needs to restart a trim. That thread
1644 	 * will be holding the spa_config_lock which would prevent the
1645 	 * txg_wait_synced from completing. Same strategy as in
1646 	 * vdev_trim_thread().
1647 	 */
1648 	mutex_exit(&vd->vdev_trim_lock);
1649 	txg_wait_synced(spa_get_dsl(vd->vdev_spa), 0);
1650 	mutex_enter(&vd->vdev_trim_lock);
1651 
1652 	/*
1653 	 * Update the header of the cache device here, before
1654 	 * broadcasting vdev_trim_cv which may lead to the removal
1655 	 * of the device. The same applies for setting l2ad_trim_all to
1656 	 * false.
1657 	 */
1658 	spa_config_enter(vd->vdev_spa, SCL_L2ARC, vd,
1659 	    RW_READER);
1660 	memset(dev->l2ad_dev_hdr, 0, dev->l2ad_dev_hdr_asize);
1661 	l2arc_dev_hdr_update(dev);
1662 	spa_config_exit(vd->vdev_spa, SCL_L2ARC, vd);
1663 
1664 	vd->vdev_trim_thread = NULL;
1665 	if (vd->vdev_trim_state == VDEV_TRIM_COMPLETE)
1666 		dev->l2ad_trim_all = B_FALSE;
1667 
1668 	cv_broadcast(&vd->vdev_trim_cv);
1669 	mutex_exit(&vd->vdev_trim_lock);
1670 
1671 	thread_exit();
1672 }
1673 
1674 /*
1675  * Punches out TRIM threads for the L2ARC devices in a spa and assigns them
1676  * to vd->vdev_trim_thread variable. This facilitates the management of
1677  * trimming the whole cache device using TRIM_TYPE_MANUAL upon addition
1678  * to a pool or pool creation or when the header of the device is invalid.
1679  */
1680 void
1681 vdev_trim_l2arc(spa_t *spa)
1682 {
1683 	ASSERT(spa_namespace_held());
1684 
1685 	/*
1686 	 * Locate the spa's l2arc devices and kick off TRIM threads.
1687 	 */
1688 	for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
1689 		vdev_t *vd = spa->spa_l2cache.sav_vdevs[i];
1690 		l2arc_dev_t *dev = l2arc_vdev_get(vd);
1691 
1692 		if (dev == NULL || !dev->l2ad_trim_all) {
1693 			/*
1694 			 * Don't attempt TRIM if the vdev is UNAVAIL or if the
1695 			 * cache device was not marked for whole device TRIM
1696 			 * (ie l2arc_trim_ahead = 0, or the L2ARC device header
1697 			 * is valid with trim_state = VDEV_TRIM_COMPLETE and
1698 			 * l2ad_log_entries > 0).
1699 			 */
1700 			continue;
1701 		}
1702 
1703 		mutex_enter(&vd->vdev_trim_lock);
1704 		ASSERT(vd->vdev_ops->vdev_op_leaf);
1705 		ASSERT(vdev_is_concrete(vd));
1706 		ASSERT0P(vd->vdev_trim_thread);
1707 		ASSERT(!vd->vdev_detached);
1708 		ASSERT(!vd->vdev_trim_exit_wanted);
1709 		ASSERT(!vd->vdev_top->vdev_removing);
1710 		vdev_trim_change_state(vd, VDEV_TRIM_ACTIVE, 0, 0, 0);
1711 		vd->vdev_trim_thread = thread_create(NULL, 0,
1712 		    vdev_trim_l2arc_thread, vd, 0, &p0, TS_RUN, maxclsyspri);
1713 		mutex_exit(&vd->vdev_trim_lock);
1714 	}
1715 }
1716 
1717 /*
1718  * A wrapper which calls vdev_trim_ranges(). It is intended to be called
1719  * on leaf vdevs.
1720  */
1721 int
1722 vdev_trim_simple(vdev_t *vd, uint64_t start, uint64_t size)
1723 {
1724 	trim_args_t ta = {0};
1725 	zfs_range_seg64_t physical_rs;
1726 	int error;
1727 	physical_rs.rs_start = start;
1728 	physical_rs.rs_end = start + size;
1729 
1730 	ASSERT(vdev_is_concrete(vd));
1731 	ASSERT(vd->vdev_ops->vdev_op_leaf);
1732 	ASSERT(!vd->vdev_detached);
1733 	ASSERT(!vd->vdev_top->vdev_removing);
1734 	ASSERT(!vd->vdev_top->vdev_rz_expanding);
1735 
1736 	ta.trim_vdev = vd;
1737 	ta.trim_tree = zfs_range_tree_create_flags(
1738 	    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
1739 	    ZFS_RT_F_DYN_NAME, vdev_rt_name(vd, "trim_tree"));
1740 	ta.trim_type = TRIM_TYPE_SIMPLE;
1741 	ta.trim_extent_bytes_max = zfs_trim_extent_bytes_max;
1742 	ta.trim_extent_bytes_min = SPA_MINBLOCKSIZE;
1743 	ta.trim_flags = 0;
1744 
1745 	ASSERT3U(physical_rs.rs_end, >=, physical_rs.rs_start);
1746 
1747 	if (physical_rs.rs_end > physical_rs.rs_start) {
1748 		zfs_range_tree_add(ta.trim_tree, physical_rs.rs_start,
1749 		    physical_rs.rs_end - physical_rs.rs_start);
1750 	} else {
1751 		ASSERT3U(physical_rs.rs_end, ==, physical_rs.rs_start);
1752 	}
1753 
1754 	error = vdev_trim_ranges(&ta);
1755 
1756 	mutex_enter(&vd->vdev_trim_io_lock);
1757 	while (vd->vdev_trim_inflight[TRIM_TYPE_SIMPLE] > 0) {
1758 		cv_wait(&vd->vdev_trim_io_cv, &vd->vdev_trim_io_lock);
1759 	}
1760 	mutex_exit(&vd->vdev_trim_io_lock);
1761 
1762 	zfs_range_tree_vacate(ta.trim_tree, NULL, NULL);
1763 	zfs_range_tree_destroy(ta.trim_tree);
1764 
1765 	return (error);
1766 }
1767 
1768 EXPORT_SYMBOL(vdev_trim);
1769 EXPORT_SYMBOL(vdev_trim_stop);
1770 EXPORT_SYMBOL(vdev_trim_stop_all);
1771 EXPORT_SYMBOL(vdev_trim_stop_wait);
1772 EXPORT_SYMBOL(vdev_trim_restart);
1773 EXPORT_SYMBOL(vdev_autotrim);
1774 EXPORT_SYMBOL(vdev_autotrim_stop_all);
1775 EXPORT_SYMBOL(vdev_autotrim_stop_wait);
1776 EXPORT_SYMBOL(vdev_autotrim_restart);
1777 EXPORT_SYMBOL(vdev_trim_l2arc);
1778 EXPORT_SYMBOL(vdev_trim_simple);
1779 
1780 ZFS_MODULE_PARAM(zfs_trim, zfs_trim_, extent_bytes_max, UINT, ZMOD_RW,
1781 	"Max size of TRIM commands, larger will be split");
1782 
1783 ZFS_MODULE_PARAM(zfs_trim, zfs_trim_, extent_bytes_min, UINT, ZMOD_RW,
1784 	"Min size of TRIM commands, smaller will be skipped");
1785 
1786 ZFS_MODULE_PARAM(zfs_trim, zfs_trim_, metaslab_skip, UINT, ZMOD_RW,
1787 	"Skip metaslabs which have never been initialized");
1788 
1789 ZFS_MODULE_PARAM(zfs_trim, zfs_trim_, txg_batch, UINT, ZMOD_RW,
1790 	"Min number of txgs to aggregate frees before issuing TRIM");
1791 
1792 ZFS_MODULE_PARAM(zfs_trim, zfs_trim_, queue_limit, UINT, ZMOD_RW,
1793 	"Max queued TRIMs outstanding per leaf vdev");
1794