xref: /linux/fs/erofs/zdata.c (revision c134a40f86efb8d6b5a949ef70e06d5752209be5)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2018 HUAWEI, Inc.
4  *             https://www.huawei.com/
5  * Copyright (C) 2022 Alibaba Cloud
6  */
7 #include "compress.h"
8 #include <linux/psi.h>
9 #include <linux/cpuhotplug.h>
10 #include <trace/events/erofs.h>
11 
12 #define Z_EROFS_MAX_SYNC_DECOMPRESS_BYTES	12288
13 #define Z_EROFS_PCLUSTER_MAX_PAGES	(Z_EROFS_PCLUSTER_MAX_SIZE / PAGE_SIZE)
14 #define Z_EROFS_INLINE_BVECS		2
15 
16 struct z_erofs_bvec {
17 	struct page *page;
18 	int offset;
19 	unsigned int end;
20 };
21 
22 #define __Z_EROFS_BVSET(name, total) \
23 struct name { \
24 	/* point to the next page which contains the following bvecs */ \
25 	struct page *nextpage; \
26 	struct z_erofs_bvec bvec[total]; \
27 }
28 __Z_EROFS_BVSET(z_erofs_bvset,);
29 __Z_EROFS_BVSET(z_erofs_bvset_inline, Z_EROFS_INLINE_BVECS);
30 
31 /*
32  * Structure fields follow one of the following exclusion rules.
33  *
34  * I: Modifiable by initialization/destruction paths and read-only
35  *    for everyone else;
36  *
37  * L: Field should be protected by the pcluster lock;
38  *
39  * A: Field should be accessed / updated in atomic for parallelized code.
40  */
41 struct z_erofs_pcluster {
42 	struct mutex lock;
43 	struct lockref lockref;
44 
45 	/* A: point to next chained pcluster or TAILs */
46 	struct z_erofs_pcluster *next;
47 
48 	/* I: start physical position of this pcluster */
49 	erofs_off_t pos;
50 
51 	/* L: the maximum decompression size of this round */
52 	unsigned int length;
53 
54 	/* L: total number of bvecs */
55 	unsigned int vcnt;
56 
57 	/* I: pcluster size (compressed size) in bytes */
58 	unsigned int pclustersize;
59 
60 	/* I: page offset of start position of decompression */
61 	unsigned short pageofs_out;
62 
63 	/* I: page offset of inline compressed data */
64 	unsigned short pageofs_in;
65 
66 	union {
67 		/* L: inline a certain number of bvec for bootstrap */
68 		struct z_erofs_bvset_inline bvset;
69 
70 		/* I: can be used to free the pcluster by RCU. */
71 		struct rcu_head rcu;
72 	};
73 
74 	/* I: compression algorithm format */
75 	unsigned char algorithmformat;
76 
77 	/* I: whether compressed data is in-lined or not */
78 	bool from_meta;
79 
80 	/* L: whether partial decompression or not */
81 	bool partial;
82 
83 	/* L: whether extra buffer allocations are best-effort */
84 	bool besteffort;
85 
86 	/* A: compressed bvecs (can be cached or inplaced pages) */
87 	struct z_erofs_bvec compressed_bvecs[];
88 };
89 
90 /* the end of a chain of pclusters */
91 #define Z_EROFS_PCLUSTER_TAIL           ((void *) 0x700 + POISON_POINTER_DELTA)
92 
93 struct z_erofs_decompressqueue {
94 	struct super_block *sb;
95 	struct z_erofs_pcluster *head;
96 	atomic_t pending_bios;
97 
98 	union {
99 		struct completion done;
100 		struct work_struct work;
101 		struct kthread_work kthread_work;
102 	} u;
103 	bool eio, sync;
104 };
105 
106 static inline unsigned int z_erofs_pclusterpages(struct z_erofs_pcluster *pcl)
107 {
108 	return PAGE_ALIGN(pcl->pageofs_in + pcl->pclustersize) >> PAGE_SHIFT;
109 }
110 
111 static bool erofs_folio_is_managed(struct erofs_sb_info *sbi, struct folio *fo)
112 {
113 	return fo->mapping == MNGD_MAPPING(sbi);
114 }
115 
116 #define Z_EROFS_ONSTACK_PAGES		32
117 
118 /*
119  * since pclustersize is variable for big pcluster feature, introduce slab
120  * pools implementation for different pcluster sizes.
121  */
122 struct z_erofs_pcluster_slab {
123 	struct kmem_cache *slab;
124 	unsigned int maxpages;
125 	char name[48];
126 };
127 
128 #define _PCLP(n) { .maxpages = n }
129 
130 static struct z_erofs_pcluster_slab pcluster_pool[] __read_mostly = {
131 	_PCLP(1), _PCLP(4), _PCLP(16), _PCLP(64), _PCLP(128),
132 	_PCLP(Z_EROFS_PCLUSTER_MAX_PAGES + 1)
133 };
134 
135 struct z_erofs_bvec_iter {
136 	struct page *bvpage;
137 	struct z_erofs_bvset *bvset;
138 	unsigned int nr, cur;
139 };
140 
141 static struct page *z_erofs_bvec_iter_end(struct z_erofs_bvec_iter *iter)
142 {
143 	if (iter->bvpage)
144 		kunmap_local(iter->bvset);
145 	return iter->bvpage;
146 }
147 
148 static struct page *z_erofs_bvset_flip(struct z_erofs_bvec_iter *iter)
149 {
150 	unsigned long base = (unsigned long)((struct z_erofs_bvset *)0)->bvec;
151 	/* have to access nextpage in advance, otherwise it will be unmapped */
152 	struct page *nextpage = iter->bvset->nextpage;
153 	struct page *oldpage;
154 
155 	DBG_BUGON(!nextpage);
156 	oldpage = z_erofs_bvec_iter_end(iter);
157 	iter->bvpage = nextpage;
158 	iter->bvset = kmap_local_page(nextpage);
159 	iter->nr = (PAGE_SIZE - base) / sizeof(struct z_erofs_bvec);
160 	iter->cur = 0;
161 	return oldpage;
162 }
163 
164 static void z_erofs_bvec_iter_begin(struct z_erofs_bvec_iter *iter,
165 				    struct z_erofs_bvset_inline *bvset,
166 				    unsigned int bootstrap_nr,
167 				    unsigned int cur)
168 {
169 	*iter = (struct z_erofs_bvec_iter) {
170 		.nr = bootstrap_nr,
171 		.bvset = (struct z_erofs_bvset *)bvset,
172 	};
173 
174 	while (cur > iter->nr) {
175 		cur -= iter->nr;
176 		z_erofs_bvset_flip(iter);
177 	}
178 	iter->cur = cur;
179 }
180 
181 static int z_erofs_bvec_enqueue(struct z_erofs_bvec_iter *iter,
182 				struct z_erofs_bvec *bvec,
183 				struct page **candidate_bvpage,
184 				struct page **pagepool)
185 {
186 	if (iter->cur >= iter->nr) {
187 		struct page *nextpage = *candidate_bvpage;
188 
189 		if (!nextpage) {
190 			nextpage = __erofs_allocpage(pagepool, GFP_KERNEL,
191 					true);
192 			if (!nextpage)
193 				return -ENOMEM;
194 			set_page_private(nextpage, Z_EROFS_SHORTLIVED_PAGE);
195 		}
196 		DBG_BUGON(iter->bvset->nextpage);
197 		iter->bvset->nextpage = nextpage;
198 		z_erofs_bvset_flip(iter);
199 
200 		iter->bvset->nextpage = NULL;
201 		*candidate_bvpage = NULL;
202 	}
203 	iter->bvset->bvec[iter->cur++] = *bvec;
204 	return 0;
205 }
206 
207 static void z_erofs_bvec_dequeue(struct z_erofs_bvec_iter *iter,
208 				 struct z_erofs_bvec *bvec,
209 				 struct page **old_bvpage)
210 {
211 	if (iter->cur == iter->nr)
212 		*old_bvpage = z_erofs_bvset_flip(iter);
213 	else
214 		*old_bvpage = NULL;
215 	*bvec = iter->bvset->bvec[iter->cur++];
216 }
217 
218 static void z_erofs_destroy_pcluster_pool(void)
219 {
220 	int i;
221 
222 	for (i = 0; i < ARRAY_SIZE(pcluster_pool); ++i) {
223 		if (!pcluster_pool[i].slab)
224 			continue;
225 		kmem_cache_destroy(pcluster_pool[i].slab);
226 		pcluster_pool[i].slab = NULL;
227 	}
228 }
229 
230 static int z_erofs_create_pcluster_pool(void)
231 {
232 	struct z_erofs_pcluster_slab *pcs;
233 	struct z_erofs_pcluster *a;
234 	unsigned int size;
235 
236 	for (pcs = pcluster_pool;
237 	     pcs < pcluster_pool + ARRAY_SIZE(pcluster_pool); ++pcs) {
238 		size = struct_size(a, compressed_bvecs, pcs->maxpages);
239 
240 		sprintf(pcs->name, "erofs_pcluster-%u", pcs->maxpages);
241 		pcs->slab = kmem_cache_create(pcs->name, size, 0,
242 					      SLAB_RECLAIM_ACCOUNT, NULL);
243 		if (pcs->slab)
244 			continue;
245 
246 		z_erofs_destroy_pcluster_pool();
247 		return -ENOMEM;
248 	}
249 	return 0;
250 }
251 
252 static struct z_erofs_pcluster *z_erofs_alloc_pcluster(unsigned int size)
253 {
254 	unsigned int nrpages = PAGE_ALIGN(size) >> PAGE_SHIFT;
255 	struct z_erofs_pcluster_slab *pcs = pcluster_pool;
256 
257 	for (; pcs < pcluster_pool + ARRAY_SIZE(pcluster_pool); ++pcs) {
258 		struct z_erofs_pcluster *pcl;
259 
260 		if (nrpages > pcs->maxpages)
261 			continue;
262 
263 		pcl = kmem_cache_zalloc(pcs->slab, GFP_KERNEL);
264 		if (!pcl)
265 			return ERR_PTR(-ENOMEM);
266 		return pcl;
267 	}
268 	return ERR_PTR(-EINVAL);
269 }
270 
271 static void z_erofs_free_pcluster(struct z_erofs_pcluster *pcl)
272 {
273 	unsigned int pclusterpages = z_erofs_pclusterpages(pcl);
274 	int i;
275 
276 	for (i = 0; i < ARRAY_SIZE(pcluster_pool); ++i) {
277 		struct z_erofs_pcluster_slab *pcs = pcluster_pool + i;
278 
279 		if (pclusterpages > pcs->maxpages)
280 			continue;
281 
282 		kmem_cache_free(pcs->slab, pcl);
283 		return;
284 	}
285 	DBG_BUGON(1);
286 }
287 
288 static struct workqueue_struct *z_erofs_workqueue __read_mostly;
289 
290 #ifdef CONFIG_EROFS_FS_PCPU_KTHREAD
291 static struct kthread_worker __rcu **z_erofs_pcpu_workers;
292 static atomic_t erofs_percpu_workers_initialized = ATOMIC_INIT(0);
293 
294 static void erofs_destroy_percpu_workers(void)
295 {
296 	struct kthread_worker *worker;
297 	unsigned int cpu;
298 
299 	for_each_possible_cpu(cpu) {
300 		worker = rcu_dereference_protected(
301 					z_erofs_pcpu_workers[cpu], 1);
302 		rcu_assign_pointer(z_erofs_pcpu_workers[cpu], NULL);
303 		if (worker)
304 			kthread_destroy_worker(worker);
305 	}
306 	kfree(z_erofs_pcpu_workers);
307 }
308 
309 static struct kthread_worker *erofs_init_percpu_worker(int cpu)
310 {
311 	struct kthread_worker *worker =
312 		kthread_run_worker_on_cpu(cpu, 0, "erofs_worker/%u");
313 
314 	if (IS_ERR(worker))
315 		return worker;
316 	if (IS_ENABLED(CONFIG_EROFS_FS_PCPU_KTHREAD_HIPRI))
317 		sched_set_fifo_low(worker->task);
318 	return worker;
319 }
320 
321 static int erofs_init_percpu_workers(void)
322 {
323 	struct kthread_worker *worker;
324 	unsigned int cpu;
325 
326 	z_erofs_pcpu_workers = kcalloc(num_possible_cpus(),
327 			sizeof(struct kthread_worker *), GFP_ATOMIC);
328 	if (!z_erofs_pcpu_workers)
329 		return -ENOMEM;
330 
331 	for_each_online_cpu(cpu) {	/* could miss cpu{off,on}line? */
332 		worker = erofs_init_percpu_worker(cpu);
333 		if (!IS_ERR(worker))
334 			rcu_assign_pointer(z_erofs_pcpu_workers[cpu], worker);
335 	}
336 	return 0;
337 }
338 
339 #ifdef CONFIG_HOTPLUG_CPU
340 static DEFINE_SPINLOCK(z_erofs_pcpu_worker_lock);
341 static enum cpuhp_state erofs_cpuhp_state;
342 
343 static int erofs_cpu_online(unsigned int cpu)
344 {
345 	struct kthread_worker *worker, *old;
346 
347 	worker = erofs_init_percpu_worker(cpu);
348 	if (IS_ERR(worker))
349 		return PTR_ERR(worker);
350 
351 	spin_lock(&z_erofs_pcpu_worker_lock);
352 	old = rcu_dereference_protected(z_erofs_pcpu_workers[cpu],
353 			lockdep_is_held(&z_erofs_pcpu_worker_lock));
354 	if (!old)
355 		rcu_assign_pointer(z_erofs_pcpu_workers[cpu], worker);
356 	spin_unlock(&z_erofs_pcpu_worker_lock);
357 	if (old)
358 		kthread_destroy_worker(worker);
359 	return 0;
360 }
361 
362 static int erofs_cpu_offline(unsigned int cpu)
363 {
364 	struct kthread_worker *worker;
365 
366 	spin_lock(&z_erofs_pcpu_worker_lock);
367 	worker = rcu_dereference_protected(z_erofs_pcpu_workers[cpu],
368 			lockdep_is_held(&z_erofs_pcpu_worker_lock));
369 	rcu_assign_pointer(z_erofs_pcpu_workers[cpu], NULL);
370 	spin_unlock(&z_erofs_pcpu_worker_lock);
371 
372 	synchronize_rcu();
373 	if (worker)
374 		kthread_destroy_worker(worker);
375 	return 0;
376 }
377 
378 static int erofs_cpu_hotplug_init(void)
379 {
380 	int state;
381 
382 	state = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
383 			"fs/erofs:online", erofs_cpu_online, erofs_cpu_offline);
384 	if (state < 0)
385 		return state;
386 
387 	erofs_cpuhp_state = state;
388 	return 0;
389 }
390 
391 static void erofs_cpu_hotplug_destroy(void)
392 {
393 	if (erofs_cpuhp_state)
394 		cpuhp_remove_state_nocalls(erofs_cpuhp_state);
395 }
396 #else /* !CONFIG_HOTPLUG_CPU  */
397 static inline int erofs_cpu_hotplug_init(void) { return 0; }
398 static inline void erofs_cpu_hotplug_destroy(void) {}
399 #endif/* CONFIG_HOTPLUG_CPU */
400 static int z_erofs_init_pcpu_workers(struct super_block *sb)
401 {
402 	int err;
403 
404 	if (atomic_xchg(&erofs_percpu_workers_initialized, 1))
405 		return 0;
406 
407 	err = erofs_init_percpu_workers();
408 	if (err) {
409 		erofs_err(sb, "per-cpu workers: failed to allocate.");
410 		goto err_init_percpu_workers;
411 	}
412 
413 	err = erofs_cpu_hotplug_init();
414 	if (err < 0) {
415 		erofs_err(sb, "per-cpu workers: failed CPU hotplug init.");
416 		goto err_cpuhp_init;
417 	}
418 	erofs_info(sb, "initialized per-cpu workers successfully.");
419 	return err;
420 
421 err_cpuhp_init:
422 	erofs_destroy_percpu_workers();
423 err_init_percpu_workers:
424 	atomic_set(&erofs_percpu_workers_initialized, 0);
425 	return err;
426 }
427 
428 static void z_erofs_destroy_pcpu_workers(void)
429 {
430 	if (!atomic_xchg(&erofs_percpu_workers_initialized, 0))
431 		return;
432 	erofs_cpu_hotplug_destroy();
433 	erofs_destroy_percpu_workers();
434 }
435 #else /* !CONFIG_EROFS_FS_PCPU_KTHREAD */
436 static inline int z_erofs_init_pcpu_workers(struct super_block *sb) { return 0; }
437 static inline void z_erofs_destroy_pcpu_workers(void) {}
438 #endif/* CONFIG_EROFS_FS_PCPU_KTHREAD */
439 
440 void z_erofs_exit_subsystem(void)
441 {
442 	z_erofs_destroy_pcpu_workers();
443 	destroy_workqueue(z_erofs_workqueue);
444 	z_erofs_destroy_pcluster_pool();
445 	z_erofs_crypto_disable_all_engines();
446 	z_erofs_exit_decompressor();
447 }
448 
449 int __init z_erofs_init_subsystem(void)
450 {
451 	int err = z_erofs_init_decompressor();
452 
453 	if (err)
454 		goto err_decompressor;
455 
456 	err = z_erofs_create_pcluster_pool();
457 	if (err)
458 		goto err_pcluster_pool;
459 
460 	z_erofs_workqueue = alloc_workqueue("erofs_worker",
461 			WQ_UNBOUND | WQ_HIGHPRI, num_possible_cpus());
462 	if (!z_erofs_workqueue) {
463 		err = -ENOMEM;
464 		goto err_workqueue_init;
465 	}
466 
467 	return err;
468 
469 err_workqueue_init:
470 	z_erofs_destroy_pcluster_pool();
471 err_pcluster_pool:
472 	z_erofs_exit_decompressor();
473 err_decompressor:
474 	return err;
475 }
476 
477 enum z_erofs_pclustermode {
478 	/* It has previously been linked into another processing chain */
479 	Z_EROFS_PCLUSTER_INFLIGHT,
480 	/*
481 	 * A weaker form of Z_EROFS_PCLUSTER_FOLLOWED; the difference is that it
482 	 * may be dispatched to the bypass queue later due to uptodated managed
483 	 * folios.  All file-backed folios related to this pcluster cannot be
484 	 * reused for in-place I/O (or bvpage) since the pcluster may be decoded
485 	 * in a separate queue (and thus out of order).
486 	 */
487 	Z_EROFS_PCLUSTER_FOLLOWED_NOINPLACE,
488 	/*
489 	 * The pcluster has just been linked to our processing chain.
490 	 * File-backed folios (except for the head page) related to it can be
491 	 * used for in-place I/O (or bvpage).
492 	 */
493 	Z_EROFS_PCLUSTER_FOLLOWED,
494 };
495 
496 struct z_erofs_frontend {
497 	struct inode *inode, *sharedinode;
498 	struct erofs_map_blocks map;
499 	struct z_erofs_bvec_iter biter;
500 
501 	struct page *pagepool;
502 	struct page *candidate_bvpage;
503 	struct z_erofs_pcluster *pcl, *head;
504 	enum z_erofs_pclustermode mode;
505 
506 	erofs_off_t headoffset;
507 
508 	/* a pointer used to pick up inplace I/O pages */
509 	unsigned int icur;
510 };
511 
512 #define Z_EROFS_DEFINE_FRONTEND(fe, i, si, ho) struct z_erofs_frontend fe = { \
513 	.inode = i, .sharedinode = si, .head = Z_EROFS_PCLUSTER_TAIL, \
514 	.mode = Z_EROFS_PCLUSTER_FOLLOWED, .headoffset = ho }
515 
516 static bool z_erofs_should_alloc_cache(struct z_erofs_frontend *fe)
517 {
518 	unsigned int cachestrategy = EROFS_I_SB(fe->inode)->opt.cache_strategy;
519 
520 	if (cachestrategy <= EROFS_ZIP_CACHE_DISABLED)
521 		return false;
522 
523 	if (!(fe->map.m_flags & EROFS_MAP_FULL_MAPPED))
524 		return true;
525 
526 	if (cachestrategy >= EROFS_ZIP_CACHE_READAROUND &&
527 	    fe->map.m_la < fe->headoffset)
528 		return true;
529 
530 	return false;
531 }
532 
533 static void z_erofs_bind_cache(struct z_erofs_frontend *fe)
534 {
535 	struct address_space *mc = MNGD_MAPPING(EROFS_I_SB(fe->inode));
536 	struct z_erofs_pcluster *pcl = fe->pcl;
537 	unsigned int pclusterpages = z_erofs_pclusterpages(pcl);
538 	bool shouldalloc = z_erofs_should_alloc_cache(fe);
539 	pgoff_t poff = pcl->pos >> PAGE_SHIFT;
540 	bool may_bypass = true;
541 	/* Optimistic allocation, as in-place I/O can be used as a fallback */
542 	gfp_t gfp = (mapping_gfp_mask(mc) & ~__GFP_DIRECT_RECLAIM) |
543 			__GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN;
544 	struct folio *folio, *newfolio;
545 	unsigned int i;
546 
547 	if (i_blocksize(fe->inode) != PAGE_SIZE ||
548 	    fe->mode < Z_EROFS_PCLUSTER_FOLLOWED)
549 		return;
550 
551 	for (i = 0; i < pclusterpages; ++i) {
552 		/* Inaccurate check w/o locking to avoid unneeded lookups */
553 		if (READ_ONCE(pcl->compressed_bvecs[i].page))
554 			continue;
555 
556 		folio = filemap_get_folio(mc, poff + i);
557 		if (IS_ERR(folio)) {
558 			may_bypass = false;
559 			if (!shouldalloc)
560 				continue;
561 
562 			/*
563 			 * Allocate a managed folio for cached I/O, or it may be
564 			 * then filled with a file-backed folio for in-place I/O
565 			 */
566 			newfolio = filemap_alloc_folio(gfp, 0, NULL);
567 			if (!newfolio)
568 				continue;
569 			newfolio->private = Z_EROFS_PREALLOCATED_FOLIO;
570 			folio = NULL;
571 		}
572 		spin_lock(&pcl->lockref.lock);
573 		if (!pcl->compressed_bvecs[i].page) {
574 			pcl->compressed_bvecs[i].page =
575 				folio_page(folio ?: newfolio, 0);
576 			spin_unlock(&pcl->lockref.lock);
577 			continue;
578 		}
579 		spin_unlock(&pcl->lockref.lock);
580 		folio_put(folio ?: newfolio);
581 	}
582 
583 	/*
584 	 * Don't perform in-place I/O if all compressed pages are available in
585 	 * the managed cache, as the pcluster can be moved to the bypass queue.
586 	 */
587 	if (may_bypass)
588 		fe->mode = Z_EROFS_PCLUSTER_FOLLOWED_NOINPLACE;
589 }
590 
591 /* (erofs_shrinker) disconnect cached encoded data with pclusters */
592 static int erofs_try_to_free_all_cached_folios(struct erofs_sb_info *sbi,
593 					       struct z_erofs_pcluster *pcl)
594 {
595 	unsigned int pclusterpages = z_erofs_pclusterpages(pcl);
596 	struct folio *folio;
597 	int i;
598 
599 	DBG_BUGON(pcl->from_meta);
600 	/* Each cached folio contains one page unless bs > ps is supported */
601 	for (i = 0; i < pclusterpages; ++i) {
602 		if (pcl->compressed_bvecs[i].page) {
603 			folio = page_folio(pcl->compressed_bvecs[i].page);
604 			/* Avoid reclaiming or migrating this folio */
605 			if (!folio_trylock(folio))
606 				return -EBUSY;
607 
608 			if (!erofs_folio_is_managed(sbi, folio))
609 				continue;
610 			pcl->compressed_bvecs[i].page = NULL;
611 			folio_detach_private(folio);
612 			folio_unlock(folio);
613 		}
614 	}
615 	return 0;
616 }
617 
618 static bool z_erofs_cache_release_folio(struct folio *folio, gfp_t gfp)
619 {
620 	struct z_erofs_pcluster *pcl = folio_get_private(folio);
621 	struct z_erofs_bvec *bvec = pcl->compressed_bvecs;
622 	struct z_erofs_bvec *end = bvec + z_erofs_pclusterpages(pcl);
623 	bool ret;
624 
625 	if (!folio_test_private(folio))
626 		return true;
627 
628 	ret = false;
629 	spin_lock(&pcl->lockref.lock);
630 	if (pcl->lockref.count <= 0) {
631 		DBG_BUGON(pcl->from_meta);
632 		for (; bvec < end; ++bvec) {
633 			if (bvec->page && page_folio(bvec->page) == folio) {
634 				bvec->page = NULL;
635 				folio_detach_private(folio);
636 				ret = true;
637 				break;
638 			}
639 		}
640 	}
641 	spin_unlock(&pcl->lockref.lock);
642 	return ret;
643 }
644 
645 /*
646  * It will be called only on inode eviction. In case that there are still some
647  * decompression requests in progress, wait with rescheduling for a bit here.
648  * An extra lock could be introduced instead but it seems unnecessary.
649  */
650 static void z_erofs_cache_invalidate_folio(struct folio *folio,
651 					   size_t offset, size_t length)
652 {
653 	const size_t stop = length + offset;
654 
655 	/* Check for potential overflow in debug mode */
656 	DBG_BUGON(stop > folio_size(folio) || stop < length);
657 
658 	if (offset == 0 && stop == folio_size(folio))
659 		while (!z_erofs_cache_release_folio(folio, 0))
660 			cond_resched();
661 }
662 
663 static const struct address_space_operations z_erofs_cache_aops = {
664 	.release_folio = z_erofs_cache_release_folio,
665 	.invalidate_folio = z_erofs_cache_invalidate_folio,
666 };
667 
668 int z_erofs_init_super(struct super_block *sb)
669 {
670 	struct inode *inode;
671 	int err;
672 
673 	err = z_erofs_init_pcpu_workers(sb);
674 	if (err)
675 		return err;
676 
677 	inode = new_inode(sb);
678 	if (!inode)
679 		return -ENOMEM;
680 	set_nlink(inode, 1);
681 	inode->i_size = OFFSET_MAX;
682 	inode->i_mapping->a_ops = &z_erofs_cache_aops;
683 	mapping_set_gfp_mask(inode->i_mapping, GFP_KERNEL);
684 	EROFS_SB(sb)->managed_cache = inode;
685 	xa_init(&EROFS_SB(sb)->managed_pslots);
686 	return 0;
687 }
688 
689 /* callers must be with pcluster lock held */
690 static int z_erofs_attach_page(struct z_erofs_frontend *fe,
691 			       struct z_erofs_bvec *bvec, bool exclusive)
692 {
693 	struct z_erofs_pcluster *pcl = fe->pcl;
694 	int ret;
695 
696 	if (exclusive) {
697 		/* Inplace I/O is limited to one page for uncompressed data */
698 		if (pcl->algorithmformat < Z_EROFS_COMPRESSION_MAX ||
699 		    fe->icur <= 1) {
700 			/* Try to prioritize inplace I/O here */
701 			spin_lock(&pcl->lockref.lock);
702 			while (fe->icur > 0) {
703 				if (pcl->compressed_bvecs[--fe->icur].page)
704 					continue;
705 				pcl->compressed_bvecs[fe->icur] = *bvec;
706 				spin_unlock(&pcl->lockref.lock);
707 				return 0;
708 			}
709 			spin_unlock(&pcl->lockref.lock);
710 		}
711 
712 		/* otherwise, check if it can be used as a bvpage */
713 		if (fe->mode >= Z_EROFS_PCLUSTER_FOLLOWED &&
714 		    !fe->candidate_bvpage)
715 			fe->candidate_bvpage = bvec->page;
716 	}
717 	ret = z_erofs_bvec_enqueue(&fe->biter, bvec, &fe->candidate_bvpage,
718 				   &fe->pagepool);
719 	fe->pcl->vcnt += (ret >= 0);
720 	return ret;
721 }
722 
723 static bool z_erofs_get_pcluster(struct z_erofs_pcluster *pcl)
724 {
725 	if (lockref_get_not_zero(&pcl->lockref))
726 		return true;
727 
728 	spin_lock(&pcl->lockref.lock);
729 	if (__lockref_is_dead(&pcl->lockref)) {
730 		spin_unlock(&pcl->lockref.lock);
731 		return false;
732 	}
733 
734 	if (!pcl->lockref.count++)
735 		atomic_long_dec(&erofs_global_shrink_cnt);
736 	spin_unlock(&pcl->lockref.lock);
737 	return true;
738 }
739 
740 static int z_erofs_register_pcluster(struct z_erofs_frontend *fe)
741 {
742 	struct erofs_map_blocks *map = &fe->map;
743 	struct super_block *sb = fe->inode->i_sb;
744 	struct erofs_sb_info *sbi = EROFS_SB(sb);
745 	struct z_erofs_pcluster *pcl, *pre;
746 	unsigned int pageofs_in;
747 	int err;
748 
749 	pageofs_in = erofs_blkoff(sb, map->m_pa);
750 	pcl = z_erofs_alloc_pcluster(pageofs_in + map->m_plen);
751 	if (IS_ERR(pcl))
752 		return PTR_ERR(pcl);
753 
754 	lockref_init(&pcl->lockref); /* one ref for this request */
755 	pcl->algorithmformat = map->m_algorithmformat;
756 	pcl->pclustersize = map->m_plen;
757 	pcl->length = 0;
758 	pcl->partial = true;
759 	pcl->next = fe->head;
760 	pcl->pos = map->m_pa;
761 	pcl->pageofs_in = pageofs_in;
762 	pcl->pageofs_out = map->m_la & ~PAGE_MASK;
763 	pcl->from_meta = map->m_flags & EROFS_MAP_META;
764 	fe->mode = Z_EROFS_PCLUSTER_FOLLOWED;
765 
766 	/*
767 	 * lock all primary followed works before visible to others
768 	 * and mutex_trylock *never* fails for a new pcluster.
769 	 */
770 	mutex_init(&pcl->lock);
771 	DBG_BUGON(!mutex_trylock(&pcl->lock));
772 
773 	if (!pcl->from_meta) {
774 		while (1) {
775 			xa_lock(&sbi->managed_pslots);
776 			pre = __xa_cmpxchg(&sbi->managed_pslots, pcl->pos,
777 					   NULL, pcl, GFP_KERNEL);
778 			if (!pre || xa_is_err(pre) || z_erofs_get_pcluster(pre)) {
779 				xa_unlock(&sbi->managed_pslots);
780 				break;
781 			}
782 			/* try to legitimize the current in-tree one */
783 			xa_unlock(&sbi->managed_pslots);
784 			cond_resched();
785 		}
786 		if (xa_is_err(pre)) {
787 			err = xa_err(pre);
788 			goto err_out;
789 		} else if (pre) {
790 			fe->pcl = pre;
791 			err = -EEXIST;
792 			goto err_out;
793 		}
794 	}
795 	fe->head = fe->pcl = pcl;
796 	return 0;
797 
798 err_out:
799 	mutex_unlock(&pcl->lock);
800 	z_erofs_free_pcluster(pcl);
801 	return err;
802 }
803 
804 static int z_erofs_pcluster_begin(struct z_erofs_frontend *fe)
805 {
806 	struct erofs_map_blocks *map = &fe->map;
807 	struct super_block *sb = fe->inode->i_sb;
808 	struct z_erofs_pcluster *pcl = NULL;
809 	void *ptr = NULL;
810 	int ret;
811 
812 	DBG_BUGON(fe->pcl);
813 	/* must be Z_EROFS_PCLUSTER_TAIL or pointed to previous pcluster */
814 	DBG_BUGON(!fe->head);
815 
816 	if (map->m_flags & EROFS_MAP_META) {
817 		ret = erofs_init_metabuf(&map->buf, sb,
818 					 erofs_inode_in_metabox(fe->inode));
819 		if (ret)
820 			return ret;
821 		ptr = erofs_bread(&map->buf, map->m_pa, false);
822 		if (IS_ERR(ptr)) {
823 			erofs_err(sb, "failed to read inline data %pe @ pa %llu of nid %llu",
824 				  ptr, map->m_pa, EROFS_I(fe->inode)->nid);
825 			return PTR_ERR(ptr);
826 		}
827 		ptr = map->buf.page;
828 	} else {
829 		while (1) {
830 			rcu_read_lock();
831 			pcl = xa_load(&EROFS_SB(sb)->managed_pslots, map->m_pa);
832 			if (!pcl || z_erofs_get_pcluster(pcl)) {
833 				DBG_BUGON(pcl && map->m_pa != pcl->pos);
834 				rcu_read_unlock();
835 				break;
836 			}
837 			rcu_read_unlock();
838 		}
839 	}
840 
841 	if (pcl) {
842 		fe->pcl = pcl;
843 		ret = -EEXIST;
844 	} else {
845 		ret = z_erofs_register_pcluster(fe);
846 	}
847 
848 	if (ret == -EEXIST) {
849 		mutex_lock(&fe->pcl->lock);
850 		/* check if this pcluster hasn't been linked into any chain. */
851 		if (!cmpxchg(&fe->pcl->next, NULL, fe->head)) {
852 			/* .. so it can be attached to our submission chain */
853 			fe->head = fe->pcl;
854 			fe->mode = Z_EROFS_PCLUSTER_FOLLOWED;
855 		} else {	/* otherwise, it belongs to an inflight chain */
856 			fe->mode = Z_EROFS_PCLUSTER_INFLIGHT;
857 		}
858 	} else if (ret) {
859 		return ret;
860 	}
861 
862 	z_erofs_bvec_iter_begin(&fe->biter, &fe->pcl->bvset,
863 				Z_EROFS_INLINE_BVECS, fe->pcl->vcnt);
864 	if (!fe->pcl->from_meta) {
865 		/* bind cache first when cached decompression is preferred */
866 		z_erofs_bind_cache(fe);
867 	} else {
868 		folio_get(page_folio((struct page *)ptr));
869 		WRITE_ONCE(fe->pcl->compressed_bvecs[0].page, ptr);
870 		fe->pcl->pageofs_in = map->m_pa & ~PAGE_MASK;
871 		fe->mode = Z_EROFS_PCLUSTER_FOLLOWED_NOINPLACE;
872 	}
873 	/* file-backed inplace I/O pages are traversed in reverse order */
874 	fe->icur = z_erofs_pclusterpages(fe->pcl);
875 	return 0;
876 }
877 
878 static void z_erofs_rcu_callback(struct rcu_head *head)
879 {
880 	z_erofs_free_pcluster(container_of(head, struct z_erofs_pcluster, rcu));
881 }
882 
883 static bool __erofs_try_to_release_pcluster(struct erofs_sb_info *sbi,
884 					  struct z_erofs_pcluster *pcl)
885 {
886 	if (pcl->lockref.count)
887 		return false;
888 
889 	/*
890 	 * Note that all cached folios should be detached before deleted from
891 	 * the XArray.  Otherwise some folios could be still attached to the
892 	 * orphan old pcluster when the new one is available in the tree.
893 	 */
894 	if (erofs_try_to_free_all_cached_folios(sbi, pcl))
895 		return false;
896 
897 	/*
898 	 * It's impossible to fail after the pcluster is freezed, but in order
899 	 * to avoid some race conditions, add a DBG_BUGON to observe this.
900 	 */
901 	DBG_BUGON(__xa_erase(&sbi->managed_pslots, pcl->pos) != pcl);
902 
903 	lockref_mark_dead(&pcl->lockref);
904 	return true;
905 }
906 
907 static bool erofs_try_to_release_pcluster(struct erofs_sb_info *sbi,
908 					  struct z_erofs_pcluster *pcl)
909 {
910 	bool free;
911 
912 	spin_lock(&pcl->lockref.lock);
913 	free = __erofs_try_to_release_pcluster(sbi, pcl);
914 	spin_unlock(&pcl->lockref.lock);
915 	if (free) {
916 		atomic_long_dec(&erofs_global_shrink_cnt);
917 		call_rcu(&pcl->rcu, z_erofs_rcu_callback);
918 	}
919 	return free;
920 }
921 
922 unsigned long z_erofs_shrink_scan(struct erofs_sb_info *sbi, unsigned long nr)
923 {
924 	struct z_erofs_pcluster *pcl;
925 	unsigned long index, freed = 0;
926 
927 	xa_lock(&sbi->managed_pslots);
928 	xa_for_each(&sbi->managed_pslots, index, pcl) {
929 		/* try to shrink each valid pcluster */
930 		if (!erofs_try_to_release_pcluster(sbi, pcl))
931 			continue;
932 		xa_unlock(&sbi->managed_pslots);
933 
934 		++freed;
935 		if (!--nr)
936 			return freed;
937 		xa_lock(&sbi->managed_pslots);
938 	}
939 	xa_unlock(&sbi->managed_pslots);
940 	return freed;
941 }
942 
943 static void z_erofs_put_pcluster(struct erofs_sb_info *sbi,
944 		struct z_erofs_pcluster *pcl, bool try_free)
945 {
946 	bool free = false;
947 
948 	if (lockref_put_or_lock(&pcl->lockref))
949 		return;
950 
951 	DBG_BUGON(__lockref_is_dead(&pcl->lockref));
952 	if (!--pcl->lockref.count) {
953 		if (try_free && xa_trylock(&sbi->managed_pslots)) {
954 			free = __erofs_try_to_release_pcluster(sbi, pcl);
955 			xa_unlock(&sbi->managed_pslots);
956 		}
957 		atomic_long_add(!free, &erofs_global_shrink_cnt);
958 	}
959 	spin_unlock(&pcl->lockref.lock);
960 	if (free)
961 		call_rcu(&pcl->rcu, z_erofs_rcu_callback);
962 }
963 
964 static void z_erofs_pcluster_end(struct z_erofs_frontend *fe)
965 {
966 	struct z_erofs_pcluster *pcl = fe->pcl;
967 
968 	if (!pcl)
969 		return;
970 
971 	z_erofs_bvec_iter_end(&fe->biter);
972 	mutex_unlock(&pcl->lock);
973 
974 	if (fe->candidate_bvpage)
975 		fe->candidate_bvpage = NULL;
976 
977 	/* Drop refcount if it doesn't belong to our processing chain */
978 	if (fe->mode < Z_EROFS_PCLUSTER_FOLLOWED_NOINPLACE)
979 		z_erofs_put_pcluster(EROFS_I_SB(fe->inode), pcl, false);
980 	fe->pcl = NULL;
981 }
982 
983 static int z_erofs_read_fragment(struct super_block *sb, struct folio *folio,
984 			unsigned int cur, unsigned int end, erofs_off_t pos)
985 {
986 	struct inode *packed_inode = EROFS_SB(sb)->packed_inode;
987 	struct erofs_buf buf = __EROFS_BUF_INITIALIZER;
988 	unsigned int cnt;
989 	u8 *src;
990 
991 	if (!packed_inode)
992 		return -EFSCORRUPTED;
993 
994 	buf.mapping = packed_inode->i_mapping;
995 	for (; cur < end; cur += cnt, pos += cnt) {
996 		cnt = min(end - cur, sb->s_blocksize - erofs_blkoff(sb, pos));
997 		src = erofs_bread(&buf, pos, true);
998 		if (IS_ERR(src)) {
999 			erofs_put_metabuf(&buf);
1000 			return PTR_ERR(src);
1001 		}
1002 		memcpy_to_folio(folio, cur, src, cnt);
1003 	}
1004 	erofs_put_metabuf(&buf);
1005 	return 0;
1006 }
1007 
1008 static int z_erofs_scan_folio(struct z_erofs_frontend *f,
1009 			      struct folio *folio, bool ra)
1010 {
1011 	struct inode *const inode = f->inode;
1012 	struct erofs_map_blocks *const map = &f->map;
1013 	const loff_t offset = folio_pos(folio);
1014 	const unsigned int bs = i_blocksize(inode);
1015 	unsigned int end = folio_size(folio), split = 0, cur, pgs;
1016 	bool tight, excl;
1017 	int err = 0;
1018 
1019 	tight = (bs == PAGE_SIZE);
1020 	erofs_onlinefolio_init(folio);
1021 	do {
1022 		if (offset + end - 1 < map->m_la ||
1023 		    offset + end - 1 >= map->m_la + map->m_llen) {
1024 			z_erofs_pcluster_end(f);
1025 			map->m_la = offset + end - 1;
1026 			map->m_llen = 0;
1027 			err = z_erofs_map_blocks_iter(inode, map, 0);
1028 			if (err)
1029 				break;
1030 		}
1031 
1032 		cur = offset > map->m_la ? 0 : map->m_la - offset;
1033 		pgs = round_down(cur, PAGE_SIZE);
1034 		/* bump split parts first to avoid several separate cases */
1035 		++split;
1036 
1037 		if (!(map->m_flags & EROFS_MAP_MAPPED)) {
1038 			folio_zero_segment(folio, cur, end);
1039 			tight = false;
1040 		} else if (map->m_flags & __EROFS_MAP_FRAGMENT) {
1041 			erofs_off_t fpos = offset + cur - map->m_la;
1042 
1043 			err = z_erofs_read_fragment(inode->i_sb, folio, cur,
1044 					cur + min(map->m_llen - fpos, end - cur),
1045 					EROFS_I(inode)->z_fragmentoff + fpos);
1046 			if (err)
1047 				break;
1048 			tight = false;
1049 		} else {
1050 			if (!f->pcl) {
1051 				err = z_erofs_pcluster_begin(f);
1052 				if (err)
1053 					break;
1054 				f->pcl->besteffort |= !ra;
1055 			}
1056 
1057 			pgs = round_down(end - 1, PAGE_SIZE);
1058 			/*
1059 			 * Ensure this partial page belongs to this submit chain
1060 			 * rather than other concurrent submit chains or
1061 			 * noio(bypass) chains since those chains are handled
1062 			 * asynchronously thus it cannot be used for inplace I/O
1063 			 * or bvpage (should be processed in the strict order.)
1064 			 */
1065 			tight &= (f->mode >= Z_EROFS_PCLUSTER_FOLLOWED);
1066 			excl = false;
1067 			if (cur <= pgs) {
1068 				excl = (split <= 1) || tight;
1069 				cur = pgs;
1070 			}
1071 
1072 			err = z_erofs_attach_page(f, &((struct z_erofs_bvec) {
1073 				.page = folio_page(folio, pgs >> PAGE_SHIFT),
1074 				.offset = offset + pgs - map->m_la,
1075 				.end = end - pgs, }), excl);
1076 			if (err)
1077 				break;
1078 
1079 			erofs_onlinefolio_split(folio);
1080 			if (f->pcl->length < offset + end - map->m_la) {
1081 				f->pcl->length = offset + end - map->m_la;
1082 				f->pcl->pageofs_out = map->m_la & ~PAGE_MASK;
1083 			}
1084 			if ((map->m_flags & EROFS_MAP_FULL_MAPPED) &&
1085 			    !(map->m_flags & EROFS_MAP_PARTIAL_REF) &&
1086 			    f->pcl->length == map->m_llen)
1087 				f->pcl->partial = false;
1088 		}
1089 		/* shorten the remaining extent to update progress */
1090 		map->m_llen = offset + cur - map->m_la;
1091 		map->m_flags &= ~EROFS_MAP_FULL_MAPPED;
1092 		if (cur <= pgs) {
1093 			split = cur < pgs;
1094 			tight = (bs == PAGE_SIZE);
1095 		}
1096 	} while ((end = cur) > 0);
1097 	erofs_onlinefolio_end(folio, err, false);
1098 	return err;
1099 }
1100 
1101 static bool z_erofs_page_is_invalidated(struct page *page)
1102 {
1103 	return !page_folio(page)->mapping && !z_erofs_is_shortlived_page(page);
1104 }
1105 
1106 struct z_erofs_backend {
1107 	struct page *onstack_pages[Z_EROFS_ONSTACK_PAGES];
1108 	struct super_block *sb;
1109 	struct z_erofs_pcluster *pcl;
1110 	/* pages with the longest decompressed length for deduplication */
1111 	struct page **decompressed_pages;
1112 	/* pages to keep the compressed data */
1113 	struct page **compressed_pages;
1114 
1115 	struct list_head decompressed_secondary_bvecs;
1116 	struct page **pagepool;
1117 	unsigned int onstack_used, nr_pages;
1118 	/* indicate if temporary copies should be preserved for later use */
1119 	bool keepxcpy;
1120 };
1121 
1122 struct z_erofs_bvec_item {
1123 	struct z_erofs_bvec bvec;
1124 	struct list_head list;
1125 };
1126 
1127 static void z_erofs_do_decompressed_bvec(struct z_erofs_backend *be,
1128 					 struct z_erofs_bvec *bvec)
1129 {
1130 	int poff = bvec->offset + be->pcl->pageofs_out;
1131 	struct z_erofs_bvec_item *item;
1132 	struct page **page;
1133 
1134 	if (!(poff & ~PAGE_MASK) && (bvec->end == PAGE_SIZE ||
1135 			bvec->offset + bvec->end == be->pcl->length)) {
1136 		DBG_BUGON((poff >> PAGE_SHIFT) >= be->nr_pages);
1137 		page = be->decompressed_pages + (poff >> PAGE_SHIFT);
1138 		if (!*page) {
1139 			*page = bvec->page;
1140 			return;
1141 		}
1142 	} else {
1143 		be->keepxcpy = true;
1144 	}
1145 
1146 	/* (cold path) one pcluster is requested multiple times */
1147 	item = kmalloc(sizeof(*item), GFP_KERNEL | __GFP_NOFAIL);
1148 	item->bvec = *bvec;
1149 	list_add(&item->list, &be->decompressed_secondary_bvecs);
1150 }
1151 
1152 static void z_erofs_fill_other_copies(struct z_erofs_backend *be, int err)
1153 {
1154 	unsigned int off0 = be->pcl->pageofs_out;
1155 	struct list_head *p, *n;
1156 
1157 	list_for_each_safe(p, n, &be->decompressed_secondary_bvecs) {
1158 		struct z_erofs_bvec_item *bvi;
1159 		unsigned int end, cur;
1160 		void *dst, *src;
1161 
1162 		bvi = container_of(p, struct z_erofs_bvec_item, list);
1163 		cur = bvi->bvec.offset < 0 ? -bvi->bvec.offset : 0;
1164 		end = min_t(unsigned int, be->pcl->length - bvi->bvec.offset,
1165 			    bvi->bvec.end);
1166 		dst = kmap_local_page(bvi->bvec.page);
1167 		while (cur < end) {
1168 			unsigned int pgnr, scur, len;
1169 
1170 			pgnr = (bvi->bvec.offset + cur + off0) >> PAGE_SHIFT;
1171 			DBG_BUGON(pgnr >= be->nr_pages);
1172 
1173 			scur = bvi->bvec.offset + cur -
1174 					((pgnr << PAGE_SHIFT) - off0);
1175 			len = min_t(unsigned int, end - cur, PAGE_SIZE - scur);
1176 			if (!be->decompressed_pages[pgnr]) {
1177 				err = -EFSCORRUPTED;
1178 				cur += len;
1179 				continue;
1180 			}
1181 			src = kmap_local_page(be->decompressed_pages[pgnr]);
1182 			memcpy(dst + cur, src + scur, len);
1183 			kunmap_local(src);
1184 			cur += len;
1185 		}
1186 		kunmap_local(dst);
1187 		erofs_onlinefolio_end(page_folio(bvi->bvec.page), err, true);
1188 		list_del(p);
1189 		kfree(bvi);
1190 	}
1191 }
1192 
1193 static void z_erofs_parse_out_bvecs(struct z_erofs_backend *be)
1194 {
1195 	struct z_erofs_pcluster *pcl = be->pcl;
1196 	struct z_erofs_bvec_iter biter;
1197 	struct page *old_bvpage;
1198 	int i;
1199 
1200 	z_erofs_bvec_iter_begin(&biter, &pcl->bvset, Z_EROFS_INLINE_BVECS, 0);
1201 	for (i = 0; i < pcl->vcnt; ++i) {
1202 		struct z_erofs_bvec bvec;
1203 
1204 		z_erofs_bvec_dequeue(&biter, &bvec, &old_bvpage);
1205 
1206 		if (old_bvpage)
1207 			z_erofs_put_shortlivedpage(be->pagepool, old_bvpage);
1208 
1209 		DBG_BUGON(z_erofs_page_is_invalidated(bvec.page));
1210 		z_erofs_do_decompressed_bvec(be, &bvec);
1211 	}
1212 
1213 	old_bvpage = z_erofs_bvec_iter_end(&biter);
1214 	if (old_bvpage)
1215 		z_erofs_put_shortlivedpage(be->pagepool, old_bvpage);
1216 }
1217 
1218 static int z_erofs_parse_in_bvecs(struct z_erofs_backend *be, bool *overlapped)
1219 {
1220 	struct z_erofs_pcluster *pcl = be->pcl;
1221 	unsigned int pclusterpages = z_erofs_pclusterpages(pcl);
1222 	int i, err = 0;
1223 
1224 	*overlapped = false;
1225 	for (i = 0; i < pclusterpages; ++i) {
1226 		struct z_erofs_bvec *bvec = &pcl->compressed_bvecs[i];
1227 		struct page *page = bvec->page;
1228 
1229 		/* compressed data ought to be valid when decompressing */
1230 		if (IS_ERR(page) || !page) {
1231 			bvec->page = NULL;	/* clear the failure reason */
1232 			err = page ? PTR_ERR(page) : -EIO;
1233 			continue;
1234 		}
1235 		be->compressed_pages[i] = page;
1236 
1237 		if (pcl->from_meta ||
1238 		    erofs_folio_is_managed(EROFS_SB(be->sb), page_folio(page))) {
1239 			if (!PageUptodate(page))
1240 				err = -EIO;
1241 			continue;
1242 		}
1243 
1244 		DBG_BUGON(z_erofs_page_is_invalidated(page));
1245 		if (z_erofs_is_shortlived_page(page))
1246 			continue;
1247 		z_erofs_do_decompressed_bvec(be, bvec);
1248 		*overlapped = true;
1249 	}
1250 	return err;
1251 }
1252 
1253 static int z_erofs_decompress_pcluster(struct z_erofs_backend *be, bool eio)
1254 {
1255 	struct erofs_sb_info *const sbi = EROFS_SB(be->sb);
1256 	struct z_erofs_pcluster *pcl = be->pcl;
1257 	unsigned int pclusterpages = z_erofs_pclusterpages(pcl);
1258 	const struct z_erofs_decompressor *alg =
1259 				z_erofs_decomp[pcl->algorithmformat];
1260 	bool try_free = true;
1261 	int i, j, jtop, err2, err = eio ? -EIO : 0;
1262 	struct page *page;
1263 	bool overlapped;
1264 	const char *reason;
1265 
1266 	mutex_lock(&pcl->lock);
1267 	be->nr_pages = PAGE_ALIGN(pcl->length + pcl->pageofs_out) >> PAGE_SHIFT;
1268 
1269 	/* allocate (de)compressed page arrays if cannot be kept on stack */
1270 	be->decompressed_pages = NULL;
1271 	be->compressed_pages = NULL;
1272 	be->onstack_used = 0;
1273 	if (be->nr_pages <= Z_EROFS_ONSTACK_PAGES) {
1274 		be->decompressed_pages = be->onstack_pages;
1275 		be->onstack_used = be->nr_pages;
1276 		memset(be->decompressed_pages, 0,
1277 		       sizeof(struct page *) * be->nr_pages);
1278 	}
1279 
1280 	if (pclusterpages + be->onstack_used <= Z_EROFS_ONSTACK_PAGES)
1281 		be->compressed_pages = be->onstack_pages + be->onstack_used;
1282 
1283 	if (!be->decompressed_pages)
1284 		be->decompressed_pages =
1285 			kvcalloc(be->nr_pages, sizeof(struct page *),
1286 				 GFP_KERNEL | __GFP_NOFAIL);
1287 	if (!be->compressed_pages)
1288 		be->compressed_pages =
1289 			kvcalloc(pclusterpages, sizeof(struct page *),
1290 				 GFP_KERNEL | __GFP_NOFAIL);
1291 
1292 	z_erofs_parse_out_bvecs(be);
1293 	err2 = z_erofs_parse_in_bvecs(be, &overlapped);
1294 	if (err2)
1295 		err = err2;
1296 	if (!err) {
1297 		reason = alg->decompress(&(struct z_erofs_decompress_req) {
1298 					.sb = be->sb,
1299 					.in = be->compressed_pages,
1300 					.out = be->decompressed_pages,
1301 					.inpages = pclusterpages,
1302 					.outpages = be->nr_pages,
1303 					.pageofs_in = pcl->pageofs_in,
1304 					.pageofs_out = pcl->pageofs_out,
1305 					.inputsize = pcl->pclustersize,
1306 					.outputsize = pcl->length,
1307 					.alg = pcl->algorithmformat,
1308 					.inplace_io = overlapped,
1309 					.partial_decoding = pcl->partial,
1310 					.fillgaps = be->keepxcpy,
1311 					.gfp = pcl->besteffort ? GFP_KERNEL :
1312 						GFP_NOWAIT | __GFP_NORETRY
1313 				 }, be->pagepool);
1314 		if (IS_ERR(reason)) {
1315 			if (pcl->besteffort || reason != ERR_PTR(-ENOMEM))
1316 				erofs_err(be->sb, "failed to decompress (%s) %pe @ pa %llu size %u => %u",
1317 					  alg->name, reason, pcl->pos,
1318 					  pcl->pclustersize, pcl->length);
1319 			err = PTR_ERR(reason);
1320 		} else if (unlikely(reason)) {
1321 			erofs_err(be->sb, "failed to decompress (%s) %s @ pa %llu size %u => %u",
1322 				  alg->name, reason, pcl->pos,
1323 				  pcl->pclustersize, pcl->length);
1324 			err = -EFSCORRUPTED;
1325 		}
1326 	}
1327 
1328 	/* must handle all compressed pages before actual file pages */
1329 	if (pcl->from_meta) {
1330 		folio_put(page_folio(pcl->compressed_bvecs[0].page));
1331 		WRITE_ONCE(pcl->compressed_bvecs[0].page, NULL);
1332 	} else {
1333 		/* managed folios are still left in compressed_bvecs[] */
1334 		for (i = 0; i < pclusterpages; ++i) {
1335 			page = be->compressed_pages[i];
1336 			if (!page)
1337 				continue;
1338 			if (erofs_folio_is_managed(sbi, page_folio(page))) {
1339 				try_free = false;
1340 				continue;
1341 			}
1342 			(void)z_erofs_put_shortlivedpage(be->pagepool, page);
1343 			WRITE_ONCE(pcl->compressed_bvecs[i].page, NULL);
1344 		}
1345 	}
1346 	if (be->compressed_pages < be->onstack_pages ||
1347 	    be->compressed_pages >= be->onstack_pages + Z_EROFS_ONSTACK_PAGES)
1348 		kvfree(be->compressed_pages);
1349 
1350 	jtop = 0;
1351 	z_erofs_fill_other_copies(be, err);
1352 	for (i = 0; i < be->nr_pages; ++i) {
1353 		page = be->decompressed_pages[i];
1354 		if (!page)
1355 			continue;
1356 
1357 		DBG_BUGON(z_erofs_page_is_invalidated(page));
1358 		if (!z_erofs_is_shortlived_page(page)) {
1359 			erofs_onlinefolio_end(page_folio(page), err, true);
1360 			continue;
1361 		}
1362 		if (pcl->algorithmformat != Z_EROFS_COMPRESSION_LZ4) {
1363 			erofs_pagepool_add(be->pagepool, page);
1364 			continue;
1365 		}
1366 		for (j = 0; j < jtop && be->decompressed_pages[j] != page; ++j)
1367 			;
1368 		if (j >= jtop)	/* this bounce page is newly detected */
1369 			be->decompressed_pages[jtop++] = page;
1370 	}
1371 	while (jtop)
1372 		erofs_pagepool_add(be->pagepool,
1373 				   be->decompressed_pages[--jtop]);
1374 	if (be->decompressed_pages != be->onstack_pages)
1375 		kvfree(be->decompressed_pages);
1376 
1377 	pcl->length = 0;
1378 	pcl->partial = true;
1379 	pcl->besteffort = false;
1380 	pcl->bvset.nextpage = NULL;
1381 	pcl->vcnt = 0;
1382 
1383 	/* pcluster lock MUST be taken before the following line */
1384 	WRITE_ONCE(pcl->next, NULL);
1385 	mutex_unlock(&pcl->lock);
1386 
1387 	if (pcl->from_meta)
1388 		z_erofs_free_pcluster(pcl);
1389 	else
1390 		z_erofs_put_pcluster(sbi, pcl, try_free);
1391 	return err;
1392 }
1393 
1394 static int z_erofs_decompress_queue(const struct z_erofs_decompressqueue *io,
1395 				    struct page **pagepool)
1396 {
1397 	struct z_erofs_backend be = {
1398 		.sb = io->sb,
1399 		.pagepool = pagepool,
1400 		.decompressed_secondary_bvecs =
1401 			LIST_HEAD_INIT(be.decompressed_secondary_bvecs),
1402 		.pcl = io->head,
1403 	};
1404 	struct z_erofs_pcluster *next;
1405 	int err = 0;
1406 
1407 	for (; be.pcl != Z_EROFS_PCLUSTER_TAIL; be.pcl = next) {
1408 		DBG_BUGON(!be.pcl);
1409 		next = READ_ONCE(be.pcl->next);
1410 		err = z_erofs_decompress_pcluster(&be, io->eio) ?: err;
1411 	}
1412 	return err;
1413 }
1414 
1415 static void z_erofs_decompressqueue_work(struct work_struct *work)
1416 {
1417 	struct z_erofs_decompressqueue *bgq =
1418 		container_of(work, struct z_erofs_decompressqueue, u.work);
1419 	struct page *pagepool = NULL;
1420 
1421 	DBG_BUGON(bgq->head == Z_EROFS_PCLUSTER_TAIL);
1422 	z_erofs_decompress_queue(bgq, &pagepool);
1423 	erofs_release_pages(&pagepool);
1424 	kvfree(bgq);
1425 }
1426 
1427 #ifdef CONFIG_EROFS_FS_PCPU_KTHREAD
1428 static void z_erofs_decompressqueue_kthread_work(struct kthread_work *work)
1429 {
1430 	z_erofs_decompressqueue_work((struct work_struct *)work);
1431 }
1432 #endif
1433 
1434 /* Use (kthread_)work in atomic contexts to minimize scheduling overhead */
1435 static inline bool z_erofs_in_atomic(void)
1436 {
1437 	if (IS_ENABLED(CONFIG_PREEMPTION) && rcu_preempt_depth())
1438 		return true;
1439 	if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
1440 		return true;
1441 	return !preemptible();
1442 }
1443 
1444 static void z_erofs_decompress_kickoff(struct z_erofs_decompressqueue *io,
1445 				       int bios)
1446 {
1447 	struct erofs_sb_info *const sbi = EROFS_SB(io->sb);
1448 
1449 	/* wake up the caller thread for sync decompression */
1450 	if (io->sync) {
1451 		if (!atomic_add_return(bios, &io->pending_bios))
1452 			complete(&io->u.done);
1453 		return;
1454 	}
1455 
1456 	if (atomic_add_return(bios, &io->pending_bios))
1457 		return;
1458 	if (z_erofs_in_atomic()) {
1459 #ifdef CONFIG_EROFS_FS_PCPU_KTHREAD
1460 		struct kthread_worker *worker;
1461 
1462 		rcu_read_lock();
1463 		worker = rcu_dereference(
1464 				z_erofs_pcpu_workers[raw_smp_processor_id()]);
1465 		if (!worker) {
1466 			INIT_WORK(&io->u.work, z_erofs_decompressqueue_work);
1467 			queue_work(z_erofs_workqueue, &io->u.work);
1468 		} else {
1469 			kthread_queue_work(worker, &io->u.kthread_work);
1470 		}
1471 		rcu_read_unlock();
1472 #else
1473 		queue_work(z_erofs_workqueue, &io->u.work);
1474 #endif
1475 		/* See `sync_decompress` in sysfs-fs-erofs for more details */
1476 		if (sbi->sync_decompress == EROFS_SYNC_DECOMPRESS_AUTO)
1477 			sbi->sync_decompress = EROFS_SYNC_DECOMPRESS_FORCE_ON;
1478 		return;
1479 	}
1480 	z_erofs_decompressqueue_work(&io->u.work);
1481 }
1482 
1483 static void z_erofs_fill_bio_vec(struct bio_vec *bvec,
1484 				 struct z_erofs_frontend *f,
1485 				 struct z_erofs_pcluster *pcl,
1486 				 unsigned int nr,
1487 				 struct address_space *mc)
1488 {
1489 	gfp_t gfp = mapping_gfp_mask(mc);
1490 	bool tocache = false;
1491 	struct z_erofs_bvec zbv;
1492 	struct address_space *mapping;
1493 	struct folio *folio;
1494 	struct page *page;
1495 	int bs = i_blocksize(f->inode);
1496 
1497 	/* Except for inplace folios, the entire folio can be used for I/Os */
1498 	bvec->bv_offset = 0;
1499 	bvec->bv_len = PAGE_SIZE;
1500 repeat:
1501 	spin_lock(&pcl->lockref.lock);
1502 	zbv = pcl->compressed_bvecs[nr];
1503 	spin_unlock(&pcl->lockref.lock);
1504 	if (!zbv.page)
1505 		goto out_allocfolio;
1506 
1507 	bvec->bv_page = zbv.page;
1508 	DBG_BUGON(z_erofs_is_shortlived_page(bvec->bv_page));
1509 
1510 	folio = page_folio(zbv.page);
1511 	/* For preallocated managed folios, add them to page cache here */
1512 	if (folio->private == Z_EROFS_PREALLOCATED_FOLIO) {
1513 		tocache = true;
1514 		goto out_tocache;
1515 	}
1516 
1517 	mapping = READ_ONCE(folio->mapping);
1518 	/*
1519 	 * File-backed folios for inplace I/Os are all locked steady,
1520 	 * therefore it is impossible for `mapping` to be NULL.
1521 	 */
1522 	if (mapping && mapping != mc) {
1523 		if (zbv.offset < 0)
1524 			bvec->bv_offset = round_up(-zbv.offset, bs);
1525 		bvec->bv_len = round_up(zbv.end, bs) - bvec->bv_offset;
1526 		return;
1527 	}
1528 
1529 	folio_lock(folio);
1530 	if (likely(folio->mapping == mc)) {
1531 		/*
1532 		 * The cached folio is still in managed cache but without
1533 		 * a valid `->private` pcluster hint.  Let's reconnect them.
1534 		 */
1535 		if (!folio_test_private(folio)) {
1536 			folio_attach_private(folio, pcl);
1537 			/* compressed_bvecs[] already takes a ref before */
1538 			folio_put(folio);
1539 		}
1540 		if (likely(folio->private == pcl))  {
1541 			/* don't submit cache I/Os again if already uptodate */
1542 			if (folio_test_uptodate(folio)) {
1543 				folio_unlock(folio);
1544 				bvec->bv_page = NULL;
1545 			}
1546 			return;
1547 		}
1548 		/*
1549 		 * Already linked with another pcluster, which only appears in
1550 		 * crafted images by fuzzers for now.  But handle this anyway.
1551 		 */
1552 		tocache = false;	/* use temporary short-lived pages */
1553 	} else {
1554 		DBG_BUGON(1); /* referenced managed folios can't be truncated */
1555 		tocache = true;
1556 	}
1557 	folio_unlock(folio);
1558 	folio_put(folio);
1559 out_allocfolio:
1560 	page = __erofs_allocpage(&f->pagepool, gfp, true);
1561 	spin_lock(&pcl->lockref.lock);
1562 	if (unlikely(pcl->compressed_bvecs[nr].page != zbv.page)) {
1563 		if (page)
1564 			erofs_pagepool_add(&f->pagepool, page);
1565 		spin_unlock(&pcl->lockref.lock);
1566 		cond_resched();
1567 		goto repeat;
1568 	}
1569 	pcl->compressed_bvecs[nr].page = page ? page : ERR_PTR(-ENOMEM);
1570 	spin_unlock(&pcl->lockref.lock);
1571 	bvec->bv_page = page;
1572 	if (!page)
1573 		return;
1574 	folio = page_folio(page);
1575 out_tocache:
1576 	if (!tocache || bs != PAGE_SIZE ||
1577 	    filemap_add_folio(mc, folio, (pcl->pos >> PAGE_SHIFT) + nr, gfp)) {
1578 		/* turn into a temporary shortlived folio (1 ref) */
1579 		folio->private = (void *)Z_EROFS_SHORTLIVED_PAGE;
1580 		return;
1581 	}
1582 	folio_attach_private(folio, pcl);
1583 	/* drop a refcount added by allocpage (then 2 refs in total here) */
1584 	folio_put(folio);
1585 }
1586 
1587 static struct z_erofs_decompressqueue *jobqueue_init(struct super_block *sb,
1588 			      struct z_erofs_decompressqueue *fgq, bool *fg)
1589 {
1590 	struct z_erofs_decompressqueue *q;
1591 
1592 	if (fg && !*fg) {
1593 		q = kvzalloc(sizeof(*q), GFP_KERNEL | __GFP_NOWARN);
1594 		if (!q) {
1595 			*fg = true;
1596 			goto fg_out;
1597 		}
1598 #ifdef CONFIG_EROFS_FS_PCPU_KTHREAD
1599 		kthread_init_work(&q->u.kthread_work,
1600 				  z_erofs_decompressqueue_kthread_work);
1601 #else
1602 		INIT_WORK(&q->u.work, z_erofs_decompressqueue_work);
1603 #endif
1604 	} else {
1605 fg_out:
1606 		q = fgq;
1607 		init_completion(&fgq->u.done);
1608 		atomic_set(&fgq->pending_bios, 0);
1609 		q->eio = false;
1610 		q->sync = true;
1611 	}
1612 	q->sb = sb;
1613 	q->head = Z_EROFS_PCLUSTER_TAIL;
1614 	return q;
1615 }
1616 
1617 /* define decompression jobqueue types */
1618 enum {
1619 	JQ_BYPASS,
1620 	JQ_SUBMIT,
1621 	NR_JOBQUEUES,
1622 };
1623 
1624 static void z_erofs_move_to_bypass_queue(struct z_erofs_pcluster *pcl,
1625 					 struct z_erofs_pcluster *next,
1626 					 struct z_erofs_pcluster **qtail[])
1627 {
1628 	WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_TAIL);
1629 	WRITE_ONCE(*qtail[JQ_SUBMIT], next);
1630 	WRITE_ONCE(*qtail[JQ_BYPASS], pcl);
1631 	qtail[JQ_BYPASS] = &pcl->next;
1632 }
1633 
1634 static void z_erofs_endio(struct bio *bio)
1635 {
1636 	struct z_erofs_decompressqueue *q = bio->bi_private;
1637 	blk_status_t err = bio->bi_status;
1638 	struct folio_iter fi;
1639 
1640 	bio_for_each_folio_all(fi, bio) {
1641 		struct folio *folio = fi.folio;
1642 
1643 		DBG_BUGON(folio_test_uptodate(folio));
1644 		DBG_BUGON(z_erofs_page_is_invalidated(&folio->page));
1645 		if (!erofs_folio_is_managed(EROFS_SB(q->sb), folio))
1646 			continue;
1647 
1648 		if (!err)
1649 			folio_mark_uptodate(folio);
1650 		folio_unlock(folio);
1651 	}
1652 	if (err)
1653 		q->eio = true;
1654 	z_erofs_decompress_kickoff(q, -1);
1655 	if (bio->bi_bdev)
1656 		bio_put(bio);
1657 }
1658 
1659 static void z_erofs_submit_queue(struct z_erofs_frontend *f,
1660 				 struct z_erofs_decompressqueue *fgq,
1661 				 bool *force_fg, bool readahead)
1662 {
1663 	struct super_block *sb = f->inode->i_sb;
1664 	struct address_space *mc = MNGD_MAPPING(EROFS_SB(sb));
1665 	struct z_erofs_pcluster **qtail[NR_JOBQUEUES];
1666 	struct z_erofs_decompressqueue *q[NR_JOBQUEUES];
1667 	struct z_erofs_pcluster *pcl, *next;
1668 	/* bio is NULL initially, so no need to initialize last_{index,bdev} */
1669 	erofs_off_t last_pa;
1670 	unsigned int nr_bios = 0;
1671 	struct bio *bio = NULL;
1672 	unsigned long pflags;
1673 	int memstall = 0;
1674 
1675 	/* No need to read from device for pclusters in the bypass queue. */
1676 	q[JQ_BYPASS] = jobqueue_init(sb, fgq + JQ_BYPASS, NULL);
1677 	q[JQ_SUBMIT] = jobqueue_init(sb, fgq + JQ_SUBMIT, force_fg);
1678 
1679 	qtail[JQ_BYPASS] = &q[JQ_BYPASS]->head;
1680 	qtail[JQ_SUBMIT] = &q[JQ_SUBMIT]->head;
1681 
1682 	/* by default, all need io submission */
1683 	q[JQ_SUBMIT]->head = next = f->head;
1684 
1685 	do {
1686 		struct erofs_map_dev mdev;
1687 		erofs_off_t cur, end;
1688 		struct bio_vec bvec;
1689 		unsigned int i = 0;
1690 		bool bypass = true;
1691 
1692 		pcl = next;
1693 		next = READ_ONCE(pcl->next);
1694 		if (pcl->from_meta) {
1695 			z_erofs_move_to_bypass_queue(pcl, next, qtail);
1696 			continue;
1697 		}
1698 
1699 		/* no device id here, thus it will always succeed */
1700 		mdev = (struct erofs_map_dev) {
1701 			.m_pa = round_down(pcl->pos, sb->s_blocksize),
1702 		};
1703 		(void)erofs_map_dev(sb, &mdev);
1704 
1705 		cur = mdev.m_pa;
1706 		end = round_up(cur + pcl->pageofs_in + pcl->pclustersize,
1707 			       sb->s_blocksize);
1708 		do {
1709 			bvec.bv_page = NULL;
1710 			if (bio && (cur != last_pa ||
1711 				    bio->bi_bdev != mdev.m_bdev)) {
1712 drain_io:
1713 				if (erofs_is_fileio_mode(EROFS_SB(sb)))
1714 					erofs_fileio_submit_bio(bio);
1715 				else if (erofs_is_fscache_mode(sb))
1716 					erofs_fscache_submit_bio(bio);
1717 				else
1718 					submit_bio(bio);
1719 
1720 				if (memstall) {
1721 					psi_memstall_leave(&pflags);
1722 					memstall = 0;
1723 				}
1724 				bio = NULL;
1725 			}
1726 
1727 			if (!bvec.bv_page) {
1728 				z_erofs_fill_bio_vec(&bvec, f, pcl, i++, mc);
1729 				if (!bvec.bv_page)
1730 					continue;
1731 				if (cur + bvec.bv_len > end)
1732 					bvec.bv_len = end - cur;
1733 				DBG_BUGON(bvec.bv_len < sb->s_blocksize);
1734 			}
1735 
1736 			if (unlikely(PageWorkingset(bvec.bv_page)) &&
1737 			    !memstall) {
1738 				psi_memstall_enter(&pflags);
1739 				memstall = 1;
1740 			}
1741 
1742 			if (!bio) {
1743 				if (erofs_is_fileio_mode(EROFS_SB(sb)))
1744 					bio = erofs_fileio_bio_alloc(&mdev);
1745 				else if (erofs_is_fscache_mode(sb))
1746 					bio = erofs_fscache_bio_alloc(&mdev);
1747 				else
1748 					bio = bio_alloc(mdev.m_bdev, BIO_MAX_VECS,
1749 							REQ_OP_READ, GFP_NOIO);
1750 				bio->bi_end_io = z_erofs_endio;
1751 				bio->bi_iter.bi_sector =
1752 						(mdev.m_dif->fsoff + cur) >> 9;
1753 				bio->bi_private = q[JQ_SUBMIT];
1754 				if (readahead)
1755 					bio->bi_opf |= REQ_RAHEAD;
1756 				++nr_bios;
1757 			}
1758 
1759 			if (!bio_add_page(bio, bvec.bv_page, bvec.bv_len,
1760 					  bvec.bv_offset))
1761 				goto drain_io;
1762 			last_pa = cur + bvec.bv_len;
1763 			bypass = false;
1764 		} while ((cur += bvec.bv_len) < end);
1765 
1766 		if (!bypass)
1767 			qtail[JQ_SUBMIT] = &pcl->next;
1768 		else
1769 			z_erofs_move_to_bypass_queue(pcl, next, qtail);
1770 	} while (next != Z_EROFS_PCLUSTER_TAIL);
1771 
1772 	if (bio) {
1773 		if (erofs_is_fileio_mode(EROFS_SB(sb)))
1774 			erofs_fileio_submit_bio(bio);
1775 		else if (erofs_is_fscache_mode(sb))
1776 			erofs_fscache_submit_bio(bio);
1777 		else
1778 			submit_bio(bio);
1779 	}
1780 	if (memstall)
1781 		psi_memstall_leave(&pflags);
1782 
1783 	/*
1784 	 * although background is preferred, no one is pending for submission.
1785 	 * don't issue decompression but drop it directly instead.
1786 	 */
1787 	if (!*force_fg && !nr_bios) {
1788 		kvfree(q[JQ_SUBMIT]);
1789 		return;
1790 	}
1791 	z_erofs_decompress_kickoff(q[JQ_SUBMIT], nr_bios);
1792 }
1793 
1794 static int z_erofs_runqueue(struct z_erofs_frontend *f, unsigned int rabytes)
1795 {
1796 	struct z_erofs_decompressqueue io[NR_JOBQUEUES];
1797 	struct erofs_sb_info *sbi = EROFS_I_SB(f->inode);
1798 	int syncmode = sbi->sync_decompress;
1799 	bool force_fg;
1800 	int err;
1801 
1802 	force_fg = (syncmode == EROFS_SYNC_DECOMPRESS_AUTO && !rabytes) ||
1803 		(syncmode == EROFS_SYNC_DECOMPRESS_FORCE_ON &&
1804 			(rabytes <= Z_EROFS_MAX_SYNC_DECOMPRESS_BYTES));
1805 
1806 	if (f->head == Z_EROFS_PCLUSTER_TAIL)
1807 		return 0;
1808 	z_erofs_submit_queue(f, io, &force_fg, !!rabytes);
1809 
1810 	/* handle bypass queue (no i/o pclusters) immediately */
1811 	err = z_erofs_decompress_queue(&io[JQ_BYPASS], &f->pagepool);
1812 	if (!force_fg)
1813 		return err;
1814 
1815 	/* wait until all bios are completed */
1816 	wait_for_completion_io(&io[JQ_SUBMIT].u.done);
1817 
1818 	/* handle synchronous decompress queue in the caller context */
1819 	return z_erofs_decompress_queue(&io[JQ_SUBMIT], &f->pagepool) ?: err;
1820 }
1821 
1822 /*
1823  * Since partial uptodate is still unimplemented for now, we have to use
1824  * approximate readmore strategies as a start.
1825  */
1826 static void z_erofs_pcluster_readmore(struct z_erofs_frontend *f,
1827 		struct readahead_control *rac, bool backmost)
1828 {
1829 	struct inode *inode = f->inode;
1830 	struct erofs_map_blocks *map = &f->map;
1831 	erofs_off_t cur, end, headoffset = f->headoffset;
1832 	int err;
1833 
1834 	if (backmost) {
1835 		if (rac)
1836 			end = headoffset + readahead_length(rac) - 1;
1837 		else
1838 			end = headoffset + PAGE_SIZE - 1;
1839 		map->m_la = end;
1840 		err = z_erofs_map_blocks_iter(inode, map,
1841 					      EROFS_GET_BLOCKS_READMORE);
1842 		if (err || !(map->m_flags & EROFS_MAP_ENCODED))
1843 			return;
1844 
1845 		/* expand ra for the trailing edge if readahead */
1846 		if (rac) {
1847 			cur = round_up(map->m_la + map->m_llen, PAGE_SIZE);
1848 			readahead_expand(rac, headoffset, cur - headoffset);
1849 			return;
1850 		}
1851 		end = round_up(end, PAGE_SIZE);
1852 	} else {
1853 		end = round_up(map->m_la, PAGE_SIZE);
1854 		if (!(map->m_flags & EROFS_MAP_ENCODED) || !map->m_llen)
1855 			return;
1856 	}
1857 
1858 	cur = map->m_la + map->m_llen - 1;
1859 	while ((cur >= end) && (cur < i_size_read(inode))) {
1860 		pgoff_t index = cur >> PAGE_SHIFT;
1861 		struct folio *folio;
1862 
1863 		folio = erofs_grab_folio_nowait(f->sharedinode->i_mapping, index);
1864 		if (!IS_ERR_OR_NULL(folio)) {
1865 			if (folio_test_uptodate(folio))
1866 				folio_unlock(folio);
1867 			else
1868 				z_erofs_scan_folio(f, folio, !!rac);
1869 			folio_put(folio);
1870 		}
1871 
1872 		if (cur < PAGE_SIZE)
1873 			break;
1874 		cur = (index << PAGE_SHIFT) - 1;
1875 	}
1876 }
1877 
1878 static int z_erofs_read_folio(struct file *file, struct folio *folio)
1879 {
1880 	struct inode *sharedinode = folio->mapping->host;
1881 	bool need_iput;
1882 	struct inode *realinode = erofs_real_inode(sharedinode, &need_iput);
1883 	Z_EROFS_DEFINE_FRONTEND(f, realinode, sharedinode, folio_pos(folio));
1884 	int err;
1885 
1886 	trace_erofs_read_folio(realinode, folio, false);
1887 	z_erofs_pcluster_readmore(&f, NULL, true);
1888 	err = z_erofs_scan_folio(&f, folio, false);
1889 	z_erofs_pcluster_readmore(&f, NULL, false);
1890 	z_erofs_pcluster_end(&f);
1891 
1892 	/* if some pclusters are ready, need submit them anyway */
1893 	err = z_erofs_runqueue(&f, 0) ?: err;
1894 	if (err && err != -EINTR)
1895 		erofs_err(realinode->i_sb, "read error %d @ %lu of nid %llu",
1896 			  err, folio->index, EROFS_I(realinode)->nid);
1897 
1898 	erofs_put_metabuf(&f.map.buf);
1899 	erofs_release_pages(&f.pagepool);
1900 
1901 	if (need_iput)
1902 		iput(realinode);
1903 	return err;
1904 }
1905 
1906 static void z_erofs_readahead(struct readahead_control *rac)
1907 {
1908 	struct inode *sharedinode = rac->mapping->host;
1909 	bool need_iput;
1910 	struct inode *realinode = erofs_real_inode(sharedinode, &need_iput);
1911 	Z_EROFS_DEFINE_FRONTEND(f, realinode, sharedinode, readahead_pos(rac));
1912 	unsigned int nrpages = readahead_count(rac);
1913 	struct folio *head = NULL, *folio;
1914 	int err;
1915 
1916 	trace_erofs_readahead(realinode, readahead_index(rac), nrpages, false);
1917 	z_erofs_pcluster_readmore(&f, rac, true);
1918 	while ((folio = readahead_folio(rac))) {
1919 		folio->private = head;
1920 		head = folio;
1921 	}
1922 
1923 	/* traverse in reverse order for best metadata I/O performance */
1924 	while (head) {
1925 		folio = head;
1926 		head = folio_get_private(folio);
1927 
1928 		err = z_erofs_scan_folio(&f, folio, true);
1929 		if (err && err != -EINTR)
1930 			erofs_err(realinode->i_sb, "readahead error at folio %lu @ nid %llu",
1931 				  folio->index, EROFS_I(realinode)->nid);
1932 	}
1933 	z_erofs_pcluster_readmore(&f, rac, false);
1934 	z_erofs_pcluster_end(&f);
1935 
1936 	(void)z_erofs_runqueue(&f, nrpages << PAGE_SHIFT);
1937 	erofs_put_metabuf(&f.map.buf);
1938 	erofs_release_pages(&f.pagepool);
1939 
1940 	if (need_iput)
1941 		iput(realinode);
1942 }
1943 
1944 const struct address_space_operations z_erofs_aops = {
1945 	.read_folio = z_erofs_read_folio,
1946 	.readahead = z_erofs_readahead,
1947 };
1948