• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2018 HUAWEI, Inc.
4  *             http://www.huawei.com/
5  * Created by Gao Xiang <gaoxiang25@huawei.com>
6  */
7 #include "zdata.h"
8 #include "compress.h"
9 #include <linux/prefetch.h>
10 
11 #include <trace/events/erofs.h>
12 
13 /*
14  * a compressed_pages[] placeholder in order to avoid
15  * being filled with file pages for in-place decompression.
16  */
17 #define PAGE_UNALLOCATED     ((void *)0x5F0E4B1D)
18 
19 /* how to allocate cached pages for a pcluster */
20 enum z_erofs_cache_alloctype {
21 	DONTALLOC,	/* don't allocate any cached pages */
22 	DELAYEDALLOC,	/* delayed allocation (at the time of submitting io) */
23 };
24 
25 /*
26  * tagged pointer with 1-bit tag for all compressed pages
27  * tag 0 - the page is just found with an extra page reference
28  */
29 typedef tagptr1_t compressed_page_t;
30 
31 #define tag_compressed_page_justfound(page) \
32 	tagptr_fold(compressed_page_t, page, 1)
33 
34 static struct workqueue_struct *z_erofs_workqueue __read_mostly;
35 static struct kmem_cache *pcluster_cachep __read_mostly;
36 
z_erofs_exit_zip_subsystem(void)37 void z_erofs_exit_zip_subsystem(void)
38 {
39 	destroy_workqueue(z_erofs_workqueue);
40 	kmem_cache_destroy(pcluster_cachep);
41 }
42 
z_erofs_init_workqueue(void)43 static inline int z_erofs_init_workqueue(void)
44 {
45 	const unsigned int onlinecpus = num_possible_cpus();
46 	const unsigned int flags = WQ_UNBOUND | WQ_HIGHPRI | WQ_CPU_INTENSIVE;
47 
48 	/*
49 	 * no need to spawn too many threads, limiting threads could minimum
50 	 * scheduling overhead, perhaps per-CPU threads should be better?
51 	 */
52 	z_erofs_workqueue = alloc_workqueue("erofs_unzipd", flags,
53 					    onlinecpus + onlinecpus / 4);
54 	return z_erofs_workqueue ? 0 : -ENOMEM;
55 }
56 
z_erofs_pcluster_init_once(void * ptr)57 static void z_erofs_pcluster_init_once(void *ptr)
58 {
59 	struct z_erofs_pcluster *pcl = ptr;
60 	struct z_erofs_collection *cl = z_erofs_primarycollection(pcl);
61 	unsigned int i;
62 
63 	mutex_init(&cl->lock);
64 	cl->nr_pages = 0;
65 	cl->vcnt = 0;
66 	for (i = 0; i < Z_EROFS_CLUSTER_MAX_PAGES; ++i)
67 		pcl->compressed_pages[i] = NULL;
68 }
69 
z_erofs_pcluster_init_always(struct z_erofs_pcluster * pcl)70 static void z_erofs_pcluster_init_always(struct z_erofs_pcluster *pcl)
71 {
72 	struct z_erofs_collection *cl = z_erofs_primarycollection(pcl);
73 
74 	atomic_set(&pcl->obj.refcount, 1);
75 
76 	DBG_BUGON(cl->nr_pages);
77 	DBG_BUGON(cl->vcnt);
78 }
79 
z_erofs_init_zip_subsystem(void)80 int __init z_erofs_init_zip_subsystem(void)
81 {
82 	pcluster_cachep = kmem_cache_create("erofs_compress",
83 					    Z_EROFS_WORKGROUP_SIZE, 0,
84 					    SLAB_RECLAIM_ACCOUNT,
85 					    z_erofs_pcluster_init_once);
86 	if (pcluster_cachep) {
87 		if (!z_erofs_init_workqueue())
88 			return 0;
89 
90 		kmem_cache_destroy(pcluster_cachep);
91 	}
92 	return -ENOMEM;
93 }
94 
95 enum z_erofs_collectmode {
96 	COLLECT_SECONDARY,
97 	COLLECT_PRIMARY,
98 	/*
99 	 * The current collection was the tail of an exist chain, in addition
100 	 * that the previous processed chained collections are all decided to
101 	 * be hooked up to it.
102 	 * A new chain will be created for the remaining collections which are
103 	 * not processed yet, therefore different from COLLECT_PRIMARY_FOLLOWED,
104 	 * the next collection cannot reuse the whole page safely in
105 	 * the following scenario:
106 	 *  ________________________________________________________________
107 	 * |      tail (partial) page     |       head (partial) page       |
108 	 * |   (belongs to the next cl)   |   (belongs to the current cl)   |
109 	 * |_______PRIMARY_FOLLOWED_______|________PRIMARY_HOOKED___________|
110 	 */
111 	COLLECT_PRIMARY_HOOKED,
112 	COLLECT_PRIMARY_FOLLOWED_NOINPLACE,
113 	/*
114 	 * The current collection has been linked with the owned chain, and
115 	 * could also be linked with the remaining collections, which means
116 	 * if the processing page is the tail page of the collection, thus
117 	 * the current collection can safely use the whole page (since
118 	 * the previous collection is under control) for in-place I/O, as
119 	 * illustrated below:
120 	 *  ________________________________________________________________
121 	 * |  tail (partial) page |          head (partial) page           |
122 	 * |  (of the current cl) |      (of the previous collection)      |
123 	 * |  PRIMARY_FOLLOWED or |                                        |
124 	 * |_____PRIMARY_HOOKED___|____________PRIMARY_FOLLOWED____________|
125 	 *
126 	 * [  (*) the above page can be used as inplace I/O.               ]
127 	 */
128 	COLLECT_PRIMARY_FOLLOWED,
129 };
130 
131 struct z_erofs_collector {
132 	struct z_erofs_pagevec_ctor vector;
133 
134 	struct z_erofs_pcluster *pcl, *tailpcl;
135 	struct z_erofs_collection *cl;
136 	struct page **compressedpages;
137 	z_erofs_next_pcluster_t owned_head;
138 
139 	enum z_erofs_collectmode mode;
140 };
141 
142 struct z_erofs_decompress_frontend {
143 	struct inode *const inode;
144 
145 	struct z_erofs_collector clt;
146 	struct erofs_map_blocks map;
147 
148 	/* used for applying cache strategy on the fly */
149 	bool backmost;
150 	erofs_off_t headoffset;
151 };
152 
153 #define COLLECTOR_INIT() { \
154 	.owned_head = Z_EROFS_PCLUSTER_TAIL, \
155 	.mode = COLLECT_PRIMARY_FOLLOWED }
156 
157 #define DECOMPRESS_FRONTEND_INIT(__i) { \
158 	.inode = __i, .clt = COLLECTOR_INIT(), \
159 	.backmost = true, }
160 
161 static struct page *z_pagemap_global[Z_EROFS_VMAP_GLOBAL_PAGES];
162 static DEFINE_MUTEX(z_pagemap_global_lock);
163 
preload_compressed_pages(struct z_erofs_collector * clt,struct address_space * mc,enum z_erofs_cache_alloctype type,struct list_head * pagepool)164 static void preload_compressed_pages(struct z_erofs_collector *clt,
165 				     struct address_space *mc,
166 				     enum z_erofs_cache_alloctype type,
167 				     struct list_head *pagepool)
168 {
169 	const struct z_erofs_pcluster *pcl = clt->pcl;
170 	const unsigned int clusterpages = BIT(pcl->clusterbits);
171 	struct page **pages = clt->compressedpages;
172 	pgoff_t index = pcl->obj.index + (pages - pcl->compressed_pages);
173 	bool standalone = true;
174 
175 	if (clt->mode < COLLECT_PRIMARY_FOLLOWED)
176 		return;
177 
178 	for (; pages < pcl->compressed_pages + clusterpages; ++pages) {
179 		struct page *page;
180 		compressed_page_t t;
181 
182 		/* the compressed page was loaded before */
183 		if (READ_ONCE(*pages))
184 			continue;
185 
186 		page = find_get_page(mc, index);
187 
188 		if (page) {
189 			t = tag_compressed_page_justfound(page);
190 		} else if (type == DELAYEDALLOC) {
191 			t = tagptr_init(compressed_page_t, PAGE_UNALLOCATED);
192 		} else {	/* DONTALLOC */
193 			if (standalone)
194 				clt->compressedpages = pages;
195 			standalone = false;
196 			continue;
197 		}
198 
199 		if (!cmpxchg_relaxed(pages, NULL, tagptr_cast_ptr(t)))
200 			continue;
201 
202 		if (page)
203 			put_page(page);
204 	}
205 
206 	if (standalone)		/* downgrade to PRIMARY_FOLLOWED_NOINPLACE */
207 		clt->mode = COLLECT_PRIMARY_FOLLOWED_NOINPLACE;
208 }
209 
210 /* 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)211 int erofs_try_to_free_all_cached_pages(struct erofs_sb_info *sbi,
212 				       struct erofs_workgroup *grp)
213 {
214 	struct z_erofs_pcluster *const pcl =
215 		container_of(grp, struct z_erofs_pcluster, obj);
216 	struct address_space *const mapping = MNGD_MAPPING(sbi);
217 	const unsigned int clusterpages = BIT(pcl->clusterbits);
218 	int i;
219 
220 	/*
221 	 * refcount of workgroup is now freezed as 1,
222 	 * therefore no need to worry about available decompression users.
223 	 */
224 	for (i = 0; i < clusterpages; ++i) {
225 		struct page *page = pcl->compressed_pages[i];
226 
227 		if (!page)
228 			continue;
229 
230 		/* block other users from reclaiming or migrating the page */
231 		if (!trylock_page(page))
232 			return -EBUSY;
233 
234 		if (page->mapping != mapping)
235 			continue;
236 
237 		/* barrier is implied in the following 'unlock_page' */
238 		WRITE_ONCE(pcl->compressed_pages[i], NULL);
239 		set_page_private(page, 0);
240 		ClearPagePrivate(page);
241 
242 		unlock_page(page);
243 		put_page(page);
244 	}
245 	return 0;
246 }
247 
erofs_try_to_free_cached_page(struct address_space * mapping,struct page * page)248 int erofs_try_to_free_cached_page(struct address_space *mapping,
249 				  struct page *page)
250 {
251 	struct z_erofs_pcluster *const pcl = (void *)page_private(page);
252 	const unsigned int clusterpages = BIT(pcl->clusterbits);
253 	int ret = 0;	/* 0 - busy */
254 
255 	if (erofs_workgroup_try_to_freeze(&pcl->obj, 1)) {
256 		unsigned int i;
257 
258 		for (i = 0; i < clusterpages; ++i) {
259 			if (pcl->compressed_pages[i] == page) {
260 				WRITE_ONCE(pcl->compressed_pages[i], NULL);
261 				ret = 1;
262 				break;
263 			}
264 		}
265 		erofs_workgroup_unfreeze(&pcl->obj, 1);
266 
267 		if (ret) {
268 			ClearPagePrivate(page);
269 			put_page(page);
270 		}
271 	}
272 	return ret;
273 }
274 
275 /* page_type must be Z_EROFS_PAGE_TYPE_EXCLUSIVE */
z_erofs_try_inplace_io(struct z_erofs_collector * clt,struct page * page)276 static inline bool z_erofs_try_inplace_io(struct z_erofs_collector *clt,
277 					  struct page *page)
278 {
279 	struct z_erofs_pcluster *const pcl = clt->pcl;
280 	const unsigned int clusterpages = BIT(pcl->clusterbits);
281 
282 	while (clt->compressedpages < pcl->compressed_pages + clusterpages) {
283 		if (!cmpxchg(clt->compressedpages++, NULL, page))
284 			return true;
285 	}
286 	return false;
287 }
288 
289 /* 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)290 static int z_erofs_attach_page(struct z_erofs_collector *clt,
291 			       struct page *page, enum z_erofs_page_type type,
292 			       bool pvec_safereuse)
293 {
294 	int ret;
295 
296 	/* give priority for inplaceio */
297 	if (clt->mode >= COLLECT_PRIMARY &&
298 	    type == Z_EROFS_PAGE_TYPE_EXCLUSIVE &&
299 	    z_erofs_try_inplace_io(clt, page))
300 		return 0;
301 
302 	ret = z_erofs_pagevec_enqueue(&clt->vector, page, type,
303 				      pvec_safereuse);
304 	clt->cl->vcnt += (unsigned int)ret;
305 	return ret ? 0 : -EAGAIN;
306 }
307 
308 static enum z_erofs_collectmode
try_to_claim_pcluster(struct z_erofs_pcluster * pcl,z_erofs_next_pcluster_t * owned_head)309 try_to_claim_pcluster(struct z_erofs_pcluster *pcl,
310 		      z_erofs_next_pcluster_t *owned_head)
311 {
312 	/* let's claim these following types of pclusters */
313 retry:
314 	if (pcl->next == Z_EROFS_PCLUSTER_NIL) {
315 		/* type 1, nil pcluster */
316 		if (cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_NIL,
317 			    *owned_head) != Z_EROFS_PCLUSTER_NIL)
318 			goto retry;
319 
320 		*owned_head = &pcl->next;
321 		/* lucky, I am the followee :) */
322 		return COLLECT_PRIMARY_FOLLOWED;
323 	} else if (pcl->next == Z_EROFS_PCLUSTER_TAIL) {
324 		/*
325 		 * type 2, link to the end of a existing open chain,
326 		 * be careful that its submission itself is governed
327 		 * by the original owned chain.
328 		 */
329 		if (cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_TAIL,
330 			    *owned_head) != Z_EROFS_PCLUSTER_TAIL)
331 			goto retry;
332 		*owned_head = Z_EROFS_PCLUSTER_TAIL;
333 		return COLLECT_PRIMARY_HOOKED;
334 	}
335 	return COLLECT_PRIMARY;	/* :( better luck next time */
336 }
337 
cllookup(struct z_erofs_collector * clt,struct inode * inode,struct erofs_map_blocks * map)338 static struct z_erofs_collection *cllookup(struct z_erofs_collector *clt,
339 					   struct inode *inode,
340 					   struct erofs_map_blocks *map)
341 {
342 	struct erofs_workgroup *grp;
343 	struct z_erofs_pcluster *pcl;
344 	struct z_erofs_collection *cl;
345 	unsigned int length;
346 	bool tag;
347 
348 	grp = erofs_find_workgroup(inode->i_sb, map->m_pa >> PAGE_SHIFT, &tag);
349 	if (!grp)
350 		return NULL;
351 
352 	pcl = container_of(grp, struct z_erofs_pcluster, obj);
353 	if (clt->owned_head == &pcl->next || pcl == clt->tailpcl) {
354 		DBG_BUGON(1);
355 		erofs_workgroup_put(grp);
356 		return ERR_PTR(-EFSCORRUPTED);
357 	}
358 
359 	cl = z_erofs_primarycollection(pcl);
360 	if (cl->pageofs != (map->m_la & ~PAGE_MASK)) {
361 		DBG_BUGON(1);
362 		erofs_workgroup_put(grp);
363 		return ERR_PTR(-EFSCORRUPTED);
364 	}
365 
366 	length = READ_ONCE(pcl->length);
367 	if (length & Z_EROFS_PCLUSTER_FULL_LENGTH) {
368 		if ((map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT) > length) {
369 			DBG_BUGON(1);
370 			erofs_workgroup_put(grp);
371 			return ERR_PTR(-EFSCORRUPTED);
372 		}
373 	} else {
374 		unsigned int llen = map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT;
375 
376 		if (map->m_flags & EROFS_MAP_FULL_MAPPED)
377 			llen |= Z_EROFS_PCLUSTER_FULL_LENGTH;
378 
379 		while (llen > length &&
380 		       length != cmpxchg_relaxed(&pcl->length, length, llen)) {
381 			cpu_relax();
382 			length = READ_ONCE(pcl->length);
383 		}
384 	}
385 	mutex_lock(&cl->lock);
386 	/* used to check tail merging loop due to corrupted images */
387 	if (clt->owned_head == Z_EROFS_PCLUSTER_TAIL)
388 		clt->tailpcl = pcl;
389 	clt->mode = try_to_claim_pcluster(pcl, &clt->owned_head);
390 	/* clean tailpcl if the current owned_head is Z_EROFS_PCLUSTER_TAIL */
391 	if (clt->owned_head == Z_EROFS_PCLUSTER_TAIL)
392 		clt->tailpcl = NULL;
393 	clt->pcl = pcl;
394 	clt->cl = cl;
395 	return cl;
396 }
397 
clregister(struct z_erofs_collector * clt,struct inode * inode,struct erofs_map_blocks * map)398 static struct z_erofs_collection *clregister(struct z_erofs_collector *clt,
399 					     struct inode *inode,
400 					     struct erofs_map_blocks *map)
401 {
402 	struct z_erofs_pcluster *pcl;
403 	struct z_erofs_collection *cl;
404 	int err;
405 
406 	/* no available workgroup, let's allocate one */
407 	pcl = kmem_cache_alloc(pcluster_cachep, GFP_NOFS);
408 	if (!pcl)
409 		return ERR_PTR(-ENOMEM);
410 
411 	z_erofs_pcluster_init_always(pcl);
412 	pcl->obj.index = map->m_pa >> PAGE_SHIFT;
413 
414 	pcl->length = (map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT) |
415 		(map->m_flags & EROFS_MAP_FULL_MAPPED ?
416 			Z_EROFS_PCLUSTER_FULL_LENGTH : 0);
417 
418 	if (map->m_flags & EROFS_MAP_ZIPPED)
419 		pcl->algorithmformat = Z_EROFS_COMPRESSION_LZ4;
420 	else
421 		pcl->algorithmformat = Z_EROFS_COMPRESSION_SHIFTED;
422 
423 	pcl->clusterbits = EROFS_I(inode)->z_physical_clusterbits[0];
424 	pcl->clusterbits -= PAGE_SHIFT;
425 
426 	/* new pclusters should be claimed as type 1, primary and followed */
427 	pcl->next = clt->owned_head;
428 	clt->mode = COLLECT_PRIMARY_FOLLOWED;
429 
430 	cl = z_erofs_primarycollection(pcl);
431 	cl->pageofs = map->m_la & ~PAGE_MASK;
432 
433 	/*
434 	 * lock all primary followed works before visible to others
435 	 * and mutex_trylock *never* fails for a new pcluster.
436 	 */
437 	mutex_trylock(&cl->lock);
438 
439 	err = erofs_register_workgroup(inode->i_sb, &pcl->obj, 0);
440 	if (err) {
441 		mutex_unlock(&cl->lock);
442 		kmem_cache_free(pcluster_cachep, pcl);
443 		return ERR_PTR(-EAGAIN);
444 	}
445 	/* used to check tail merging loop due to corrupted images */
446 	if (clt->owned_head == Z_EROFS_PCLUSTER_TAIL)
447 		clt->tailpcl = pcl;
448 	clt->owned_head = &pcl->next;
449 	clt->pcl = pcl;
450 	clt->cl = cl;
451 	return cl;
452 }
453 
z_erofs_collector_begin(struct z_erofs_collector * clt,struct inode * inode,struct erofs_map_blocks * map)454 static int z_erofs_collector_begin(struct z_erofs_collector *clt,
455 				   struct inode *inode,
456 				   struct erofs_map_blocks *map)
457 {
458 	struct z_erofs_collection *cl;
459 
460 	DBG_BUGON(clt->cl);
461 
462 	/* must be Z_EROFS_PCLUSTER_TAIL or pointed to previous collection */
463 	DBG_BUGON(clt->owned_head == Z_EROFS_PCLUSTER_NIL);
464 	DBG_BUGON(clt->owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
465 
466 	if (!PAGE_ALIGNED(map->m_pa)) {
467 		DBG_BUGON(1);
468 		return -EINVAL;
469 	}
470 
471 repeat:
472 	cl = cllookup(clt, inode, map);
473 	if (!cl) {
474 		cl = clregister(clt, inode, map);
475 
476 		if (cl == ERR_PTR(-EAGAIN))
477 			goto repeat;
478 	}
479 
480 	if (IS_ERR(cl))
481 		return PTR_ERR(cl);
482 
483 	z_erofs_pagevec_ctor_init(&clt->vector, Z_EROFS_NR_INLINE_PAGEVECS,
484 				  cl->pagevec, cl->vcnt);
485 
486 	clt->compressedpages = clt->pcl->compressed_pages;
487 	if (clt->mode <= COLLECT_PRIMARY) /* cannot do in-place I/O */
488 		clt->compressedpages += Z_EROFS_CLUSTER_MAX_PAGES;
489 	return 0;
490 }
491 
492 /*
493  * keep in mind that no referenced pclusters will be freed
494  * only after a RCU grace period.
495  */
z_erofs_rcu_callback(struct rcu_head * head)496 static void z_erofs_rcu_callback(struct rcu_head *head)
497 {
498 	struct z_erofs_collection *const cl =
499 		container_of(head, struct z_erofs_collection, rcu);
500 
501 	kmem_cache_free(pcluster_cachep,
502 			container_of(cl, struct z_erofs_pcluster,
503 				     primary_collection));
504 }
505 
erofs_workgroup_free_rcu(struct erofs_workgroup * grp)506 void erofs_workgroup_free_rcu(struct erofs_workgroup *grp)
507 {
508 	struct z_erofs_pcluster *const pcl =
509 		container_of(grp, struct z_erofs_pcluster, obj);
510 	struct z_erofs_collection *const cl = z_erofs_primarycollection(pcl);
511 
512 	call_rcu(&cl->rcu, z_erofs_rcu_callback);
513 }
514 
z_erofs_collection_put(struct z_erofs_collection * cl)515 static void z_erofs_collection_put(struct z_erofs_collection *cl)
516 {
517 	struct z_erofs_pcluster *const pcl =
518 		container_of(cl, struct z_erofs_pcluster, primary_collection);
519 
520 	erofs_workgroup_put(&pcl->obj);
521 }
522 
z_erofs_collector_end(struct z_erofs_collector * clt)523 static bool z_erofs_collector_end(struct z_erofs_collector *clt)
524 {
525 	struct z_erofs_collection *cl = clt->cl;
526 
527 	if (!cl)
528 		return false;
529 
530 	z_erofs_pagevec_ctor_exit(&clt->vector, false);
531 	mutex_unlock(&cl->lock);
532 
533 	/*
534 	 * if all pending pages are added, don't hold its reference
535 	 * any longer if the pcluster isn't hosted by ourselves.
536 	 */
537 	if (clt->mode < COLLECT_PRIMARY_FOLLOWED_NOINPLACE)
538 		z_erofs_collection_put(cl);
539 
540 	clt->cl = NULL;
541 	return true;
542 }
543 
__stagingpage_alloc(struct list_head * pagepool,gfp_t gfp)544 static inline struct page *__stagingpage_alloc(struct list_head *pagepool,
545 					       gfp_t gfp)
546 {
547 	struct page *page = erofs_allocpage(pagepool, gfp, true);
548 
549 	page->mapping = Z_EROFS_MAPPING_STAGING;
550 	return page;
551 }
552 
should_alloc_managed_pages(struct z_erofs_decompress_frontend * fe,unsigned int cachestrategy,erofs_off_t la)553 static bool should_alloc_managed_pages(struct z_erofs_decompress_frontend *fe,
554 				       unsigned int cachestrategy,
555 				       erofs_off_t la)
556 {
557 	if (cachestrategy <= EROFS_ZIP_CACHE_DISABLED)
558 		return false;
559 
560 	if (fe->backmost)
561 		return true;
562 
563 	return cachestrategy >= EROFS_ZIP_CACHE_READAROUND &&
564 		la < fe->headoffset;
565 }
566 
z_erofs_do_read_page(struct z_erofs_decompress_frontend * fe,struct page * page,struct list_head * pagepool)567 static int z_erofs_do_read_page(struct z_erofs_decompress_frontend *fe,
568 				struct page *page,
569 				struct list_head *pagepool)
570 {
571 	struct inode *const inode = fe->inode;
572 	struct erofs_sb_info *const sbi __maybe_unused = EROFS_I_SB(inode);
573 	struct erofs_map_blocks *const map = &fe->map;
574 	struct z_erofs_collector *const clt = &fe->clt;
575 	const loff_t offset = page_offset(page);
576 	bool tight = true;
577 
578 	enum z_erofs_cache_alloctype cache_strategy;
579 	enum z_erofs_page_type page_type;
580 	unsigned int cur, end, spiltted, index;
581 	int err = 0;
582 
583 	/* register locked file pages as online pages in pack */
584 	z_erofs_onlinepage_init(page);
585 
586 	spiltted = 0;
587 	end = PAGE_SIZE;
588 repeat:
589 	cur = end - 1;
590 
591 	/* lucky, within the range of the current map_blocks */
592 	if (offset + cur >= map->m_la &&
593 	    offset + cur < map->m_la + map->m_llen) {
594 		/* didn't get a valid collection previously (very rare) */
595 		if (!clt->cl)
596 			goto restart_now;
597 		goto hitted;
598 	}
599 
600 	/* go ahead the next map_blocks */
601 	erofs_dbg("%s: [out-of-range] pos %llu", __func__, offset + cur);
602 
603 	if (z_erofs_collector_end(clt))
604 		fe->backmost = false;
605 
606 	map->m_la = offset + cur;
607 	map->m_llen = 0;
608 	err = z_erofs_map_blocks_iter(inode, map, 0);
609 	if (err)
610 		goto err_out;
611 
612 restart_now:
613 	if (!(map->m_flags & EROFS_MAP_MAPPED))
614 		goto hitted;
615 
616 	err = z_erofs_collector_begin(clt, inode, map);
617 	if (err)
618 		goto err_out;
619 
620 	/* preload all compressed pages (maybe downgrade role if necessary) */
621 	if (should_alloc_managed_pages(fe, sbi->cache_strategy, map->m_la))
622 		cache_strategy = DELAYEDALLOC;
623 	else
624 		cache_strategy = DONTALLOC;
625 
626 	preload_compressed_pages(clt, MNGD_MAPPING(sbi),
627 				 cache_strategy, pagepool);
628 
629 hitted:
630 	/*
631 	 * Ensure the current partial page belongs to this submit chain rather
632 	 * than other concurrent submit chains or the noio(bypass) chain since
633 	 * those chains are handled asynchronously thus the page cannot be used
634 	 * for inplace I/O or pagevec (should be processed in strict order.)
635 	 */
636 	tight &= (clt->mode >= COLLECT_PRIMARY_HOOKED &&
637 		  clt->mode != COLLECT_PRIMARY_FOLLOWED_NOINPLACE);
638 
639 	cur = end - min_t(erofs_off_t, offset + end - map->m_la, end);
640 	if (!(map->m_flags & EROFS_MAP_MAPPED)) {
641 		zero_user_segment(page, cur, end);
642 		++spiltted;
643 		tight = false;
644 		goto next_part;
645 	}
646 
647 	/* let's derive page type */
648 	page_type = cur ? Z_EROFS_VLE_PAGE_TYPE_HEAD :
649 		(!spiltted ? Z_EROFS_PAGE_TYPE_EXCLUSIVE :
650 			(tight ? Z_EROFS_PAGE_TYPE_EXCLUSIVE :
651 				Z_EROFS_VLE_PAGE_TYPE_TAIL_SHARED));
652 
653 	if (cur)
654 		tight &= (clt->mode >= COLLECT_PRIMARY_FOLLOWED);
655 
656 retry:
657 	err = z_erofs_attach_page(clt, page, page_type,
658 				  clt->mode >= COLLECT_PRIMARY_FOLLOWED);
659 	/* should allocate an additional staging page for pagevec */
660 	if (err == -EAGAIN) {
661 		struct page *const newpage =
662 			__stagingpage_alloc(pagepool, GFP_NOFS);
663 
664 		err = z_erofs_attach_page(clt, newpage,
665 					  Z_EROFS_PAGE_TYPE_EXCLUSIVE, true);
666 		if (!err)
667 			goto retry;
668 	}
669 
670 	if (err)
671 		goto err_out;
672 
673 	index = page->index - (map->m_la >> PAGE_SHIFT);
674 
675 	z_erofs_onlinepage_fixup(page, index, true);
676 
677 	/* bump up the number of spiltted parts of a page */
678 	++spiltted;
679 	/* also update nr_pages */
680 	clt->cl->nr_pages = max_t(pgoff_t, clt->cl->nr_pages, index + 1);
681 next_part:
682 	/* can be used for verification */
683 	map->m_llen = offset + cur - map->m_la;
684 
685 	end = cur;
686 	if (end > 0)
687 		goto repeat;
688 
689 out:
690 	z_erofs_onlinepage_endio(page);
691 
692 	erofs_dbg("%s, finish page: %pK spiltted: %u map->m_llen %llu",
693 		  __func__, page, spiltted, map->m_llen);
694 	return err;
695 
696 	/* if some error occurred while processing this page */
697 err_out:
698 	SetPageError(page);
699 	goto out;
700 }
701 
z_erofs_vle_unzip_kickoff(void * ptr,int bios)702 static void z_erofs_vle_unzip_kickoff(void *ptr, int bios)
703 {
704 	tagptr1_t t = tagptr_init(tagptr1_t, ptr);
705 	struct z_erofs_unzip_io *io = tagptr_unfold_ptr(t);
706 	bool background = tagptr_unfold_tags(t);
707 
708 	if (!background) {
709 		unsigned long flags;
710 
711 		spin_lock_irqsave(&io->u.wait.lock, flags);
712 		if (!atomic_add_return(bios, &io->pending_bios))
713 			wake_up_locked(&io->u.wait);
714 		spin_unlock_irqrestore(&io->u.wait.lock, flags);
715 		return;
716 	}
717 
718 	if (!atomic_add_return(bios, &io->pending_bios))
719 		queue_work(z_erofs_workqueue, &io->u.work);
720 }
721 
z_erofs_vle_read_endio(struct bio * bio)722 static inline void z_erofs_vle_read_endio(struct bio *bio)
723 {
724 	struct erofs_sb_info *sbi = NULL;
725 	blk_status_t err = bio->bi_status;
726 	struct bio_vec *bvec;
727 	struct bvec_iter_all iter_all;
728 
729 	bio_for_each_segment_all(bvec, bio, iter_all) {
730 		struct page *page = bvec->bv_page;
731 		bool cachemngd = false;
732 
733 		DBG_BUGON(PageUptodate(page));
734 		DBG_BUGON(!page->mapping);
735 
736 		if (!sbi && !z_erofs_page_is_staging(page))
737 			sbi = EROFS_SB(page->mapping->host->i_sb);
738 
739 		/* sbi should already be gotten if the page is managed */
740 		if (sbi)
741 			cachemngd = erofs_page_is_managed(sbi, page);
742 
743 		if (err)
744 			SetPageError(page);
745 		else if (cachemngd)
746 			SetPageUptodate(page);
747 
748 		if (cachemngd)
749 			unlock_page(page);
750 	}
751 
752 	z_erofs_vle_unzip_kickoff(bio->bi_private, -1);
753 	bio_put(bio);
754 }
755 
z_erofs_decompress_pcluster(struct super_block * sb,struct z_erofs_pcluster * pcl,struct list_head * pagepool)756 static int z_erofs_decompress_pcluster(struct super_block *sb,
757 				       struct z_erofs_pcluster *pcl,
758 				       struct list_head *pagepool)
759 {
760 	struct erofs_sb_info *const sbi = EROFS_SB(sb);
761 	const unsigned int clusterpages = BIT(pcl->clusterbits);
762 	struct z_erofs_pagevec_ctor ctor;
763 	unsigned int i, outputsize, llen, nr_pages;
764 	struct page *pages_onstack[Z_EROFS_VMAP_ONSTACK_PAGES];
765 	struct page **pages, **compressed_pages, *page;
766 
767 	enum z_erofs_page_type page_type;
768 	bool overlapped, partial;
769 	struct z_erofs_collection *cl;
770 	int err;
771 
772 	might_sleep();
773 	cl = z_erofs_primarycollection(pcl);
774 	DBG_BUGON(!READ_ONCE(cl->nr_pages));
775 
776 	mutex_lock(&cl->lock);
777 	nr_pages = cl->nr_pages;
778 
779 	if (nr_pages <= Z_EROFS_VMAP_ONSTACK_PAGES) {
780 		pages = pages_onstack;
781 	} else if (nr_pages <= Z_EROFS_VMAP_GLOBAL_PAGES &&
782 		   mutex_trylock(&z_pagemap_global_lock)) {
783 		pages = z_pagemap_global;
784 	} else {
785 		gfp_t gfp_flags = GFP_KERNEL;
786 
787 		if (nr_pages > Z_EROFS_VMAP_GLOBAL_PAGES)
788 			gfp_flags |= __GFP_NOFAIL;
789 
790 		pages = kvmalloc_array(nr_pages, sizeof(struct page *),
791 				       gfp_flags);
792 
793 		/* fallback to global pagemap for the lowmem scenario */
794 		if (!pages) {
795 			mutex_lock(&z_pagemap_global_lock);
796 			pages = z_pagemap_global;
797 		}
798 	}
799 
800 	for (i = 0; i < nr_pages; ++i)
801 		pages[i] = NULL;
802 
803 	err = 0;
804 	z_erofs_pagevec_ctor_init(&ctor, Z_EROFS_NR_INLINE_PAGEVECS,
805 				  cl->pagevec, 0);
806 
807 	for (i = 0; i < cl->vcnt; ++i) {
808 		unsigned int pagenr;
809 
810 		page = z_erofs_pagevec_dequeue(&ctor, &page_type);
811 
812 		/* all pages in pagevec ought to be valid */
813 		DBG_BUGON(!page);
814 		DBG_BUGON(!page->mapping);
815 
816 		if (z_erofs_put_stagingpage(pagepool, page))
817 			continue;
818 
819 		if (page_type == Z_EROFS_VLE_PAGE_TYPE_HEAD)
820 			pagenr = 0;
821 		else
822 			pagenr = z_erofs_onlinepage_index(page);
823 
824 		DBG_BUGON(pagenr >= nr_pages);
825 
826 		/*
827 		 * currently EROFS doesn't support multiref(dedup),
828 		 * so here erroring out one multiref page.
829 		 */
830 		if (pages[pagenr]) {
831 			DBG_BUGON(1);
832 			SetPageError(pages[pagenr]);
833 			z_erofs_onlinepage_endio(pages[pagenr]);
834 			err = -EFSCORRUPTED;
835 		}
836 		pages[pagenr] = page;
837 	}
838 	z_erofs_pagevec_ctor_exit(&ctor, true);
839 
840 	overlapped = false;
841 	compressed_pages = pcl->compressed_pages;
842 
843 	for (i = 0; i < clusterpages; ++i) {
844 		unsigned int pagenr;
845 
846 		page = compressed_pages[i];
847 
848 		/* all compressed pages ought to be valid */
849 		DBG_BUGON(!page);
850 		DBG_BUGON(!page->mapping);
851 
852 		if (!z_erofs_page_is_staging(page)) {
853 			if (erofs_page_is_managed(sbi, page)) {
854 				if (!PageUptodate(page))
855 					err = -EIO;
856 				continue;
857 			}
858 
859 			/*
860 			 * only if non-head page can be selected
861 			 * for inplace decompression
862 			 */
863 			pagenr = z_erofs_onlinepage_index(page);
864 
865 			DBG_BUGON(pagenr >= nr_pages);
866 			if (pages[pagenr]) {
867 				DBG_BUGON(1);
868 				SetPageError(pages[pagenr]);
869 				z_erofs_onlinepage_endio(pages[pagenr]);
870 				err = -EFSCORRUPTED;
871 			}
872 			pages[pagenr] = page;
873 
874 			overlapped = true;
875 		}
876 
877 		/* PG_error needs checking for inplaced and staging pages */
878 		if (PageError(page)) {
879 			DBG_BUGON(PageUptodate(page));
880 			err = -EIO;
881 		}
882 	}
883 
884 	if (err)
885 		goto out;
886 
887 	llen = pcl->length >> Z_EROFS_PCLUSTER_LENGTH_BIT;
888 	if (nr_pages << PAGE_SHIFT >= cl->pageofs + llen) {
889 		outputsize = llen;
890 		partial = !(pcl->length & Z_EROFS_PCLUSTER_FULL_LENGTH);
891 	} else {
892 		outputsize = (nr_pages << PAGE_SHIFT) - cl->pageofs;
893 		partial = true;
894 	}
895 
896 	err = z_erofs_decompress(&(struct z_erofs_decompress_req) {
897 					.sb = sb,
898 					.in = compressed_pages,
899 					.out = pages,
900 					.pageofs_out = cl->pageofs,
901 					.inputsize = PAGE_SIZE,
902 					.outputsize = outputsize,
903 					.alg = pcl->algorithmformat,
904 					.inplace_io = overlapped,
905 					.partial_decoding = partial
906 				 }, pagepool);
907 
908 out:
909 	/* must handle all compressed pages before endding pages */
910 	for (i = 0; i < clusterpages; ++i) {
911 		page = compressed_pages[i];
912 
913 		if (erofs_page_is_managed(sbi, page))
914 			continue;
915 
916 		/* recycle all individual staging pages */
917 		(void)z_erofs_put_stagingpage(pagepool, page);
918 
919 		WRITE_ONCE(compressed_pages[i], NULL);
920 	}
921 
922 	for (i = 0; i < nr_pages; ++i) {
923 		page = pages[i];
924 		if (!page)
925 			continue;
926 
927 		DBG_BUGON(!page->mapping);
928 
929 		/* recycle all individual staging pages */
930 		if (z_erofs_put_stagingpage(pagepool, page))
931 			continue;
932 
933 		if (err < 0)
934 			SetPageError(page);
935 
936 		z_erofs_onlinepage_endio(page);
937 	}
938 
939 	if (pages == z_pagemap_global)
940 		mutex_unlock(&z_pagemap_global_lock);
941 	else if (pages != pages_onstack)
942 		kvfree(pages);
943 
944 	cl->nr_pages = 0;
945 	cl->vcnt = 0;
946 
947 	/* all cl locks MUST be taken before the following line */
948 	WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_NIL);
949 
950 	/* all cl locks SHOULD be released right now */
951 	mutex_unlock(&cl->lock);
952 
953 	z_erofs_collection_put(cl);
954 	return err;
955 }
956 
z_erofs_vle_unzip_all(struct super_block * sb,struct z_erofs_unzip_io * io,struct list_head * pagepool)957 static void z_erofs_vle_unzip_all(struct super_block *sb,
958 				  struct z_erofs_unzip_io *io,
959 				  struct list_head *pagepool)
960 {
961 	z_erofs_next_pcluster_t owned = io->head;
962 
963 	while (owned != Z_EROFS_PCLUSTER_TAIL_CLOSED) {
964 		struct z_erofs_pcluster *pcl;
965 
966 		/* no possible that 'owned' equals Z_EROFS_WORK_TPTR_TAIL */
967 		DBG_BUGON(owned == Z_EROFS_PCLUSTER_TAIL);
968 
969 		/* no possible that 'owned' equals NULL */
970 		DBG_BUGON(owned == Z_EROFS_PCLUSTER_NIL);
971 
972 		pcl = container_of(owned, struct z_erofs_pcluster, next);
973 		owned = READ_ONCE(pcl->next);
974 
975 		z_erofs_decompress_pcluster(sb, pcl, pagepool);
976 	}
977 }
978 
z_erofs_vle_unzip_wq(struct work_struct * work)979 static void z_erofs_vle_unzip_wq(struct work_struct *work)
980 {
981 	struct z_erofs_unzip_io_sb *iosb =
982 		container_of(work, struct z_erofs_unzip_io_sb, io.u.work);
983 	LIST_HEAD(pagepool);
984 
985 	DBG_BUGON(iosb->io.head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
986 	z_erofs_vle_unzip_all(iosb->sb, &iosb->io, &pagepool);
987 
988 	put_pages_list(&pagepool);
989 	kvfree(iosb);
990 }
991 
pickup_page_for_submission(struct z_erofs_pcluster * pcl,unsigned int nr,struct list_head * pagepool,struct address_space * mc,gfp_t gfp)992 static struct page *pickup_page_for_submission(struct z_erofs_pcluster *pcl,
993 					       unsigned int nr,
994 					       struct list_head *pagepool,
995 					       struct address_space *mc,
996 					       gfp_t gfp)
997 {
998 	/* determined at compile time to avoid too many #ifdefs */
999 	const bool nocache = __builtin_constant_p(mc) ? !mc : false;
1000 	const pgoff_t index = pcl->obj.index;
1001 	bool tocache = false;
1002 
1003 	struct address_space *mapping;
1004 	struct page *oldpage, *page;
1005 
1006 	compressed_page_t t;
1007 	int justfound;
1008 
1009 repeat:
1010 	page = READ_ONCE(pcl->compressed_pages[nr]);
1011 	oldpage = page;
1012 
1013 	if (!page)
1014 		goto out_allocpage;
1015 
1016 	/*
1017 	 * the cached page has not been allocated and
1018 	 * an placeholder is out there, prepare it now.
1019 	 */
1020 	if (!nocache && page == PAGE_UNALLOCATED) {
1021 		tocache = true;
1022 		goto out_allocpage;
1023 	}
1024 
1025 	/* process the target tagged pointer */
1026 	t = tagptr_init(compressed_page_t, page);
1027 	justfound = tagptr_unfold_tags(t);
1028 	page = tagptr_unfold_ptr(t);
1029 
1030 	mapping = READ_ONCE(page->mapping);
1031 
1032 	/*
1033 	 * if managed cache is disabled, it's no way to
1034 	 * get such a cached-like page.
1035 	 */
1036 	if (nocache) {
1037 		/* if managed cache is disabled, it is impossible `justfound' */
1038 		DBG_BUGON(justfound);
1039 
1040 		/* and it should be locked, not uptodate, and not truncated */
1041 		DBG_BUGON(!PageLocked(page));
1042 		DBG_BUGON(PageUptodate(page));
1043 		DBG_BUGON(!mapping);
1044 		goto out;
1045 	}
1046 
1047 	/*
1048 	 * unmanaged (file) pages are all locked solidly,
1049 	 * therefore it is impossible for `mapping' to be NULL.
1050 	 */
1051 	if (mapping && mapping != mc)
1052 		/* ought to be unmanaged pages */
1053 		goto out;
1054 
1055 	lock_page(page);
1056 
1057 	/* only true if page reclaim goes wrong, should never happen */
1058 	DBG_BUGON(justfound && PagePrivate(page));
1059 
1060 	/* the page is still in manage cache */
1061 	if (page->mapping == mc) {
1062 		WRITE_ONCE(pcl->compressed_pages[nr], page);
1063 
1064 		ClearPageError(page);
1065 		if (!PagePrivate(page)) {
1066 			/*
1067 			 * impossible to be !PagePrivate(page) for
1068 			 * the current restriction as well if
1069 			 * the page is already in compressed_pages[].
1070 			 */
1071 			DBG_BUGON(!justfound);
1072 
1073 			justfound = 0;
1074 			set_page_private(page, (unsigned long)pcl);
1075 			SetPagePrivate(page);
1076 		}
1077 
1078 		/* no need to submit io if it is already up-to-date */
1079 		if (PageUptodate(page)) {
1080 			unlock_page(page);
1081 			page = NULL;
1082 		}
1083 		goto out;
1084 	}
1085 
1086 	/*
1087 	 * the managed page has been truncated, it's unsafe to
1088 	 * reuse this one, let's allocate a new cache-managed page.
1089 	 */
1090 	DBG_BUGON(page->mapping);
1091 	DBG_BUGON(!justfound);
1092 
1093 	tocache = true;
1094 	unlock_page(page);
1095 	put_page(page);
1096 out_allocpage:
1097 	page = __stagingpage_alloc(pagepool, gfp);
1098 	if (oldpage != cmpxchg(&pcl->compressed_pages[nr], oldpage, page)) {
1099 		list_add(&page->lru, pagepool);
1100 		cpu_relax();
1101 		goto repeat;
1102 	}
1103 	if (nocache || !tocache)
1104 		goto out;
1105 	if (add_to_page_cache_lru(page, mc, index + nr, gfp)) {
1106 		page->mapping = Z_EROFS_MAPPING_STAGING;
1107 		goto out;
1108 	}
1109 
1110 	set_page_private(page, (unsigned long)pcl);
1111 	SetPagePrivate(page);
1112 out:	/* the only exit (for tracing and debugging) */
1113 	return page;
1114 }
1115 
jobqueue_init(struct super_block * sb,struct z_erofs_unzip_io * io,bool foreground)1116 static struct z_erofs_unzip_io *jobqueue_init(struct super_block *sb,
1117 					      struct z_erofs_unzip_io *io,
1118 					      bool foreground)
1119 {
1120 	struct z_erofs_unzip_io_sb *iosb;
1121 
1122 	if (foreground) {
1123 		/* waitqueue available for foreground io */
1124 		DBG_BUGON(!io);
1125 
1126 		init_waitqueue_head(&io->u.wait);
1127 		atomic_set(&io->pending_bios, 0);
1128 		goto out;
1129 	}
1130 
1131 	iosb = kvzalloc(sizeof(*iosb), GFP_KERNEL | __GFP_NOFAIL);
1132 	DBG_BUGON(!iosb);
1133 
1134 	/* initialize fields in the allocated descriptor */
1135 	io = &iosb->io;
1136 	iosb->sb = sb;
1137 	INIT_WORK(&io->u.work, z_erofs_vle_unzip_wq);
1138 out:
1139 	io->head = Z_EROFS_PCLUSTER_TAIL_CLOSED;
1140 	return io;
1141 }
1142 
1143 /* define decompression jobqueue types */
1144 enum {
1145 	JQ_BYPASS,
1146 	JQ_SUBMIT,
1147 	NR_JOBQUEUES,
1148 };
1149 
jobqueueset_init(struct super_block * sb,z_erofs_next_pcluster_t qtail[],struct z_erofs_unzip_io * q[],struct z_erofs_unzip_io * fgq,bool forcefg)1150 static void *jobqueueset_init(struct super_block *sb,
1151 			      z_erofs_next_pcluster_t qtail[],
1152 			      struct z_erofs_unzip_io *q[],
1153 			      struct z_erofs_unzip_io *fgq,
1154 			      bool forcefg)
1155 {
1156 	/*
1157 	 * if managed cache is enabled, bypass jobqueue is needed,
1158 	 * no need to read from device for all pclusters in this queue.
1159 	 */
1160 	q[JQ_BYPASS] = jobqueue_init(sb, fgq + JQ_BYPASS, true);
1161 	qtail[JQ_BYPASS] = &q[JQ_BYPASS]->head;
1162 
1163 	q[JQ_SUBMIT] = jobqueue_init(sb, fgq + JQ_SUBMIT, forcefg);
1164 	qtail[JQ_SUBMIT] = &q[JQ_SUBMIT]->head;
1165 
1166 	return tagptr_cast_ptr(tagptr_fold(tagptr1_t, q[JQ_SUBMIT], !forcefg));
1167 }
1168 
move_to_bypass_jobqueue(struct z_erofs_pcluster * pcl,z_erofs_next_pcluster_t qtail[],z_erofs_next_pcluster_t owned_head)1169 static void move_to_bypass_jobqueue(struct z_erofs_pcluster *pcl,
1170 				    z_erofs_next_pcluster_t qtail[],
1171 				    z_erofs_next_pcluster_t owned_head)
1172 {
1173 	z_erofs_next_pcluster_t *const submit_qtail = qtail[JQ_SUBMIT];
1174 	z_erofs_next_pcluster_t *const bypass_qtail = qtail[JQ_BYPASS];
1175 
1176 	DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1177 	if (owned_head == Z_EROFS_PCLUSTER_TAIL)
1178 		owned_head = Z_EROFS_PCLUSTER_TAIL_CLOSED;
1179 
1180 	WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_TAIL_CLOSED);
1181 
1182 	WRITE_ONCE(*submit_qtail, owned_head);
1183 	WRITE_ONCE(*bypass_qtail, &pcl->next);
1184 
1185 	qtail[JQ_BYPASS] = &pcl->next;
1186 }
1187 
postsubmit_is_all_bypassed(struct z_erofs_unzip_io * q[],unsigned int nr_bios,bool force_fg)1188 static bool postsubmit_is_all_bypassed(struct z_erofs_unzip_io *q[],
1189 				       unsigned int nr_bios,
1190 				       bool force_fg)
1191 {
1192 	/*
1193 	 * although background is preferred, no one is pending for submission.
1194 	 * don't issue workqueue for decompression but drop it directly instead.
1195 	 */
1196 	if (force_fg || nr_bios)
1197 		return false;
1198 
1199 	kvfree(container_of(q[JQ_SUBMIT], struct z_erofs_unzip_io_sb, io));
1200 	return true;
1201 }
1202 
z_erofs_vle_submit_all(struct super_block * sb,z_erofs_next_pcluster_t owned_head,struct list_head * pagepool,struct z_erofs_unzip_io * fgq,bool force_fg)1203 static bool z_erofs_vle_submit_all(struct super_block *sb,
1204 				   z_erofs_next_pcluster_t owned_head,
1205 				   struct list_head *pagepool,
1206 				   struct z_erofs_unzip_io *fgq,
1207 				   bool force_fg)
1208 {
1209 	struct erofs_sb_info *const sbi __maybe_unused = EROFS_SB(sb);
1210 	z_erofs_next_pcluster_t qtail[NR_JOBQUEUES];
1211 	struct z_erofs_unzip_io *q[NR_JOBQUEUES];
1212 	struct bio *bio;
1213 	void *bi_private;
1214 	/* since bio will be NULL, no need to initialize last_index */
1215 	pgoff_t uninitialized_var(last_index);
1216 	bool force_submit = false;
1217 	unsigned int nr_bios;
1218 
1219 	if (owned_head == Z_EROFS_PCLUSTER_TAIL)
1220 		return false;
1221 
1222 	force_submit = false;
1223 	bio = NULL;
1224 	nr_bios = 0;
1225 	bi_private = jobqueueset_init(sb, qtail, q, fgq, force_fg);
1226 
1227 	/* by default, all need io submission */
1228 	q[JQ_SUBMIT]->head = owned_head;
1229 
1230 	do {
1231 		struct z_erofs_pcluster *pcl;
1232 		unsigned int clusterpages;
1233 		pgoff_t first_index;
1234 		struct page *page;
1235 		unsigned int i = 0, bypass = 0;
1236 		int err;
1237 
1238 		/* no possible 'owned_head' equals the following */
1239 		DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1240 		DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_NIL);
1241 
1242 		pcl = container_of(owned_head, struct z_erofs_pcluster, next);
1243 
1244 		clusterpages = BIT(pcl->clusterbits);
1245 
1246 		/* close the main owned chain at first */
1247 		owned_head = cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_TAIL,
1248 				     Z_EROFS_PCLUSTER_TAIL_CLOSED);
1249 
1250 		first_index = pcl->obj.index;
1251 		force_submit |= (first_index != last_index + 1);
1252 
1253 repeat:
1254 		page = pickup_page_for_submission(pcl, i, pagepool,
1255 						  MNGD_MAPPING(sbi),
1256 						  GFP_NOFS);
1257 		if (!page) {
1258 			force_submit = true;
1259 			++bypass;
1260 			goto skippage;
1261 		}
1262 
1263 		if (bio && force_submit) {
1264 submit_bio_retry:
1265 			submit_bio(bio);
1266 			bio = NULL;
1267 		}
1268 
1269 		if (!bio) {
1270 			bio = bio_alloc(GFP_NOIO, BIO_MAX_PAGES);
1271 
1272 			bio->bi_end_io = z_erofs_vle_read_endio;
1273 			bio_set_dev(bio, sb->s_bdev);
1274 			bio->bi_iter.bi_sector = (sector_t)(first_index + i) <<
1275 				LOG_SECTORS_PER_BLOCK;
1276 			bio->bi_private = bi_private;
1277 			bio->bi_opf = REQ_OP_READ;
1278 
1279 			++nr_bios;
1280 		}
1281 
1282 		err = bio_add_page(bio, page, PAGE_SIZE, 0);
1283 		if (err < PAGE_SIZE)
1284 			goto submit_bio_retry;
1285 
1286 		force_submit = false;
1287 		last_index = first_index + i;
1288 skippage:
1289 		if (++i < clusterpages)
1290 			goto repeat;
1291 
1292 		if (bypass < clusterpages)
1293 			qtail[JQ_SUBMIT] = &pcl->next;
1294 		else
1295 			move_to_bypass_jobqueue(pcl, qtail, owned_head);
1296 	} while (owned_head != Z_EROFS_PCLUSTER_TAIL);
1297 
1298 	if (bio)
1299 		submit_bio(bio);
1300 
1301 	if (postsubmit_is_all_bypassed(q, nr_bios, force_fg))
1302 		return true;
1303 
1304 	z_erofs_vle_unzip_kickoff(bi_private, nr_bios);
1305 	return true;
1306 }
1307 
z_erofs_submit_and_unzip(struct super_block * sb,struct z_erofs_collector * clt,struct list_head * pagepool,bool force_fg)1308 static void z_erofs_submit_and_unzip(struct super_block *sb,
1309 				     struct z_erofs_collector *clt,
1310 				     struct list_head *pagepool,
1311 				     bool force_fg)
1312 {
1313 	struct z_erofs_unzip_io io[NR_JOBQUEUES];
1314 
1315 	if (!z_erofs_vle_submit_all(sb, clt->owned_head,
1316 				    pagepool, io, force_fg))
1317 		return;
1318 
1319 	/* decompress no I/O pclusters immediately */
1320 	z_erofs_vle_unzip_all(sb, &io[JQ_BYPASS], pagepool);
1321 
1322 	if (!force_fg)
1323 		return;
1324 
1325 	/* wait until all bios are completed */
1326 	wait_event(io[JQ_SUBMIT].u.wait,
1327 		   !atomic_read(&io[JQ_SUBMIT].pending_bios));
1328 
1329 	/* let's synchronous decompression */
1330 	z_erofs_vle_unzip_all(sb, &io[JQ_SUBMIT], pagepool);
1331 }
1332 
z_erofs_vle_normalaccess_readpage(struct file * file,struct page * page)1333 static int z_erofs_vle_normalaccess_readpage(struct file *file,
1334 					     struct page *page)
1335 {
1336 	struct inode *const inode = page->mapping->host;
1337 	struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1338 	int err;
1339 	LIST_HEAD(pagepool);
1340 
1341 	trace_erofs_readpage(page, false);
1342 
1343 	f.headoffset = (erofs_off_t)page->index << PAGE_SHIFT;
1344 
1345 	err = z_erofs_do_read_page(&f, page, &pagepool);
1346 	(void)z_erofs_collector_end(&f.clt);
1347 
1348 	/* if some compressed cluster ready, need submit them anyway */
1349 	z_erofs_submit_and_unzip(inode->i_sb, &f.clt, &pagepool, true);
1350 
1351 	if (err)
1352 		erofs_err(inode->i_sb, "failed to read, err [%d]", err);
1353 
1354 	if (f.map.mpage)
1355 		put_page(f.map.mpage);
1356 
1357 	/* clean up the remaining free pages */
1358 	put_pages_list(&pagepool);
1359 	return err;
1360 }
1361 
should_decompress_synchronously(struct erofs_sb_info * sbi,unsigned int nr)1362 static bool should_decompress_synchronously(struct erofs_sb_info *sbi,
1363 					    unsigned int nr)
1364 {
1365 	return nr <= sbi->max_sync_decompress_pages;
1366 }
1367 
z_erofs_vle_normalaccess_readpages(struct file * filp,struct address_space * mapping,struct list_head * pages,unsigned int nr_pages)1368 static int z_erofs_vle_normalaccess_readpages(struct file *filp,
1369 					      struct address_space *mapping,
1370 					      struct list_head *pages,
1371 					      unsigned int nr_pages)
1372 {
1373 	struct inode *const inode = mapping->host;
1374 	struct erofs_sb_info *const sbi = EROFS_I_SB(inode);
1375 
1376 	bool sync = should_decompress_synchronously(sbi, nr_pages);
1377 	struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1378 	gfp_t gfp = mapping_gfp_constraint(mapping, GFP_KERNEL);
1379 	struct page *head = NULL;
1380 	LIST_HEAD(pagepool);
1381 
1382 	trace_erofs_readpages(mapping->host, lru_to_page(pages),
1383 			      nr_pages, false);
1384 
1385 	f.headoffset = (erofs_off_t)lru_to_page(pages)->index << PAGE_SHIFT;
1386 
1387 	for (; nr_pages; --nr_pages) {
1388 		struct page *page = lru_to_page(pages);
1389 
1390 		prefetchw(&page->flags);
1391 		list_del(&page->lru);
1392 
1393 		/*
1394 		 * A pure asynchronous readahead is indicated if
1395 		 * a PG_readahead marked page is hitted at first.
1396 		 * Let's also do asynchronous decompression for this case.
1397 		 */
1398 		sync &= !(PageReadahead(page) && !head);
1399 
1400 		if (add_to_page_cache_lru(page, mapping, page->index, gfp)) {
1401 			list_add(&page->lru, &pagepool);
1402 			continue;
1403 		}
1404 
1405 		set_page_private(page, (unsigned long)head);
1406 		head = page;
1407 	}
1408 
1409 	while (head) {
1410 		struct page *page = head;
1411 		int err;
1412 
1413 		/* traversal in reverse order */
1414 		head = (void *)page_private(page);
1415 
1416 		err = z_erofs_do_read_page(&f, page, &pagepool);
1417 		if (err)
1418 			erofs_err(inode->i_sb,
1419 				  "readahead error at page %lu @ nid %llu",
1420 				  page->index, EROFS_I(inode)->nid);
1421 		put_page(page);
1422 	}
1423 
1424 	(void)z_erofs_collector_end(&f.clt);
1425 
1426 	z_erofs_submit_and_unzip(inode->i_sb, &f.clt, &pagepool, sync);
1427 
1428 	if (f.map.mpage)
1429 		put_page(f.map.mpage);
1430 
1431 	/* clean up the remaining free pages */
1432 	put_pages_list(&pagepool);
1433 	return 0;
1434 }
1435 
1436 const struct address_space_operations z_erofs_vle_normalaccess_aops = {
1437 	.readpage = z_erofs_vle_normalaccess_readpage,
1438 	.readpages = z_erofs_vle_normalaccess_readpages,
1439 };
1440 
1441