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