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