xref: /openbmc/linux/fs/erofs/zdata.c (revision 9f6cc76e)
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 	struct page **compressedpages;
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 	const struct z_erofs_pcluster *pcl = clt->pcl;
242 	struct page **pages = clt->compressedpages;
243 	pgoff_t index = pcl->obj.index + (pages - pcl->compressed_pages);
244 	bool standalone = true;
245 	gfp_t gfp = (mapping_gfp_mask(mc) & ~__GFP_DIRECT_RECLAIM) |
246 			__GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN;
247 
248 	if (clt->mode < COLLECT_PRIMARY_FOLLOWED)
249 		return;
250 
251 	for (; pages < pcl->compressed_pages + pcl->pclusterpages; ++pages) {
252 		struct page *page;
253 		compressed_page_t t;
254 		struct page *newpage = NULL;
255 
256 		/* the compressed page was loaded before */
257 		if (READ_ONCE(*pages))
258 			continue;
259 
260 		page = find_get_page(mc, index);
261 
262 		if (page) {
263 			t = tag_compressed_page_justfound(page);
264 		} else {
265 			/* I/O is needed, no possible to decompress directly */
266 			standalone = false;
267 			switch (type) {
268 			case DELAYEDALLOC:
269 				t = tagptr_init(compressed_page_t,
270 						PAGE_UNALLOCATED);
271 				break;
272 			case TRYALLOC:
273 				newpage = erofs_allocpage(pagepool, gfp);
274 				if (!newpage)
275 					continue;
276 				set_page_private(newpage,
277 						 Z_EROFS_PREALLOCATED_PAGE);
278 				t = tag_compressed_page_justfound(newpage);
279 				break;
280 			default:        /* DONTALLOC */
281 				continue;
282 			}
283 		}
284 
285 		if (!cmpxchg_relaxed(pages, NULL, tagptr_cast_ptr(t)))
286 			continue;
287 
288 		if (page) {
289 			put_page(page);
290 		} else if (newpage) {
291 			set_page_private(newpage, 0);
292 			list_add(&newpage->lru, pagepool);
293 		}
294 	}
295 
296 	/*
297 	 * don't do inplace I/O if all compressed pages are available in
298 	 * managed cache since it can be moved to the bypass queue instead.
299 	 */
300 	if (standalone)
301 		clt->mode = COLLECT_PRIMARY_FOLLOWED_NOINPLACE;
302 }
303 
304 /* called by erofs_shrinker to get rid of all compressed_pages */
305 int erofs_try_to_free_all_cached_pages(struct erofs_sb_info *sbi,
306 				       struct erofs_workgroup *grp)
307 {
308 	struct z_erofs_pcluster *const pcl =
309 		container_of(grp, struct z_erofs_pcluster, obj);
310 	struct address_space *const mapping = MNGD_MAPPING(sbi);
311 	int i;
312 
313 	/*
314 	 * refcount of workgroup is now freezed as 1,
315 	 * therefore no need to worry about available decompression users.
316 	 */
317 	for (i = 0; i < pcl->pclusterpages; ++i) {
318 		struct page *page = pcl->compressed_pages[i];
319 
320 		if (!page)
321 			continue;
322 
323 		/* block other users from reclaiming or migrating the page */
324 		if (!trylock_page(page))
325 			return -EBUSY;
326 
327 		if (page->mapping != mapping)
328 			continue;
329 
330 		/* barrier is implied in the following 'unlock_page' */
331 		WRITE_ONCE(pcl->compressed_pages[i], NULL);
332 		detach_page_private(page);
333 		unlock_page(page);
334 	}
335 	return 0;
336 }
337 
338 int erofs_try_to_free_cached_page(struct address_space *mapping,
339 				  struct page *page)
340 {
341 	struct z_erofs_pcluster *const pcl = (void *)page_private(page);
342 	int ret = 0;	/* 0 - busy */
343 
344 	if (erofs_workgroup_try_to_freeze(&pcl->obj, 1)) {
345 		unsigned int i;
346 
347 		for (i = 0; i < pcl->pclusterpages; ++i) {
348 			if (pcl->compressed_pages[i] == page) {
349 				WRITE_ONCE(pcl->compressed_pages[i], NULL);
350 				ret = 1;
351 				break;
352 			}
353 		}
354 		erofs_workgroup_unfreeze(&pcl->obj, 1);
355 
356 		if (ret)
357 			detach_page_private(page);
358 	}
359 	return ret;
360 }
361 
362 /* page_type must be Z_EROFS_PAGE_TYPE_EXCLUSIVE */
363 static inline bool z_erofs_try_inplace_io(struct z_erofs_collector *clt,
364 					  struct page *page)
365 {
366 	struct z_erofs_pcluster *const pcl = clt->pcl;
367 
368 	while (clt->compressedpages <
369 	       pcl->compressed_pages + pcl->pclusterpages) {
370 		if (!cmpxchg(clt->compressedpages++, NULL, page))
371 			return true;
372 	}
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 	bool occupied;
383 
384 	/* give priority for inplaceio */
385 	if (clt->mode >= COLLECT_PRIMARY &&
386 	    type == Z_EROFS_PAGE_TYPE_EXCLUSIVE &&
387 	    z_erofs_try_inplace_io(clt, page))
388 		return 0;
389 
390 	ret = z_erofs_pagevec_enqueue(&clt->vector,
391 				      page, type, &occupied);
392 	clt->cl->vcnt += (unsigned int)ret;
393 
394 	return ret ? 0 : -EAGAIN;
395 }
396 
397 static void z_erofs_try_to_claim_pcluster(struct z_erofs_collector *clt)
398 {
399 	struct z_erofs_pcluster *pcl = clt->pcl;
400 	z_erofs_next_pcluster_t *owned_head = &clt->owned_head;
401 
402 	/* type 1, nil pcluster (this pcluster doesn't belong to any chain.) */
403 	if (cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_NIL,
404 		    *owned_head) == Z_EROFS_PCLUSTER_NIL) {
405 		*owned_head = &pcl->next;
406 		/* so we can attach this pcluster to our submission chain. */
407 		clt->mode = COLLECT_PRIMARY_FOLLOWED;
408 		return;
409 	}
410 
411 	/*
412 	 * type 2, link to the end of an existing open chain, be careful
413 	 * that its submission is controlled by the original attached chain.
414 	 */
415 	if (cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_TAIL,
416 		    *owned_head) == Z_EROFS_PCLUSTER_TAIL) {
417 		*owned_head = Z_EROFS_PCLUSTER_TAIL;
418 		clt->mode = COLLECT_PRIMARY_HOOKED;
419 		clt->tailpcl = NULL;
420 		return;
421 	}
422 	/* type 3, it belongs to a chain, but it isn't the end of the chain */
423 	clt->mode = COLLECT_PRIMARY;
424 }
425 
426 static int z_erofs_lookup_collection(struct z_erofs_collector *clt,
427 				     struct inode *inode,
428 				     struct erofs_map_blocks *map)
429 {
430 	struct z_erofs_pcluster *pcl = clt->pcl;
431 	struct z_erofs_collection *cl;
432 	unsigned int length;
433 
434 	/* to avoid unexpected loop formed by corrupted images */
435 	if (clt->owned_head == &pcl->next || pcl == clt->tailpcl) {
436 		DBG_BUGON(1);
437 		return -EFSCORRUPTED;
438 	}
439 
440 	cl = z_erofs_primarycollection(pcl);
441 	if (cl->pageofs != (map->m_la & ~PAGE_MASK)) {
442 		DBG_BUGON(1);
443 		return -EFSCORRUPTED;
444 	}
445 
446 	length = READ_ONCE(pcl->length);
447 	if (length & Z_EROFS_PCLUSTER_FULL_LENGTH) {
448 		if ((map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT) > length) {
449 			DBG_BUGON(1);
450 			return -EFSCORRUPTED;
451 		}
452 	} else {
453 		unsigned int llen = map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT;
454 
455 		if (map->m_flags & EROFS_MAP_FULL_MAPPED)
456 			llen |= Z_EROFS_PCLUSTER_FULL_LENGTH;
457 
458 		while (llen > length &&
459 		       length != cmpxchg_relaxed(&pcl->length, length, llen)) {
460 			cpu_relax();
461 			length = READ_ONCE(pcl->length);
462 		}
463 	}
464 	mutex_lock(&cl->lock);
465 	/* used to check tail merging loop due to corrupted images */
466 	if (clt->owned_head == Z_EROFS_PCLUSTER_TAIL)
467 		clt->tailpcl = pcl;
468 
469 	z_erofs_try_to_claim_pcluster(clt);
470 	clt->cl = cl;
471 	return 0;
472 }
473 
474 static int z_erofs_register_collection(struct z_erofs_collector *clt,
475 				       struct inode *inode,
476 				       struct erofs_map_blocks *map)
477 {
478 	struct z_erofs_pcluster *pcl;
479 	struct z_erofs_collection *cl;
480 	struct erofs_workgroup *grp;
481 	int err;
482 
483 	/* no available pcluster, let's allocate one */
484 	pcl = z_erofs_alloc_pcluster(map->m_plen >> PAGE_SHIFT);
485 	if (IS_ERR(pcl))
486 		return PTR_ERR(pcl);
487 
488 	atomic_set(&pcl->obj.refcount, 1);
489 	pcl->obj.index = map->m_pa >> PAGE_SHIFT;
490 
491 	pcl->length = (map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT) |
492 		(map->m_flags & EROFS_MAP_FULL_MAPPED ?
493 			Z_EROFS_PCLUSTER_FULL_LENGTH : 0);
494 
495 	if (map->m_flags & EROFS_MAP_ZIPPED)
496 		pcl->algorithmformat = Z_EROFS_COMPRESSION_LZ4;
497 	else
498 		pcl->algorithmformat = Z_EROFS_COMPRESSION_SHIFTED;
499 
500 	/* new pclusters should be claimed as type 1, primary and followed */
501 	pcl->next = clt->owned_head;
502 	clt->mode = COLLECT_PRIMARY_FOLLOWED;
503 
504 	cl = z_erofs_primarycollection(pcl);
505 	cl->pageofs = map->m_la & ~PAGE_MASK;
506 
507 	/*
508 	 * lock all primary followed works before visible to others
509 	 * and mutex_trylock *never* fails for a new pcluster.
510 	 */
511 	mutex_init(&cl->lock);
512 	DBG_BUGON(!mutex_trylock(&cl->lock));
513 
514 	grp = erofs_insert_workgroup(inode->i_sb, &pcl->obj);
515 	if (IS_ERR(grp)) {
516 		err = PTR_ERR(grp);
517 		goto err_out;
518 	}
519 
520 	if (grp != &pcl->obj) {
521 		clt->pcl = container_of(grp, struct z_erofs_pcluster, obj);
522 		err = -EEXIST;
523 		goto err_out;
524 	}
525 	/* used to check tail merging loop due to corrupted images */
526 	if (clt->owned_head == Z_EROFS_PCLUSTER_TAIL)
527 		clt->tailpcl = pcl;
528 	clt->owned_head = &pcl->next;
529 	clt->pcl = pcl;
530 	clt->cl = cl;
531 	return 0;
532 
533 err_out:
534 	mutex_unlock(&cl->lock);
535 	z_erofs_free_pcluster(pcl);
536 	return err;
537 }
538 
539 static int z_erofs_collector_begin(struct z_erofs_collector *clt,
540 				   struct inode *inode,
541 				   struct erofs_map_blocks *map)
542 {
543 	struct erofs_workgroup *grp;
544 	int ret;
545 
546 	DBG_BUGON(clt->cl);
547 
548 	/* must be Z_EROFS_PCLUSTER_TAIL or pointed to previous collection */
549 	DBG_BUGON(clt->owned_head == Z_EROFS_PCLUSTER_NIL);
550 	DBG_BUGON(clt->owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
551 
552 	if (!PAGE_ALIGNED(map->m_pa)) {
553 		DBG_BUGON(1);
554 		return -EINVAL;
555 	}
556 
557 	grp = erofs_find_workgroup(inode->i_sb, map->m_pa >> PAGE_SHIFT);
558 	if (grp) {
559 		clt->pcl = container_of(grp, struct z_erofs_pcluster, obj);
560 	} else {
561 		ret = z_erofs_register_collection(clt, inode, map);
562 
563 		if (!ret)
564 			goto out;
565 		if (ret != -EEXIST)
566 			return ret;
567 	}
568 
569 	ret = z_erofs_lookup_collection(clt, inode, map);
570 	if (ret) {
571 		erofs_workgroup_put(&clt->pcl->obj);
572 		return ret;
573 	}
574 
575 out:
576 	z_erofs_pagevec_ctor_init(&clt->vector, Z_EROFS_NR_INLINE_PAGEVECS,
577 				  clt->cl->pagevec, clt->cl->vcnt);
578 
579 	clt->compressedpages = clt->pcl->compressed_pages;
580 	if (clt->mode <= COLLECT_PRIMARY) /* cannot do in-place I/O */
581 		clt->compressedpages += 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