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