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