xref: /openbmc/linux/fs/erofs/zdata.c (revision 83a386c0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2018 HUAWEI, Inc.
4  *             https://www.huawei.com/
5  */
6 #include "zdata.h"
7 #include "compress.h"
8 #include <linux/prefetch.h>
9 
10 #include <trace/events/erofs.h>
11 
12 /*
13  * since pclustersize is variable for big pcluster feature, introduce slab
14  * pools implementation for different pcluster sizes.
15  */
16 struct z_erofs_pcluster_slab {
17 	struct kmem_cache *slab;
18 	unsigned int maxpages;
19 	char name[48];
20 };
21 
22 #define _PCLP(n) { .maxpages = n }
23 
24 static struct z_erofs_pcluster_slab pcluster_pool[] __read_mostly = {
25 	_PCLP(1), _PCLP(4), _PCLP(16), _PCLP(64), _PCLP(128),
26 	_PCLP(Z_EROFS_PCLUSTER_MAX_PAGES)
27 };
28 
29 static void z_erofs_destroy_pcluster_pool(void)
30 {
31 	int i;
32 
33 	for (i = 0; i < ARRAY_SIZE(pcluster_pool); ++i) {
34 		if (!pcluster_pool[i].slab)
35 			continue;
36 		kmem_cache_destroy(pcluster_pool[i].slab);
37 		pcluster_pool[i].slab = NULL;
38 	}
39 }
40 
41 static int z_erofs_create_pcluster_pool(void)
42 {
43 	struct z_erofs_pcluster_slab *pcs;
44 	struct z_erofs_pcluster *a;
45 	unsigned int size;
46 
47 	for (pcs = pcluster_pool;
48 	     pcs < pcluster_pool + ARRAY_SIZE(pcluster_pool); ++pcs) {
49 		size = struct_size(a, compressed_pages, pcs->maxpages);
50 
51 		sprintf(pcs->name, "erofs_pcluster-%u", pcs->maxpages);
52 		pcs->slab = kmem_cache_create(pcs->name, size, 0,
53 					      SLAB_RECLAIM_ACCOUNT, NULL);
54 		if (pcs->slab)
55 			continue;
56 
57 		z_erofs_destroy_pcluster_pool();
58 		return -ENOMEM;
59 	}
60 	return 0;
61 }
62 
63 static struct z_erofs_pcluster *z_erofs_alloc_pcluster(unsigned int nrpages)
64 {
65 	int i;
66 
67 	for (i = 0; i < ARRAY_SIZE(pcluster_pool); ++i) {
68 		struct z_erofs_pcluster_slab *pcs = pcluster_pool + i;
69 		struct z_erofs_pcluster *pcl;
70 
71 		if (nrpages > pcs->maxpages)
72 			continue;
73 
74 		pcl = kmem_cache_zalloc(pcs->slab, GFP_NOFS);
75 		if (!pcl)
76 			return ERR_PTR(-ENOMEM);
77 		pcl->pclusterpages = nrpages;
78 		return pcl;
79 	}
80 	return ERR_PTR(-EINVAL);
81 }
82 
83 static void z_erofs_free_pcluster(struct z_erofs_pcluster *pcl)
84 {
85 	unsigned int pclusterpages = z_erofs_pclusterpages(pcl);
86 	int i;
87 
88 	for (i = 0; i < ARRAY_SIZE(pcluster_pool); ++i) {
89 		struct z_erofs_pcluster_slab *pcs = pcluster_pool + i;
90 
91 		if (pclusterpages > pcs->maxpages)
92 			continue;
93 
94 		kmem_cache_free(pcs->slab, pcl);
95 		return;
96 	}
97 	DBG_BUGON(1);
98 }
99 
100 /* how to allocate cached pages for a pcluster */
101 enum z_erofs_cache_alloctype {
102 	DONTALLOC,	/* don't allocate any cached pages */
103 	/*
104 	 * try to use cached I/O if page allocation succeeds or fallback
105 	 * to in-place I/O instead to avoid any direct reclaim.
106 	 */
107 	TRYALLOC,
108 };
109 
110 /*
111  * tagged pointer with 1-bit tag for all compressed pages
112  * tag 0 - the page is just found with an extra page reference
113  */
114 typedef tagptr1_t compressed_page_t;
115 
116 #define tag_compressed_page_justfound(page) \
117 	tagptr_fold(compressed_page_t, page, 1)
118 
119 static struct workqueue_struct *z_erofs_workqueue __read_mostly;
120 
121 void z_erofs_exit_zip_subsystem(void)
122 {
123 	destroy_workqueue(z_erofs_workqueue);
124 	z_erofs_destroy_pcluster_pool();
125 }
126 
127 static inline int z_erofs_init_workqueue(void)
128 {
129 	const unsigned int onlinecpus = num_possible_cpus();
130 
131 	/*
132 	 * no need to spawn too many threads, limiting threads could minimum
133 	 * scheduling overhead, perhaps per-CPU threads should be better?
134 	 */
135 	z_erofs_workqueue = alloc_workqueue("erofs_unzipd",
136 					    WQ_UNBOUND | WQ_HIGHPRI,
137 					    onlinecpus + onlinecpus / 4);
138 	return z_erofs_workqueue ? 0 : -ENOMEM;
139 }
140 
141 int __init z_erofs_init_zip_subsystem(void)
142 {
143 	int err = z_erofs_create_pcluster_pool();
144 
145 	if (err)
146 		return err;
147 	err = z_erofs_init_workqueue();
148 	if (err)
149 		z_erofs_destroy_pcluster_pool();
150 	return err;
151 }
152 
153 enum z_erofs_collectmode {
154 	COLLECT_SECONDARY,
155 	COLLECT_PRIMARY,
156 	/*
157 	 * The current collection was the tail of an exist chain, in addition
158 	 * that the previous processed chained collections are all decided to
159 	 * be hooked up to it.
160 	 * A new chain will be created for the remaining collections which are
161 	 * not processed yet, therefore different from COLLECT_PRIMARY_FOLLOWED,
162 	 * the next collection cannot reuse the whole page safely in
163 	 * the following scenario:
164 	 *  ________________________________________________________________
165 	 * |      tail (partial) page     |       head (partial) page       |
166 	 * |   (belongs to the next cl)   |   (belongs to the current cl)   |
167 	 * |_______PRIMARY_FOLLOWED_______|________PRIMARY_HOOKED___________|
168 	 */
169 	COLLECT_PRIMARY_HOOKED,
170 	/*
171 	 * a weak form of COLLECT_PRIMARY_FOLLOWED, the difference is that it
172 	 * could be dispatched into bypass queue later due to uptodated managed
173 	 * pages. All related online pages cannot be reused for inplace I/O (or
174 	 * pagevec) since it can be directly decoded without I/O submission.
175 	 */
176 	COLLECT_PRIMARY_FOLLOWED_NOINPLACE,
177 	/*
178 	 * The current collection has been linked with the owned chain, and
179 	 * could also be linked with the remaining collections, which means
180 	 * if the processing page is the tail page of the collection, thus
181 	 * the current collection can safely use the whole page (since
182 	 * the previous collection is under control) for in-place I/O, as
183 	 * illustrated below:
184 	 *  ________________________________________________________________
185 	 * |  tail (partial) page |          head (partial) page           |
186 	 * |  (of the current cl) |      (of the previous collection)      |
187 	 * |  PRIMARY_FOLLOWED or |                                        |
188 	 * |_____PRIMARY_HOOKED___|____________PRIMARY_FOLLOWED____________|
189 	 *
190 	 * [  (*) the above page can be used as inplace I/O.               ]
191 	 */
192 	COLLECT_PRIMARY_FOLLOWED,
193 };
194 
195 struct z_erofs_decompress_frontend {
196 	struct inode *const inode;
197 	struct erofs_map_blocks map;
198 
199 	struct z_erofs_pagevec_ctor vector;
200 
201 	struct z_erofs_pcluster *pcl, *tailpcl;
202 	/* a pointer used to pick up inplace I/O pages */
203 	struct page **icpage_ptr;
204 	z_erofs_next_pcluster_t owned_head;
205 
206 	enum z_erofs_collectmode mode;
207 
208 	bool readahead;
209 	/* used for applying cache strategy on the fly */
210 	bool backmost;
211 	erofs_off_t headoffset;
212 };
213 
214 #define DECOMPRESS_FRONTEND_INIT(__i) { \
215 	.inode = __i, .owned_head = Z_EROFS_PCLUSTER_TAIL, \
216 	.mode = COLLECT_PRIMARY_FOLLOWED, .backmost = true }
217 
218 static struct page *z_pagemap_global[Z_EROFS_VMAP_GLOBAL_PAGES];
219 static DEFINE_MUTEX(z_pagemap_global_lock);
220 
221 static void z_erofs_bind_cache(struct z_erofs_decompress_frontend *fe,
222 			       enum z_erofs_cache_alloctype type,
223 			       struct page **pagepool)
224 {
225 	struct address_space *mc = MNGD_MAPPING(EROFS_I_SB(fe->inode));
226 	struct z_erofs_pcluster *pcl = fe->pcl;
227 	bool standalone = true;
228 	/*
229 	 * optimistic allocation without direct reclaim since inplace I/O
230 	 * can be used if low memory otherwise.
231 	 */
232 	gfp_t gfp = (mapping_gfp_mask(mc) & ~__GFP_DIRECT_RECLAIM) |
233 			__GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN;
234 	struct page **pages;
235 	pgoff_t index;
236 
237 	if (fe->mode < COLLECT_PRIMARY_FOLLOWED)
238 		return;
239 
240 	pages = pcl->compressed_pages;
241 	index = pcl->obj.index;
242 	for (; index < pcl->obj.index + pcl->pclusterpages; ++index, ++pages) {
243 		struct page *page;
244 		compressed_page_t t;
245 		struct page *newpage = NULL;
246 
247 		/* the compressed page was loaded before */
248 		if (READ_ONCE(*pages))
249 			continue;
250 
251 		page = find_get_page(mc, index);
252 
253 		if (page) {
254 			t = tag_compressed_page_justfound(page);
255 		} else {
256 			/* I/O is needed, no possible to decompress directly */
257 			standalone = false;
258 			switch (type) {
259 			case TRYALLOC:
260 				newpage = erofs_allocpage(pagepool, gfp);
261 				if (!newpage)
262 					continue;
263 				set_page_private(newpage,
264 						 Z_EROFS_PREALLOCATED_PAGE);
265 				t = tag_compressed_page_justfound(newpage);
266 				break;
267 			default:        /* DONTALLOC */
268 				continue;
269 			}
270 		}
271 
272 		if (!cmpxchg_relaxed(pages, NULL, tagptr_cast_ptr(t)))
273 			continue;
274 
275 		if (page)
276 			put_page(page);
277 		else if (newpage)
278 			erofs_pagepool_add(pagepool, newpage);
279 	}
280 
281 	/*
282 	 * don't do inplace I/O if all compressed pages are available in
283 	 * managed cache since it can be moved to the bypass queue instead.
284 	 */
285 	if (standalone)
286 		fe->mode = COLLECT_PRIMARY_FOLLOWED_NOINPLACE;
287 }
288 
289 /* called by erofs_shrinker to get rid of all compressed_pages */
290 int erofs_try_to_free_all_cached_pages(struct erofs_sb_info *sbi,
291 				       struct erofs_workgroup *grp)
292 {
293 	struct z_erofs_pcluster *const pcl =
294 		container_of(grp, struct z_erofs_pcluster, obj);
295 	int i;
296 
297 	DBG_BUGON(z_erofs_is_inline_pcluster(pcl));
298 	/*
299 	 * refcount of workgroup is now freezed as 1,
300 	 * therefore no need to worry about available decompression users.
301 	 */
302 	for (i = 0; i < pcl->pclusterpages; ++i) {
303 		struct page *page = pcl->compressed_pages[i];
304 
305 		if (!page)
306 			continue;
307 
308 		/* block other users from reclaiming or migrating the page */
309 		if (!trylock_page(page))
310 			return -EBUSY;
311 
312 		if (!erofs_page_is_managed(sbi, page))
313 			continue;
314 
315 		/* barrier is implied in the following 'unlock_page' */
316 		WRITE_ONCE(pcl->compressed_pages[i], NULL);
317 		detach_page_private(page);
318 		unlock_page(page);
319 	}
320 	return 0;
321 }
322 
323 int erofs_try_to_free_cached_page(struct page *page)
324 {
325 	struct z_erofs_pcluster *const pcl = (void *)page_private(page);
326 	int ret = 0;	/* 0 - busy */
327 
328 	if (erofs_workgroup_try_to_freeze(&pcl->obj, 1)) {
329 		unsigned int i;
330 
331 		DBG_BUGON(z_erofs_is_inline_pcluster(pcl));
332 		for (i = 0; i < pcl->pclusterpages; ++i) {
333 			if (pcl->compressed_pages[i] == page) {
334 				WRITE_ONCE(pcl->compressed_pages[i], NULL);
335 				ret = 1;
336 				break;
337 			}
338 		}
339 		erofs_workgroup_unfreeze(&pcl->obj, 1);
340 
341 		if (ret)
342 			detach_page_private(page);
343 	}
344 	return ret;
345 }
346 
347 /* page_type must be Z_EROFS_PAGE_TYPE_EXCLUSIVE */
348 static bool z_erofs_try_inplace_io(struct z_erofs_decompress_frontend *fe,
349 				   struct page *page)
350 {
351 	struct z_erofs_pcluster *const pcl = fe->pcl;
352 
353 	while (fe->icpage_ptr > pcl->compressed_pages)
354 		if (!cmpxchg(--fe->icpage_ptr, NULL, page))
355 			return true;
356 	return false;
357 }
358 
359 /* callers must be with pcluster lock held */
360 static int z_erofs_attach_page(struct z_erofs_decompress_frontend *fe,
361 			       struct page *page, enum z_erofs_page_type type,
362 			       bool pvec_safereuse)
363 {
364 	int ret;
365 
366 	/* give priority for inplaceio */
367 	if (fe->mode >= COLLECT_PRIMARY &&
368 	    type == Z_EROFS_PAGE_TYPE_EXCLUSIVE &&
369 	    z_erofs_try_inplace_io(fe, page))
370 		return 0;
371 
372 	ret = z_erofs_pagevec_enqueue(&fe->vector, page, type,
373 				      pvec_safereuse);
374 	fe->pcl->vcnt += (unsigned int)ret;
375 	return ret ? 0 : -EAGAIN;
376 }
377 
378 static void z_erofs_try_to_claim_pcluster(struct z_erofs_decompress_frontend *f)
379 {
380 	struct z_erofs_pcluster *pcl = f->pcl;
381 	z_erofs_next_pcluster_t *owned_head = &f->owned_head;
382 
383 	/* type 1, nil pcluster (this pcluster doesn't belong to any chain.) */
384 	if (cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_NIL,
385 		    *owned_head) == Z_EROFS_PCLUSTER_NIL) {
386 		*owned_head = &pcl->next;
387 		/* so we can attach this pcluster to our submission chain. */
388 		f->mode = COLLECT_PRIMARY_FOLLOWED;
389 		return;
390 	}
391 
392 	/*
393 	 * type 2, link to the end of an existing open chain, be careful
394 	 * that its submission is controlled by the original attached chain.
395 	 */
396 	if (cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_TAIL,
397 		    *owned_head) == Z_EROFS_PCLUSTER_TAIL) {
398 		*owned_head = Z_EROFS_PCLUSTER_TAIL;
399 		f->mode = COLLECT_PRIMARY_HOOKED;
400 		f->tailpcl = NULL;
401 		return;
402 	}
403 	/* type 3, it belongs to a chain, but it isn't the end of the chain */
404 	f->mode = COLLECT_PRIMARY;
405 }
406 
407 static int z_erofs_lookup_pcluster(struct z_erofs_decompress_frontend *fe)
408 {
409 	struct erofs_map_blocks *map = &fe->map;
410 	struct z_erofs_pcluster *pcl = fe->pcl;
411 	unsigned int length;
412 
413 	/* to avoid unexpected loop formed by corrupted images */
414 	if (fe->owned_head == &pcl->next || pcl == fe->tailpcl) {
415 		DBG_BUGON(1);
416 		return -EFSCORRUPTED;
417 	}
418 
419 	if (pcl->pageofs_out != (map->m_la & ~PAGE_MASK)) {
420 		DBG_BUGON(1);
421 		return -EFSCORRUPTED;
422 	}
423 
424 	length = READ_ONCE(pcl->length);
425 	if (length & Z_EROFS_PCLUSTER_FULL_LENGTH) {
426 		if ((map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT) > length) {
427 			DBG_BUGON(1);
428 			return -EFSCORRUPTED;
429 		}
430 	} else {
431 		unsigned int llen = map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT;
432 
433 		if (map->m_flags & EROFS_MAP_FULL_MAPPED)
434 			llen |= Z_EROFS_PCLUSTER_FULL_LENGTH;
435 
436 		while (llen > length &&
437 		       length != cmpxchg_relaxed(&pcl->length, length, llen)) {
438 			cpu_relax();
439 			length = READ_ONCE(pcl->length);
440 		}
441 	}
442 	mutex_lock(&pcl->lock);
443 	/* used to check tail merging loop due to corrupted images */
444 	if (fe->owned_head == Z_EROFS_PCLUSTER_TAIL)
445 		fe->tailpcl = pcl;
446 
447 	z_erofs_try_to_claim_pcluster(fe);
448 	return 0;
449 }
450 
451 static int z_erofs_register_pcluster(struct z_erofs_decompress_frontend *fe)
452 {
453 	struct erofs_map_blocks *map = &fe->map;
454 	bool ztailpacking = map->m_flags & EROFS_MAP_META;
455 	struct z_erofs_pcluster *pcl;
456 	struct erofs_workgroup *grp;
457 	int err;
458 
459 	if (!(map->m_flags & EROFS_MAP_ENCODED)) {
460 		DBG_BUGON(1);
461 		return -EFSCORRUPTED;
462 	}
463 
464 	/* no available pcluster, let's allocate one */
465 	pcl = z_erofs_alloc_pcluster(ztailpacking ? 1 :
466 				     map->m_plen >> PAGE_SHIFT);
467 	if (IS_ERR(pcl))
468 		return PTR_ERR(pcl);
469 
470 	atomic_set(&pcl->obj.refcount, 1);
471 	pcl->algorithmformat = map->m_algorithmformat;
472 	pcl->length = (map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT) |
473 		(map->m_flags & EROFS_MAP_FULL_MAPPED ?
474 			Z_EROFS_PCLUSTER_FULL_LENGTH : 0);
475 
476 	/* new pclusters should be claimed as type 1, primary and followed */
477 	pcl->next = fe->owned_head;
478 	pcl->pageofs_out = map->m_la & ~PAGE_MASK;
479 	fe->mode = COLLECT_PRIMARY_FOLLOWED;
480 
481 	/*
482 	 * lock all primary followed works before visible to others
483 	 * and mutex_trylock *never* fails for a new pcluster.
484 	 */
485 	mutex_init(&pcl->lock);
486 	DBG_BUGON(!mutex_trylock(&pcl->lock));
487 
488 	if (ztailpacking) {
489 		pcl->obj.index = 0;	/* which indicates ztailpacking */
490 		pcl->pageofs_in = erofs_blkoff(map->m_pa);
491 		pcl->tailpacking_size = map->m_plen;
492 	} else {
493 		pcl->obj.index = map->m_pa >> PAGE_SHIFT;
494 
495 		grp = erofs_insert_workgroup(fe->inode->i_sb, &pcl->obj);
496 		if (IS_ERR(grp)) {
497 			err = PTR_ERR(grp);
498 			goto err_out;
499 		}
500 
501 		if (grp != &pcl->obj) {
502 			fe->pcl = container_of(grp,
503 					struct z_erofs_pcluster, obj);
504 			err = -EEXIST;
505 			goto err_out;
506 		}
507 	}
508 	/* used to check tail merging loop due to corrupted images */
509 	if (fe->owned_head == Z_EROFS_PCLUSTER_TAIL)
510 		fe->tailpcl = pcl;
511 	fe->owned_head = &pcl->next;
512 	fe->pcl = pcl;
513 	return 0;
514 
515 err_out:
516 	mutex_unlock(&pcl->lock);
517 	z_erofs_free_pcluster(pcl);
518 	return err;
519 }
520 
521 static int z_erofs_collector_begin(struct z_erofs_decompress_frontend *fe)
522 {
523 	struct erofs_map_blocks *map = &fe->map;
524 	struct erofs_workgroup *grp;
525 	int ret;
526 
527 	DBG_BUGON(fe->pcl);
528 
529 	/* must be Z_EROFS_PCLUSTER_TAIL or pointed to previous pcluster */
530 	DBG_BUGON(fe->owned_head == Z_EROFS_PCLUSTER_NIL);
531 	DBG_BUGON(fe->owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
532 
533 	if (map->m_flags & EROFS_MAP_META) {
534 		if ((map->m_pa & ~PAGE_MASK) + map->m_plen > PAGE_SIZE) {
535 			DBG_BUGON(1);
536 			return -EFSCORRUPTED;
537 		}
538 		goto tailpacking;
539 	}
540 
541 	grp = erofs_find_workgroup(fe->inode->i_sb, map->m_pa >> PAGE_SHIFT);
542 	if (grp) {
543 		fe->pcl = container_of(grp, struct z_erofs_pcluster, obj);
544 	} else {
545 tailpacking:
546 		ret = z_erofs_register_pcluster(fe);
547 		if (!ret)
548 			goto out;
549 		if (ret != -EEXIST)
550 			return ret;
551 	}
552 
553 	ret = z_erofs_lookup_pcluster(fe);
554 	if (ret) {
555 		erofs_workgroup_put(&fe->pcl->obj);
556 		return ret;
557 	}
558 
559 out:
560 	z_erofs_pagevec_ctor_init(&fe->vector, Z_EROFS_NR_INLINE_PAGEVECS,
561 				  fe->pcl->pagevec, fe->pcl->vcnt);
562 	/* since file-backed online pages are traversed in reverse order */
563 	fe->icpage_ptr = fe->pcl->compressed_pages +
564 			z_erofs_pclusterpages(fe->pcl);
565 	return 0;
566 }
567 
568 /*
569  * keep in mind that no referenced pclusters will be freed
570  * only after a RCU grace period.
571  */
572 static void z_erofs_rcu_callback(struct rcu_head *head)
573 {
574 	z_erofs_free_pcluster(container_of(head,
575 			struct z_erofs_pcluster, rcu));
576 }
577 
578 void erofs_workgroup_free_rcu(struct erofs_workgroup *grp)
579 {
580 	struct z_erofs_pcluster *const pcl =
581 		container_of(grp, struct z_erofs_pcluster, obj);
582 
583 	call_rcu(&pcl->rcu, z_erofs_rcu_callback);
584 }
585 
586 static bool z_erofs_collector_end(struct z_erofs_decompress_frontend *fe)
587 {
588 	struct z_erofs_pcluster *pcl = fe->pcl;
589 
590 	if (!pcl)
591 		return false;
592 
593 	z_erofs_pagevec_ctor_exit(&fe->vector, false);
594 	mutex_unlock(&pcl->lock);
595 
596 	/*
597 	 * if all pending pages are added, don't hold its reference
598 	 * any longer if the pcluster isn't hosted by ourselves.
599 	 */
600 	if (fe->mode < COLLECT_PRIMARY_FOLLOWED_NOINPLACE)
601 		erofs_workgroup_put(&pcl->obj);
602 
603 	fe->pcl = NULL;
604 	return true;
605 }
606 
607 static bool should_alloc_managed_pages(struct z_erofs_decompress_frontend *fe,
608 				       unsigned int cachestrategy,
609 				       erofs_off_t la)
610 {
611 	if (cachestrategy <= EROFS_ZIP_CACHE_DISABLED)
612 		return false;
613 
614 	if (fe->backmost)
615 		return true;
616 
617 	return cachestrategy >= EROFS_ZIP_CACHE_READAROUND &&
618 		la < fe->headoffset;
619 }
620 
621 static int z_erofs_do_read_page(struct z_erofs_decompress_frontend *fe,
622 				struct page *page, struct page **pagepool)
623 {
624 	struct inode *const inode = fe->inode;
625 	struct erofs_sb_info *const sbi = EROFS_I_SB(inode);
626 	struct erofs_map_blocks *const map = &fe->map;
627 	const loff_t offset = page_offset(page);
628 	bool tight = true;
629 
630 	enum z_erofs_cache_alloctype cache_strategy;
631 	enum z_erofs_page_type page_type;
632 	unsigned int cur, end, spiltted, index;
633 	int err = 0;
634 
635 	/* register locked file pages as online pages in pack */
636 	z_erofs_onlinepage_init(page);
637 
638 	spiltted = 0;
639 	end = PAGE_SIZE;
640 repeat:
641 	cur = end - 1;
642 
643 	if (offset + cur < map->m_la ||
644 	    offset + cur >= map->m_la + map->m_llen) {
645 		erofs_dbg("out-of-range map @ pos %llu", offset + cur);
646 
647 		if (z_erofs_collector_end(fe))
648 			fe->backmost = false;
649 		map->m_la = offset + cur;
650 		map->m_llen = 0;
651 		err = z_erofs_map_blocks_iter(inode, map, 0);
652 		if (err)
653 			goto err_out;
654 	} else {
655 		if (fe->pcl)
656 			goto hitted;
657 		/* didn't get a valid pcluster previously (very rare) */
658 	}
659 
660 	if (!(map->m_flags & EROFS_MAP_MAPPED))
661 		goto hitted;
662 
663 	err = z_erofs_collector_begin(fe);
664 	if (err)
665 		goto err_out;
666 
667 	if (z_erofs_is_inline_pcluster(fe->pcl)) {
668 		void *mp;
669 
670 		mp = erofs_read_metabuf(&fe->map.buf, inode->i_sb,
671 					erofs_blknr(map->m_pa), EROFS_NO_KMAP);
672 		if (IS_ERR(mp)) {
673 			err = PTR_ERR(mp);
674 			erofs_err(inode->i_sb,
675 				  "failed to get inline page, err %d", err);
676 			goto err_out;
677 		}
678 		get_page(fe->map.buf.page);
679 		WRITE_ONCE(fe->pcl->compressed_pages[0], fe->map.buf.page);
680 		fe->mode = COLLECT_PRIMARY_FOLLOWED_NOINPLACE;
681 	} else {
682 		/* bind cache first when cached decompression is preferred */
683 		if (should_alloc_managed_pages(fe, sbi->opt.cache_strategy,
684 					       map->m_la))
685 			cache_strategy = TRYALLOC;
686 		else
687 			cache_strategy = DONTALLOC;
688 
689 		z_erofs_bind_cache(fe, cache_strategy, pagepool);
690 	}
691 hitted:
692 	/*
693 	 * Ensure the current partial page belongs to this submit chain rather
694 	 * than other concurrent submit chains or the noio(bypass) chain since
695 	 * those chains are handled asynchronously thus the page cannot be used
696 	 * for inplace I/O or pagevec (should be processed in strict order.)
697 	 */
698 	tight &= (fe->mode >= COLLECT_PRIMARY_HOOKED &&
699 		  fe->mode != COLLECT_PRIMARY_FOLLOWED_NOINPLACE);
700 
701 	cur = end - min_t(unsigned int, offset + end - map->m_la, end);
702 	if (!(map->m_flags & EROFS_MAP_MAPPED)) {
703 		zero_user_segment(page, cur, end);
704 		goto next_part;
705 	}
706 
707 	/* let's derive page type */
708 	page_type = cur ? Z_EROFS_VLE_PAGE_TYPE_HEAD :
709 		(!spiltted ? Z_EROFS_PAGE_TYPE_EXCLUSIVE :
710 			(tight ? Z_EROFS_PAGE_TYPE_EXCLUSIVE :
711 				Z_EROFS_VLE_PAGE_TYPE_TAIL_SHARED));
712 
713 	if (cur)
714 		tight &= (fe->mode >= COLLECT_PRIMARY_FOLLOWED);
715 
716 retry:
717 	err = z_erofs_attach_page(fe, page, page_type,
718 				  fe->mode >= COLLECT_PRIMARY_FOLLOWED);
719 	/* should allocate an additional short-lived page for pagevec */
720 	if (err == -EAGAIN) {
721 		struct page *const newpage =
722 				alloc_page(GFP_NOFS | __GFP_NOFAIL);
723 
724 		set_page_private(newpage, Z_EROFS_SHORTLIVED_PAGE);
725 		err = z_erofs_attach_page(fe, newpage,
726 					  Z_EROFS_PAGE_TYPE_EXCLUSIVE, true);
727 		if (!err)
728 			goto retry;
729 	}
730 
731 	if (err)
732 		goto err_out;
733 
734 	index = page->index - (map->m_la >> PAGE_SHIFT);
735 
736 	z_erofs_onlinepage_fixup(page, index, true);
737 
738 	/* bump up the number of spiltted parts of a page */
739 	++spiltted;
740 	/* also update nr_pages */
741 	fe->pcl->nr_pages = max_t(pgoff_t, fe->pcl->nr_pages, index + 1);
742 next_part:
743 	/* can be used for verification */
744 	map->m_llen = offset + cur - map->m_la;
745 
746 	end = cur;
747 	if (end > 0)
748 		goto repeat;
749 
750 out:
751 	z_erofs_onlinepage_endio(page);
752 
753 	erofs_dbg("%s, finish page: %pK spiltted: %u map->m_llen %llu",
754 		  __func__, page, spiltted, map->m_llen);
755 	return err;
756 
757 	/* if some error occurred while processing this page */
758 err_out:
759 	SetPageError(page);
760 	goto out;
761 }
762 
763 static bool z_erofs_get_sync_decompress_policy(struct erofs_sb_info *sbi,
764 				       unsigned int readahead_pages)
765 {
766 	/* auto: enable for read_folio, disable for readahead */
767 	if ((sbi->opt.sync_decompress == EROFS_SYNC_DECOMPRESS_AUTO) &&
768 	    !readahead_pages)
769 		return true;
770 
771 	if ((sbi->opt.sync_decompress == EROFS_SYNC_DECOMPRESS_FORCE_ON) &&
772 	    (readahead_pages <= sbi->opt.max_sync_decompress_pages))
773 		return true;
774 
775 	return false;
776 }
777 
778 static bool z_erofs_page_is_invalidated(struct page *page)
779 {
780 	return !page->mapping && !z_erofs_is_shortlived_page(page);
781 }
782 
783 static int z_erofs_decompress_pcluster(struct super_block *sb,
784 				       struct z_erofs_pcluster *pcl,
785 				       struct page **pagepool)
786 {
787 	struct erofs_sb_info *const sbi = EROFS_SB(sb);
788 	unsigned int pclusterpages = z_erofs_pclusterpages(pcl);
789 	struct z_erofs_pagevec_ctor ctor;
790 	unsigned int i, inputsize, outputsize, llen, nr_pages;
791 	struct page *pages_onstack[Z_EROFS_VMAP_ONSTACK_PAGES];
792 	struct page **pages, **compressed_pages, *page;
793 
794 	enum z_erofs_page_type page_type;
795 	bool overlapped, partial;
796 	int err;
797 
798 	might_sleep();
799 	DBG_BUGON(!READ_ONCE(pcl->nr_pages));
800 
801 	mutex_lock(&pcl->lock);
802 	nr_pages = pcl->nr_pages;
803 
804 	if (nr_pages <= Z_EROFS_VMAP_ONSTACK_PAGES) {
805 		pages = pages_onstack;
806 	} else if (nr_pages <= Z_EROFS_VMAP_GLOBAL_PAGES &&
807 		   mutex_trylock(&z_pagemap_global_lock)) {
808 		pages = z_pagemap_global;
809 	} else {
810 		gfp_t gfp_flags = GFP_KERNEL;
811 
812 		if (nr_pages > Z_EROFS_VMAP_GLOBAL_PAGES)
813 			gfp_flags |= __GFP_NOFAIL;
814 
815 		pages = kvmalloc_array(nr_pages, sizeof(struct page *),
816 				       gfp_flags);
817 
818 		/* fallback to global pagemap for the lowmem scenario */
819 		if (!pages) {
820 			mutex_lock(&z_pagemap_global_lock);
821 			pages = z_pagemap_global;
822 		}
823 	}
824 
825 	for (i = 0; i < nr_pages; ++i)
826 		pages[i] = NULL;
827 
828 	err = 0;
829 	z_erofs_pagevec_ctor_init(&ctor, Z_EROFS_NR_INLINE_PAGEVECS,
830 				  pcl->pagevec, 0);
831 
832 	for (i = 0; i < pcl->vcnt; ++i) {
833 		unsigned int pagenr;
834 
835 		page = z_erofs_pagevec_dequeue(&ctor, &page_type);
836 
837 		/* all pages in pagevec ought to be valid */
838 		DBG_BUGON(!page);
839 		DBG_BUGON(z_erofs_page_is_invalidated(page));
840 
841 		if (z_erofs_put_shortlivedpage(pagepool, page))
842 			continue;
843 
844 		if (page_type == Z_EROFS_VLE_PAGE_TYPE_HEAD)
845 			pagenr = 0;
846 		else
847 			pagenr = z_erofs_onlinepage_index(page);
848 
849 		DBG_BUGON(pagenr >= nr_pages);
850 
851 		/*
852 		 * currently EROFS doesn't support multiref(dedup),
853 		 * so here erroring out one multiref page.
854 		 */
855 		if (pages[pagenr]) {
856 			DBG_BUGON(1);
857 			SetPageError(pages[pagenr]);
858 			z_erofs_onlinepage_endio(pages[pagenr]);
859 			err = -EFSCORRUPTED;
860 		}
861 		pages[pagenr] = page;
862 	}
863 	z_erofs_pagevec_ctor_exit(&ctor, true);
864 
865 	overlapped = false;
866 	compressed_pages = pcl->compressed_pages;
867 
868 	for (i = 0; i < pclusterpages; ++i) {
869 		unsigned int pagenr;
870 
871 		page = compressed_pages[i];
872 		/* all compressed pages ought to be valid */
873 		DBG_BUGON(!page);
874 
875 		if (z_erofs_is_inline_pcluster(pcl)) {
876 			if (!PageUptodate(page))
877 				err = -EIO;
878 			continue;
879 		}
880 
881 		DBG_BUGON(z_erofs_page_is_invalidated(page));
882 		if (!z_erofs_is_shortlived_page(page)) {
883 			if (erofs_page_is_managed(sbi, page)) {
884 				if (!PageUptodate(page))
885 					err = -EIO;
886 				continue;
887 			}
888 
889 			/*
890 			 * only if non-head page can be selected
891 			 * for inplace decompression
892 			 */
893 			pagenr = z_erofs_onlinepage_index(page);
894 
895 			DBG_BUGON(pagenr >= nr_pages);
896 			if (pages[pagenr]) {
897 				DBG_BUGON(1);
898 				SetPageError(pages[pagenr]);
899 				z_erofs_onlinepage_endio(pages[pagenr]);
900 				err = -EFSCORRUPTED;
901 			}
902 			pages[pagenr] = page;
903 
904 			overlapped = true;
905 		}
906 
907 		/* PG_error needs checking for all non-managed pages */
908 		if (PageError(page)) {
909 			DBG_BUGON(PageUptodate(page));
910 			err = -EIO;
911 		}
912 	}
913 
914 	if (err)
915 		goto out;
916 
917 	llen = pcl->length >> Z_EROFS_PCLUSTER_LENGTH_BIT;
918 	if (nr_pages << PAGE_SHIFT >= pcl->pageofs_out + llen) {
919 		outputsize = llen;
920 		partial = !(pcl->length & Z_EROFS_PCLUSTER_FULL_LENGTH);
921 	} else {
922 		outputsize = (nr_pages << PAGE_SHIFT) - pcl->pageofs_out;
923 		partial = true;
924 	}
925 
926 	if (z_erofs_is_inline_pcluster(pcl))
927 		inputsize = pcl->tailpacking_size;
928 	else
929 		inputsize = pclusterpages * PAGE_SIZE;
930 
931 	err = z_erofs_decompress(&(struct z_erofs_decompress_req) {
932 					.sb = sb,
933 					.in = compressed_pages,
934 					.out = pages,
935 					.pageofs_in = pcl->pageofs_in,
936 					.pageofs_out = pcl->pageofs_out,
937 					.inputsize = inputsize,
938 					.outputsize = outputsize,
939 					.alg = pcl->algorithmformat,
940 					.inplace_io = overlapped,
941 					.partial_decoding = partial
942 				 }, pagepool);
943 
944 out:
945 	/* must handle all compressed pages before actual file pages */
946 	if (z_erofs_is_inline_pcluster(pcl)) {
947 		page = compressed_pages[0];
948 		WRITE_ONCE(compressed_pages[0], NULL);
949 		put_page(page);
950 	} else {
951 		for (i = 0; i < pclusterpages; ++i) {
952 			page = compressed_pages[i];
953 
954 			if (erofs_page_is_managed(sbi, page))
955 				continue;
956 
957 			/* recycle all individual short-lived pages */
958 			(void)z_erofs_put_shortlivedpage(pagepool, page);
959 			WRITE_ONCE(compressed_pages[i], NULL);
960 		}
961 	}
962 
963 	for (i = 0; i < nr_pages; ++i) {
964 		page = pages[i];
965 		if (!page)
966 			continue;
967 
968 		DBG_BUGON(z_erofs_page_is_invalidated(page));
969 
970 		/* recycle all individual short-lived pages */
971 		if (z_erofs_put_shortlivedpage(pagepool, page))
972 			continue;
973 
974 		if (err < 0)
975 			SetPageError(page);
976 
977 		z_erofs_onlinepage_endio(page);
978 	}
979 
980 	if (pages == z_pagemap_global)
981 		mutex_unlock(&z_pagemap_global_lock);
982 	else if (pages != pages_onstack)
983 		kvfree(pages);
984 
985 	pcl->nr_pages = 0;
986 	pcl->vcnt = 0;
987 
988 	/* pcluster lock MUST be taken before the following line */
989 	WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_NIL);
990 	mutex_unlock(&pcl->lock);
991 	return err;
992 }
993 
994 static void z_erofs_decompress_queue(const struct z_erofs_decompressqueue *io,
995 				     struct page **pagepool)
996 {
997 	z_erofs_next_pcluster_t owned = io->head;
998 
999 	while (owned != Z_EROFS_PCLUSTER_TAIL_CLOSED) {
1000 		struct z_erofs_pcluster *pcl;
1001 
1002 		/* no possible that 'owned' equals Z_EROFS_WORK_TPTR_TAIL */
1003 		DBG_BUGON(owned == Z_EROFS_PCLUSTER_TAIL);
1004 
1005 		/* no possible that 'owned' equals NULL */
1006 		DBG_BUGON(owned == Z_EROFS_PCLUSTER_NIL);
1007 
1008 		pcl = container_of(owned, struct z_erofs_pcluster, next);
1009 		owned = READ_ONCE(pcl->next);
1010 
1011 		z_erofs_decompress_pcluster(io->sb, pcl, pagepool);
1012 		erofs_workgroup_put(&pcl->obj);
1013 	}
1014 }
1015 
1016 static void z_erofs_decompressqueue_work(struct work_struct *work)
1017 {
1018 	struct z_erofs_decompressqueue *bgq =
1019 		container_of(work, struct z_erofs_decompressqueue, u.work);
1020 	struct page *pagepool = NULL;
1021 
1022 	DBG_BUGON(bgq->head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1023 	z_erofs_decompress_queue(bgq, &pagepool);
1024 
1025 	erofs_release_pages(&pagepool);
1026 	kvfree(bgq);
1027 }
1028 
1029 static void z_erofs_decompress_kickoff(struct z_erofs_decompressqueue *io,
1030 				       bool sync, int bios)
1031 {
1032 	struct erofs_sb_info *const sbi = EROFS_SB(io->sb);
1033 
1034 	/* wake up the caller thread for sync decompression */
1035 	if (sync) {
1036 		if (!atomic_add_return(bios, &io->pending_bios))
1037 			complete(&io->u.done);
1038 
1039 		return;
1040 	}
1041 
1042 	if (atomic_add_return(bios, &io->pending_bios))
1043 		return;
1044 	/* Use workqueue and sync decompression for atomic contexts only */
1045 	if (in_atomic() || irqs_disabled()) {
1046 		queue_work(z_erofs_workqueue, &io->u.work);
1047 		/* enable sync decompression for readahead */
1048 		if (sbi->opt.sync_decompress == EROFS_SYNC_DECOMPRESS_AUTO)
1049 			sbi->opt.sync_decompress = EROFS_SYNC_DECOMPRESS_FORCE_ON;
1050 		return;
1051 	}
1052 	z_erofs_decompressqueue_work(&io->u.work);
1053 }
1054 
1055 static struct page *pickup_page_for_submission(struct z_erofs_pcluster *pcl,
1056 					       unsigned int nr,
1057 					       struct page **pagepool,
1058 					       struct address_space *mc)
1059 {
1060 	const pgoff_t index = pcl->obj.index;
1061 	gfp_t gfp = mapping_gfp_mask(mc);
1062 	bool tocache = false;
1063 
1064 	struct address_space *mapping;
1065 	struct page *oldpage, *page;
1066 
1067 	compressed_page_t t;
1068 	int justfound;
1069 
1070 repeat:
1071 	page = READ_ONCE(pcl->compressed_pages[nr]);
1072 	oldpage = page;
1073 
1074 	if (!page)
1075 		goto out_allocpage;
1076 
1077 	/* process the target tagged pointer */
1078 	t = tagptr_init(compressed_page_t, page);
1079 	justfound = tagptr_unfold_tags(t);
1080 	page = tagptr_unfold_ptr(t);
1081 
1082 	/*
1083 	 * preallocated cached pages, which is used to avoid direct reclaim
1084 	 * otherwise, it will go inplace I/O path instead.
1085 	 */
1086 	if (page->private == Z_EROFS_PREALLOCATED_PAGE) {
1087 		WRITE_ONCE(pcl->compressed_pages[nr], page);
1088 		set_page_private(page, 0);
1089 		tocache = true;
1090 		goto out_tocache;
1091 	}
1092 	mapping = READ_ONCE(page->mapping);
1093 
1094 	/*
1095 	 * file-backed online pages in plcuster are all locked steady,
1096 	 * therefore it is impossible for `mapping' to be NULL.
1097 	 */
1098 	if (mapping && mapping != mc)
1099 		/* ought to be unmanaged pages */
1100 		goto out;
1101 
1102 	/* directly return for shortlived page as well */
1103 	if (z_erofs_is_shortlived_page(page))
1104 		goto out;
1105 
1106 	lock_page(page);
1107 
1108 	/* only true if page reclaim goes wrong, should never happen */
1109 	DBG_BUGON(justfound && PagePrivate(page));
1110 
1111 	/* the page is still in manage cache */
1112 	if (page->mapping == mc) {
1113 		WRITE_ONCE(pcl->compressed_pages[nr], page);
1114 
1115 		ClearPageError(page);
1116 		if (!PagePrivate(page)) {
1117 			/*
1118 			 * impossible to be !PagePrivate(page) for
1119 			 * the current restriction as well if
1120 			 * the page is already in compressed_pages[].
1121 			 */
1122 			DBG_BUGON(!justfound);
1123 
1124 			justfound = 0;
1125 			set_page_private(page, (unsigned long)pcl);
1126 			SetPagePrivate(page);
1127 		}
1128 
1129 		/* no need to submit io if it is already up-to-date */
1130 		if (PageUptodate(page)) {
1131 			unlock_page(page);
1132 			page = NULL;
1133 		}
1134 		goto out;
1135 	}
1136 
1137 	/*
1138 	 * the managed page has been truncated, it's unsafe to
1139 	 * reuse this one, let's allocate a new cache-managed page.
1140 	 */
1141 	DBG_BUGON(page->mapping);
1142 	DBG_BUGON(!justfound);
1143 
1144 	tocache = true;
1145 	unlock_page(page);
1146 	put_page(page);
1147 out_allocpage:
1148 	page = erofs_allocpage(pagepool, gfp | __GFP_NOFAIL);
1149 	if (oldpage != cmpxchg(&pcl->compressed_pages[nr], oldpage, page)) {
1150 		erofs_pagepool_add(pagepool, page);
1151 		cond_resched();
1152 		goto repeat;
1153 	}
1154 out_tocache:
1155 	if (!tocache || add_to_page_cache_lru(page, mc, index + nr, gfp)) {
1156 		/* turn into temporary page if fails (1 ref) */
1157 		set_page_private(page, Z_EROFS_SHORTLIVED_PAGE);
1158 		goto out;
1159 	}
1160 	attach_page_private(page, pcl);
1161 	/* drop a refcount added by allocpage (then we have 2 refs here) */
1162 	put_page(page);
1163 
1164 out:	/* the only exit (for tracing and debugging) */
1165 	return page;
1166 }
1167 
1168 static struct z_erofs_decompressqueue *
1169 jobqueue_init(struct super_block *sb,
1170 	      struct z_erofs_decompressqueue *fgq, bool *fg)
1171 {
1172 	struct z_erofs_decompressqueue *q;
1173 
1174 	if (fg && !*fg) {
1175 		q = kvzalloc(sizeof(*q), GFP_KERNEL | __GFP_NOWARN);
1176 		if (!q) {
1177 			*fg = true;
1178 			goto fg_out;
1179 		}
1180 		INIT_WORK(&q->u.work, z_erofs_decompressqueue_work);
1181 	} else {
1182 fg_out:
1183 		q = fgq;
1184 		init_completion(&fgq->u.done);
1185 		atomic_set(&fgq->pending_bios, 0);
1186 	}
1187 	q->sb = sb;
1188 	q->head = Z_EROFS_PCLUSTER_TAIL_CLOSED;
1189 	return q;
1190 }
1191 
1192 /* define decompression jobqueue types */
1193 enum {
1194 	JQ_BYPASS,
1195 	JQ_SUBMIT,
1196 	NR_JOBQUEUES,
1197 };
1198 
1199 static void *jobqueueset_init(struct super_block *sb,
1200 			      struct z_erofs_decompressqueue *q[],
1201 			      struct z_erofs_decompressqueue *fgq, bool *fg)
1202 {
1203 	/*
1204 	 * if managed cache is enabled, bypass jobqueue is needed,
1205 	 * no need to read from device for all pclusters in this queue.
1206 	 */
1207 	q[JQ_BYPASS] = jobqueue_init(sb, fgq + JQ_BYPASS, NULL);
1208 	q[JQ_SUBMIT] = jobqueue_init(sb, fgq + JQ_SUBMIT, fg);
1209 
1210 	return tagptr_cast_ptr(tagptr_fold(tagptr1_t, q[JQ_SUBMIT], *fg));
1211 }
1212 
1213 static void move_to_bypass_jobqueue(struct z_erofs_pcluster *pcl,
1214 				    z_erofs_next_pcluster_t qtail[],
1215 				    z_erofs_next_pcluster_t owned_head)
1216 {
1217 	z_erofs_next_pcluster_t *const submit_qtail = qtail[JQ_SUBMIT];
1218 	z_erofs_next_pcluster_t *const bypass_qtail = qtail[JQ_BYPASS];
1219 
1220 	DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1221 	if (owned_head == Z_EROFS_PCLUSTER_TAIL)
1222 		owned_head = Z_EROFS_PCLUSTER_TAIL_CLOSED;
1223 
1224 	WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_TAIL_CLOSED);
1225 
1226 	WRITE_ONCE(*submit_qtail, owned_head);
1227 	WRITE_ONCE(*bypass_qtail, &pcl->next);
1228 
1229 	qtail[JQ_BYPASS] = &pcl->next;
1230 }
1231 
1232 static void z_erofs_decompressqueue_endio(struct bio *bio)
1233 {
1234 	tagptr1_t t = tagptr_init(tagptr1_t, bio->bi_private);
1235 	struct z_erofs_decompressqueue *q = tagptr_unfold_ptr(t);
1236 	blk_status_t err = bio->bi_status;
1237 	struct bio_vec *bvec;
1238 	struct bvec_iter_all iter_all;
1239 
1240 	bio_for_each_segment_all(bvec, bio, iter_all) {
1241 		struct page *page = bvec->bv_page;
1242 
1243 		DBG_BUGON(PageUptodate(page));
1244 		DBG_BUGON(z_erofs_page_is_invalidated(page));
1245 
1246 		if (err)
1247 			SetPageError(page);
1248 
1249 		if (erofs_page_is_managed(EROFS_SB(q->sb), page)) {
1250 			if (!err)
1251 				SetPageUptodate(page);
1252 			unlock_page(page);
1253 		}
1254 	}
1255 	z_erofs_decompress_kickoff(q, tagptr_unfold_tags(t), -1);
1256 	bio_put(bio);
1257 }
1258 
1259 static void z_erofs_submit_queue(struct z_erofs_decompress_frontend *f,
1260 				 struct page **pagepool,
1261 				 struct z_erofs_decompressqueue *fgq,
1262 				 bool *force_fg)
1263 {
1264 	struct super_block *sb = f->inode->i_sb;
1265 	struct address_space *mc = MNGD_MAPPING(EROFS_SB(sb));
1266 	z_erofs_next_pcluster_t qtail[NR_JOBQUEUES];
1267 	struct z_erofs_decompressqueue *q[NR_JOBQUEUES];
1268 	void *bi_private;
1269 	z_erofs_next_pcluster_t owned_head = f->owned_head;
1270 	/* bio is NULL initially, so no need to initialize last_{index,bdev} */
1271 	pgoff_t last_index;
1272 	struct block_device *last_bdev;
1273 	unsigned int nr_bios = 0;
1274 	struct bio *bio = NULL;
1275 
1276 	bi_private = jobqueueset_init(sb, q, fgq, force_fg);
1277 	qtail[JQ_BYPASS] = &q[JQ_BYPASS]->head;
1278 	qtail[JQ_SUBMIT] = &q[JQ_SUBMIT]->head;
1279 
1280 	/* by default, all need io submission */
1281 	q[JQ_SUBMIT]->head = owned_head;
1282 
1283 	do {
1284 		struct erofs_map_dev mdev;
1285 		struct z_erofs_pcluster *pcl;
1286 		pgoff_t cur, end;
1287 		unsigned int i = 0;
1288 		bool bypass = true;
1289 
1290 		/* no possible 'owned_head' equals the following */
1291 		DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1292 		DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_NIL);
1293 
1294 		pcl = container_of(owned_head, struct z_erofs_pcluster, next);
1295 
1296 		/* close the main owned chain at first */
1297 		owned_head = cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_TAIL,
1298 				     Z_EROFS_PCLUSTER_TAIL_CLOSED);
1299 		if (z_erofs_is_inline_pcluster(pcl)) {
1300 			move_to_bypass_jobqueue(pcl, qtail, owned_head);
1301 			continue;
1302 		}
1303 
1304 		/* no device id here, thus it will always succeed */
1305 		mdev = (struct erofs_map_dev) {
1306 			.m_pa = blknr_to_addr(pcl->obj.index),
1307 		};
1308 		(void)erofs_map_dev(sb, &mdev);
1309 
1310 		cur = erofs_blknr(mdev.m_pa);
1311 		end = cur + pcl->pclusterpages;
1312 
1313 		do {
1314 			struct page *page;
1315 
1316 			page = pickup_page_for_submission(pcl, i++, pagepool,
1317 							  mc);
1318 			if (!page)
1319 				continue;
1320 
1321 			if (bio && (cur != last_index + 1 ||
1322 				    last_bdev != mdev.m_bdev)) {
1323 submit_bio_retry:
1324 				submit_bio(bio);
1325 				bio = NULL;
1326 			}
1327 
1328 			if (!bio) {
1329 				bio = bio_alloc(mdev.m_bdev, BIO_MAX_VECS,
1330 						REQ_OP_READ, GFP_NOIO);
1331 				bio->bi_end_io = z_erofs_decompressqueue_endio;
1332 
1333 				last_bdev = mdev.m_bdev;
1334 				bio->bi_iter.bi_sector = (sector_t)cur <<
1335 					LOG_SECTORS_PER_BLOCK;
1336 				bio->bi_private = bi_private;
1337 				if (f->readahead)
1338 					bio->bi_opf |= REQ_RAHEAD;
1339 				++nr_bios;
1340 			}
1341 
1342 			if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE)
1343 				goto submit_bio_retry;
1344 
1345 			last_index = cur;
1346 			bypass = false;
1347 		} while (++cur < end);
1348 
1349 		if (!bypass)
1350 			qtail[JQ_SUBMIT] = &pcl->next;
1351 		else
1352 			move_to_bypass_jobqueue(pcl, qtail, owned_head);
1353 	} while (owned_head != Z_EROFS_PCLUSTER_TAIL);
1354 
1355 	if (bio)
1356 		submit_bio(bio);
1357 
1358 	/*
1359 	 * although background is preferred, no one is pending for submission.
1360 	 * don't issue workqueue for decompression but drop it directly instead.
1361 	 */
1362 	if (!*force_fg && !nr_bios) {
1363 		kvfree(q[JQ_SUBMIT]);
1364 		return;
1365 	}
1366 	z_erofs_decompress_kickoff(q[JQ_SUBMIT], *force_fg, nr_bios);
1367 }
1368 
1369 static void z_erofs_runqueue(struct z_erofs_decompress_frontend *f,
1370 			     struct page **pagepool, bool force_fg)
1371 {
1372 	struct z_erofs_decompressqueue io[NR_JOBQUEUES];
1373 
1374 	if (f->owned_head == Z_EROFS_PCLUSTER_TAIL)
1375 		return;
1376 	z_erofs_submit_queue(f, pagepool, io, &force_fg);
1377 
1378 	/* handle bypass queue (no i/o pclusters) immediately */
1379 	z_erofs_decompress_queue(&io[JQ_BYPASS], pagepool);
1380 
1381 	if (!force_fg)
1382 		return;
1383 
1384 	/* wait until all bios are completed */
1385 	wait_for_completion_io(&io[JQ_SUBMIT].u.done);
1386 
1387 	/* handle synchronous decompress queue in the caller context */
1388 	z_erofs_decompress_queue(&io[JQ_SUBMIT], pagepool);
1389 }
1390 
1391 /*
1392  * Since partial uptodate is still unimplemented for now, we have to use
1393  * approximate readmore strategies as a start.
1394  */
1395 static void z_erofs_pcluster_readmore(struct z_erofs_decompress_frontend *f,
1396 				      struct readahead_control *rac,
1397 				      erofs_off_t end,
1398 				      struct page **pagepool,
1399 				      bool backmost)
1400 {
1401 	struct inode *inode = f->inode;
1402 	struct erofs_map_blocks *map = &f->map;
1403 	erofs_off_t cur;
1404 	int err;
1405 
1406 	if (backmost) {
1407 		map->m_la = end;
1408 		err = z_erofs_map_blocks_iter(inode, map,
1409 					      EROFS_GET_BLOCKS_READMORE);
1410 		if (err)
1411 			return;
1412 
1413 		/* expend ra for the trailing edge if readahead */
1414 		if (rac) {
1415 			loff_t newstart = readahead_pos(rac);
1416 
1417 			cur = round_up(map->m_la + map->m_llen, PAGE_SIZE);
1418 			readahead_expand(rac, newstart, cur - newstart);
1419 			return;
1420 		}
1421 		end = round_up(end, PAGE_SIZE);
1422 	} else {
1423 		end = round_up(map->m_la, PAGE_SIZE);
1424 
1425 		if (!map->m_llen)
1426 			return;
1427 	}
1428 
1429 	cur = map->m_la + map->m_llen - 1;
1430 	while (cur >= end) {
1431 		pgoff_t index = cur >> PAGE_SHIFT;
1432 		struct page *page;
1433 
1434 		page = erofs_grab_cache_page_nowait(inode->i_mapping, index);
1435 		if (page) {
1436 			if (PageUptodate(page)) {
1437 				unlock_page(page);
1438 			} else {
1439 				err = z_erofs_do_read_page(f, page, pagepool);
1440 				if (err)
1441 					erofs_err(inode->i_sb,
1442 						  "readmore error at page %lu @ nid %llu",
1443 						  index, EROFS_I(inode)->nid);
1444 			}
1445 			put_page(page);
1446 		}
1447 
1448 		if (cur < PAGE_SIZE)
1449 			break;
1450 		cur = (index << PAGE_SHIFT) - 1;
1451 	}
1452 }
1453 
1454 static int z_erofs_read_folio(struct file *file, struct folio *folio)
1455 {
1456 	struct page *page = &folio->page;
1457 	struct inode *const inode = page->mapping->host;
1458 	struct erofs_sb_info *const sbi = EROFS_I_SB(inode);
1459 	struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1460 	struct page *pagepool = NULL;
1461 	int err;
1462 
1463 	trace_erofs_readpage(page, false);
1464 	f.headoffset = (erofs_off_t)page->index << PAGE_SHIFT;
1465 
1466 	z_erofs_pcluster_readmore(&f, NULL, f.headoffset + PAGE_SIZE - 1,
1467 				  &pagepool, true);
1468 	err = z_erofs_do_read_page(&f, page, &pagepool);
1469 	z_erofs_pcluster_readmore(&f, NULL, 0, &pagepool, false);
1470 
1471 	(void)z_erofs_collector_end(&f);
1472 
1473 	/* if some compressed cluster ready, need submit them anyway */
1474 	z_erofs_runqueue(&f, &pagepool,
1475 			 z_erofs_get_sync_decompress_policy(sbi, 0));
1476 
1477 	if (err)
1478 		erofs_err(inode->i_sb, "failed to read, err [%d]", err);
1479 
1480 	erofs_put_metabuf(&f.map.buf);
1481 	erofs_release_pages(&pagepool);
1482 	return err;
1483 }
1484 
1485 static void z_erofs_readahead(struct readahead_control *rac)
1486 {
1487 	struct inode *const inode = rac->mapping->host;
1488 	struct erofs_sb_info *const sbi = EROFS_I_SB(inode);
1489 	struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1490 	struct page *pagepool = NULL, *head = NULL, *page;
1491 	unsigned int nr_pages;
1492 
1493 	f.readahead = true;
1494 	f.headoffset = readahead_pos(rac);
1495 
1496 	z_erofs_pcluster_readmore(&f, rac, f.headoffset +
1497 				  readahead_length(rac) - 1, &pagepool, true);
1498 	nr_pages = readahead_count(rac);
1499 	trace_erofs_readpages(inode, readahead_index(rac), nr_pages, false);
1500 
1501 	while ((page = readahead_page(rac))) {
1502 		set_page_private(page, (unsigned long)head);
1503 		head = page;
1504 	}
1505 
1506 	while (head) {
1507 		struct page *page = head;
1508 		int err;
1509 
1510 		/* traversal in reverse order */
1511 		head = (void *)page_private(page);
1512 
1513 		err = z_erofs_do_read_page(&f, page, &pagepool);
1514 		if (err)
1515 			erofs_err(inode->i_sb,
1516 				  "readahead error at page %lu @ nid %llu",
1517 				  page->index, EROFS_I(inode)->nid);
1518 		put_page(page);
1519 	}
1520 	z_erofs_pcluster_readmore(&f, rac, 0, &pagepool, false);
1521 	(void)z_erofs_collector_end(&f);
1522 
1523 	z_erofs_runqueue(&f, &pagepool,
1524 			 z_erofs_get_sync_decompress_policy(sbi, nr_pages));
1525 	erofs_put_metabuf(&f.map.buf);
1526 	erofs_release_pages(&pagepool);
1527 }
1528 
1529 const struct address_space_operations z_erofs_aops = {
1530 	.read_folio = z_erofs_read_folio,
1531 	.readahead = z_erofs_readahead,
1532 };
1533