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