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