xref: /linux/fs/xfs/xfs_zone_alloc.c (revision 912a5b8e344ad1e3cb6aefedf243404d522ad822)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2023-2025 Christoph Hellwig.
4  * Copyright (c) 2024-2025, Western Digital Corporation or its affiliates.
5  */
6 #include "xfs_platform.h"
7 #include "xfs_shared.h"
8 #include "xfs_format.h"
9 #include "xfs_log_format.h"
10 #include "xfs_error.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_mount.h"
13 #include "xfs_inode.h"
14 #include "xfs_iomap.h"
15 #include "xfs_trans.h"
16 #include "xfs_alloc.h"
17 #include "xfs_bmap.h"
18 #include "xfs_bmap_btree.h"
19 #include "xfs_trans_space.h"
20 #include "xfs_refcount.h"
21 #include "xfs_rtbitmap.h"
22 #include "xfs_rtrmap_btree.h"
23 #include "xfs_zone_alloc.h"
24 #include "xfs_sysfs.h"
25 #include "xfs_zone_priv.h"
26 #include "xfs_zones.h"
27 #include "xfs_trace.h"
28 #include "xfs_mru_cache.h"
29 
30 static void
31 xfs_open_zone_free_rcu(
32 	struct callback_head	*cb)
33 {
34 	struct xfs_open_zone	*oz = container_of(cb, typeof(*oz), oz_rcu);
35 
36 	xfs_rtgroup_rele(oz->oz_rtg);
37 	kfree(oz);
38 }
39 
40 void
41 xfs_open_zone_put(
42 	struct xfs_open_zone	*oz)
43 {
44 	if (atomic_dec_and_test(&oz->oz_ref))
45 		call_rcu(&oz->oz_rcu, xfs_open_zone_free_rcu);
46 }
47 
48 static inline uint32_t
49 xfs_zone_bucket(
50 	struct xfs_mount	*mp,
51 	uint32_t		used_blocks)
52 {
53 	return XFS_ZONE_USED_BUCKETS * used_blocks /
54 			mp->m_groups[XG_TYPE_RTG].blocks;
55 }
56 
57 static inline void
58 xfs_zone_add_to_bucket(
59 	struct xfs_zone_info	*zi,
60 	xfs_rgnumber_t		rgno,
61 	uint32_t		to_bucket)
62 {
63 	__set_bit(rgno, zi->zi_used_bucket_bitmap[to_bucket]);
64 	zi->zi_used_bucket_entries[to_bucket]++;
65 }
66 
67 static inline void
68 xfs_zone_remove_from_bucket(
69 	struct xfs_zone_info	*zi,
70 	xfs_rgnumber_t		rgno,
71 	uint32_t		from_bucket)
72 {
73 	__clear_bit(rgno, zi->zi_used_bucket_bitmap[from_bucket]);
74 	zi->zi_used_bucket_entries[from_bucket]--;
75 }
76 
77 static void
78 xfs_zone_account_reclaimable(
79 	struct xfs_rtgroup	*rtg,
80 	uint32_t		freed)
81 {
82 	struct xfs_group	*xg = rtg_group(rtg);
83 	struct xfs_mount	*mp = rtg_mount(rtg);
84 	struct xfs_zone_info	*zi = mp->m_zone_info;
85 	uint32_t		used = rtg_rmap(rtg)->i_used_blocks;
86 	xfs_rgnumber_t		rgno = rtg_rgno(rtg);
87 	uint32_t		from_bucket = xfs_zone_bucket(mp, used + freed);
88 	uint32_t		to_bucket = xfs_zone_bucket(mp, used);
89 	bool			was_full = (used + freed == rtg_blocks(rtg));
90 
91 	/*
92 	 * This can be called from log recovery, where the zone_info structure
93 	 * hasn't been allocated yet.  Skip all work as xfs_mount_zones will
94 	 * add the zones to the right buckets before the file systems becomes
95 	 * active.
96 	 */
97 	if (!zi)
98 		return;
99 
100 	if (!used) {
101 		/*
102 		 * The zone is now empty, remove it from the bottom bucket and
103 		 * trigger a reset.
104 		 */
105 		trace_xfs_zone_emptied(rtg);
106 
107 		spin_lock(&zi->zi_used_buckets_lock);
108 		if (!was_full)
109 			xfs_zone_remove_from_bucket(zi, rgno, from_bucket);
110 		spin_unlock(&zi->zi_used_buckets_lock);
111 
112 		spin_lock(&zi->zi_reset_list_lock);
113 		xg->xg_next_reset = zi->zi_reset_list;
114 		zi->zi_reset_list = xg;
115 		spin_unlock(&zi->zi_reset_list_lock);
116 
117 		if (zi->zi_gc_thread)
118 			wake_up_process(zi->zi_gc_thread);
119 	} else if (was_full) {
120 		/*
121 		 * The zone transitioned from full, mark it up as reclaimable
122 		 * and wake up GC which might be waiting for zones to reclaim.
123 		 */
124 		spin_lock(&zi->zi_used_buckets_lock);
125 		xfs_zone_add_to_bucket(zi, rgno, to_bucket);
126 		spin_unlock(&zi->zi_used_buckets_lock);
127 
128 		if (zi->zi_gc_thread && xfs_zoned_need_gc(mp))
129 			wake_up_process(zi->zi_gc_thread);
130 	} else if (to_bucket != from_bucket) {
131 		/*
132 		 * Move the zone to a new bucket if it dropped below the
133 		 * threshold.
134 		 */
135 		spin_lock(&zi->zi_used_buckets_lock);
136 		xfs_zone_add_to_bucket(zi, rgno, to_bucket);
137 		xfs_zone_remove_from_bucket(zi, rgno, from_bucket);
138 		spin_unlock(&zi->zi_used_buckets_lock);
139 	}
140 }
141 
142 /*
143  * Check if we have any zones that can be reclaimed by looking at the entry
144  * counters for the zone buckets.
145  */
146 bool
147 xfs_zoned_have_reclaimable(
148 	struct xfs_zone_info	*zi)
149 {
150 	int i;
151 
152 	spin_lock(&zi->zi_used_buckets_lock);
153 	for (i = 0; i < XFS_ZONE_USED_BUCKETS; i++) {
154 		if (zi->zi_used_bucket_entries[i]) {
155 			spin_unlock(&zi->zi_used_buckets_lock);
156 			return true;
157 		}
158 	}
159 	spin_unlock(&zi->zi_used_buckets_lock);
160 
161 	return false;
162 }
163 
164 static void
165 xfs_open_zone_mark_full(
166 	struct xfs_open_zone	*oz)
167 {
168 	struct xfs_rtgroup	*rtg = oz->oz_rtg;
169 	struct xfs_mount	*mp = rtg_mount(rtg);
170 	struct xfs_zone_info	*zi = mp->m_zone_info;
171 	uint32_t		used = rtg_rmap(rtg)->i_used_blocks;
172 
173 	trace_xfs_zone_full(rtg);
174 
175 	WRITE_ONCE(rtg->rtg_open_zone, NULL);
176 
177 	spin_lock(&zi->zi_open_zones_lock);
178 	if (oz->oz_is_gc)
179 		zi->zi_nr_open_gc_zones--;
180 	else
181 		zi->zi_nr_open_zones--;
182 	list_del_init(&oz->oz_entry);
183 	spin_unlock(&zi->zi_open_zones_lock);
184 
185 	if (oz->oz_is_gc)
186 		wake_up_process(zi->zi_gc_thread);
187 	else
188 		wake_up_all(&zi->zi_zone_wait);
189 
190 	if (used < rtg_blocks(rtg))
191 		xfs_zone_account_reclaimable(rtg, rtg_blocks(rtg) - used);
192 	xfs_open_zone_put(oz);
193 }
194 
195 static inline void
196 xfs_zone_inc_written(
197 	struct xfs_open_zone	*oz,
198 	xfs_filblks_t		len)
199 {
200 	xfs_assert_ilocked(rtg_rmap(oz->oz_rtg), XFS_ILOCK_EXCL);
201 
202 	oz->oz_written += len;
203 	if (oz->oz_written == rtg_blocks(oz->oz_rtg))
204 		xfs_open_zone_mark_full(oz);
205 }
206 
207 /*
208  * Called for blocks that have been written to disk, but not actually linked to
209  * an inode, which can happen when garbage collection races with user data
210  * writes to a file.
211  */
212 static void
213 xfs_zone_skip_blocks(
214 	struct xfs_open_zone	*oz,
215 	xfs_filblks_t		len)
216 {
217 	struct xfs_rtgroup	*rtg = oz->oz_rtg;
218 
219 	trace_xfs_zone_skip_blocks(oz, 0, len);
220 
221 	xfs_rtgroup_lock(rtg, XFS_RTGLOCK_RMAP);
222 	xfs_zone_inc_written(oz, len);
223 	xfs_rtgroup_unlock(rtg, XFS_RTGLOCK_RMAP);
224 
225 	xfs_add_frextents(rtg_mount(rtg), len);
226 }
227 
228 static int
229 xfs_zoned_map_extent(
230 	struct xfs_trans	*tp,
231 	struct xfs_inode	*ip,
232 	struct xfs_bmbt_irec	*new,
233 	struct xfs_open_zone	*oz,
234 	xfs_fsblock_t		old_startblock)
235 {
236 	struct xfs_bmbt_irec	data;
237 	struct xfs_rtgroup	*rtg = oz->oz_rtg;
238 	struct xfs_inode	*rmapip = rtg_rmap(rtg);
239 	int			nmaps = 1;
240 	int			error;
241 
242 	/* Grab the corresponding mapping in the data fork. */
243 	error = xfs_bmapi_read(ip, new->br_startoff, new->br_blockcount, &data,
244 			       &nmaps, 0);
245 	if (error)
246 		return error;
247 
248 	/*
249 	 * Cap the update to the existing extent in the data fork because we can
250 	 * only overwrite one extent at a time.
251 	 */
252 	ASSERT(new->br_blockcount >= data.br_blockcount);
253 	new->br_blockcount = data.br_blockcount;
254 
255 	/*
256 	 * If a data write raced with this GC write, keep the existing data in
257 	 * the data fork, mark our newly written GC extent as reclaimable, then
258 	 * move on to the next extent.
259 	 *
260 	 * Note that this can also happen when racing with operations that do
261 	 * not actually invalidate the data, but just move it to a different
262 	 * inode (XFS_IOC_EXCHANGE_RANGE), or to a different offset inside the
263 	 * inode (FALLOC_FL_COLLAPSE_RANGE / FALLOC_FL_INSERT_RANGE).  If the
264 	 * data was just moved around, GC fails to free the zone, but the zone
265 	 * becomes a GC candidate again as soon as all previous GC I/O has
266 	 * finished and these blocks will be moved out eventually.
267 	 */
268 	if (old_startblock != NULLFSBLOCK &&
269 	    old_startblock != data.br_startblock)
270 		goto skip;
271 
272 	trace_xfs_reflink_cow_remap_from(ip, new);
273 	trace_xfs_reflink_cow_remap_to(ip, &data);
274 
275 	error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK,
276 			XFS_IEXT_REFLINK_END_COW_CNT);
277 	if (error)
278 		return error;
279 
280 	if (data.br_startblock != HOLESTARTBLOCK) {
281 		ASSERT(data.br_startblock != DELAYSTARTBLOCK);
282 		ASSERT(!isnullstartblock(data.br_startblock));
283 
284 		xfs_bmap_unmap_extent(tp, ip, XFS_DATA_FORK, &data);
285 		if (xfs_is_reflink_inode(ip)) {
286 			xfs_refcount_decrease_extent(tp, true, &data);
287 		} else {
288 			error = xfs_free_extent_later(tp, data.br_startblock,
289 					data.br_blockcount, NULL,
290 					XFS_AG_RESV_NONE,
291 					XFS_FREE_EXTENT_REALTIME);
292 			if (error)
293 				return error;
294 		}
295 	}
296 
297 	trace_xfs_zone_record_blocks(oz,
298 		xfs_rtb_to_rgbno(tp->t_mountp, new->br_startblock),
299 		new->br_blockcount);
300 	xfs_rtgroup_lock(rtg, XFS_RTGLOCK_RMAP);
301 	xfs_rtgroup_trans_join(tp, rtg, XFS_RTGLOCK_RMAP);
302 	rmapip->i_used_blocks += new->br_blockcount;
303 	ASSERT(rmapip->i_used_blocks <= rtg_blocks(rtg));
304 	xfs_zone_inc_written(oz, new->br_blockcount);
305 	xfs_trans_log_inode(tp, rmapip, XFS_ILOG_CORE);
306 
307 	/* Map the new blocks into the data fork. */
308 	xfs_bmap_map_extent(tp, ip, XFS_DATA_FORK, new);
309 	return 0;
310 
311 skip:
312 	trace_xfs_reflink_cow_remap_skip(ip, new);
313 	xfs_zone_skip_blocks(oz, new->br_blockcount);
314 	return 0;
315 }
316 
317 int
318 xfs_zoned_end_io(
319 	struct xfs_inode	*ip,
320 	xfs_off_t		offset,
321 	xfs_off_t		count,
322 	xfs_daddr_t		daddr,
323 	struct xfs_open_zone	*oz,
324 	xfs_fsblock_t		old_startblock)
325 {
326 	struct xfs_mount	*mp = ip->i_mount;
327 	xfs_fileoff_t		end_fsb = XFS_B_TO_FSB(mp, offset + count);
328 	struct xfs_bmbt_irec	new = {
329 		.br_startoff	= XFS_B_TO_FSBT(mp, offset),
330 		.br_startblock	= xfs_daddr_to_rtb(mp, daddr),
331 		.br_state	= XFS_EXT_NORM,
332 	};
333 	unsigned int		resblks =
334 		XFS_EXTENTADD_SPACE_RES(mp, XFS_DATA_FORK);
335 	struct xfs_trans	*tp;
336 	int			error;
337 
338 	if (xfs_is_shutdown(mp))
339 		return -EIO;
340 
341 	while (new.br_startoff < end_fsb) {
342 		new.br_blockcount = end_fsb - new.br_startoff;
343 
344 		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks, 0,
345 				XFS_TRANS_RESERVE | XFS_TRANS_RES_FDBLKS, &tp);
346 		if (error)
347 			return error;
348 		xfs_ilock(ip, XFS_ILOCK_EXCL);
349 		xfs_trans_ijoin(tp, ip, 0);
350 
351 		error = xfs_zoned_map_extent(tp, ip, &new, oz, old_startblock);
352 		if (error)
353 			xfs_trans_cancel(tp);
354 		else
355 			error = xfs_trans_commit(tp);
356 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
357 		if (error)
358 			return error;
359 
360 		new.br_startoff += new.br_blockcount;
361 		new.br_startblock += new.br_blockcount;
362 		if (old_startblock != NULLFSBLOCK)
363 			old_startblock += new.br_blockcount;
364 	}
365 
366 	return 0;
367 }
368 
369 /*
370  * "Free" blocks allocated in a zone.
371  *
372  * Just decrement the used blocks counter and report the space as freed.
373  */
374 int
375 xfs_zone_free_blocks(
376 	struct xfs_trans	*tp,
377 	struct xfs_rtgroup	*rtg,
378 	xfs_fsblock_t		fsbno,
379 	xfs_filblks_t		len)
380 {
381 	struct xfs_mount	*mp = tp->t_mountp;
382 	struct xfs_inode	*rmapip = rtg_rmap(rtg);
383 
384 	xfs_assert_ilocked(rmapip, XFS_ILOCK_EXCL);
385 
386 	if (len > rmapip->i_used_blocks) {
387 		xfs_err(mp,
388 "trying to free more blocks (%lld) than used counter (%u).",
389 			len, rmapip->i_used_blocks);
390 		ASSERT(len <= rmapip->i_used_blocks);
391 		xfs_rtginode_mark_sick(rtg, XFS_RTGI_RMAP);
392 		xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
393 		return -EFSCORRUPTED;
394 	}
395 
396 	trace_xfs_zone_free_blocks(rtg, xfs_rtb_to_rgbno(mp, fsbno), len);
397 
398 	rmapip->i_used_blocks -= len;
399 	/*
400 	 * Don't add open zones to the reclaimable buckets.  The I/O completion
401 	 * for writing the last block will take care of accounting for already
402 	 * unused blocks instead.
403 	 */
404 	if (!READ_ONCE(rtg->rtg_open_zone))
405 		xfs_zone_account_reclaimable(rtg, len);
406 	xfs_add_frextents(mp, len);
407 	xfs_trans_log_inode(tp, rmapip, XFS_ILOG_CORE);
408 	return 0;
409 }
410 
411 static struct xfs_open_zone *
412 xfs_init_open_zone(
413 	struct xfs_rtgroup	*rtg,
414 	xfs_rgblock_t		write_pointer,
415 	enum rw_hint		write_hint,
416 	bool			is_gc)
417 {
418 	struct xfs_open_zone	*oz;
419 
420 	oz = kzalloc_obj(*oz, GFP_NOFS | __GFP_NOFAIL);
421 	spin_lock_init(&oz->oz_alloc_lock);
422 	atomic_set(&oz->oz_ref, 1);
423 	oz->oz_rtg = rtg;
424 	oz->oz_allocated = write_pointer;
425 	oz->oz_written = write_pointer;
426 	oz->oz_write_hint = write_hint;
427 	oz->oz_is_gc = is_gc;
428 
429 	/*
430 	 * All dereferences of rtg->rtg_open_zone hold the ILOCK for the rmap
431 	 * inode, but we don't really want to take that here because we are
432 	 * under the zone_list_lock.  Ensure the pointer is only set for a fully
433 	 * initialized open zone structure so that a racy lookup finding it is
434 	 * fine.
435 	 */
436 	WRITE_ONCE(rtg->rtg_open_zone, oz);
437 	return oz;
438 }
439 
440 /*
441  * Find a completely free zone, open it, and return a reference.
442  */
443 struct xfs_open_zone *
444 xfs_open_zone(
445 	struct xfs_mount	*mp,
446 	enum rw_hint		write_hint,
447 	bool			is_gc)
448 {
449 	struct xfs_zone_info	*zi = mp->m_zone_info;
450 	XA_STATE		(xas, &mp->m_groups[XG_TYPE_RTG].xa, 0);
451 	struct xfs_group	*xg;
452 
453 	/*
454 	 * Pick the free zone with lowest index. Zones in the beginning of the
455 	 * address space typically provides higher bandwidth than those at the
456 	 * end of the address space on HDDs.
457 	 */
458 	xas_lock(&xas);
459 	xas_for_each_marked(&xas, xg, ULONG_MAX, XFS_RTG_FREE)
460 		if (atomic_inc_not_zero(&xg->xg_active_ref))
461 			goto found;
462 	xas_unlock(&xas);
463 	return NULL;
464 
465 found:
466 	xas_clear_mark(&xas, XFS_RTG_FREE);
467 	atomic_dec(&zi->zi_nr_free_zones);
468 	xas_unlock(&xas);
469 
470 	set_current_state(TASK_RUNNING);
471 	return xfs_init_open_zone(to_rtg(xg), 0, write_hint, is_gc);
472 }
473 
474 static struct xfs_open_zone *
475 xfs_try_open_zone(
476 	struct xfs_mount	*mp,
477 	enum rw_hint		write_hint)
478 		__releases(&mp->m_zone_info->zi_open_zones_lock)
479 		__acquires(&mp->m_zone_info->zi_open_zones_lock)
480 {
481 	struct xfs_zone_info	*zi = mp->m_zone_info;
482 	struct xfs_open_zone	*oz;
483 
484 	if (zi->zi_nr_open_zones >= mp->m_max_open_zones - XFS_OPEN_GC_ZONES)
485 		return NULL;
486 	if (atomic_read(&zi->zi_nr_free_zones) <
487 	    XFS_GC_ZONES - XFS_OPEN_GC_ZONES)
488 		return NULL;
489 
490 	/*
491 	 * Increment the open zone count to reserve our slot before dropping
492 	 * zi_open_zones_lock.
493 	 */
494 	zi->zi_nr_open_zones++;
495 	spin_unlock(&zi->zi_open_zones_lock);
496 	oz = xfs_open_zone(mp, write_hint, false);
497 	spin_lock(&zi->zi_open_zones_lock);
498 	if (!oz) {
499 		zi->zi_nr_open_zones--;
500 		return NULL;
501 	}
502 
503 	atomic_inc(&oz->oz_ref);
504 	list_add_tail(&oz->oz_entry, &zi->zi_open_zones);
505 
506 	/*
507 	 * If this was the last free zone, other waiters might be waiting
508 	 * on us to write to it as well.
509 	 */
510 	wake_up_all(&zi->zi_zone_wait);
511 
512 	if (xfs_zoned_need_gc(mp))
513 		wake_up_process(zi->zi_gc_thread);
514 
515 	trace_xfs_zone_opened(oz->oz_rtg);
516 	return oz;
517 }
518 
519 enum xfs_zone_alloc_score {
520 	/* Any open zone will do it, we're desperate */
521 	XFS_ZONE_ALLOC_ANY	= 0,
522 
523 	/* It better fit somehow */
524 	XFS_ZONE_ALLOC_OK	= 1,
525 
526 	/* Only reuse a zone if it fits really well. */
527 	XFS_ZONE_ALLOC_GOOD	= 2,
528 };
529 
530 /*
531  * Life time hint co-location matrix.  Fields not set default to 0
532  * aka XFS_ZONE_ALLOC_ANY.
533  */
534 static const unsigned int
535 xfs_zoned_hint_score[WRITE_LIFE_HINT_NR][WRITE_LIFE_HINT_NR] = {
536 	[WRITE_LIFE_NOT_SET]	= {
537 		[WRITE_LIFE_NOT_SET]	= XFS_ZONE_ALLOC_OK,
538 	},
539 	[WRITE_LIFE_NONE]	= {
540 		[WRITE_LIFE_NONE]	= XFS_ZONE_ALLOC_OK,
541 	},
542 	[WRITE_LIFE_SHORT]	= {
543 		[WRITE_LIFE_SHORT]	= XFS_ZONE_ALLOC_GOOD,
544 	},
545 	[WRITE_LIFE_MEDIUM]	= {
546 		[WRITE_LIFE_MEDIUM]	= XFS_ZONE_ALLOC_GOOD,
547 	},
548 	[WRITE_LIFE_LONG]	= {
549 		[WRITE_LIFE_LONG]	= XFS_ZONE_ALLOC_OK,
550 		[WRITE_LIFE_EXTREME]	= XFS_ZONE_ALLOC_OK,
551 	},
552 	[WRITE_LIFE_EXTREME]	= {
553 		[WRITE_LIFE_LONG]	= XFS_ZONE_ALLOC_OK,
554 		[WRITE_LIFE_EXTREME]	= XFS_ZONE_ALLOC_OK,
555 	},
556 };
557 
558 static bool
559 xfs_try_use_zone(
560 	struct xfs_zone_info	*zi,
561 	enum rw_hint		file_hint,
562 	struct xfs_open_zone	*oz,
563 	unsigned int		goodness)
564 {
565 	if (oz->oz_is_gc)
566 		return false;
567 
568 	if (oz->oz_allocated == rtg_blocks(oz->oz_rtg))
569 		return false;
570 
571 	if (xfs_zoned_hint_score[oz->oz_write_hint][file_hint] < goodness)
572 		return false;
573 
574 	if (!atomic_inc_not_zero(&oz->oz_ref))
575 		return false;
576 
577 	/*
578 	 * If we have a hint set for the data, use that for the zone even if
579 	 * some data was written already without any hint set, but don't change
580 	 * the temperature after that as that would make little sense without
581 	 * tracking per-temperature class written block counts, which is
582 	 * probably overkill anyway.
583 	 */
584 	if (file_hint != WRITE_LIFE_NOT_SET &&
585 	    oz->oz_write_hint == WRITE_LIFE_NOT_SET)
586 		oz->oz_write_hint = file_hint;
587 
588 	/*
589 	 * If we couldn't match by inode or life time we just pick the first
590 	 * zone with enough space above.  For that we want the least busy zone
591 	 * for some definition of "least" busy.  For now this simple LRU
592 	 * algorithm that rotates every zone to the end of the list will do it,
593 	 * even if it isn't exactly cache friendly.
594 	 */
595 	if (!list_is_last(&oz->oz_entry, &zi->zi_open_zones))
596 		list_move_tail(&oz->oz_entry, &zi->zi_open_zones);
597 	return true;
598 }
599 
600 static struct xfs_open_zone *
601 xfs_select_open_zone_lru(
602 	struct xfs_zone_info	*zi,
603 	enum rw_hint		file_hint,
604 	unsigned int		goodness)
605 {
606 	struct xfs_open_zone	*oz;
607 
608 	lockdep_assert_held(&zi->zi_open_zones_lock);
609 
610 	list_for_each_entry(oz, &zi->zi_open_zones, oz_entry)
611 		if (xfs_try_use_zone(zi, file_hint, oz, goodness))
612 			return oz;
613 
614 	cond_resched_lock(&zi->zi_open_zones_lock);
615 	return NULL;
616 }
617 
618 static struct xfs_open_zone *
619 xfs_select_open_zone_mru(
620 	struct xfs_zone_info	*zi,
621 	enum rw_hint		file_hint)
622 {
623 	struct xfs_open_zone	*oz;
624 
625 	lockdep_assert_held(&zi->zi_open_zones_lock);
626 
627 	list_for_each_entry_reverse(oz, &zi->zi_open_zones, oz_entry)
628 		if (xfs_try_use_zone(zi, file_hint, oz, XFS_ZONE_ALLOC_OK))
629 			return oz;
630 
631 	cond_resched_lock(&zi->zi_open_zones_lock);
632 	return NULL;
633 }
634 
635 static inline enum rw_hint xfs_inode_write_hint(struct xfs_inode *ip)
636 {
637 	if (xfs_has_nolifetime(ip->i_mount))
638 		return WRITE_LIFE_NOT_SET;
639 	return VFS_I(ip)->i_write_hint;
640 }
641 
642 /*
643  * Try to tightly pack small files that are written back after they were closed
644  * instead of trying to open new zones for them or spread them to the least
645  * recently used zone. This optimizes the data layout for workloads that untar
646  * or copy a lot of small files. Right now this does not separate multiple such
647  * streams.
648  */
649 static inline bool xfs_zoned_pack_tight(struct xfs_inode *ip)
650 {
651 	struct xfs_mount *mp = ip->i_mount;
652 	size_t zone_capacity =
653 		XFS_FSB_TO_B(mp, mp->m_groups[XG_TYPE_RTG].blocks);
654 
655 	/*
656 	 * Do not pack write files that are already using a full zone to avoid
657 	 * fragmentation.
658 	 */
659 	if (i_size_read(VFS_I(ip)) >= zone_capacity)
660 		return false;
661 
662 	return !inode_is_open_for_write(VFS_I(ip)) &&
663 		!(ip->i_diflags & XFS_DIFLAG_APPEND);
664 }
665 
666 static struct xfs_open_zone *
667 xfs_select_zone_nowait(
668 	struct xfs_mount	*mp,
669 	enum rw_hint		write_hint,
670 	bool			pack_tight)
671 {
672 	struct xfs_zone_info	*zi = mp->m_zone_info;
673 	struct xfs_open_zone	*oz = NULL;
674 
675 	if (xfs_is_shutdown(mp))
676 		return NULL;
677 
678 	/*
679 	 * Try to fill up open zones with matching temperature if available.  It
680 	 * is better to try to co-locate data when this is favorable, so we can
681 	 * activate empty zones when it is statistically better to separate
682 	 * data.
683 	 */
684 	spin_lock(&zi->zi_open_zones_lock);
685 	oz = xfs_select_open_zone_lru(zi, write_hint, XFS_ZONE_ALLOC_GOOD);
686 	if (oz)
687 		goto out_unlock;
688 
689 	if (pack_tight) {
690 		oz = xfs_select_open_zone_mru(zi, write_hint);
691 		if (oz)
692 			goto out_unlock;
693 	}
694 
695 	/*
696 	 * See if we can open a new zone and use that so that data for different
697 	 * files is mixed as little as possible.
698 	 */
699 	oz = xfs_try_open_zone(mp, write_hint);
700 	if (oz)
701 		goto out_unlock;
702 
703 	/*
704 	 * Try to find a zone that is an ok match to colocate data with.
705 	 */
706 	oz = xfs_select_open_zone_lru(zi, write_hint, XFS_ZONE_ALLOC_OK);
707 	if (oz)
708 		goto out_unlock;
709 
710 	/*
711 	 * Pick the least recently used zone, regardless of hint match
712 	 */
713 	oz = xfs_select_open_zone_lru(zi, write_hint, XFS_ZONE_ALLOC_ANY);
714 out_unlock:
715 	spin_unlock(&zi->zi_open_zones_lock);
716 	return oz;
717 }
718 
719 static struct xfs_open_zone *
720 xfs_select_zone(
721 	struct xfs_mount	*mp,
722 	enum rw_hint		write_hint,
723 	bool			pack_tight)
724 {
725 	struct xfs_zone_info	*zi = mp->m_zone_info;
726 	DEFINE_WAIT		(wait);
727 	struct xfs_open_zone	*oz;
728 
729 	oz = xfs_select_zone_nowait(mp, write_hint, pack_tight);
730 	if (oz)
731 		return oz;
732 
733 	for (;;) {
734 		prepare_to_wait(&zi->zi_zone_wait, &wait, TASK_UNINTERRUPTIBLE);
735 		oz = xfs_select_zone_nowait(mp, write_hint, pack_tight);
736 		if (oz || xfs_is_shutdown(mp))
737 			break;
738 		schedule();
739 	}
740 	finish_wait(&zi->zi_zone_wait, &wait);
741 	return oz;
742 }
743 
744 static unsigned int
745 xfs_zone_alloc_blocks(
746 	struct xfs_open_zone	*oz,
747 	xfs_filblks_t		count_fsb,
748 	sector_t		*sector,
749 	bool			*is_seq)
750 {
751 	struct xfs_rtgroup	*rtg = oz->oz_rtg;
752 	struct xfs_mount	*mp = rtg_mount(rtg);
753 	xfs_rgblock_t		allocated;
754 
755 	spin_lock(&oz->oz_alloc_lock);
756 	count_fsb = min3(count_fsb, XFS_MAX_BMBT_EXTLEN,
757 		(xfs_filblks_t)rtg_blocks(rtg) - oz->oz_allocated);
758 	if (!count_fsb) {
759 		spin_unlock(&oz->oz_alloc_lock);
760 		return 0;
761 	}
762 	allocated = oz->oz_allocated;
763 	oz->oz_allocated += count_fsb;
764 	spin_unlock(&oz->oz_alloc_lock);
765 
766 	trace_xfs_zone_alloc_blocks(oz, allocated, count_fsb);
767 
768 	*sector = xfs_gbno_to_daddr(rtg_group(rtg), 0);
769 	*is_seq = bdev_zone_is_seq(mp->m_rtdev_targp->bt_bdev, *sector);
770 	if (!*is_seq)
771 		*sector += XFS_FSB_TO_BB(mp, allocated);
772 	return XFS_FSB_TO_B(mp, count_fsb);
773 }
774 
775 void
776 xfs_mark_rtg_boundary(
777 	struct iomap_ioend	*ioend)
778 {
779 	struct xfs_mount	*mp = XFS_I(ioend->io_inode)->i_mount;
780 	sector_t		sector = ioend->io_bio.bi_iter.bi_sector;
781 
782 	if (xfs_rtb_to_rgbno(mp, xfs_daddr_to_rtb(mp, sector)) == 0)
783 		ioend->io_flags |= IOMAP_IOEND_BOUNDARY;
784 }
785 
786 /*
787  * Check if we have a cached last open zone available for the inode and
788  * if yes return a reference to it.
789  */
790 static struct xfs_open_zone *
791 xfs_get_cached_zone(
792 	struct xfs_inode	*ip)
793 {
794 	struct xfs_open_zone	*oz;
795 
796 	rcu_read_lock();
797 	oz = VFS_I(ip)->i_private;
798 	if (!oz)
799 		goto out_unlock;
800 
801 	/*
802 	 * GC only steals open zones at mount time, so no GC zones should end up
803 	 * in the cache.
804 	 */
805 	ASSERT(!oz->oz_is_gc);
806 
807 	/*
808 	 * Drop the old cached open zone if it is full.
809 	 */
810 	if (oz->oz_allocated == rtg_blocks(oz->oz_rtg)) {
811 		spin_lock(&ip->i_flags_lock);
812 		oz = VFS_I(ip)->i_private;
813 		if (oz && oz->oz_allocated == rtg_blocks(oz->oz_rtg)) {
814 			VFS_I(ip)->i_private = NULL;
815 			spin_unlock(&ip->i_flags_lock);
816 			xfs_open_zone_put(oz);
817 			oz = NULL;
818 			goto out_unlock;
819 		}
820 		spin_unlock(&ip->i_flags_lock);
821 	}
822 
823 	if (!atomic_inc_not_zero(&oz->oz_ref))
824 		oz = NULL;
825 out_unlock:
826 	rcu_read_unlock();
827 	return oz;
828 }
829 
830 /*
831  * Stash our zone in the inode so that is is reused for future allocations.
832  *
833  * The open_zone structure will be pinned until either the inode is freed or
834  * until the cached open zone is replaced with a different one because the
835  * current one was full when we tried to use it.  This means we keep any
836  * open zone around forever as long as any inode that used it for the last
837  * write is cached, which slightly increases the memory use of cached inodes
838  * that were every written to, but significantly simplifies the cached zone
839  * lookup.  Because the open_zone is clearly marked as full when all data
840  * in the underlying RTG was written, the caching is always safe.
841  *
842  * Called with a reference on @oz held.  And returns two references on the
843  * returned zone: one for the caller and one for pinning the zone in
844  * inode->i_private.
845  */
846 static struct xfs_open_zone *
847 xfs_set_cached_zone(
848 	struct xfs_inode	*ip,
849 	struct xfs_open_zone	*oz)
850 {
851 	struct xfs_open_zone	*old_oz;
852 
853 	/*
854 	 * If the open zone cached in the inode still has free space, use that
855 	 * instead of the new open zone just selected.  This can happen when
856 	 * multiple threads race to perform zone selection for an inode.
857 	 * io_uring worker threads seem to be good way to trigger this.
858 	 *
859 	 * We need to grab an extra reference to this open zone as the caller
860 	 * owns a reference in addition to the i_private pointer.
861 	 */
862 	spin_lock(&ip->i_flags_lock);
863 	old_oz = VFS_I(ip)->i_private;
864 	if (old_oz && old_oz->oz_allocated < rtg_blocks(old_oz->oz_rtg) &&
865 	    atomic_inc_not_zero(&old_oz->oz_ref)) {
866 		spin_unlock(&ip->i_flags_lock);
867 		xfs_open_zone_put(oz);
868 		return old_oz;
869 	}
870 	VFS_I(ip)->i_private = oz;
871 	atomic_inc(&oz->oz_ref);
872 	spin_unlock(&ip->i_flags_lock);
873 	if (old_oz)
874 		xfs_open_zone_put(old_oz);
875 	return oz;
876 }
877 
878 static void
879 xfs_submit_zoned_bio(
880 	struct iomap_ioend	*ioend,
881 	struct xfs_open_zone	*oz,
882 	bool			is_seq)
883 {
884 	ioend->io_bio.bi_iter.bi_sector = ioend->io_sector;
885 	ioend->io_private = oz;
886 	atomic_inc(&oz->oz_ref); /* for xfs_zoned_end_io */
887 
888 	if (is_seq) {
889 		ioend->io_bio.bi_opf &= ~REQ_OP_WRITE;
890 		ioend->io_bio.bi_opf |= REQ_OP_ZONE_APPEND;
891 	} else {
892 		xfs_mark_rtg_boundary(ioend);
893 	}
894 
895 	submit_bio(&ioend->io_bio);
896 }
897 
898 void
899 xfs_zone_alloc_and_submit(
900 	struct iomap_ioend	*ioend,
901 	struct xfs_open_zone	**oz)
902 {
903 	struct xfs_inode	*ip = XFS_I(ioend->io_inode);
904 	struct xfs_mount	*mp = ip->i_mount;
905 	enum rw_hint		write_hint = xfs_inode_write_hint(ip);
906 	bool			pack_tight = xfs_zoned_pack_tight(ip);
907 	unsigned int		alloc_len;
908 	struct iomap_ioend	*split;
909 	bool			is_seq;
910 
911 	if (xfs_is_shutdown(mp))
912 		goto out_error;
913 
914 	/*
915 	 * If we don't have a locally cached zone in this write context, see if
916 	 * the inode is still associated with a zone and use that if so.
917 	 */
918 	if (!*oz)
919 select_zone:
920 		*oz = xfs_get_cached_zone(ip);
921 	if (!*oz) {
922 		*oz = xfs_select_zone(mp, write_hint, pack_tight);
923 		if (!*oz)
924 			goto out_error;
925 		*oz = xfs_set_cached_zone(ip, *oz);
926 	}
927 
928 	alloc_len = xfs_zone_alloc_blocks(*oz, XFS_B_TO_FSB(mp, ioend->io_size),
929 			&ioend->io_sector, &is_seq);
930 	if (!alloc_len) {
931 		xfs_open_zone_put(*oz);
932 		goto select_zone;
933 	}
934 
935 	while ((split = iomap_split_ioend(ioend, alloc_len, is_seq))) {
936 		if (IS_ERR(split))
937 			goto out_split_error;
938 		alloc_len -= split->io_bio.bi_iter.bi_size;
939 		xfs_submit_zoned_bio(split, *oz, is_seq);
940 		if (!alloc_len) {
941 			xfs_open_zone_put(*oz);
942 			goto select_zone;
943 		}
944 	}
945 
946 	xfs_submit_zoned_bio(ioend, *oz, is_seq);
947 	return;
948 
949 out_split_error:
950 	ioend->io_bio.bi_status = errno_to_blk_status(PTR_ERR(split));
951 out_error:
952 	bio_io_error(&ioend->io_bio);
953 }
954 
955 /*
956  * Wake up all threads waiting for a zoned space allocation when the file system
957  * is shut down.
958  */
959 void
960 xfs_zoned_wake_all(
961 	struct xfs_mount	*mp)
962 {
963 	/*
964 	 * Don't wake up if there is no m_zone_info.  This is complicated by the
965 	 * fact that unmount can't atomically clear m_zone_info and thus we need
966 	 * to check SB_ACTIVE for that, but mount temporarily enables SB_ACTIVE
967 	 * during log recovery so we can't entirely rely on that either.
968 	 */
969 	if ((mp->m_super->s_flags & SB_ACTIVE) && mp->m_zone_info)
970 		wake_up_all(&mp->m_zone_info->zi_zone_wait);
971 }
972 
973 /*
974  * Check if @rgbno in @rgb is a potentially valid block.  It might still be
975  * unused, but that information is only found in the rmap.
976  */
977 bool
978 xfs_zone_rgbno_is_valid(
979 	struct xfs_rtgroup	*rtg,
980 	xfs_rgnumber_t		rgbno)
981 {
982 	lockdep_assert_held(&rtg_rmap(rtg)->i_lock);
983 
984 	if (rtg->rtg_open_zone)
985 		return rgbno < rtg->rtg_open_zone->oz_allocated;
986 	return !xa_get_mark(&rtg_mount(rtg)->m_groups[XG_TYPE_RTG].xa,
987 			rtg_rgno(rtg), XFS_RTG_FREE);
988 }
989 
990 void
991 xfs_zone_mark_free(
992 	struct xfs_rtgroup	*rtg)
993 {
994 	xfs_group_set_mark(rtg_group(rtg), XFS_RTG_FREE);
995 	atomic_inc(&rtg_mount(rtg)->m_zone_info->zi_nr_free_zones);
996 }
997 
998 static void
999 xfs_free_open_zones(
1000 	struct xfs_zone_info	*zi)
1001 {
1002 	struct xfs_open_zone	*oz;
1003 
1004 	spin_lock(&zi->zi_open_zones_lock);
1005 	while ((oz = list_first_entry_or_null(&zi->zi_open_zones,
1006 			struct xfs_open_zone, oz_entry))) {
1007 		list_del(&oz->oz_entry);
1008 		xfs_open_zone_put(oz);
1009 	}
1010 	spin_unlock(&zi->zi_open_zones_lock);
1011 
1012 	/*
1013 	 * Wait for all open zones to be freed so that they drop the group
1014 	 * references:
1015 	 */
1016 	rcu_barrier();
1017 }
1018 
1019 struct xfs_init_zones {
1020 	uint32_t		zone_size;
1021 	uint32_t		zone_capacity;
1022 	uint64_t		available;
1023 	uint64_t		reclaimable;
1024 };
1025 
1026 /*
1027  * For sequential write required zones, we restart writing at the hardware write
1028  * pointer returned by xfs_validate_blk_zone().
1029  *
1030  * For conventional zones or conventional devices we have to query the rmap to
1031  * find the highest recorded block and set the write pointer to the block after
1032  * that.  In case of a power loss this misses blocks where the data I/O has
1033  * completed but not recorded in the rmap yet, and it also rewrites blocks if
1034  * the most recently written ones got deleted again before unmount, but this is
1035  * the best we can do without hardware support.
1036  */
1037 static int
1038 xfs_query_write_pointer(
1039 	struct xfs_init_zones	*iz,
1040 	struct xfs_rtgroup	*rtg,
1041 	xfs_rgblock_t		*write_pointer)
1042 {
1043 	struct xfs_mount	*mp = rtg_mount(rtg);
1044 	struct block_device	*bdev = mp->m_rtdev_targp->bt_bdev;
1045 	sector_t		start = xfs_gbno_to_daddr(&rtg->rtg_group, 0);
1046 	xfs_rgblock_t		highest_rgbno;
1047 	struct blk_zone		zone = {};
1048 	int			error;
1049 
1050 	if (bdev_is_zoned(bdev)) {
1051 		error = blkdev_get_zone_info(bdev, start, &zone);
1052 		if (error)
1053 			return error;
1054 		if (zone.start != start) {
1055 			xfs_warn(mp, "mismatched zone start: 0x%llx/0x%llx.",
1056 				zone.start, start);
1057 			return -EFSCORRUPTED;
1058 		}
1059 
1060 		if (!xfs_validate_blk_zone(mp, &zone, rtg_rgno(rtg),
1061 				iz->zone_size, iz->zone_capacity,
1062 				write_pointer))
1063 			return -EFSCORRUPTED;
1064 
1065 		/*
1066 		 * Use the hardware write pointer returned by
1067 		 * xfs_validate_blk_zone for sequential write required zones,
1068 		 * else fall through to the rmap-based estimation below.
1069 		 */
1070 		if (zone.cond != BLK_ZONE_COND_NOT_WP)
1071 			return 0;
1072 	}
1073 
1074 	xfs_rtgroup_lock(rtg, XFS_RTGLOCK_RMAP);
1075 	highest_rgbno = xfs_rtrmap_highest_rgbno(rtg);
1076 	xfs_rtgroup_unlock(rtg, XFS_RTGLOCK_RMAP);
1077 
1078 	if (highest_rgbno == NULLRGBLOCK)
1079 		*write_pointer = 0;
1080 	else
1081 		*write_pointer = highest_rgbno + 1;
1082 	return 0;
1083 }
1084 
1085 static int
1086 xfs_init_zone(
1087 	struct xfs_init_zones	*iz,
1088 	struct xfs_rtgroup	*rtg,
1089 	xfs_rgblock_t		write_pointer)
1090 {
1091 	struct xfs_mount	*mp = rtg_mount(rtg);
1092 	struct xfs_zone_info	*zi = mp->m_zone_info;
1093 	uint32_t		used = rtg_rmap(rtg)->i_used_blocks;
1094 	int			error;
1095 
1096 	if (write_pointer > rtg->rtg_extents) {
1097 		xfs_warn(mp, "zone %u has invalid write pointer (0x%x).",
1098 			 rtg_rgno(rtg), write_pointer);
1099 		return -EFSCORRUPTED;
1100 	}
1101 
1102 	if (used > rtg->rtg_extents) {
1103 		xfs_warn(mp,
1104 "zone %u has used counter (0x%x) larger than zone capacity (0x%llx).",
1105 			 rtg_rgno(rtg), used, rtg->rtg_extents);
1106 		return -EFSCORRUPTED;
1107 	}
1108 
1109 	if (used > write_pointer) {
1110 		xfs_warn(mp,
1111 "zone %u has used counter (0x%x) larger than write pointer (0x%x).",
1112 			 rtg_rgno(rtg), used, write_pointer);
1113 		return -EFSCORRUPTED;
1114 	}
1115 
1116 	if (write_pointer == 0 && used != 0) {
1117 		xfs_warn(mp, "empty zone %u has non-zero used counter (0x%x).",
1118 			rtg_rgno(rtg), used);
1119 		return -EFSCORRUPTED;
1120 	}
1121 
1122 	/*
1123 	 * If there are no used blocks, but the zone is not in empty state yet
1124 	 * we lost power before the zoned reset.  In that case finish the work
1125 	 * here.
1126 	 */
1127 	if (write_pointer == rtg_blocks(rtg) && used == 0) {
1128 		error = xfs_zone_gc_reset_sync(rtg);
1129 		if (error)
1130 			return error;
1131 		write_pointer = 0;
1132 	}
1133 
1134 	if (write_pointer == 0) {
1135 		/* zone is empty */
1136 		xfs_zone_mark_free(rtg);
1137 		iz->available += rtg_blocks(rtg);
1138 	} else if (write_pointer < rtg_blocks(rtg)) {
1139 		/* zone is open */
1140 		struct xfs_open_zone *oz;
1141 
1142 		atomic_inc(&rtg_group(rtg)->xg_active_ref);
1143 		oz = xfs_init_open_zone(rtg, write_pointer, WRITE_LIFE_NOT_SET,
1144 				false);
1145 		list_add_tail(&oz->oz_entry, &zi->zi_open_zones);
1146 		zi->zi_nr_open_zones++;
1147 
1148 		iz->available += (rtg_blocks(rtg) - write_pointer);
1149 		iz->reclaimable += write_pointer - used;
1150 	} else if (used < rtg_blocks(rtg)) {
1151 		/* zone fully written, but has freed blocks */
1152 		xfs_zone_account_reclaimable(rtg, rtg_blocks(rtg) - used);
1153 		iz->reclaimable += (rtg_blocks(rtg) - used);
1154 	}
1155 
1156 	return 0;
1157 }
1158 
1159 /*
1160  * Calculate the max open zone limit based on the of number of backing zones
1161  * available.
1162  */
1163 static inline uint32_t
1164 xfs_max_open_zones(
1165 	struct xfs_mount	*mp)
1166 {
1167 	unsigned int		max_open, max_open_data_zones;
1168 
1169 	/*
1170 	 * We need two zones for every open data zone, one in reserve as we
1171 	 * don't reclaim open zones.  One data zone and its spare is included
1172 	 * in XFS_MIN_ZONES to support at least one user data writer.
1173 	 */
1174 	max_open_data_zones = (mp->m_sb.sb_rgcount - XFS_MIN_ZONES) / 2 + 1;
1175 	max_open = max_open_data_zones + XFS_OPEN_GC_ZONES;
1176 
1177 	/*
1178 	 * Cap the max open limit to 1/4 of available space.  Without this we'd
1179 	 * run out of easy reclaim targets too quickly and storage devices don't
1180 	 * handle huge numbers of concurrent write streams overly well.
1181 	 */
1182 	max_open = min(max_open, mp->m_sb.sb_rgcount / 4);
1183 
1184 	return max(XFS_MIN_OPEN_ZONES, max_open);
1185 }
1186 
1187 /*
1188  * Normally we use the open zone limit that the device reports.  If there is
1189  * none let the user pick one from the command line.
1190  *
1191  * If the device doesn't report an open zone limit and there is no override,
1192  * allow to hold about a quarter of the zones open.  In theory we could allow
1193  * all to be open, but at that point we run into GC deadlocks because we can't
1194  * reclaim open zones.
1195  *
1196  * When used on conventional SSDs a lower open limit is advisable as we'll
1197  * otherwise overwhelm the FTL just as much as a conventional block allocator.
1198  *
1199  * Note: To debug the open zone management code, force max_open to 1 here.
1200  */
1201 static int
1202 xfs_calc_open_zones(
1203 	struct xfs_mount	*mp)
1204 {
1205 	struct block_device	*bdev = mp->m_rtdev_targp->bt_bdev;
1206 	unsigned int		bdev_open_zones = bdev_max_open_zones(bdev);
1207 
1208 	if (!mp->m_max_open_zones) {
1209 		if (bdev_open_zones)
1210 			mp->m_max_open_zones = bdev_open_zones;
1211 		else
1212 			mp->m_max_open_zones = XFS_DEFAULT_MAX_OPEN_ZONES;
1213 	}
1214 
1215 	if (mp->m_max_open_zones < XFS_MIN_OPEN_ZONES) {
1216 		xfs_notice(mp, "need at least %u open zones.",
1217 			XFS_MIN_OPEN_ZONES);
1218 		return -EIO;
1219 	}
1220 
1221 	if (bdev_open_zones && bdev_open_zones < mp->m_max_open_zones) {
1222 		mp->m_max_open_zones = bdev_open_zones;
1223 		xfs_info(mp, "limiting open zones to %u due to hardware limit.",
1224 			bdev_open_zones);
1225 	}
1226 
1227 	if (mp->m_max_open_zones > xfs_max_open_zones(mp)) {
1228 		mp->m_max_open_zones = xfs_max_open_zones(mp);
1229 		xfs_info(mp,
1230 "limiting open zones to %u due to total zone count (%u)",
1231 			mp->m_max_open_zones, mp->m_sb.sb_rgcount);
1232 	}
1233 
1234 	return 0;
1235 }
1236 
1237 static unsigned long *
1238 xfs_alloc_bucket_bitmap(
1239 	struct xfs_mount	*mp)
1240 {
1241 	return kvmalloc_array(BITS_TO_LONGS(mp->m_sb.sb_rgcount),
1242 			sizeof(unsigned long), GFP_KERNEL | __GFP_ZERO);
1243 }
1244 
1245 static struct xfs_zone_info *
1246 xfs_alloc_zone_info(
1247 	struct xfs_mount	*mp)
1248 {
1249 	struct xfs_zone_info	*zi;
1250 	int			i;
1251 
1252 	zi = kzalloc_obj(*zi);
1253 	if (!zi)
1254 		return NULL;
1255 	INIT_LIST_HEAD(&zi->zi_open_zones);
1256 	INIT_LIST_HEAD(&zi->zi_reclaim_reservations);
1257 	spin_lock_init(&zi->zi_reset_list_lock);
1258 	spin_lock_init(&zi->zi_open_zones_lock);
1259 	spin_lock_init(&zi->zi_reservation_lock);
1260 	init_waitqueue_head(&zi->zi_zone_wait);
1261 	spin_lock_init(&zi->zi_used_buckets_lock);
1262 	for (i = 0; i < XFS_ZONE_USED_BUCKETS; i++) {
1263 		zi->zi_used_bucket_bitmap[i] = xfs_alloc_bucket_bitmap(mp);
1264 		if (!zi->zi_used_bucket_bitmap[i])
1265 			goto out_free_bitmaps;
1266 	}
1267 	return zi;
1268 
1269 out_free_bitmaps:
1270 	while (--i >= 0)
1271 		kvfree(zi->zi_used_bucket_bitmap[i]);
1272 	kfree(zi);
1273 	return NULL;
1274 }
1275 
1276 static void
1277 xfs_free_zone_info(
1278 	struct xfs_zone_info	*zi)
1279 {
1280 	int			i;
1281 
1282 	xfs_free_open_zones(zi);
1283 	for (i = 0; i < XFS_ZONE_USED_BUCKETS; i++)
1284 		kvfree(zi->zi_used_bucket_bitmap[i]);
1285 	kfree(zi);
1286 }
1287 
1288 static int
1289 xfs_report_zones(
1290 	struct xfs_mount	*mp,
1291 	struct xfs_init_zones	*iz)
1292 {
1293 	struct xfs_rtgroup	*rtg = NULL;
1294 
1295 	while ((rtg = xfs_rtgroup_next(mp, rtg))) {
1296 		xfs_rgblock_t		write_pointer;
1297 		int			error;
1298 
1299 		error = xfs_query_write_pointer(iz, rtg, &write_pointer);
1300 		if (!error)
1301 			error = xfs_init_zone(iz, rtg, write_pointer);
1302 		if (error) {
1303 			xfs_rtgroup_rele(rtg);
1304 			return error;
1305 		}
1306 	}
1307 
1308 	return 0;
1309 }
1310 
1311 static inline bool
1312 xfs_zone_is_conv(
1313 	struct xfs_rtgroup	*rtg)
1314 {
1315 	return !bdev_zone_is_seq(rtg_mount(rtg)->m_rtdev_targp->bt_bdev,
1316 			xfs_gbno_to_daddr(rtg_group(rtg), 0));
1317 }
1318 
1319 static struct xfs_open_zone *
1320 xfs_find_fullest_conventional_open_zone(
1321 	struct xfs_mount	*mp)
1322 {
1323 	struct xfs_zone_info	*zi = mp->m_zone_info;
1324 	struct xfs_open_zone	*found = NULL, *oz;
1325 
1326 	spin_lock(&zi->zi_open_zones_lock);
1327 	list_for_each_entry(oz, &zi->zi_open_zones, oz_entry) {
1328 		if (!xfs_zone_is_conv(oz->oz_rtg))
1329 			continue;
1330 		if (!found || oz->oz_allocated > found->oz_allocated)
1331 			found = oz;
1332 	}
1333 	spin_unlock(&zi->zi_open_zones_lock);
1334 
1335 	return found;
1336 }
1337 
1338 /*
1339  * Find the fullest conventional zones and remove them from the open zone pool
1340  * until we are at the open zone limit.
1341  *
1342  * We can end up with spurious "open" zones when the last blocks in a fully
1343  * written zone were invalidate as there is no write pointer for conventional
1344  * zones.
1345  *
1346  * If we are still over the limit when there is no conventional open zone left,
1347  * the user overrode the max open zones limit using the max_open_zones mount
1348  * option we should fail.
1349  */
1350 static int
1351 xfs_finish_spurious_open_zones(
1352 	struct xfs_mount	*mp,
1353 	struct xfs_init_zones	*iz)
1354 {
1355 	struct xfs_zone_info	*zi = mp->m_zone_info;
1356 
1357 	while (zi->zi_nr_open_zones > mp->m_max_open_zones) {
1358 		struct xfs_open_zone	*oz;
1359 		xfs_filblks_t		adjust;
1360 
1361 		oz = xfs_find_fullest_conventional_open_zone(mp);
1362 		if (!oz) {
1363 			xfs_err(mp,
1364 "too many open zones for max_open_zones limit (%u/%u)",
1365 			zi->zi_nr_open_zones, mp->m_max_open_zones);
1366 			return -EINVAL;
1367 		}
1368 
1369 		xfs_rtgroup_lock(oz->oz_rtg, XFS_RTGLOCK_RMAP);
1370 		adjust = rtg_blocks(oz->oz_rtg) - oz->oz_written;
1371 		trace_xfs_zone_spurious_open(oz, oz->oz_written, adjust);
1372 		oz->oz_written = rtg_blocks(oz->oz_rtg);
1373 		xfs_open_zone_mark_full(oz);
1374 		xfs_rtgroup_unlock(oz->oz_rtg, XFS_RTGLOCK_RMAP);
1375 		iz->available -= adjust;
1376 		iz->reclaimable += adjust;
1377 	}
1378 
1379 	return 0;
1380 }
1381 
1382 int
1383 xfs_mount_zones(
1384 	struct xfs_mount	*mp)
1385 {
1386 	struct xfs_init_zones	iz = {
1387 		.zone_capacity	= mp->m_groups[XG_TYPE_RTG].blocks,
1388 		.zone_size	= xfs_rtgroup_raw_size(mp),
1389 	};
1390 	int			error;
1391 
1392 	if (!mp->m_rtdev_targp) {
1393 		xfs_notice(mp, "RT device missing.");
1394 		return -EINVAL;
1395 	}
1396 
1397 	if (!xfs_has_rtgroups(mp) || !xfs_has_rmapbt(mp)) {
1398 		xfs_notice(mp, "invalid flag combination.");
1399 		return -EFSCORRUPTED;
1400 	}
1401 	if (mp->m_sb.sb_rextsize != 1) {
1402 		xfs_notice(mp, "zoned file systems do not support rextsize.");
1403 		return -EFSCORRUPTED;
1404 	}
1405 	if (mp->m_sb.sb_rgcount < XFS_MIN_ZONES) {
1406 		xfs_notice(mp,
1407 "zoned file systems need to have at least %u zones.", XFS_MIN_ZONES);
1408 		return -EFSCORRUPTED;
1409 	}
1410 
1411 	error = xfs_calc_open_zones(mp);
1412 	if (error)
1413 		return error;
1414 
1415 	mp->m_zone_info = xfs_alloc_zone_info(mp);
1416 	if (!mp->m_zone_info)
1417 		return -ENOMEM;
1418 
1419 	error = xfs_report_zones(mp, &iz);
1420 	if (error)
1421 		goto out_free_zone_info;
1422 
1423 	error = xfs_finish_spurious_open_zones(mp, &iz);
1424 	if (error)
1425 		goto out_free_zone_info;
1426 
1427 	xfs_set_freecounter(mp, XC_FREE_RTAVAILABLE, iz.available);
1428 	xfs_set_freecounter(mp, XC_FREE_RTEXTENTS,
1429 			iz.available + iz.reclaimable);
1430 
1431 	/*
1432 	 * The writeback code switches between inodes regularly to provide
1433 	 * fairness.  The default lower bound is 4MiB, but for zoned file
1434 	 * systems we want to increase that both to reduce seeks, but also more
1435 	 * importantly so that workloads that writes files in a multiple of the
1436 	 * zone size do not get fragmented and require garbage collection when
1437 	 * they shouldn't.  Increase is to the zone size capped by the max
1438 	 * extent len.
1439 	 *
1440 	 * Note that because s_min_writeback_pages is a superblock field, this
1441 	 * value also get applied to non-zoned files on the data device if
1442 	 * there are any.  On typical zoned setup all data is on the RT device
1443 	 * because using the more efficient sequential write required zones
1444 	 * is the reason for using the zone allocator, and either the RT device
1445 	 * and the (meta)data device are on the same block device, or the
1446 	 * (meta)data device is on a fast SSD while the data on the RT device
1447 	 * is on a SMR HDD.  In any combination of the above cases enforcing
1448 	 * the higher min_writeback_pages for non-RT inodes is either a noop
1449 	 * or beneficial.
1450 	 */
1451 	mp->m_super->s_min_writeback_pages =
1452 		XFS_FSB_TO_B(mp, min(iz.zone_capacity, XFS_MAX_BMBT_EXTLEN)) >>
1453 			PAGE_SHIFT;
1454 
1455 	/*
1456 	 * The user may configure GC to free up a percentage of unused blocks.
1457 	 * By default this is 0. GC will always trigger at the minimum level
1458 	 * for keeping max_open_zones available for data placement.
1459 	 */
1460 	mp->m_zonegc_low_space = 0;
1461 
1462 	error = xfs_zone_gc_mount(mp);
1463 	if (error)
1464 		goto out_free_zone_info;
1465 
1466 	error = xfs_zoned_sysfs_init(mp);
1467 	if (error)
1468 		goto out_zone_gc_unmount;
1469 
1470 	xfs_info(mp, "%u zones of %u blocks (%u max open zones)",
1471 		 mp->m_sb.sb_rgcount, iz.zone_capacity, mp->m_max_open_zones);
1472 	trace_xfs_zones_mount(mp);
1473 	return 0;
1474 
1475 out_zone_gc_unmount:
1476 	xfs_zone_gc_unmount(mp);
1477 out_free_zone_info:
1478 	xfs_free_zone_info(mp->m_zone_info);
1479 	return error;
1480 }
1481 
1482 void
1483 xfs_unmount_zones(
1484 	struct xfs_mount	*mp)
1485 {
1486 	xfs_zoned_sysfs_del(mp);
1487 	xfs_zone_gc_unmount(mp);
1488 	xfs_free_zone_info(mp->m_zone_info);
1489 }
1490