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