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