xref: /openbmc/linux/fs/erofs/zdata.c (revision c4a11bf4)
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 page **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 			erofs_pagepool_add(pagepool, newpage);
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 	int i;
311 
312 	/*
313 	 * refcount of workgroup is now freezed as 1,
314 	 * therefore no need to worry about available decompression users.
315 	 */
316 	for (i = 0; i < pcl->pclusterpages; ++i) {
317 		struct page *page = pcl->compressed_pages[i];
318 
319 		if (!page)
320 			continue;
321 
322 		/* block other users from reclaiming or migrating the page */
323 		if (!trylock_page(page))
324 			return -EBUSY;
325 
326 		if (!erofs_page_is_managed(sbi, page))
327 			continue;
328 
329 		/* barrier is implied in the following 'unlock_page' */
330 		WRITE_ONCE(pcl->compressed_pages[i], NULL);
331 		detach_page_private(page);
332 		unlock_page(page);
333 	}
334 	return 0;
335 }
336 
337 int erofs_try_to_free_cached_page(struct page *page)
338 {
339 	struct z_erofs_pcluster *const pcl = (void *)page_private(page);
340 	int ret = 0;	/* 0 - busy */
341 
342 	if (erofs_workgroup_try_to_freeze(&pcl->obj, 1)) {
343 		unsigned int i;
344 
345 		for (i = 0; i < pcl->pclusterpages; ++i) {
346 			if (pcl->compressed_pages[i] == page) {
347 				WRITE_ONCE(pcl->compressed_pages[i], NULL);
348 				ret = 1;
349 				break;
350 			}
351 		}
352 		erofs_workgroup_unfreeze(&pcl->obj, 1);
353 
354 		if (ret)
355 			detach_page_private(page);
356 	}
357 	return ret;
358 }
359 
360 /* page_type must be Z_EROFS_PAGE_TYPE_EXCLUSIVE */
361 static bool z_erofs_try_inplace_io(struct z_erofs_collector *clt,
362 				   struct page *page)
363 {
364 	struct z_erofs_pcluster *const pcl = clt->pcl;
365 
366 	while (clt->icpage_ptr > pcl->compressed_pages)
367 		if (!cmpxchg(--clt->icpage_ptr, NULL, page))
368 			return true;
369 	return false;
370 }
371 
372 /* callers must be with collection lock held */
373 static int z_erofs_attach_page(struct z_erofs_collector *clt,
374 			       struct page *page,
375 			       enum z_erofs_page_type type)
376 {
377 	int ret;
378 
379 	/* give priority for inplaceio */
380 	if (clt->mode >= COLLECT_PRIMARY &&
381 	    type == Z_EROFS_PAGE_TYPE_EXCLUSIVE &&
382 	    z_erofs_try_inplace_io(clt, page))
383 		return 0;
384 
385 	ret = z_erofs_pagevec_enqueue(&clt->vector, page, type);
386 	clt->cl->vcnt += (unsigned int)ret;
387 
388 	return ret ? 0 : -EAGAIN;
389 }
390 
391 static void z_erofs_try_to_claim_pcluster(struct z_erofs_collector *clt)
392 {
393 	struct z_erofs_pcluster *pcl = clt->pcl;
394 	z_erofs_next_pcluster_t *owned_head = &clt->owned_head;
395 
396 	/* type 1, nil pcluster (this pcluster doesn't belong to any chain.) */
397 	if (cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_NIL,
398 		    *owned_head) == Z_EROFS_PCLUSTER_NIL) {
399 		*owned_head = &pcl->next;
400 		/* so we can attach this pcluster to our submission chain. */
401 		clt->mode = COLLECT_PRIMARY_FOLLOWED;
402 		return;
403 	}
404 
405 	/*
406 	 * type 2, link to the end of an existing open chain, be careful
407 	 * that its submission is controlled by the original attached chain.
408 	 */
409 	if (cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_TAIL,
410 		    *owned_head) == Z_EROFS_PCLUSTER_TAIL) {
411 		*owned_head = Z_EROFS_PCLUSTER_TAIL;
412 		clt->mode = COLLECT_PRIMARY_HOOKED;
413 		clt->tailpcl = NULL;
414 		return;
415 	}
416 	/* type 3, it belongs to a chain, but it isn't the end of the chain */
417 	clt->mode = COLLECT_PRIMARY;
418 }
419 
420 static int z_erofs_lookup_collection(struct z_erofs_collector *clt,
421 				     struct inode *inode,
422 				     struct erofs_map_blocks *map)
423 {
424 	struct z_erofs_pcluster *pcl = clt->pcl;
425 	struct z_erofs_collection *cl;
426 	unsigned int length;
427 
428 	/* to avoid unexpected loop formed by corrupted images */
429 	if (clt->owned_head == &pcl->next || pcl == clt->tailpcl) {
430 		DBG_BUGON(1);
431 		return -EFSCORRUPTED;
432 	}
433 
434 	cl = z_erofs_primarycollection(pcl);
435 	if (cl->pageofs != (map->m_la & ~PAGE_MASK)) {
436 		DBG_BUGON(1);
437 		return -EFSCORRUPTED;
438 	}
439 
440 	length = READ_ONCE(pcl->length);
441 	if (length & Z_EROFS_PCLUSTER_FULL_LENGTH) {
442 		if ((map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT) > length) {
443 			DBG_BUGON(1);
444 			return -EFSCORRUPTED;
445 		}
446 	} else {
447 		unsigned int llen = map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT;
448 
449 		if (map->m_flags & EROFS_MAP_FULL_MAPPED)
450 			llen |= Z_EROFS_PCLUSTER_FULL_LENGTH;
451 
452 		while (llen > length &&
453 		       length != cmpxchg_relaxed(&pcl->length, length, llen)) {
454 			cpu_relax();
455 			length = READ_ONCE(pcl->length);
456 		}
457 	}
458 	mutex_lock(&cl->lock);
459 	/* used to check tail merging loop due to corrupted images */
460 	if (clt->owned_head == Z_EROFS_PCLUSTER_TAIL)
461 		clt->tailpcl = pcl;
462 
463 	z_erofs_try_to_claim_pcluster(clt);
464 	clt->cl = cl;
465 	return 0;
466 }
467 
468 static int z_erofs_register_collection(struct z_erofs_collector *clt,
469 				       struct inode *inode,
470 				       struct erofs_map_blocks *map)
471 {
472 	struct z_erofs_pcluster *pcl;
473 	struct z_erofs_collection *cl;
474 	struct erofs_workgroup *grp;
475 	int err;
476 
477 	if (!(map->m_flags & EROFS_MAP_ENCODED)) {
478 		DBG_BUGON(1);
479 		return -EFSCORRUPTED;
480 	}
481 
482 	/* no available pcluster, let's allocate one */
483 	pcl = z_erofs_alloc_pcluster(map->m_plen >> PAGE_SHIFT);
484 	if (IS_ERR(pcl))
485 		return PTR_ERR(pcl);
486 
487 	atomic_set(&pcl->obj.refcount, 1);
488 	pcl->obj.index = map->m_pa >> PAGE_SHIFT;
489 	pcl->algorithmformat = map->m_algorithmformat;
490 	pcl->length = (map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT) |
491 		(map->m_flags & EROFS_MAP_FULL_MAPPED ?
492 			Z_EROFS_PCLUSTER_FULL_LENGTH : 0);
493 
494 	/* new pclusters should be claimed as type 1, primary and followed */
495 	pcl->next = clt->owned_head;
496 	clt->mode = COLLECT_PRIMARY_FOLLOWED;
497 
498 	cl = z_erofs_primarycollection(pcl);
499 	cl->pageofs = map->m_la & ~PAGE_MASK;
500 
501 	/*
502 	 * lock all primary followed works before visible to others
503 	 * and mutex_trylock *never* fails for a new pcluster.
504 	 */
505 	mutex_init(&cl->lock);
506 	DBG_BUGON(!mutex_trylock(&cl->lock));
507 
508 	grp = erofs_insert_workgroup(inode->i_sb, &pcl->obj);
509 	if (IS_ERR(grp)) {
510 		err = PTR_ERR(grp);
511 		goto err_out;
512 	}
513 
514 	if (grp != &pcl->obj) {
515 		clt->pcl = container_of(grp, struct z_erofs_pcluster, obj);
516 		err = -EEXIST;
517 		goto err_out;
518 	}
519 	/* used to check tail merging loop due to corrupted images */
520 	if (clt->owned_head == Z_EROFS_PCLUSTER_TAIL)
521 		clt->tailpcl = pcl;
522 	clt->owned_head = &pcl->next;
523 	clt->pcl = pcl;
524 	clt->cl = cl;
525 	return 0;
526 
527 err_out:
528 	mutex_unlock(&cl->lock);
529 	z_erofs_free_pcluster(pcl);
530 	return err;
531 }
532 
533 static int z_erofs_collector_begin(struct z_erofs_collector *clt,
534 				   struct inode *inode,
535 				   struct erofs_map_blocks *map)
536 {
537 	struct erofs_workgroup *grp;
538 	int ret;
539 
540 	DBG_BUGON(clt->cl);
541 
542 	/* must be Z_EROFS_PCLUSTER_TAIL or pointed to previous collection */
543 	DBG_BUGON(clt->owned_head == Z_EROFS_PCLUSTER_NIL);
544 	DBG_BUGON(clt->owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
545 
546 	if (!PAGE_ALIGNED(map->m_pa)) {
547 		DBG_BUGON(1);
548 		return -EINVAL;
549 	}
550 
551 	grp = erofs_find_workgroup(inode->i_sb, map->m_pa >> PAGE_SHIFT);
552 	if (grp) {
553 		clt->pcl = container_of(grp, struct z_erofs_pcluster, obj);
554 	} else {
555 		ret = z_erofs_register_collection(clt, inode, map);
556 
557 		if (!ret)
558 			goto out;
559 		if (ret != -EEXIST)
560 			return ret;
561 	}
562 
563 	ret = z_erofs_lookup_collection(clt, inode, map);
564 	if (ret) {
565 		erofs_workgroup_put(&clt->pcl->obj);
566 		return ret;
567 	}
568 
569 out:
570 	z_erofs_pagevec_ctor_init(&clt->vector, Z_EROFS_NR_INLINE_PAGEVECS,
571 				  clt->cl->pagevec, clt->cl->vcnt);
572 
573 	/* since file-backed online pages are traversed in reverse order */
574 	clt->icpage_ptr = clt->pcl->compressed_pages + clt->pcl->pclusterpages;
575 	return 0;
576 }
577 
578 /*
579  * keep in mind that no referenced pclusters will be freed
580  * only after a RCU grace period.
581  */
582 static void z_erofs_rcu_callback(struct rcu_head *head)
583 {
584 	struct z_erofs_collection *const cl =
585 		container_of(head, struct z_erofs_collection, rcu);
586 
587 	z_erofs_free_pcluster(container_of(cl, struct z_erofs_pcluster,
588 					   primary_collection));
589 }
590 
591 void erofs_workgroup_free_rcu(struct erofs_workgroup *grp)
592 {
593 	struct z_erofs_pcluster *const pcl =
594 		container_of(grp, struct z_erofs_pcluster, obj);
595 	struct z_erofs_collection *const cl = z_erofs_primarycollection(pcl);
596 
597 	call_rcu(&cl->rcu, z_erofs_rcu_callback);
598 }
599 
600 static void z_erofs_collection_put(struct z_erofs_collection *cl)
601 {
602 	struct z_erofs_pcluster *const pcl =
603 		container_of(cl, struct z_erofs_pcluster, primary_collection);
604 
605 	erofs_workgroup_put(&pcl->obj);
606 }
607 
608 static bool z_erofs_collector_end(struct z_erofs_collector *clt)
609 {
610 	struct z_erofs_collection *cl = clt->cl;
611 
612 	if (!cl)
613 		return false;
614 
615 	z_erofs_pagevec_ctor_exit(&clt->vector, false);
616 	mutex_unlock(&cl->lock);
617 
618 	/*
619 	 * if all pending pages are added, don't hold its reference
620 	 * any longer if the pcluster isn't hosted by ourselves.
621 	 */
622 	if (clt->mode < COLLECT_PRIMARY_FOLLOWED_NOINPLACE)
623 		z_erofs_collection_put(cl);
624 
625 	clt->cl = NULL;
626 	return true;
627 }
628 
629 static bool should_alloc_managed_pages(struct z_erofs_decompress_frontend *fe,
630 				       unsigned int cachestrategy,
631 				       erofs_off_t la)
632 {
633 	if (cachestrategy <= EROFS_ZIP_CACHE_DISABLED)
634 		return false;
635 
636 	if (fe->backmost)
637 		return true;
638 
639 	return cachestrategy >= EROFS_ZIP_CACHE_READAROUND &&
640 		la < fe->headoffset;
641 }
642 
643 static int z_erofs_do_read_page(struct z_erofs_decompress_frontend *fe,
644 				struct page *page, struct page **pagepool)
645 {
646 	struct inode *const inode = fe->inode;
647 	struct erofs_sb_info *const sbi = EROFS_I_SB(inode);
648 	struct erofs_map_blocks *const map = &fe->map;
649 	struct z_erofs_collector *const clt = &fe->clt;
650 	const loff_t offset = page_offset(page);
651 	bool tight = true;
652 
653 	enum z_erofs_cache_alloctype cache_strategy;
654 	enum z_erofs_page_type page_type;
655 	unsigned int cur, end, spiltted, index;
656 	int err = 0;
657 
658 	/* register locked file pages as online pages in pack */
659 	z_erofs_onlinepage_init(page);
660 
661 	spiltted = 0;
662 	end = PAGE_SIZE;
663 repeat:
664 	cur = end - 1;
665 
666 	/* lucky, within the range of the current map_blocks */
667 	if (offset + cur >= map->m_la &&
668 	    offset + cur < map->m_la + map->m_llen) {
669 		/* didn't get a valid collection previously (very rare) */
670 		if (!clt->cl)
671 			goto restart_now;
672 		goto hitted;
673 	}
674 
675 	/* go ahead the next map_blocks */
676 	erofs_dbg("%s: [out-of-range] pos %llu", __func__, offset + cur);
677 
678 	if (z_erofs_collector_end(clt))
679 		fe->backmost = false;
680 
681 	map->m_la = offset + cur;
682 	map->m_llen = 0;
683 	err = z_erofs_map_blocks_iter(inode, map, 0);
684 	if (err)
685 		goto err_out;
686 
687 restart_now:
688 	if (!(map->m_flags & EROFS_MAP_MAPPED))
689 		goto hitted;
690 
691 	err = z_erofs_collector_begin(clt, inode, map);
692 	if (err)
693 		goto err_out;
694 
695 	/* preload all compressed pages (maybe downgrade role if necessary) */
696 	if (should_alloc_managed_pages(fe, sbi->opt.cache_strategy, map->m_la))
697 		cache_strategy = TRYALLOC;
698 	else
699 		cache_strategy = DONTALLOC;
700 
701 	preload_compressed_pages(clt, MNGD_MAPPING(sbi),
702 				 cache_strategy, pagepool);
703 
704 hitted:
705 	/*
706 	 * Ensure the current partial page belongs to this submit chain rather
707 	 * than other concurrent submit chains or the noio(bypass) chain since
708 	 * those chains are handled asynchronously thus the page cannot be used
709 	 * for inplace I/O or pagevec (should be processed in strict order.)
710 	 */
711 	tight &= (clt->mode >= COLLECT_PRIMARY_HOOKED &&
712 		  clt->mode != COLLECT_PRIMARY_FOLLOWED_NOINPLACE);
713 
714 	cur = end - min_t(unsigned int, offset + end - map->m_la, end);
715 	if (!(map->m_flags & EROFS_MAP_MAPPED)) {
716 		zero_user_segment(page, cur, end);
717 		goto next_part;
718 	}
719 
720 	/* let's derive page type */
721 	page_type = cur ? Z_EROFS_VLE_PAGE_TYPE_HEAD :
722 		(!spiltted ? Z_EROFS_PAGE_TYPE_EXCLUSIVE :
723 			(tight ? Z_EROFS_PAGE_TYPE_EXCLUSIVE :
724 				Z_EROFS_VLE_PAGE_TYPE_TAIL_SHARED));
725 
726 	if (cur)
727 		tight &= (clt->mode >= COLLECT_PRIMARY_FOLLOWED);
728 
729 retry:
730 	err = z_erofs_attach_page(clt, page, page_type);
731 	/* should allocate an additional short-lived page for pagevec */
732 	if (err == -EAGAIN) {
733 		struct page *const newpage =
734 				alloc_page(GFP_NOFS | __GFP_NOFAIL);
735 
736 		set_page_private(newpage, Z_EROFS_SHORTLIVED_PAGE);
737 		err = z_erofs_attach_page(clt, newpage,
738 					  Z_EROFS_PAGE_TYPE_EXCLUSIVE);
739 		if (!err)
740 			goto retry;
741 	}
742 
743 	if (err)
744 		goto err_out;
745 
746 	index = page->index - (map->m_la >> PAGE_SHIFT);
747 
748 	z_erofs_onlinepage_fixup(page, index, true);
749 
750 	/* bump up the number of spiltted parts of a page */
751 	++spiltted;
752 	/* also update nr_pages */
753 	clt->cl->nr_pages = max_t(pgoff_t, clt->cl->nr_pages, index + 1);
754 next_part:
755 	/* can be used for verification */
756 	map->m_llen = offset + cur - map->m_la;
757 
758 	end = cur;
759 	if (end > 0)
760 		goto repeat;
761 
762 out:
763 	z_erofs_onlinepage_endio(page);
764 
765 	erofs_dbg("%s, finish page: %pK spiltted: %u map->m_llen %llu",
766 		  __func__, page, spiltted, map->m_llen);
767 	return err;
768 
769 	/* if some error occurred while processing this page */
770 err_out:
771 	SetPageError(page);
772 	goto out;
773 }
774 
775 static void z_erofs_decompressqueue_work(struct work_struct *work);
776 static void z_erofs_decompress_kickoff(struct z_erofs_decompressqueue *io,
777 				       bool sync, int bios)
778 {
779 	struct erofs_sb_info *const sbi = EROFS_SB(io->sb);
780 
781 	/* wake up the caller thread for sync decompression */
782 	if (sync) {
783 		unsigned long flags;
784 
785 		spin_lock_irqsave(&io->u.wait.lock, flags);
786 		if (!atomic_add_return(bios, &io->pending_bios))
787 			wake_up_locked(&io->u.wait);
788 		spin_unlock_irqrestore(&io->u.wait.lock, flags);
789 		return;
790 	}
791 
792 	if (atomic_add_return(bios, &io->pending_bios))
793 		return;
794 	/* Use workqueue and sync decompression for atomic contexts only */
795 	if (in_atomic() || irqs_disabled()) {
796 		queue_work(z_erofs_workqueue, &io->u.work);
797 		sbi->opt.readahead_sync_decompress = true;
798 		return;
799 	}
800 	z_erofs_decompressqueue_work(&io->u.work);
801 }
802 
803 static bool z_erofs_page_is_invalidated(struct page *page)
804 {
805 	return !page->mapping && !z_erofs_is_shortlived_page(page);
806 }
807 
808 static void z_erofs_decompressqueue_endio(struct bio *bio)
809 {
810 	tagptr1_t t = tagptr_init(tagptr1_t, bio->bi_private);
811 	struct z_erofs_decompressqueue *q = tagptr_unfold_ptr(t);
812 	blk_status_t err = bio->bi_status;
813 	struct bio_vec *bvec;
814 	struct bvec_iter_all iter_all;
815 
816 	bio_for_each_segment_all(bvec, bio, iter_all) {
817 		struct page *page = bvec->bv_page;
818 
819 		DBG_BUGON(PageUptodate(page));
820 		DBG_BUGON(z_erofs_page_is_invalidated(page));
821 
822 		if (err)
823 			SetPageError(page);
824 
825 		if (erofs_page_is_managed(EROFS_SB(q->sb), page)) {
826 			if (!err)
827 				SetPageUptodate(page);
828 			unlock_page(page);
829 		}
830 	}
831 	z_erofs_decompress_kickoff(q, tagptr_unfold_tags(t), -1);
832 	bio_put(bio);
833 }
834 
835 static int z_erofs_decompress_pcluster(struct super_block *sb,
836 				       struct z_erofs_pcluster *pcl,
837 				       struct page **pagepool)
838 {
839 	struct erofs_sb_info *const sbi = EROFS_SB(sb);
840 	struct z_erofs_pagevec_ctor ctor;
841 	unsigned int i, inputsize, outputsize, llen, nr_pages;
842 	struct page *pages_onstack[Z_EROFS_VMAP_ONSTACK_PAGES];
843 	struct page **pages, **compressed_pages, *page;
844 
845 	enum z_erofs_page_type page_type;
846 	bool overlapped, partial;
847 	struct z_erofs_collection *cl;
848 	int err;
849 
850 	might_sleep();
851 	cl = z_erofs_primarycollection(pcl);
852 	DBG_BUGON(!READ_ONCE(cl->nr_pages));
853 
854 	mutex_lock(&cl->lock);
855 	nr_pages = cl->nr_pages;
856 
857 	if (nr_pages <= Z_EROFS_VMAP_ONSTACK_PAGES) {
858 		pages = pages_onstack;
859 	} else if (nr_pages <= Z_EROFS_VMAP_GLOBAL_PAGES &&
860 		   mutex_trylock(&z_pagemap_global_lock)) {
861 		pages = z_pagemap_global;
862 	} else {
863 		gfp_t gfp_flags = GFP_KERNEL;
864 
865 		if (nr_pages > Z_EROFS_VMAP_GLOBAL_PAGES)
866 			gfp_flags |= __GFP_NOFAIL;
867 
868 		pages = kvmalloc_array(nr_pages, sizeof(struct page *),
869 				       gfp_flags);
870 
871 		/* fallback to global pagemap for the lowmem scenario */
872 		if (!pages) {
873 			mutex_lock(&z_pagemap_global_lock);
874 			pages = z_pagemap_global;
875 		}
876 	}
877 
878 	for (i = 0; i < nr_pages; ++i)
879 		pages[i] = NULL;
880 
881 	err = 0;
882 	z_erofs_pagevec_ctor_init(&ctor, Z_EROFS_NR_INLINE_PAGEVECS,
883 				  cl->pagevec, 0);
884 
885 	for (i = 0; i < cl->vcnt; ++i) {
886 		unsigned int pagenr;
887 
888 		page = z_erofs_pagevec_dequeue(&ctor, &page_type);
889 
890 		/* all pages in pagevec ought to be valid */
891 		DBG_BUGON(!page);
892 		DBG_BUGON(z_erofs_page_is_invalidated(page));
893 
894 		if (z_erofs_put_shortlivedpage(pagepool, page))
895 			continue;
896 
897 		if (page_type == Z_EROFS_VLE_PAGE_TYPE_HEAD)
898 			pagenr = 0;
899 		else
900 			pagenr = z_erofs_onlinepage_index(page);
901 
902 		DBG_BUGON(pagenr >= nr_pages);
903 
904 		/*
905 		 * currently EROFS doesn't support multiref(dedup),
906 		 * so here erroring out one multiref page.
907 		 */
908 		if (pages[pagenr]) {
909 			DBG_BUGON(1);
910 			SetPageError(pages[pagenr]);
911 			z_erofs_onlinepage_endio(pages[pagenr]);
912 			err = -EFSCORRUPTED;
913 		}
914 		pages[pagenr] = page;
915 	}
916 	z_erofs_pagevec_ctor_exit(&ctor, true);
917 
918 	overlapped = false;
919 	compressed_pages = pcl->compressed_pages;
920 
921 	for (i = 0; i < pcl->pclusterpages; ++i) {
922 		unsigned int pagenr;
923 
924 		page = compressed_pages[i];
925 
926 		/* all compressed pages ought to be valid */
927 		DBG_BUGON(!page);
928 		DBG_BUGON(z_erofs_page_is_invalidated(page));
929 
930 		if (!z_erofs_is_shortlived_page(page)) {
931 			if (erofs_page_is_managed(sbi, page)) {
932 				if (!PageUptodate(page))
933 					err = -EIO;
934 				continue;
935 			}
936 
937 			/*
938 			 * only if non-head page can be selected
939 			 * for inplace decompression
940 			 */
941 			pagenr = z_erofs_onlinepage_index(page);
942 
943 			DBG_BUGON(pagenr >= nr_pages);
944 			if (pages[pagenr]) {
945 				DBG_BUGON(1);
946 				SetPageError(pages[pagenr]);
947 				z_erofs_onlinepage_endio(pages[pagenr]);
948 				err = -EFSCORRUPTED;
949 			}
950 			pages[pagenr] = page;
951 
952 			overlapped = true;
953 		}
954 
955 		/* PG_error needs checking for all non-managed pages */
956 		if (PageError(page)) {
957 			DBG_BUGON(PageUptodate(page));
958 			err = -EIO;
959 		}
960 	}
961 
962 	if (err)
963 		goto out;
964 
965 	llen = pcl->length >> Z_EROFS_PCLUSTER_LENGTH_BIT;
966 	if (nr_pages << PAGE_SHIFT >= cl->pageofs + llen) {
967 		outputsize = llen;
968 		partial = !(pcl->length & Z_EROFS_PCLUSTER_FULL_LENGTH);
969 	} else {
970 		outputsize = (nr_pages << PAGE_SHIFT) - cl->pageofs;
971 		partial = true;
972 	}
973 
974 	inputsize = pcl->pclusterpages * PAGE_SIZE;
975 	err = z_erofs_decompress(&(struct z_erofs_decompress_req) {
976 					.sb = sb,
977 					.in = compressed_pages,
978 					.out = pages,
979 					.pageofs_out = cl->pageofs,
980 					.inputsize = inputsize,
981 					.outputsize = outputsize,
982 					.alg = pcl->algorithmformat,
983 					.inplace_io = overlapped,
984 					.partial_decoding = partial
985 				 }, pagepool);
986 
987 out:
988 	/* must handle all compressed pages before ending pages */
989 	for (i = 0; i < pcl->pclusterpages; ++i) {
990 		page = compressed_pages[i];
991 
992 		if (erofs_page_is_managed(sbi, page))
993 			continue;
994 
995 		/* recycle all individual short-lived pages */
996 		(void)z_erofs_put_shortlivedpage(pagepool, page);
997 
998 		WRITE_ONCE(compressed_pages[i], NULL);
999 	}
1000 
1001 	for (i = 0; i < nr_pages; ++i) {
1002 		page = pages[i];
1003 		if (!page)
1004 			continue;
1005 
1006 		DBG_BUGON(z_erofs_page_is_invalidated(page));
1007 
1008 		/* recycle all individual short-lived pages */
1009 		if (z_erofs_put_shortlivedpage(pagepool, page))
1010 			continue;
1011 
1012 		if (err < 0)
1013 			SetPageError(page);
1014 
1015 		z_erofs_onlinepage_endio(page);
1016 	}
1017 
1018 	if (pages == z_pagemap_global)
1019 		mutex_unlock(&z_pagemap_global_lock);
1020 	else if (pages != pages_onstack)
1021 		kvfree(pages);
1022 
1023 	cl->nr_pages = 0;
1024 	cl->vcnt = 0;
1025 
1026 	/* all cl locks MUST be taken before the following line */
1027 	WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_NIL);
1028 
1029 	/* all cl locks SHOULD be released right now */
1030 	mutex_unlock(&cl->lock);
1031 
1032 	z_erofs_collection_put(cl);
1033 	return err;
1034 }
1035 
1036 static void z_erofs_decompress_queue(const struct z_erofs_decompressqueue *io,
1037 				     struct page **pagepool)
1038 {
1039 	z_erofs_next_pcluster_t owned = io->head;
1040 
1041 	while (owned != Z_EROFS_PCLUSTER_TAIL_CLOSED) {
1042 		struct z_erofs_pcluster *pcl;
1043 
1044 		/* no possible that 'owned' equals Z_EROFS_WORK_TPTR_TAIL */
1045 		DBG_BUGON(owned == Z_EROFS_PCLUSTER_TAIL);
1046 
1047 		/* no possible that 'owned' equals NULL */
1048 		DBG_BUGON(owned == Z_EROFS_PCLUSTER_NIL);
1049 
1050 		pcl = container_of(owned, struct z_erofs_pcluster, next);
1051 		owned = READ_ONCE(pcl->next);
1052 
1053 		z_erofs_decompress_pcluster(io->sb, pcl, pagepool);
1054 	}
1055 }
1056 
1057 static void z_erofs_decompressqueue_work(struct work_struct *work)
1058 {
1059 	struct z_erofs_decompressqueue *bgq =
1060 		container_of(work, struct z_erofs_decompressqueue, u.work);
1061 	struct page *pagepool = NULL;
1062 
1063 	DBG_BUGON(bgq->head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1064 	z_erofs_decompress_queue(bgq, &pagepool);
1065 
1066 	erofs_release_pages(&pagepool);
1067 	kvfree(bgq);
1068 }
1069 
1070 static struct page *pickup_page_for_submission(struct z_erofs_pcluster *pcl,
1071 					       unsigned int nr,
1072 					       struct page **pagepool,
1073 					       struct address_space *mc,
1074 					       gfp_t gfp)
1075 {
1076 	const pgoff_t index = pcl->obj.index;
1077 	bool tocache = false;
1078 
1079 	struct address_space *mapping;
1080 	struct page *oldpage, *page;
1081 
1082 	compressed_page_t t;
1083 	int justfound;
1084 
1085 repeat:
1086 	page = READ_ONCE(pcl->compressed_pages[nr]);
1087 	oldpage = page;
1088 
1089 	if (!page)
1090 		goto out_allocpage;
1091 
1092 	/*
1093 	 * the cached page has not been allocated and
1094 	 * an placeholder is out there, prepare it now.
1095 	 */
1096 	if (page == PAGE_UNALLOCATED) {
1097 		tocache = true;
1098 		goto out_allocpage;
1099 	}
1100 
1101 	/* process the target tagged pointer */
1102 	t = tagptr_init(compressed_page_t, page);
1103 	justfound = tagptr_unfold_tags(t);
1104 	page = tagptr_unfold_ptr(t);
1105 
1106 	/*
1107 	 * preallocated cached pages, which is used to avoid direct reclaim
1108 	 * otherwise, it will go inplace I/O path instead.
1109 	 */
1110 	if (page->private == Z_EROFS_PREALLOCATED_PAGE) {
1111 		WRITE_ONCE(pcl->compressed_pages[nr], page);
1112 		set_page_private(page, 0);
1113 		tocache = true;
1114 		goto out_tocache;
1115 	}
1116 	mapping = READ_ONCE(page->mapping);
1117 
1118 	/*
1119 	 * file-backed online pages in plcuster are all locked steady,
1120 	 * therefore it is impossible for `mapping' to be NULL.
1121 	 */
1122 	if (mapping && mapping != mc)
1123 		/* ought to be unmanaged pages */
1124 		goto out;
1125 
1126 	/* directly return for shortlived page as well */
1127 	if (z_erofs_is_shortlived_page(page))
1128 		goto out;
1129 
1130 	lock_page(page);
1131 
1132 	/* only true if page reclaim goes wrong, should never happen */
1133 	DBG_BUGON(justfound && PagePrivate(page));
1134 
1135 	/* the page is still in manage cache */
1136 	if (page->mapping == mc) {
1137 		WRITE_ONCE(pcl->compressed_pages[nr], page);
1138 
1139 		ClearPageError(page);
1140 		if (!PagePrivate(page)) {
1141 			/*
1142 			 * impossible to be !PagePrivate(page) for
1143 			 * the current restriction as well if
1144 			 * the page is already in compressed_pages[].
1145 			 */
1146 			DBG_BUGON(!justfound);
1147 
1148 			justfound = 0;
1149 			set_page_private(page, (unsigned long)pcl);
1150 			SetPagePrivate(page);
1151 		}
1152 
1153 		/* no need to submit io if it is already up-to-date */
1154 		if (PageUptodate(page)) {
1155 			unlock_page(page);
1156 			page = NULL;
1157 		}
1158 		goto out;
1159 	}
1160 
1161 	/*
1162 	 * the managed page has been truncated, it's unsafe to
1163 	 * reuse this one, let's allocate a new cache-managed page.
1164 	 */
1165 	DBG_BUGON(page->mapping);
1166 	DBG_BUGON(!justfound);
1167 
1168 	tocache = true;
1169 	unlock_page(page);
1170 	put_page(page);
1171 out_allocpage:
1172 	page = erofs_allocpage(pagepool, gfp | __GFP_NOFAIL);
1173 	if (oldpage != cmpxchg(&pcl->compressed_pages[nr], oldpage, page)) {
1174 		erofs_pagepool_add(pagepool, page);
1175 		cond_resched();
1176 		goto repeat;
1177 	}
1178 out_tocache:
1179 	if (!tocache || add_to_page_cache_lru(page, mc, index + nr, gfp)) {
1180 		/* turn into temporary page if fails (1 ref) */
1181 		set_page_private(page, Z_EROFS_SHORTLIVED_PAGE);
1182 		goto out;
1183 	}
1184 	attach_page_private(page, pcl);
1185 	/* drop a refcount added by allocpage (then we have 2 refs here) */
1186 	put_page(page);
1187 
1188 out:	/* the only exit (for tracing and debugging) */
1189 	return page;
1190 }
1191 
1192 static struct z_erofs_decompressqueue *
1193 jobqueue_init(struct super_block *sb,
1194 	      struct z_erofs_decompressqueue *fgq, bool *fg)
1195 {
1196 	struct z_erofs_decompressqueue *q;
1197 
1198 	if (fg && !*fg) {
1199 		q = kvzalloc(sizeof(*q), GFP_KERNEL | __GFP_NOWARN);
1200 		if (!q) {
1201 			*fg = true;
1202 			goto fg_out;
1203 		}
1204 		INIT_WORK(&q->u.work, z_erofs_decompressqueue_work);
1205 	} else {
1206 fg_out:
1207 		q = fgq;
1208 		init_waitqueue_head(&fgq->u.wait);
1209 		atomic_set(&fgq->pending_bios, 0);
1210 	}
1211 	q->sb = sb;
1212 	q->head = Z_EROFS_PCLUSTER_TAIL_CLOSED;
1213 	return q;
1214 }
1215 
1216 /* define decompression jobqueue types */
1217 enum {
1218 	JQ_BYPASS,
1219 	JQ_SUBMIT,
1220 	NR_JOBQUEUES,
1221 };
1222 
1223 static void *jobqueueset_init(struct super_block *sb,
1224 			      struct z_erofs_decompressqueue *q[],
1225 			      struct z_erofs_decompressqueue *fgq, bool *fg)
1226 {
1227 	/*
1228 	 * if managed cache is enabled, bypass jobqueue is needed,
1229 	 * no need to read from device for all pclusters in this queue.
1230 	 */
1231 	q[JQ_BYPASS] = jobqueue_init(sb, fgq + JQ_BYPASS, NULL);
1232 	q[JQ_SUBMIT] = jobqueue_init(sb, fgq + JQ_SUBMIT, fg);
1233 
1234 	return tagptr_cast_ptr(tagptr_fold(tagptr1_t, q[JQ_SUBMIT], *fg));
1235 }
1236 
1237 static void move_to_bypass_jobqueue(struct z_erofs_pcluster *pcl,
1238 				    z_erofs_next_pcluster_t qtail[],
1239 				    z_erofs_next_pcluster_t owned_head)
1240 {
1241 	z_erofs_next_pcluster_t *const submit_qtail = qtail[JQ_SUBMIT];
1242 	z_erofs_next_pcluster_t *const bypass_qtail = qtail[JQ_BYPASS];
1243 
1244 	DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1245 	if (owned_head == Z_EROFS_PCLUSTER_TAIL)
1246 		owned_head = Z_EROFS_PCLUSTER_TAIL_CLOSED;
1247 
1248 	WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_TAIL_CLOSED);
1249 
1250 	WRITE_ONCE(*submit_qtail, owned_head);
1251 	WRITE_ONCE(*bypass_qtail, &pcl->next);
1252 
1253 	qtail[JQ_BYPASS] = &pcl->next;
1254 }
1255 
1256 static void z_erofs_submit_queue(struct super_block *sb,
1257 				 struct z_erofs_decompress_frontend *f,
1258 				 struct page **pagepool,
1259 				 struct z_erofs_decompressqueue *fgq,
1260 				 bool *force_fg)
1261 {
1262 	struct erofs_sb_info *const sbi = EROFS_SB(sb);
1263 	z_erofs_next_pcluster_t qtail[NR_JOBQUEUES];
1264 	struct z_erofs_decompressqueue *q[NR_JOBQUEUES];
1265 	void *bi_private;
1266 	z_erofs_next_pcluster_t owned_head = f->clt.owned_head;
1267 	/* bio is NULL initially, so no need to initialize last_{index,bdev} */
1268 	pgoff_t last_index;
1269 	struct block_device *last_bdev;
1270 	unsigned int nr_bios = 0;
1271 	struct bio *bio = NULL;
1272 
1273 	bi_private = jobqueueset_init(sb, q, fgq, force_fg);
1274 	qtail[JQ_BYPASS] = &q[JQ_BYPASS]->head;
1275 	qtail[JQ_SUBMIT] = &q[JQ_SUBMIT]->head;
1276 
1277 	/* by default, all need io submission */
1278 	q[JQ_SUBMIT]->head = owned_head;
1279 
1280 	do {
1281 		struct erofs_map_dev mdev;
1282 		struct z_erofs_pcluster *pcl;
1283 		pgoff_t cur, end;
1284 		unsigned int i = 0;
1285 		bool bypass = true;
1286 
1287 		/* no possible 'owned_head' equals the following */
1288 		DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1289 		DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_NIL);
1290 
1291 		pcl = container_of(owned_head, struct z_erofs_pcluster, next);
1292 
1293 		/* no device id here, thus it will always succeed */
1294 		mdev = (struct erofs_map_dev) {
1295 			.m_pa = blknr_to_addr(pcl->obj.index),
1296 		};
1297 		(void)erofs_map_dev(sb, &mdev);
1298 
1299 		cur = erofs_blknr(mdev.m_pa);
1300 		end = cur + pcl->pclusterpages;
1301 
1302 		/* close the main owned chain at first */
1303 		owned_head = cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_TAIL,
1304 				     Z_EROFS_PCLUSTER_TAIL_CLOSED);
1305 
1306 		do {
1307 			struct page *page;
1308 
1309 			page = pickup_page_for_submission(pcl, i++, pagepool,
1310 							  MNGD_MAPPING(sbi),
1311 							  GFP_NOFS);
1312 			if (!page)
1313 				continue;
1314 
1315 			if (bio && (cur != last_index + 1 ||
1316 				    last_bdev != mdev.m_bdev)) {
1317 submit_bio_retry:
1318 				submit_bio(bio);
1319 				bio = NULL;
1320 			}
1321 
1322 			if (!bio) {
1323 				bio = bio_alloc(GFP_NOIO, BIO_MAX_VECS);
1324 				bio->bi_end_io = z_erofs_decompressqueue_endio;
1325 
1326 				bio_set_dev(bio, mdev.m_bdev);
1327 				last_bdev = mdev.m_bdev;
1328 				bio->bi_iter.bi_sector = (sector_t)cur <<
1329 					LOG_SECTORS_PER_BLOCK;
1330 				bio->bi_private = bi_private;
1331 				bio->bi_opf = REQ_OP_READ;
1332 				if (f->readahead)
1333 					bio->bi_opf |= REQ_RAHEAD;
1334 				++nr_bios;
1335 			}
1336 
1337 			if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE)
1338 				goto submit_bio_retry;
1339 
1340 			last_index = cur;
1341 			bypass = false;
1342 		} while (++cur < end);
1343 
1344 		if (!bypass)
1345 			qtail[JQ_SUBMIT] = &pcl->next;
1346 		else
1347 			move_to_bypass_jobqueue(pcl, qtail, owned_head);
1348 	} while (owned_head != Z_EROFS_PCLUSTER_TAIL);
1349 
1350 	if (bio)
1351 		submit_bio(bio);
1352 
1353 	/*
1354 	 * although background is preferred, no one is pending for submission.
1355 	 * don't issue workqueue for decompression but drop it directly instead.
1356 	 */
1357 	if (!*force_fg && !nr_bios) {
1358 		kvfree(q[JQ_SUBMIT]);
1359 		return;
1360 	}
1361 	z_erofs_decompress_kickoff(q[JQ_SUBMIT], *force_fg, nr_bios);
1362 }
1363 
1364 static void z_erofs_runqueue(struct super_block *sb,
1365 			     struct z_erofs_decompress_frontend *f,
1366 			     struct page **pagepool, bool force_fg)
1367 {
1368 	struct z_erofs_decompressqueue io[NR_JOBQUEUES];
1369 
1370 	if (f->clt.owned_head == Z_EROFS_PCLUSTER_TAIL)
1371 		return;
1372 	z_erofs_submit_queue(sb, f, pagepool, io, &force_fg);
1373 
1374 	/* handle bypass queue (no i/o pclusters) immediately */
1375 	z_erofs_decompress_queue(&io[JQ_BYPASS], pagepool);
1376 
1377 	if (!force_fg)
1378 		return;
1379 
1380 	/* wait until all bios are completed */
1381 	io_wait_event(io[JQ_SUBMIT].u.wait,
1382 		      !atomic_read(&io[JQ_SUBMIT].pending_bios));
1383 
1384 	/* handle synchronous decompress queue in the caller context */
1385 	z_erofs_decompress_queue(&io[JQ_SUBMIT], pagepool);
1386 }
1387 
1388 /*
1389  * Since partial uptodate is still unimplemented for now, we have to use
1390  * approximate readmore strategies as a start.
1391  */
1392 static void z_erofs_pcluster_readmore(struct z_erofs_decompress_frontend *f,
1393 				      struct readahead_control *rac,
1394 				      erofs_off_t end,
1395 				      struct page **pagepool,
1396 				      bool backmost)
1397 {
1398 	struct inode *inode = f->inode;
1399 	struct erofs_map_blocks *map = &f->map;
1400 	erofs_off_t cur;
1401 	int err;
1402 
1403 	if (backmost) {
1404 		map->m_la = end;
1405 		err = z_erofs_map_blocks_iter(inode, map,
1406 					      EROFS_GET_BLOCKS_READMORE);
1407 		if (err)
1408 			return;
1409 
1410 		/* expend ra for the trailing edge if readahead */
1411 		if (rac) {
1412 			loff_t newstart = readahead_pos(rac);
1413 
1414 			cur = round_up(map->m_la + map->m_llen, PAGE_SIZE);
1415 			readahead_expand(rac, newstart, cur - newstart);
1416 			return;
1417 		}
1418 		end = round_up(end, PAGE_SIZE);
1419 	} else {
1420 		end = round_up(map->m_la, PAGE_SIZE);
1421 
1422 		if (!map->m_llen)
1423 			return;
1424 	}
1425 
1426 	cur = map->m_la + map->m_llen - 1;
1427 	while (cur >= end) {
1428 		pgoff_t index = cur >> PAGE_SHIFT;
1429 		struct page *page;
1430 
1431 		page = erofs_grab_cache_page_nowait(inode->i_mapping, index);
1432 		if (!page)
1433 			goto skip;
1434 
1435 		if (PageUptodate(page)) {
1436 			unlock_page(page);
1437 			put_page(page);
1438 			goto skip;
1439 		}
1440 
1441 		err = z_erofs_do_read_page(f, page, pagepool);
1442 		if (err)
1443 			erofs_err(inode->i_sb,
1444 				  "readmore error at page %lu @ nid %llu",
1445 				  index, EROFS_I(inode)->nid);
1446 		put_page(page);
1447 skip:
1448 		if (cur < PAGE_SIZE)
1449 			break;
1450 		cur = (index << PAGE_SHIFT) - 1;
1451 	}
1452 }
1453 
1454 static int z_erofs_readpage(struct file *file, struct page *page)
1455 {
1456 	struct inode *const inode = page->mapping->host;
1457 	struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1458 	struct page *pagepool = NULL;
1459 	int err;
1460 
1461 	trace_erofs_readpage(page, false);
1462 	f.headoffset = (erofs_off_t)page->index << PAGE_SHIFT;
1463 
1464 	z_erofs_pcluster_readmore(&f, NULL, f.headoffset + PAGE_SIZE - 1,
1465 				  &pagepool, true);
1466 	err = z_erofs_do_read_page(&f, page, &pagepool);
1467 	z_erofs_pcluster_readmore(&f, NULL, 0, &pagepool, false);
1468 
1469 	(void)z_erofs_collector_end(&f.clt);
1470 
1471 	/* if some compressed cluster ready, need submit them anyway */
1472 	z_erofs_runqueue(inode->i_sb, &f, &pagepool, true);
1473 
1474 	if (err)
1475 		erofs_err(inode->i_sb, "failed to read, err [%d]", err);
1476 
1477 	if (f.map.mpage)
1478 		put_page(f.map.mpage);
1479 
1480 	erofs_release_pages(&pagepool);
1481 	return err;
1482 }
1483 
1484 static void z_erofs_readahead(struct readahead_control *rac)
1485 {
1486 	struct inode *const inode = rac->mapping->host;
1487 	struct erofs_sb_info *const sbi = EROFS_I_SB(inode);
1488 	struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1489 	struct page *pagepool = NULL, *head = NULL, *page;
1490 	unsigned int nr_pages;
1491 
1492 	f.readahead = true;
1493 	f.headoffset = readahead_pos(rac);
1494 
1495 	z_erofs_pcluster_readmore(&f, rac, f.headoffset +
1496 				  readahead_length(rac) - 1, &pagepool, true);
1497 	nr_pages = readahead_count(rac);
1498 	trace_erofs_readpages(inode, readahead_index(rac), nr_pages, false);
1499 
1500 	while ((page = readahead_page(rac))) {
1501 		set_page_private(page, (unsigned long)head);
1502 		head = page;
1503 	}
1504 
1505 	while (head) {
1506 		struct page *page = head;
1507 		int err;
1508 
1509 		/* traversal in reverse order */
1510 		head = (void *)page_private(page);
1511 
1512 		err = z_erofs_do_read_page(&f, page, &pagepool);
1513 		if (err)
1514 			erofs_err(inode->i_sb,
1515 				  "readahead error at page %lu @ nid %llu",
1516 				  page->index, EROFS_I(inode)->nid);
1517 		put_page(page);
1518 	}
1519 	z_erofs_pcluster_readmore(&f, rac, 0, &pagepool, false);
1520 	(void)z_erofs_collector_end(&f.clt);
1521 
1522 	z_erofs_runqueue(inode->i_sb, &f, &pagepool,
1523 			 sbi->opt.readahead_sync_decompress &&
1524 			 nr_pages <= sbi->opt.max_sync_decompress_pages);
1525 	if (f.map.mpage)
1526 		put_page(f.map.mpage);
1527 	erofs_release_pages(&pagepool);
1528 }
1529 
1530 const struct address_space_operations z_erofs_aops = {
1531 	.readpage = z_erofs_readpage,
1532 	.readahead = z_erofs_readahead,
1533 };
1534