]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fs-io.c
Update bcachefs sources to e7f6215768 bcachefs: Fix snapshot_skiplist_good()
[bcachefs-tools-debian] / libbcachefs / fs-io.c
1 // SPDX-License-Identifier: GPL-2.0
2 #ifndef NO_BCACHEFS_FS
3
4 #include "bcachefs.h"
5 #include "alloc_foreground.h"
6 #include "btree_update.h"
7 #include "buckets.h"
8 #include "clock.h"
9 #include "error.h"
10 #include "extents.h"
11 #include "extent_update.h"
12 #include "fs.h"
13 #include "fs-io.h"
14 #include "fs-io-buffered.h"
15 #include "fs-io-pagecache.h"
16 #include "fsck.h"
17 #include "inode.h"
18 #include "journal.h"
19 #include "io.h"
20 #include "keylist.h"
21 #include "quota.h"
22 #include "reflink.h"
23 #include "trace.h"
24
25 #include <linux/aio.h>
26 #include <linux/backing-dev.h>
27 #include <linux/falloc.h>
28 #include <linux/migrate.h>
29 #include <linux/mmu_context.h>
30 #include <linux/pagevec.h>
31 #include <linux/rmap.h>
32 #include <linux/sched/signal.h>
33 #include <linux/task_io_accounting_ops.h>
34 #include <linux/uio.h>
35
36 #include <trace/events/writeback.h>
37
38 struct nocow_flush {
39         struct closure  *cl;
40         struct bch_dev  *ca;
41         struct bio      bio;
42 };
43
44 static void nocow_flush_endio(struct bio *_bio)
45 {
46
47         struct nocow_flush *bio = container_of(_bio, struct nocow_flush, bio);
48
49         closure_put(bio->cl);
50         percpu_ref_put(&bio->ca->io_ref);
51         bio_put(&bio->bio);
52 }
53
54 void bch2_inode_flush_nocow_writes_async(struct bch_fs *c,
55                                          struct bch_inode_info *inode,
56                                          struct closure *cl)
57 {
58         struct nocow_flush *bio;
59         struct bch_dev *ca;
60         struct bch_devs_mask devs;
61         unsigned dev;
62
63         dev = find_first_bit(inode->ei_devs_need_flush.d, BCH_SB_MEMBERS_MAX);
64         if (dev == BCH_SB_MEMBERS_MAX)
65                 return;
66
67         devs = inode->ei_devs_need_flush;
68         memset(&inode->ei_devs_need_flush, 0, sizeof(inode->ei_devs_need_flush));
69
70         for_each_set_bit(dev, devs.d, BCH_SB_MEMBERS_MAX) {
71                 rcu_read_lock();
72                 ca = rcu_dereference(c->devs[dev]);
73                 if (ca && !percpu_ref_tryget(&ca->io_ref))
74                         ca = NULL;
75                 rcu_read_unlock();
76
77                 if (!ca)
78                         continue;
79
80                 bio = container_of(bio_alloc_bioset(ca->disk_sb.bdev, 0,
81                                                     REQ_OP_FLUSH,
82                                                     GFP_KERNEL,
83                                                     &c->nocow_flush_bioset),
84                                    struct nocow_flush, bio);
85                 bio->cl                 = cl;
86                 bio->ca                 = ca;
87                 bio->bio.bi_end_io      = nocow_flush_endio;
88                 closure_bio_submit(&bio->bio, cl);
89         }
90 }
91
92 static int bch2_inode_flush_nocow_writes(struct bch_fs *c,
93                                          struct bch_inode_info *inode)
94 {
95         struct closure cl;
96
97         closure_init_stack(&cl);
98         bch2_inode_flush_nocow_writes_async(c, inode, &cl);
99         closure_sync(&cl);
100
101         return 0;
102 }
103
104 /* i_size updates: */
105
106 struct inode_new_size {
107         loff_t          new_size;
108         u64             now;
109         unsigned        fields;
110 };
111
112 static int inode_set_size(struct btree_trans *trans,
113                           struct bch_inode_info *inode,
114                           struct bch_inode_unpacked *bi,
115                           void *p)
116 {
117         struct inode_new_size *s = p;
118
119         bi->bi_size = s->new_size;
120         if (s->fields & ATTR_ATIME)
121                 bi->bi_atime = s->now;
122         if (s->fields & ATTR_MTIME)
123                 bi->bi_mtime = s->now;
124         if (s->fields & ATTR_CTIME)
125                 bi->bi_ctime = s->now;
126
127         return 0;
128 }
129
130 int __must_check bch2_write_inode_size(struct bch_fs *c,
131                                        struct bch_inode_info *inode,
132                                        loff_t new_size, unsigned fields)
133 {
134         struct inode_new_size s = {
135                 .new_size       = new_size,
136                 .now            = bch2_current_time(c),
137                 .fields         = fields,
138         };
139
140         return bch2_write_inode(c, inode, inode_set_size, &s, fields);
141 }
142
143 void __bch2_i_sectors_acct(struct bch_fs *c, struct bch_inode_info *inode,
144                            struct quota_res *quota_res, s64 sectors)
145 {
146         bch2_fs_inconsistent_on((s64) inode->v.i_blocks + sectors < 0, c,
147                                 "inode %lu i_blocks underflow: %llu + %lli < 0 (ondisk %lli)",
148                                 inode->v.i_ino, (u64) inode->v.i_blocks, sectors,
149                                 inode->ei_inode.bi_sectors);
150         inode->v.i_blocks += sectors;
151
152 #ifdef CONFIG_BCACHEFS_QUOTA
153         if (quota_res &&
154             !test_bit(EI_INODE_SNAPSHOT, &inode->ei_flags) &&
155             sectors > 0) {
156                 BUG_ON(sectors > quota_res->sectors);
157                 BUG_ON(sectors > inode->ei_quota_reserved);
158
159                 quota_res->sectors -= sectors;
160                 inode->ei_quota_reserved -= sectors;
161         } else {
162                 bch2_quota_acct(c, inode->ei_qid, Q_SPC, sectors, KEY_TYPE_QUOTA_WARN);
163         }
164 #endif
165 }
166
167
168 /* fsync: */
169
170 /*
171  * inode->ei_inode.bi_journal_seq won't be up to date since it's set in an
172  * insert trigger: look up the btree inode instead
173  */
174 static int bch2_flush_inode(struct bch_fs *c,
175                             struct bch_inode_info *inode)
176 {
177         struct bch_inode_unpacked u;
178         int ret;
179
180         if (c->opts.journal_flush_disabled)
181                 return 0;
182
183         ret = bch2_inode_find_by_inum(c, inode_inum(inode), &u);
184         if (ret)
185                 return ret;
186
187         return bch2_journal_flush_seq(&c->journal, u.bi_journal_seq) ?:
188                 bch2_inode_flush_nocow_writes(c, inode);
189 }
190
191 int bch2_fsync(struct file *file, loff_t start, loff_t end, int datasync)
192 {
193         struct bch_inode_info *inode = file_bch_inode(file);
194         struct bch_fs *c = inode->v.i_sb->s_fs_info;
195         int ret, ret2, ret3;
196
197         ret = file_write_and_wait_range(file, start, end);
198         ret2 = sync_inode_metadata(&inode->v, 1);
199         ret3 = bch2_flush_inode(c, inode);
200
201         return bch2_err_class(ret ?: ret2 ?: ret3);
202 }
203
204 /* truncate: */
205
206 static inline int range_has_data(struct bch_fs *c, u32 subvol,
207                                  struct bpos start,
208                                  struct bpos end)
209 {
210         struct btree_trans trans;
211         struct btree_iter iter;
212         struct bkey_s_c k;
213         int ret = 0;
214
215         bch2_trans_init(&trans, c, 0, 0);
216 retry:
217         bch2_trans_begin(&trans);
218
219         ret = bch2_subvolume_get_snapshot(&trans, subvol, &start.snapshot);
220         if (ret)
221                 goto err;
222
223         for_each_btree_key_upto_norestart(&trans, iter, BTREE_ID_extents, start, end, 0, k, ret)
224                 if (bkey_extent_is_data(k.k) && !bkey_extent_is_unwritten(k)) {
225                         ret = 1;
226                         break;
227                 }
228         start = iter.pos;
229         bch2_trans_iter_exit(&trans, &iter);
230 err:
231         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
232                 goto retry;
233
234         bch2_trans_exit(&trans);
235         return ret;
236 }
237
238 static int __bch2_truncate_folio(struct bch_inode_info *inode,
239                                  pgoff_t index, loff_t start, loff_t end)
240 {
241         struct bch_fs *c = inode->v.i_sb->s_fs_info;
242         struct address_space *mapping = inode->v.i_mapping;
243         struct bch_folio *s;
244         unsigned start_offset = start & (PAGE_SIZE - 1);
245         unsigned end_offset = ((end - 1) & (PAGE_SIZE - 1)) + 1;
246         unsigned i;
247         struct folio *folio;
248         s64 i_sectors_delta = 0;
249         int ret = 0;
250         u64 end_pos;
251
252         folio = filemap_lock_folio(mapping, index);
253         if (IS_ERR_OR_NULL(folio)) {
254                 /*
255                  * XXX: we're doing two index lookups when we end up reading the
256                  * folio
257                  */
258                 ret = range_has_data(c, inode->ei_subvol,
259                                 POS(inode->v.i_ino, (index << PAGE_SECTORS_SHIFT)),
260                                 POS(inode->v.i_ino, (index << PAGE_SECTORS_SHIFT) + PAGE_SECTORS));
261                 if (ret <= 0)
262                         return ret;
263
264                 folio = __filemap_get_folio(mapping, index,
265                                             FGP_LOCK|FGP_CREAT, GFP_KERNEL);
266                 if (IS_ERR_OR_NULL(folio)) {
267                         ret = -ENOMEM;
268                         goto out;
269                 }
270         }
271
272         BUG_ON(start    >= folio_end_pos(folio));
273         BUG_ON(end      <= folio_pos(folio));
274
275         start_offset    = max(start, folio_pos(folio)) - folio_pos(folio);
276         end_offset      = min_t(u64, end, folio_end_pos(folio)) - folio_pos(folio);
277
278         /* Folio boundary? Nothing to do */
279         if (start_offset == 0 &&
280             end_offset == folio_size(folio)) {
281                 ret = 0;
282                 goto unlock;
283         }
284
285         s = bch2_folio_create(folio, 0);
286         if (!s) {
287                 ret = -ENOMEM;
288                 goto unlock;
289         }
290
291         if (!folio_test_uptodate(folio)) {
292                 ret = bch2_read_single_folio(folio, mapping);
293                 if (ret)
294                         goto unlock;
295         }
296
297         ret = bch2_folio_set(c, inode_inum(inode), &folio, 1);
298         if (ret)
299                 goto unlock;
300
301         for (i = round_up(start_offset, block_bytes(c)) >> 9;
302              i < round_down(end_offset, block_bytes(c)) >> 9;
303              i++) {
304                 s->s[i].nr_replicas     = 0;
305
306                 i_sectors_delta -= s->s[i].state == SECTOR_dirty;
307                 bch2_folio_sector_set(folio, s, i, SECTOR_unallocated);
308         }
309
310         bch2_i_sectors_acct(c, inode, NULL, i_sectors_delta);
311
312         /*
313          * Caller needs to know whether this folio will be written out by
314          * writeback - doing an i_size update if necessary - or whether it will
315          * be responsible for the i_size update.
316          *
317          * Note that we shouldn't ever see a folio beyond EOF, but check and
318          * warn if so. This has been observed by failure to clean up folios
319          * after a short write and there's still a chance reclaim will fix
320          * things up.
321          */
322         WARN_ON_ONCE(folio_pos(folio) >= inode->v.i_size);
323         end_pos = folio_end_pos(folio);
324         if (inode->v.i_size > folio_pos(folio))
325                 end_pos = min_t(u64, inode->v.i_size, end_pos);
326         ret = s->s[folio_pos_to_s(folio, end_pos - 1)].state >= SECTOR_dirty;
327
328         folio_zero_segment(folio, start_offset, end_offset);
329
330         /*
331          * Bit of a hack - we don't want truncate to fail due to -ENOSPC.
332          *
333          * XXX: because we aren't currently tracking whether the folio has actual
334          * data in it (vs. just 0s, or only partially written) this wrong. ick.
335          */
336         BUG_ON(bch2_get_folio_disk_reservation(c, inode, folio, false));
337
338         /*
339          * This removes any writeable userspace mappings; we need to force
340          * .page_mkwrite to be called again before any mmapped writes, to
341          * redirty the full page:
342          */
343         folio_mkclean(folio);
344         filemap_dirty_folio(mapping, folio);
345 unlock:
346         folio_unlock(folio);
347         folio_put(folio);
348 out:
349         return ret;
350 }
351
352 static int bch2_truncate_folio(struct bch_inode_info *inode, loff_t from)
353 {
354         return __bch2_truncate_folio(inode, from >> PAGE_SHIFT,
355                                      from, ANYSINT_MAX(loff_t));
356 }
357
358 static int bch2_truncate_folios(struct bch_inode_info *inode,
359                                 loff_t start, loff_t end)
360 {
361         int ret = __bch2_truncate_folio(inode, start >> PAGE_SHIFT,
362                                         start, end);
363
364         if (ret >= 0 &&
365             start >> PAGE_SHIFT != end >> PAGE_SHIFT)
366                 ret = __bch2_truncate_folio(inode,
367                                         (end - 1) >> PAGE_SHIFT,
368                                         start, end);
369         return ret;
370 }
371
372 static int bch2_extend(struct mnt_idmap *idmap,
373                        struct bch_inode_info *inode,
374                        struct bch_inode_unpacked *inode_u,
375                        struct iattr *iattr)
376 {
377         struct address_space *mapping = inode->v.i_mapping;
378         int ret;
379
380         /*
381          * sync appends:
382          *
383          * this has to be done _before_ extending i_size:
384          */
385         ret = filemap_write_and_wait_range(mapping, inode_u->bi_size, S64_MAX);
386         if (ret)
387                 return ret;
388
389         truncate_setsize(&inode->v, iattr->ia_size);
390
391         return bch2_setattr_nonsize(idmap, inode, iattr);
392 }
393
394 static int bch2_truncate_finish_fn(struct btree_trans *trans,
395                                    struct bch_inode_info *inode,
396                                    struct bch_inode_unpacked *bi,
397                                    void *p)
398 {
399         bi->bi_flags &= ~BCH_INODE_I_SIZE_DIRTY;
400         return 0;
401 }
402
403 static int bch2_truncate_start_fn(struct btree_trans *trans,
404                                   struct bch_inode_info *inode,
405                                   struct bch_inode_unpacked *bi, void *p)
406 {
407         u64 *new_i_size = p;
408
409         bi->bi_flags |= BCH_INODE_I_SIZE_DIRTY;
410         bi->bi_size = *new_i_size;
411         return 0;
412 }
413
414 int bch2_truncate(struct mnt_idmap *idmap,
415                   struct bch_inode_info *inode, struct iattr *iattr)
416 {
417         struct bch_fs *c = inode->v.i_sb->s_fs_info;
418         struct address_space *mapping = inode->v.i_mapping;
419         struct bch_inode_unpacked inode_u;
420         u64 new_i_size = iattr->ia_size;
421         s64 i_sectors_delta = 0;
422         int ret = 0;
423
424         /*
425          * If the truncate call with change the size of the file, the
426          * cmtimes should be updated. If the size will not change, we
427          * do not need to update the cmtimes.
428          */
429         if (iattr->ia_size != inode->v.i_size) {
430                 if (!(iattr->ia_valid & ATTR_MTIME))
431                         ktime_get_coarse_real_ts64(&iattr->ia_mtime);
432                 if (!(iattr->ia_valid & ATTR_CTIME))
433                         ktime_get_coarse_real_ts64(&iattr->ia_ctime);
434                 iattr->ia_valid |= ATTR_MTIME|ATTR_CTIME;
435         }
436
437         inode_dio_wait(&inode->v);
438         bch2_pagecache_block_get(inode);
439
440         ret = bch2_inode_find_by_inum(c, inode_inum(inode), &inode_u);
441         if (ret)
442                 goto err;
443
444         /*
445          * check this before next assertion; on filesystem error our normal
446          * invariants are a bit broken (truncate has to truncate the page cache
447          * before the inode).
448          */
449         ret = bch2_journal_error(&c->journal);
450         if (ret)
451                 goto err;
452
453         WARN_ONCE(!test_bit(EI_INODE_ERROR, &inode->ei_flags) &&
454                   inode->v.i_size < inode_u.bi_size,
455                   "truncate spotted in mem i_size < btree i_size: %llu < %llu\n",
456                   (u64) inode->v.i_size, inode_u.bi_size);
457
458         if (iattr->ia_size > inode->v.i_size) {
459                 ret = bch2_extend(idmap, inode, &inode_u, iattr);
460                 goto err;
461         }
462
463         iattr->ia_valid &= ~ATTR_SIZE;
464
465         ret = bch2_truncate_folio(inode, iattr->ia_size);
466         if (unlikely(ret < 0))
467                 goto err;
468
469         /*
470          * When extending, we're going to write the new i_size to disk
471          * immediately so we need to flush anything above the current on disk
472          * i_size first:
473          *
474          * Also, when extending we need to flush the page that i_size currently
475          * straddles - if it's mapped to userspace, we need to ensure that
476          * userspace has to redirty it and call .mkwrite -> set_page_dirty
477          * again to allocate the part of the page that was extended.
478          */
479         if (iattr->ia_size > inode_u.bi_size)
480                 ret = filemap_write_and_wait_range(mapping,
481                                 inode_u.bi_size,
482                                 iattr->ia_size - 1);
483         else if (iattr->ia_size & (PAGE_SIZE - 1))
484                 ret = filemap_write_and_wait_range(mapping,
485                                 round_down(iattr->ia_size, PAGE_SIZE),
486                                 iattr->ia_size - 1);
487         if (ret)
488                 goto err;
489
490         mutex_lock(&inode->ei_update_lock);
491         ret = bch2_write_inode(c, inode, bch2_truncate_start_fn,
492                                &new_i_size, 0);
493         mutex_unlock(&inode->ei_update_lock);
494
495         if (unlikely(ret))
496                 goto err;
497
498         truncate_setsize(&inode->v, iattr->ia_size);
499
500         ret = bch2_fpunch(c, inode_inum(inode),
501                         round_up(iattr->ia_size, block_bytes(c)) >> 9,
502                         U64_MAX, &i_sectors_delta);
503         bch2_i_sectors_acct(c, inode, NULL, i_sectors_delta);
504
505         bch2_fs_inconsistent_on(!inode->v.i_size && inode->v.i_blocks &&
506                                 !bch2_journal_error(&c->journal), c,
507                                 "inode %lu truncated to 0 but i_blocks %llu (ondisk %lli)",
508                                 inode->v.i_ino, (u64) inode->v.i_blocks,
509                                 inode->ei_inode.bi_sectors);
510         if (unlikely(ret))
511                 goto err;
512
513         mutex_lock(&inode->ei_update_lock);
514         ret = bch2_write_inode(c, inode, bch2_truncate_finish_fn, NULL, 0);
515         mutex_unlock(&inode->ei_update_lock);
516
517         ret = bch2_setattr_nonsize(idmap, inode, iattr);
518 err:
519         bch2_pagecache_block_put(inode);
520         return bch2_err_class(ret);
521 }
522
523 /* fallocate: */
524
525 static int inode_update_times_fn(struct btree_trans *trans,
526                                  struct bch_inode_info *inode,
527                                  struct bch_inode_unpacked *bi, void *p)
528 {
529         struct bch_fs *c = inode->v.i_sb->s_fs_info;
530
531         bi->bi_mtime = bi->bi_ctime = bch2_current_time(c);
532         return 0;
533 }
534
535 static long bchfs_fpunch(struct bch_inode_info *inode, loff_t offset, loff_t len)
536 {
537         struct bch_fs *c = inode->v.i_sb->s_fs_info;
538         u64 end         = offset + len;
539         u64 block_start = round_up(offset, block_bytes(c));
540         u64 block_end   = round_down(end, block_bytes(c));
541         bool truncated_last_page;
542         int ret = 0;
543
544         ret = bch2_truncate_folios(inode, offset, end);
545         if (unlikely(ret < 0))
546                 goto err;
547
548         truncated_last_page = ret;
549
550         truncate_pagecache_range(&inode->v, offset, end - 1);
551
552         if (block_start < block_end) {
553                 s64 i_sectors_delta = 0;
554
555                 ret = bch2_fpunch(c, inode_inum(inode),
556                                   block_start >> 9, block_end >> 9,
557                                   &i_sectors_delta);
558                 bch2_i_sectors_acct(c, inode, NULL, i_sectors_delta);
559         }
560
561         mutex_lock(&inode->ei_update_lock);
562         if (end >= inode->v.i_size && !truncated_last_page) {
563                 ret = bch2_write_inode_size(c, inode, inode->v.i_size,
564                                             ATTR_MTIME|ATTR_CTIME);
565         } else {
566                 ret = bch2_write_inode(c, inode, inode_update_times_fn, NULL,
567                                        ATTR_MTIME|ATTR_CTIME);
568         }
569         mutex_unlock(&inode->ei_update_lock);
570 err:
571         return ret;
572 }
573
574 static long bchfs_fcollapse_finsert(struct bch_inode_info *inode,
575                                    loff_t offset, loff_t len,
576                                    bool insert)
577 {
578         struct bch_fs *c = inode->v.i_sb->s_fs_info;
579         struct address_space *mapping = inode->v.i_mapping;
580         struct bkey_buf copy;
581         struct btree_trans trans;
582         struct btree_iter src, dst, del;
583         loff_t shift, new_size;
584         u64 src_start;
585         int ret = 0;
586
587         if ((offset | len) & (block_bytes(c) - 1))
588                 return -EINVAL;
589
590         if (insert) {
591                 if (inode->v.i_sb->s_maxbytes - inode->v.i_size < len)
592                         return -EFBIG;
593
594                 if (offset >= inode->v.i_size)
595                         return -EINVAL;
596
597                 src_start       = U64_MAX;
598                 shift           = len;
599         } else {
600                 if (offset + len >= inode->v.i_size)
601                         return -EINVAL;
602
603                 src_start       = offset + len;
604                 shift           = -len;
605         }
606
607         new_size = inode->v.i_size + shift;
608
609         ret = bch2_write_invalidate_inode_pages_range(mapping, offset, LLONG_MAX);
610         if (ret)
611                 return ret;
612
613         if (insert) {
614                 i_size_write(&inode->v, new_size);
615                 mutex_lock(&inode->ei_update_lock);
616                 ret = bch2_write_inode_size(c, inode, new_size,
617                                             ATTR_MTIME|ATTR_CTIME);
618                 mutex_unlock(&inode->ei_update_lock);
619         } else {
620                 s64 i_sectors_delta = 0;
621
622                 ret = bch2_fpunch(c, inode_inum(inode),
623                                   offset >> 9, (offset + len) >> 9,
624                                   &i_sectors_delta);
625                 bch2_i_sectors_acct(c, inode, NULL, i_sectors_delta);
626
627                 if (ret)
628                         return ret;
629         }
630
631         bch2_bkey_buf_init(&copy);
632         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
633         bch2_trans_iter_init(&trans, &src, BTREE_ID_extents,
634                         POS(inode->v.i_ino, src_start >> 9),
635                         BTREE_ITER_INTENT);
636         bch2_trans_copy_iter(&dst, &src);
637         bch2_trans_copy_iter(&del, &src);
638
639         while (ret == 0 ||
640                bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
641                 struct disk_reservation disk_res =
642                         bch2_disk_reservation_init(c, 0);
643                 struct bkey_i delete;
644                 struct bkey_s_c k;
645                 struct bpos next_pos;
646                 struct bpos move_pos = POS(inode->v.i_ino, offset >> 9);
647                 struct bpos atomic_end;
648                 unsigned trigger_flags = 0;
649                 u32 snapshot;
650
651                 bch2_trans_begin(&trans);
652
653                 ret = bch2_subvolume_get_snapshot(&trans,
654                                         inode->ei_subvol, &snapshot);
655                 if (ret)
656                         continue;
657
658                 bch2_btree_iter_set_snapshot(&src, snapshot);
659                 bch2_btree_iter_set_snapshot(&dst, snapshot);
660                 bch2_btree_iter_set_snapshot(&del, snapshot);
661
662                 bch2_trans_begin(&trans);
663
664                 k = insert
665                         ? bch2_btree_iter_peek_prev(&src)
666                         : bch2_btree_iter_peek_upto(&src, POS(inode->v.i_ino, U64_MAX));
667                 if ((ret = bkey_err(k)))
668                         continue;
669
670                 if (!k.k || k.k->p.inode != inode->v.i_ino)
671                         break;
672
673                 if (insert &&
674                     bkey_le(k.k->p, POS(inode->v.i_ino, offset >> 9)))
675                         break;
676 reassemble:
677                 bch2_bkey_buf_reassemble(&copy, c, k);
678
679                 if (insert &&
680                     bkey_lt(bkey_start_pos(k.k), move_pos))
681                         bch2_cut_front(move_pos, copy.k);
682
683                 copy.k->k.p.offset += shift >> 9;
684                 bch2_btree_iter_set_pos(&dst, bkey_start_pos(&copy.k->k));
685
686                 ret = bch2_extent_atomic_end(&trans, &dst, copy.k, &atomic_end);
687                 if (ret)
688                         continue;
689
690                 if (!bkey_eq(atomic_end, copy.k->k.p)) {
691                         if (insert) {
692                                 move_pos = atomic_end;
693                                 move_pos.offset -= shift >> 9;
694                                 goto reassemble;
695                         } else {
696                                 bch2_cut_back(atomic_end, copy.k);
697                         }
698                 }
699
700                 bkey_init(&delete.k);
701                 delete.k.p = copy.k->k.p;
702                 delete.k.size = copy.k->k.size;
703                 delete.k.p.offset -= shift >> 9;
704                 bch2_btree_iter_set_pos(&del, bkey_start_pos(&delete.k));
705
706                 next_pos = insert ? bkey_start_pos(&delete.k) : delete.k.p;
707
708                 if (copy.k->k.size != k.k->size) {
709                         /* We might end up splitting compressed extents: */
710                         unsigned nr_ptrs =
711                                 bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(copy.k));
712
713                         ret = bch2_disk_reservation_get(c, &disk_res,
714                                         copy.k->k.size, nr_ptrs,
715                                         BCH_DISK_RESERVATION_NOFAIL);
716                         BUG_ON(ret);
717                 }
718
719                 ret =   bch2_btree_iter_traverse(&del) ?:
720                         bch2_trans_update(&trans, &del, &delete, trigger_flags) ?:
721                         bch2_trans_update(&trans, &dst, copy.k, trigger_flags) ?:
722                         bch2_trans_commit(&trans, &disk_res, NULL,
723                                           BTREE_INSERT_NOFAIL);
724                 bch2_disk_reservation_put(c, &disk_res);
725
726                 if (!ret)
727                         bch2_btree_iter_set_pos(&src, next_pos);
728         }
729         bch2_trans_iter_exit(&trans, &del);
730         bch2_trans_iter_exit(&trans, &dst);
731         bch2_trans_iter_exit(&trans, &src);
732         bch2_trans_exit(&trans);
733         bch2_bkey_buf_exit(&copy, c);
734
735         if (ret)
736                 return ret;
737
738         mutex_lock(&inode->ei_update_lock);
739         if (!insert) {
740                 i_size_write(&inode->v, new_size);
741                 ret = bch2_write_inode_size(c, inode, new_size,
742                                             ATTR_MTIME|ATTR_CTIME);
743         } else {
744                 /* We need an inode update to update bi_journal_seq for fsync: */
745                 ret = bch2_write_inode(c, inode, inode_update_times_fn, NULL,
746                                        ATTR_MTIME|ATTR_CTIME);
747         }
748         mutex_unlock(&inode->ei_update_lock);
749         return ret;
750 }
751
752 static int __bchfs_fallocate(struct bch_inode_info *inode, int mode,
753                              u64 start_sector, u64 end_sector)
754 {
755         struct bch_fs *c = inode->v.i_sb->s_fs_info;
756         struct btree_trans trans;
757         struct btree_iter iter;
758         struct bpos end_pos = POS(inode->v.i_ino, end_sector);
759         struct bch_io_opts opts;
760         int ret = 0;
761
762         bch2_inode_opts_get(&opts, c, &inode->ei_inode);
763         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 512);
764
765         bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
766                         POS(inode->v.i_ino, start_sector),
767                         BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
768
769         while (!ret && bkey_lt(iter.pos, end_pos)) {
770                 s64 i_sectors_delta = 0;
771                 struct quota_res quota_res = { 0 };
772                 struct bkey_s_c k;
773                 unsigned sectors;
774                 bool is_allocation;
775                 u64 hole_start, hole_end;
776                 u32 snapshot;
777
778                 bch2_trans_begin(&trans);
779
780                 ret = bch2_subvolume_get_snapshot(&trans,
781                                         inode->ei_subvol, &snapshot);
782                 if (ret)
783                         goto bkey_err;
784
785                 bch2_btree_iter_set_snapshot(&iter, snapshot);
786
787                 k = bch2_btree_iter_peek_slot(&iter);
788                 if ((ret = bkey_err(k)))
789                         goto bkey_err;
790
791                 hole_start      = iter.pos.offset;
792                 hole_end        = bpos_min(k.k->p, end_pos).offset;
793                 is_allocation   = bkey_extent_is_allocation(k.k);
794
795                 /* already reserved */
796                 if (bkey_extent_is_reservation(k) &&
797                     bch2_bkey_nr_ptrs_fully_allocated(k) >= opts.data_replicas) {
798                         bch2_btree_iter_advance(&iter);
799                         continue;
800                 }
801
802                 if (bkey_extent_is_data(k.k) &&
803                     !(mode & FALLOC_FL_ZERO_RANGE)) {
804                         bch2_btree_iter_advance(&iter);
805                         continue;
806                 }
807
808                 if (!(mode & FALLOC_FL_ZERO_RANGE)) {
809                         /*
810                          * Lock ordering - can't be holding btree locks while
811                          * blocking on a folio lock:
812                          */
813                         if (bch2_clamp_data_hole(&inode->v,
814                                                  &hole_start,
815                                                  &hole_end,
816                                                  opts.data_replicas, true))
817                                 ret = drop_locks_do(&trans,
818                                         (bch2_clamp_data_hole(&inode->v,
819                                                               &hole_start,
820                                                               &hole_end,
821                                                               opts.data_replicas, false), 0));
822                         bch2_btree_iter_set_pos(&iter, POS(iter.pos.inode, hole_start));
823
824                         if (ret)
825                                 goto bkey_err;
826
827                         if (hole_start == hole_end)
828                                 continue;
829                 }
830
831                 sectors = hole_end - hole_start;
832
833                 if (!is_allocation) {
834                         ret = bch2_quota_reservation_add(c, inode,
835                                         &quota_res, sectors, true);
836                         if (unlikely(ret))
837                                 goto bkey_err;
838                 }
839
840                 ret = bch2_extent_fallocate(&trans, inode_inum(inode), &iter,
841                                             sectors, opts, &i_sectors_delta,
842                                             writepoint_hashed((unsigned long) current));
843                 if (ret)
844                         goto bkey_err;
845
846                 bch2_i_sectors_acct(c, inode, &quota_res, i_sectors_delta);
847
848                 drop_locks_do(&trans,
849                         (bch2_mark_pagecache_reserved(inode, hole_start, iter.pos.offset), 0));
850 bkey_err:
851                 bch2_quota_reservation_put(c, inode, &quota_res);
852                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
853                         ret = 0;
854         }
855
856         if (bch2_err_matches(ret, ENOSPC) && (mode & FALLOC_FL_ZERO_RANGE)) {
857                 struct quota_res quota_res = { 0 };
858                 s64 i_sectors_delta = 0;
859
860                 bch2_fpunch_at(&trans, &iter, inode_inum(inode),
861                                end_sector, &i_sectors_delta);
862                 bch2_i_sectors_acct(c, inode, &quota_res, i_sectors_delta);
863                 bch2_quota_reservation_put(c, inode, &quota_res);
864         }
865
866         bch2_trans_iter_exit(&trans, &iter);
867         bch2_trans_exit(&trans);
868         return ret;
869 }
870
871 static long bchfs_fallocate(struct bch_inode_info *inode, int mode,
872                             loff_t offset, loff_t len)
873 {
874         struct bch_fs *c = inode->v.i_sb->s_fs_info;
875         u64 end         = offset + len;
876         u64 block_start = round_down(offset,    block_bytes(c));
877         u64 block_end   = round_up(end,         block_bytes(c));
878         bool truncated_last_page = false;
879         int ret, ret2 = 0;
880
881         if (!(mode & FALLOC_FL_KEEP_SIZE) && end > inode->v.i_size) {
882                 ret = inode_newsize_ok(&inode->v, end);
883                 if (ret)
884                         return ret;
885         }
886
887         if (mode & FALLOC_FL_ZERO_RANGE) {
888                 ret = bch2_truncate_folios(inode, offset, end);
889                 if (unlikely(ret < 0))
890                         return ret;
891
892                 truncated_last_page = ret;
893
894                 truncate_pagecache_range(&inode->v, offset, end - 1);
895
896                 block_start     = round_up(offset,      block_bytes(c));
897                 block_end       = round_down(end,       block_bytes(c));
898         }
899
900         ret = __bchfs_fallocate(inode, mode, block_start >> 9, block_end >> 9);
901
902         /*
903          * On -ENOSPC in ZERO_RANGE mode, we still want to do the inode update,
904          * so that the VFS cache i_size is consistent with the btree i_size:
905          */
906         if (ret &&
907             !(bch2_err_matches(ret, ENOSPC) && (mode & FALLOC_FL_ZERO_RANGE)))
908                 return ret;
909
910         if (mode & FALLOC_FL_KEEP_SIZE && end > inode->v.i_size)
911                 end = inode->v.i_size;
912
913         if (end >= inode->v.i_size &&
914             (((mode & FALLOC_FL_ZERO_RANGE) && !truncated_last_page) ||
915              !(mode & FALLOC_FL_KEEP_SIZE))) {
916                 spin_lock(&inode->v.i_lock);
917                 i_size_write(&inode->v, end);
918                 spin_unlock(&inode->v.i_lock);
919
920                 mutex_lock(&inode->ei_update_lock);
921                 ret2 = bch2_write_inode_size(c, inode, end, 0);
922                 mutex_unlock(&inode->ei_update_lock);
923         }
924
925         return ret ?: ret2;
926 }
927
928 long bch2_fallocate_dispatch(struct file *file, int mode,
929                              loff_t offset, loff_t len)
930 {
931         struct bch_inode_info *inode = file_bch_inode(file);
932         struct bch_fs *c = inode->v.i_sb->s_fs_info;
933         long ret;
934
935         if (!bch2_write_ref_tryget(c, BCH_WRITE_REF_fallocate))
936                 return -EROFS;
937
938         inode_lock(&inode->v);
939         inode_dio_wait(&inode->v);
940         bch2_pagecache_block_get(inode);
941
942         ret = file_modified(file);
943         if (ret)
944                 goto err;
945
946         if (!(mode & ~(FALLOC_FL_KEEP_SIZE|FALLOC_FL_ZERO_RANGE)))
947                 ret = bchfs_fallocate(inode, mode, offset, len);
948         else if (mode == (FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE))
949                 ret = bchfs_fpunch(inode, offset, len);
950         else if (mode == FALLOC_FL_INSERT_RANGE)
951                 ret = bchfs_fcollapse_finsert(inode, offset, len, true);
952         else if (mode == FALLOC_FL_COLLAPSE_RANGE)
953                 ret = bchfs_fcollapse_finsert(inode, offset, len, false);
954         else
955                 ret = -EOPNOTSUPP;
956 err:
957         bch2_pagecache_block_put(inode);
958         inode_unlock(&inode->v);
959         bch2_write_ref_put(c, BCH_WRITE_REF_fallocate);
960
961         return bch2_err_class(ret);
962 }
963
964 /*
965  * Take a quota reservation for unallocated blocks in a given file range
966  * Does not check pagecache
967  */
968 static int quota_reserve_range(struct bch_inode_info *inode,
969                                struct quota_res *res,
970                                u64 start, u64 end)
971 {
972         struct bch_fs *c = inode->v.i_sb->s_fs_info;
973         struct btree_trans trans;
974         struct btree_iter iter;
975         struct bkey_s_c k;
976         u32 snapshot;
977         u64 sectors = end - start;
978         u64 pos = start;
979         int ret;
980
981         bch2_trans_init(&trans, c, 0, 0);
982 retry:
983         bch2_trans_begin(&trans);
984
985         ret = bch2_subvolume_get_snapshot(&trans, inode->ei_subvol, &snapshot);
986         if (ret)
987                 goto err;
988
989         bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
990                              SPOS(inode->v.i_ino, pos, snapshot), 0);
991
992         while (!(ret = btree_trans_too_many_iters(&trans)) &&
993                (k = bch2_btree_iter_peek_upto(&iter, POS(inode->v.i_ino, end - 1))).k &&
994                !(ret = bkey_err(k))) {
995                 if (bkey_extent_is_allocation(k.k)) {
996                         u64 s = min(end, k.k->p.offset) -
997                                 max(start, bkey_start_offset(k.k));
998                         BUG_ON(s > sectors);
999                         sectors -= s;
1000                 }
1001                 bch2_btree_iter_advance(&iter);
1002         }
1003         pos = iter.pos.offset;
1004         bch2_trans_iter_exit(&trans, &iter);
1005 err:
1006         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1007                 goto retry;
1008
1009         bch2_trans_exit(&trans);
1010
1011         if (ret)
1012                 return ret;
1013
1014         return bch2_quota_reservation_add(c, inode, res, sectors, true);
1015 }
1016
1017 loff_t bch2_remap_file_range(struct file *file_src, loff_t pos_src,
1018                              struct file *file_dst, loff_t pos_dst,
1019                              loff_t len, unsigned remap_flags)
1020 {
1021         struct bch_inode_info *src = file_bch_inode(file_src);
1022         struct bch_inode_info *dst = file_bch_inode(file_dst);
1023         struct bch_fs *c = src->v.i_sb->s_fs_info;
1024         struct quota_res quota_res = { 0 };
1025         s64 i_sectors_delta = 0;
1026         u64 aligned_len;
1027         loff_t ret = 0;
1028
1029         if (remap_flags & ~(REMAP_FILE_DEDUP|REMAP_FILE_ADVISORY))
1030                 return -EINVAL;
1031
1032         if (remap_flags & REMAP_FILE_DEDUP)
1033                 return -EOPNOTSUPP;
1034
1035         if ((pos_src & (block_bytes(c) - 1)) ||
1036             (pos_dst & (block_bytes(c) - 1)))
1037                 return -EINVAL;
1038
1039         if (src == dst &&
1040             abs(pos_src - pos_dst) < len)
1041                 return -EINVAL;
1042
1043         bch2_lock_inodes(INODE_LOCK|INODE_PAGECACHE_BLOCK, src, dst);
1044
1045         inode_dio_wait(&src->v);
1046         inode_dio_wait(&dst->v);
1047
1048         ret = generic_remap_file_range_prep(file_src, pos_src,
1049                                             file_dst, pos_dst,
1050                                             &len, remap_flags);
1051         if (ret < 0 || len == 0)
1052                 goto err;
1053
1054         aligned_len = round_up((u64) len, block_bytes(c));
1055
1056         ret = bch2_write_invalidate_inode_pages_range(dst->v.i_mapping,
1057                                 pos_dst, pos_dst + len - 1);
1058         if (ret)
1059                 goto err;
1060
1061         ret = quota_reserve_range(dst, &quota_res, pos_dst >> 9,
1062                                   (pos_dst + aligned_len) >> 9);
1063         if (ret)
1064                 goto err;
1065
1066         file_update_time(file_dst);
1067
1068         bch2_mark_pagecache_unallocated(src, pos_src >> 9,
1069                                    (pos_src + aligned_len) >> 9);
1070
1071         ret = bch2_remap_range(c,
1072                                inode_inum(dst), pos_dst >> 9,
1073                                inode_inum(src), pos_src >> 9,
1074                                aligned_len >> 9,
1075                                pos_dst + len, &i_sectors_delta);
1076         if (ret < 0)
1077                 goto err;
1078
1079         /*
1080          * due to alignment, we might have remapped slightly more than requsted
1081          */
1082         ret = min((u64) ret << 9, (u64) len);
1083
1084         bch2_i_sectors_acct(c, dst, &quota_res, i_sectors_delta);
1085
1086         spin_lock(&dst->v.i_lock);
1087         if (pos_dst + ret > dst->v.i_size)
1088                 i_size_write(&dst->v, pos_dst + ret);
1089         spin_unlock(&dst->v.i_lock);
1090
1091         if ((file_dst->f_flags & (__O_SYNC | O_DSYNC)) ||
1092             IS_SYNC(file_inode(file_dst)))
1093                 ret = bch2_flush_inode(c, dst);
1094 err:
1095         bch2_quota_reservation_put(c, dst, &quota_res);
1096         bch2_unlock_inodes(INODE_LOCK|INODE_PAGECACHE_BLOCK, src, dst);
1097
1098         return bch2_err_class(ret);
1099 }
1100
1101 /* fseek: */
1102
1103 static loff_t bch2_seek_data(struct file *file, u64 offset)
1104 {
1105         struct bch_inode_info *inode = file_bch_inode(file);
1106         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1107         struct btree_trans trans;
1108         struct btree_iter iter;
1109         struct bkey_s_c k;
1110         subvol_inum inum = inode_inum(inode);
1111         u64 isize, next_data = MAX_LFS_FILESIZE;
1112         u32 snapshot;
1113         int ret;
1114
1115         isize = i_size_read(&inode->v);
1116         if (offset >= isize)
1117                 return -ENXIO;
1118
1119         bch2_trans_init(&trans, c, 0, 0);
1120 retry:
1121         bch2_trans_begin(&trans);
1122
1123         ret = bch2_subvolume_get_snapshot(&trans, inum.subvol, &snapshot);
1124         if (ret)
1125                 goto err;
1126
1127         for_each_btree_key_upto_norestart(&trans, iter, BTREE_ID_extents,
1128                            SPOS(inode->v.i_ino, offset >> 9, snapshot),
1129                            POS(inode->v.i_ino, U64_MAX),
1130                            0, k, ret) {
1131                 if (bkey_extent_is_data(k.k)) {
1132                         next_data = max(offset, bkey_start_offset(k.k) << 9);
1133                         break;
1134                 } else if (k.k->p.offset >> 9 > isize)
1135                         break;
1136         }
1137         bch2_trans_iter_exit(&trans, &iter);
1138 err:
1139         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1140                 goto retry;
1141
1142         bch2_trans_exit(&trans);
1143         if (ret)
1144                 return ret;
1145
1146         if (next_data > offset)
1147                 next_data = bch2_seek_pagecache_data(&inode->v,
1148                                         offset, next_data, 0, false);
1149
1150         if (next_data >= isize)
1151                 return -ENXIO;
1152
1153         return vfs_setpos(file, next_data, MAX_LFS_FILESIZE);
1154 }
1155
1156 static loff_t bch2_seek_hole(struct file *file, u64 offset)
1157 {
1158         struct bch_inode_info *inode = file_bch_inode(file);
1159         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1160         struct btree_trans trans;
1161         struct btree_iter iter;
1162         struct bkey_s_c k;
1163         subvol_inum inum = inode_inum(inode);
1164         u64 isize, next_hole = MAX_LFS_FILESIZE;
1165         u32 snapshot;
1166         int ret;
1167
1168         isize = i_size_read(&inode->v);
1169         if (offset >= isize)
1170                 return -ENXIO;
1171
1172         bch2_trans_init(&trans, c, 0, 0);
1173 retry:
1174         bch2_trans_begin(&trans);
1175
1176         ret = bch2_subvolume_get_snapshot(&trans, inum.subvol, &snapshot);
1177         if (ret)
1178                 goto err;
1179
1180         for_each_btree_key_norestart(&trans, iter, BTREE_ID_extents,
1181                            SPOS(inode->v.i_ino, offset >> 9, snapshot),
1182                            BTREE_ITER_SLOTS, k, ret) {
1183                 if (k.k->p.inode != inode->v.i_ino) {
1184                         next_hole = bch2_seek_pagecache_hole(&inode->v,
1185                                         offset, MAX_LFS_FILESIZE, 0, false);
1186                         break;
1187                 } else if (!bkey_extent_is_data(k.k)) {
1188                         next_hole = bch2_seek_pagecache_hole(&inode->v,
1189                                         max(offset, bkey_start_offset(k.k) << 9),
1190                                         k.k->p.offset << 9, 0, false);
1191
1192                         if (next_hole < k.k->p.offset << 9)
1193                                 break;
1194                 } else {
1195                         offset = max(offset, bkey_start_offset(k.k) << 9);
1196                 }
1197         }
1198         bch2_trans_iter_exit(&trans, &iter);
1199 err:
1200         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1201                 goto retry;
1202
1203         bch2_trans_exit(&trans);
1204         if (ret)
1205                 return ret;
1206
1207         if (next_hole > isize)
1208                 next_hole = isize;
1209
1210         return vfs_setpos(file, next_hole, MAX_LFS_FILESIZE);
1211 }
1212
1213 loff_t bch2_llseek(struct file *file, loff_t offset, int whence)
1214 {
1215         loff_t ret;
1216
1217         switch (whence) {
1218         case SEEK_SET:
1219         case SEEK_CUR:
1220         case SEEK_END:
1221                 ret = generic_file_llseek(file, offset, whence);
1222                 break;
1223         case SEEK_DATA:
1224                 ret = bch2_seek_data(file, offset);
1225                 break;
1226         case SEEK_HOLE:
1227                 ret = bch2_seek_hole(file, offset);
1228                 break;
1229         default:
1230                 ret = -EINVAL;
1231                 break;
1232         }
1233
1234         return bch2_err_class(ret);
1235 }
1236
1237 void bch2_fs_fsio_exit(struct bch_fs *c)
1238 {
1239         bioset_exit(&c->nocow_flush_bioset);
1240 }
1241
1242 int bch2_fs_fsio_init(struct bch_fs *c)
1243 {
1244         if (bioset_init(&c->nocow_flush_bioset,
1245                         1, offsetof(struct nocow_flush, bio), 0))
1246                 return -BCH_ERR_ENOMEM_nocow_flush_bioset_init;
1247
1248         return 0;
1249 }
1250
1251 #endif /* NO_BCACHEFS_FS */