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