xref: /linux/fs/erofs/zdata.c (revision ed90ed56e4b1311797302c2e6107f5049ba4586d)
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 "compress.h"
8 #include <linux/psi.h>
9 #include <linux/cpuhotplug.h>
10 #include <trace/events/erofs.h>
11 
12 #define Z_EROFS_PCLUSTER_MAX_PAGES	(Z_EROFS_PCLUSTER_MAX_SIZE / PAGE_SIZE)
13 #define Z_EROFS_INLINE_BVECS		2
14 
15 /*
16  * let's leave a type here in case of introducing
17  * another tagged pointer later.
18  */
19 typedef void *z_erofs_next_pcluster_t;
20 
21 struct z_erofs_bvec {
22 	struct page *page;
23 	int offset;
24 	unsigned int end;
25 };
26 
27 #define __Z_EROFS_BVSET(name, total) \
28 struct name { \
29 	/* point to the next page which contains the following bvecs */ \
30 	struct page *nextpage; \
31 	struct z_erofs_bvec bvec[total]; \
32 }
33 __Z_EROFS_BVSET(z_erofs_bvset,);
34 __Z_EROFS_BVSET(z_erofs_bvset_inline, Z_EROFS_INLINE_BVECS);
35 
36 /*
37  * Structure fields follow one of the following exclusion rules.
38  *
39  * I: Modifiable by initialization/destruction paths and read-only
40  *    for everyone else;
41  *
42  * L: Field should be protected by the pcluster lock;
43  *
44  * A: Field should be accessed / updated in atomic for parallelized code.
45  */
46 struct z_erofs_pcluster {
47 	struct mutex lock;
48 	struct lockref lockref;
49 
50 	/* A: point to next chained pcluster or TAILs */
51 	z_erofs_next_pcluster_t next;
52 
53 	/* I: start block address of this pcluster */
54 	erofs_off_t index;
55 
56 	/* L: the maximum decompression size of this round */
57 	unsigned int length;
58 
59 	/* L: total number of bvecs */
60 	unsigned int vcnt;
61 
62 	/* I: pcluster size (compressed size) in bytes */
63 	unsigned int pclustersize;
64 
65 	/* I: page offset of start position of decompression */
66 	unsigned short pageofs_out;
67 
68 	/* I: page offset of inline compressed data */
69 	unsigned short pageofs_in;
70 
71 	union {
72 		/* L: inline a certain number of bvec for bootstrap */
73 		struct z_erofs_bvset_inline bvset;
74 
75 		/* I: can be used to free the pcluster by RCU. */
76 		struct rcu_head rcu;
77 	};
78 
79 	/* I: compression algorithm format */
80 	unsigned char algorithmformat;
81 
82 	/* L: whether partial decompression or not */
83 	bool partial;
84 
85 	/* L: indicate several pageofs_outs or not */
86 	bool multibases;
87 
88 	/* L: whether extra buffer allocations are best-effort */
89 	bool besteffort;
90 
91 	/* A: compressed bvecs (can be cached or inplaced pages) */
92 	struct z_erofs_bvec compressed_bvecs[];
93 };
94 
95 /* the end of a chain of pclusters */
96 #define Z_EROFS_PCLUSTER_TAIL           ((void *) 0x700 + POISON_POINTER_DELTA)
97 #define Z_EROFS_PCLUSTER_NIL            (NULL)
98 
99 struct z_erofs_decompressqueue {
100 	struct super_block *sb;
101 	atomic_t pending_bios;
102 	z_erofs_next_pcluster_t head;
103 
104 	union {
105 		struct completion done;
106 		struct work_struct work;
107 		struct kthread_work kthread_work;
108 	} u;
109 	bool eio, sync;
110 };
111 
z_erofs_is_inline_pcluster(struct z_erofs_pcluster * pcl)112 static inline bool z_erofs_is_inline_pcluster(struct z_erofs_pcluster *pcl)
113 {
114 	return !pcl->index;
115 }
116 
z_erofs_pclusterpages(struct z_erofs_pcluster * pcl)117 static inline unsigned int z_erofs_pclusterpages(struct z_erofs_pcluster *pcl)
118 {
119 	return PAGE_ALIGN(pcl->pclustersize) >> PAGE_SHIFT;
120 }
121 
erofs_folio_is_managed(struct erofs_sb_info * sbi,struct folio * fo)122 static bool erofs_folio_is_managed(struct erofs_sb_info *sbi, struct folio *fo)
123 {
124 	return fo->mapping == MNGD_MAPPING(sbi);
125 }
126 
127 #define Z_EROFS_ONSTACK_PAGES		32
128 
129 /*
130  * since pclustersize is variable for big pcluster feature, introduce slab
131  * pools implementation for different pcluster sizes.
132  */
133 struct z_erofs_pcluster_slab {
134 	struct kmem_cache *slab;
135 	unsigned int maxpages;
136 	char name[48];
137 };
138 
139 #define _PCLP(n) { .maxpages = n }
140 
141 static struct z_erofs_pcluster_slab pcluster_pool[] __read_mostly = {
142 	_PCLP(1), _PCLP(4), _PCLP(16), _PCLP(64), _PCLP(128),
143 	_PCLP(Z_EROFS_PCLUSTER_MAX_PAGES)
144 };
145 
146 struct z_erofs_bvec_iter {
147 	struct page *bvpage;
148 	struct z_erofs_bvset *bvset;
149 	unsigned int nr, cur;
150 };
151 
z_erofs_bvec_iter_end(struct z_erofs_bvec_iter * iter)152 static struct page *z_erofs_bvec_iter_end(struct z_erofs_bvec_iter *iter)
153 {
154 	if (iter->bvpage)
155 		kunmap_local(iter->bvset);
156 	return iter->bvpage;
157 }
158 
z_erofs_bvset_flip(struct z_erofs_bvec_iter * iter)159 static struct page *z_erofs_bvset_flip(struct z_erofs_bvec_iter *iter)
160 {
161 	unsigned long base = (unsigned long)((struct z_erofs_bvset *)0)->bvec;
162 	/* have to access nextpage in advance, otherwise it will be unmapped */
163 	struct page *nextpage = iter->bvset->nextpage;
164 	struct page *oldpage;
165 
166 	DBG_BUGON(!nextpage);
167 	oldpage = z_erofs_bvec_iter_end(iter);
168 	iter->bvpage = nextpage;
169 	iter->bvset = kmap_local_page(nextpage);
170 	iter->nr = (PAGE_SIZE - base) / sizeof(struct z_erofs_bvec);
171 	iter->cur = 0;
172 	return oldpage;
173 }
174 
z_erofs_bvec_iter_begin(struct z_erofs_bvec_iter * iter,struct z_erofs_bvset_inline * bvset,unsigned int bootstrap_nr,unsigned int cur)175 static void z_erofs_bvec_iter_begin(struct z_erofs_bvec_iter *iter,
176 				    struct z_erofs_bvset_inline *bvset,
177 				    unsigned int bootstrap_nr,
178 				    unsigned int cur)
179 {
180 	*iter = (struct z_erofs_bvec_iter) {
181 		.nr = bootstrap_nr,
182 		.bvset = (struct z_erofs_bvset *)bvset,
183 	};
184 
185 	while (cur > iter->nr) {
186 		cur -= iter->nr;
187 		z_erofs_bvset_flip(iter);
188 	}
189 	iter->cur = cur;
190 }
191 
z_erofs_bvec_enqueue(struct z_erofs_bvec_iter * iter,struct z_erofs_bvec * bvec,struct page ** candidate_bvpage,struct page ** pagepool)192 static int z_erofs_bvec_enqueue(struct z_erofs_bvec_iter *iter,
193 				struct z_erofs_bvec *bvec,
194 				struct page **candidate_bvpage,
195 				struct page **pagepool)
196 {
197 	if (iter->cur >= iter->nr) {
198 		struct page *nextpage = *candidate_bvpage;
199 
200 		if (!nextpage) {
201 			nextpage = __erofs_allocpage(pagepool, GFP_KERNEL,
202 					true);
203 			if (!nextpage)
204 				return -ENOMEM;
205 			set_page_private(nextpage, Z_EROFS_SHORTLIVED_PAGE);
206 		}
207 		DBG_BUGON(iter->bvset->nextpage);
208 		iter->bvset->nextpage = nextpage;
209 		z_erofs_bvset_flip(iter);
210 
211 		iter->bvset->nextpage = NULL;
212 		*candidate_bvpage = NULL;
213 	}
214 	iter->bvset->bvec[iter->cur++] = *bvec;
215 	return 0;
216 }
217 
z_erofs_bvec_dequeue(struct z_erofs_bvec_iter * iter,struct z_erofs_bvec * bvec,struct page ** old_bvpage)218 static void z_erofs_bvec_dequeue(struct z_erofs_bvec_iter *iter,
219 				 struct z_erofs_bvec *bvec,
220 				 struct page **old_bvpage)
221 {
222 	if (iter->cur == iter->nr)
223 		*old_bvpage = z_erofs_bvset_flip(iter);
224 	else
225 		*old_bvpage = NULL;
226 	*bvec = iter->bvset->bvec[iter->cur++];
227 }
228 
z_erofs_destroy_pcluster_pool(void)229 static void z_erofs_destroy_pcluster_pool(void)
230 {
231 	int i;
232 
233 	for (i = 0; i < ARRAY_SIZE(pcluster_pool); ++i) {
234 		if (!pcluster_pool[i].slab)
235 			continue;
236 		kmem_cache_destroy(pcluster_pool[i].slab);
237 		pcluster_pool[i].slab = NULL;
238 	}
239 }
240 
z_erofs_create_pcluster_pool(void)241 static int z_erofs_create_pcluster_pool(void)
242 {
243 	struct z_erofs_pcluster_slab *pcs;
244 	struct z_erofs_pcluster *a;
245 	unsigned int size;
246 
247 	for (pcs = pcluster_pool;
248 	     pcs < pcluster_pool + ARRAY_SIZE(pcluster_pool); ++pcs) {
249 		size = struct_size(a, compressed_bvecs, pcs->maxpages);
250 
251 		sprintf(pcs->name, "erofs_pcluster-%u", pcs->maxpages);
252 		pcs->slab = kmem_cache_create(pcs->name, size, 0,
253 					      SLAB_RECLAIM_ACCOUNT, NULL);
254 		if (pcs->slab)
255 			continue;
256 
257 		z_erofs_destroy_pcluster_pool();
258 		return -ENOMEM;
259 	}
260 	return 0;
261 }
262 
z_erofs_alloc_pcluster(unsigned int size)263 static struct z_erofs_pcluster *z_erofs_alloc_pcluster(unsigned int size)
264 {
265 	unsigned int nrpages = PAGE_ALIGN(size) >> PAGE_SHIFT;
266 	struct z_erofs_pcluster_slab *pcs = pcluster_pool;
267 
268 	for (; pcs < pcluster_pool + ARRAY_SIZE(pcluster_pool); ++pcs) {
269 		struct z_erofs_pcluster *pcl;
270 
271 		if (nrpages > pcs->maxpages)
272 			continue;
273 
274 		pcl = kmem_cache_zalloc(pcs->slab, GFP_KERNEL);
275 		if (!pcl)
276 			return ERR_PTR(-ENOMEM);
277 		pcl->pclustersize = size;
278 		return pcl;
279 	}
280 	return ERR_PTR(-EINVAL);
281 }
282 
z_erofs_free_pcluster(struct z_erofs_pcluster * pcl)283 static void z_erofs_free_pcluster(struct z_erofs_pcluster *pcl)
284 {
285 	unsigned int pclusterpages = z_erofs_pclusterpages(pcl);
286 	int i;
287 
288 	for (i = 0; i < ARRAY_SIZE(pcluster_pool); ++i) {
289 		struct z_erofs_pcluster_slab *pcs = pcluster_pool + i;
290 
291 		if (pclusterpages > pcs->maxpages)
292 			continue;
293 
294 		kmem_cache_free(pcs->slab, pcl);
295 		return;
296 	}
297 	DBG_BUGON(1);
298 }
299 
300 static struct workqueue_struct *z_erofs_workqueue __read_mostly;
301 
302 #ifdef CONFIG_EROFS_FS_PCPU_KTHREAD
303 static struct kthread_worker __rcu **z_erofs_pcpu_workers;
304 
erofs_destroy_percpu_workers(void)305 static void erofs_destroy_percpu_workers(void)
306 {
307 	struct kthread_worker *worker;
308 	unsigned int cpu;
309 
310 	for_each_possible_cpu(cpu) {
311 		worker = rcu_dereference_protected(
312 					z_erofs_pcpu_workers[cpu], 1);
313 		rcu_assign_pointer(z_erofs_pcpu_workers[cpu], NULL);
314 		if (worker)
315 			kthread_destroy_worker(worker);
316 	}
317 	kfree(z_erofs_pcpu_workers);
318 }
319 
erofs_init_percpu_worker(int cpu)320 static struct kthread_worker *erofs_init_percpu_worker(int cpu)
321 {
322 	struct kthread_worker *worker =
323 		kthread_create_worker_on_cpu(cpu, 0, "erofs_worker/%u", cpu);
324 
325 	if (IS_ERR(worker))
326 		return worker;
327 	if (IS_ENABLED(CONFIG_EROFS_FS_PCPU_KTHREAD_HIPRI))
328 		sched_set_fifo_low(worker->task);
329 	return worker;
330 }
331 
erofs_init_percpu_workers(void)332 static int erofs_init_percpu_workers(void)
333 {
334 	struct kthread_worker *worker;
335 	unsigned int cpu;
336 
337 	z_erofs_pcpu_workers = kcalloc(num_possible_cpus(),
338 			sizeof(struct kthread_worker *), GFP_ATOMIC);
339 	if (!z_erofs_pcpu_workers)
340 		return -ENOMEM;
341 
342 	for_each_online_cpu(cpu) {	/* could miss cpu{off,on}line? */
343 		worker = erofs_init_percpu_worker(cpu);
344 		if (!IS_ERR(worker))
345 			rcu_assign_pointer(z_erofs_pcpu_workers[cpu], worker);
346 	}
347 	return 0;
348 }
349 #else
erofs_destroy_percpu_workers(void)350 static inline void erofs_destroy_percpu_workers(void) {}
erofs_init_percpu_workers(void)351 static inline int erofs_init_percpu_workers(void) { return 0; }
352 #endif
353 
354 #if defined(CONFIG_HOTPLUG_CPU) && defined(CONFIG_EROFS_FS_PCPU_KTHREAD)
355 static DEFINE_SPINLOCK(z_erofs_pcpu_worker_lock);
356 static enum cpuhp_state erofs_cpuhp_state;
357 
erofs_cpu_online(unsigned int cpu)358 static int erofs_cpu_online(unsigned int cpu)
359 {
360 	struct kthread_worker *worker, *old;
361 
362 	worker = erofs_init_percpu_worker(cpu);
363 	if (IS_ERR(worker))
364 		return PTR_ERR(worker);
365 
366 	spin_lock(&z_erofs_pcpu_worker_lock);
367 	old = rcu_dereference_protected(z_erofs_pcpu_workers[cpu],
368 			lockdep_is_held(&z_erofs_pcpu_worker_lock));
369 	if (!old)
370 		rcu_assign_pointer(z_erofs_pcpu_workers[cpu], worker);
371 	spin_unlock(&z_erofs_pcpu_worker_lock);
372 	if (old)
373 		kthread_destroy_worker(worker);
374 	return 0;
375 }
376 
erofs_cpu_offline(unsigned int cpu)377 static int erofs_cpu_offline(unsigned int cpu)
378 {
379 	struct kthread_worker *worker;
380 
381 	spin_lock(&z_erofs_pcpu_worker_lock);
382 	worker = rcu_dereference_protected(z_erofs_pcpu_workers[cpu],
383 			lockdep_is_held(&z_erofs_pcpu_worker_lock));
384 	rcu_assign_pointer(z_erofs_pcpu_workers[cpu], NULL);
385 	spin_unlock(&z_erofs_pcpu_worker_lock);
386 
387 	synchronize_rcu();
388 	if (worker)
389 		kthread_destroy_worker(worker);
390 	return 0;
391 }
392 
erofs_cpu_hotplug_init(void)393 static int erofs_cpu_hotplug_init(void)
394 {
395 	int state;
396 
397 	state = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
398 			"fs/erofs:online", erofs_cpu_online, erofs_cpu_offline);
399 	if (state < 0)
400 		return state;
401 
402 	erofs_cpuhp_state = state;
403 	return 0;
404 }
405 
erofs_cpu_hotplug_destroy(void)406 static void erofs_cpu_hotplug_destroy(void)
407 {
408 	if (erofs_cpuhp_state)
409 		cpuhp_remove_state_nocalls(erofs_cpuhp_state);
410 }
411 #else /* !CONFIG_HOTPLUG_CPU || !CONFIG_EROFS_FS_PCPU_KTHREAD */
erofs_cpu_hotplug_init(void)412 static inline int erofs_cpu_hotplug_init(void) { return 0; }
erofs_cpu_hotplug_destroy(void)413 static inline void erofs_cpu_hotplug_destroy(void) {}
414 #endif
415 
z_erofs_exit_subsystem(void)416 void z_erofs_exit_subsystem(void)
417 {
418 	erofs_cpu_hotplug_destroy();
419 	erofs_destroy_percpu_workers();
420 	destroy_workqueue(z_erofs_workqueue);
421 	z_erofs_destroy_pcluster_pool();
422 	z_erofs_exit_decompressor();
423 }
424 
z_erofs_init_subsystem(void)425 int __init z_erofs_init_subsystem(void)
426 {
427 	int err = z_erofs_init_decompressor();
428 
429 	if (err)
430 		goto err_decompressor;
431 
432 	err = z_erofs_create_pcluster_pool();
433 	if (err)
434 		goto err_pcluster_pool;
435 
436 	z_erofs_workqueue = alloc_workqueue("erofs_worker",
437 			WQ_UNBOUND | WQ_HIGHPRI, num_possible_cpus());
438 	if (!z_erofs_workqueue) {
439 		err = -ENOMEM;
440 		goto err_workqueue_init;
441 	}
442 
443 	err = erofs_init_percpu_workers();
444 	if (err)
445 		goto err_pcpu_worker;
446 
447 	err = erofs_cpu_hotplug_init();
448 	if (err < 0)
449 		goto err_cpuhp_init;
450 	return err;
451 
452 err_cpuhp_init:
453 	erofs_destroy_percpu_workers();
454 err_pcpu_worker:
455 	destroy_workqueue(z_erofs_workqueue);
456 err_workqueue_init:
457 	z_erofs_destroy_pcluster_pool();
458 err_pcluster_pool:
459 	z_erofs_exit_decompressor();
460 err_decompressor:
461 	return err;
462 }
463 
464 enum z_erofs_pclustermode {
465 	Z_EROFS_PCLUSTER_INFLIGHT,
466 	/*
467 	 * a weak form of Z_EROFS_PCLUSTER_FOLLOWED, the difference is that it
468 	 * could be dispatched into bypass queue later due to uptodated managed
469 	 * pages. All related online pages cannot be reused for inplace I/O (or
470 	 * bvpage) since it can be directly decoded without I/O submission.
471 	 */
472 	Z_EROFS_PCLUSTER_FOLLOWED_NOINPLACE,
473 	/*
474 	 * The pcluster was just linked to a decompression chain by us.  It can
475 	 * also be linked with the remaining pclusters, which means if the
476 	 * processing page is the tail page of a pcluster, this pcluster can
477 	 * safely use the whole page (since the previous pcluster is within the
478 	 * same chain) for in-place I/O, as illustrated below:
479 	 *  ___________________________________________________
480 	 * |  tail (partial) page  |    head (partial) page    |
481 	 * |  (of the current pcl) |   (of the previous pcl)   |
482 	 * |___PCLUSTER_FOLLOWED___|_____PCLUSTER_FOLLOWED_____|
483 	 *
484 	 * [  (*) the page above can be used as inplace I/O.   ]
485 	 */
486 	Z_EROFS_PCLUSTER_FOLLOWED,
487 };
488 
489 struct z_erofs_decompress_frontend {
490 	struct inode *const inode;
491 	struct erofs_map_blocks map;
492 	struct z_erofs_bvec_iter biter;
493 
494 	struct page *pagepool;
495 	struct page *candidate_bvpage;
496 	struct z_erofs_pcluster *pcl;
497 	z_erofs_next_pcluster_t owned_head;
498 	enum z_erofs_pclustermode mode;
499 
500 	erofs_off_t headoffset;
501 
502 	/* a pointer used to pick up inplace I/O pages */
503 	unsigned int icur;
504 };
505 
506 #define DECOMPRESS_FRONTEND_INIT(__i) { \
507 	.inode = __i, .owned_head = Z_EROFS_PCLUSTER_TAIL, \
508 	.mode = Z_EROFS_PCLUSTER_FOLLOWED }
509 
z_erofs_should_alloc_cache(struct z_erofs_decompress_frontend * fe)510 static bool z_erofs_should_alloc_cache(struct z_erofs_decompress_frontend *fe)
511 {
512 	unsigned int cachestrategy = EROFS_I_SB(fe->inode)->opt.cache_strategy;
513 
514 	if (cachestrategy <= EROFS_ZIP_CACHE_DISABLED)
515 		return false;
516 
517 	if (!(fe->map.m_flags & EROFS_MAP_FULL_MAPPED))
518 		return true;
519 
520 	if (cachestrategy >= EROFS_ZIP_CACHE_READAROUND &&
521 	    fe->map.m_la < fe->headoffset)
522 		return true;
523 
524 	return false;
525 }
526 
z_erofs_bind_cache(struct z_erofs_decompress_frontend * fe)527 static void z_erofs_bind_cache(struct z_erofs_decompress_frontend *fe)
528 {
529 	struct address_space *mc = MNGD_MAPPING(EROFS_I_SB(fe->inode));
530 	struct z_erofs_pcluster *pcl = fe->pcl;
531 	unsigned int pclusterpages = z_erofs_pclusterpages(pcl);
532 	bool shouldalloc = z_erofs_should_alloc_cache(fe);
533 	bool standalone = true;
534 	/*
535 	 * optimistic allocation without direct reclaim since inplace I/O
536 	 * can be used if low memory otherwise.
537 	 */
538 	gfp_t gfp = (mapping_gfp_mask(mc) & ~__GFP_DIRECT_RECLAIM) |
539 			__GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN;
540 	unsigned int i;
541 
542 	if (i_blocksize(fe->inode) != PAGE_SIZE ||
543 	    fe->mode < Z_EROFS_PCLUSTER_FOLLOWED)
544 		return;
545 
546 	for (i = 0; i < pclusterpages; ++i) {
547 		struct page *page, *newpage;
548 
549 		/* Inaccurate check w/o locking to avoid unneeded lookups */
550 		if (READ_ONCE(pcl->compressed_bvecs[i].page))
551 			continue;
552 
553 		page = find_get_page(mc, pcl->index + i);
554 		if (!page) {
555 			/* I/O is needed, no possible to decompress directly */
556 			standalone = false;
557 			if (!shouldalloc)
558 				continue;
559 
560 			/*
561 			 * Try cached I/O if allocation succeeds or fallback to
562 			 * in-place I/O instead to avoid any direct reclaim.
563 			 */
564 			newpage = erofs_allocpage(&fe->pagepool, gfp);
565 			if (!newpage)
566 				continue;
567 			set_page_private(newpage, Z_EROFS_PREALLOCATED_PAGE);
568 		}
569 		spin_lock(&pcl->lockref.lock);
570 		if (!pcl->compressed_bvecs[i].page) {
571 			pcl->compressed_bvecs[i].page = page ? page : newpage;
572 			spin_unlock(&pcl->lockref.lock);
573 			continue;
574 		}
575 		spin_unlock(&pcl->lockref.lock);
576 
577 		if (page)
578 			put_page(page);
579 		else if (newpage)
580 			erofs_pagepool_add(&fe->pagepool, newpage);
581 	}
582 
583 	/*
584 	 * don't do inplace I/O if all compressed pages are available in
585 	 * managed cache since it can be moved to the bypass queue instead.
586 	 */
587 	if (standalone)
588 		fe->mode = Z_EROFS_PCLUSTER_FOLLOWED_NOINPLACE;
589 }
590 
591 /* (erofs_shrinker) disconnect cached encoded data with pclusters */
erofs_try_to_free_all_cached_folios(struct erofs_sb_info * sbi,struct z_erofs_pcluster * pcl)592 static int erofs_try_to_free_all_cached_folios(struct erofs_sb_info *sbi,
593 					       struct z_erofs_pcluster *pcl)
594 {
595 	unsigned int pclusterpages = z_erofs_pclusterpages(pcl);
596 	struct folio *folio;
597 	int i;
598 
599 	DBG_BUGON(z_erofs_is_inline_pcluster(pcl));
600 	/* Each cached folio contains one page unless bs > ps is supported */
601 	for (i = 0; i < pclusterpages; ++i) {
602 		if (pcl->compressed_bvecs[i].page) {
603 			folio = page_folio(pcl->compressed_bvecs[i].page);
604 			/* Avoid reclaiming or migrating this folio */
605 			if (!folio_trylock(folio))
606 				return -EBUSY;
607 
608 			if (!erofs_folio_is_managed(sbi, folio))
609 				continue;
610 			pcl->compressed_bvecs[i].page = NULL;
611 			folio_detach_private(folio);
612 			folio_unlock(folio);
613 		}
614 	}
615 	return 0;
616 }
617 
z_erofs_cache_release_folio(struct folio * folio,gfp_t gfp)618 static bool z_erofs_cache_release_folio(struct folio *folio, gfp_t gfp)
619 {
620 	struct z_erofs_pcluster *pcl = folio_get_private(folio);
621 	struct z_erofs_bvec *bvec = pcl->compressed_bvecs;
622 	struct z_erofs_bvec *end = bvec + z_erofs_pclusterpages(pcl);
623 	bool ret;
624 
625 	if (!folio_test_private(folio))
626 		return true;
627 
628 	ret = false;
629 	spin_lock(&pcl->lockref.lock);
630 	if (pcl->lockref.count <= 0) {
631 		DBG_BUGON(z_erofs_is_inline_pcluster(pcl));
632 		for (; bvec < end; ++bvec) {
633 			if (bvec->page && page_folio(bvec->page) == folio) {
634 				bvec->page = NULL;
635 				folio_detach_private(folio);
636 				ret = true;
637 				break;
638 			}
639 		}
640 	}
641 	spin_unlock(&pcl->lockref.lock);
642 	return ret;
643 }
644 
645 /*
646  * It will be called only on inode eviction. In case that there are still some
647  * decompression requests in progress, wait with rescheduling for a bit here.
648  * An extra lock could be introduced instead but it seems unnecessary.
649  */
z_erofs_cache_invalidate_folio(struct folio * folio,size_t offset,size_t length)650 static void z_erofs_cache_invalidate_folio(struct folio *folio,
651 					   size_t offset, size_t length)
652 {
653 	const size_t stop = length + offset;
654 
655 	/* Check for potential overflow in debug mode */
656 	DBG_BUGON(stop > folio_size(folio) || stop < length);
657 
658 	if (offset == 0 && stop == folio_size(folio))
659 		while (!z_erofs_cache_release_folio(folio, 0))
660 			cond_resched();
661 }
662 
663 static const struct address_space_operations z_erofs_cache_aops = {
664 	.release_folio = z_erofs_cache_release_folio,
665 	.invalidate_folio = z_erofs_cache_invalidate_folio,
666 };
667 
erofs_init_managed_cache(struct super_block * sb)668 int erofs_init_managed_cache(struct super_block *sb)
669 {
670 	struct inode *const inode = new_inode(sb);
671 
672 	if (!inode)
673 		return -ENOMEM;
674 
675 	set_nlink(inode, 1);
676 	inode->i_size = OFFSET_MAX;
677 	inode->i_mapping->a_ops = &z_erofs_cache_aops;
678 	mapping_set_gfp_mask(inode->i_mapping, GFP_KERNEL);
679 	EROFS_SB(sb)->managed_cache = inode;
680 	return 0;
681 }
682 
683 /* callers must be with pcluster lock held */
z_erofs_attach_page(struct z_erofs_decompress_frontend * fe,struct z_erofs_bvec * bvec,bool exclusive)684 static int z_erofs_attach_page(struct z_erofs_decompress_frontend *fe,
685 			       struct z_erofs_bvec *bvec, bool exclusive)
686 {
687 	struct z_erofs_pcluster *pcl = fe->pcl;
688 	int ret;
689 
690 	if (exclusive) {
691 		/* give priority for inplaceio to use file pages first */
692 		spin_lock(&pcl->lockref.lock);
693 		while (fe->icur > 0) {
694 			if (pcl->compressed_bvecs[--fe->icur].page)
695 				continue;
696 			pcl->compressed_bvecs[fe->icur] = *bvec;
697 			spin_unlock(&pcl->lockref.lock);
698 			return 0;
699 		}
700 		spin_unlock(&pcl->lockref.lock);
701 
702 		/* otherwise, check if it can be used as a bvpage */
703 		if (fe->mode >= Z_EROFS_PCLUSTER_FOLLOWED &&
704 		    !fe->candidate_bvpage)
705 			fe->candidate_bvpage = bvec->page;
706 	}
707 	ret = z_erofs_bvec_enqueue(&fe->biter, bvec, &fe->candidate_bvpage,
708 				   &fe->pagepool);
709 	fe->pcl->vcnt += (ret >= 0);
710 	return ret;
711 }
712 
z_erofs_get_pcluster(struct z_erofs_pcluster * pcl)713 static bool z_erofs_get_pcluster(struct z_erofs_pcluster *pcl)
714 {
715 	if (lockref_get_not_zero(&pcl->lockref))
716 		return true;
717 
718 	spin_lock(&pcl->lockref.lock);
719 	if (__lockref_is_dead(&pcl->lockref)) {
720 		spin_unlock(&pcl->lockref.lock);
721 		return false;
722 	}
723 
724 	if (!pcl->lockref.count++)
725 		atomic_long_dec(&erofs_global_shrink_cnt);
726 	spin_unlock(&pcl->lockref.lock);
727 	return true;
728 }
729 
z_erofs_register_pcluster(struct z_erofs_decompress_frontend * fe)730 static int z_erofs_register_pcluster(struct z_erofs_decompress_frontend *fe)
731 {
732 	struct erofs_map_blocks *map = &fe->map;
733 	struct super_block *sb = fe->inode->i_sb;
734 	struct erofs_sb_info *sbi = EROFS_SB(sb);
735 	bool ztailpacking = map->m_flags & EROFS_MAP_META;
736 	struct z_erofs_pcluster *pcl, *pre;
737 	int err;
738 
739 	if (!(map->m_flags & EROFS_MAP_ENCODED) ||
740 	    (!ztailpacking && !erofs_blknr(sb, map->m_pa))) {
741 		DBG_BUGON(1);
742 		return -EFSCORRUPTED;
743 	}
744 
745 	/* no available pcluster, let's allocate one */
746 	pcl = z_erofs_alloc_pcluster(map->m_plen);
747 	if (IS_ERR(pcl))
748 		return PTR_ERR(pcl);
749 
750 	spin_lock_init(&pcl->lockref.lock);
751 	pcl->lockref.count = 1;		/* one ref for this request */
752 	pcl->algorithmformat = map->m_algorithmformat;
753 	pcl->length = 0;
754 	pcl->partial = true;
755 
756 	/* new pclusters should be claimed as type 1, primary and followed */
757 	pcl->next = fe->owned_head;
758 	pcl->pageofs_out = map->m_la & ~PAGE_MASK;
759 	fe->mode = Z_EROFS_PCLUSTER_FOLLOWED;
760 
761 	/*
762 	 * lock all primary followed works before visible to others
763 	 * and mutex_trylock *never* fails for a new pcluster.
764 	 */
765 	mutex_init(&pcl->lock);
766 	DBG_BUGON(!mutex_trylock(&pcl->lock));
767 
768 	if (ztailpacking) {
769 		pcl->index = 0;		/* which indicates ztailpacking */
770 	} else {
771 		pcl->index = erofs_blknr(sb, map->m_pa);
772 		while (1) {
773 			xa_lock(&sbi->managed_pslots);
774 			pre = __xa_cmpxchg(&sbi->managed_pslots, pcl->index,
775 					   NULL, pcl, GFP_KERNEL);
776 			if (!pre || xa_is_err(pre) || z_erofs_get_pcluster(pre)) {
777 				xa_unlock(&sbi->managed_pslots);
778 				break;
779 			}
780 			/* try to legitimize the current in-tree one */
781 			xa_unlock(&sbi->managed_pslots);
782 			cond_resched();
783 		}
784 		if (xa_is_err(pre)) {
785 			err = xa_err(pre);
786 			goto err_out;
787 		} else if (pre) {
788 			fe->pcl = pre;
789 			err = -EEXIST;
790 			goto err_out;
791 		}
792 	}
793 	fe->owned_head = &pcl->next;
794 	fe->pcl = pcl;
795 	return 0;
796 
797 err_out:
798 	mutex_unlock(&pcl->lock);
799 	z_erofs_free_pcluster(pcl);
800 	return err;
801 }
802 
z_erofs_pcluster_begin(struct z_erofs_decompress_frontend * fe)803 static int z_erofs_pcluster_begin(struct z_erofs_decompress_frontend *fe)
804 {
805 	struct erofs_map_blocks *map = &fe->map;
806 	struct super_block *sb = fe->inode->i_sb;
807 	erofs_blk_t blknr = erofs_blknr(sb, map->m_pa);
808 	struct z_erofs_pcluster *pcl = NULL;
809 	int ret;
810 
811 	DBG_BUGON(fe->pcl);
812 	/* must be Z_EROFS_PCLUSTER_TAIL or pointed to previous pcluster */
813 	DBG_BUGON(fe->owned_head == Z_EROFS_PCLUSTER_NIL);
814 
815 	if (!(map->m_flags & EROFS_MAP_META)) {
816 		while (1) {
817 			rcu_read_lock();
818 			pcl = xa_load(&EROFS_SB(sb)->managed_pslots, blknr);
819 			if (!pcl || z_erofs_get_pcluster(pcl)) {
820 				DBG_BUGON(pcl && blknr != pcl->index);
821 				rcu_read_unlock();
822 				break;
823 			}
824 			rcu_read_unlock();
825 		}
826 	} else if ((map->m_pa & ~PAGE_MASK) + map->m_plen > PAGE_SIZE) {
827 		DBG_BUGON(1);
828 		return -EFSCORRUPTED;
829 	}
830 
831 	if (pcl) {
832 		fe->pcl = pcl;
833 		ret = -EEXIST;
834 	} else {
835 		ret = z_erofs_register_pcluster(fe);
836 	}
837 
838 	if (ret == -EEXIST) {
839 		mutex_lock(&fe->pcl->lock);
840 		/* check if this pcluster hasn't been linked into any chain. */
841 		if (cmpxchg(&fe->pcl->next, Z_EROFS_PCLUSTER_NIL,
842 			    fe->owned_head) == Z_EROFS_PCLUSTER_NIL) {
843 			/* .. so it can be attached to our submission chain */
844 			fe->owned_head = &fe->pcl->next;
845 			fe->mode = Z_EROFS_PCLUSTER_FOLLOWED;
846 		} else {	/* otherwise, it belongs to an inflight chain */
847 			fe->mode = Z_EROFS_PCLUSTER_INFLIGHT;
848 		}
849 	} else if (ret) {
850 		return ret;
851 	}
852 
853 	z_erofs_bvec_iter_begin(&fe->biter, &fe->pcl->bvset,
854 				Z_EROFS_INLINE_BVECS, fe->pcl->vcnt);
855 	if (!z_erofs_is_inline_pcluster(fe->pcl)) {
856 		/* bind cache first when cached decompression is preferred */
857 		z_erofs_bind_cache(fe);
858 	} else {
859 		void *mptr;
860 
861 		mptr = erofs_read_metabuf(&map->buf, sb, map->m_pa, EROFS_NO_KMAP);
862 		if (IS_ERR(mptr)) {
863 			ret = PTR_ERR(mptr);
864 			erofs_err(sb, "failed to get inline data %d", ret);
865 			return ret;
866 		}
867 		get_page(map->buf.page);
868 		WRITE_ONCE(fe->pcl->compressed_bvecs[0].page, map->buf.page);
869 		fe->pcl->pageofs_in = map->m_pa & ~PAGE_MASK;
870 		fe->mode = Z_EROFS_PCLUSTER_FOLLOWED_NOINPLACE;
871 	}
872 	/* file-backed inplace I/O pages are traversed in reverse order */
873 	fe->icur = z_erofs_pclusterpages(fe->pcl);
874 	return 0;
875 }
876 
877 /*
878  * keep in mind that no referenced pclusters will be freed
879  * only after a RCU grace period.
880  */
z_erofs_rcu_callback(struct rcu_head * head)881 static void z_erofs_rcu_callback(struct rcu_head *head)
882 {
883 	z_erofs_free_pcluster(container_of(head,
884 			struct z_erofs_pcluster, rcu));
885 }
886 
__erofs_try_to_release_pcluster(struct erofs_sb_info * sbi,struct z_erofs_pcluster * pcl)887 static bool __erofs_try_to_release_pcluster(struct erofs_sb_info *sbi,
888 					  struct z_erofs_pcluster *pcl)
889 {
890 	if (pcl->lockref.count)
891 		return false;
892 
893 	/*
894 	 * Note that all cached folios should be detached before deleted from
895 	 * the XArray.  Otherwise some folios could be still attached to the
896 	 * orphan old pcluster when the new one is available in the tree.
897 	 */
898 	if (erofs_try_to_free_all_cached_folios(sbi, pcl))
899 		return false;
900 
901 	/*
902 	 * It's impossible to fail after the pcluster is freezed, but in order
903 	 * to avoid some race conditions, add a DBG_BUGON to observe this.
904 	 */
905 	DBG_BUGON(__xa_erase(&sbi->managed_pslots, pcl->index) != pcl);
906 
907 	lockref_mark_dead(&pcl->lockref);
908 	return true;
909 }
910 
erofs_try_to_release_pcluster(struct erofs_sb_info * sbi,struct z_erofs_pcluster * pcl)911 static bool erofs_try_to_release_pcluster(struct erofs_sb_info *sbi,
912 					  struct z_erofs_pcluster *pcl)
913 {
914 	bool free;
915 
916 	spin_lock(&pcl->lockref.lock);
917 	free = __erofs_try_to_release_pcluster(sbi, pcl);
918 	spin_unlock(&pcl->lockref.lock);
919 	if (free) {
920 		atomic_long_dec(&erofs_global_shrink_cnt);
921 		call_rcu(&pcl->rcu, z_erofs_rcu_callback);
922 	}
923 	return free;
924 }
925 
z_erofs_shrink_scan(struct erofs_sb_info * sbi,unsigned long nr_shrink)926 unsigned long z_erofs_shrink_scan(struct erofs_sb_info *sbi,
927 				  unsigned long nr_shrink)
928 {
929 	struct z_erofs_pcluster *pcl;
930 	unsigned int freed = 0;
931 	unsigned long index;
932 
933 	xa_lock(&sbi->managed_pslots);
934 	xa_for_each(&sbi->managed_pslots, index, pcl) {
935 		/* try to shrink each valid pcluster */
936 		if (!erofs_try_to_release_pcluster(sbi, pcl))
937 			continue;
938 		xa_unlock(&sbi->managed_pslots);
939 
940 		++freed;
941 		if (!--nr_shrink)
942 			return freed;
943 		xa_lock(&sbi->managed_pslots);
944 	}
945 	xa_unlock(&sbi->managed_pslots);
946 	return freed;
947 }
948 
z_erofs_put_pcluster(struct erofs_sb_info * sbi,struct z_erofs_pcluster * pcl,bool try_free)949 static void z_erofs_put_pcluster(struct erofs_sb_info *sbi,
950 		struct z_erofs_pcluster *pcl, bool try_free)
951 {
952 	bool free = false;
953 
954 	if (lockref_put_or_lock(&pcl->lockref))
955 		return;
956 
957 	DBG_BUGON(__lockref_is_dead(&pcl->lockref));
958 	if (!--pcl->lockref.count) {
959 		if (try_free && xa_trylock(&sbi->managed_pslots)) {
960 			free = __erofs_try_to_release_pcluster(sbi, pcl);
961 			xa_unlock(&sbi->managed_pslots);
962 		}
963 		atomic_long_add(!free, &erofs_global_shrink_cnt);
964 	}
965 	spin_unlock(&pcl->lockref.lock);
966 	if (free)
967 		call_rcu(&pcl->rcu, z_erofs_rcu_callback);
968 }
969 
z_erofs_pcluster_end(struct z_erofs_decompress_frontend * fe)970 static void z_erofs_pcluster_end(struct z_erofs_decompress_frontend *fe)
971 {
972 	struct z_erofs_pcluster *pcl = fe->pcl;
973 
974 	if (!pcl)
975 		return;
976 
977 	z_erofs_bvec_iter_end(&fe->biter);
978 	mutex_unlock(&pcl->lock);
979 
980 	if (fe->candidate_bvpage)
981 		fe->candidate_bvpage = NULL;
982 
983 	/*
984 	 * if all pending pages are added, don't hold its reference
985 	 * any longer if the pcluster isn't hosted by ourselves.
986 	 */
987 	if (fe->mode < Z_EROFS_PCLUSTER_FOLLOWED_NOINPLACE)
988 		z_erofs_put_pcluster(EROFS_I_SB(fe->inode), pcl, false);
989 
990 	fe->pcl = NULL;
991 }
992 
z_erofs_read_fragment(struct super_block * sb,struct folio * folio,unsigned int cur,unsigned int end,erofs_off_t pos)993 static int z_erofs_read_fragment(struct super_block *sb, struct folio *folio,
994 			unsigned int cur, unsigned int end, erofs_off_t pos)
995 {
996 	struct inode *packed_inode = EROFS_SB(sb)->packed_inode;
997 	struct erofs_buf buf = __EROFS_BUF_INITIALIZER;
998 	unsigned int cnt;
999 	u8 *src;
1000 
1001 	if (!packed_inode)
1002 		return -EFSCORRUPTED;
1003 
1004 	buf.mapping = packed_inode->i_mapping;
1005 	for (; cur < end; cur += cnt, pos += cnt) {
1006 		cnt = min(end - cur, sb->s_blocksize - erofs_blkoff(sb, pos));
1007 		src = erofs_bread(&buf, pos, EROFS_KMAP);
1008 		if (IS_ERR(src)) {
1009 			erofs_put_metabuf(&buf);
1010 			return PTR_ERR(src);
1011 		}
1012 		memcpy_to_folio(folio, cur, src, cnt);
1013 	}
1014 	erofs_put_metabuf(&buf);
1015 	return 0;
1016 }
1017 
z_erofs_scan_folio(struct z_erofs_decompress_frontend * f,struct folio * folio,bool ra)1018 static int z_erofs_scan_folio(struct z_erofs_decompress_frontend *f,
1019 			      struct folio *folio, bool ra)
1020 {
1021 	struct inode *const inode = f->inode;
1022 	struct erofs_map_blocks *const map = &f->map;
1023 	const loff_t offset = folio_pos(folio);
1024 	const unsigned int bs = i_blocksize(inode);
1025 	unsigned int end = folio_size(folio), split = 0, cur, pgs;
1026 	bool tight, excl;
1027 	int err = 0;
1028 
1029 	tight = (bs == PAGE_SIZE);
1030 	erofs_onlinefolio_init(folio);
1031 	do {
1032 		if (offset + end - 1 < map->m_la ||
1033 		    offset + end - 1 >= map->m_la + map->m_llen) {
1034 			z_erofs_pcluster_end(f);
1035 			map->m_la = offset + end - 1;
1036 			map->m_llen = 0;
1037 			err = z_erofs_map_blocks_iter(inode, map, 0);
1038 			if (err)
1039 				break;
1040 		}
1041 
1042 		cur = offset > map->m_la ? 0 : map->m_la - offset;
1043 		pgs = round_down(cur, PAGE_SIZE);
1044 		/* bump split parts first to avoid several separate cases */
1045 		++split;
1046 
1047 		if (!(map->m_flags & EROFS_MAP_MAPPED)) {
1048 			folio_zero_segment(folio, cur, end);
1049 			tight = false;
1050 		} else if (map->m_flags & EROFS_MAP_FRAGMENT) {
1051 			erofs_off_t fpos = offset + cur - map->m_la;
1052 
1053 			err = z_erofs_read_fragment(inode->i_sb, folio, cur,
1054 					cur + min(map->m_llen - fpos, end - cur),
1055 					EROFS_I(inode)->z_fragmentoff + fpos);
1056 			if (err)
1057 				break;
1058 			tight = false;
1059 		} else {
1060 			if (!f->pcl) {
1061 				err = z_erofs_pcluster_begin(f);
1062 				if (err)
1063 					break;
1064 				f->pcl->besteffort |= !ra;
1065 			}
1066 
1067 			pgs = round_down(end - 1, PAGE_SIZE);
1068 			/*
1069 			 * Ensure this partial page belongs to this submit chain
1070 			 * rather than other concurrent submit chains or
1071 			 * noio(bypass) chains since those chains are handled
1072 			 * asynchronously thus it cannot be used for inplace I/O
1073 			 * or bvpage (should be processed in the strict order.)
1074 			 */
1075 			tight &= (f->mode >= Z_EROFS_PCLUSTER_FOLLOWED);
1076 			excl = false;
1077 			if (cur <= pgs) {
1078 				excl = (split <= 1) || tight;
1079 				cur = pgs;
1080 			}
1081 
1082 			err = z_erofs_attach_page(f, &((struct z_erofs_bvec) {
1083 				.page = folio_page(folio, pgs >> PAGE_SHIFT),
1084 				.offset = offset + pgs - map->m_la,
1085 				.end = end - pgs, }), excl);
1086 			if (err)
1087 				break;
1088 
1089 			erofs_onlinefolio_split(folio);
1090 			if (f->pcl->pageofs_out != (map->m_la & ~PAGE_MASK))
1091 				f->pcl->multibases = true;
1092 			if (f->pcl->length < offset + end - map->m_la) {
1093 				f->pcl->length = offset + end - map->m_la;
1094 				f->pcl->pageofs_out = map->m_la & ~PAGE_MASK;
1095 			}
1096 			if ((map->m_flags & EROFS_MAP_FULL_MAPPED) &&
1097 			    !(map->m_flags & EROFS_MAP_PARTIAL_REF) &&
1098 			    f->pcl->length == map->m_llen)
1099 				f->pcl->partial = false;
1100 		}
1101 		/* shorten the remaining extent to update progress */
1102 		map->m_llen = offset + cur - map->m_la;
1103 		map->m_flags &= ~EROFS_MAP_FULL_MAPPED;
1104 		if (cur <= pgs) {
1105 			split = cur < pgs;
1106 			tight = (bs == PAGE_SIZE);
1107 		}
1108 	} while ((end = cur) > 0);
1109 	erofs_onlinefolio_end(folio, err);
1110 	return err;
1111 }
1112 
z_erofs_is_sync_decompress(struct erofs_sb_info * sbi,unsigned int readahead_pages)1113 static bool z_erofs_is_sync_decompress(struct erofs_sb_info *sbi,
1114 				       unsigned int readahead_pages)
1115 {
1116 	/* auto: enable for read_folio, disable for readahead */
1117 	if ((sbi->opt.sync_decompress == EROFS_SYNC_DECOMPRESS_AUTO) &&
1118 	    !readahead_pages)
1119 		return true;
1120 
1121 	if ((sbi->opt.sync_decompress == EROFS_SYNC_DECOMPRESS_FORCE_ON) &&
1122 	    (readahead_pages <= sbi->opt.max_sync_decompress_pages))
1123 		return true;
1124 
1125 	return false;
1126 }
1127 
z_erofs_page_is_invalidated(struct page * page)1128 static bool z_erofs_page_is_invalidated(struct page *page)
1129 {
1130 	return !page_folio(page)->mapping && !z_erofs_is_shortlived_page(page);
1131 }
1132 
1133 struct z_erofs_decompress_backend {
1134 	struct page *onstack_pages[Z_EROFS_ONSTACK_PAGES];
1135 	struct super_block *sb;
1136 	struct z_erofs_pcluster *pcl;
1137 
1138 	/* pages with the longest decompressed length for deduplication */
1139 	struct page **decompressed_pages;
1140 	/* pages to keep the compressed data */
1141 	struct page **compressed_pages;
1142 
1143 	struct list_head decompressed_secondary_bvecs;
1144 	struct page **pagepool;
1145 	unsigned int onstack_used, nr_pages;
1146 };
1147 
1148 struct z_erofs_bvec_item {
1149 	struct z_erofs_bvec bvec;
1150 	struct list_head list;
1151 };
1152 
z_erofs_do_decompressed_bvec(struct z_erofs_decompress_backend * be,struct z_erofs_bvec * bvec)1153 static void z_erofs_do_decompressed_bvec(struct z_erofs_decompress_backend *be,
1154 					 struct z_erofs_bvec *bvec)
1155 {
1156 	struct z_erofs_bvec_item *item;
1157 	unsigned int pgnr;
1158 
1159 	if (!((bvec->offset + be->pcl->pageofs_out) & ~PAGE_MASK) &&
1160 	    (bvec->end == PAGE_SIZE ||
1161 	     bvec->offset + bvec->end == be->pcl->length)) {
1162 		pgnr = (bvec->offset + be->pcl->pageofs_out) >> PAGE_SHIFT;
1163 		DBG_BUGON(pgnr >= be->nr_pages);
1164 		if (!be->decompressed_pages[pgnr]) {
1165 			be->decompressed_pages[pgnr] = bvec->page;
1166 			return;
1167 		}
1168 	}
1169 
1170 	/* (cold path) one pcluster is requested multiple times */
1171 	item = kmalloc(sizeof(*item), GFP_KERNEL | __GFP_NOFAIL);
1172 	item->bvec = *bvec;
1173 	list_add(&item->list, &be->decompressed_secondary_bvecs);
1174 }
1175 
z_erofs_fill_other_copies(struct z_erofs_decompress_backend * be,int err)1176 static void z_erofs_fill_other_copies(struct z_erofs_decompress_backend *be,
1177 				      int err)
1178 {
1179 	unsigned int off0 = be->pcl->pageofs_out;
1180 	struct list_head *p, *n;
1181 
1182 	list_for_each_safe(p, n, &be->decompressed_secondary_bvecs) {
1183 		struct z_erofs_bvec_item *bvi;
1184 		unsigned int end, cur;
1185 		void *dst, *src;
1186 
1187 		bvi = container_of(p, struct z_erofs_bvec_item, list);
1188 		cur = bvi->bvec.offset < 0 ? -bvi->bvec.offset : 0;
1189 		end = min_t(unsigned int, be->pcl->length - bvi->bvec.offset,
1190 			    bvi->bvec.end);
1191 		dst = kmap_local_page(bvi->bvec.page);
1192 		while (cur < end) {
1193 			unsigned int pgnr, scur, len;
1194 
1195 			pgnr = (bvi->bvec.offset + cur + off0) >> PAGE_SHIFT;
1196 			DBG_BUGON(pgnr >= be->nr_pages);
1197 
1198 			scur = bvi->bvec.offset + cur -
1199 					((pgnr << PAGE_SHIFT) - off0);
1200 			len = min_t(unsigned int, end - cur, PAGE_SIZE - scur);
1201 			if (!be->decompressed_pages[pgnr]) {
1202 				err = -EFSCORRUPTED;
1203 				cur += len;
1204 				continue;
1205 			}
1206 			src = kmap_local_page(be->decompressed_pages[pgnr]);
1207 			memcpy(dst + cur, src + scur, len);
1208 			kunmap_local(src);
1209 			cur += len;
1210 		}
1211 		kunmap_local(dst);
1212 		erofs_onlinefolio_end(page_folio(bvi->bvec.page), err);
1213 		list_del(p);
1214 		kfree(bvi);
1215 	}
1216 }
1217 
z_erofs_parse_out_bvecs(struct z_erofs_decompress_backend * be)1218 static void z_erofs_parse_out_bvecs(struct z_erofs_decompress_backend *be)
1219 {
1220 	struct z_erofs_pcluster *pcl = be->pcl;
1221 	struct z_erofs_bvec_iter biter;
1222 	struct page *old_bvpage;
1223 	int i;
1224 
1225 	z_erofs_bvec_iter_begin(&biter, &pcl->bvset, Z_EROFS_INLINE_BVECS, 0);
1226 	for (i = 0; i < pcl->vcnt; ++i) {
1227 		struct z_erofs_bvec bvec;
1228 
1229 		z_erofs_bvec_dequeue(&biter, &bvec, &old_bvpage);
1230 
1231 		if (old_bvpage)
1232 			z_erofs_put_shortlivedpage(be->pagepool, old_bvpage);
1233 
1234 		DBG_BUGON(z_erofs_page_is_invalidated(bvec.page));
1235 		z_erofs_do_decompressed_bvec(be, &bvec);
1236 	}
1237 
1238 	old_bvpage = z_erofs_bvec_iter_end(&biter);
1239 	if (old_bvpage)
1240 		z_erofs_put_shortlivedpage(be->pagepool, old_bvpage);
1241 }
1242 
z_erofs_parse_in_bvecs(struct z_erofs_decompress_backend * be,bool * overlapped)1243 static int z_erofs_parse_in_bvecs(struct z_erofs_decompress_backend *be,
1244 				  bool *overlapped)
1245 {
1246 	struct z_erofs_pcluster *pcl = be->pcl;
1247 	unsigned int pclusterpages = z_erofs_pclusterpages(pcl);
1248 	int i, err = 0;
1249 
1250 	*overlapped = false;
1251 	for (i = 0; i < pclusterpages; ++i) {
1252 		struct z_erofs_bvec *bvec = &pcl->compressed_bvecs[i];
1253 		struct page *page = bvec->page;
1254 
1255 		/* compressed data ought to be valid when decompressing */
1256 		if (IS_ERR(page) || !page) {
1257 			bvec->page = NULL;	/* clear the failure reason */
1258 			err = page ? PTR_ERR(page) : -EIO;
1259 			continue;
1260 		}
1261 		be->compressed_pages[i] = page;
1262 
1263 		if (z_erofs_is_inline_pcluster(pcl) ||
1264 		    erofs_folio_is_managed(EROFS_SB(be->sb), page_folio(page))) {
1265 			if (!PageUptodate(page))
1266 				err = -EIO;
1267 			continue;
1268 		}
1269 
1270 		DBG_BUGON(z_erofs_page_is_invalidated(page));
1271 		if (z_erofs_is_shortlived_page(page))
1272 			continue;
1273 		z_erofs_do_decompressed_bvec(be, bvec);
1274 		*overlapped = true;
1275 	}
1276 	return err;
1277 }
1278 
z_erofs_decompress_pcluster(struct z_erofs_decompress_backend * be,int err)1279 static int z_erofs_decompress_pcluster(struct z_erofs_decompress_backend *be,
1280 				       int err)
1281 {
1282 	struct erofs_sb_info *const sbi = EROFS_SB(be->sb);
1283 	struct z_erofs_pcluster *pcl = be->pcl;
1284 	unsigned int pclusterpages = z_erofs_pclusterpages(pcl);
1285 	const struct z_erofs_decompressor *decomp =
1286 				z_erofs_decomp[pcl->algorithmformat];
1287 	int i, j, jtop, err2;
1288 	struct page *page;
1289 	bool overlapped;
1290 	bool try_free = true;
1291 
1292 	mutex_lock(&pcl->lock);
1293 	be->nr_pages = PAGE_ALIGN(pcl->length + pcl->pageofs_out) >> PAGE_SHIFT;
1294 
1295 	/* allocate (de)compressed page arrays if cannot be kept on stack */
1296 	be->decompressed_pages = NULL;
1297 	be->compressed_pages = NULL;
1298 	be->onstack_used = 0;
1299 	if (be->nr_pages <= Z_EROFS_ONSTACK_PAGES) {
1300 		be->decompressed_pages = be->onstack_pages;
1301 		be->onstack_used = be->nr_pages;
1302 		memset(be->decompressed_pages, 0,
1303 		       sizeof(struct page *) * be->nr_pages);
1304 	}
1305 
1306 	if (pclusterpages + be->onstack_used <= Z_EROFS_ONSTACK_PAGES)
1307 		be->compressed_pages = be->onstack_pages + be->onstack_used;
1308 
1309 	if (!be->decompressed_pages)
1310 		be->decompressed_pages =
1311 			kvcalloc(be->nr_pages, sizeof(struct page *),
1312 				 GFP_KERNEL | __GFP_NOFAIL);
1313 	if (!be->compressed_pages)
1314 		be->compressed_pages =
1315 			kvcalloc(pclusterpages, sizeof(struct page *),
1316 				 GFP_KERNEL | __GFP_NOFAIL);
1317 
1318 	z_erofs_parse_out_bvecs(be);
1319 	err2 = z_erofs_parse_in_bvecs(be, &overlapped);
1320 	if (err2)
1321 		err = err2;
1322 	if (!err)
1323 		err = decomp->decompress(&(struct z_erofs_decompress_req) {
1324 					.sb = be->sb,
1325 					.in = be->compressed_pages,
1326 					.out = be->decompressed_pages,
1327 					.pageofs_in = pcl->pageofs_in,
1328 					.pageofs_out = pcl->pageofs_out,
1329 					.inputsize = pcl->pclustersize,
1330 					.outputsize = pcl->length,
1331 					.alg = pcl->algorithmformat,
1332 					.inplace_io = overlapped,
1333 					.partial_decoding = pcl->partial,
1334 					.fillgaps = pcl->multibases,
1335 					.gfp = pcl->besteffort ? GFP_KERNEL :
1336 						GFP_NOWAIT | __GFP_NORETRY
1337 				 }, be->pagepool);
1338 
1339 	/* must handle all compressed pages before actual file pages */
1340 	if (z_erofs_is_inline_pcluster(pcl)) {
1341 		page = pcl->compressed_bvecs[0].page;
1342 		WRITE_ONCE(pcl->compressed_bvecs[0].page, NULL);
1343 		put_page(page);
1344 	} else {
1345 		/* managed folios are still left in compressed_bvecs[] */
1346 		for (i = 0; i < pclusterpages; ++i) {
1347 			page = be->compressed_pages[i];
1348 			if (!page)
1349 				continue;
1350 			if (erofs_folio_is_managed(sbi, page_folio(page))) {
1351 				try_free = false;
1352 				continue;
1353 			}
1354 			(void)z_erofs_put_shortlivedpage(be->pagepool, page);
1355 			WRITE_ONCE(pcl->compressed_bvecs[i].page, NULL);
1356 		}
1357 	}
1358 	if (be->compressed_pages < be->onstack_pages ||
1359 	    be->compressed_pages >= be->onstack_pages + Z_EROFS_ONSTACK_PAGES)
1360 		kvfree(be->compressed_pages);
1361 
1362 	jtop = 0;
1363 	z_erofs_fill_other_copies(be, err);
1364 	for (i = 0; i < be->nr_pages; ++i) {
1365 		page = be->decompressed_pages[i];
1366 		if (!page)
1367 			continue;
1368 
1369 		DBG_BUGON(z_erofs_page_is_invalidated(page));
1370 		if (!z_erofs_is_shortlived_page(page)) {
1371 			erofs_onlinefolio_end(page_folio(page), err);
1372 			continue;
1373 		}
1374 		if (pcl->algorithmformat != Z_EROFS_COMPRESSION_LZ4) {
1375 			erofs_pagepool_add(be->pagepool, page);
1376 			continue;
1377 		}
1378 		for (j = 0; j < jtop && be->decompressed_pages[j] != page; ++j)
1379 			;
1380 		if (j >= jtop)	/* this bounce page is newly detected */
1381 			be->decompressed_pages[jtop++] = page;
1382 	}
1383 	while (jtop)
1384 		erofs_pagepool_add(be->pagepool,
1385 				   be->decompressed_pages[--jtop]);
1386 	if (be->decompressed_pages != be->onstack_pages)
1387 		kvfree(be->decompressed_pages);
1388 
1389 	pcl->length = 0;
1390 	pcl->partial = true;
1391 	pcl->multibases = false;
1392 	pcl->besteffort = false;
1393 	pcl->bvset.nextpage = NULL;
1394 	pcl->vcnt = 0;
1395 
1396 	/* pcluster lock MUST be taken before the following line */
1397 	WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_NIL);
1398 	mutex_unlock(&pcl->lock);
1399 
1400 	if (z_erofs_is_inline_pcluster(pcl))
1401 		z_erofs_free_pcluster(pcl);
1402 	else
1403 		z_erofs_put_pcluster(sbi, pcl, try_free);
1404 	return err;
1405 }
1406 
z_erofs_decompress_queue(const struct z_erofs_decompressqueue * io,struct page ** pagepool)1407 static int z_erofs_decompress_queue(const struct z_erofs_decompressqueue *io,
1408 				    struct page **pagepool)
1409 {
1410 	struct z_erofs_decompress_backend be = {
1411 		.sb = io->sb,
1412 		.pagepool = pagepool,
1413 		.decompressed_secondary_bvecs =
1414 			LIST_HEAD_INIT(be.decompressed_secondary_bvecs),
1415 	};
1416 	z_erofs_next_pcluster_t owned = io->head;
1417 	int err = io->eio ? -EIO : 0;
1418 
1419 	while (owned != Z_EROFS_PCLUSTER_TAIL) {
1420 		DBG_BUGON(owned == Z_EROFS_PCLUSTER_NIL);
1421 
1422 		be.pcl = container_of(owned, struct z_erofs_pcluster, next);
1423 		owned = READ_ONCE(be.pcl->next);
1424 
1425 		err = z_erofs_decompress_pcluster(&be, err) ?: err;
1426 	}
1427 	return err;
1428 }
1429 
z_erofs_decompressqueue_work(struct work_struct * work)1430 static void z_erofs_decompressqueue_work(struct work_struct *work)
1431 {
1432 	struct z_erofs_decompressqueue *bgq =
1433 		container_of(work, struct z_erofs_decompressqueue, u.work);
1434 	struct page *pagepool = NULL;
1435 
1436 	DBG_BUGON(bgq->head == Z_EROFS_PCLUSTER_TAIL);
1437 	z_erofs_decompress_queue(bgq, &pagepool);
1438 	erofs_release_pages(&pagepool);
1439 	kvfree(bgq);
1440 }
1441 
1442 #ifdef CONFIG_EROFS_FS_PCPU_KTHREAD
z_erofs_decompressqueue_kthread_work(struct kthread_work * work)1443 static void z_erofs_decompressqueue_kthread_work(struct kthread_work *work)
1444 {
1445 	z_erofs_decompressqueue_work((struct work_struct *)work);
1446 }
1447 #endif
1448 
z_erofs_decompress_kickoff(struct z_erofs_decompressqueue * io,int bios)1449 static void z_erofs_decompress_kickoff(struct z_erofs_decompressqueue *io,
1450 				       int bios)
1451 {
1452 	struct erofs_sb_info *const sbi = EROFS_SB(io->sb);
1453 
1454 	/* wake up the caller thread for sync decompression */
1455 	if (io->sync) {
1456 		if (!atomic_add_return(bios, &io->pending_bios))
1457 			complete(&io->u.done);
1458 		return;
1459 	}
1460 
1461 	if (atomic_add_return(bios, &io->pending_bios))
1462 		return;
1463 	/* Use (kthread_)work and sync decompression for atomic contexts only */
1464 	if (!in_task() || irqs_disabled() || rcu_read_lock_any_held()) {
1465 #ifdef CONFIG_EROFS_FS_PCPU_KTHREAD
1466 		struct kthread_worker *worker;
1467 
1468 		rcu_read_lock();
1469 		worker = rcu_dereference(
1470 				z_erofs_pcpu_workers[raw_smp_processor_id()]);
1471 		if (!worker) {
1472 			INIT_WORK(&io->u.work, z_erofs_decompressqueue_work);
1473 			queue_work(z_erofs_workqueue, &io->u.work);
1474 		} else {
1475 			kthread_queue_work(worker, &io->u.kthread_work);
1476 		}
1477 		rcu_read_unlock();
1478 #else
1479 		queue_work(z_erofs_workqueue, &io->u.work);
1480 #endif
1481 		/* enable sync decompression for readahead */
1482 		if (sbi->opt.sync_decompress == EROFS_SYNC_DECOMPRESS_AUTO)
1483 			sbi->opt.sync_decompress = EROFS_SYNC_DECOMPRESS_FORCE_ON;
1484 		return;
1485 	}
1486 	z_erofs_decompressqueue_work(&io->u.work);
1487 }
1488 
z_erofs_fill_bio_vec(struct bio_vec * bvec,struct z_erofs_decompress_frontend * f,struct z_erofs_pcluster * pcl,unsigned int nr,struct address_space * mc)1489 static void z_erofs_fill_bio_vec(struct bio_vec *bvec,
1490 				 struct z_erofs_decompress_frontend *f,
1491 				 struct z_erofs_pcluster *pcl,
1492 				 unsigned int nr,
1493 				 struct address_space *mc)
1494 {
1495 	gfp_t gfp = mapping_gfp_mask(mc);
1496 	bool tocache = false;
1497 	struct z_erofs_bvec zbv;
1498 	struct address_space *mapping;
1499 	struct folio *folio;
1500 	struct page *page;
1501 	int bs = i_blocksize(f->inode);
1502 
1503 	/* Except for inplace folios, the entire folio can be used for I/Os */
1504 	bvec->bv_offset = 0;
1505 	bvec->bv_len = PAGE_SIZE;
1506 repeat:
1507 	spin_lock(&pcl->lockref.lock);
1508 	zbv = pcl->compressed_bvecs[nr];
1509 	spin_unlock(&pcl->lockref.lock);
1510 	if (!zbv.page)
1511 		goto out_allocfolio;
1512 
1513 	bvec->bv_page = zbv.page;
1514 	DBG_BUGON(z_erofs_is_shortlived_page(bvec->bv_page));
1515 
1516 	folio = page_folio(zbv.page);
1517 	/*
1518 	 * Handle preallocated cached folios.  We tried to allocate such folios
1519 	 * without triggering direct reclaim.  If allocation failed, inplace
1520 	 * file-backed folios will be used instead.
1521 	 */
1522 	if (folio->private == (void *)Z_EROFS_PREALLOCATED_PAGE) {
1523 		tocache = true;
1524 		goto out_tocache;
1525 	}
1526 
1527 	mapping = READ_ONCE(folio->mapping);
1528 	/*
1529 	 * File-backed folios for inplace I/Os are all locked steady,
1530 	 * therefore it is impossible for `mapping` to be NULL.
1531 	 */
1532 	if (mapping && mapping != mc) {
1533 		if (zbv.offset < 0)
1534 			bvec->bv_offset = round_up(-zbv.offset, bs);
1535 		bvec->bv_len = round_up(zbv.end, bs) - bvec->bv_offset;
1536 		return;
1537 	}
1538 
1539 	folio_lock(folio);
1540 	if (likely(folio->mapping == mc)) {
1541 		/*
1542 		 * The cached folio is still in managed cache but without
1543 		 * a valid `->private` pcluster hint.  Let's reconnect them.
1544 		 */
1545 		if (!folio_test_private(folio)) {
1546 			folio_attach_private(folio, pcl);
1547 			/* compressed_bvecs[] already takes a ref before */
1548 			folio_put(folio);
1549 		}
1550 		if (likely(folio->private == pcl))  {
1551 			/* don't submit cache I/Os again if already uptodate */
1552 			if (folio_test_uptodate(folio)) {
1553 				folio_unlock(folio);
1554 				bvec->bv_page = NULL;
1555 			}
1556 			return;
1557 		}
1558 		/*
1559 		 * Already linked with another pcluster, which only appears in
1560 		 * crafted images by fuzzers for now.  But handle this anyway.
1561 		 */
1562 		tocache = false;	/* use temporary short-lived pages */
1563 	} else {
1564 		DBG_BUGON(1); /* referenced managed folios can't be truncated */
1565 		tocache = true;
1566 	}
1567 	folio_unlock(folio);
1568 	folio_put(folio);
1569 out_allocfolio:
1570 	page = __erofs_allocpage(&f->pagepool, gfp, true);
1571 	spin_lock(&pcl->lockref.lock);
1572 	if (unlikely(pcl->compressed_bvecs[nr].page != zbv.page)) {
1573 		if (page)
1574 			erofs_pagepool_add(&f->pagepool, page);
1575 		spin_unlock(&pcl->lockref.lock);
1576 		cond_resched();
1577 		goto repeat;
1578 	}
1579 	pcl->compressed_bvecs[nr].page = page ? page : ERR_PTR(-ENOMEM);
1580 	spin_unlock(&pcl->lockref.lock);
1581 	bvec->bv_page = page;
1582 	if (!page)
1583 		return;
1584 	folio = page_folio(page);
1585 out_tocache:
1586 	if (!tocache || bs != PAGE_SIZE ||
1587 	    filemap_add_folio(mc, folio, pcl->index + nr, gfp)) {
1588 		/* turn into a temporary shortlived folio (1 ref) */
1589 		folio->private = (void *)Z_EROFS_SHORTLIVED_PAGE;
1590 		return;
1591 	}
1592 	folio_attach_private(folio, pcl);
1593 	/* drop a refcount added by allocpage (then 2 refs in total here) */
1594 	folio_put(folio);
1595 }
1596 
jobqueue_init(struct super_block * sb,struct z_erofs_decompressqueue * fgq,bool * fg)1597 static struct z_erofs_decompressqueue *jobqueue_init(struct super_block *sb,
1598 			      struct z_erofs_decompressqueue *fgq, bool *fg)
1599 {
1600 	struct z_erofs_decompressqueue *q;
1601 
1602 	if (fg && !*fg) {
1603 		q = kvzalloc(sizeof(*q), GFP_KERNEL | __GFP_NOWARN);
1604 		if (!q) {
1605 			*fg = true;
1606 			goto fg_out;
1607 		}
1608 #ifdef CONFIG_EROFS_FS_PCPU_KTHREAD
1609 		kthread_init_work(&q->u.kthread_work,
1610 				  z_erofs_decompressqueue_kthread_work);
1611 #else
1612 		INIT_WORK(&q->u.work, z_erofs_decompressqueue_work);
1613 #endif
1614 	} else {
1615 fg_out:
1616 		q = fgq;
1617 		init_completion(&fgq->u.done);
1618 		atomic_set(&fgq->pending_bios, 0);
1619 		q->eio = false;
1620 		q->sync = true;
1621 	}
1622 	q->sb = sb;
1623 	q->head = Z_EROFS_PCLUSTER_TAIL;
1624 	return q;
1625 }
1626 
1627 /* define decompression jobqueue types */
1628 enum {
1629 	JQ_BYPASS,
1630 	JQ_SUBMIT,
1631 	NR_JOBQUEUES,
1632 };
1633 
move_to_bypass_jobqueue(struct z_erofs_pcluster * pcl,z_erofs_next_pcluster_t qtail[],z_erofs_next_pcluster_t owned_head)1634 static void move_to_bypass_jobqueue(struct z_erofs_pcluster *pcl,
1635 				    z_erofs_next_pcluster_t qtail[],
1636 				    z_erofs_next_pcluster_t owned_head)
1637 {
1638 	z_erofs_next_pcluster_t *const submit_qtail = qtail[JQ_SUBMIT];
1639 	z_erofs_next_pcluster_t *const bypass_qtail = qtail[JQ_BYPASS];
1640 
1641 	WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_TAIL);
1642 
1643 	WRITE_ONCE(*submit_qtail, owned_head);
1644 	WRITE_ONCE(*bypass_qtail, &pcl->next);
1645 
1646 	qtail[JQ_BYPASS] = &pcl->next;
1647 }
1648 
z_erofs_endio(struct bio * bio)1649 static void z_erofs_endio(struct bio *bio)
1650 {
1651 	struct z_erofs_decompressqueue *q = bio->bi_private;
1652 	blk_status_t err = bio->bi_status;
1653 	struct folio_iter fi;
1654 
1655 	bio_for_each_folio_all(fi, bio) {
1656 		struct folio *folio = fi.folio;
1657 
1658 		DBG_BUGON(folio_test_uptodate(folio));
1659 		DBG_BUGON(z_erofs_page_is_invalidated(&folio->page));
1660 		if (!erofs_folio_is_managed(EROFS_SB(q->sb), folio))
1661 			continue;
1662 
1663 		if (!err)
1664 			folio_mark_uptodate(folio);
1665 		folio_unlock(folio);
1666 	}
1667 	if (err)
1668 		q->eio = true;
1669 	z_erofs_decompress_kickoff(q, -1);
1670 	if (bio->bi_bdev)
1671 		bio_put(bio);
1672 }
1673 
z_erofs_submit_queue(struct z_erofs_decompress_frontend * f,struct z_erofs_decompressqueue * fgq,bool * force_fg,bool readahead)1674 static void z_erofs_submit_queue(struct z_erofs_decompress_frontend *f,
1675 				 struct z_erofs_decompressqueue *fgq,
1676 				 bool *force_fg, bool readahead)
1677 {
1678 	struct super_block *sb = f->inode->i_sb;
1679 	struct address_space *mc = MNGD_MAPPING(EROFS_SB(sb));
1680 	z_erofs_next_pcluster_t qtail[NR_JOBQUEUES];
1681 	struct z_erofs_decompressqueue *q[NR_JOBQUEUES];
1682 	z_erofs_next_pcluster_t owned_head = f->owned_head;
1683 	/* bio is NULL initially, so no need to initialize last_{index,bdev} */
1684 	erofs_off_t last_pa;
1685 	unsigned int nr_bios = 0;
1686 	struct bio *bio = NULL;
1687 	unsigned long pflags;
1688 	int memstall = 0;
1689 
1690 	/* No need to read from device for pclusters in the bypass queue. */
1691 	q[JQ_BYPASS] = jobqueue_init(sb, fgq + JQ_BYPASS, NULL);
1692 	q[JQ_SUBMIT] = jobqueue_init(sb, fgq + JQ_SUBMIT, force_fg);
1693 
1694 	qtail[JQ_BYPASS] = &q[JQ_BYPASS]->head;
1695 	qtail[JQ_SUBMIT] = &q[JQ_SUBMIT]->head;
1696 
1697 	/* by default, all need io submission */
1698 	q[JQ_SUBMIT]->head = owned_head;
1699 
1700 	do {
1701 		struct erofs_map_dev mdev;
1702 		struct z_erofs_pcluster *pcl;
1703 		erofs_off_t cur, end;
1704 		struct bio_vec bvec;
1705 		unsigned int i = 0;
1706 		bool bypass = true;
1707 
1708 		DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_NIL);
1709 		pcl = container_of(owned_head, struct z_erofs_pcluster, next);
1710 		owned_head = READ_ONCE(pcl->next);
1711 
1712 		if (z_erofs_is_inline_pcluster(pcl)) {
1713 			move_to_bypass_jobqueue(pcl, qtail, owned_head);
1714 			continue;
1715 		}
1716 
1717 		/* no device id here, thus it will always succeed */
1718 		mdev = (struct erofs_map_dev) {
1719 			.m_pa = erofs_pos(sb, pcl->index),
1720 		};
1721 		(void)erofs_map_dev(sb, &mdev);
1722 
1723 		cur = mdev.m_pa;
1724 		end = cur + pcl->pclustersize;
1725 		do {
1726 			bvec.bv_page = NULL;
1727 			if (bio && (cur != last_pa ||
1728 				    bio->bi_bdev != mdev.m_bdev)) {
1729 drain_io:
1730 				if (erofs_is_fileio_mode(EROFS_SB(sb)))
1731 					erofs_fileio_submit_bio(bio);
1732 				else if (erofs_is_fscache_mode(sb))
1733 					erofs_fscache_submit_bio(bio);
1734 				else
1735 					submit_bio(bio);
1736 
1737 				if (memstall) {
1738 					psi_memstall_leave(&pflags);
1739 					memstall = 0;
1740 				}
1741 				bio = NULL;
1742 			}
1743 
1744 			if (!bvec.bv_page) {
1745 				z_erofs_fill_bio_vec(&bvec, f, pcl, i++, mc);
1746 				if (!bvec.bv_page)
1747 					continue;
1748 				if (cur + bvec.bv_len > end)
1749 					bvec.bv_len = end - cur;
1750 				DBG_BUGON(bvec.bv_len < sb->s_blocksize);
1751 			}
1752 
1753 			if (unlikely(PageWorkingset(bvec.bv_page)) &&
1754 			    !memstall) {
1755 				psi_memstall_enter(&pflags);
1756 				memstall = 1;
1757 			}
1758 
1759 			if (!bio) {
1760 				if (erofs_is_fileio_mode(EROFS_SB(sb)))
1761 					bio = erofs_fileio_bio_alloc(&mdev);
1762 				else if (erofs_is_fscache_mode(sb))
1763 					bio = erofs_fscache_bio_alloc(&mdev);
1764 				else
1765 					bio = bio_alloc(mdev.m_bdev, BIO_MAX_VECS,
1766 							REQ_OP_READ, GFP_NOIO);
1767 				bio->bi_end_io = z_erofs_endio;
1768 				bio->bi_iter.bi_sector = cur >> 9;
1769 				bio->bi_private = q[JQ_SUBMIT];
1770 				if (readahead)
1771 					bio->bi_opf |= REQ_RAHEAD;
1772 				++nr_bios;
1773 			}
1774 
1775 			if (!bio_add_page(bio, bvec.bv_page, bvec.bv_len,
1776 					  bvec.bv_offset))
1777 				goto drain_io;
1778 			last_pa = cur + bvec.bv_len;
1779 			bypass = false;
1780 		} while ((cur += bvec.bv_len) < end);
1781 
1782 		if (!bypass)
1783 			qtail[JQ_SUBMIT] = &pcl->next;
1784 		else
1785 			move_to_bypass_jobqueue(pcl, qtail, owned_head);
1786 	} while (owned_head != Z_EROFS_PCLUSTER_TAIL);
1787 
1788 	if (bio) {
1789 		if (erofs_is_fileio_mode(EROFS_SB(sb)))
1790 			erofs_fileio_submit_bio(bio);
1791 		else if (erofs_is_fscache_mode(sb))
1792 			erofs_fscache_submit_bio(bio);
1793 		else
1794 			submit_bio(bio);
1795 	}
1796 	if (memstall)
1797 		psi_memstall_leave(&pflags);
1798 
1799 	/*
1800 	 * although background is preferred, no one is pending for submission.
1801 	 * don't issue decompression but drop it directly instead.
1802 	 */
1803 	if (!*force_fg && !nr_bios) {
1804 		kvfree(q[JQ_SUBMIT]);
1805 		return;
1806 	}
1807 	z_erofs_decompress_kickoff(q[JQ_SUBMIT], nr_bios);
1808 }
1809 
z_erofs_runqueue(struct z_erofs_decompress_frontend * f,unsigned int ra_folios)1810 static int z_erofs_runqueue(struct z_erofs_decompress_frontend *f,
1811 			    unsigned int ra_folios)
1812 {
1813 	struct z_erofs_decompressqueue io[NR_JOBQUEUES];
1814 	struct erofs_sb_info *sbi = EROFS_I_SB(f->inode);
1815 	bool force_fg = z_erofs_is_sync_decompress(sbi, ra_folios);
1816 	int err;
1817 
1818 	if (f->owned_head == Z_EROFS_PCLUSTER_TAIL)
1819 		return 0;
1820 	z_erofs_submit_queue(f, io, &force_fg, !!ra_folios);
1821 
1822 	/* handle bypass queue (no i/o pclusters) immediately */
1823 	err = z_erofs_decompress_queue(&io[JQ_BYPASS], &f->pagepool);
1824 	if (!force_fg)
1825 		return err;
1826 
1827 	/* wait until all bios are completed */
1828 	wait_for_completion_io(&io[JQ_SUBMIT].u.done);
1829 
1830 	/* handle synchronous decompress queue in the caller context */
1831 	return z_erofs_decompress_queue(&io[JQ_SUBMIT], &f->pagepool) ?: err;
1832 }
1833 
1834 /*
1835  * Since partial uptodate is still unimplemented for now, we have to use
1836  * approximate readmore strategies as a start.
1837  */
z_erofs_pcluster_readmore(struct z_erofs_decompress_frontend * f,struct readahead_control * rac,bool backmost)1838 static void z_erofs_pcluster_readmore(struct z_erofs_decompress_frontend *f,
1839 		struct readahead_control *rac, bool backmost)
1840 {
1841 	struct inode *inode = f->inode;
1842 	struct erofs_map_blocks *map = &f->map;
1843 	erofs_off_t cur, end, headoffset = f->headoffset;
1844 	int err;
1845 
1846 	if (backmost) {
1847 		if (rac)
1848 			end = headoffset + readahead_length(rac) - 1;
1849 		else
1850 			end = headoffset + PAGE_SIZE - 1;
1851 		map->m_la = end;
1852 		err = z_erofs_map_blocks_iter(inode, map,
1853 					      EROFS_GET_BLOCKS_READMORE);
1854 		if (err)
1855 			return;
1856 
1857 		/* expand ra for the trailing edge if readahead */
1858 		if (rac) {
1859 			cur = round_up(map->m_la + map->m_llen, PAGE_SIZE);
1860 			readahead_expand(rac, headoffset, cur - headoffset);
1861 			return;
1862 		}
1863 		end = round_up(end, PAGE_SIZE);
1864 	} else {
1865 		end = round_up(map->m_la, PAGE_SIZE);
1866 		if (!map->m_llen)
1867 			return;
1868 	}
1869 
1870 	cur = map->m_la + map->m_llen - 1;
1871 	while ((cur >= end) && (cur < i_size_read(inode))) {
1872 		pgoff_t index = cur >> PAGE_SHIFT;
1873 		struct folio *folio;
1874 
1875 		folio = erofs_grab_folio_nowait(inode->i_mapping, index);
1876 		if (!IS_ERR_OR_NULL(folio)) {
1877 			if (folio_test_uptodate(folio))
1878 				folio_unlock(folio);
1879 			else
1880 				z_erofs_scan_folio(f, folio, !!rac);
1881 			folio_put(folio);
1882 		}
1883 
1884 		if (cur < PAGE_SIZE)
1885 			break;
1886 		cur = (index << PAGE_SHIFT) - 1;
1887 	}
1888 }
1889 
z_erofs_read_folio(struct file * file,struct folio * folio)1890 static int z_erofs_read_folio(struct file *file, struct folio *folio)
1891 {
1892 	struct inode *const inode = folio->mapping->host;
1893 	struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1894 	int err;
1895 
1896 	trace_erofs_read_folio(folio, false);
1897 	f.headoffset = (erofs_off_t)folio->index << PAGE_SHIFT;
1898 
1899 	z_erofs_pcluster_readmore(&f, NULL, true);
1900 	err = z_erofs_scan_folio(&f, folio, false);
1901 	z_erofs_pcluster_readmore(&f, NULL, false);
1902 	z_erofs_pcluster_end(&f);
1903 
1904 	/* if some pclusters are ready, need submit them anyway */
1905 	err = z_erofs_runqueue(&f, 0) ?: err;
1906 	if (err && err != -EINTR)
1907 		erofs_err(inode->i_sb, "read error %d @ %lu of nid %llu",
1908 			  err, folio->index, EROFS_I(inode)->nid);
1909 
1910 	erofs_put_metabuf(&f.map.buf);
1911 	erofs_release_pages(&f.pagepool);
1912 	return err;
1913 }
1914 
z_erofs_readahead(struct readahead_control * rac)1915 static void z_erofs_readahead(struct readahead_control *rac)
1916 {
1917 	struct inode *const inode = rac->mapping->host;
1918 	struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1919 	struct folio *head = NULL, *folio;
1920 	unsigned int nr_folios;
1921 	int err;
1922 
1923 	f.headoffset = readahead_pos(rac);
1924 
1925 	z_erofs_pcluster_readmore(&f, rac, true);
1926 	nr_folios = readahead_count(rac);
1927 	trace_erofs_readpages(inode, readahead_index(rac), nr_folios, false);
1928 
1929 	while ((folio = readahead_folio(rac))) {
1930 		folio->private = head;
1931 		head = folio;
1932 	}
1933 
1934 	/* traverse in reverse order for best metadata I/O performance */
1935 	while (head) {
1936 		folio = head;
1937 		head = folio_get_private(folio);
1938 
1939 		err = z_erofs_scan_folio(&f, folio, true);
1940 		if (err && err != -EINTR)
1941 			erofs_err(inode->i_sb, "readahead error at folio %lu @ nid %llu",
1942 				  folio->index, EROFS_I(inode)->nid);
1943 	}
1944 	z_erofs_pcluster_readmore(&f, rac, false);
1945 	z_erofs_pcluster_end(&f);
1946 
1947 	(void)z_erofs_runqueue(&f, nr_folios);
1948 	erofs_put_metabuf(&f.map.buf);
1949 	erofs_release_pages(&f.pagepool);
1950 }
1951 
1952 const struct address_space_operations z_erofs_aops = {
1953 	.read_folio = z_erofs_read_folio,
1954 	.readahead = z_erofs_readahead,
1955 };
1956