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