xref: /openbmc/linux/fs/erofs/zdata.c (revision 901181b7)
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 void z_erofs_decompressqueue_work(struct work_struct *work);
766 static void z_erofs_decompress_kickoff(struct z_erofs_decompressqueue *io,
767 				       bool sync, int bios)
768 {
769 	struct erofs_sb_info *const sbi = EROFS_SB(io->sb);
770 
771 	/* wake up the caller thread for sync decompression */
772 	if (sync) {
773 		unsigned long flags;
774 
775 		spin_lock_irqsave(&io->u.wait.lock, flags);
776 		if (!atomic_add_return(bios, &io->pending_bios))
777 			wake_up_locked(&io->u.wait);
778 		spin_unlock_irqrestore(&io->u.wait.lock, flags);
779 		return;
780 	}
781 
782 	if (atomic_add_return(bios, &io->pending_bios))
783 		return;
784 	/* Use workqueue and sync decompression for atomic contexts only */
785 	if (in_atomic() || irqs_disabled()) {
786 		queue_work(z_erofs_workqueue, &io->u.work);
787 		sbi->opt.readahead_sync_decompress = true;
788 		return;
789 	}
790 	z_erofs_decompressqueue_work(&io->u.work);
791 }
792 
793 static bool z_erofs_page_is_invalidated(struct page *page)
794 {
795 	return !page->mapping && !z_erofs_is_shortlived_page(page);
796 }
797 
798 static void z_erofs_decompressqueue_endio(struct bio *bio)
799 {
800 	tagptr1_t t = tagptr_init(tagptr1_t, bio->bi_private);
801 	struct z_erofs_decompressqueue *q = tagptr_unfold_ptr(t);
802 	blk_status_t err = bio->bi_status;
803 	struct bio_vec *bvec;
804 	struct bvec_iter_all iter_all;
805 
806 	bio_for_each_segment_all(bvec, bio, iter_all) {
807 		struct page *page = bvec->bv_page;
808 
809 		DBG_BUGON(PageUptodate(page));
810 		DBG_BUGON(z_erofs_page_is_invalidated(page));
811 
812 		if (err)
813 			SetPageError(page);
814 
815 		if (erofs_page_is_managed(EROFS_SB(q->sb), page)) {
816 			if (!err)
817 				SetPageUptodate(page);
818 			unlock_page(page);
819 		}
820 	}
821 	z_erofs_decompress_kickoff(q, tagptr_unfold_tags(t), -1);
822 	bio_put(bio);
823 }
824 
825 static int z_erofs_decompress_pcluster(struct super_block *sb,
826 				       struct z_erofs_pcluster *pcl,
827 				       struct page **pagepool)
828 {
829 	struct erofs_sb_info *const sbi = EROFS_SB(sb);
830 	struct z_erofs_pagevec_ctor ctor;
831 	unsigned int i, inputsize, outputsize, llen, nr_pages;
832 	struct page *pages_onstack[Z_EROFS_VMAP_ONSTACK_PAGES];
833 	struct page **pages, **compressed_pages, *page;
834 
835 	enum z_erofs_page_type page_type;
836 	bool overlapped, partial;
837 	struct z_erofs_collection *cl;
838 	int err;
839 
840 	might_sleep();
841 	cl = z_erofs_primarycollection(pcl);
842 	DBG_BUGON(!READ_ONCE(cl->nr_pages));
843 
844 	mutex_lock(&cl->lock);
845 	nr_pages = cl->nr_pages;
846 
847 	if (nr_pages <= Z_EROFS_VMAP_ONSTACK_PAGES) {
848 		pages = pages_onstack;
849 	} else if (nr_pages <= Z_EROFS_VMAP_GLOBAL_PAGES &&
850 		   mutex_trylock(&z_pagemap_global_lock)) {
851 		pages = z_pagemap_global;
852 	} else {
853 		gfp_t gfp_flags = GFP_KERNEL;
854 
855 		if (nr_pages > Z_EROFS_VMAP_GLOBAL_PAGES)
856 			gfp_flags |= __GFP_NOFAIL;
857 
858 		pages = kvmalloc_array(nr_pages, sizeof(struct page *),
859 				       gfp_flags);
860 
861 		/* fallback to global pagemap for the lowmem scenario */
862 		if (!pages) {
863 			mutex_lock(&z_pagemap_global_lock);
864 			pages = z_pagemap_global;
865 		}
866 	}
867 
868 	for (i = 0; i < nr_pages; ++i)
869 		pages[i] = NULL;
870 
871 	err = 0;
872 	z_erofs_pagevec_ctor_init(&ctor, Z_EROFS_NR_INLINE_PAGEVECS,
873 				  cl->pagevec, 0);
874 
875 	for (i = 0; i < cl->vcnt; ++i) {
876 		unsigned int pagenr;
877 
878 		page = z_erofs_pagevec_dequeue(&ctor, &page_type);
879 
880 		/* all pages in pagevec ought to be valid */
881 		DBG_BUGON(!page);
882 		DBG_BUGON(z_erofs_page_is_invalidated(page));
883 
884 		if (z_erofs_put_shortlivedpage(pagepool, page))
885 			continue;
886 
887 		if (page_type == Z_EROFS_VLE_PAGE_TYPE_HEAD)
888 			pagenr = 0;
889 		else
890 			pagenr = z_erofs_onlinepage_index(page);
891 
892 		DBG_BUGON(pagenr >= nr_pages);
893 
894 		/*
895 		 * currently EROFS doesn't support multiref(dedup),
896 		 * so here erroring out one multiref page.
897 		 */
898 		if (pages[pagenr]) {
899 			DBG_BUGON(1);
900 			SetPageError(pages[pagenr]);
901 			z_erofs_onlinepage_endio(pages[pagenr]);
902 			err = -EFSCORRUPTED;
903 		}
904 		pages[pagenr] = page;
905 	}
906 	z_erofs_pagevec_ctor_exit(&ctor, true);
907 
908 	overlapped = false;
909 	compressed_pages = pcl->compressed_pages;
910 
911 	for (i = 0; i < pcl->pclusterpages; ++i) {
912 		unsigned int pagenr;
913 
914 		page = compressed_pages[i];
915 
916 		/* all compressed pages ought to be valid */
917 		DBG_BUGON(!page);
918 		DBG_BUGON(z_erofs_page_is_invalidated(page));
919 
920 		if (!z_erofs_is_shortlived_page(page)) {
921 			if (erofs_page_is_managed(sbi, page)) {
922 				if (!PageUptodate(page))
923 					err = -EIO;
924 				continue;
925 			}
926 
927 			/*
928 			 * only if non-head page can be selected
929 			 * for inplace decompression
930 			 */
931 			pagenr = z_erofs_onlinepage_index(page);
932 
933 			DBG_BUGON(pagenr >= nr_pages);
934 			if (pages[pagenr]) {
935 				DBG_BUGON(1);
936 				SetPageError(pages[pagenr]);
937 				z_erofs_onlinepage_endio(pages[pagenr]);
938 				err = -EFSCORRUPTED;
939 			}
940 			pages[pagenr] = page;
941 
942 			overlapped = true;
943 		}
944 
945 		/* PG_error needs checking for all non-managed pages */
946 		if (PageError(page)) {
947 			DBG_BUGON(PageUptodate(page));
948 			err = -EIO;
949 		}
950 	}
951 
952 	if (err)
953 		goto out;
954 
955 	llen = pcl->length >> Z_EROFS_PCLUSTER_LENGTH_BIT;
956 	if (nr_pages << PAGE_SHIFT >= cl->pageofs + llen) {
957 		outputsize = llen;
958 		partial = !(pcl->length & Z_EROFS_PCLUSTER_FULL_LENGTH);
959 	} else {
960 		outputsize = (nr_pages << PAGE_SHIFT) - cl->pageofs;
961 		partial = true;
962 	}
963 
964 	inputsize = pcl->pclusterpages * PAGE_SIZE;
965 	err = z_erofs_decompress(&(struct z_erofs_decompress_req) {
966 					.sb = sb,
967 					.in = compressed_pages,
968 					.out = pages,
969 					.pageofs_out = cl->pageofs,
970 					.inputsize = inputsize,
971 					.outputsize = outputsize,
972 					.alg = pcl->algorithmformat,
973 					.inplace_io = overlapped,
974 					.partial_decoding = partial
975 				 }, pagepool);
976 
977 out:
978 	/* must handle all compressed pages before ending pages */
979 	for (i = 0; i < pcl->pclusterpages; ++i) {
980 		page = compressed_pages[i];
981 
982 		if (erofs_page_is_managed(sbi, page))
983 			continue;
984 
985 		/* recycle all individual short-lived pages */
986 		(void)z_erofs_put_shortlivedpage(pagepool, page);
987 
988 		WRITE_ONCE(compressed_pages[i], NULL);
989 	}
990 
991 	for (i = 0; i < nr_pages; ++i) {
992 		page = pages[i];
993 		if (!page)
994 			continue;
995 
996 		DBG_BUGON(z_erofs_page_is_invalidated(page));
997 
998 		/* recycle all individual short-lived pages */
999 		if (z_erofs_put_shortlivedpage(pagepool, page))
1000 			continue;
1001 
1002 		if (err < 0)
1003 			SetPageError(page);
1004 
1005 		z_erofs_onlinepage_endio(page);
1006 	}
1007 
1008 	if (pages == z_pagemap_global)
1009 		mutex_unlock(&z_pagemap_global_lock);
1010 	else if (pages != pages_onstack)
1011 		kvfree(pages);
1012 
1013 	cl->nr_pages = 0;
1014 	cl->vcnt = 0;
1015 
1016 	/* all cl locks MUST be taken before the following line */
1017 	WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_NIL);
1018 
1019 	/* all cl locks SHOULD be released right now */
1020 	mutex_unlock(&cl->lock);
1021 
1022 	z_erofs_collection_put(cl);
1023 	return err;
1024 }
1025 
1026 static void z_erofs_decompress_queue(const struct z_erofs_decompressqueue *io,
1027 				     struct page **pagepool)
1028 {
1029 	z_erofs_next_pcluster_t owned = io->head;
1030 
1031 	while (owned != Z_EROFS_PCLUSTER_TAIL_CLOSED) {
1032 		struct z_erofs_pcluster *pcl;
1033 
1034 		/* no possible that 'owned' equals Z_EROFS_WORK_TPTR_TAIL */
1035 		DBG_BUGON(owned == Z_EROFS_PCLUSTER_TAIL);
1036 
1037 		/* no possible that 'owned' equals NULL */
1038 		DBG_BUGON(owned == Z_EROFS_PCLUSTER_NIL);
1039 
1040 		pcl = container_of(owned, struct z_erofs_pcluster, next);
1041 		owned = READ_ONCE(pcl->next);
1042 
1043 		z_erofs_decompress_pcluster(io->sb, pcl, pagepool);
1044 	}
1045 }
1046 
1047 static void z_erofs_decompressqueue_work(struct work_struct *work)
1048 {
1049 	struct z_erofs_decompressqueue *bgq =
1050 		container_of(work, struct z_erofs_decompressqueue, u.work);
1051 	struct page *pagepool = NULL;
1052 
1053 	DBG_BUGON(bgq->head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1054 	z_erofs_decompress_queue(bgq, &pagepool);
1055 
1056 	erofs_release_pages(&pagepool);
1057 	kvfree(bgq);
1058 }
1059 
1060 static struct page *pickup_page_for_submission(struct z_erofs_pcluster *pcl,
1061 					       unsigned int nr,
1062 					       struct page **pagepool,
1063 					       struct address_space *mc,
1064 					       gfp_t gfp)
1065 {
1066 	const pgoff_t index = pcl->obj.index;
1067 	bool tocache = false;
1068 
1069 	struct address_space *mapping;
1070 	struct page *oldpage, *page;
1071 
1072 	compressed_page_t t;
1073 	int justfound;
1074 
1075 repeat:
1076 	page = READ_ONCE(pcl->compressed_pages[nr]);
1077 	oldpage = page;
1078 
1079 	if (!page)
1080 		goto out_allocpage;
1081 
1082 	/* process the target tagged pointer */
1083 	t = tagptr_init(compressed_page_t, page);
1084 	justfound = tagptr_unfold_tags(t);
1085 	page = tagptr_unfold_ptr(t);
1086 
1087 	/*
1088 	 * preallocated cached pages, which is used to avoid direct reclaim
1089 	 * otherwise, it will go inplace I/O path instead.
1090 	 */
1091 	if (page->private == Z_EROFS_PREALLOCATED_PAGE) {
1092 		WRITE_ONCE(pcl->compressed_pages[nr], page);
1093 		set_page_private(page, 0);
1094 		tocache = true;
1095 		goto out_tocache;
1096 	}
1097 	mapping = READ_ONCE(page->mapping);
1098 
1099 	/*
1100 	 * file-backed online pages in plcuster are all locked steady,
1101 	 * therefore it is impossible for `mapping' to be NULL.
1102 	 */
1103 	if (mapping && mapping != mc)
1104 		/* ought to be unmanaged pages */
1105 		goto out;
1106 
1107 	/* directly return for shortlived page as well */
1108 	if (z_erofs_is_shortlived_page(page))
1109 		goto out;
1110 
1111 	lock_page(page);
1112 
1113 	/* only true if page reclaim goes wrong, should never happen */
1114 	DBG_BUGON(justfound && PagePrivate(page));
1115 
1116 	/* the page is still in manage cache */
1117 	if (page->mapping == mc) {
1118 		WRITE_ONCE(pcl->compressed_pages[nr], page);
1119 
1120 		ClearPageError(page);
1121 		if (!PagePrivate(page)) {
1122 			/*
1123 			 * impossible to be !PagePrivate(page) for
1124 			 * the current restriction as well if
1125 			 * the page is already in compressed_pages[].
1126 			 */
1127 			DBG_BUGON(!justfound);
1128 
1129 			justfound = 0;
1130 			set_page_private(page, (unsigned long)pcl);
1131 			SetPagePrivate(page);
1132 		}
1133 
1134 		/* no need to submit io if it is already up-to-date */
1135 		if (PageUptodate(page)) {
1136 			unlock_page(page);
1137 			page = NULL;
1138 		}
1139 		goto out;
1140 	}
1141 
1142 	/*
1143 	 * the managed page has been truncated, it's unsafe to
1144 	 * reuse this one, let's allocate a new cache-managed page.
1145 	 */
1146 	DBG_BUGON(page->mapping);
1147 	DBG_BUGON(!justfound);
1148 
1149 	tocache = true;
1150 	unlock_page(page);
1151 	put_page(page);
1152 out_allocpage:
1153 	page = erofs_allocpage(pagepool, gfp | __GFP_NOFAIL);
1154 	if (oldpage != cmpxchg(&pcl->compressed_pages[nr], oldpage, page)) {
1155 		erofs_pagepool_add(pagepool, page);
1156 		cond_resched();
1157 		goto repeat;
1158 	}
1159 out_tocache:
1160 	if (!tocache || add_to_page_cache_lru(page, mc, index + nr, gfp)) {
1161 		/* turn into temporary page if fails (1 ref) */
1162 		set_page_private(page, Z_EROFS_SHORTLIVED_PAGE);
1163 		goto out;
1164 	}
1165 	attach_page_private(page, pcl);
1166 	/* drop a refcount added by allocpage (then we have 2 refs here) */
1167 	put_page(page);
1168 
1169 out:	/* the only exit (for tracing and debugging) */
1170 	return page;
1171 }
1172 
1173 static struct z_erofs_decompressqueue *
1174 jobqueue_init(struct super_block *sb,
1175 	      struct z_erofs_decompressqueue *fgq, bool *fg)
1176 {
1177 	struct z_erofs_decompressqueue *q;
1178 
1179 	if (fg && !*fg) {
1180 		q = kvzalloc(sizeof(*q), GFP_KERNEL | __GFP_NOWARN);
1181 		if (!q) {
1182 			*fg = true;
1183 			goto fg_out;
1184 		}
1185 		INIT_WORK(&q->u.work, z_erofs_decompressqueue_work);
1186 	} else {
1187 fg_out:
1188 		q = fgq;
1189 		init_waitqueue_head(&fgq->u.wait);
1190 		atomic_set(&fgq->pending_bios, 0);
1191 	}
1192 	q->sb = sb;
1193 	q->head = Z_EROFS_PCLUSTER_TAIL_CLOSED;
1194 	return q;
1195 }
1196 
1197 /* define decompression jobqueue types */
1198 enum {
1199 	JQ_BYPASS,
1200 	JQ_SUBMIT,
1201 	NR_JOBQUEUES,
1202 };
1203 
1204 static void *jobqueueset_init(struct super_block *sb,
1205 			      struct z_erofs_decompressqueue *q[],
1206 			      struct z_erofs_decompressqueue *fgq, bool *fg)
1207 {
1208 	/*
1209 	 * if managed cache is enabled, bypass jobqueue is needed,
1210 	 * no need to read from device for all pclusters in this queue.
1211 	 */
1212 	q[JQ_BYPASS] = jobqueue_init(sb, fgq + JQ_BYPASS, NULL);
1213 	q[JQ_SUBMIT] = jobqueue_init(sb, fgq + JQ_SUBMIT, fg);
1214 
1215 	return tagptr_cast_ptr(tagptr_fold(tagptr1_t, q[JQ_SUBMIT], *fg));
1216 }
1217 
1218 static void move_to_bypass_jobqueue(struct z_erofs_pcluster *pcl,
1219 				    z_erofs_next_pcluster_t qtail[],
1220 				    z_erofs_next_pcluster_t owned_head)
1221 {
1222 	z_erofs_next_pcluster_t *const submit_qtail = qtail[JQ_SUBMIT];
1223 	z_erofs_next_pcluster_t *const bypass_qtail = qtail[JQ_BYPASS];
1224 
1225 	DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1226 	if (owned_head == Z_EROFS_PCLUSTER_TAIL)
1227 		owned_head = Z_EROFS_PCLUSTER_TAIL_CLOSED;
1228 
1229 	WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_TAIL_CLOSED);
1230 
1231 	WRITE_ONCE(*submit_qtail, owned_head);
1232 	WRITE_ONCE(*bypass_qtail, &pcl->next);
1233 
1234 	qtail[JQ_BYPASS] = &pcl->next;
1235 }
1236 
1237 static void z_erofs_submit_queue(struct super_block *sb,
1238 				 struct z_erofs_decompress_frontend *f,
1239 				 struct page **pagepool,
1240 				 struct z_erofs_decompressqueue *fgq,
1241 				 bool *force_fg)
1242 {
1243 	struct erofs_sb_info *const sbi = EROFS_SB(sb);
1244 	z_erofs_next_pcluster_t qtail[NR_JOBQUEUES];
1245 	struct z_erofs_decompressqueue *q[NR_JOBQUEUES];
1246 	void *bi_private;
1247 	z_erofs_next_pcluster_t owned_head = f->clt.owned_head;
1248 	/* bio is NULL initially, so no need to initialize last_{index,bdev} */
1249 	pgoff_t last_index;
1250 	struct block_device *last_bdev;
1251 	unsigned int nr_bios = 0;
1252 	struct bio *bio = NULL;
1253 
1254 	bi_private = jobqueueset_init(sb, q, fgq, force_fg);
1255 	qtail[JQ_BYPASS] = &q[JQ_BYPASS]->head;
1256 	qtail[JQ_SUBMIT] = &q[JQ_SUBMIT]->head;
1257 
1258 	/* by default, all need io submission */
1259 	q[JQ_SUBMIT]->head = owned_head;
1260 
1261 	do {
1262 		struct erofs_map_dev mdev;
1263 		struct z_erofs_pcluster *pcl;
1264 		pgoff_t cur, end;
1265 		unsigned int i = 0;
1266 		bool bypass = true;
1267 
1268 		/* no possible 'owned_head' equals the following */
1269 		DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1270 		DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_NIL);
1271 
1272 		pcl = container_of(owned_head, struct z_erofs_pcluster, next);
1273 
1274 		/* no device id here, thus it will always succeed */
1275 		mdev = (struct erofs_map_dev) {
1276 			.m_pa = blknr_to_addr(pcl->obj.index),
1277 		};
1278 		(void)erofs_map_dev(sb, &mdev);
1279 
1280 		cur = erofs_blknr(mdev.m_pa);
1281 		end = cur + pcl->pclusterpages;
1282 
1283 		/* close the main owned chain at first */
1284 		owned_head = cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_TAIL,
1285 				     Z_EROFS_PCLUSTER_TAIL_CLOSED);
1286 
1287 		do {
1288 			struct page *page;
1289 
1290 			page = pickup_page_for_submission(pcl, i++, pagepool,
1291 							  MNGD_MAPPING(sbi),
1292 							  GFP_NOFS);
1293 			if (!page)
1294 				continue;
1295 
1296 			if (bio && (cur != last_index + 1 ||
1297 				    last_bdev != mdev.m_bdev)) {
1298 submit_bio_retry:
1299 				submit_bio(bio);
1300 				bio = NULL;
1301 			}
1302 
1303 			if (!bio) {
1304 				bio = bio_alloc(GFP_NOIO, BIO_MAX_VECS);
1305 				bio->bi_end_io = z_erofs_decompressqueue_endio;
1306 
1307 				bio_set_dev(bio, mdev.m_bdev);
1308 				last_bdev = mdev.m_bdev;
1309 				bio->bi_iter.bi_sector = (sector_t)cur <<
1310 					LOG_SECTORS_PER_BLOCK;
1311 				bio->bi_private = bi_private;
1312 				bio->bi_opf = REQ_OP_READ;
1313 				if (f->readahead)
1314 					bio->bi_opf |= REQ_RAHEAD;
1315 				++nr_bios;
1316 			}
1317 
1318 			if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE)
1319 				goto submit_bio_retry;
1320 
1321 			last_index = cur;
1322 			bypass = false;
1323 		} while (++cur < end);
1324 
1325 		if (!bypass)
1326 			qtail[JQ_SUBMIT] = &pcl->next;
1327 		else
1328 			move_to_bypass_jobqueue(pcl, qtail, owned_head);
1329 	} while (owned_head != Z_EROFS_PCLUSTER_TAIL);
1330 
1331 	if (bio)
1332 		submit_bio(bio);
1333 
1334 	/*
1335 	 * although background is preferred, no one is pending for submission.
1336 	 * don't issue workqueue for decompression but drop it directly instead.
1337 	 */
1338 	if (!*force_fg && !nr_bios) {
1339 		kvfree(q[JQ_SUBMIT]);
1340 		return;
1341 	}
1342 	z_erofs_decompress_kickoff(q[JQ_SUBMIT], *force_fg, nr_bios);
1343 }
1344 
1345 static void z_erofs_runqueue(struct super_block *sb,
1346 			     struct z_erofs_decompress_frontend *f,
1347 			     struct page **pagepool, bool force_fg)
1348 {
1349 	struct z_erofs_decompressqueue io[NR_JOBQUEUES];
1350 
1351 	if (f->clt.owned_head == Z_EROFS_PCLUSTER_TAIL)
1352 		return;
1353 	z_erofs_submit_queue(sb, f, pagepool, io, &force_fg);
1354 
1355 	/* handle bypass queue (no i/o pclusters) immediately */
1356 	z_erofs_decompress_queue(&io[JQ_BYPASS], pagepool);
1357 
1358 	if (!force_fg)
1359 		return;
1360 
1361 	/* wait until all bios are completed */
1362 	io_wait_event(io[JQ_SUBMIT].u.wait,
1363 		      !atomic_read(&io[JQ_SUBMIT].pending_bios));
1364 
1365 	/* handle synchronous decompress queue in the caller context */
1366 	z_erofs_decompress_queue(&io[JQ_SUBMIT], pagepool);
1367 }
1368 
1369 /*
1370  * Since partial uptodate is still unimplemented for now, we have to use
1371  * approximate readmore strategies as a start.
1372  */
1373 static void z_erofs_pcluster_readmore(struct z_erofs_decompress_frontend *f,
1374 				      struct readahead_control *rac,
1375 				      erofs_off_t end,
1376 				      struct page **pagepool,
1377 				      bool backmost)
1378 {
1379 	struct inode *inode = f->inode;
1380 	struct erofs_map_blocks *map = &f->map;
1381 	erofs_off_t cur;
1382 	int err;
1383 
1384 	if (backmost) {
1385 		map->m_la = end;
1386 		err = z_erofs_map_blocks_iter(inode, map,
1387 					      EROFS_GET_BLOCKS_READMORE);
1388 		if (err)
1389 			return;
1390 
1391 		/* expend ra for the trailing edge if readahead */
1392 		if (rac) {
1393 			loff_t newstart = readahead_pos(rac);
1394 
1395 			cur = round_up(map->m_la + map->m_llen, PAGE_SIZE);
1396 			readahead_expand(rac, newstart, cur - newstart);
1397 			return;
1398 		}
1399 		end = round_up(end, PAGE_SIZE);
1400 	} else {
1401 		end = round_up(map->m_la, PAGE_SIZE);
1402 
1403 		if (!map->m_llen)
1404 			return;
1405 	}
1406 
1407 	cur = map->m_la + map->m_llen - 1;
1408 	while (cur >= end) {
1409 		pgoff_t index = cur >> PAGE_SHIFT;
1410 		struct page *page;
1411 
1412 		page = erofs_grab_cache_page_nowait(inode->i_mapping, index);
1413 		if (!page)
1414 			goto skip;
1415 
1416 		if (PageUptodate(page)) {
1417 			unlock_page(page);
1418 			put_page(page);
1419 			goto skip;
1420 		}
1421 
1422 		err = z_erofs_do_read_page(f, page, pagepool);
1423 		if (err)
1424 			erofs_err(inode->i_sb,
1425 				  "readmore error at page %lu @ nid %llu",
1426 				  index, EROFS_I(inode)->nid);
1427 		put_page(page);
1428 skip:
1429 		if (cur < PAGE_SIZE)
1430 			break;
1431 		cur = (index << PAGE_SHIFT) - 1;
1432 	}
1433 }
1434 
1435 static int z_erofs_readpage(struct file *file, struct page *page)
1436 {
1437 	struct inode *const inode = page->mapping->host;
1438 	struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1439 	struct page *pagepool = NULL;
1440 	int err;
1441 
1442 	trace_erofs_readpage(page, false);
1443 	f.headoffset = (erofs_off_t)page->index << PAGE_SHIFT;
1444 
1445 	z_erofs_pcluster_readmore(&f, NULL, f.headoffset + PAGE_SIZE - 1,
1446 				  &pagepool, true);
1447 	err = z_erofs_do_read_page(&f, page, &pagepool);
1448 	z_erofs_pcluster_readmore(&f, NULL, 0, &pagepool, false);
1449 
1450 	(void)z_erofs_collector_end(&f.clt);
1451 
1452 	/* if some compressed cluster ready, need submit them anyway */
1453 	z_erofs_runqueue(inode->i_sb, &f, &pagepool, true);
1454 
1455 	if (err)
1456 		erofs_err(inode->i_sb, "failed to read, err [%d]", err);
1457 
1458 	if (f.map.mpage)
1459 		put_page(f.map.mpage);
1460 
1461 	erofs_release_pages(&pagepool);
1462 	return err;
1463 }
1464 
1465 static void z_erofs_readahead(struct readahead_control *rac)
1466 {
1467 	struct inode *const inode = rac->mapping->host;
1468 	struct erofs_sb_info *const sbi = EROFS_I_SB(inode);
1469 	struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1470 	struct page *pagepool = NULL, *head = NULL, *page;
1471 	unsigned int nr_pages;
1472 
1473 	f.readahead = true;
1474 	f.headoffset = readahead_pos(rac);
1475 
1476 	z_erofs_pcluster_readmore(&f, rac, f.headoffset +
1477 				  readahead_length(rac) - 1, &pagepool, true);
1478 	nr_pages = readahead_count(rac);
1479 	trace_erofs_readpages(inode, readahead_index(rac), nr_pages, false);
1480 
1481 	while ((page = readahead_page(rac))) {
1482 		set_page_private(page, (unsigned long)head);
1483 		head = page;
1484 	}
1485 
1486 	while (head) {
1487 		struct page *page = head;
1488 		int err;
1489 
1490 		/* traversal in reverse order */
1491 		head = (void *)page_private(page);
1492 
1493 		err = z_erofs_do_read_page(&f, page, &pagepool);
1494 		if (err)
1495 			erofs_err(inode->i_sb,
1496 				  "readahead error at page %lu @ nid %llu",
1497 				  page->index, EROFS_I(inode)->nid);
1498 		put_page(page);
1499 	}
1500 	z_erofs_pcluster_readmore(&f, rac, 0, &pagepool, false);
1501 	(void)z_erofs_collector_end(&f.clt);
1502 
1503 	z_erofs_runqueue(inode->i_sb, &f, &pagepool,
1504 			 sbi->opt.readahead_sync_decompress &&
1505 			 nr_pages <= sbi->opt.max_sync_decompress_pages);
1506 	if (f.map.mpage)
1507 		put_page(f.map.mpage);
1508 	erofs_release_pages(&pagepool);
1509 }
1510 
1511 const struct address_space_operations z_erofs_aops = {
1512 	.readpage = z_erofs_readpage,
1513 	.readahead = z_erofs_readahead,
1514 };
1515