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