]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fs-io.c
1bffddf6ce519dcad1d8ad34b97715265ffafd81
[bcachefs-tools-debian] / libbcachefs / fs-io.c
1 #ifndef NO_BCACHEFS_FS
2
3 #include "bcachefs.h"
4 #include "btree_update.h"
5 #include "buckets.h"
6 #include "clock.h"
7 #include "error.h"
8 #include "fs.h"
9 #include "fs-io.h"
10 #include "fsck.h"
11 #include "inode.h"
12 #include "journal.h"
13 #include "io.h"
14 #include "keylist.h"
15 #include "quota.h"
16
17 #include <linux/aio.h>
18 #include <linux/backing-dev.h>
19 #include <linux/falloc.h>
20 #include <linux/migrate.h>
21 #include <linux/mmu_context.h>
22 #include <linux/pagevec.h>
23 #include <linux/task_io_accounting_ops.h>
24 #include <linux/uio.h>
25 #include <linux/writeback.h>
26
27 #include <trace/events/bcachefs.h>
28 #include <trace/events/writeback.h>
29
30 struct quota_res {
31         u64                             sectors;
32 };
33
34 struct i_sectors_hook {
35         struct extent_insert_hook       hook;
36         struct bch_inode_info           *inode;
37         struct quota_res                quota_res;
38         s64                             sectors;
39         u64                             new_i_size;
40         unsigned                        flags;
41         unsigned                        appending:1;
42 };
43
44 struct bchfs_write_op {
45         struct bch_inode_info           *inode;
46         s64                             sectors_added;
47         bool                            is_dio;
48         bool                            unalloc;
49         u64                             new_i_size;
50
51         /* must be last: */
52         struct bch_write_op             op;
53 };
54
55 struct bch_writepage_io {
56         struct closure                  cl;
57         u64                             new_sectors;
58
59         /* must be last: */
60         struct bchfs_write_op           op;
61 };
62
63 struct dio_write {
64         struct closure                  cl;
65         struct kiocb                    *req;
66         struct task_struct              *task;
67         unsigned                        loop:1,
68                                         sync:1,
69                                         free_iov:1;
70         struct quota_res                quota_res;
71
72         struct iov_iter                 iter;
73         struct iovec                    inline_vecs[2];
74
75         /* must be last: */
76         struct bchfs_write_op           iop;
77 };
78
79 struct dio_read {
80         struct closure                  cl;
81         struct kiocb                    *req;
82         long                            ret;
83         struct bch_read_bio             rbio;
84 };
85
86 /* pagecache_block must be held */
87 static int write_invalidate_inode_pages_range(struct address_space *mapping,
88                                               loff_t start, loff_t end)
89 {
90         int ret;
91
92         /*
93          * XXX: the way this is currently implemented, we can spin if a process
94          * is continually redirtying a specific page
95          */
96         do {
97                 if (!mapping->nrpages &&
98                     !mapping->nrexceptional)
99                         return 0;
100
101                 ret = filemap_write_and_wait_range(mapping, start, end);
102                 if (ret)
103                         break;
104
105                 if (!mapping->nrpages)
106                         return 0;
107
108                 ret = invalidate_inode_pages2_range(mapping,
109                                 start >> PAGE_SHIFT,
110                                 end >> PAGE_SHIFT);
111         } while (ret == -EBUSY);
112
113         return ret;
114 }
115
116 /* quotas */
117
118 #ifdef CONFIG_BCACHEFS_QUOTA
119
120 static void bch2_quota_reservation_put(struct bch_fs *c,
121                                        struct bch_inode_info *inode,
122                                        struct quota_res *res)
123 {
124         if (!res->sectors)
125                 return;
126
127         mutex_lock(&inode->ei_update_lock);
128         BUG_ON(res->sectors > inode->ei_quota_reserved);
129
130         bch2_quota_acct(c, inode->ei_qid, Q_SPC,
131                         -((s64) res->sectors), BCH_QUOTA_PREALLOC);
132         inode->ei_quota_reserved -= res->sectors;
133         mutex_unlock(&inode->ei_update_lock);
134
135         res->sectors = 0;
136 }
137
138 static int bch2_quota_reservation_add(struct bch_fs *c,
139                                       struct bch_inode_info *inode,
140                                       struct quota_res *res,
141                                       unsigned sectors,
142                                       bool check_enospc)
143 {
144         int ret;
145
146         mutex_lock(&inode->ei_update_lock);
147         ret = bch2_quota_acct(c, inode->ei_qid, Q_SPC, sectors,
148                               check_enospc ? BCH_QUOTA_PREALLOC : BCH_QUOTA_NOCHECK);
149         if (likely(!ret)) {
150                 inode->ei_quota_reserved += sectors;
151                 res->sectors += sectors;
152         }
153         mutex_unlock(&inode->ei_update_lock);
154
155         return ret;
156 }
157
158 #else
159
160 static void bch2_quota_reservation_put(struct bch_fs *c,
161                                        struct bch_inode_info *inode,
162                                        struct quota_res *res)
163 {
164 }
165
166 static int bch2_quota_reservation_add(struct bch_fs *c,
167                                       struct bch_inode_info *inode,
168                                       struct quota_res *res,
169                                       unsigned sectors,
170                                       bool check_enospc)
171 {
172         return 0;
173 }
174
175 #endif
176
177 /* i_size updates: */
178
179 static int inode_set_size(struct bch_inode_info *inode,
180                           struct bch_inode_unpacked *bi,
181                           void *p)
182 {
183         loff_t *new_i_size = p;
184
185         lockdep_assert_held(&inode->ei_update_lock);
186
187         bi->bi_size = *new_i_size;
188         return 0;
189 }
190
191 static int __must_check bch2_write_inode_size(struct bch_fs *c,
192                                               struct bch_inode_info *inode,
193                                               loff_t new_size)
194 {
195         return __bch2_write_inode(c, inode, inode_set_size, &new_size);
196 }
197
198 static void __i_sectors_acct(struct bch_fs *c, struct bch_inode_info *inode,
199                              struct quota_res *quota_res, int sectors)
200 {
201 #ifdef CONFIG_BCACHEFS_QUOTA
202         if (quota_res && sectors > 0) {
203                 BUG_ON(sectors > quota_res->sectors);
204                 BUG_ON(sectors > inode->ei_quota_reserved);
205
206                 quota_res->sectors -= sectors;
207                 inode->ei_quota_reserved -= sectors;
208         } else {
209                 bch2_quota_acct(c, inode->ei_qid, Q_SPC, sectors, BCH_QUOTA_WARN);
210         }
211 #endif
212         inode->v.i_blocks += sectors;
213 }
214
215 static void i_sectors_acct(struct bch_fs *c, struct bch_inode_info *inode,
216                            struct quota_res *quota_res, int sectors)
217 {
218         mutex_lock(&inode->ei_update_lock);
219         __i_sectors_acct(c, inode, quota_res, sectors);
220         mutex_unlock(&inode->ei_update_lock);
221 }
222
223 /* i_sectors accounting: */
224
225 static enum btree_insert_ret
226 i_sectors_hook_fn(struct extent_insert_hook *hook,
227                   struct bpos committed_pos,
228                   struct bpos next_pos,
229                   struct bkey_s_c k,
230                   const struct bkey_i *insert)
231 {
232         struct i_sectors_hook *h = container_of(hook,
233                                 struct i_sectors_hook, hook);
234         s64 sectors = next_pos.offset - committed_pos.offset;
235         int sign = bkey_extent_is_allocation(&insert->k) -
236                 (k.k && bkey_extent_is_allocation(k.k));
237
238         EBUG_ON(!(h->inode->ei_inode.bi_flags & BCH_INODE_I_SECTORS_DIRTY));
239
240         h->sectors += sectors * sign;
241
242         return BTREE_INSERT_OK;
243 }
244
245 static int i_sectors_dirty_finish_fn(struct bch_inode_info *inode,
246                                      struct bch_inode_unpacked *bi,
247                                      void *p)
248 {
249         struct i_sectors_hook *h = p;
250
251         if (h->new_i_size != U64_MAX &&
252             (!h->appending ||
253              h->new_i_size > bi->bi_size))
254                 bi->bi_size = h->new_i_size;
255         bi->bi_sectors  += h->sectors;
256         bi->bi_flags    &= ~h->flags;
257         return 0;
258 }
259
260 static int i_sectors_dirty_finish(struct bch_fs *c, struct i_sectors_hook *h)
261 {
262         int ret;
263
264         mutex_lock(&h->inode->ei_update_lock);
265         if (h->new_i_size != U64_MAX)
266                 i_size_write(&h->inode->v, h->new_i_size);
267
268         __i_sectors_acct(c, h->inode, &h->quota_res, h->sectors);
269
270         ret = __bch2_write_inode(c, h->inode, i_sectors_dirty_finish_fn, h);
271         mutex_unlock(&h->inode->ei_update_lock);
272
273         bch2_quota_reservation_put(c, h->inode, &h->quota_res);
274
275         h->sectors = 0;
276
277         return ret;
278 }
279
280 static int i_sectors_dirty_start_fn(struct bch_inode_info *inode,
281                                     struct bch_inode_unpacked *bi, void *p)
282 {
283         struct i_sectors_hook *h = p;
284
285         if (h->flags & BCH_INODE_I_SIZE_DIRTY)
286                 bi->bi_size = h->new_i_size;
287
288         bi->bi_flags |= h->flags;
289         return 0;
290 }
291
292 static int i_sectors_dirty_start(struct bch_fs *c, struct i_sectors_hook *h)
293 {
294         int ret;
295
296         mutex_lock(&h->inode->ei_update_lock);
297         ret = __bch2_write_inode(c, h->inode, i_sectors_dirty_start_fn, h);
298         mutex_unlock(&h->inode->ei_update_lock);
299
300         return ret;
301 }
302
303 static inline struct i_sectors_hook
304 i_sectors_hook_init(struct bch_inode_info *inode, unsigned flags)
305 {
306         return (struct i_sectors_hook) {
307                 .hook.fn        = i_sectors_hook_fn,
308                 .inode          = inode,
309                 .sectors        = 0,
310                 .new_i_size     = U64_MAX,
311                 .flags          = flags|BCH_INODE_I_SECTORS_DIRTY,
312         };
313 }
314
315 /* normal i_size/i_sectors update machinery: */
316
317 struct bchfs_extent_trans_hook {
318         struct bchfs_write_op           *op;
319         struct extent_insert_hook       hook;
320
321         struct bch_inode_unpacked       inode_u;
322         struct bkey_inode_buf           inode_p;
323
324         bool                            need_inode_update;
325 };
326
327 static enum btree_insert_ret
328 bchfs_extent_update_hook(struct extent_insert_hook *hook,
329                          struct bpos committed_pos,
330                          struct bpos next_pos,
331                          struct bkey_s_c k,
332                          const struct bkey_i *insert)
333 {
334         struct bchfs_extent_trans_hook *h = container_of(hook,
335                                 struct bchfs_extent_trans_hook, hook);
336         struct bch_inode_info *inode = h->op->inode;
337         int sign = bkey_extent_is_allocation(&insert->k) -
338                 (k.k && bkey_extent_is_allocation(k.k));
339         s64 sectors = (s64) (next_pos.offset - committed_pos.offset) * sign;
340         u64 offset = min(next_pos.offset << 9, h->op->new_i_size);
341         bool do_pack = false;
342
343         if (h->op->unalloc &&
344             !bch2_extent_is_fully_allocated(k))
345                 return BTREE_INSERT_ENOSPC;
346
347         BUG_ON((next_pos.offset << 9) > round_up(offset, PAGE_SIZE));
348
349         /* XXX: inode->i_size locking */
350         if (offset > inode->ei_inode.bi_size) {
351                 if (!h->need_inode_update) {
352                         h->need_inode_update = true;
353                         return BTREE_INSERT_NEED_TRAVERSE;
354                 }
355
356                 BUG_ON(h->inode_u.bi_flags & BCH_INODE_I_SIZE_DIRTY);
357
358                 h->inode_u.bi_size = offset;
359                 do_pack = true;
360
361                 inode->ei_inode.bi_size = offset;
362
363                 if (h->op->is_dio)
364                         i_size_write(&inode->v, offset);
365         }
366
367         if (sectors) {
368                 if (!h->need_inode_update) {
369                         h->need_inode_update = true;
370                         return BTREE_INSERT_NEED_TRAVERSE;
371                 }
372
373                 h->inode_u.bi_sectors += sectors;
374                 do_pack = true;
375
376                 h->op->sectors_added += sectors;
377         }
378
379         if (do_pack)
380                 bch2_inode_pack(&h->inode_p, &h->inode_u);
381
382         return BTREE_INSERT_OK;
383 }
384
385 static int bchfs_write_index_update(struct bch_write_op *wop)
386 {
387         struct bchfs_write_op *op = container_of(wop,
388                                 struct bchfs_write_op, op);
389         struct keylist *keys = &op->op.insert_keys;
390         struct btree_iter extent_iter, inode_iter;
391         struct bchfs_extent_trans_hook hook;
392         struct bkey_i *k = bch2_keylist_front(keys);
393         s64 orig_sectors_added = op->sectors_added;
394         int ret;
395
396         BUG_ON(k->k.p.inode != op->inode->v.i_ino);
397
398         bch2_btree_iter_init(&extent_iter, wop->c, BTREE_ID_EXTENTS,
399                              bkey_start_pos(&bch2_keylist_front(keys)->k),
400                              BTREE_ITER_INTENT);
401         bch2_btree_iter_init(&inode_iter, wop->c, BTREE_ID_INODES,
402                              POS(extent_iter.pos.inode, 0),
403                              BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
404
405         hook.op                 = op;
406         hook.hook.fn            = bchfs_extent_update_hook;
407         hook.need_inode_update  = false;
408
409         do {
410                 /* XXX: inode->i_size locking */
411                 k = bch2_keylist_front(keys);
412                 if (min(k->k.p.offset << 9, op->new_i_size) >
413                     op->inode->ei_inode.bi_size)
414                         hook.need_inode_update = true;
415
416                 if (hook.need_inode_update) {
417                         struct bkey_s_c inode;
418
419                         if (!btree_iter_linked(&inode_iter))
420                                 bch2_btree_iter_link(&extent_iter, &inode_iter);
421
422                         inode = bch2_btree_iter_peek_slot(&inode_iter);
423                         if ((ret = btree_iter_err(inode)))
424                                 goto err;
425
426                         if (WARN_ONCE(inode.k->type != BCH_INODE_FS,
427                                       "inode %llu not found when updating",
428                                       extent_iter.pos.inode)) {
429                                 ret = -ENOENT;
430                                 break;
431                         }
432
433                         if (WARN_ONCE(bkey_bytes(inode.k) >
434                                       sizeof(hook.inode_p),
435                                       "inode %llu too big (%zu bytes, buf %zu)",
436                                       extent_iter.pos.inode,
437                                       bkey_bytes(inode.k),
438                                       sizeof(hook.inode_p))) {
439                                 ret = -ENOENT;
440                                 break;
441                         }
442
443                         bkey_reassemble(&hook.inode_p.inode.k_i, inode);
444                         ret = bch2_inode_unpack(bkey_s_c_to_inode(inode),
445                                                &hook.inode_u);
446                         if (WARN_ONCE(ret,
447                                       "error %i unpacking inode %llu",
448                                       ret, extent_iter.pos.inode)) {
449                                 ret = -ENOENT;
450                                 break;
451                         }
452
453                         ret = bch2_btree_insert_at(wop->c, &wop->res,
454                                         &hook.hook, op_journal_seq(wop),
455                                         BTREE_INSERT_NOFAIL|BTREE_INSERT_ATOMIC,
456                                         BTREE_INSERT_ENTRY(&extent_iter, k),
457                                         BTREE_INSERT_ENTRY_EXTRA_RES(&inode_iter,
458                                                         &hook.inode_p.inode.k_i, 2));
459                 } else {
460                         ret = bch2_btree_insert_at(wop->c, &wop->res,
461                                         &hook.hook, op_journal_seq(wop),
462                                         BTREE_INSERT_NOFAIL|BTREE_INSERT_ATOMIC,
463                                         BTREE_INSERT_ENTRY(&extent_iter, k));
464                 }
465
466                 BUG_ON(bkey_cmp(extent_iter.pos, bkey_start_pos(&k->k)));
467                 BUG_ON(!ret != !k->k.size);
468 err:
469                 if (ret == -EINTR)
470                         continue;
471                 if (ret)
472                         break;
473
474                 BUG_ON(bkey_cmp(extent_iter.pos, k->k.p) < 0);
475                 bch2_keylist_pop_front(keys);
476         } while (!bch2_keylist_empty(keys));
477
478         bch2_btree_iter_unlock(&extent_iter);
479         bch2_btree_iter_unlock(&inode_iter);
480
481         if (op->is_dio) {
482                 struct dio_write *dio = container_of(op, struct dio_write, iop);
483
484                 i_sectors_acct(wop->c, op->inode, &dio->quota_res,
485                                op->sectors_added - orig_sectors_added);
486         }
487
488         return ret;
489 }
490
491 static inline void bch2_fswrite_op_init(struct bchfs_write_op *op,
492                                         struct bch_fs *c,
493                                         struct bch_inode_info *inode,
494                                         struct bch_io_opts opts,
495                                         bool is_dio)
496 {
497         op->inode               = inode;
498         op->sectors_added       = 0;
499         op->is_dio              = is_dio;
500         op->unalloc             = false;
501         op->new_i_size          = U64_MAX;
502
503         bch2_write_op_init(&op->op, c);
504         op->op.csum_type        = bch2_data_checksum_type(c, opts.data_checksum);
505         op->op.compression_type = bch2_compression_opt_to_type(opts.compression);
506         op->op.devs             = c->fastest_devs;
507         op->op.index_update_fn  = bchfs_write_index_update;
508         op_journal_seq_set(&op->op, &inode->ei_journal_seq);
509 }
510
511 static inline struct bch_io_opts io_opts(struct bch_fs *c, struct bch_inode_info *inode)
512 {
513         struct bch_io_opts opts = bch2_opts_to_inode_opts(c->opts);
514
515         bch2_io_opts_apply(&opts, bch2_inode_opts_get(&inode->ei_inode));
516         return opts;
517 }
518
519 /* page state: */
520
521 /* stored in page->private: */
522
523 /*
524  * bch_page_state has to (unfortunately) be manipulated with cmpxchg - we could
525  * almost protected it with the page lock, except that bch2_writepage_io_done has
526  * to update the sector counts (and from interrupt/bottom half context).
527  */
528 struct bch_page_state {
529 union { struct {
530         /* existing data: */
531         unsigned                sectors:PAGE_SECTOR_SHIFT + 1;
532         unsigned                nr_replicas:4;
533         unsigned                compressed:1;
534
535         /* Owns PAGE_SECTORS sized reservation: */
536         unsigned                reserved:1;
537         unsigned                reservation_replicas:4;
538
539         /* Owns PAGE_SECTORS sized quota reservation: */
540         unsigned                quota_reserved:1;
541
542         /*
543          * Number of sectors on disk - for i_blocks
544          * Uncompressed size, not compressed size:
545          */
546         unsigned                dirty_sectors:PAGE_SECTOR_SHIFT + 1;
547 };
548         /* for cmpxchg: */
549         unsigned long           v;
550 };
551 };
552
553 #define page_state_cmpxchg(_ptr, _new, _expr)                           \
554 ({                                                                      \
555         unsigned long _v = READ_ONCE((_ptr)->v);                        \
556         struct bch_page_state _old;                                     \
557                                                                         \
558         do {                                                            \
559                 _old.v = _new.v = _v;                                   \
560                 _expr;                                                  \
561                                                                         \
562                 EBUG_ON(_new.sectors + _new.dirty_sectors > PAGE_SECTORS);\
563         } while (_old.v != _new.v &&                                    \
564                  (_v = cmpxchg(&(_ptr)->v, _old.v, _new.v)) != _old.v); \
565                                                                         \
566         _old;                                                           \
567 })
568
569 static inline struct bch_page_state *page_state(struct page *page)
570 {
571         struct bch_page_state *s = (void *) &page->private;
572
573         BUILD_BUG_ON(sizeof(*s) > sizeof(page->private));
574
575         if (!PagePrivate(page))
576                 SetPagePrivate(page);
577
578         return s;
579 }
580
581 static inline unsigned page_res_sectors(struct bch_page_state s)
582 {
583
584         return s.reserved ? s.reservation_replicas * PAGE_SECTORS : 0;
585 }
586
587 static void __bch2_put_page_reservation(struct bch_fs *c, struct bch_inode_info *inode,
588                                         struct bch_page_state s)
589 {
590         struct disk_reservation res = { .sectors = page_res_sectors(s) };
591         struct quota_res quota_res = { .sectors = s.quota_reserved ? PAGE_SECTORS : 0 };
592
593         bch2_quota_reservation_put(c, inode, &quota_res);
594         bch2_disk_reservation_put(c, &res);
595 }
596
597 static void bch2_put_page_reservation(struct bch_fs *c, struct bch_inode_info *inode,
598                                       struct page *page)
599 {
600         struct bch_page_state s;
601
602         s = page_state_cmpxchg(page_state(page), s, {
603                 s.reserved              = 0;
604                 s.quota_reserved        = 0;
605         });
606
607         __bch2_put_page_reservation(c, inode, s);
608 }
609
610 static int bch2_get_page_reservation(struct bch_fs *c, struct bch_inode_info *inode,
611                                      struct page *page, bool check_enospc)
612 {
613         struct bch_page_state *s = page_state(page), new, old;
614         struct disk_reservation disk_res = bch2_disk_reservation_init(c,
615                                                 READ_ONCE(c->opts.data_replicas));
616         struct quota_res quota_res = { 0 };
617         int ret = 0;
618
619         /*
620          * XXX: this could likely be quite a bit simpler, page reservations
621          * _should_ only be manipulated with page locked:
622          */
623
624         old = page_state_cmpxchg(s, new, {
625                 if (new.reserved
626                     ? (new.reservation_replicas < disk_res.nr_replicas)
627                     : (new.sectors < PAGE_SECTORS ||
628                        new.nr_replicas < disk_res.nr_replicas ||
629                        new.compressed)) {
630                         int sectors = (disk_res.nr_replicas * PAGE_SECTORS -
631                                        page_res_sectors(new) -
632                                        disk_res.sectors);
633
634                         if (sectors > 0) {
635                                 ret = bch2_disk_reservation_add(c, &disk_res, sectors,
636                                                 !check_enospc
637                                                 ? BCH_DISK_RESERVATION_NOFAIL : 0);
638                                 if (unlikely(ret))
639                                         goto err;
640                         }
641
642                         new.reserved = 1;
643                         new.reservation_replicas = disk_res.nr_replicas;
644                 }
645
646                 if (!new.quota_reserved &&
647                     new.sectors + new.dirty_sectors < PAGE_SECTORS) {
648                         ret = bch2_quota_reservation_add(c, inode, &quota_res,
649                                                 PAGE_SECTORS - quota_res.sectors,
650                                                 check_enospc);
651                         if (unlikely(ret))
652                                 goto err;
653
654                         new.quota_reserved = 1;
655                 }
656         });
657
658         quota_res.sectors -= (new.quota_reserved - old.quota_reserved) * PAGE_SECTORS;
659         disk_res.sectors -= page_res_sectors(new) - page_res_sectors(old);
660 err:
661         bch2_quota_reservation_put(c, inode, &quota_res);
662         bch2_disk_reservation_put(c, &disk_res);
663         return ret;
664 }
665
666 static void bch2_clear_page_bits(struct page *page)
667 {
668         struct bch_inode_info *inode = to_bch_ei(page->mapping->host);
669         struct bch_fs *c = inode->v.i_sb->s_fs_info;
670         struct bch_page_state s;
671
672         if (!PagePrivate(page))
673                 return;
674
675         s = xchg(page_state(page), (struct bch_page_state) { .v = 0 });
676         ClearPagePrivate(page);
677
678         if (s.dirty_sectors)
679                 i_sectors_acct(c, inode, NULL, -s.dirty_sectors);
680
681         __bch2_put_page_reservation(c, inode, s);
682 }
683
684 int bch2_set_page_dirty(struct page *page)
685 {
686         struct bch_inode_info *inode = to_bch_ei(page->mapping->host);
687         struct bch_fs *c = inode->v.i_sb->s_fs_info;
688         struct quota_res quota_res = { 0 };
689         struct bch_page_state old, new;
690
691         old = page_state_cmpxchg(page_state(page), new,
692                 new.dirty_sectors = PAGE_SECTORS - new.sectors;
693                 new.quota_reserved = 0;
694         );
695
696         quota_res.sectors += old.quota_reserved * PAGE_SECTORS;
697
698         if (old.dirty_sectors != new.dirty_sectors)
699                 i_sectors_acct(c, inode, &quota_res,
700                                new.dirty_sectors - old.dirty_sectors);
701         bch2_quota_reservation_put(c, inode, &quota_res);
702
703         return __set_page_dirty_nobuffers(page);
704 }
705
706 int bch2_page_mkwrite(struct vm_fault *vmf)
707 {
708         struct page *page = vmf->page;
709         struct file *file = vmf->vma->vm_file;
710         struct bch_inode_info *inode = file_bch_inode(file);
711         struct address_space *mapping = inode->v.i_mapping;
712         struct bch_fs *c = inode->v.i_sb->s_fs_info;
713         int ret = VM_FAULT_LOCKED;
714
715         sb_start_pagefault(inode->v.i_sb);
716         file_update_time(file);
717
718         /*
719          * Not strictly necessary, but helps avoid dio writes livelocking in
720          * write_invalidate_inode_pages_range() - can drop this if/when we get
721          * a write_invalidate_inode_pages_range() that works without dropping
722          * page lock before invalidating page
723          */
724         if (current->pagecache_lock != &mapping->add_lock)
725                 pagecache_add_get(&mapping->add_lock);
726
727         lock_page(page);
728         if (page->mapping != mapping ||
729             page_offset(page) > i_size_read(&inode->v)) {
730                 unlock_page(page);
731                 ret = VM_FAULT_NOPAGE;
732                 goto out;
733         }
734
735         if (bch2_get_page_reservation(c, inode, page, true)) {
736                 unlock_page(page);
737                 ret = VM_FAULT_SIGBUS;
738                 goto out;
739         }
740
741         if (!PageDirty(page))
742                 set_page_dirty(page);
743         wait_for_stable_page(page);
744 out:
745         if (current->pagecache_lock != &mapping->add_lock)
746                 pagecache_add_put(&mapping->add_lock);
747         sb_end_pagefault(inode->v.i_sb);
748         return ret;
749 }
750
751 void bch2_invalidatepage(struct page *page, unsigned int offset,
752                          unsigned int length)
753 {
754         EBUG_ON(!PageLocked(page));
755         EBUG_ON(PageWriteback(page));
756
757         if (offset || length < PAGE_SIZE)
758                 return;
759
760         bch2_clear_page_bits(page);
761 }
762
763 int bch2_releasepage(struct page *page, gfp_t gfp_mask)
764 {
765         EBUG_ON(!PageLocked(page));
766         EBUG_ON(PageWriteback(page));
767
768         if (PageDirty(page))
769                 return 0;
770
771         bch2_clear_page_bits(page);
772         return 1;
773 }
774
775 #ifdef CONFIG_MIGRATION
776 int bch2_migrate_page(struct address_space *mapping, struct page *newpage,
777                       struct page *page, enum migrate_mode mode)
778 {
779         int ret;
780
781         ret = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0);
782         if (ret != MIGRATEPAGE_SUCCESS)
783                 return ret;
784
785         if (PagePrivate(page)) {
786                 *page_state(newpage) = *page_state(page);
787                 ClearPagePrivate(page);
788         }
789
790         migrate_page_copy(newpage, page);
791         return MIGRATEPAGE_SUCCESS;
792 }
793 #endif
794
795 /* readpages/writepages: */
796
797 static bool bio_can_add_page_contig(struct bio *bio, struct page *page)
798 {
799         sector_t offset = (sector_t) page->index << PAGE_SECTOR_SHIFT;
800
801         return bio->bi_vcnt < bio->bi_max_vecs &&
802                 bio_end_sector(bio) == offset;
803 }
804
805 static void __bio_add_page(struct bio *bio, struct page *page)
806 {
807         bio->bi_io_vec[bio->bi_vcnt++] = (struct bio_vec) {
808                 .bv_page = page,
809                 .bv_len = PAGE_SIZE,
810                 .bv_offset = 0,
811         };
812
813         bio->bi_iter.bi_size += PAGE_SIZE;
814 }
815
816 static int bio_add_page_contig(struct bio *bio, struct page *page)
817 {
818         sector_t offset = (sector_t) page->index << PAGE_SECTOR_SHIFT;
819
820         EBUG_ON(!bio->bi_max_vecs);
821
822         if (!bio->bi_vcnt)
823                 bio->bi_iter.bi_sector = offset;
824         else if (!bio_can_add_page_contig(bio, page))
825                 return -1;
826
827         __bio_add_page(bio, page);
828         return 0;
829 }
830
831 /* readpage(s): */
832
833 static void bch2_readpages_end_io(struct bio *bio)
834 {
835         struct bio_vec *bv;
836         int i;
837
838         bio_for_each_segment_all(bv, bio, i) {
839                 struct page *page = bv->bv_page;
840
841                 if (!bio->bi_status) {
842                         SetPageUptodate(page);
843                 } else {
844                         ClearPageUptodate(page);
845                         SetPageError(page);
846                 }
847                 unlock_page(page);
848         }
849
850         bio_put(bio);
851 }
852
853 struct readpages_iter {
854         struct address_space    *mapping;
855         struct list_head        pages;
856         unsigned                nr_pages;
857 };
858
859 static inline void page_state_init_for_read(struct page *page)
860 {
861         struct bch_page_state *s = page_state(page);
862
863         BUG_ON(s->reserved);
864         s->sectors      = 0;
865         s->compressed   = 0;
866 }
867
868 static int readpage_add_page(struct readpages_iter *iter, struct page *page)
869 {
870         int ret;
871
872         prefetchw(&page->flags);
873         page_state_init_for_read(page);
874
875         ret = add_to_page_cache_lru(page, iter->mapping,
876                                     page->index, GFP_NOFS);
877         put_page(page);
878         return ret;
879 }
880
881 static inline struct page *readpage_iter_next(struct readpages_iter *iter)
882 {
883         while (iter->nr_pages) {
884                 struct page *page =
885                         list_last_entry(&iter->pages, struct page, lru);
886
887                 prefetchw(&page->flags);
888                 list_del(&page->lru);
889                 iter->nr_pages--;
890
891                 if (!readpage_add_page(iter, page))
892                         return page;
893         }
894
895         return NULL;
896 }
897
898 #define for_each_readpage_page(_iter, _page)                            \
899         for (;                                                          \
900              ((_page) = __readpage_next_page(&(_iter)));)               \
901
902 static void bch2_add_page_sectors(struct bio *bio, struct bkey_s_c k)
903 {
904         struct bvec_iter iter;
905         struct bio_vec bv;
906         bool compressed = bch2_extent_is_compressed(k);
907         unsigned nr_ptrs = bch2_extent_nr_dirty_ptrs(k);
908
909         bio_for_each_segment(bv, bio, iter) {
910                 struct bch_page_state *s = page_state(bv.bv_page);
911
912                 /* sectors in @k from the start of this page: */
913                 unsigned k_sectors = k.k->size - (iter.bi_sector - k.k->p.offset);
914
915                 unsigned page_sectors = min(bv.bv_len >> 9, k_sectors);
916
917                 s->nr_replicas = !s->sectors
918                         ? nr_ptrs
919                         : min_t(unsigned, s->nr_replicas, nr_ptrs);
920
921                 BUG_ON(s->sectors + page_sectors > PAGE_SECTORS);
922                 s->sectors += page_sectors;
923
924                 s->compressed |= compressed;
925         }
926 }
927
928 static void readpage_bio_extend(struct readpages_iter *iter,
929                                 struct bio *bio, u64 offset,
930                                 bool get_more)
931 {
932         struct page *page;
933         pgoff_t page_offset;
934         int ret;
935
936         while (bio_end_sector(bio) < offset &&
937                bio->bi_vcnt < bio->bi_max_vecs) {
938                 page_offset = bio_end_sector(bio) >> PAGE_SECTOR_SHIFT;
939
940                 if (iter->nr_pages) {
941                         page = list_last_entry(&iter->pages, struct page, lru);
942                         if (page->index != page_offset)
943                                 break;
944
945                         list_del(&page->lru);
946                         iter->nr_pages--;
947                 } else if (get_more) {
948                         rcu_read_lock();
949                         page = radix_tree_lookup(&iter->mapping->page_tree, page_offset);
950                         rcu_read_unlock();
951
952                         if (page && !radix_tree_exceptional_entry(page))
953                                 break;
954
955                         page = __page_cache_alloc(readahead_gfp_mask(iter->mapping));
956                         if (!page)
957                                 break;
958
959                         page->index = page_offset;
960                         ClearPageReadahead(bio->bi_io_vec[bio->bi_vcnt - 1].bv_page);
961                 } else {
962                         break;
963                 }
964
965                 ret = readpage_add_page(iter, page);
966                 if (ret)
967                         break;
968
969                 __bio_add_page(bio, page);
970         }
971
972         if (!iter->nr_pages)
973                 SetPageReadahead(bio->bi_io_vec[bio->bi_vcnt - 1].bv_page);
974 }
975
976 static void bchfs_read(struct bch_fs *c, struct btree_iter *iter,
977                        struct bch_read_bio *rbio, u64 inum,
978                        struct readpages_iter *readpages_iter)
979 {
980         struct bio *bio = &rbio->bio;
981         int flags = BCH_READ_RETRY_IF_STALE|
982                 BCH_READ_MAY_PROMOTE;
983
984         while (1) {
985                 struct extent_pick_ptr pick;
986                 BKEY_PADDED(k) tmp;
987                 struct bkey_s_c k;
988                 unsigned bytes;
989                 bool is_last;
990
991                 bch2_btree_iter_set_pos(iter, POS(inum, bio->bi_iter.bi_sector));
992
993                 k = bch2_btree_iter_peek_slot(iter);
994                 BUG_ON(!k.k);
995
996                 if (IS_ERR(k.k)) {
997                         int ret = bch2_btree_iter_unlock(iter);
998                         BUG_ON(!ret);
999                         bcache_io_error(c, bio, "btree IO error %i", ret);
1000                         bio_endio(bio);
1001                         return;
1002                 }
1003
1004                 bkey_reassemble(&tmp.k, k);
1005                 bch2_btree_iter_unlock(iter);
1006                 k = bkey_i_to_s_c(&tmp.k);
1007
1008                 bch2_extent_pick_ptr(c, k, NULL, &pick);
1009                 if (IS_ERR(pick.ca)) {
1010                         bcache_io_error(c, bio, "no device to read from");
1011                         bio_endio(bio);
1012                         return;
1013                 }
1014
1015                 if (readpages_iter)
1016                         readpage_bio_extend(readpages_iter,
1017                                             bio, k.k->p.offset,
1018                                             pick.ca &&
1019                                             (pick.crc.csum_type ||
1020                                              pick.crc.compression_type));
1021
1022                 bytes = (min_t(u64, k.k->p.offset, bio_end_sector(bio)) -
1023                          bio->bi_iter.bi_sector) << 9;
1024                 is_last = bytes == bio->bi_iter.bi_size;
1025                 swap(bio->bi_iter.bi_size, bytes);
1026
1027                 if (bkey_extent_is_allocation(k.k))
1028                         bch2_add_page_sectors(bio, k);
1029
1030                 if (pick.ca) {
1031                         if (!is_last) {
1032                                 bio_inc_remaining(&rbio->bio);
1033                                 flags |= BCH_READ_MUST_CLONE;
1034                                 trace_read_split(&rbio->bio);
1035                         }
1036
1037                         bch2_read_extent(c, rbio, bkey_s_c_to_extent(k),
1038                                          &pick, flags);
1039                 } else {
1040                         zero_fill_bio(bio);
1041
1042                         if (is_last)
1043                                 bio_endio(bio);
1044                 }
1045
1046                 if (is_last)
1047                         return;
1048
1049                 swap(bio->bi_iter.bi_size, bytes);
1050                 bio_advance(bio, bytes);
1051         }
1052 }
1053
1054 int bch2_readpages(struct file *file, struct address_space *mapping,
1055                    struct list_head *pages, unsigned nr_pages)
1056 {
1057         struct bch_inode_info *inode = to_bch_ei(mapping->host);
1058         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1059         struct bch_io_opts opts = io_opts(c, inode);
1060         struct btree_iter iter;
1061         struct page *page;
1062         struct readpages_iter readpages_iter = {
1063                 .mapping = mapping, .nr_pages = nr_pages
1064         };
1065
1066         bch2_btree_iter_init(&iter, c, BTREE_ID_EXTENTS, POS_MIN,
1067                              BTREE_ITER_SLOTS);
1068
1069         INIT_LIST_HEAD(&readpages_iter.pages);
1070         list_add(&readpages_iter.pages, pages);
1071         list_del_init(pages);
1072
1073         if (current->pagecache_lock != &mapping->add_lock)
1074                 pagecache_add_get(&mapping->add_lock);
1075
1076         while ((page = readpage_iter_next(&readpages_iter))) {
1077                 unsigned n = max_t(unsigned,
1078                                    min_t(unsigned, readpages_iter.nr_pages + 1,
1079                                          BIO_MAX_PAGES),
1080                                    c->sb.encoded_extent_max >> PAGE_SECTOR_SHIFT);
1081
1082                 struct bch_read_bio *rbio =
1083                         rbio_init(bio_alloc_bioset(GFP_NOFS, n, &c->bio_read),
1084                                   opts);
1085
1086                 rbio->bio.bi_end_io = bch2_readpages_end_io;
1087                 bio_add_page_contig(&rbio->bio, page);
1088                 bchfs_read(c, &iter, rbio, inode->v.i_ino, &readpages_iter);
1089         }
1090
1091         if (current->pagecache_lock != &mapping->add_lock)
1092                 pagecache_add_put(&mapping->add_lock);
1093
1094         return 0;
1095 }
1096
1097 static void __bchfs_readpage(struct bch_fs *c, struct bch_read_bio *rbio,
1098                              u64 inum, struct page *page)
1099 {
1100         struct btree_iter iter;
1101
1102         page_state_init_for_read(page);
1103
1104         bio_set_op_attrs(&rbio->bio, REQ_OP_READ, REQ_SYNC);
1105         bio_add_page_contig(&rbio->bio, page);
1106
1107         bch2_btree_iter_init(&iter, c, BTREE_ID_EXTENTS, POS_MIN,
1108                              BTREE_ITER_SLOTS);
1109         bchfs_read(c, &iter, rbio, inum, NULL);
1110 }
1111
1112 int bch2_readpage(struct file *file, struct page *page)
1113 {
1114         struct bch_inode_info *inode = to_bch_ei(page->mapping->host);
1115         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1116         struct bch_io_opts opts = io_opts(c, inode);
1117         struct bch_read_bio *rbio;
1118
1119         rbio = rbio_init(bio_alloc_bioset(GFP_NOFS, 1, &c->bio_read), opts);
1120         rbio->bio.bi_end_io = bch2_readpages_end_io;
1121
1122         __bchfs_readpage(c, rbio, inode->v.i_ino, page);
1123         return 0;
1124 }
1125
1126 static void bch2_read_single_page_end_io(struct bio *bio)
1127 {
1128         complete(bio->bi_private);
1129 }
1130
1131 static int bch2_read_single_page(struct page *page,
1132                                  struct address_space *mapping)
1133 {
1134         struct bch_inode_info *inode = to_bch_ei(mapping->host);
1135         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1136         struct bch_read_bio *rbio;
1137         int ret;
1138         DECLARE_COMPLETION_ONSTACK(done);
1139
1140         rbio = rbio_init(bio_alloc_bioset(GFP_NOFS, 1, &c->bio_read),
1141                          io_opts(c, inode));
1142         rbio->bio.bi_private = &done;
1143         rbio->bio.bi_end_io = bch2_read_single_page_end_io;
1144
1145         __bchfs_readpage(c, rbio, inode->v.i_ino, page);
1146         wait_for_completion(&done);
1147
1148         ret = blk_status_to_errno(rbio->bio.bi_status);
1149         bio_put(&rbio->bio);
1150
1151         if (ret < 0)
1152                 return ret;
1153
1154         SetPageUptodate(page);
1155         return 0;
1156 }
1157
1158 /* writepages: */
1159
1160 struct bch_writepage_state {
1161         struct bch_writepage_io *io;
1162         struct bch_io_opts      opts;
1163 };
1164
1165 static inline struct bch_writepage_state bch_writepage_state_init(struct bch_fs *c,
1166                                                                   struct bch_inode_info *inode)
1167 {
1168         return (struct bch_writepage_state) { .opts = io_opts(c, inode) };
1169 }
1170
1171 static void bch2_writepage_io_free(struct closure *cl)
1172 {
1173         struct bch_writepage_io *io = container_of(cl,
1174                                         struct bch_writepage_io, cl);
1175
1176         bio_put(&io->op.op.wbio.bio);
1177 }
1178
1179 static void bch2_writepage_io_done(struct closure *cl)
1180 {
1181         struct bch_writepage_io *io = container_of(cl,
1182                                         struct bch_writepage_io, cl);
1183         struct bch_fs *c = io->op.op.c;
1184         struct bio *bio = &io->op.op.wbio.bio;
1185         struct bio_vec *bvec;
1186         unsigned i;
1187
1188         atomic_sub(bio->bi_vcnt, &c->writeback_pages);
1189         wake_up(&c->writeback_wait);
1190
1191         if (io->op.op.error) {
1192                 bio_for_each_segment_all(bvec, bio, i)
1193                         SetPageError(bvec->bv_page);
1194                 set_bit(AS_EIO, &io->op.inode->v.i_mapping->flags);
1195         }
1196
1197         /*
1198          * racing with fallocate can cause us to add fewer sectors than
1199          * expected - but we shouldn't add more sectors than expected:
1200          */
1201         BUG_ON(io->op.sectors_added > (s64) io->new_sectors);
1202
1203         /*
1204          * (error (due to going RO) halfway through a page can screw that up
1205          * slightly)
1206          * XXX wtf?
1207            BUG_ON(io->op.sectors_added - io->new_sectors >= (s64) PAGE_SECTORS);
1208          */
1209
1210         /*
1211          * PageWriteback is effectively our ref on the inode - fixup i_blocks
1212          * before calling end_page_writeback:
1213          */
1214         if (io->op.sectors_added != io->new_sectors)
1215                 i_sectors_acct(c, io->op.inode, NULL,
1216                                io->op.sectors_added - (s64) io->new_sectors);
1217
1218         bio_for_each_segment_all(bvec, bio, i)
1219                 end_page_writeback(bvec->bv_page);
1220
1221         closure_return_with_destructor(&io->cl, bch2_writepage_io_free);
1222 }
1223
1224 static void bch2_writepage_do_io(struct bch_writepage_state *w)
1225 {
1226         struct bch_writepage_io *io = w->io;
1227         struct bio *bio = &io->op.op.wbio.bio;
1228
1229         w->io = NULL;
1230         atomic_add(bio->bi_vcnt, &io->op.op.c->writeback_pages);
1231
1232         closure_call(&io->op.op.cl, bch2_write, NULL, &io->cl);
1233         continue_at(&io->cl, bch2_writepage_io_done, NULL);
1234 }
1235
1236 /*
1237  * Get a bch_writepage_io and add @page to it - appending to an existing one if
1238  * possible, else allocating a new one:
1239  */
1240 static void bch2_writepage_io_alloc(struct bch_fs *c,
1241                                     struct bch_writepage_state *w,
1242                                     struct bch_inode_info *inode,
1243                                     struct page *page,
1244                                     unsigned nr_replicas)
1245 {
1246         struct bch_write_op *op;
1247         u64 offset = (u64) page->index << PAGE_SECTOR_SHIFT;
1248
1249         w->io = container_of(bio_alloc_bioset(GFP_NOFS,
1250                                               BIO_MAX_PAGES,
1251                                               &c->writepage_bioset),
1252                              struct bch_writepage_io, op.op.wbio.bio);
1253
1254         closure_init(&w->io->cl, NULL);
1255         w->io->new_sectors      = 0;
1256         bch2_fswrite_op_init(&w->io->op, c, inode, w->opts, false);
1257         op                      = &w->io->op.op;
1258         op->nr_replicas         = nr_replicas;
1259         op->res.nr_replicas     = nr_replicas;
1260         op->write_point         = writepoint_hashed(inode->ei_last_dirtied);
1261         op->pos                 = POS(inode->v.i_ino, offset);
1262         op->wbio.bio.bi_iter.bi_sector = offset;
1263 }
1264
1265 static int __bch2_writepage(struct bch_fs *c, struct page *page,
1266                             struct writeback_control *wbc,
1267                             struct bch_writepage_state *w)
1268 {
1269         struct bch_inode_info *inode = to_bch_ei(page->mapping->host);
1270         struct bch_page_state new, old;
1271         unsigned offset;
1272         loff_t i_size = i_size_read(&inode->v);
1273         pgoff_t end_index = i_size >> PAGE_SHIFT;
1274
1275         EBUG_ON(!PageUptodate(page));
1276
1277         /* Is the page fully inside i_size? */
1278         if (page->index < end_index)
1279                 goto do_io;
1280
1281         /* Is the page fully outside i_size? (truncate in progress) */
1282         offset = i_size & (PAGE_SIZE - 1);
1283         if (page->index > end_index || !offset) {
1284                 unlock_page(page);
1285                 return 0;
1286         }
1287
1288         /*
1289          * The page straddles i_size.  It must be zeroed out on each and every
1290          * writepage invocation because it may be mmapped.  "A file is mapped
1291          * in multiples of the page size.  For a file that is not a multiple of
1292          * the  page size, the remaining memory is zeroed when mapped, and
1293          * writes to that region are not written out to the file."
1294          */
1295         zero_user_segment(page, offset, PAGE_SIZE);
1296 do_io:
1297         /* Before unlocking the page, transfer reservation to w->io: */
1298         old = page_state_cmpxchg(page_state(page), new, {
1299                 EBUG_ON(!new.reserved &&
1300                         (new.sectors != PAGE_SECTORS ||
1301                         new.compressed));
1302
1303                 if (new.reserved)
1304                         new.nr_replicas = new.reservation_replicas;
1305                 new.reserved = 0;
1306
1307                 new.compressed |= w->opts.compression != 0;
1308
1309                 new.sectors += new.dirty_sectors;
1310                 new.dirty_sectors = 0;
1311         });
1312
1313         if (w->io &&
1314             (w->io->op.op.res.nr_replicas != new.nr_replicas ||
1315              !bio_can_add_page_contig(&w->io->op.op.wbio.bio, page)))
1316                 bch2_writepage_do_io(w);
1317
1318         if (!w->io)
1319                 bch2_writepage_io_alloc(c, w, inode, page, new.nr_replicas);
1320
1321         w->io->new_sectors += new.sectors - old.sectors;
1322
1323         BUG_ON(inode != w->io->op.inode);
1324         BUG_ON(bio_add_page_contig(&w->io->op.op.wbio.bio, page));
1325
1326         if (old.reserved)
1327                 w->io->op.op.res.sectors += old.reservation_replicas * PAGE_SECTORS;
1328
1329         /* while page is locked: */
1330         w->io->op.new_i_size = i_size;
1331
1332         if (wbc->sync_mode == WB_SYNC_ALL)
1333                 w->io->op.op.wbio.bio.bi_opf |= REQ_SYNC;
1334
1335         BUG_ON(PageWriteback(page));
1336         set_page_writeback(page);
1337         unlock_page(page);
1338
1339         return 0;
1340 }
1341
1342 int bch2_writepages(struct address_space *mapping, struct writeback_control *wbc)
1343 {
1344         struct bch_fs *c = mapping->host->i_sb->s_fs_info;
1345         struct bch_writepage_state w =
1346                 bch_writepage_state_init(c, to_bch_ei(mapping->host));
1347         struct pagecache_iter iter;
1348         struct page *page;
1349         int ret = 0;
1350         int done = 0;
1351         pgoff_t uninitialized_var(writeback_index);
1352         pgoff_t index;
1353         pgoff_t end;            /* Inclusive */
1354         pgoff_t done_index;
1355         int cycled;
1356         int range_whole = 0;
1357         int tag;
1358
1359         if (wbc->range_cyclic) {
1360                 writeback_index = mapping->writeback_index; /* prev offset */
1361                 index = writeback_index;
1362                 if (index == 0)
1363                         cycled = 1;
1364                 else
1365                         cycled = 0;
1366                 end = -1;
1367         } else {
1368                 index = wbc->range_start >> PAGE_SHIFT;
1369                 end = wbc->range_end >> PAGE_SHIFT;
1370                 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
1371                         range_whole = 1;
1372                 cycled = 1; /* ignore range_cyclic tests */
1373         }
1374         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
1375                 tag = PAGECACHE_TAG_TOWRITE;
1376         else
1377                 tag = PAGECACHE_TAG_DIRTY;
1378 retry:
1379         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
1380                 tag_pages_for_writeback(mapping, index, end);
1381
1382         done_index = index;
1383 get_pages:
1384         for_each_pagecache_tag(&iter, mapping, tag, index, end, page) {
1385                 done_index = page->index;
1386
1387                 if (w.io &&
1388                     !bio_can_add_page_contig(&w.io->op.op.wbio.bio, page))
1389                         bch2_writepage_do_io(&w);
1390
1391                 if (!w.io &&
1392                     atomic_read(&c->writeback_pages) >=
1393                     c->writeback_pages_max) {
1394                         /* don't sleep with pages pinned: */
1395                         pagecache_iter_release(&iter);
1396
1397                         __wait_event(c->writeback_wait,
1398                                      atomic_read(&c->writeback_pages) <
1399                                      c->writeback_pages_max);
1400                         goto get_pages;
1401                 }
1402
1403                 lock_page(page);
1404
1405                 /*
1406                  * Page truncated or invalidated. We can freely skip it
1407                  * then, even for data integrity operations: the page
1408                  * has disappeared concurrently, so there could be no
1409                  * real expectation of this data interity operation
1410                  * even if there is now a new, dirty page at the same
1411                  * pagecache address.
1412                  */
1413                 if (unlikely(page->mapping != mapping)) {
1414 continue_unlock:
1415                         unlock_page(page);
1416                         continue;
1417                 }
1418
1419                 if (!PageDirty(page)) {
1420                         /* someone wrote it for us */
1421                         goto continue_unlock;
1422                 }
1423
1424                 if (PageWriteback(page)) {
1425                         if (wbc->sync_mode != WB_SYNC_NONE)
1426                                 wait_on_page_writeback(page);
1427                         else
1428                                 goto continue_unlock;
1429                 }
1430
1431                 BUG_ON(PageWriteback(page));
1432                 if (!clear_page_dirty_for_io(page))
1433                         goto continue_unlock;
1434
1435                 trace_wbc_writepage(wbc, inode_to_bdi(mapping->host));
1436                 ret = __bch2_writepage(c, page, wbc, &w);
1437                 if (unlikely(ret)) {
1438                         if (ret == AOP_WRITEPAGE_ACTIVATE) {
1439                                 unlock_page(page);
1440                                 ret = 0;
1441                         } else {
1442                                 /*
1443                                  * done_index is set past this page,
1444                                  * so media errors will not choke
1445                                  * background writeout for the entire
1446                                  * file. This has consequences for
1447                                  * range_cyclic semantics (ie. it may
1448                                  * not be suitable for data integrity
1449                                  * writeout).
1450                                  */
1451                                 done_index = page->index + 1;
1452                                 done = 1;
1453                                 break;
1454                         }
1455                 }
1456
1457                 /*
1458                  * We stop writing back only if we are not doing
1459                  * integrity sync. In case of integrity sync we have to
1460                  * keep going until we have written all the pages
1461                  * we tagged for writeback prior to entering this loop.
1462                  */
1463                 if (--wbc->nr_to_write <= 0 &&
1464                     wbc->sync_mode == WB_SYNC_NONE) {
1465                         done = 1;
1466                         break;
1467                 }
1468         }
1469         pagecache_iter_release(&iter);
1470
1471         if (w.io)
1472                 bch2_writepage_do_io(&w);
1473
1474         if (!cycled && !done) {
1475                 /*
1476                  * range_cyclic:
1477                  * We hit the last page and there is more work to be done: wrap
1478                  * back to the start of the file
1479                  */
1480                 cycled = 1;
1481                 index = 0;
1482                 end = writeback_index - 1;
1483                 goto retry;
1484         }
1485         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
1486                 mapping->writeback_index = done_index;
1487
1488         return ret;
1489 }
1490
1491 int bch2_writepage(struct page *page, struct writeback_control *wbc)
1492 {
1493         struct bch_fs *c = page->mapping->host->i_sb->s_fs_info;
1494         struct bch_writepage_state w =
1495                 bch_writepage_state_init(c, to_bch_ei(page->mapping->host));
1496         int ret;
1497
1498         ret = __bch2_writepage(c, page, wbc, &w);
1499         if (w.io)
1500                 bch2_writepage_do_io(&w);
1501
1502         return ret;
1503 }
1504
1505 /* buffered writes: */
1506
1507 int bch2_write_begin(struct file *file, struct address_space *mapping,
1508                      loff_t pos, unsigned len, unsigned flags,
1509                      struct page **pagep, void **fsdata)
1510 {
1511         struct bch_inode_info *inode = to_bch_ei(mapping->host);
1512         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1513         pgoff_t index = pos >> PAGE_SHIFT;
1514         unsigned offset = pos & (PAGE_SIZE - 1);
1515         struct page *page;
1516         int ret = -ENOMEM;
1517
1518         BUG_ON(inode_unhashed(&inode->v));
1519
1520         /* Not strictly necessary - same reason as mkwrite(): */
1521         pagecache_add_get(&mapping->add_lock);
1522
1523         page = grab_cache_page_write_begin(mapping, index, flags);
1524         if (!page)
1525                 goto err_unlock;
1526
1527         if (PageUptodate(page))
1528                 goto out;
1529
1530         /* If we're writing entire page, don't need to read it in first: */
1531         if (len == PAGE_SIZE)
1532                 goto out;
1533
1534         if (!offset && pos + len >= inode->v.i_size) {
1535                 zero_user_segment(page, len, PAGE_SIZE);
1536                 flush_dcache_page(page);
1537                 goto out;
1538         }
1539
1540         if (index > inode->v.i_size >> PAGE_SHIFT) {
1541                 zero_user_segments(page, 0, offset, offset + len, PAGE_SIZE);
1542                 flush_dcache_page(page);
1543                 goto out;
1544         }
1545 readpage:
1546         ret = bch2_read_single_page(page, mapping);
1547         if (ret)
1548                 goto err;
1549 out:
1550         ret = bch2_get_page_reservation(c, inode, page, true);
1551         if (ret) {
1552                 if (!PageUptodate(page)) {
1553                         /*
1554                          * If the page hasn't been read in, we won't know if we
1555                          * actually need a reservation - we don't actually need
1556                          * to read here, we just need to check if the page is
1557                          * fully backed by uncompressed data:
1558                          */
1559                         goto readpage;
1560                 }
1561
1562                 goto err;
1563         }
1564
1565         *pagep = page;
1566         return 0;
1567 err:
1568         unlock_page(page);
1569         put_page(page);
1570         *pagep = NULL;
1571 err_unlock:
1572         pagecache_add_put(&mapping->add_lock);
1573         return ret;
1574 }
1575
1576 int bch2_write_end(struct file *file, struct address_space *mapping,
1577                    loff_t pos, unsigned len, unsigned copied,
1578                    struct page *page, void *fsdata)
1579 {
1580         struct bch_inode_info *inode = to_bch_ei(mapping->host);
1581         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1582
1583         lockdep_assert_held(&inode->v.i_rwsem);
1584
1585         if (unlikely(copied < len && !PageUptodate(page))) {
1586                 /*
1587                  * The page needs to be read in, but that would destroy
1588                  * our partial write - simplest thing is to just force
1589                  * userspace to redo the write:
1590                  */
1591                 zero_user(page, 0, PAGE_SIZE);
1592                 flush_dcache_page(page);
1593                 copied = 0;
1594         }
1595
1596         if (pos + copied > inode->v.i_size)
1597                 i_size_write(&inode->v, pos + copied);
1598
1599         if (copied) {
1600                 if (!PageUptodate(page))
1601                         SetPageUptodate(page);
1602                 if (!PageDirty(page))
1603                         set_page_dirty(page);
1604
1605                 inode->ei_last_dirtied = (unsigned long) current;
1606         } else {
1607                 bch2_put_page_reservation(c, inode, page);
1608         }
1609
1610         unlock_page(page);
1611         put_page(page);
1612         pagecache_add_put(&mapping->add_lock);
1613
1614         return copied;
1615 }
1616
1617 /* O_DIRECT reads */
1618
1619 static void bch2_dio_read_complete(struct closure *cl)
1620 {
1621         struct dio_read *dio = container_of(cl, struct dio_read, cl);
1622
1623         dio->req->ki_complete(dio->req, dio->ret, 0);
1624         bio_check_pages_dirty(&dio->rbio.bio);  /* transfers ownership */
1625 }
1626
1627 static void bch2_direct_IO_read_endio(struct bio *bio)
1628 {
1629         struct dio_read *dio = bio->bi_private;
1630
1631         if (bio->bi_status)
1632                 dio->ret = blk_status_to_errno(bio->bi_status);
1633
1634         closure_put(&dio->cl);
1635 }
1636
1637 static void bch2_direct_IO_read_split_endio(struct bio *bio)
1638 {
1639         bch2_direct_IO_read_endio(bio);
1640         bio_check_pages_dirty(bio);     /* transfers ownership */
1641 }
1642
1643 static int bch2_direct_IO_read(struct kiocb *req, struct iov_iter *iter)
1644 {
1645         struct file *file = req->ki_filp;
1646         struct bch_inode_info *inode = file_bch_inode(file);
1647         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1648         struct bch_io_opts opts = io_opts(c, inode);
1649         struct dio_read *dio;
1650         struct bio *bio;
1651         loff_t offset = req->ki_pos;
1652         bool sync = is_sync_kiocb(req);
1653         ssize_t ret;
1654
1655         if ((offset|iter->count) & (block_bytes(c) - 1))
1656                 return -EINVAL;
1657
1658         ret = min_t(loff_t, iter->count,
1659                     max_t(loff_t, 0, i_size_read(&inode->v) - offset));
1660         iov_iter_truncate(iter, round_up(ret, block_bytes(c)));
1661
1662         if (!ret)
1663                 return ret;
1664
1665         bio = bio_alloc_bioset(GFP_KERNEL,
1666                                iov_iter_npages(iter, BIO_MAX_PAGES),
1667                                &c->dio_read_bioset);
1668
1669         bio->bi_end_io = bch2_direct_IO_read_endio;
1670
1671         dio = container_of(bio, struct dio_read, rbio.bio);
1672         closure_init(&dio->cl, NULL);
1673
1674         /*
1675          * this is a _really_ horrible hack just to avoid an atomic sub at the
1676          * end:
1677          */
1678         if (!sync) {
1679                 set_closure_fn(&dio->cl, bch2_dio_read_complete, NULL);
1680                 atomic_set(&dio->cl.remaining,
1681                            CLOSURE_REMAINING_INITIALIZER -
1682                            CLOSURE_RUNNING +
1683                            CLOSURE_DESTRUCTOR);
1684         } else {
1685                 atomic_set(&dio->cl.remaining,
1686                            CLOSURE_REMAINING_INITIALIZER + 1);
1687         }
1688
1689         dio->req        = req;
1690         dio->ret        = ret;
1691
1692         goto start;
1693         while (iter->count) {
1694                 bio = bio_alloc_bioset(GFP_KERNEL,
1695                                        iov_iter_npages(iter, BIO_MAX_PAGES),
1696                                        &c->bio_read);
1697                 bio->bi_end_io          = bch2_direct_IO_read_split_endio;
1698 start:
1699                 bio_set_op_attrs(bio, REQ_OP_READ, REQ_SYNC);
1700                 bio->bi_iter.bi_sector  = offset >> 9;
1701                 bio->bi_private         = dio;
1702
1703                 ret = bio_iov_iter_get_pages(bio, iter);
1704                 if (ret < 0) {
1705                         /* XXX: fault inject this path */
1706                         bio->bi_status = BLK_STS_RESOURCE;
1707                         bio_endio(bio);
1708                         break;
1709                 }
1710
1711                 offset += bio->bi_iter.bi_size;
1712                 bio_set_pages_dirty(bio);
1713
1714                 if (iter->count)
1715                         closure_get(&dio->cl);
1716
1717                 bch2_read(c, rbio_init(bio, opts), inode->v.i_ino);
1718         }
1719
1720         if (sync) {
1721                 closure_sync(&dio->cl);
1722                 closure_debug_destroy(&dio->cl);
1723                 ret = dio->ret;
1724                 bio_check_pages_dirty(&dio->rbio.bio); /* transfers ownership */
1725                 return ret;
1726         } else {
1727                 return -EIOCBQUEUED;
1728         }
1729 }
1730
1731 /* O_DIRECT writes */
1732
1733 static void bch2_dio_write_loop_async(struct closure *);
1734
1735 static long bch2_dio_write_loop(struct dio_write *dio)
1736 {
1737         struct kiocb *req = dio->req;
1738         struct address_space *mapping = req->ki_filp->f_mapping;
1739         struct bch_inode_info *inode = dio->iop.inode;
1740         struct bio *bio = &dio->iop.op.wbio.bio;
1741         struct bio_vec *bv;
1742         bool sync;
1743         long ret;
1744         int i;
1745
1746         if (dio->loop)
1747                 goto loop;
1748
1749         inode_dio_begin(&inode->v);
1750         __pagecache_block_get(&mapping->add_lock);
1751
1752         /* Write and invalidate pagecache range that we're writing to: */
1753         ret = write_invalidate_inode_pages_range(mapping, req->ki_pos,
1754                                 req->ki_pos + iov_iter_count(&dio->iter) - 1);
1755         if (unlikely(ret))
1756                 goto err;
1757
1758         while (1) {
1759                 BUG_ON(current->pagecache_lock);
1760                 current->pagecache_lock = &mapping->add_lock;
1761                 if (current != dio->task)
1762                         use_mm(dio->task->mm);
1763
1764                 ret = bio_iov_iter_get_pages(bio, &dio->iter);
1765
1766                 if (current != dio->task)
1767                         unuse_mm(dio->task->mm);
1768                 current->pagecache_lock = NULL;
1769
1770                 if (unlikely(ret < 0))
1771                         goto err;
1772
1773                 dio->iop.op.pos = POS(inode->v.i_ino,
1774                                 (req->ki_pos >> 9) + dio->iop.op.written);
1775
1776                 task_io_account_write(bio->bi_iter.bi_size);
1777
1778                 closure_call(&dio->iop.op.cl, bch2_write, NULL, &dio->cl);
1779
1780                 if (!dio->sync && !dio->loop && dio->iter.count) {
1781                         struct iovec *iov = dio->inline_vecs;
1782
1783                         if (dio->iter.nr_segs > ARRAY_SIZE(dio->inline_vecs)) {
1784                                 iov = kmalloc(dio->iter.nr_segs * sizeof(*iov),
1785                                               GFP_KERNEL);
1786                                 if (unlikely(!iov)) {
1787                                         dio->iop.op.error = -ENOMEM;
1788                                         goto err_wait_io;
1789                                 }
1790
1791                                 dio->free_iov = true;
1792                         }
1793
1794                         memcpy(iov, dio->iter.iov, dio->iter.nr_segs * sizeof(*iov));
1795                         dio->iter.iov = iov;
1796                 }
1797 err_wait_io:
1798                 dio->loop = true;
1799
1800                 if (!dio->sync) {
1801                         continue_at_noreturn(&dio->cl,
1802                                         bch2_dio_write_loop_async, NULL);
1803                         return -EIOCBQUEUED;
1804                 }
1805
1806                 closure_sync(&dio->cl);
1807 loop:
1808                 bio_for_each_segment_all(bv, bio, i)
1809                         put_page(bv->bv_page);
1810                 if (!dio->iter.count || dio->iop.op.error)
1811                         break;
1812                 bio_reset(bio);
1813         }
1814
1815         ret = dio->iop.op.error ?: ((long) dio->iop.op.written << 9);
1816 err:
1817         __pagecache_block_put(&mapping->add_lock);
1818         bch2_disk_reservation_put(dio->iop.op.c, &dio->iop.op.res);
1819         bch2_quota_reservation_put(dio->iop.op.c, inode, &dio->quota_res);
1820
1821         if (dio->free_iov)
1822                 kfree(dio->iter.iov);
1823
1824         closure_debug_destroy(&dio->cl);
1825
1826         sync = dio->sync;
1827         bio_put(bio);
1828
1829         /* inode->i_dio_count is our ref on inode and thus bch_fs */
1830         inode_dio_end(&inode->v);
1831
1832         if (!sync) {
1833                 req->ki_complete(req, ret, 0);
1834                 ret = -EIOCBQUEUED;
1835         }
1836         return ret;
1837 }
1838
1839 static void bch2_dio_write_loop_async(struct closure *cl)
1840 {
1841         struct dio_write *dio = container_of(cl, struct dio_write, cl);
1842
1843         bch2_dio_write_loop(dio);
1844 }
1845
1846 static int bch2_direct_IO_write(struct kiocb *req,
1847                                 struct iov_iter *iter,
1848                                 bool swap)
1849 {
1850         struct file *file = req->ki_filp;
1851         struct bch_inode_info *inode = file_bch_inode(file);
1852         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1853         struct dio_write *dio;
1854         struct bio *bio;
1855         loff_t offset = req->ki_pos;
1856         ssize_t ret;
1857
1858         lockdep_assert_held(&inode->v.i_rwsem);
1859
1860         if (unlikely(!iter->count))
1861                 return 0;
1862
1863         if (unlikely((offset|iter->count) & (block_bytes(c) - 1)))
1864                 return -EINVAL;
1865
1866         bio = bio_alloc_bioset(GFP_KERNEL,
1867                                iov_iter_npages(iter, BIO_MAX_PAGES),
1868                                &c->dio_write_bioset);
1869         dio = container_of(bio, struct dio_write, iop.op.wbio.bio);
1870         closure_init(&dio->cl, NULL);
1871         dio->req                = req;
1872         dio->task               = current;
1873         dio->loop               = false;
1874         dio->sync               = is_sync_kiocb(req) ||
1875                 offset + iter->count > inode->v.i_size;
1876         dio->free_iov           = false;
1877         dio->quota_res.sectors  = 0;
1878         dio->iter               = *iter;
1879         bch2_fswrite_op_init(&dio->iop, c, inode, io_opts(c, inode), true);
1880         dio->iop.op.write_point = writepoint_hashed((unsigned long) dio->task);
1881         dio->iop.op.flags |= BCH_WRITE_NOPUT_RESERVATION;
1882
1883         if ((req->ki_flags & IOCB_DSYNC) &&
1884             !c->opts.journal_flush_disabled)
1885                 dio->iop.op.flags |= BCH_WRITE_FLUSH;
1886
1887         ret = bch2_quota_reservation_add(c, inode, &dio->quota_res,
1888                                          iter->count >> 9, true);
1889         if (unlikely(ret))
1890                 goto err;
1891
1892         ret = bch2_disk_reservation_get(c, &dio->iop.op.res, iter->count >> 9,
1893                                         c->opts.data_replicas, 0);
1894         if (unlikely(ret)) {
1895                 if (bch2_check_range_allocated(c, POS(inode->v.i_ino,
1896                                                       offset >> 9),
1897                                                iter->count >> 9))
1898                         goto err;
1899
1900                 dio->iop.unalloc = true;
1901         }
1902
1903         dio->iop.op.nr_replicas = dio->iop.op.res.nr_replicas;
1904
1905         return bch2_dio_write_loop(dio);
1906 err:
1907         bch2_disk_reservation_put(c, &dio->iop.op.res);
1908         bch2_quota_reservation_put(c, inode, &dio->quota_res);
1909         closure_debug_destroy(&dio->cl);
1910         bio_put(bio);
1911         return ret;
1912 }
1913
1914 ssize_t bch2_direct_IO(struct kiocb *req, struct iov_iter *iter)
1915 {
1916         struct blk_plug plug;
1917         ssize_t ret;
1918
1919         blk_start_plug(&plug);
1920         ret = iov_iter_rw(iter) == WRITE
1921                 ? bch2_direct_IO_write(req, iter, false)
1922                 : bch2_direct_IO_read(req, iter);
1923         blk_finish_plug(&plug);
1924
1925         return ret;
1926 }
1927
1928 static ssize_t
1929 bch2_direct_write(struct kiocb *iocb, struct iov_iter *iter)
1930 {
1931         return bch2_direct_IO_write(iocb, iter, true);
1932 }
1933
1934 static ssize_t __bch2_write_iter(struct kiocb *iocb, struct iov_iter *from)
1935 {
1936         struct file *file = iocb->ki_filp;
1937         struct bch_inode_info *inode = file_bch_inode(file);
1938         ssize_t ret;
1939
1940         /* We can write back this queue in page reclaim */
1941         current->backing_dev_info = inode_to_bdi(&inode->v);
1942         ret = file_remove_privs(file);
1943         if (ret)
1944                 goto out;
1945
1946         ret = file_update_time(file);
1947         if (ret)
1948                 goto out;
1949
1950         ret = iocb->ki_flags & IOCB_DIRECT
1951                 ? bch2_direct_write(iocb, from)
1952                 : generic_perform_write(file, from, iocb->ki_pos);
1953
1954         if (likely(ret > 0))
1955                 iocb->ki_pos += ret;
1956 out:
1957         current->backing_dev_info = NULL;
1958         return ret;
1959 }
1960
1961 ssize_t bch2_write_iter(struct kiocb *iocb, struct iov_iter *from)
1962 {
1963         struct bch_inode_info *inode = file_bch_inode(iocb->ki_filp);
1964         bool direct = iocb->ki_flags & IOCB_DIRECT;
1965         ssize_t ret;
1966
1967         inode_lock(&inode->v);
1968         ret = generic_write_checks(iocb, from);
1969         if (ret > 0)
1970                 ret = __bch2_write_iter(iocb, from);
1971         inode_unlock(&inode->v);
1972
1973         if (ret > 0 && !direct)
1974                 ret = generic_write_sync(iocb, ret);
1975
1976         return ret;
1977 }
1978
1979 /* fsync: */
1980
1981 int bch2_fsync(struct file *file, loff_t start, loff_t end, int datasync)
1982 {
1983         struct bch_inode_info *inode = file_bch_inode(file);
1984         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1985         int ret;
1986
1987         ret = filemap_write_and_wait_range(inode->v.i_mapping, start, end);
1988         if (ret)
1989                 return ret;
1990
1991         if (c->opts.journal_flush_disabled)
1992                 return 0;
1993
1994         return bch2_journal_flush_seq(&c->journal, inode->ei_journal_seq);
1995 }
1996
1997 /* truncate: */
1998
1999 static int __bch2_truncate_page(struct bch_inode_info *inode,
2000                                 pgoff_t index, loff_t start, loff_t end)
2001 {
2002         struct bch_fs *c = inode->v.i_sb->s_fs_info;
2003         struct address_space *mapping = inode->v.i_mapping;
2004         unsigned start_offset = start & (PAGE_SIZE - 1);
2005         unsigned end_offset = ((end - 1) & (PAGE_SIZE - 1)) + 1;
2006         struct page *page;
2007         int ret = 0;
2008
2009         /* Page boundary? Nothing to do */
2010         if (!((index == start >> PAGE_SHIFT && start_offset) ||
2011               (index == end >> PAGE_SHIFT && end_offset != PAGE_SIZE)))
2012                 return 0;
2013
2014         /* Above i_size? */
2015         if (index << PAGE_SHIFT >= inode->v.i_size)
2016                 return 0;
2017
2018         page = find_lock_page(mapping, index);
2019         if (!page) {
2020                 struct btree_iter iter;
2021                 struct bkey_s_c k = bkey_s_c_null;
2022
2023                 /*
2024                  * XXX: we're doing two index lookups when we end up reading the
2025                  * page
2026                  */
2027                 for_each_btree_key(&iter, c, BTREE_ID_EXTENTS,
2028                                    POS(inode->v.i_ino,
2029                                        index << PAGE_SECTOR_SHIFT), 0, k) {
2030                         if (bkey_cmp(bkey_start_pos(k.k),
2031                                      POS(inode->v.i_ino,
2032                                          (index + 1) << PAGE_SECTOR_SHIFT)) >= 0)
2033                                 break;
2034
2035                         if (k.k->type != KEY_TYPE_DISCARD &&
2036                             k.k->type != BCH_RESERVATION) {
2037                                 bch2_btree_iter_unlock(&iter);
2038                                 goto create;
2039                         }
2040                 }
2041                 bch2_btree_iter_unlock(&iter);
2042                 return 0;
2043 create:
2044                 page = find_or_create_page(mapping, index, GFP_KERNEL);
2045                 if (unlikely(!page)) {
2046                         ret = -ENOMEM;
2047                         goto out;
2048                 }
2049         }
2050
2051         if (!PageUptodate(page)) {
2052                 ret = bch2_read_single_page(page, mapping);
2053                 if (ret)
2054                         goto unlock;
2055         }
2056
2057         /*
2058          * Bit of a hack - we don't want truncate to fail due to -ENOSPC.
2059          *
2060          * XXX: because we aren't currently tracking whether the page has actual
2061          * data in it (vs. just 0s, or only partially written) this wrong. ick.
2062          */
2063         ret = bch2_get_page_reservation(c, inode, page, false);
2064         BUG_ON(ret);
2065
2066         if (index == start >> PAGE_SHIFT &&
2067             index == end >> PAGE_SHIFT)
2068                 zero_user_segment(page, start_offset, end_offset);
2069         else if (index == start >> PAGE_SHIFT)
2070                 zero_user_segment(page, start_offset, PAGE_SIZE);
2071         else if (index == end >> PAGE_SHIFT)
2072                 zero_user_segment(page, 0, end_offset);
2073
2074         if (!PageDirty(page))
2075                 set_page_dirty(page);
2076 unlock:
2077         unlock_page(page);
2078         put_page(page);
2079 out:
2080         return ret;
2081 }
2082
2083 static int bch2_truncate_page(struct bch_inode_info *inode, loff_t from)
2084 {
2085         return __bch2_truncate_page(inode, from >> PAGE_SHIFT,
2086                                     from, from + PAGE_SIZE);
2087 }
2088
2089 int bch2_truncate(struct bch_inode_info *inode, struct iattr *iattr)
2090 {
2091         struct bch_fs *c = inode->v.i_sb->s_fs_info;
2092         struct address_space *mapping = inode->v.i_mapping;
2093         bool shrink = iattr->ia_size <= inode->v.i_size;
2094         struct i_sectors_hook i_sectors_hook =
2095                 i_sectors_hook_init(inode, BCH_INODE_I_SIZE_DIRTY);
2096         int ret = 0;
2097
2098         inode_dio_wait(&inode->v);
2099         pagecache_block_get(&mapping->add_lock);
2100
2101         truncate_setsize(&inode->v, iattr->ia_size);
2102
2103         /* sync appends.. */
2104         /* XXX what protects inode->i_size? */
2105         if (iattr->ia_size > inode->ei_inode.bi_size)
2106                 ret = filemap_write_and_wait_range(mapping,
2107                                                    inode->ei_inode.bi_size, S64_MAX);
2108         if (ret)
2109                 goto err_put_pagecache;
2110
2111         i_sectors_hook.new_i_size = iattr->ia_size;
2112
2113         ret = i_sectors_dirty_start(c, &i_sectors_hook);
2114         if (unlikely(ret))
2115                 goto err;
2116
2117         /*
2118          * There might be persistent reservations (from fallocate())
2119          * above i_size, which bch2_inode_truncate() will discard - we're
2120          * only supposed to discard them if we're doing a real truncate
2121          * here (new i_size < current i_size):
2122          */
2123         if (shrink) {
2124                 ret = bch2_truncate_page(inode, iattr->ia_size);
2125                 if (unlikely(ret))
2126                         goto err;
2127
2128                 ret = bch2_inode_truncate(c, inode->v.i_ino,
2129                                           round_up(iattr->ia_size, PAGE_SIZE) >> 9,
2130                                           &i_sectors_hook.hook,
2131                                           &inode->ei_journal_seq);
2132                 if (unlikely(ret))
2133                         goto err;
2134         }
2135
2136         setattr_copy(&inode->v, iattr);
2137         inode->v.i_mtime = inode->v.i_ctime = current_time(&inode->v);
2138 err:
2139         /*
2140          * On error - in particular, bch2_truncate_page() error - don't clear
2141          * I_SIZE_DIRTY, as we've left data above i_size!:
2142          */
2143         if (ret)
2144                 i_sectors_hook.flags &= ~BCH_INODE_I_SIZE_DIRTY;
2145
2146         ret = i_sectors_dirty_finish(c, &i_sectors_hook) ?: ret;
2147 err_put_pagecache:
2148         pagecache_block_put(&mapping->add_lock);
2149         return ret;
2150 }
2151
2152 /* fallocate: */
2153
2154 static long bch2_fpunch(struct bch_inode_info *inode, loff_t offset, loff_t len)
2155 {
2156         struct bch_fs *c = inode->v.i_sb->s_fs_info;
2157         struct address_space *mapping = inode->v.i_mapping;
2158         u64 ino = inode->v.i_ino;
2159         u64 discard_start = round_up(offset, PAGE_SIZE) >> 9;
2160         u64 discard_end = round_down(offset + len, PAGE_SIZE) >> 9;
2161         int ret = 0;
2162
2163         inode_lock(&inode->v);
2164         inode_dio_wait(&inode->v);
2165         pagecache_block_get(&mapping->add_lock);
2166
2167         ret = __bch2_truncate_page(inode,
2168                                    offset >> PAGE_SHIFT,
2169                                    offset, offset + len);
2170         if (unlikely(ret))
2171                 goto err;
2172
2173         if (offset >> PAGE_SHIFT !=
2174             (offset + len) >> PAGE_SHIFT) {
2175                 ret = __bch2_truncate_page(inode,
2176                                            (offset + len) >> PAGE_SHIFT,
2177                                            offset, offset + len);
2178                 if (unlikely(ret))
2179                         goto err;
2180         }
2181
2182         truncate_pagecache_range(&inode->v, offset, offset + len - 1);
2183
2184         if (discard_start < discard_end) {
2185                 /*
2186                  * We need to pass in a disk reservation here because we might
2187                  * be splitting a compressed extent into two. This isn't a
2188                  * problem with truncate because truncate will never split an
2189                  * extent, only truncate it...
2190                  */
2191                 struct disk_reservation disk_res =
2192                         bch2_disk_reservation_init(c, 0);
2193                 struct i_sectors_hook i_sectors_hook =
2194                         i_sectors_hook_init(inode, 0);
2195                 int ret;
2196
2197                 ret = i_sectors_dirty_start(c, &i_sectors_hook);
2198                 if (unlikely(ret))
2199                         goto err;
2200
2201                 ret = bch2_btree_delete_range(c,
2202                                 BTREE_ID_EXTENTS,
2203                                 POS(ino, discard_start),
2204                                 POS(ino, discard_end),
2205                                 ZERO_VERSION,
2206                                 &disk_res,
2207                                 &i_sectors_hook.hook,
2208                                 &inode->ei_journal_seq);
2209
2210                 ret = i_sectors_dirty_finish(c, &i_sectors_hook) ?: ret;
2211         }
2212 err:
2213         pagecache_block_put(&mapping->add_lock);
2214         inode_unlock(&inode->v);
2215
2216         return ret;
2217 }
2218
2219 static long bch2_fcollapse(struct bch_inode_info *inode,
2220                            loff_t offset, loff_t len)
2221 {
2222         struct bch_fs *c = inode->v.i_sb->s_fs_info;
2223         struct address_space *mapping = inode->v.i_mapping;
2224         struct btree_iter src;
2225         struct btree_iter dst;
2226         BKEY_PADDED(k) copy;
2227         struct bkey_s_c k;
2228         struct i_sectors_hook i_sectors_hook = i_sectors_hook_init(inode, 0);
2229         loff_t new_size;
2230         int ret;
2231
2232         if ((offset | len) & (PAGE_SIZE - 1))
2233                 return -EINVAL;
2234
2235         bch2_btree_iter_init(&dst, c, BTREE_ID_EXTENTS,
2236                              POS(inode->v.i_ino, offset >> 9),
2237                              BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
2238         /* position will be set from dst iter's position: */
2239         bch2_btree_iter_init(&src, c, BTREE_ID_EXTENTS, POS_MIN,
2240                              BTREE_ITER_SLOTS);
2241         bch2_btree_iter_link(&src, &dst);
2242
2243         /*
2244          * We need i_mutex to keep the page cache consistent with the extents
2245          * btree, and the btree consistent with i_size - we don't need outside
2246          * locking for the extents btree itself, because we're using linked
2247          * iterators
2248          */
2249         inode_lock(&inode->v);
2250         inode_dio_wait(&inode->v);
2251         pagecache_block_get(&mapping->add_lock);
2252
2253         ret = -EINVAL;
2254         if (offset + len >= inode->v.i_size)
2255                 goto err;
2256
2257         if (inode->v.i_size < len)
2258                 goto err;
2259
2260         new_size = inode->v.i_size - len;
2261
2262         ret = write_invalidate_inode_pages_range(mapping, offset, LLONG_MAX);
2263         if (ret)
2264                 goto err;
2265
2266         ret = i_sectors_dirty_start(c, &i_sectors_hook);
2267         if (ret)
2268                 goto err;
2269
2270         while (bkey_cmp(dst.pos,
2271                         POS(inode->v.i_ino,
2272                             round_up(new_size, PAGE_SIZE) >> 9)) < 0) {
2273                 struct disk_reservation disk_res;
2274
2275                 bch2_btree_iter_set_pos(&src,
2276                         POS(dst.pos.inode, dst.pos.offset + (len >> 9)));
2277
2278                 k = bch2_btree_iter_peek_slot(&src);
2279                 if ((ret = btree_iter_err(k)))
2280                         goto btree_iter_err;
2281
2282                 bkey_reassemble(&copy.k, k);
2283
2284                 if (bkey_deleted(&copy.k.k))
2285                         copy.k.k.type = KEY_TYPE_DISCARD;
2286
2287                 bch2_cut_front(src.pos, &copy.k);
2288                 copy.k.k.p.offset -= len >> 9;
2289
2290                 BUG_ON(bkey_cmp(dst.pos, bkey_start_pos(&copy.k.k)));
2291
2292                 ret = bch2_disk_reservation_get(c, &disk_res, copy.k.k.size,
2293                                 bch2_extent_nr_dirty_ptrs(bkey_i_to_s_c(&copy.k)),
2294                                 BCH_DISK_RESERVATION_NOFAIL);
2295                 BUG_ON(ret);
2296
2297                 ret = bch2_btree_insert_at(c, &disk_res, &i_sectors_hook.hook,
2298                                            &inode->ei_journal_seq,
2299                                            BTREE_INSERT_ATOMIC|
2300                                            BTREE_INSERT_NOFAIL,
2301                                            BTREE_INSERT_ENTRY(&dst, &copy.k));
2302                 bch2_disk_reservation_put(c, &disk_res);
2303 btree_iter_err:
2304                 if (ret == -EINTR)
2305                         ret = 0;
2306                 if (ret)
2307                         goto err_put_sectors_dirty;
2308                 /*
2309                  * XXX: if we error here we've left data with multiple
2310                  * pointers... which isn't a _super_ serious problem...
2311                  */
2312
2313                 bch2_btree_iter_cond_resched(&src);
2314         }
2315
2316         bch2_btree_iter_unlock(&src);
2317         bch2_btree_iter_unlock(&dst);
2318
2319         ret = bch2_inode_truncate(c, inode->v.i_ino,
2320                                  round_up(new_size, PAGE_SIZE) >> 9,
2321                                  &i_sectors_hook.hook,
2322                                  &inode->ei_journal_seq);
2323         if (ret)
2324                 goto err_put_sectors_dirty;
2325
2326         i_size_write(&inode->v, new_size);
2327         i_sectors_hook.new_i_size = new_size;
2328 err_put_sectors_dirty:
2329         ret = i_sectors_dirty_finish(c, &i_sectors_hook) ?: ret;
2330 err:
2331         pagecache_block_put(&mapping->add_lock);
2332         inode_unlock(&inode->v);
2333
2334         bch2_btree_iter_unlock(&src);
2335         bch2_btree_iter_unlock(&dst);
2336         return ret;
2337 }
2338
2339 static long bch2_fallocate(struct bch_inode_info *inode, int mode,
2340                            loff_t offset, loff_t len)
2341 {
2342         struct address_space *mapping = inode->v.i_mapping;
2343         struct bch_fs *c = inode->v.i_sb->s_fs_info;
2344         struct i_sectors_hook i_sectors_hook = i_sectors_hook_init(inode, 0);
2345         struct btree_iter iter;
2346         struct bpos end_pos;
2347         loff_t block_start, block_end;
2348         loff_t end = offset + len;
2349         unsigned sectors;
2350         unsigned replicas = READ_ONCE(c->opts.data_replicas);
2351         int ret;
2352
2353         bch2_btree_iter_init(&iter, c, BTREE_ID_EXTENTS, POS_MIN,
2354                              BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
2355
2356         inode_lock(&inode->v);
2357         inode_dio_wait(&inode->v);
2358         pagecache_block_get(&mapping->add_lock);
2359
2360         if (!(mode & FALLOC_FL_KEEP_SIZE) && end > inode->v.i_size) {
2361                 ret = inode_newsize_ok(&inode->v, end);
2362                 if (ret)
2363                         goto err;
2364         }
2365
2366         if (mode & FALLOC_FL_ZERO_RANGE) {
2367                 ret = __bch2_truncate_page(inode,
2368                                            offset >> PAGE_SHIFT,
2369                                            offset, end);
2370
2371                 if (!ret &&
2372                     offset >> PAGE_SHIFT != end >> PAGE_SHIFT)
2373                         ret = __bch2_truncate_page(inode,
2374                                                    end >> PAGE_SHIFT,
2375                                                    offset, end);
2376
2377                 if (unlikely(ret))
2378                         goto err;
2379
2380                 truncate_pagecache_range(&inode->v, offset, end - 1);
2381
2382                 block_start     = round_up(offset, PAGE_SIZE);
2383                 block_end       = round_down(end, PAGE_SIZE);
2384         } else {
2385                 block_start     = round_down(offset, PAGE_SIZE);
2386                 block_end       = round_up(end, PAGE_SIZE);
2387         }
2388
2389         bch2_btree_iter_set_pos(&iter, POS(inode->v.i_ino, block_start >> 9));
2390         end_pos = POS(inode->v.i_ino, block_end >> 9);
2391
2392         ret = i_sectors_dirty_start(c, &i_sectors_hook);
2393         if (unlikely(ret))
2394                 goto err;
2395
2396         while (bkey_cmp(iter.pos, end_pos) < 0) {
2397                 struct disk_reservation disk_res = { 0 };
2398                 struct bkey_i_reservation reservation;
2399                 struct bkey_s_c k;
2400
2401                 k = bch2_btree_iter_peek_slot(&iter);
2402                 if ((ret = btree_iter_err(k)))
2403                         goto btree_iter_err;
2404
2405                 /* already reserved */
2406                 if (k.k->type == BCH_RESERVATION &&
2407                     bkey_s_c_to_reservation(k).v->nr_replicas >= replicas) {
2408                         bch2_btree_iter_next_slot(&iter);
2409                         continue;
2410                 }
2411
2412                 if (bkey_extent_is_data(k.k)) {
2413                         if (!(mode & FALLOC_FL_ZERO_RANGE)) {
2414                                 bch2_btree_iter_next_slot(&iter);
2415                                 continue;
2416                         }
2417                 }
2418
2419                 bkey_reservation_init(&reservation.k_i);
2420                 reservation.k.type      = BCH_RESERVATION;
2421                 reservation.k.p         = k.k->p;
2422                 reservation.k.size      = k.k->size;
2423
2424                 bch2_cut_front(iter.pos, &reservation.k_i);
2425                 bch2_cut_back(end_pos, &reservation.k);
2426
2427                 sectors = reservation.k.size;
2428                 reservation.v.nr_replicas = bch2_extent_nr_dirty_ptrs(k);
2429
2430                 if (!bkey_extent_is_allocation(k.k)) {
2431                         ret = bch2_quota_reservation_add(c, inode,
2432                                         &i_sectors_hook.quota_res,
2433                                         sectors, true);
2434                         if (unlikely(ret))
2435                                 goto err_put_sectors_dirty;
2436                 }
2437
2438                 if (reservation.v.nr_replicas < replicas ||
2439                     bch2_extent_is_compressed(k)) {
2440                         ret = bch2_disk_reservation_get(c, &disk_res, sectors,
2441                                                         replicas, 0);
2442                         if (unlikely(ret))
2443                                 goto err_put_sectors_dirty;
2444
2445                         reservation.v.nr_replicas = disk_res.nr_replicas;
2446                 }
2447
2448                 ret = bch2_btree_insert_at(c, &disk_res, &i_sectors_hook.hook,
2449                                           &inode->ei_journal_seq,
2450                                           BTREE_INSERT_ATOMIC|
2451                                           BTREE_INSERT_NOFAIL,
2452                                           BTREE_INSERT_ENTRY(&iter, &reservation.k_i));
2453                 bch2_disk_reservation_put(c, &disk_res);
2454 btree_iter_err:
2455                 if (ret < 0 && ret != -EINTR)
2456                         goto err_put_sectors_dirty;
2457
2458         }
2459         bch2_btree_iter_unlock(&iter);
2460
2461         ret = i_sectors_dirty_finish(c, &i_sectors_hook) ?: ret;
2462
2463         if (!(mode & FALLOC_FL_KEEP_SIZE) &&
2464             end > inode->v.i_size) {
2465                 i_size_write(&inode->v, end);
2466
2467                 mutex_lock(&inode->ei_update_lock);
2468                 ret = bch2_write_inode_size(c, inode, inode->v.i_size);
2469                 mutex_unlock(&inode->ei_update_lock);
2470         }
2471
2472         /* blech */
2473         if ((mode & FALLOC_FL_KEEP_SIZE) &&
2474             (mode & FALLOC_FL_ZERO_RANGE) &&
2475             inode->ei_inode.bi_size != inode->v.i_size) {
2476                 /* sync appends.. */
2477                 ret = filemap_write_and_wait_range(mapping,
2478                                         inode->ei_inode.bi_size, S64_MAX);
2479                 if (ret)
2480                         goto err;
2481
2482                 if (inode->ei_inode.bi_size != inode->v.i_size) {
2483                         mutex_lock(&inode->ei_update_lock);
2484                         ret = bch2_write_inode_size(c, inode, inode->v.i_size);
2485                         mutex_unlock(&inode->ei_update_lock);
2486                 }
2487         }
2488
2489         pagecache_block_put(&mapping->add_lock);
2490         inode_unlock(&inode->v);
2491
2492         return 0;
2493 err_put_sectors_dirty:
2494         ret = i_sectors_dirty_finish(c, &i_sectors_hook) ?: ret;
2495 err:
2496         bch2_btree_iter_unlock(&iter);
2497         pagecache_block_put(&mapping->add_lock);
2498         inode_unlock(&inode->v);
2499         return ret;
2500 }
2501
2502 long bch2_fallocate_dispatch(struct file *file, int mode,
2503                              loff_t offset, loff_t len)
2504 {
2505         struct bch_inode_info *inode = file_bch_inode(file);
2506
2507         if (!(mode & ~(FALLOC_FL_KEEP_SIZE|FALLOC_FL_ZERO_RANGE)))
2508                 return bch2_fallocate(inode, mode, offset, len);
2509
2510         if (mode == (FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE))
2511                 return bch2_fpunch(inode, offset, len);
2512
2513         if (mode == FALLOC_FL_COLLAPSE_RANGE)
2514                 return bch2_fcollapse(inode, offset, len);
2515
2516         return -EOPNOTSUPP;
2517 }
2518
2519 /* fseek: */
2520
2521 static bool page_is_data(struct page *page)
2522 {
2523         /* XXX: should only have to check PageDirty */
2524         return PagePrivate(page) &&
2525                 (page_state(page)->sectors ||
2526                  page_state(page)->dirty_sectors);
2527 }
2528
2529 static loff_t bch2_next_pagecache_data(struct inode *vinode,
2530                                        loff_t start_offset,
2531                                        loff_t end_offset)
2532 {
2533         struct address_space *mapping = vinode->i_mapping;
2534         struct page *page;
2535         pgoff_t index;
2536
2537         for (index = start_offset >> PAGE_SHIFT;
2538              index < end_offset >> PAGE_SHIFT;
2539              index++) {
2540                 if (find_get_pages(mapping, &index, 1, &page)) {
2541                         lock_page(page);
2542
2543                         if (page_is_data(page))
2544                                 end_offset =
2545                                         min(end_offset,
2546                                         max(start_offset,
2547                                             ((loff_t) index) << PAGE_SHIFT));
2548                         unlock_page(page);
2549                         put_page(page);
2550                 } else {
2551                         break;
2552                 }
2553         }
2554
2555         return end_offset;
2556 }
2557
2558 static loff_t bch2_seek_data(struct file *file, u64 offset)
2559 {
2560         struct bch_inode_info *inode = file_bch_inode(file);
2561         struct bch_fs *c = inode->v.i_sb->s_fs_info;
2562         struct btree_iter iter;
2563         struct bkey_s_c k;
2564         u64 isize, next_data = MAX_LFS_FILESIZE;
2565         int ret;
2566
2567         isize = i_size_read(&inode->v);
2568         if (offset >= isize)
2569                 return -ENXIO;
2570
2571         for_each_btree_key(&iter, c, BTREE_ID_EXTENTS,
2572                            POS(inode->v.i_ino, offset >> 9), 0, k) {
2573                 if (k.k->p.inode != inode->v.i_ino) {
2574                         break;
2575                 } else if (bkey_extent_is_data(k.k)) {
2576                         next_data = max(offset, bkey_start_offset(k.k) << 9);
2577                         break;
2578                 } else if (k.k->p.offset >> 9 > isize)
2579                         break;
2580         }
2581
2582         ret = bch2_btree_iter_unlock(&iter);
2583         if (ret)
2584                 return ret;
2585
2586         if (next_data > offset)
2587                 next_data = bch2_next_pagecache_data(&inode->v,
2588                                                      offset, next_data);
2589
2590         if (next_data > isize)
2591                 return -ENXIO;
2592
2593         return vfs_setpos(file, next_data, MAX_LFS_FILESIZE);
2594 }
2595
2596 static bool page_slot_is_data(struct address_space *mapping, pgoff_t index)
2597 {
2598         struct page *page;
2599         bool ret;
2600
2601         page = find_lock_entry(mapping, index);
2602         if (!page || radix_tree_exception(page))
2603                 return false;
2604
2605         ret = page_is_data(page);
2606         unlock_page(page);
2607
2608         return ret;
2609 }
2610
2611 static loff_t bch2_next_pagecache_hole(struct inode *vinode,
2612                                        loff_t start_offset,
2613                                        loff_t end_offset)
2614 {
2615         struct address_space *mapping = vinode->i_mapping;
2616         pgoff_t index;
2617
2618         for (index = start_offset >> PAGE_SHIFT;
2619              index < end_offset >> PAGE_SHIFT;
2620              index++)
2621                 if (!page_slot_is_data(mapping, index))
2622                         end_offset = max(start_offset,
2623                                          ((loff_t) index) << PAGE_SHIFT);
2624
2625         return end_offset;
2626 }
2627
2628 static loff_t bch2_seek_hole(struct file *file, u64 offset)
2629 {
2630         struct bch_inode_info *inode = file_bch_inode(file);
2631         struct bch_fs *c = inode->v.i_sb->s_fs_info;
2632         struct btree_iter iter;
2633         struct bkey_s_c k;
2634         u64 isize, next_hole = MAX_LFS_FILESIZE;
2635         int ret;
2636
2637         isize = i_size_read(&inode->v);
2638         if (offset >= isize)
2639                 return -ENXIO;
2640
2641         for_each_btree_key(&iter, c, BTREE_ID_EXTENTS,
2642                            POS(inode->v.i_ino, offset >> 9),
2643                            BTREE_ITER_SLOTS, k) {
2644                 if (k.k->p.inode != inode->v.i_ino) {
2645                         next_hole = bch2_next_pagecache_hole(&inode->v,
2646                                         offset, MAX_LFS_FILESIZE);
2647                         break;
2648                 } else if (!bkey_extent_is_data(k.k)) {
2649                         next_hole = bch2_next_pagecache_hole(&inode->v,
2650                                         max(offset, bkey_start_offset(k.k) << 9),
2651                                         k.k->p.offset << 9);
2652
2653                         if (next_hole < k.k->p.offset << 9)
2654                                 break;
2655                 } else {
2656                         offset = max(offset, bkey_start_offset(k.k) << 9);
2657                 }
2658         }
2659
2660         ret = bch2_btree_iter_unlock(&iter);
2661         if (ret)
2662                 return ret;
2663
2664         if (next_hole > isize)
2665                 next_hole = isize;
2666
2667         return vfs_setpos(file, next_hole, MAX_LFS_FILESIZE);
2668 }
2669
2670 loff_t bch2_llseek(struct file *file, loff_t offset, int whence)
2671 {
2672         switch (whence) {
2673         case SEEK_SET:
2674         case SEEK_CUR:
2675         case SEEK_END:
2676                 return generic_file_llseek(file, offset, whence);
2677         case SEEK_DATA:
2678                 return bch2_seek_data(file, offset);
2679         case SEEK_HOLE:
2680                 return bch2_seek_hole(file, offset);
2681         }
2682
2683         return -EINVAL;
2684 }
2685
2686 void bch2_fs_fsio_exit(struct bch_fs *c)
2687 {
2688         bioset_exit(&c->dio_write_bioset);
2689         bioset_exit(&c->dio_read_bioset);
2690         bioset_exit(&c->writepage_bioset);
2691 }
2692
2693 int bch2_fs_fsio_init(struct bch_fs *c)
2694 {
2695         if (bioset_init(&c->writepage_bioset,
2696                         4, offsetof(struct bch_writepage_io, op.op.wbio.bio),
2697                         BIOSET_NEED_BVECS) ||
2698             bioset_init(&c->dio_read_bioset,
2699                         4, offsetof(struct dio_read, rbio.bio),
2700                         BIOSET_NEED_BVECS) ||
2701             bioset_init(&c->dio_write_bioset,
2702                         4, offsetof(struct dio_write, iop.op.wbio.bio),
2703                         BIOSET_NEED_BVECS))
2704                 return -ENOMEM;
2705
2706         return 0;
2707 }
2708
2709 #endif /* NO_BCACHEFS_FS */