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