xref: /linux/fs/xfs/xfs_zone_alloc.c (revision fafb66e5903c2bcfc7b7e259042a8282f18a6faa)
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 {
479 	struct xfs_zone_info	*zi = mp->m_zone_info;
480 	struct xfs_open_zone	*oz;
481 
482 	if (zi->zi_nr_open_zones >= mp->m_max_open_zones - XFS_OPEN_GC_ZONES)
483 		return NULL;
484 	if (atomic_read(&zi->zi_nr_free_zones) <
485 	    XFS_GC_ZONES - XFS_OPEN_GC_ZONES)
486 		return NULL;
487 
488 	/*
489 	 * Increment the open zone count to reserve our slot before dropping
490 	 * zi_open_zones_lock.
491 	 */
492 	zi->zi_nr_open_zones++;
493 	spin_unlock(&zi->zi_open_zones_lock);
494 	oz = xfs_open_zone(mp, write_hint, false);
495 	spin_lock(&zi->zi_open_zones_lock);
496 	if (!oz) {
497 		zi->zi_nr_open_zones--;
498 		return NULL;
499 	}
500 
501 	atomic_inc(&oz->oz_ref);
502 	list_add_tail(&oz->oz_entry, &zi->zi_open_zones);
503 
504 	/*
505 	 * If this was the last free zone, other waiters might be waiting
506 	 * on us to write to it as well.
507 	 */
508 	wake_up_all(&zi->zi_zone_wait);
509 
510 	if (xfs_zoned_need_gc(mp))
511 		wake_up_process(zi->zi_gc_thread);
512 
513 	trace_xfs_zone_opened(oz->oz_rtg);
514 	return oz;
515 }
516 
517 enum xfs_zone_alloc_score {
518 	/* Any open zone will do it, we're desperate */
519 	XFS_ZONE_ALLOC_ANY	= 0,
520 
521 	/* It better fit somehow */
522 	XFS_ZONE_ALLOC_OK	= 1,
523 
524 	/* Only reuse a zone if it fits really well. */
525 	XFS_ZONE_ALLOC_GOOD	= 2,
526 };
527 
528 /*
529  * Life time hint co-location matrix.  Fields not set default to 0
530  * aka XFS_ZONE_ALLOC_ANY.
531  */
532 static const unsigned int
533 xfs_zoned_hint_score[WRITE_LIFE_HINT_NR][WRITE_LIFE_HINT_NR] = {
534 	[WRITE_LIFE_NOT_SET]	= {
535 		[WRITE_LIFE_NOT_SET]	= XFS_ZONE_ALLOC_OK,
536 	},
537 	[WRITE_LIFE_NONE]	= {
538 		[WRITE_LIFE_NONE]	= XFS_ZONE_ALLOC_OK,
539 	},
540 	[WRITE_LIFE_SHORT]	= {
541 		[WRITE_LIFE_SHORT]	= XFS_ZONE_ALLOC_GOOD,
542 	},
543 	[WRITE_LIFE_MEDIUM]	= {
544 		[WRITE_LIFE_MEDIUM]	= XFS_ZONE_ALLOC_GOOD,
545 	},
546 	[WRITE_LIFE_LONG]	= {
547 		[WRITE_LIFE_LONG]	= XFS_ZONE_ALLOC_OK,
548 		[WRITE_LIFE_EXTREME]	= XFS_ZONE_ALLOC_OK,
549 	},
550 	[WRITE_LIFE_EXTREME]	= {
551 		[WRITE_LIFE_LONG]	= XFS_ZONE_ALLOC_OK,
552 		[WRITE_LIFE_EXTREME]	= XFS_ZONE_ALLOC_OK,
553 	},
554 };
555 
556 static bool
557 xfs_try_use_zone(
558 	struct xfs_zone_info	*zi,
559 	enum rw_hint		file_hint,
560 	struct xfs_open_zone	*oz,
561 	unsigned int		goodness)
562 {
563 	if (oz->oz_is_gc)
564 		return false;
565 
566 	if (oz->oz_allocated == rtg_blocks(oz->oz_rtg))
567 		return false;
568 
569 	if (xfs_zoned_hint_score[oz->oz_write_hint][file_hint] < goodness)
570 		return false;
571 
572 	if (!atomic_inc_not_zero(&oz->oz_ref))
573 		return false;
574 
575 	/*
576 	 * If we have a hint set for the data, use that for the zone even if
577 	 * some data was written already without any hint set, but don't change
578 	 * the temperature after that as that would make little sense without
579 	 * tracking per-temperature class written block counts, which is
580 	 * probably overkill anyway.
581 	 */
582 	if (file_hint != WRITE_LIFE_NOT_SET &&
583 	    oz->oz_write_hint == WRITE_LIFE_NOT_SET)
584 		oz->oz_write_hint = file_hint;
585 
586 	/*
587 	 * If we couldn't match by inode or life time we just pick the first
588 	 * zone with enough space above.  For that we want the least busy zone
589 	 * for some definition of "least" busy.  For now this simple LRU
590 	 * algorithm that rotates every zone to the end of the list will do it,
591 	 * even if it isn't exactly cache friendly.
592 	 */
593 	if (!list_is_last(&oz->oz_entry, &zi->zi_open_zones))
594 		list_move_tail(&oz->oz_entry, &zi->zi_open_zones);
595 	return true;
596 }
597 
598 static struct xfs_open_zone *
599 xfs_select_open_zone_lru(
600 	struct xfs_zone_info	*zi,
601 	enum rw_hint		file_hint,
602 	unsigned int		goodness)
603 {
604 	struct xfs_open_zone	*oz;
605 
606 	lockdep_assert_held(&zi->zi_open_zones_lock);
607 
608 	list_for_each_entry(oz, &zi->zi_open_zones, oz_entry)
609 		if (xfs_try_use_zone(zi, file_hint, oz, goodness))
610 			return oz;
611 
612 	cond_resched_lock(&zi->zi_open_zones_lock);
613 	return NULL;
614 }
615 
616 static struct xfs_open_zone *
617 xfs_select_open_zone_mru(
618 	struct xfs_zone_info	*zi,
619 	enum rw_hint		file_hint)
620 {
621 	struct xfs_open_zone	*oz;
622 
623 	lockdep_assert_held(&zi->zi_open_zones_lock);
624 
625 	list_for_each_entry_reverse(oz, &zi->zi_open_zones, oz_entry)
626 		if (xfs_try_use_zone(zi, file_hint, oz, XFS_ZONE_ALLOC_OK))
627 			return oz;
628 
629 	cond_resched_lock(&zi->zi_open_zones_lock);
630 	return NULL;
631 }
632 
633 static inline enum rw_hint xfs_inode_write_hint(struct xfs_inode *ip)
634 {
635 	if (xfs_has_nolifetime(ip->i_mount))
636 		return WRITE_LIFE_NOT_SET;
637 	return VFS_I(ip)->i_write_hint;
638 }
639 
640 /*
641  * Try to tightly pack small files that are written back after they were closed
642  * instead of trying to open new zones for them or spread them to the least
643  * recently used zone. This optimizes the data layout for workloads that untar
644  * or copy a lot of small files. Right now this does not separate multiple such
645  * streams.
646  */
647 static inline bool xfs_zoned_pack_tight(struct xfs_inode *ip)
648 {
649 	struct xfs_mount *mp = ip->i_mount;
650 	size_t zone_capacity =
651 		XFS_FSB_TO_B(mp, mp->m_groups[XG_TYPE_RTG].blocks);
652 
653 	/*
654 	 * Do not pack write files that are already using a full zone to avoid
655 	 * fragmentation.
656 	 */
657 	if (i_size_read(VFS_I(ip)) >= zone_capacity)
658 		return false;
659 
660 	return !inode_is_open_for_write(VFS_I(ip)) &&
661 		!(ip->i_diflags & XFS_DIFLAG_APPEND);
662 }
663 
664 static struct xfs_open_zone *
665 xfs_select_zone_nowait(
666 	struct xfs_mount	*mp,
667 	enum rw_hint		write_hint,
668 	bool			pack_tight)
669 {
670 	struct xfs_zone_info	*zi = mp->m_zone_info;
671 	struct xfs_open_zone	*oz = NULL;
672 
673 	if (xfs_is_shutdown(mp))
674 		return NULL;
675 
676 	/*
677 	 * Try to fill up open zones with matching temperature if available.  It
678 	 * is better to try to co-locate data when this is favorable, so we can
679 	 * activate empty zones when it is statistically better to separate
680 	 * data.
681 	 */
682 	spin_lock(&zi->zi_open_zones_lock);
683 	oz = xfs_select_open_zone_lru(zi, write_hint, XFS_ZONE_ALLOC_GOOD);
684 	if (oz)
685 		goto out_unlock;
686 
687 	if (pack_tight) {
688 		oz = xfs_select_open_zone_mru(zi, write_hint);
689 		if (oz)
690 			goto out_unlock;
691 	}
692 
693 	/*
694 	 * See if we can open a new zone and use that so that data for different
695 	 * files is mixed as little as possible.
696 	 */
697 	oz = xfs_try_open_zone(mp, write_hint);
698 	if (oz)
699 		goto out_unlock;
700 
701 	/*
702 	 * Try to find a zone that is an ok match to colocate data with.
703 	 */
704 	oz = xfs_select_open_zone_lru(zi, write_hint, XFS_ZONE_ALLOC_OK);
705 	if (oz)
706 		goto out_unlock;
707 
708 	/*
709 	 * Pick the least recently used zone, regardless of hint match
710 	 */
711 	oz = xfs_select_open_zone_lru(zi, write_hint, XFS_ZONE_ALLOC_ANY);
712 out_unlock:
713 	spin_unlock(&zi->zi_open_zones_lock);
714 	return oz;
715 }
716 
717 static struct xfs_open_zone *
718 xfs_select_zone(
719 	struct xfs_mount	*mp,
720 	enum rw_hint		write_hint,
721 	bool			pack_tight)
722 {
723 	struct xfs_zone_info	*zi = mp->m_zone_info;
724 	DEFINE_WAIT		(wait);
725 	struct xfs_open_zone	*oz;
726 
727 	oz = xfs_select_zone_nowait(mp, write_hint, pack_tight);
728 	if (oz)
729 		return oz;
730 
731 	for (;;) {
732 		prepare_to_wait(&zi->zi_zone_wait, &wait, TASK_UNINTERRUPTIBLE);
733 		oz = xfs_select_zone_nowait(mp, write_hint, pack_tight);
734 		if (oz || xfs_is_shutdown(mp))
735 			break;
736 		schedule();
737 	}
738 	finish_wait(&zi->zi_zone_wait, &wait);
739 	return oz;
740 }
741 
742 static unsigned int
743 xfs_zone_alloc_blocks(
744 	struct xfs_open_zone	*oz,
745 	xfs_filblks_t		count_fsb,
746 	sector_t		*sector,
747 	bool			*is_seq)
748 {
749 	struct xfs_rtgroup	*rtg = oz->oz_rtg;
750 	struct xfs_mount	*mp = rtg_mount(rtg);
751 	xfs_rgblock_t		allocated;
752 
753 	spin_lock(&oz->oz_alloc_lock);
754 	count_fsb = min3(count_fsb, XFS_MAX_BMBT_EXTLEN,
755 		(xfs_filblks_t)rtg_blocks(rtg) - oz->oz_allocated);
756 	if (!count_fsb) {
757 		spin_unlock(&oz->oz_alloc_lock);
758 		return 0;
759 	}
760 	allocated = oz->oz_allocated;
761 	oz->oz_allocated += count_fsb;
762 	spin_unlock(&oz->oz_alloc_lock);
763 
764 	trace_xfs_zone_alloc_blocks(oz, allocated, count_fsb);
765 
766 	*sector = xfs_gbno_to_daddr(rtg_group(rtg), 0);
767 	*is_seq = bdev_zone_is_seq(mp->m_rtdev_targp->bt_bdev, *sector);
768 	if (!*is_seq)
769 		*sector += XFS_FSB_TO_BB(mp, allocated);
770 	return XFS_FSB_TO_B(mp, count_fsb);
771 }
772 
773 void
774 xfs_mark_rtg_boundary(
775 	struct iomap_ioend	*ioend)
776 {
777 	struct xfs_mount	*mp = XFS_I(ioend->io_inode)->i_mount;
778 	sector_t		sector = ioend->io_bio.bi_iter.bi_sector;
779 
780 	if (xfs_rtb_to_rgbno(mp, xfs_daddr_to_rtb(mp, sector)) == 0)
781 		ioend->io_flags |= IOMAP_IOEND_BOUNDARY;
782 }
783 
784 /*
785  * Check if we have a cached last open zone available for the inode and
786  * if yes return a reference to it.
787  */
788 static struct xfs_open_zone *
789 xfs_get_cached_zone(
790 	struct xfs_inode	*ip)
791 {
792 	struct xfs_open_zone	*oz;
793 
794 	rcu_read_lock();
795 	oz = VFS_I(ip)->i_private;
796 	if (oz) {
797 		/*
798 		 * GC only steals open zones at mount time, so no GC zones
799 		 * should end up in the cache.
800 		 */
801 		ASSERT(!oz->oz_is_gc);
802 		if (!atomic_inc_not_zero(&oz->oz_ref))
803 			oz = NULL;
804 	}
805 	rcu_read_unlock();
806 
807 	return oz;
808 }
809 
810 /*
811  * Stash our zone in the inode so that is is reused for future allocations.
812  *
813  * The open_zone structure will be pinned until either the inode is freed or
814  * until the cached open zone is replaced with a different one because the
815  * current one was full when we tried to use it.  This means we keep any
816  * open zone around forever as long as any inode that used it for the last
817  * write is cached, which slightly increases the memory use of cached inodes
818  * that were every written to, but significantly simplifies the cached zone
819  * lookup.  Because the open_zone is clearly marked as full when all data
820  * in the underlying RTG was written, the caching is always safe.
821  */
822 static void
823 xfs_set_cached_zone(
824 	struct xfs_inode	*ip,
825 	struct xfs_open_zone	*oz)
826 {
827 	struct xfs_open_zone	*old_oz;
828 
829 	atomic_inc(&oz->oz_ref);
830 	old_oz = xchg(&VFS_I(ip)->i_private, oz);
831 	if (old_oz)
832 		xfs_open_zone_put(old_oz);
833 }
834 
835 static void
836 xfs_submit_zoned_bio(
837 	struct iomap_ioend	*ioend,
838 	struct xfs_open_zone	*oz,
839 	bool			is_seq)
840 {
841 	ioend->io_bio.bi_iter.bi_sector = ioend->io_sector;
842 	ioend->io_private = oz;
843 	atomic_inc(&oz->oz_ref); /* for xfs_zoned_end_io */
844 
845 	if (is_seq) {
846 		ioend->io_bio.bi_opf &= ~REQ_OP_WRITE;
847 		ioend->io_bio.bi_opf |= REQ_OP_ZONE_APPEND;
848 	} else {
849 		xfs_mark_rtg_boundary(ioend);
850 	}
851 
852 	submit_bio(&ioend->io_bio);
853 }
854 
855 void
856 xfs_zone_alloc_and_submit(
857 	struct iomap_ioend	*ioend,
858 	struct xfs_open_zone	**oz)
859 {
860 	struct xfs_inode	*ip = XFS_I(ioend->io_inode);
861 	struct xfs_mount	*mp = ip->i_mount;
862 	enum rw_hint		write_hint = xfs_inode_write_hint(ip);
863 	bool			pack_tight = xfs_zoned_pack_tight(ip);
864 	unsigned int		alloc_len;
865 	struct iomap_ioend	*split;
866 	bool			is_seq;
867 
868 	if (xfs_is_shutdown(mp))
869 		goto out_error;
870 
871 	/*
872 	 * If we don't have a locally cached zone in this write context, see if
873 	 * the inode is still associated with a zone and use that if so.
874 	 */
875 	if (!*oz)
876 		*oz = xfs_get_cached_zone(ip);
877 
878 	if (!*oz) {
879 select_zone:
880 		*oz = xfs_select_zone(mp, write_hint, pack_tight);
881 		if (!*oz)
882 			goto out_error;
883 		xfs_set_cached_zone(ip, *oz);
884 	}
885 
886 	alloc_len = xfs_zone_alloc_blocks(*oz, XFS_B_TO_FSB(mp, ioend->io_size),
887 			&ioend->io_sector, &is_seq);
888 	if (!alloc_len) {
889 		xfs_open_zone_put(*oz);
890 		goto select_zone;
891 	}
892 
893 	while ((split = iomap_split_ioend(ioend, alloc_len, is_seq))) {
894 		if (IS_ERR(split))
895 			goto out_split_error;
896 		alloc_len -= split->io_bio.bi_iter.bi_size;
897 		xfs_submit_zoned_bio(split, *oz, is_seq);
898 		if (!alloc_len) {
899 			xfs_open_zone_put(*oz);
900 			goto select_zone;
901 		}
902 	}
903 
904 	xfs_submit_zoned_bio(ioend, *oz, is_seq);
905 	return;
906 
907 out_split_error:
908 	ioend->io_bio.bi_status = errno_to_blk_status(PTR_ERR(split));
909 out_error:
910 	bio_io_error(&ioend->io_bio);
911 }
912 
913 /*
914  * Wake up all threads waiting for a zoned space allocation when the file system
915  * is shut down.
916  */
917 void
918 xfs_zoned_wake_all(
919 	struct xfs_mount	*mp)
920 {
921 	/*
922 	 * Don't wake up if there is no m_zone_info.  This is complicated by the
923 	 * fact that unmount can't atomically clear m_zone_info and thus we need
924 	 * to check SB_ACTIVE for that, but mount temporarily enables SB_ACTIVE
925 	 * during log recovery so we can't entirely rely on that either.
926 	 */
927 	if ((mp->m_super->s_flags & SB_ACTIVE) && mp->m_zone_info)
928 		wake_up_all(&mp->m_zone_info->zi_zone_wait);
929 }
930 
931 /*
932  * Check if @rgbno in @rgb is a potentially valid block.  It might still be
933  * unused, but that information is only found in the rmap.
934  */
935 bool
936 xfs_zone_rgbno_is_valid(
937 	struct xfs_rtgroup	*rtg,
938 	xfs_rgnumber_t		rgbno)
939 {
940 	lockdep_assert_held(&rtg_rmap(rtg)->i_lock);
941 
942 	if (rtg->rtg_open_zone)
943 		return rgbno < rtg->rtg_open_zone->oz_allocated;
944 	return !xa_get_mark(&rtg_mount(rtg)->m_groups[XG_TYPE_RTG].xa,
945 			rtg_rgno(rtg), XFS_RTG_FREE);
946 }
947 
948 void
949 xfs_zone_mark_free(
950 	struct xfs_rtgroup	*rtg)
951 {
952 	xfs_group_set_mark(rtg_group(rtg), XFS_RTG_FREE);
953 	atomic_inc(&rtg_mount(rtg)->m_zone_info->zi_nr_free_zones);
954 }
955 
956 static void
957 xfs_free_open_zones(
958 	struct xfs_zone_info	*zi)
959 {
960 	struct xfs_open_zone	*oz;
961 
962 	spin_lock(&zi->zi_open_zones_lock);
963 	while ((oz = list_first_entry_or_null(&zi->zi_open_zones,
964 			struct xfs_open_zone, oz_entry))) {
965 		list_del(&oz->oz_entry);
966 		xfs_open_zone_put(oz);
967 	}
968 	spin_unlock(&zi->zi_open_zones_lock);
969 
970 	/*
971 	 * Wait for all open zones to be freed so that they drop the group
972 	 * references:
973 	 */
974 	rcu_barrier();
975 }
976 
977 struct xfs_init_zones {
978 	uint32_t		zone_size;
979 	uint32_t		zone_capacity;
980 	uint64_t		available;
981 	uint64_t		reclaimable;
982 };
983 
984 /*
985  * For sequential write required zones, we restart writing at the hardware write
986  * pointer returned by xfs_validate_blk_zone().
987  *
988  * For conventional zones or conventional devices we have to query the rmap to
989  * find the highest recorded block and set the write pointer to the block after
990  * that.  In case of a power loss this misses blocks where the data I/O has
991  * completed but not recorded in the rmap yet, and it also rewrites blocks if
992  * the most recently written ones got deleted again before unmount, but this is
993  * the best we can do without hardware support.
994  */
995 static int
996 xfs_query_write_pointer(
997 	struct xfs_init_zones	*iz,
998 	struct xfs_rtgroup	*rtg,
999 	xfs_rgblock_t		*write_pointer)
1000 {
1001 	struct xfs_mount	*mp = rtg_mount(rtg);
1002 	struct block_device	*bdev = mp->m_rtdev_targp->bt_bdev;
1003 	sector_t		start = xfs_gbno_to_daddr(&rtg->rtg_group, 0);
1004 	xfs_rgblock_t		highest_rgbno;
1005 	struct blk_zone		zone = {};
1006 	int			error;
1007 
1008 	if (bdev_is_zoned(bdev)) {
1009 		error = blkdev_get_zone_info(bdev, start, &zone);
1010 		if (error)
1011 			return error;
1012 		if (zone.start != start) {
1013 			xfs_warn(mp, "mismatched zone start: 0x%llx/0x%llx.",
1014 				zone.start, start);
1015 			return -EFSCORRUPTED;
1016 		}
1017 
1018 		if (!xfs_validate_blk_zone(mp, &zone, rtg_rgno(rtg),
1019 				iz->zone_size, iz->zone_capacity,
1020 				write_pointer))
1021 			return -EFSCORRUPTED;
1022 
1023 		/*
1024 		 * Use the hardware write pointer returned by
1025 		 * xfs_validate_blk_zone for sequential write required zones,
1026 		 * else fall through to the rmap-based estimation below.
1027 		 */
1028 		if (zone.cond != BLK_ZONE_COND_NOT_WP)
1029 			return 0;
1030 	}
1031 
1032 	xfs_rtgroup_lock(rtg, XFS_RTGLOCK_RMAP);
1033 	highest_rgbno = xfs_rtrmap_highest_rgbno(rtg);
1034 	xfs_rtgroup_unlock(rtg, XFS_RTGLOCK_RMAP);
1035 
1036 	if (highest_rgbno == NULLRGBLOCK)
1037 		*write_pointer = 0;
1038 	else
1039 		*write_pointer = highest_rgbno + 1;
1040 	return 0;
1041 }
1042 
1043 static int
1044 xfs_init_zone(
1045 	struct xfs_init_zones	*iz,
1046 	struct xfs_rtgroup	*rtg,
1047 	xfs_rgblock_t		write_pointer)
1048 {
1049 	struct xfs_mount	*mp = rtg_mount(rtg);
1050 	struct xfs_zone_info	*zi = mp->m_zone_info;
1051 	uint32_t		used = rtg_rmap(rtg)->i_used_blocks;
1052 	int			error;
1053 
1054 	if (write_pointer > rtg->rtg_extents) {
1055 		xfs_warn(mp, "zone %u has invalid write pointer (0x%x).",
1056 			 rtg_rgno(rtg), write_pointer);
1057 		return -EFSCORRUPTED;
1058 	}
1059 
1060 	if (used > rtg->rtg_extents) {
1061 		xfs_warn(mp,
1062 "zone %u has used counter (0x%x) larger than zone capacity (0x%llx).",
1063 			 rtg_rgno(rtg), used, rtg->rtg_extents);
1064 		return -EFSCORRUPTED;
1065 	}
1066 
1067 	if (used > write_pointer) {
1068 		xfs_warn(mp,
1069 "zone %u has used counter (0x%x) larger than write pointer (0x%x).",
1070 			 rtg_rgno(rtg), used, write_pointer);
1071 		return -EFSCORRUPTED;
1072 	}
1073 
1074 	if (write_pointer == 0 && used != 0) {
1075 		xfs_warn(mp, "empty zone %u has non-zero used counter (0x%x).",
1076 			rtg_rgno(rtg), used);
1077 		return -EFSCORRUPTED;
1078 	}
1079 
1080 	/*
1081 	 * If there are no used blocks, but the zone is not in empty state yet
1082 	 * we lost power before the zoned reset.  In that case finish the work
1083 	 * here.
1084 	 */
1085 	if (write_pointer == rtg_blocks(rtg) && used == 0) {
1086 		error = xfs_zone_gc_reset_sync(rtg);
1087 		if (error)
1088 			return error;
1089 		write_pointer = 0;
1090 	}
1091 
1092 	if (write_pointer == 0) {
1093 		/* zone is empty */
1094 		xfs_zone_mark_free(rtg);
1095 		iz->available += rtg_blocks(rtg);
1096 	} else if (write_pointer < rtg_blocks(rtg)) {
1097 		/* zone is open */
1098 		struct xfs_open_zone *oz;
1099 
1100 		atomic_inc(&rtg_group(rtg)->xg_active_ref);
1101 		oz = xfs_init_open_zone(rtg, write_pointer, WRITE_LIFE_NOT_SET,
1102 				false);
1103 		list_add_tail(&oz->oz_entry, &zi->zi_open_zones);
1104 		zi->zi_nr_open_zones++;
1105 
1106 		iz->available += (rtg_blocks(rtg) - write_pointer);
1107 		iz->reclaimable += write_pointer - used;
1108 	} else if (used < rtg_blocks(rtg)) {
1109 		/* zone fully written, but has freed blocks */
1110 		xfs_zone_account_reclaimable(rtg, rtg_blocks(rtg) - used);
1111 		iz->reclaimable += (rtg_blocks(rtg) - used);
1112 	}
1113 
1114 	return 0;
1115 }
1116 
1117 /*
1118  * Calculate the max open zone limit based on the of number of backing zones
1119  * available.
1120  */
1121 static inline uint32_t
1122 xfs_max_open_zones(
1123 	struct xfs_mount	*mp)
1124 {
1125 	unsigned int		max_open, max_open_data_zones;
1126 
1127 	/*
1128 	 * We need two zones for every open data zone, one in reserve as we
1129 	 * don't reclaim open zones.  One data zone and its spare is included
1130 	 * in XFS_MIN_ZONES to support at least one user data writer.
1131 	 */
1132 	max_open_data_zones = (mp->m_sb.sb_rgcount - XFS_MIN_ZONES) / 2 + 1;
1133 	max_open = max_open_data_zones + XFS_OPEN_GC_ZONES;
1134 
1135 	/*
1136 	 * Cap the max open limit to 1/4 of available space.  Without this we'd
1137 	 * run out of easy reclaim targets too quickly and storage devices don't
1138 	 * handle huge numbers of concurrent write streams overly well.
1139 	 */
1140 	max_open = min(max_open, mp->m_sb.sb_rgcount / 4);
1141 
1142 	return max(XFS_MIN_OPEN_ZONES, max_open);
1143 }
1144 
1145 /*
1146  * Normally we use the open zone limit that the device reports.  If there is
1147  * none let the user pick one from the command line.
1148  *
1149  * If the device doesn't report an open zone limit and there is no override,
1150  * allow to hold about a quarter of the zones open.  In theory we could allow
1151  * all to be open, but at that point we run into GC deadlocks because we can't
1152  * reclaim open zones.
1153  *
1154  * When used on conventional SSDs a lower open limit is advisable as we'll
1155  * otherwise overwhelm the FTL just as much as a conventional block allocator.
1156  *
1157  * Note: To debug the open zone management code, force max_open to 1 here.
1158  */
1159 static int
1160 xfs_calc_open_zones(
1161 	struct xfs_mount	*mp)
1162 {
1163 	struct block_device	*bdev = mp->m_rtdev_targp->bt_bdev;
1164 	unsigned int		bdev_open_zones = bdev_max_open_zones(bdev);
1165 
1166 	if (!mp->m_max_open_zones) {
1167 		if (bdev_open_zones)
1168 			mp->m_max_open_zones = bdev_open_zones;
1169 		else
1170 			mp->m_max_open_zones = XFS_DEFAULT_MAX_OPEN_ZONES;
1171 	}
1172 
1173 	if (mp->m_max_open_zones < XFS_MIN_OPEN_ZONES) {
1174 		xfs_notice(mp, "need at least %u open zones.",
1175 			XFS_MIN_OPEN_ZONES);
1176 		return -EIO;
1177 	}
1178 
1179 	if (bdev_open_zones && bdev_open_zones < mp->m_max_open_zones) {
1180 		mp->m_max_open_zones = bdev_open_zones;
1181 		xfs_info(mp, "limiting open zones to %u due to hardware limit.",
1182 			bdev_open_zones);
1183 	}
1184 
1185 	if (mp->m_max_open_zones > xfs_max_open_zones(mp)) {
1186 		mp->m_max_open_zones = xfs_max_open_zones(mp);
1187 		xfs_info(mp,
1188 "limiting open zones to %u due to total zone count (%u)",
1189 			mp->m_max_open_zones, mp->m_sb.sb_rgcount);
1190 	}
1191 
1192 	return 0;
1193 }
1194 
1195 static unsigned long *
1196 xfs_alloc_bucket_bitmap(
1197 	struct xfs_mount	*mp)
1198 {
1199 	return kvmalloc_array(BITS_TO_LONGS(mp->m_sb.sb_rgcount),
1200 			sizeof(unsigned long), GFP_KERNEL | __GFP_ZERO);
1201 }
1202 
1203 static struct xfs_zone_info *
1204 xfs_alloc_zone_info(
1205 	struct xfs_mount	*mp)
1206 {
1207 	struct xfs_zone_info	*zi;
1208 	int			i;
1209 
1210 	zi = kzalloc_obj(*zi);
1211 	if (!zi)
1212 		return NULL;
1213 	INIT_LIST_HEAD(&zi->zi_open_zones);
1214 	INIT_LIST_HEAD(&zi->zi_reclaim_reservations);
1215 	spin_lock_init(&zi->zi_reset_list_lock);
1216 	spin_lock_init(&zi->zi_open_zones_lock);
1217 	spin_lock_init(&zi->zi_reservation_lock);
1218 	init_waitqueue_head(&zi->zi_zone_wait);
1219 	spin_lock_init(&zi->zi_used_buckets_lock);
1220 	for (i = 0; i < XFS_ZONE_USED_BUCKETS; i++) {
1221 		zi->zi_used_bucket_bitmap[i] = xfs_alloc_bucket_bitmap(mp);
1222 		if (!zi->zi_used_bucket_bitmap[i])
1223 			goto out_free_bitmaps;
1224 	}
1225 	return zi;
1226 
1227 out_free_bitmaps:
1228 	while (--i >= 0)
1229 		kvfree(zi->zi_used_bucket_bitmap[i]);
1230 	kfree(zi);
1231 	return NULL;
1232 }
1233 
1234 static void
1235 xfs_free_zone_info(
1236 	struct xfs_zone_info	*zi)
1237 {
1238 	int			i;
1239 
1240 	xfs_free_open_zones(zi);
1241 	for (i = 0; i < XFS_ZONE_USED_BUCKETS; i++)
1242 		kvfree(zi->zi_used_bucket_bitmap[i]);
1243 	kfree(zi);
1244 }
1245 
1246 static int
1247 xfs_report_zones(
1248 	struct xfs_mount	*mp,
1249 	struct xfs_init_zones	*iz)
1250 {
1251 	struct xfs_rtgroup	*rtg = NULL;
1252 
1253 	while ((rtg = xfs_rtgroup_next(mp, rtg))) {
1254 		xfs_rgblock_t		write_pointer;
1255 		int			error;
1256 
1257 		error = xfs_query_write_pointer(iz, rtg, &write_pointer);
1258 		if (!error)
1259 			error = xfs_init_zone(iz, rtg, write_pointer);
1260 		if (error) {
1261 			xfs_rtgroup_rele(rtg);
1262 			return error;
1263 		}
1264 	}
1265 
1266 	return 0;
1267 }
1268 
1269 static inline bool
1270 xfs_zone_is_conv(
1271 	struct xfs_rtgroup	*rtg)
1272 {
1273 	return !bdev_zone_is_seq(rtg_mount(rtg)->m_rtdev_targp->bt_bdev,
1274 			xfs_gbno_to_daddr(rtg_group(rtg), 0));
1275 }
1276 
1277 static struct xfs_open_zone *
1278 xfs_find_fullest_conventional_open_zone(
1279 	struct xfs_mount	*mp)
1280 {
1281 	struct xfs_zone_info	*zi = mp->m_zone_info;
1282 	struct xfs_open_zone	*found = NULL, *oz;
1283 
1284 	spin_lock(&zi->zi_open_zones_lock);
1285 	list_for_each_entry(oz, &zi->zi_open_zones, oz_entry) {
1286 		if (!xfs_zone_is_conv(oz->oz_rtg))
1287 			continue;
1288 		if (!found || oz->oz_allocated > found->oz_allocated)
1289 			found = oz;
1290 	}
1291 	spin_unlock(&zi->zi_open_zones_lock);
1292 
1293 	return found;
1294 }
1295 
1296 /*
1297  * Find the fullest conventional zones and remove them from the open zone pool
1298  * until we are at the open zone limit.
1299  *
1300  * We can end up with spurious "open" zones when the last blocks in a fully
1301  * written zone were invalidate as there is no write pointer for conventional
1302  * zones.
1303  *
1304  * If we are still over the limit when there is no conventional open zone left,
1305  * the user overrode the max open zones limit using the max_open_zones mount
1306  * option we should fail.
1307  */
1308 static int
1309 xfs_finish_spurious_open_zones(
1310 	struct xfs_mount	*mp,
1311 	struct xfs_init_zones	*iz)
1312 {
1313 	struct xfs_zone_info	*zi = mp->m_zone_info;
1314 
1315 	while (zi->zi_nr_open_zones > mp->m_max_open_zones) {
1316 		struct xfs_open_zone	*oz;
1317 		xfs_filblks_t		adjust;
1318 
1319 		oz = xfs_find_fullest_conventional_open_zone(mp);
1320 		if (!oz) {
1321 			xfs_err(mp,
1322 "too many open zones for max_open_zones limit (%u/%u)",
1323 			zi->zi_nr_open_zones, mp->m_max_open_zones);
1324 			return -EINVAL;
1325 		}
1326 
1327 		xfs_rtgroup_lock(oz->oz_rtg, XFS_RTGLOCK_RMAP);
1328 		adjust = rtg_blocks(oz->oz_rtg) - oz->oz_written;
1329 		trace_xfs_zone_spurious_open(oz, oz->oz_written, adjust);
1330 		oz->oz_written = rtg_blocks(oz->oz_rtg);
1331 		xfs_open_zone_mark_full(oz);
1332 		xfs_rtgroup_unlock(oz->oz_rtg, XFS_RTGLOCK_RMAP);
1333 		iz->available -= adjust;
1334 		iz->reclaimable += adjust;
1335 	}
1336 
1337 	return 0;
1338 }
1339 
1340 int
1341 xfs_mount_zones(
1342 	struct xfs_mount	*mp)
1343 {
1344 	struct xfs_init_zones	iz = {
1345 		.zone_capacity	= mp->m_groups[XG_TYPE_RTG].blocks,
1346 		.zone_size	= xfs_rtgroup_raw_size(mp),
1347 	};
1348 	int			error;
1349 
1350 	if (!mp->m_rtdev_targp) {
1351 		xfs_notice(mp, "RT device missing.");
1352 		return -EINVAL;
1353 	}
1354 
1355 	if (!xfs_has_rtgroups(mp) || !xfs_has_rmapbt(mp)) {
1356 		xfs_notice(mp, "invalid flag combination.");
1357 		return -EFSCORRUPTED;
1358 	}
1359 	if (mp->m_sb.sb_rextsize != 1) {
1360 		xfs_notice(mp, "zoned file systems do not support rextsize.");
1361 		return -EFSCORRUPTED;
1362 	}
1363 	if (mp->m_sb.sb_rgcount < XFS_MIN_ZONES) {
1364 		xfs_notice(mp,
1365 "zoned file systems need to have at least %u zones.", XFS_MIN_ZONES);
1366 		return -EFSCORRUPTED;
1367 	}
1368 
1369 	error = xfs_calc_open_zones(mp);
1370 	if (error)
1371 		return error;
1372 
1373 	mp->m_zone_info = xfs_alloc_zone_info(mp);
1374 	if (!mp->m_zone_info)
1375 		return -ENOMEM;
1376 
1377 	error = xfs_report_zones(mp, &iz);
1378 	if (error)
1379 		goto out_free_zone_info;
1380 
1381 	error = xfs_finish_spurious_open_zones(mp, &iz);
1382 	if (error)
1383 		goto out_free_zone_info;
1384 
1385 	xfs_set_freecounter(mp, XC_FREE_RTAVAILABLE, iz.available);
1386 	xfs_set_freecounter(mp, XC_FREE_RTEXTENTS,
1387 			iz.available + iz.reclaimable);
1388 
1389 	/*
1390 	 * The writeback code switches between inodes regularly to provide
1391 	 * fairness.  The default lower bound is 4MiB, but for zoned file
1392 	 * systems we want to increase that both to reduce seeks, but also more
1393 	 * importantly so that workloads that writes files in a multiple of the
1394 	 * zone size do not get fragmented and require garbage collection when
1395 	 * they shouldn't.  Increase is to the zone size capped by the max
1396 	 * extent len.
1397 	 *
1398 	 * Note that because s_min_writeback_pages is a superblock field, this
1399 	 * value also get applied to non-zoned files on the data device if
1400 	 * there are any.  On typical zoned setup all data is on the RT device
1401 	 * because using the more efficient sequential write required zones
1402 	 * is the reason for using the zone allocator, and either the RT device
1403 	 * and the (meta)data device are on the same block device, or the
1404 	 * (meta)data device is on a fast SSD while the data on the RT device
1405 	 * is on a SMR HDD.  In any combination of the above cases enforcing
1406 	 * the higher min_writeback_pages for non-RT inodes is either a noop
1407 	 * or beneficial.
1408 	 */
1409 	mp->m_super->s_min_writeback_pages =
1410 		XFS_FSB_TO_B(mp, min(iz.zone_capacity, XFS_MAX_BMBT_EXTLEN)) >>
1411 			PAGE_SHIFT;
1412 
1413 	/*
1414 	 * The user may configure GC to free up a percentage of unused blocks.
1415 	 * By default this is 0. GC will always trigger at the minimum level
1416 	 * for keeping max_open_zones available for data placement.
1417 	 */
1418 	mp->m_zonegc_low_space = 0;
1419 
1420 	error = xfs_zone_gc_mount(mp);
1421 	if (error)
1422 		goto out_free_zone_info;
1423 
1424 	error = xfs_zoned_sysfs_init(mp);
1425 	if (error)
1426 		goto out_zone_gc_unmount;
1427 
1428 	xfs_info(mp, "%u zones of %u blocks (%u max open zones)",
1429 		 mp->m_sb.sb_rgcount, iz.zone_capacity, mp->m_max_open_zones);
1430 	trace_xfs_zones_mount(mp);
1431 	return 0;
1432 
1433 out_zone_gc_unmount:
1434 	xfs_zone_gc_unmount(mp);
1435 out_free_zone_info:
1436 	xfs_free_zone_info(mp->m_zone_info);
1437 	return error;
1438 }
1439 
1440 void
1441 xfs_unmount_zones(
1442 	struct xfs_mount	*mp)
1443 {
1444 	xfs_zoned_sysfs_del(mp);
1445 	xfs_zone_gc_unmount(mp);
1446 	xfs_free_zone_info(mp->m_zone_info);
1447 }
1448