1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2018 HUAWEI, Inc.
4 * https://www.huawei.com/
8 #include <linux/prefetch.h>
10 #include <trace/events/erofs.h>
13 * since pclustersize is variable for big pcluster feature, introduce slab
14 * pools implementation for different pcluster sizes.
16 struct z_erofs_pcluster_slab {
17 struct kmem_cache *slab;
18 unsigned int maxpages;
22 #define _PCLP(n) { .maxpages = n }
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)
29 static void z_erofs_destroy_pcluster_pool(void)
33 for (i = 0; i < ARRAY_SIZE(pcluster_pool); ++i) {
34 if (!pcluster_pool[i].slab)
36 kmem_cache_destroy(pcluster_pool[i].slab);
37 pcluster_pool[i].slab = NULL;
41 static int z_erofs_create_pcluster_pool(void)
43 struct z_erofs_pcluster_slab *pcs;
44 struct z_erofs_pcluster *a;
47 for (pcs = pcluster_pool;
48 pcs < pcluster_pool + ARRAY_SIZE(pcluster_pool); ++pcs) {
49 size = struct_size(a, compressed_pages, pcs->maxpages);
51 sprintf(pcs->name, "erofs_pcluster-%u", pcs->maxpages);
52 pcs->slab = kmem_cache_create(pcs->name, size, 0,
53 SLAB_RECLAIM_ACCOUNT, NULL);
57 z_erofs_destroy_pcluster_pool();
63 static struct z_erofs_pcluster *z_erofs_alloc_pcluster(unsigned int nrpages)
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;
71 if (nrpages > pcs->maxpages)
74 pcl = kmem_cache_zalloc(pcs->slab, GFP_NOFS);
76 return ERR_PTR(-ENOMEM);
77 pcl->pclusterpages = nrpages;
80 return ERR_PTR(-EINVAL);
83 static void z_erofs_free_pcluster(struct z_erofs_pcluster *pcl)
87 for (i = 0; i < ARRAY_SIZE(pcluster_pool); ++i) {
88 struct z_erofs_pcluster_slab *pcs = pcluster_pool + i;
90 if (pcl->pclusterpages > pcs->maxpages)
93 kmem_cache_free(pcs->slab, pcl);
100 * a compressed_pages[] placeholder in order to avoid
101 * being filled with file pages for in-place decompression.
103 #define PAGE_UNALLOCATED ((void *)0x5F0E4B1D)
105 /* how to allocate cached pages for a pcluster */
106 enum z_erofs_cache_alloctype {
107 DONTALLOC, /* don't allocate any cached pages */
108 DELAYEDALLOC, /* delayed allocation (at the time of submitting io) */
110 * try to use cached I/O if page allocation succeeds or fallback
111 * to in-place I/O instead to avoid any direct reclaim.
117 * tagged pointer with 1-bit tag for all compressed pages
118 * tag 0 - the page is just found with an extra page reference
120 typedef tagptr1_t compressed_page_t;
122 #define tag_compressed_page_justfound(page) \
123 tagptr_fold(compressed_page_t, page, 1)
125 static struct workqueue_struct *z_erofs_workqueue __read_mostly;
127 void z_erofs_exit_zip_subsystem(void)
129 destroy_workqueue(z_erofs_workqueue);
130 z_erofs_destroy_pcluster_pool();
133 static inline int z_erofs_init_workqueue(void)
135 const unsigned int onlinecpus = num_possible_cpus();
138 * no need to spawn too many threads, limiting threads could minimum
139 * scheduling overhead, perhaps per-CPU threads should be better?
141 z_erofs_workqueue = alloc_workqueue("erofs_unzipd",
142 WQ_UNBOUND | WQ_HIGHPRI,
143 onlinecpus + onlinecpus / 4);
144 return z_erofs_workqueue ? 0 : -ENOMEM;
147 int __init z_erofs_init_zip_subsystem(void)
149 int err = z_erofs_create_pcluster_pool();
153 err = z_erofs_init_workqueue();
155 z_erofs_destroy_pcluster_pool();
159 enum z_erofs_collectmode {
163 * The current collection was the tail of an exist chain, in addition
164 * that the previous processed chained collections are all decided to
165 * be hooked up to it.
166 * A new chain will be created for the remaining collections which are
167 * not processed yet, therefore different from COLLECT_PRIMARY_FOLLOWED,
168 * the next collection cannot reuse the whole page safely in
169 * the following scenario:
170 * ________________________________________________________________
171 * | tail (partial) page | head (partial) page |
172 * | (belongs to the next cl) | (belongs to the current cl) |
173 * |_______PRIMARY_FOLLOWED_______|________PRIMARY_HOOKED___________|
175 COLLECT_PRIMARY_HOOKED,
177 * a weak form of COLLECT_PRIMARY_FOLLOWED, the difference is that it
178 * could be dispatched into bypass queue later due to uptodated managed
179 * pages. All related online pages cannot be reused for inplace I/O (or
180 * pagevec) since it can be directly decoded without I/O submission.
182 COLLECT_PRIMARY_FOLLOWED_NOINPLACE,
184 * The current collection has been linked with the owned chain, and
185 * could also be linked with the remaining collections, which means
186 * if the processing page is the tail page of the collection, thus
187 * the current collection can safely use the whole page (since
188 * the previous collection is under control) for in-place I/O, as
190 * ________________________________________________________________
191 * | tail (partial) page | head (partial) page |
192 * | (of the current cl) | (of the previous collection) |
193 * | PRIMARY_FOLLOWED or | |
194 * |_____PRIMARY_HOOKED___|____________PRIMARY_FOLLOWED____________|
196 * [ (*) the above page can be used as inplace I/O. ]
198 COLLECT_PRIMARY_FOLLOWED,
201 struct z_erofs_collector {
202 struct z_erofs_pagevec_ctor vector;
204 struct z_erofs_pcluster *pcl, *tailpcl;
205 struct z_erofs_collection *cl;
206 /* a pointer used to pick up inplace I/O pages */
207 struct page **icpage_ptr;
208 z_erofs_next_pcluster_t owned_head;
210 enum z_erofs_collectmode mode;
213 struct z_erofs_decompress_frontend {
214 struct inode *const inode;
216 struct z_erofs_collector clt;
217 struct erofs_map_blocks map;
220 /* used for applying cache strategy on the fly */
222 erofs_off_t headoffset;
225 #define COLLECTOR_INIT() { \
226 .owned_head = Z_EROFS_PCLUSTER_TAIL, \
227 .mode = COLLECT_PRIMARY_FOLLOWED }
229 #define DECOMPRESS_FRONTEND_INIT(__i) { \
230 .inode = __i, .clt = COLLECTOR_INIT(), \
233 static struct page *z_pagemap_global[Z_EROFS_VMAP_GLOBAL_PAGES];
234 static DEFINE_MUTEX(z_pagemap_global_lock);
236 static void preload_compressed_pages(struct z_erofs_collector *clt,
237 struct address_space *mc,
238 enum z_erofs_cache_alloctype type,
239 struct list_head *pagepool)
241 struct z_erofs_pcluster *pcl = clt->pcl;
242 bool standalone = true;
243 gfp_t gfp = (mapping_gfp_mask(mc) & ~__GFP_DIRECT_RECLAIM) |
244 __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN;
248 if (clt->mode < COLLECT_PRIMARY_FOLLOWED)
251 pages = pcl->compressed_pages;
252 index = pcl->obj.index;
253 for (; index < pcl->obj.index + pcl->pclusterpages; ++index, ++pages) {
256 struct page *newpage = NULL;
258 /* the compressed page was loaded before */
259 if (READ_ONCE(*pages))
262 page = find_get_page(mc, index);
265 t = tag_compressed_page_justfound(page);
267 /* I/O is needed, no possible to decompress directly */
271 t = tagptr_init(compressed_page_t,
275 newpage = erofs_allocpage(pagepool, gfp);
278 set_page_private(newpage,
279 Z_EROFS_PREALLOCATED_PAGE);
280 t = tag_compressed_page_justfound(newpage);
282 default: /* DONTALLOC */
287 if (!cmpxchg_relaxed(pages, NULL, tagptr_cast_ptr(t)))
292 } else if (newpage) {
293 set_page_private(newpage, 0);
294 list_add(&newpage->lru, pagepool);
299 * don't do inplace I/O if all compressed pages are available in
300 * managed cache since it can be moved to the bypass queue instead.
303 clt->mode = COLLECT_PRIMARY_FOLLOWED_NOINPLACE;
306 /* called by erofs_shrinker to get rid of all compressed_pages */
307 int erofs_try_to_free_all_cached_pages(struct erofs_sb_info *sbi,
308 struct erofs_workgroup *grp)
310 struct z_erofs_pcluster *const pcl =
311 container_of(grp, struct z_erofs_pcluster, obj);
315 * refcount of workgroup is now freezed as 1,
316 * therefore no need to worry about available decompression users.
318 for (i = 0; i < pcl->pclusterpages; ++i) {
319 struct page *page = pcl->compressed_pages[i];
324 /* block other users from reclaiming or migrating the page */
325 if (!trylock_page(page))
328 if (!erofs_page_is_managed(sbi, page))
331 /* barrier is implied in the following 'unlock_page' */
332 WRITE_ONCE(pcl->compressed_pages[i], NULL);
333 detach_page_private(page);
339 int erofs_try_to_free_cached_page(struct page *page)
341 struct z_erofs_pcluster *const pcl = (void *)page_private(page);
342 int ret = 0; /* 0 - busy */
344 if (erofs_workgroup_try_to_freeze(&pcl->obj, 1)) {
347 for (i = 0; i < pcl->pclusterpages; ++i) {
348 if (pcl->compressed_pages[i] == page) {
349 WRITE_ONCE(pcl->compressed_pages[i], NULL);
354 erofs_workgroup_unfreeze(&pcl->obj, 1);
357 detach_page_private(page);
362 /* page_type must be Z_EROFS_PAGE_TYPE_EXCLUSIVE */
363 static bool z_erofs_try_inplace_io(struct z_erofs_collector *clt,
366 struct z_erofs_pcluster *const pcl = clt->pcl;
368 while (clt->icpage_ptr > pcl->compressed_pages)
369 if (!cmpxchg(--clt->icpage_ptr, NULL, page))
374 /* callers must be with collection lock held */
375 static int z_erofs_attach_page(struct z_erofs_collector *clt,
376 struct page *page, enum z_erofs_page_type type,
381 /* give priority for inplaceio */
382 if (clt->mode >= COLLECT_PRIMARY &&
383 type == Z_EROFS_PAGE_TYPE_EXCLUSIVE &&
384 z_erofs_try_inplace_io(clt, page))
387 ret = z_erofs_pagevec_enqueue(&clt->vector, page, type,
389 clt->cl->vcnt += (unsigned int)ret;
390 return ret ? 0 : -EAGAIN;
393 static void z_erofs_try_to_claim_pcluster(struct z_erofs_collector *clt)
395 struct z_erofs_pcluster *pcl = clt->pcl;
396 z_erofs_next_pcluster_t *owned_head = &clt->owned_head;
398 /* type 1, nil pcluster (this pcluster doesn't belong to any chain.) */
399 if (cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_NIL,
400 *owned_head) == Z_EROFS_PCLUSTER_NIL) {
401 *owned_head = &pcl->next;
402 /* so we can attach this pcluster to our submission chain. */
403 clt->mode = COLLECT_PRIMARY_FOLLOWED;
408 * type 2, link to the end of an existing open chain, be careful
409 * that its submission is controlled by the original attached chain.
411 if (cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_TAIL,
412 *owned_head) == Z_EROFS_PCLUSTER_TAIL) {
413 *owned_head = Z_EROFS_PCLUSTER_TAIL;
414 clt->mode = COLLECT_PRIMARY_HOOKED;
418 /* type 3, it belongs to a chain, but it isn't the end of the chain */
419 clt->mode = COLLECT_PRIMARY;
422 static int z_erofs_lookup_collection(struct z_erofs_collector *clt,
424 struct erofs_map_blocks *map)
426 struct z_erofs_pcluster *pcl = clt->pcl;
427 struct z_erofs_collection *cl;
430 /* to avoid unexpected loop formed by corrupted images */
431 if (clt->owned_head == &pcl->next || pcl == clt->tailpcl) {
433 return -EFSCORRUPTED;
436 cl = z_erofs_primarycollection(pcl);
437 if (cl->pageofs != (map->m_la & ~PAGE_MASK)) {
439 return -EFSCORRUPTED;
442 length = READ_ONCE(pcl->length);
443 if (length & Z_EROFS_PCLUSTER_FULL_LENGTH) {
444 if ((map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT) > length) {
446 return -EFSCORRUPTED;
449 unsigned int llen = map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT;
451 if (map->m_flags & EROFS_MAP_FULL_MAPPED)
452 llen |= Z_EROFS_PCLUSTER_FULL_LENGTH;
454 while (llen > length &&
455 length != cmpxchg_relaxed(&pcl->length, length, llen)) {
457 length = READ_ONCE(pcl->length);
460 mutex_lock(&cl->lock);
461 /* used to check tail merging loop due to corrupted images */
462 if (clt->owned_head == Z_EROFS_PCLUSTER_TAIL)
465 z_erofs_try_to_claim_pcluster(clt);
470 static int z_erofs_register_collection(struct z_erofs_collector *clt,
472 struct erofs_map_blocks *map)
474 struct z_erofs_pcluster *pcl;
475 struct z_erofs_collection *cl;
476 struct erofs_workgroup *grp;
479 /* no available pcluster, let's allocate one */
480 pcl = z_erofs_alloc_pcluster(map->m_plen >> PAGE_SHIFT);
484 atomic_set(&pcl->obj.refcount, 1);
485 pcl->obj.index = map->m_pa >> PAGE_SHIFT;
487 pcl->length = (map->m_llen << Z_EROFS_PCLUSTER_LENGTH_BIT) |
488 (map->m_flags & EROFS_MAP_FULL_MAPPED ?
489 Z_EROFS_PCLUSTER_FULL_LENGTH : 0);
491 if (map->m_flags & EROFS_MAP_ZIPPED)
492 pcl->algorithmformat = Z_EROFS_COMPRESSION_LZ4;
494 pcl->algorithmformat = Z_EROFS_COMPRESSION_SHIFTED;
496 /* new pclusters should be claimed as type 1, primary and followed */
497 pcl->next = clt->owned_head;
498 clt->mode = COLLECT_PRIMARY_FOLLOWED;
500 cl = z_erofs_primarycollection(pcl);
501 cl->pageofs = map->m_la & ~PAGE_MASK;
504 * lock all primary followed works before visible to others
505 * and mutex_trylock *never* fails for a new pcluster.
507 mutex_init(&cl->lock);
508 DBG_BUGON(!mutex_trylock(&cl->lock));
510 grp = erofs_insert_workgroup(inode->i_sb, &pcl->obj);
516 if (grp != &pcl->obj) {
517 clt->pcl = container_of(grp, struct z_erofs_pcluster, obj);
521 /* used to check tail merging loop due to corrupted images */
522 if (clt->owned_head == Z_EROFS_PCLUSTER_TAIL)
524 clt->owned_head = &pcl->next;
530 mutex_unlock(&cl->lock);
531 z_erofs_free_pcluster(pcl);
535 static int z_erofs_collector_begin(struct z_erofs_collector *clt,
537 struct erofs_map_blocks *map)
539 struct erofs_workgroup *grp;
544 /* must be Z_EROFS_PCLUSTER_TAIL or pointed to previous collection */
545 DBG_BUGON(clt->owned_head == Z_EROFS_PCLUSTER_NIL);
546 DBG_BUGON(clt->owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
548 if (!PAGE_ALIGNED(map->m_pa)) {
553 grp = erofs_find_workgroup(inode->i_sb, map->m_pa >> PAGE_SHIFT);
555 clt->pcl = container_of(grp, struct z_erofs_pcluster, obj);
557 ret = z_erofs_register_collection(clt, inode, map);
565 ret = z_erofs_lookup_collection(clt, inode, map);
567 erofs_workgroup_put(&clt->pcl->obj);
572 z_erofs_pagevec_ctor_init(&clt->vector, Z_EROFS_NR_INLINE_PAGEVECS,
573 clt->cl->pagevec, clt->cl->vcnt);
575 /* since file-backed online pages are traversed in reverse order */
576 clt->icpage_ptr = clt->pcl->compressed_pages + clt->pcl->pclusterpages;
581 * keep in mind that no referenced pclusters will be freed
582 * only after a RCU grace period.
584 static void z_erofs_rcu_callback(struct rcu_head *head)
586 struct z_erofs_collection *const cl =
587 container_of(head, struct z_erofs_collection, rcu);
589 z_erofs_free_pcluster(container_of(cl, struct z_erofs_pcluster,
590 primary_collection));
593 void erofs_workgroup_free_rcu(struct erofs_workgroup *grp)
595 struct z_erofs_pcluster *const pcl =
596 container_of(grp, struct z_erofs_pcluster, obj);
597 struct z_erofs_collection *const cl = z_erofs_primarycollection(pcl);
599 call_rcu(&cl->rcu, z_erofs_rcu_callback);
602 static void z_erofs_collection_put(struct z_erofs_collection *cl)
604 struct z_erofs_pcluster *const pcl =
605 container_of(cl, struct z_erofs_pcluster, primary_collection);
607 erofs_workgroup_put(&pcl->obj);
610 static bool z_erofs_collector_end(struct z_erofs_collector *clt)
612 struct z_erofs_collection *cl = clt->cl;
617 z_erofs_pagevec_ctor_exit(&clt->vector, false);
618 mutex_unlock(&cl->lock);
621 * if all pending pages are added, don't hold its reference
622 * any longer if the pcluster isn't hosted by ourselves.
624 if (clt->mode < COLLECT_PRIMARY_FOLLOWED_NOINPLACE)
625 z_erofs_collection_put(cl);
631 static bool should_alloc_managed_pages(struct z_erofs_decompress_frontend *fe,
632 unsigned int cachestrategy,
635 if (cachestrategy <= EROFS_ZIP_CACHE_DISABLED)
641 return cachestrategy >= EROFS_ZIP_CACHE_READAROUND &&
645 static int z_erofs_do_read_page(struct z_erofs_decompress_frontend *fe,
646 struct page *page, struct list_head *pagepool)
648 struct inode *const inode = fe->inode;
649 struct erofs_sb_info *const sbi = EROFS_I_SB(inode);
650 struct erofs_map_blocks *const map = &fe->map;
651 struct z_erofs_collector *const clt = &fe->clt;
652 const loff_t offset = page_offset(page);
655 enum z_erofs_cache_alloctype cache_strategy;
656 enum z_erofs_page_type page_type;
657 unsigned int cur, end, spiltted, index;
660 /* register locked file pages as online pages in pack */
661 z_erofs_onlinepage_init(page);
668 /* lucky, within the range of the current map_blocks */
669 if (offset + cur >= map->m_la &&
670 offset + cur < map->m_la + map->m_llen) {
671 /* didn't get a valid collection previously (very rare) */
677 /* go ahead the next map_blocks */
678 erofs_dbg("%s: [out-of-range] pos %llu", __func__, offset + cur);
680 if (z_erofs_collector_end(clt))
681 fe->backmost = false;
683 map->m_la = offset + cur;
685 err = z_erofs_map_blocks_iter(inode, map, 0);
690 if (!(map->m_flags & EROFS_MAP_MAPPED))
693 err = z_erofs_collector_begin(clt, inode, map);
697 /* preload all compressed pages (maybe downgrade role if necessary) */
698 if (should_alloc_managed_pages(fe, sbi->ctx.cache_strategy, map->m_la))
699 cache_strategy = TRYALLOC;
701 cache_strategy = DONTALLOC;
703 preload_compressed_pages(clt, MNGD_MAPPING(sbi),
704 cache_strategy, pagepool);
708 * Ensure the current partial page belongs to this submit chain rather
709 * than other concurrent submit chains or the noio(bypass) chain since
710 * those chains are handled asynchronously thus the page cannot be used
711 * for inplace I/O or pagevec (should be processed in strict order.)
713 tight &= (clt->mode >= COLLECT_PRIMARY_HOOKED &&
714 clt->mode != COLLECT_PRIMARY_FOLLOWED_NOINPLACE);
716 cur = end - min_t(unsigned int, offset + end - map->m_la, end);
717 if (!(map->m_flags & EROFS_MAP_MAPPED)) {
718 zero_user_segment(page, cur, end);
722 /* let's derive page type */
723 page_type = cur ? Z_EROFS_VLE_PAGE_TYPE_HEAD :
724 (!spiltted ? Z_EROFS_PAGE_TYPE_EXCLUSIVE :
725 (tight ? Z_EROFS_PAGE_TYPE_EXCLUSIVE :
726 Z_EROFS_VLE_PAGE_TYPE_TAIL_SHARED));
729 tight &= (clt->mode >= COLLECT_PRIMARY_FOLLOWED);
732 err = z_erofs_attach_page(clt, page, page_type,
733 clt->mode >= COLLECT_PRIMARY_FOLLOWED);
734 /* should allocate an additional short-lived page for pagevec */
735 if (err == -EAGAIN) {
736 struct page *const newpage =
737 alloc_page(GFP_NOFS | __GFP_NOFAIL);
739 set_page_private(newpage, Z_EROFS_SHORTLIVED_PAGE);
740 err = z_erofs_attach_page(clt, newpage,
741 Z_EROFS_PAGE_TYPE_EXCLUSIVE, true);
749 index = page->index - (map->m_la >> PAGE_SHIFT);
751 z_erofs_onlinepage_fixup(page, index, true);
753 /* bump up the number of spiltted parts of a page */
755 /* also update nr_pages */
756 clt->cl->nr_pages = max_t(pgoff_t, clt->cl->nr_pages, index + 1);
758 /* can be used for verification */
759 map->m_llen = offset + cur - map->m_la;
766 z_erofs_onlinepage_endio(page);
768 erofs_dbg("%s, finish page: %pK spiltted: %u map->m_llen %llu",
769 __func__, page, spiltted, map->m_llen);
772 /* if some error occurred while processing this page */
778 static void z_erofs_decompressqueue_work(struct work_struct *work);
779 static void z_erofs_decompress_kickoff(struct z_erofs_decompressqueue *io,
782 struct erofs_sb_info *const sbi = EROFS_SB(io->sb);
784 /* wake up the caller thread for sync decompression */
788 spin_lock_irqsave(&io->u.wait.lock, flags);
789 if (!atomic_add_return(bios, &io->pending_bios))
790 wake_up_locked(&io->u.wait);
791 spin_unlock_irqrestore(&io->u.wait.lock, flags);
795 if (atomic_add_return(bios, &io->pending_bios))
797 /* Use workqueue and sync decompression for atomic contexts only */
798 if (in_atomic() || irqs_disabled()) {
799 queue_work(z_erofs_workqueue, &io->u.work);
800 sbi->ctx.readahead_sync_decompress = true;
803 z_erofs_decompressqueue_work(&io->u.work);
806 static bool z_erofs_page_is_invalidated(struct page *page)
808 return !page->mapping && !z_erofs_is_shortlived_page(page);
811 static void z_erofs_decompressqueue_endio(struct bio *bio)
813 tagptr1_t t = tagptr_init(tagptr1_t, bio->bi_private);
814 struct z_erofs_decompressqueue *q = tagptr_unfold_ptr(t);
815 blk_status_t err = bio->bi_status;
816 struct bio_vec *bvec;
817 struct bvec_iter_all iter_all;
819 bio_for_each_segment_all(bvec, bio, iter_all) {
820 struct page *page = bvec->bv_page;
822 DBG_BUGON(PageUptodate(page));
823 DBG_BUGON(z_erofs_page_is_invalidated(page));
828 if (erofs_page_is_managed(EROFS_SB(q->sb), page)) {
830 SetPageUptodate(page);
834 z_erofs_decompress_kickoff(q, tagptr_unfold_tags(t), -1);
838 static int z_erofs_decompress_pcluster(struct super_block *sb,
839 struct z_erofs_pcluster *pcl,
840 struct list_head *pagepool)
842 struct erofs_sb_info *const sbi = EROFS_SB(sb);
843 struct z_erofs_pagevec_ctor ctor;
844 unsigned int i, inputsize, outputsize, llen, nr_pages;
845 struct page *pages_onstack[Z_EROFS_VMAP_ONSTACK_PAGES];
846 struct page **pages, **compressed_pages, *page;
848 enum z_erofs_page_type page_type;
849 bool overlapped, partial;
850 struct z_erofs_collection *cl;
854 cl = z_erofs_primarycollection(pcl);
855 DBG_BUGON(!READ_ONCE(cl->nr_pages));
857 mutex_lock(&cl->lock);
858 nr_pages = cl->nr_pages;
860 if (nr_pages <= Z_EROFS_VMAP_ONSTACK_PAGES) {
861 pages = pages_onstack;
862 } else if (nr_pages <= Z_EROFS_VMAP_GLOBAL_PAGES &&
863 mutex_trylock(&z_pagemap_global_lock)) {
864 pages = z_pagemap_global;
866 gfp_t gfp_flags = GFP_KERNEL;
868 if (nr_pages > Z_EROFS_VMAP_GLOBAL_PAGES)
869 gfp_flags |= __GFP_NOFAIL;
871 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
874 /* fallback to global pagemap for the lowmem scenario */
876 mutex_lock(&z_pagemap_global_lock);
877 pages = z_pagemap_global;
881 for (i = 0; i < nr_pages; ++i)
885 z_erofs_pagevec_ctor_init(&ctor, Z_EROFS_NR_INLINE_PAGEVECS,
888 for (i = 0; i < cl->vcnt; ++i) {
891 page = z_erofs_pagevec_dequeue(&ctor, &page_type);
893 /* all pages in pagevec ought to be valid */
895 DBG_BUGON(z_erofs_page_is_invalidated(page));
897 if (z_erofs_put_shortlivedpage(pagepool, page))
900 if (page_type == Z_EROFS_VLE_PAGE_TYPE_HEAD)
903 pagenr = z_erofs_onlinepage_index(page);
905 DBG_BUGON(pagenr >= nr_pages);
908 * currently EROFS doesn't support multiref(dedup),
909 * so here erroring out one multiref page.
913 SetPageError(pages[pagenr]);
914 z_erofs_onlinepage_endio(pages[pagenr]);
917 pages[pagenr] = page;
919 z_erofs_pagevec_ctor_exit(&ctor, true);
922 compressed_pages = pcl->compressed_pages;
924 for (i = 0; i < pcl->pclusterpages; ++i) {
927 page = compressed_pages[i];
929 /* all compressed pages ought to be valid */
931 DBG_BUGON(z_erofs_page_is_invalidated(page));
933 if (!z_erofs_is_shortlived_page(page)) {
934 if (erofs_page_is_managed(sbi, page)) {
935 if (!PageUptodate(page))
941 * only if non-head page can be selected
942 * for inplace decompression
944 pagenr = z_erofs_onlinepage_index(page);
946 DBG_BUGON(pagenr >= nr_pages);
949 SetPageError(pages[pagenr]);
950 z_erofs_onlinepage_endio(pages[pagenr]);
953 pages[pagenr] = page;
958 /* PG_error needs checking for all non-managed pages */
959 if (PageError(page)) {
960 DBG_BUGON(PageUptodate(page));
968 llen = pcl->length >> Z_EROFS_PCLUSTER_LENGTH_BIT;
969 if (nr_pages << PAGE_SHIFT >= cl->pageofs + llen) {
971 partial = !(pcl->length & Z_EROFS_PCLUSTER_FULL_LENGTH);
973 outputsize = (nr_pages << PAGE_SHIFT) - cl->pageofs;
977 inputsize = pcl->pclusterpages * PAGE_SIZE;
978 err = z_erofs_decompress(&(struct z_erofs_decompress_req) {
980 .in = compressed_pages,
982 .pageofs_out = cl->pageofs,
983 .inputsize = inputsize,
984 .outputsize = outputsize,
985 .alg = pcl->algorithmformat,
986 .inplace_io = overlapped,
987 .partial_decoding = partial
991 /* must handle all compressed pages before ending pages */
992 for (i = 0; i < pcl->pclusterpages; ++i) {
993 page = compressed_pages[i];
995 if (erofs_page_is_managed(sbi, page))
998 /* recycle all individual short-lived pages */
999 (void)z_erofs_put_shortlivedpage(pagepool, page);
1001 WRITE_ONCE(compressed_pages[i], NULL);
1004 for (i = 0; i < nr_pages; ++i) {
1009 DBG_BUGON(z_erofs_page_is_invalidated(page));
1011 /* recycle all individual short-lived pages */
1012 if (z_erofs_put_shortlivedpage(pagepool, page))
1018 z_erofs_onlinepage_endio(page);
1021 if (pages == z_pagemap_global)
1022 mutex_unlock(&z_pagemap_global_lock);
1023 else if (pages != pages_onstack)
1029 /* all cl locks MUST be taken before the following line */
1030 WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_NIL);
1032 /* all cl locks SHOULD be released right now */
1033 mutex_unlock(&cl->lock);
1035 z_erofs_collection_put(cl);
1039 static void z_erofs_decompress_queue(const struct z_erofs_decompressqueue *io,
1040 struct list_head *pagepool)
1042 z_erofs_next_pcluster_t owned = io->head;
1044 while (owned != Z_EROFS_PCLUSTER_TAIL_CLOSED) {
1045 struct z_erofs_pcluster *pcl;
1047 /* no possible that 'owned' equals Z_EROFS_WORK_TPTR_TAIL */
1048 DBG_BUGON(owned == Z_EROFS_PCLUSTER_TAIL);
1050 /* no possible that 'owned' equals NULL */
1051 DBG_BUGON(owned == Z_EROFS_PCLUSTER_NIL);
1053 pcl = container_of(owned, struct z_erofs_pcluster, next);
1054 owned = READ_ONCE(pcl->next);
1056 z_erofs_decompress_pcluster(io->sb, pcl, pagepool);
1060 static void z_erofs_decompressqueue_work(struct work_struct *work)
1062 struct z_erofs_decompressqueue *bgq =
1063 container_of(work, struct z_erofs_decompressqueue, u.work);
1064 LIST_HEAD(pagepool);
1066 DBG_BUGON(bgq->head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1067 z_erofs_decompress_queue(bgq, &pagepool);
1069 put_pages_list(&pagepool);
1073 static struct page *pickup_page_for_submission(struct z_erofs_pcluster *pcl,
1075 struct list_head *pagepool,
1076 struct address_space *mc,
1079 const pgoff_t index = pcl->obj.index;
1080 bool tocache = false;
1082 struct address_space *mapping;
1083 struct page *oldpage, *page;
1085 compressed_page_t t;
1089 page = READ_ONCE(pcl->compressed_pages[nr]);
1096 * the cached page has not been allocated and
1097 * an placeholder is out there, prepare it now.
1099 if (page == PAGE_UNALLOCATED) {
1104 /* process the target tagged pointer */
1105 t = tagptr_init(compressed_page_t, page);
1106 justfound = tagptr_unfold_tags(t);
1107 page = tagptr_unfold_ptr(t);
1110 * preallocated cached pages, which is used to avoid direct reclaim
1111 * otherwise, it will go inplace I/O path instead.
1113 if (page->private == Z_EROFS_PREALLOCATED_PAGE) {
1114 WRITE_ONCE(pcl->compressed_pages[nr], page);
1115 set_page_private(page, 0);
1119 mapping = READ_ONCE(page->mapping);
1122 * file-backed online pages in plcuster are all locked steady,
1123 * therefore it is impossible for `mapping' to be NULL.
1125 if (mapping && mapping != mc)
1126 /* ought to be unmanaged pages */
1129 /* directly return for shortlived page as well */
1130 if (z_erofs_is_shortlived_page(page))
1135 /* only true if page reclaim goes wrong, should never happen */
1136 DBG_BUGON(justfound && PagePrivate(page));
1138 /* the page is still in manage cache */
1139 if (page->mapping == mc) {
1140 WRITE_ONCE(pcl->compressed_pages[nr], page);
1142 ClearPageError(page);
1143 if (!PagePrivate(page)) {
1145 * impossible to be !PagePrivate(page) for
1146 * the current restriction as well if
1147 * the page is already in compressed_pages[].
1149 DBG_BUGON(!justfound);
1152 set_page_private(page, (unsigned long)pcl);
1153 SetPagePrivate(page);
1156 /* no need to submit io if it is already up-to-date */
1157 if (PageUptodate(page)) {
1165 * the managed page has been truncated, it's unsafe to
1166 * reuse this one, let's allocate a new cache-managed page.
1168 DBG_BUGON(page->mapping);
1169 DBG_BUGON(!justfound);
1175 page = erofs_allocpage(pagepool, gfp | __GFP_NOFAIL);
1176 if (oldpage != cmpxchg(&pcl->compressed_pages[nr], oldpage, page)) {
1177 list_add(&page->lru, pagepool);
1182 if (!tocache || add_to_page_cache_lru(page, mc, index + nr, gfp)) {
1183 /* turn into temporary page if fails (1 ref) */
1184 set_page_private(page, Z_EROFS_SHORTLIVED_PAGE);
1187 attach_page_private(page, pcl);
1188 /* drop a refcount added by allocpage (then we have 2 refs here) */
1191 out: /* the only exit (for tracing and debugging) */
1195 static struct z_erofs_decompressqueue *
1196 jobqueue_init(struct super_block *sb,
1197 struct z_erofs_decompressqueue *fgq, bool *fg)
1199 struct z_erofs_decompressqueue *q;
1202 q = kvzalloc(sizeof(*q), GFP_KERNEL | __GFP_NOWARN);
1207 INIT_WORK(&q->u.work, z_erofs_decompressqueue_work);
1211 init_waitqueue_head(&fgq->u.wait);
1212 atomic_set(&fgq->pending_bios, 0);
1215 q->head = Z_EROFS_PCLUSTER_TAIL_CLOSED;
1219 /* define decompression jobqueue types */
1226 static void *jobqueueset_init(struct super_block *sb,
1227 struct z_erofs_decompressqueue *q[],
1228 struct z_erofs_decompressqueue *fgq, bool *fg)
1231 * if managed cache is enabled, bypass jobqueue is needed,
1232 * no need to read from device for all pclusters in this queue.
1234 q[JQ_BYPASS] = jobqueue_init(sb, fgq + JQ_BYPASS, NULL);
1235 q[JQ_SUBMIT] = jobqueue_init(sb, fgq + JQ_SUBMIT, fg);
1237 return tagptr_cast_ptr(tagptr_fold(tagptr1_t, q[JQ_SUBMIT], *fg));
1240 static void move_to_bypass_jobqueue(struct z_erofs_pcluster *pcl,
1241 z_erofs_next_pcluster_t qtail[],
1242 z_erofs_next_pcluster_t owned_head)
1244 z_erofs_next_pcluster_t *const submit_qtail = qtail[JQ_SUBMIT];
1245 z_erofs_next_pcluster_t *const bypass_qtail = qtail[JQ_BYPASS];
1247 DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1248 if (owned_head == Z_EROFS_PCLUSTER_TAIL)
1249 owned_head = Z_EROFS_PCLUSTER_TAIL_CLOSED;
1251 WRITE_ONCE(pcl->next, Z_EROFS_PCLUSTER_TAIL_CLOSED);
1253 WRITE_ONCE(*submit_qtail, owned_head);
1254 WRITE_ONCE(*bypass_qtail, &pcl->next);
1256 qtail[JQ_BYPASS] = &pcl->next;
1259 static void z_erofs_submit_queue(struct super_block *sb,
1260 struct z_erofs_decompress_frontend *f,
1261 struct list_head *pagepool,
1262 struct z_erofs_decompressqueue *fgq,
1265 struct erofs_sb_info *const sbi = EROFS_SB(sb);
1266 z_erofs_next_pcluster_t qtail[NR_JOBQUEUES];
1267 struct z_erofs_decompressqueue *q[NR_JOBQUEUES];
1269 z_erofs_next_pcluster_t owned_head = f->clt.owned_head;
1270 /* since bio will be NULL, no need to initialize last_index */
1272 unsigned int nr_bios = 0;
1273 struct bio *bio = NULL;
1275 bi_private = jobqueueset_init(sb, q, fgq, force_fg);
1276 qtail[JQ_BYPASS] = &q[JQ_BYPASS]->head;
1277 qtail[JQ_SUBMIT] = &q[JQ_SUBMIT]->head;
1279 /* by default, all need io submission */
1280 q[JQ_SUBMIT]->head = owned_head;
1283 struct z_erofs_pcluster *pcl;
1288 /* no possible 'owned_head' equals the following */
1289 DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_TAIL_CLOSED);
1290 DBG_BUGON(owned_head == Z_EROFS_PCLUSTER_NIL);
1292 pcl = container_of(owned_head, struct z_erofs_pcluster, next);
1294 cur = pcl->obj.index;
1295 end = cur + pcl->pclusterpages;
1297 /* close the main owned chain at first */
1298 owned_head = cmpxchg(&pcl->next, Z_EROFS_PCLUSTER_TAIL,
1299 Z_EROFS_PCLUSTER_TAIL_CLOSED);
1304 page = pickup_page_for_submission(pcl, i++, pagepool,
1310 if (bio && cur != last_index + 1) {
1317 bio = bio_alloc(GFP_NOIO, BIO_MAX_VECS);
1319 bio->bi_end_io = z_erofs_decompressqueue_endio;
1320 bio_set_dev(bio, sb->s_bdev);
1321 bio->bi_iter.bi_sector = (sector_t)cur <<
1322 LOG_SECTORS_PER_BLOCK;
1323 bio->bi_private = bi_private;
1324 bio->bi_opf = REQ_OP_READ;
1326 bio->bi_opf |= REQ_RAHEAD;
1330 if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE)
1331 goto submit_bio_retry;
1335 } while (++cur < end);
1338 qtail[JQ_SUBMIT] = &pcl->next;
1340 move_to_bypass_jobqueue(pcl, qtail, owned_head);
1341 } while (owned_head != Z_EROFS_PCLUSTER_TAIL);
1347 * although background is preferred, no one is pending for submission.
1348 * don't issue workqueue for decompression but drop it directly instead.
1350 if (!*force_fg && !nr_bios) {
1351 kvfree(q[JQ_SUBMIT]);
1354 z_erofs_decompress_kickoff(q[JQ_SUBMIT], *force_fg, nr_bios);
1357 static void z_erofs_runqueue(struct super_block *sb,
1358 struct z_erofs_decompress_frontend *f,
1359 struct list_head *pagepool, bool force_fg)
1361 struct z_erofs_decompressqueue io[NR_JOBQUEUES];
1363 if (f->clt.owned_head == Z_EROFS_PCLUSTER_TAIL)
1365 z_erofs_submit_queue(sb, f, pagepool, io, &force_fg);
1367 /* handle bypass queue (no i/o pclusters) immediately */
1368 z_erofs_decompress_queue(&io[JQ_BYPASS], pagepool);
1373 /* wait until all bios are completed */
1374 io_wait_event(io[JQ_SUBMIT].u.wait,
1375 !atomic_read(&io[JQ_SUBMIT].pending_bios));
1377 /* handle synchronous decompress queue in the caller context */
1378 z_erofs_decompress_queue(&io[JQ_SUBMIT], pagepool);
1381 static int z_erofs_readpage(struct file *file, struct page *page)
1383 struct inode *const inode = page->mapping->host;
1384 struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1386 LIST_HEAD(pagepool);
1388 trace_erofs_readpage(page, false);
1390 f.headoffset = (erofs_off_t)page->index << PAGE_SHIFT;
1392 err = z_erofs_do_read_page(&f, page, &pagepool);
1393 (void)z_erofs_collector_end(&f.clt);
1395 /* if some compressed cluster ready, need submit them anyway */
1396 z_erofs_runqueue(inode->i_sb, &f, &pagepool, true);
1399 erofs_err(inode->i_sb, "failed to read, err [%d]", err);
1402 put_page(f.map.mpage);
1404 /* clean up the remaining free pages */
1405 put_pages_list(&pagepool);
1409 static void z_erofs_readahead(struct readahead_control *rac)
1411 struct inode *const inode = rac->mapping->host;
1412 struct erofs_sb_info *const sbi = EROFS_I_SB(inode);
1414 unsigned int nr_pages = readahead_count(rac);
1415 bool sync = (sbi->ctx.readahead_sync_decompress &&
1416 nr_pages <= sbi->ctx.max_sync_decompress_pages);
1417 struct z_erofs_decompress_frontend f = DECOMPRESS_FRONTEND_INIT(inode);
1418 struct page *page, *head = NULL;
1419 LIST_HEAD(pagepool);
1421 trace_erofs_readpages(inode, readahead_index(rac), nr_pages, false);
1424 f.headoffset = readahead_pos(rac);
1426 while ((page = readahead_page(rac))) {
1427 prefetchw(&page->flags);
1430 * A pure asynchronous readahead is indicated if
1431 * a PG_readahead marked page is hitted at first.
1432 * Let's also do asynchronous decompression for this case.
1434 sync &= !(PageReadahead(page) && !head);
1436 set_page_private(page, (unsigned long)head);
1441 struct page *page = head;
1444 /* traversal in reverse order */
1445 head = (void *)page_private(page);
1447 err = z_erofs_do_read_page(&f, page, &pagepool);
1449 erofs_err(inode->i_sb,
1450 "readahead error at page %lu @ nid %llu",
1451 page->index, EROFS_I(inode)->nid);
1455 (void)z_erofs_collector_end(&f.clt);
1457 z_erofs_runqueue(inode->i_sb, &f, &pagepool, sync);
1460 put_page(f.map.mpage);
1462 /* clean up the remaining free pages */
1463 put_pages_list(&pagepool);
1466 const struct address_space_operations z_erofs_aops = {
1467 .readpage = z_erofs_readpage,
1468 .readahead = z_erofs_readahead,