xref: /openbmc/linux/fs/erofs/zdata.c (revision 40452ffc)
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 /* how to allocate cached pages for a pcluster */
100 enum z_erofs_cache_alloctype {
101 	DONTALLOC,	/* don't allocate any cached pages */
102 	/*
103 	 * try to use cached I/O if page allocation succeeds or fallback
104 	 * to in-place I/O instead to avoid any direct reclaim.
105 	 */
106 	TRYALLOC,
107 };
108 
109 /*
110  * tagged pointer with 1-bit tag for all compressed pages
111  * tag 0 - the page is just found with an extra page reference
112  */
113 typedef tagptr1_t compressed_page_t;
114 
115 #define tag_compressed_page_justfound(page) \
116 	tagptr_fold(compressed_page_t, page, 1)
117 
118 static struct workqueue_struct *z_erofs_workqueue __read_mostly;
119 
120 void z_erofs_exit_zip_subsystem(void)
121 {
122 	destroy_workqueue(z_erofs_workqueue);
123 	z_erofs_destroy_pcluster_pool();
124 }
125 
126 static inline int z_erofs_init_workqueue(void)
127 {
128 	const unsigned int onlinecpus = num_possible_cpus();
129 
130 	/*
131 	 * no need to spawn too many threads, limiting threads could minimum
132 	 * scheduling overhead, perhaps per-CPU threads should be better?
133 	 */
134 	z_erofs_workqueue = alloc_workqueue("erofs_unzipd",
135 					    WQ_UNBOUND | WQ_HIGHPRI,
136 					    onlinecpus + onlinecpus / 4);
137 	return z_erofs_workqueue ? 0 : -ENOMEM;
138 }
139 
140 int __init z_erofs_init_zip_subsystem(void)
141 {
142 	int err = z_erofs_create_pcluster_pool();
143 
144 	if (err)
145 		return err;
146 	err = z_erofs_init_workqueue();
147 	if (err)
148 		z_erofs_destroy_pcluster_pool();
149 	return err;
150 }
151 
152 enum z_erofs_collectmode {
153 	COLLECT_SECONDARY,
154 	COLLECT_PRIMARY,
155 	/*
156 	 * The current collection was the tail of an exist chain, in addition
157 	 * that the previous processed chained collections are all decided to
158 	 * be hooked up to it.
159 	 * A new chain will be created for the remaining collections which are
160 	 * not processed yet, therefore different from COLLECT_PRIMARY_FOLLOWED,
161 	 * the next collection cannot reuse the whole page safely in
162 	 * the following scenario:
163 	 *  ________________________________________________________________
164 	 * |      tail (partial) page     |       head (partial) page       |
165 	 * |   (belongs to the next cl)   |   (belongs to the current cl)   |
166 	 * |_______PRIMARY_FOLLOWED_______|________PRIMARY_HOOKED___________|
167 	 */
168 	COLLECT_PRIMARY_HOOKED,
169 	/*
170 	 * a weak form of COLLECT_PRIMARY_FOLLOWED, the difference is that it
171 	 * could be dispatched into bypass queue later due to uptodated managed
172 	 * pages. All related online pages cannot be reused for inplace I/O (or
173 	 * pagevec) since it can be directly decoded without I/O submission.
174 	 */
175 	COLLECT_PRIMARY_FOLLOWED_NOINPLACE,
176 	/*
177 	 * The current collection has been linked with the owned chain, and
178 	 * could also be linked with the remaining collections, which means
179 	 * if the processing page is the tail page of the collection, thus
180 	 * the current collection can safely use the whole page (since
181 	 * the previous collection is under control) for in-place I/O, as
182 	 * illustrated below:
183 	 *  ________________________________________________________________
184 	 * |  tail (partial) page |          head (partial) page           |
185 	 * |  (of the current cl) |      (of the previous collection)      |
186 	 * |  PRIMARY_FOLLOWED or |                                        |
187 	 * |_____PRIMARY_HOOKED___|____________PRIMARY_FOLLOWED____________|
188 	 *
189 	 * [  (*) the above page can be used as inplace I/O.               ]
190 	 */
191 	COLLECT_PRIMARY_FOLLOWED,
192 };
193 
194 struct z_erofs_collector {
195 	struct z_erofs_pagevec_ctor vector;
196 
197 	struct z_erofs_pcluster *pcl, *tailpcl;
198 	struct z_erofs_collection *cl;
199 	/* a pointer used to pick up inplace I/O pages */
200 	struct page **icpage_ptr;
201 	z_erofs_next_pcluster_t owned_head;
202 
203 	enum z_erofs_collectmode mode;
204 };
205 
206 struct z_erofs_decompress_frontend {
207 	struct inode *const inode;
208 
209 	struct z_erofs_collector clt;
210 	struct erofs_map_blocks map;
211 
212 	bool readahead;
213 	/* used for applying cache strategy on the fly */
214 	bool backmost;
215 	erofs_off_t headoffset;
216 };
217 
218 #define COLLECTOR_INIT() { \
219 	.owned_head = Z_EROFS_PCLUSTER_TAIL, \
220 	.mode = COLLECT_PRIMARY_FOLLOWED }
221 
222 #define DECOMPRESS_FRONTEND_INIT(__i) { \
223 	.inode = __i, .clt = COLLECTOR_INIT(), \
224 	.backmost = true, }
225 
226 static struct page *z_pagemap_global[Z_EROFS_VMAP_GLOBAL_PAGES];
227 static DEFINE_MUTEX(z_pagemap_global_lock);
228 
229 static void preload_compressed_pages(struct z_erofs_collector *clt,
230 				     struct address_space *mc,
231 				     enum z_erofs_cache_alloctype type,
232 				     struct page **pagepool)
233 {
234 	struct z_erofs_pcluster *pcl = clt->pcl;
235 	bool standalone = true;
236 	gfp_t gfp = (mapping_gfp_mask(mc) & ~__GFP_DIRECT_RECLAIM) |
237 			__GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN;
238 	struct page **pages;
239 	pgoff_t index;
240 
241 	if (clt->mode < COLLECT_PRIMARY_FOLLOWED)
242 		return;
243 
244 	pages = pcl->compressed_pages;
245 	index = pcl->obj.index;
246 	for (; index < pcl->obj.index + pcl->pclusterpages; ++index, ++pages) {
247 		struct page *page;
248 		compressed_page_t t;
249 		struct page *newpage = NULL;
250 
251 		/* the compressed page was loaded before */
252 		if (READ_ONCE(*pages))
253 			continue;
254 
255 		page = find_get_page(mc, index);
256 
257 		if (page) {
258 			t = tag_compressed_page_justfound(page);
259 		} else {
260 			/* I/O is needed, no possible to decompress directly */
261 			standalone = false;
262 			switch (type) {
263 			case TRYALLOC:
264 				newpage = erofs_allocpage(pagepool, gfp);
265 				if (!newpage)
266 					continue;
267 				set_page_private(newpage,
268 						 Z_EROFS_PREALLOCATED_PAGE);
269 				t = tag_compressed_page_justfound(newpage);
270 				break;
271 			default:        /* DONTALLOC */
272 				continue;
273 			}
274 		}
275 
276 		if (!cmpxchg_relaxed(pages, NULL, tagptr_cast_ptr(t)))
277 			continue;
278 
279 		if (page)
280 			put_page(page);
281 		else if (newpage)
282 			erofs_pagepool_add(pagepool, newpage);
283 	}
284 
285 	/*
286 	 * don't do inplace I/O if all compressed pages are available in
287 	 * managed cache since it can be moved to the bypass queue instead.
288 	 */
289 	if (standalone)
290 		clt->mode = COLLECT_PRIMARY_FOLLOWED_NOINPLACE;
291 }
292 
293 /* called by erofs_shrinker to get rid of all compressed_pages */
294 int erofs_try_to_free_all_cached_pages(struct erofs_sb_info *sbi,
295 				       struct erofs_workgroup *grp)
296 {
297 	struct z_erofs_pcluster *const pcl =
298 		container_of(grp, struct z_erofs_pcluster, obj);
299 	int i;
300 
301 	/*
302 	 * refcount of workgroup is now freezed as 1,
303 	 * therefore no need to worry about available decompression users.
304 	 */
305 	for (i = 0; i < pcl->pclusterpages; ++i) {
306 		struct page *page = pcl->compressed_pages[i];
307 
308 		if (!page)
309 			continue;
310 
311 		/* block other users from reclaiming or migrating the page */
312 		if (!trylock_page(page))
313 			return -EBUSY;
314 
315 		if (!erofs_page_is_managed(sbi, page))
316 			continue;
317 
318 		/* barrier is implied in the following 'unlock_page' */
319 		WRITE_ONCE(pcl->compressed_pages[i], NULL);
320 		detach_page_private(page);
321 		unlock_page(page);
322 	}
323 	return 0;
324 }
325 
326 int erofs_try_to_free_cached_page(struct page *page)
327 {
328 	struct z_erofs_pcluster *const pcl = (void *)page_private(page);
329 	int ret = 0;	/* 0 - busy */
330 
331 	if (erofs_workgroup_try_to_freeze(&pcl->obj, 1)) {
332 		unsigned int i;
333 
334 		for (i = 0; i < pcl->pclusterpages; ++i) {
335 			if (pcl->compressed_pages[i] == page) {
336 				WRITE_ONCE(pcl->compressed_pages[i], NULL);
337 				ret = 1;
338 				break;
339 			}
340 		}
341 		erofs_workgroup_unfreeze(&pcl->obj, 1);
342 
343 		if (ret)
344 			detach_page_private(page);
345 	}
346 	return ret;
347 }
348 
349 /* page_type must be Z_EROFS_PAGE_TYPE_EXCLUSIVE */
350 static bool z_erofs_try_inplace_io(struct z_erofs_collector *clt,
351 				   struct page *page)
352 {
353 	struct z_erofs_pcluster *const pcl = clt->pcl;
354 
355 	while (clt->icpage_ptr > pcl->compressed_pages)
356 		if (!cmpxchg(--clt->icpage_ptr, NULL, page))
357 			return true;
358 	return false;
359 }
360 
361 /* callers must be with collection lock held */
362 static int z_erofs_attach_page(struct z_erofs_collector *clt,
363 			       struct page *page, enum z_erofs_page_type type,
364 			       bool pvec_safereuse)
365 {
366 	int ret;
367 
368 	/* give priority for inplaceio */
369 	if (clt->mode >= COLLECT_PRIMARY &&
370 	    type == Z_EROFS_PAGE_TYPE_EXCLUSIVE &&
371 	    z_erofs_try_inplace_io(clt, page))
372 		return 0;
373 
374 	ret = z_erofs_pagevec_enqueue(&clt->vector, page, type,
375 				      pvec_safereuse);
376 	clt->cl->vcnt += (unsigned int)ret;
377 	return ret ? 0 : -EAGAIN;
378 }
379 
380 static void z_erofs_try_to_claim_pcluster(struct z_erofs_collector *clt)
381 {
382 	struct z_erofs_pcluster *pcl = clt->pcl;
383 	z_erofs_next_pcluster_t *owned_head = &clt->owned_head;
384 
385 	/* type 1, nil pcluster (this pcluster doesn't belong to any chain.) */
386 	if (cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_NIL,
387 		    *owned_head) == Z_EROFS_PCLUSTER_NIL) {
388 		*owned_head = &pcl->next;
389 		/* so we can attach this pcluster to our submission chain. */
390 		clt->mode = COLLECT_PRIMARY_FOLLOWED;
391 		return;
392 	}
393 
394 	/*
395 	 * type 2, link to the end of an existing open chain, be careful
396 	 * that its submission is controlled by the original attached chain.
397 	 */
398 	if (cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_TAIL,
399 		    *owned_head) == Z_EROFS_PCLUSTER_TAIL) {
400 		*owned_head = Z_EROFS_PCLUSTER_TAIL;
401 		clt->mode = COLLECT_PRIMARY_HOOKED;
402 		clt->tailpcl = NULL;
403 		return;
404 	}
405 	/* type 3, it belongs to a chain, but it isn't the end of the chain */
406 	clt->mode = COLLECT_PRIMARY;
407 }
408 
409 static int z_erofs_lookup_collection(struct z_erofs_collector *clt,
410 				     struct inode *inode,
411 				     struct erofs_map_blocks *map)
412 {
413 	struct z_erofs_pcluster *pcl = clt->pcl;
414 	struct z_erofs_collection *cl;
415 	unsigned int length;
416 
417 	/* to avoid unexpected loop formed by corrupted images */
418 	if (clt->owned_head == &pcl->next || pcl == clt->tailpcl) {
419 		DBG_BUGON(1);
420 		return -EFSCORRUPTED;
421 	}
422 
423 	cl = z_erofs_primarycollection(pcl);
424 	if (cl->pageofs != (map->m_la & ~PAGE_MASK)) {
425 		DBG_BUGON(1);
426 		return -EFSCORRUPTED;
427 	}
428 
429 	length = READ_ONCE(pcl->length);
430 	if (length & Z_EROFS_PCLUSTER_FULL_LENGTH) {
431 		if ((map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT) > length) {
432 			DBG_BUGON(1);
433 			return -EFSCORRUPTED;
434 		}
435 	} else {
436 		unsigned int llen = map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT;
437 
438 		if (map->m_flags & EROFS_MAP_FULL_MAPPED)
439 			llen |= Z_EROFS_PCLUSTER_FULL_LENGTH;
440 
441 		while (llen > length &&
442 		       length != cmpxchg_relaxed(&pcl->length, length, llen)) {
443 			cpu_relax();
444 			length = READ_ONCE(pcl->length);
445 		}
446 	}
447 	mutex_lock(&cl->lock);
448 	/* used to check tail merging loop due to corrupted images */
449 	if (clt->owned_head == Z_EROFS_PCLUSTER_TAIL)
450 		clt->tailpcl = pcl;
451 
452 	z_erofs_try_to_claim_pcluster(clt);
453 	clt->cl = cl;
454 	return 0;
455 }
456 
457 static int z_erofs_register_collection(struct z_erofs_collector *clt,
458 				       struct inode *inode,
459 				       struct erofs_map_blocks *map)
460 {
461 	struct z_erofs_pcluster *pcl;
462 	struct z_erofs_collection *cl;
463 	struct erofs_workgroup *grp;
464 	int err;
465 
466 	if (!(map->m_flags & EROFS_MAP_ENCODED)) {
467 		DBG_BUGON(1);
468 		return -EFSCORRUPTED;
469 	}
470 
471 	/* no available pcluster, let's allocate one */
472 	pcl = z_erofs_alloc_pcluster(map->m_plen >> PAGE_SHIFT);
473 	if (IS_ERR(pcl))
474 		return PTR_ERR(pcl);
475 
476 	atomic_set(&pcl->obj.refcount, 1);
477 	pcl->obj.index = map->m_pa >> PAGE_SHIFT;
478 	pcl->algorithmformat = map->m_algorithmformat;
479 	pcl->length = (map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT) |
480 		(map->m_flags & EROFS_MAP_FULL_MAPPED ?
481 			Z_EROFS_PCLUSTER_FULL_LENGTH : 0);
482 
483 	/* new pclusters should be claimed as type 1, primary and followed */
484 	pcl->next = clt->owned_head;
485 	clt->mode = COLLECT_PRIMARY_FOLLOWED;
486 
487 	cl = z_erofs_primarycollection(pcl);
488 	cl->pageofs = map->m_la & ~PAGE_MASK;
489 
490 	/*
491 	 * lock all primary followed works before visible to others
492 	 * and mutex_trylock *never* fails for a new pcluster.
493 	 */
494 	mutex_init(&cl->lock);
495 	DBG_BUGON(!mutex_trylock(&cl->lock));
496 
497 	grp = erofs_insert_workgroup(inode->i_sb, &pcl->obj);
498 	if (IS_ERR(grp)) {
499 		err = PTR_ERR(grp);
500 		goto err_out;
501 	}
502 
503 	if (grp != &pcl->obj) {
504 		clt->pcl = container_of(grp, struct z_erofs_pcluster, obj);
505 		err = -EEXIST;
506 		goto err_out;
507 	}
508 	/* used to check tail merging loop due to corrupted images */
509 	if (clt->owned_head == Z_EROFS_PCLUSTER_TAIL)
510 		clt->tailpcl = pcl;
511 	clt->owned_head = &pcl->next;
512 	clt->pcl = pcl;
513 	clt->cl = cl;
514 	return 0;
515 
516 err_out:
517 	mutex_unlock(&cl->lock);
518 	z_erofs_free_pcluster(pcl);
519 	return err;
520 }
521 
522 static int z_erofs_collector_begin(struct z_erofs_collector *clt,
523 				   struct inode *inode,
524 				   struct erofs_map_blocks *map)
525 {
526 	struct erofs_workgroup *grp;
527 	int ret;
528 
529 	DBG_BUGON(clt->cl);
530 
531 	/* must be Z_EROFS_PCLUSTER_TAIL or pointed to previous collection */
532 	DBG_BUGON(clt->owned_head == Z_EROFS_PCLUSTER_NIL);
533 	DBG_BUGON(clt->owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
534 
535 	if (!PAGE_ALIGNED(map->m_pa)) {
536 		DBG_BUGON(1);
537 		return -EINVAL;
538 	}
539 
540 	grp = erofs_find_workgroup(inode->i_sb, map->m_pa >> PAGE_SHIFT);
541 	if (grp) {
542 		clt->pcl = container_of(grp, struct z_erofs_pcluster, obj);
543 	} else {
544 		ret = z_erofs_register_collection(clt, inode, map);
545 
546 		if (!ret)
547 			goto out;
548 		if (ret != -EEXIST)
549 			return ret;
550 	}
551 
552 	ret = z_erofs_lookup_collection(clt, inode, map);
553 	if (ret) {
554 		erofs_workgroup_put(&clt->pcl->obj);
555 		return ret;
556 	}
557 
558 out:
559 	z_erofs_pagevec_ctor_init(&clt->vector, Z_EROFS_NR_INLINE_PAGEVECS,
560 				  clt->cl->pagevec, clt->cl->vcnt);
561 
562 	/* since file-backed online pages are traversed in reverse order */
563 	clt->icpage_ptr = clt->pcl->compressed_pages + clt->pcl->pclusterpages;
564 	return 0;
565 }
566 
567 /*
568  * keep in mind that no referenced pclusters will be freed
569  * only after a RCU grace period.
570  */
571 static void z_erofs_rcu_callback(struct rcu_head *head)
572 {
573 	struct z_erofs_collection *const cl =
574 		container_of(head, struct z_erofs_collection, rcu);
575 
576 	z_erofs_free_pcluster(container_of(cl, struct z_erofs_pcluster,
577 					   primary_collection));
578 }
579 
580 void erofs_workgroup_free_rcu(struct erofs_workgroup *grp)
581 {
582 	struct z_erofs_pcluster *const pcl =
583 		container_of(grp, struct z_erofs_pcluster, obj);
584 	struct z_erofs_collection *const cl = z_erofs_primarycollection(pcl);
585 
586 	call_rcu(&cl->rcu, z_erofs_rcu_callback);
587 }
588 
589 static void z_erofs_collection_put(struct z_erofs_collection *cl)
590 {
591 	struct z_erofs_pcluster *const pcl =
592 		container_of(cl, struct z_erofs_pcluster, primary_collection);
593 
594 	erofs_workgroup_put(&pcl->obj);
595 }
596 
597 static bool z_erofs_collector_end(struct z_erofs_collector *clt)
598 {
599 	struct z_erofs_collection *cl = clt->cl;
600 
601 	if (!cl)
602 		return false;
603 
604 	z_erofs_pagevec_ctor_exit(&clt->vector, false);
605 	mutex_unlock(&cl->lock);
606 
607 	/*
608 	 * if all pending pages are added, don't hold its reference
609 	 * any longer if the pcluster isn't hosted by ourselves.
610 	 */
611 	if (clt->mode < COLLECT_PRIMARY_FOLLOWED_NOINPLACE)
612 		z_erofs_collection_put(cl);
613 
614 	clt->cl = NULL;
615 	return true;
616 }
617 
618 static bool should_alloc_managed_pages(struct z_erofs_decompress_frontend *fe,
619 				       unsigned int cachestrategy,
620 				       erofs_off_t la)
621 {
622 	if (cachestrategy <= EROFS_ZIP_CACHE_DISABLED)
623 		return false;
624 
625 	if (fe->backmost)
626 		return true;
627 
628 	return cachestrategy >= EROFS_ZIP_CACHE_READAROUND &&
629 		la < fe->headoffset;
630 }
631 
632 static int z_erofs_do_read_page(struct z_erofs_decompress_frontend *fe,
633 				struct page *page, struct page **pagepool)
634 {
635 	struct inode *const inode = fe->inode;
636 	struct erofs_sb_info *const sbi = EROFS_I_SB(inode);
637 	struct erofs_map_blocks *const map = &fe->map;
638 	struct z_erofs_collector *const clt = &fe->clt;
639 	const loff_t offset = page_offset(page);
640 	bool tight = true;
641 
642 	enum z_erofs_cache_alloctype cache_strategy;
643 	enum z_erofs_page_type page_type;
644 	unsigned int cur, end, spiltted, index;
645 	int err = 0;
646 
647 	/* register locked file pages as online pages in pack */
648 	z_erofs_onlinepage_init(page);
649 
650 	spiltted = 0;
651 	end = PAGE_SIZE;
652 repeat:
653 	cur = end - 1;
654 
655 	/* lucky, within the range of the current map_blocks */
656 	if (offset + cur >= map->m_la &&
657 	    offset + cur < map->m_la + map->m_llen) {
658 		/* didn't get a valid collection previously (very rare) */
659 		if (!clt->cl)
660 			goto restart_now;
661 		goto hitted;
662 	}
663 
664 	/* go ahead the next map_blocks */
665 	erofs_dbg("%s: [out-of-range] pos %llu", __func__, offset + cur);
666 
667 	if (z_erofs_collector_end(clt))
668 		fe->backmost = false;
669 
670 	map->m_la = offset + cur;
671 	map->m_llen = 0;
672 	err = z_erofs_map_blocks_iter(inode, map, 0);
673 	if (err)
674 		goto err_out;
675 
676 restart_now:
677 	if (!(map->m_flags & EROFS_MAP_MAPPED))
678 		goto hitted;
679 
680 	err = z_erofs_collector_begin(clt, inode, map);
681 	if (err)
682 		goto err_out;
683 
684 	/* preload all compressed pages (maybe downgrade role if necessary) */
685 	if (should_alloc_managed_pages(fe, sbi->opt.cache_strategy, map->m_la))
686 		cache_strategy = TRYALLOC;
687 	else
688 		cache_strategy = DONTALLOC;
689 
690 	preload_compressed_pages(clt, MNGD_MAPPING(sbi),
691 				 cache_strategy, pagepool);
692 
693 hitted:
694 	/*
695 	 * Ensure the current partial page belongs to this submit chain rather
696 	 * than other concurrent submit chains or the noio(bypass) chain since
697 	 * those chains are handled asynchronously thus the page cannot be used
698 	 * for inplace I/O or pagevec (should be processed in strict order.)
699 	 */
700 	tight &= (clt->mode >= COLLECT_PRIMARY_HOOKED &&
701 		  clt->mode != COLLECT_PRIMARY_FOLLOWED_NOINPLACE);
702 
703 	cur = end - min_t(unsigned int, offset + end - map->m_la, end);
704 	if (!(map->m_flags & EROFS_MAP_MAPPED)) {
705 		zero_user_segment(page, cur, end);
706 		goto next_part;
707 	}
708 
709 	/* let's derive page type */
710 	page_type = cur ? Z_EROFS_VLE_PAGE_TYPE_HEAD :
711 		(!spiltted ? Z_EROFS_PAGE_TYPE_EXCLUSIVE :
712 			(tight ? Z_EROFS_PAGE_TYPE_EXCLUSIVE :
713 				Z_EROFS_VLE_PAGE_TYPE_TAIL_SHARED));
714 
715 	if (cur)
716 		tight &= (clt->mode >= COLLECT_PRIMARY_FOLLOWED);
717 
718 retry:
719 	err = z_erofs_attach_page(clt, page, page_type,
720 				  clt->mode >= COLLECT_PRIMARY_FOLLOWED);
721 	/* should allocate an additional short-lived page for pagevec */
722 	if (err == -EAGAIN) {
723 		struct page *const newpage =
724 				alloc_page(GFP_NOFS | __GFP_NOFAIL);
725 
726 		set_page_private(newpage, Z_EROFS_SHORTLIVED_PAGE);
727 		err = z_erofs_attach_page(clt, newpage,
728 					  Z_EROFS_PAGE_TYPE_EXCLUSIVE, true);
729 		if (!err)
730 			goto retry;
731 	}
732 
733 	if (err)
734 		goto err_out;
735 
736 	index = page->index - (map->m_la >> PAGE_SHIFT);
737 
738 	z_erofs_onlinepage_fixup(page, index, true);
739 
740 	/* bump up the number of spiltted parts of a page */
741 	++spiltted;
742 	/* also update nr_pages */
743 	clt->cl->nr_pages = max_t(pgoff_t, clt->cl->nr_pages, index + 1);
744 next_part:
745 	/* can be used for verification */
746 	map->m_llen = offset + cur - map->m_la;
747 
748 	end = cur;
749 	if (end > 0)
750 		goto repeat;
751 
752 out:
753 	z_erofs_onlinepage_endio(page);
754 
755 	erofs_dbg("%s, finish page: %pK spiltted: %u map->m_llen %llu",
756 		  __func__, page, spiltted, map->m_llen);
757 	return err;
758 
759 	/* if some error occurred while processing this page */
760 err_out:
761 	SetPageError(page);
762 	goto out;
763 }
764 
765 static bool z_erofs_get_sync_decompress_policy(struct erofs_sb_info *sbi,
766 				       unsigned int readahead_pages)
767 {
768 	/* auto: enable for readpage, disable for readahead */
769 	if ((sbi->opt.sync_decompress == EROFS_SYNC_DECOMPRESS_AUTO) &&
770 	    !readahead_pages)
771 		return true;
772 
773 	if ((sbi->opt.sync_decompress == EROFS_SYNC_DECOMPRESS_FORCE_ON) &&
774 	    (readahead_pages <= sbi->opt.max_sync_decompress_pages))
775 		return true;
776 
777 	return false;
778 }
779 
780 static void z_erofs_decompressqueue_work(struct work_struct *work);
781 static void z_erofs_decompress_kickoff(struct z_erofs_decompressqueue *io,
782 				       bool sync, int bios)
783 {
784 	struct erofs_sb_info *const sbi = EROFS_SB(io->sb);
785 
786 	/* wake up the caller thread for sync decompression */
787 	if (sync) {
788 		unsigned long flags;
789 
790 		spin_lock_irqsave(&io->u.wait.lock, flags);
791 		if (!atomic_add_return(bios, &io->pending_bios))
792 			wake_up_locked(&io->u.wait);
793 		spin_unlock_irqrestore(&io->u.wait.lock, flags);
794 		return;
795 	}
796 
797 	if (atomic_add_return(bios, &io->pending_bios))
798 		return;
799 	/* Use workqueue and sync decompression for atomic contexts only */
800 	if (in_atomic() || irqs_disabled()) {
801 		queue_work(z_erofs_workqueue, &io->u.work);
802 		/* enable sync decompression for readahead */
803 		if (sbi->opt.sync_decompress == EROFS_SYNC_DECOMPRESS_AUTO)
804 			sbi->opt.sync_decompress = EROFS_SYNC_DECOMPRESS_FORCE_ON;
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 page **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 page **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 	struct page *pagepool = NULL;
1069 
1070 	DBG_BUGON(bgq->head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1071 	z_erofs_decompress_queue(bgq, &pagepool);
1072 
1073 	erofs_release_pages(&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 page **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 	/* process the target tagged pointer */
1100 	t = tagptr_init(compressed_page_t, page);
1101 	justfound = tagptr_unfold_tags(t);
1102 	page = tagptr_unfold_ptr(t);
1103 
1104 	/*
1105 	 * preallocated cached pages, which is used to avoid direct reclaim
1106 	 * otherwise, it will go inplace I/O path instead.
1107 	 */
1108 	if (page->private == Z_EROFS_PREALLOCATED_PAGE) {
1109 		WRITE_ONCE(pcl->compressed_pages[nr], page);
1110 		set_page_private(page, 0);
1111 		tocache = true;
1112 		goto out_tocache;
1113 	}
1114 	mapping = READ_ONCE(page->mapping);
1115 
1116 	/*
1117 	 * file-backed online pages in plcuster are all locked steady,
1118 	 * therefore it is impossible for `mapping' to be NULL.
1119 	 */
1120 	if (mapping && mapping != mc)
1121 		/* ought to be unmanaged pages */
1122 		goto out;
1123 
1124 	/* directly return for shortlived page as well */
1125 	if (z_erofs_is_shortlived_page(page))
1126 		goto out;
1127 
1128 	lock_page(page);
1129 
1130 	/* only true if page reclaim goes wrong, should never happen */
1131 	DBG_BUGON(justfound && PagePrivate(page));
1132 
1133 	/* the page is still in manage cache */
1134 	if (page->mapping == mc) {
1135 		WRITE_ONCE(pcl->compressed_pages[nr], page);
1136 
1137 		ClearPageError(page);
1138 		if (!PagePrivate(page)) {
1139 			/*
1140 			 * impossible to be !PagePrivate(page) for
1141 			 * the current restriction as well if
1142 			 * the page is already in compressed_pages[].
1143 			 */
1144 			DBG_BUGON(!justfound);
1145 
1146 			justfound = 0;
1147 			set_page_private(page, (unsigned long)pcl);
1148 			SetPagePrivate(page);
1149 		}
1150 
1151 		/* no need to submit io if it is already up-to-date */
1152 		if (PageUptodate(page)) {
1153 			unlock_page(page);
1154 			page = NULL;
1155 		}
1156 		goto out;
1157 	}
1158 
1159 	/*
1160 	 * the managed page has been truncated, it's unsafe to
1161 	 * reuse this one, let's allocate a new cache-managed page.
1162 	 */
1163 	DBG_BUGON(page->mapping);
1164 	DBG_BUGON(!justfound);
1165 
1166 	tocache = true;
1167 	unlock_page(page);
1168 	put_page(page);
1169 out_allocpage:
1170 	page = erofs_allocpage(pagepool, gfp | __GFP_NOFAIL);
1171 	if (oldpage != cmpxchg(&pcl->compressed_pages[nr], oldpage, page)) {
1172 		erofs_pagepool_add(pagepool, page);
1173 		cond_resched();
1174 		goto repeat;
1175 	}
1176 out_tocache:
1177 	if (!tocache || add_to_page_cache_lru(page, mc, index + nr, gfp)) {
1178 		/* turn into temporary page if fails (1 ref) */
1179 		set_page_private(page, Z_EROFS_SHORTLIVED_PAGE);
1180 		goto out;
1181 	}
1182 	attach_page_private(page, pcl);
1183 	/* drop a refcount added by allocpage (then we have 2 refs here) */
1184 	put_page(page);
1185 
1186 out:	/* the only exit (for tracing and debugging) */
1187 	return page;
1188 }
1189 
1190 static struct z_erofs_decompressqueue *
1191 jobqueue_init(struct super_block *sb,
1192 	      struct z_erofs_decompressqueue *fgq, bool *fg)
1193 {
1194 	struct z_erofs_decompressqueue *q;
1195 
1196 	if (fg && !*fg) {
1197 		q = kvzalloc(sizeof(*q), GFP_KERNEL | __GFP_NOWARN);
1198 		if (!q) {
1199 			*fg = true;
1200 			goto fg_out;
1201 		}
1202 		INIT_WORK(&q->u.work, z_erofs_decompressqueue_work);
1203 	} else {
1204 fg_out:
1205 		q = fgq;
1206 		init_waitqueue_head(&fgq->u.wait);
1207 		atomic_set(&fgq->pending_bios, 0);
1208 	}
1209 	q->sb = sb;
1210 	q->head = Z_EROFS_PCLUSTER_TAIL_CLOSED;
1211 	return q;
1212 }
1213 
1214 /* define decompression jobqueue types */
1215 enum {
1216 	JQ_BYPASS,
1217 	JQ_SUBMIT,
1218 	NR_JOBQUEUES,
1219 };
1220 
1221 static void *jobqueueset_init(struct super_block *sb,
1222 			      struct z_erofs_decompressqueue *q[],
1223 			      struct z_erofs_decompressqueue *fgq, bool *fg)
1224 {
1225 	/*
1226 	 * if managed cache is enabled, bypass jobqueue is needed,
1227 	 * no need to read from device for all pclusters in this queue.
1228 	 */
1229 	q[JQ_BYPASS] = jobqueue_init(sb, fgq + JQ_BYPASS, NULL);
1230 	q[JQ_SUBMIT] = jobqueue_init(sb, fgq + JQ_SUBMIT, fg);
1231 
1232 	return tagptr_cast_ptr(tagptr_fold(tagptr1_t, q[JQ_SUBMIT], *fg));
1233 }
1234 
1235 static void move_to_bypass_jobqueue(struct z_erofs_pcluster *pcl,
1236 				    z_erofs_next_pcluster_t qtail[],
1237 				    z_erofs_next_pcluster_t owned_head)
1238 {
1239 	z_erofs_next_pcluster_t *const submit_qtail = qtail[JQ_SUBMIT];
1240 	z_erofs_next_pcluster_t *const bypass_qtail = qtail[JQ_BYPASS];
1241 
1242 	DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1243 	if (owned_head == Z_EROFS_PCLUSTER_TAIL)
1244 		owned_head = Z_EROFS_PCLUSTER_TAIL_CLOSED;
1245 
1246 	WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_TAIL_CLOSED);
1247 
1248 	WRITE_ONCE(*submit_qtail, owned_head);
1249 	WRITE_ONCE(*bypass_qtail, &pcl->next);
1250 
1251 	qtail[JQ_BYPASS] = &pcl->next;
1252 }
1253 
1254 static void z_erofs_submit_queue(struct super_block *sb,
1255 				 struct z_erofs_decompress_frontend *f,
1256 				 struct page **pagepool,
1257 				 struct z_erofs_decompressqueue *fgq,
1258 				 bool *force_fg)
1259 {
1260 	struct erofs_sb_info *const sbi = EROFS_SB(sb);
1261 	z_erofs_next_pcluster_t qtail[NR_JOBQUEUES];
1262 	struct z_erofs_decompressqueue *q[NR_JOBQUEUES];
1263 	void *bi_private;
1264 	z_erofs_next_pcluster_t owned_head = f->clt.owned_head;
1265 	/* bio is NULL initially, so no need to initialize last_{index,bdev} */
1266 	pgoff_t last_index;
1267 	struct block_device *last_bdev;
1268 	unsigned int nr_bios = 0;
1269 	struct bio *bio = NULL;
1270 
1271 	bi_private = jobqueueset_init(sb, q, fgq, force_fg);
1272 	qtail[JQ_BYPASS] = &q[JQ_BYPASS]->head;
1273 	qtail[JQ_SUBMIT] = &q[JQ_SUBMIT]->head;
1274 
1275 	/* by default, all need io submission */
1276 	q[JQ_SUBMIT]->head = owned_head;
1277 
1278 	do {
1279 		struct erofs_map_dev mdev;
1280 		struct z_erofs_pcluster *pcl;
1281 		pgoff_t cur, end;
1282 		unsigned int i = 0;
1283 		bool bypass = true;
1284 
1285 		/* no possible 'owned_head' equals the following */
1286 		DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1287 		DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_NIL);
1288 
1289 		pcl = container_of(owned_head, struct z_erofs_pcluster, next);
1290 
1291 		/* no device id here, thus it will always succeed */
1292 		mdev = (struct erofs_map_dev) {
1293 			.m_pa = blknr_to_addr(pcl->obj.index),
1294 		};
1295 		(void)erofs_map_dev(sb, &mdev);
1296 
1297 		cur = erofs_blknr(mdev.m_pa);
1298 		end = cur + pcl->pclusterpages;
1299 
1300 		/* close the main owned chain at first */
1301 		owned_head = cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_TAIL,
1302 				     Z_EROFS_PCLUSTER_TAIL_CLOSED);
1303 
1304 		do {
1305 			struct page *page;
1306 
1307 			page = pickup_page_for_submission(pcl, i++, pagepool,
1308 							  MNGD_MAPPING(sbi),
1309 							  GFP_NOFS);
1310 			if (!page)
1311 				continue;
1312 
1313 			if (bio && (cur != last_index + 1 ||
1314 				    last_bdev != mdev.m_bdev)) {
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 				bio->bi_end_io = z_erofs_decompressqueue_endio;
1323 
1324 				bio_set_dev(bio, mdev.m_bdev);
1325 				last_bdev = mdev.m_bdev;
1326 				bio->bi_iter.bi_sector = (sector_t)cur <<
1327 					LOG_SECTORS_PER_BLOCK;
1328 				bio->bi_private = bi_private;
1329 				bio->bi_opf = REQ_OP_READ;
1330 				if (f->readahead)
1331 					bio->bi_opf |= REQ_RAHEAD;
1332 				++nr_bios;
1333 			}
1334 
1335 			if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE)
1336 				goto submit_bio_retry;
1337 
1338 			last_index = cur;
1339 			bypass = false;
1340 		} while (++cur < end);
1341 
1342 		if (!bypass)
1343 			qtail[JQ_SUBMIT] = &pcl->next;
1344 		else
1345 			move_to_bypass_jobqueue(pcl, qtail, owned_head);
1346 	} while (owned_head != Z_EROFS_PCLUSTER_TAIL);
1347 
1348 	if (bio)
1349 		submit_bio(bio);
1350 
1351 	/*
1352 	 * although background is preferred, no one is pending for submission.
1353 	 * don't issue workqueue for decompression but drop it directly instead.
1354 	 */
1355 	if (!*force_fg && !nr_bios) {
1356 		kvfree(q[JQ_SUBMIT]);
1357 		return;
1358 	}
1359 	z_erofs_decompress_kickoff(q[JQ_SUBMIT], *force_fg, nr_bios);
1360 }
1361 
1362 static void z_erofs_runqueue(struct super_block *sb,
1363 			     struct z_erofs_decompress_frontend *f,
1364 			     struct page **pagepool, bool force_fg)
1365 {
1366 	struct z_erofs_decompressqueue io[NR_JOBQUEUES];
1367 
1368 	if (f->clt.owned_head == Z_EROFS_PCLUSTER_TAIL)
1369 		return;
1370 	z_erofs_submit_queue(sb, f, pagepool, io, &force_fg);
1371 
1372 	/* handle bypass queue (no i/o pclusters) immediately */
1373 	z_erofs_decompress_queue(&io[JQ_BYPASS], pagepool);
1374 
1375 	if (!force_fg)
1376 		return;
1377 
1378 	/* wait until all bios are completed */
1379 	io_wait_event(io[JQ_SUBMIT].u.wait,
1380 		      !atomic_read(&io[JQ_SUBMIT].pending_bios));
1381 
1382 	/* handle synchronous decompress queue in the caller context */
1383 	z_erofs_decompress_queue(&io[JQ_SUBMIT], pagepool);
1384 }
1385 
1386 /*
1387  * Since partial uptodate is still unimplemented for now, we have to use
1388  * approximate readmore strategies as a start.
1389  */
1390 static void z_erofs_pcluster_readmore(struct z_erofs_decompress_frontend *f,
1391 				      struct readahead_control *rac,
1392 				      erofs_off_t end,
1393 				      struct page **pagepool,
1394 				      bool backmost)
1395 {
1396 	struct inode *inode = f->inode;
1397 	struct erofs_map_blocks *map = &f->map;
1398 	erofs_off_t cur;
1399 	int err;
1400 
1401 	if (backmost) {
1402 		map->m_la = end;
1403 		err = z_erofs_map_blocks_iter(inode, map,
1404 					      EROFS_GET_BLOCKS_READMORE);
1405 		if (err)
1406 			return;
1407 
1408 		/* expend ra for the trailing edge if readahead */
1409 		if (rac) {
1410 			loff_t newstart = readahead_pos(rac);
1411 
1412 			cur = round_up(map->m_la + map->m_llen, PAGE_SIZE);
1413 			readahead_expand(rac, newstart, cur - newstart);
1414 			return;
1415 		}
1416 		end = round_up(end, PAGE_SIZE);
1417 	} else {
1418 		end = round_up(map->m_la, PAGE_SIZE);
1419 
1420 		if (!map->m_llen)
1421 			return;
1422 	}
1423 
1424 	cur = map->m_la + map->m_llen - 1;
1425 	while (cur >= end) {
1426 		pgoff_t index = cur >> PAGE_SHIFT;
1427 		struct page *page;
1428 
1429 		page = erofs_grab_cache_page_nowait(inode->i_mapping, index);
1430 		if (!page)
1431 			goto skip;
1432 
1433 		if (PageUptodate(page)) {
1434 			unlock_page(page);
1435 			put_page(page);
1436 			goto skip;
1437 		}
1438 
1439 		err = z_erofs_do_read_page(f, page, pagepool);
1440 		if (err)
1441 			erofs_err(inode->i_sb,
1442 				  "readmore error at page %lu @ nid %llu",
1443 				  index, EROFS_I(inode)->nid);
1444 		put_page(page);
1445 skip:
1446 		if (cur < PAGE_SIZE)
1447 			break;
1448 		cur = (index << PAGE_SHIFT) - 1;
1449 	}
1450 }
1451 
1452 static int z_erofs_readpage(struct file *file, struct page *page)
1453 {
1454 	struct inode *const inode = page->mapping->host;
1455 	struct erofs_sb_info *const sbi = EROFS_I_SB(inode);
1456 	struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1457 	struct page *pagepool = NULL;
1458 	int err;
1459 
1460 	trace_erofs_readpage(page, false);
1461 	f.headoffset = (erofs_off_t)page->index << PAGE_SHIFT;
1462 
1463 	z_erofs_pcluster_readmore(&f, NULL, f.headoffset + PAGE_SIZE - 1,
1464 				  &pagepool, true);
1465 	err = z_erofs_do_read_page(&f, page, &pagepool);
1466 	z_erofs_pcluster_readmore(&f, NULL, 0, &pagepool, false);
1467 
1468 	(void)z_erofs_collector_end(&f.clt);
1469 
1470 	/* if some compressed cluster ready, need submit them anyway */
1471 	z_erofs_runqueue(inode->i_sb, &f, &pagepool,
1472 			 z_erofs_get_sync_decompress_policy(sbi, 0));
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 			 z_erofs_get_sync_decompress_policy(sbi, nr_pages));
1524 	if (f.map.mpage)
1525 		put_page(f.map.mpage);
1526 	erofs_release_pages(&pagepool);
1527 }
1528 
1529 const struct address_space_operations z_erofs_aops = {
1530 	.readpage = z_erofs_readpage,
1531 	.readahead = z_erofs_readahead,
1532 };
1533