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