btrfs: fix uninitialized parent in insert_state
[platform/kernel/linux-starfive.git] / fs / btrfs / file.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5
6 #include <linux/fs.h>
7 #include <linux/pagemap.h>
8 #include <linux/time.h>
9 #include <linux/init.h>
10 #include <linux/string.h>
11 #include <linux/backing-dev.h>
12 #include <linux/falloc.h>
13 #include <linux/writeback.h>
14 #include <linux/compat.h>
15 #include <linux/slab.h>
16 #include <linux/btrfs.h>
17 #include <linux/uio.h>
18 #include <linux/iversion.h>
19 #include <linux/fsverity.h>
20 #include "ctree.h"
21 #include "disk-io.h"
22 #include "transaction.h"
23 #include "btrfs_inode.h"
24 #include "print-tree.h"
25 #include "tree-log.h"
26 #include "locking.h"
27 #include "volumes.h"
28 #include "qgroup.h"
29 #include "compression.h"
30 #include "delalloc-space.h"
31 #include "reflink.h"
32 #include "subpage.h"
33
34 static struct kmem_cache *btrfs_inode_defrag_cachep;
35 /*
36  * when auto defrag is enabled we
37  * queue up these defrag structs to remember which
38  * inodes need defragging passes
39  */
40 struct inode_defrag {
41         struct rb_node rb_node;
42         /* objectid */
43         u64 ino;
44         /*
45          * transid where the defrag was added, we search for
46          * extents newer than this
47          */
48         u64 transid;
49
50         /* root objectid */
51         u64 root;
52
53         /*
54          * The extent size threshold for autodefrag.
55          *
56          * This value is different for compressed/non-compressed extents,
57          * thus needs to be passed from higher layer.
58          * (aka, inode_should_defrag())
59          */
60         u32 extent_thresh;
61 };
62
63 static int __compare_inode_defrag(struct inode_defrag *defrag1,
64                                   struct inode_defrag *defrag2)
65 {
66         if (defrag1->root > defrag2->root)
67                 return 1;
68         else if (defrag1->root < defrag2->root)
69                 return -1;
70         else if (defrag1->ino > defrag2->ino)
71                 return 1;
72         else if (defrag1->ino < defrag2->ino)
73                 return -1;
74         else
75                 return 0;
76 }
77
78 /* pop a record for an inode into the defrag tree.  The lock
79  * must be held already
80  *
81  * If you're inserting a record for an older transid than an
82  * existing record, the transid already in the tree is lowered
83  *
84  * If an existing record is found the defrag item you
85  * pass in is freed
86  */
87 static int __btrfs_add_inode_defrag(struct btrfs_inode *inode,
88                                     struct inode_defrag *defrag)
89 {
90         struct btrfs_fs_info *fs_info = inode->root->fs_info;
91         struct inode_defrag *entry;
92         struct rb_node **p;
93         struct rb_node *parent = NULL;
94         int ret;
95
96         p = &fs_info->defrag_inodes.rb_node;
97         while (*p) {
98                 parent = *p;
99                 entry = rb_entry(parent, struct inode_defrag, rb_node);
100
101                 ret = __compare_inode_defrag(defrag, entry);
102                 if (ret < 0)
103                         p = &parent->rb_left;
104                 else if (ret > 0)
105                         p = &parent->rb_right;
106                 else {
107                         /* if we're reinserting an entry for
108                          * an old defrag run, make sure to
109                          * lower the transid of our existing record
110                          */
111                         if (defrag->transid < entry->transid)
112                                 entry->transid = defrag->transid;
113                         entry->extent_thresh = min(defrag->extent_thresh,
114                                                    entry->extent_thresh);
115                         return -EEXIST;
116                 }
117         }
118         set_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags);
119         rb_link_node(&defrag->rb_node, parent, p);
120         rb_insert_color(&defrag->rb_node, &fs_info->defrag_inodes);
121         return 0;
122 }
123
124 static inline int __need_auto_defrag(struct btrfs_fs_info *fs_info)
125 {
126         if (!btrfs_test_opt(fs_info, AUTO_DEFRAG))
127                 return 0;
128
129         if (btrfs_fs_closing(fs_info))
130                 return 0;
131
132         return 1;
133 }
134
135 /*
136  * insert a defrag record for this inode if auto defrag is
137  * enabled
138  */
139 int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans,
140                            struct btrfs_inode *inode, u32 extent_thresh)
141 {
142         struct btrfs_root *root = inode->root;
143         struct btrfs_fs_info *fs_info = root->fs_info;
144         struct inode_defrag *defrag;
145         u64 transid;
146         int ret;
147
148         if (!__need_auto_defrag(fs_info))
149                 return 0;
150
151         if (test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags))
152                 return 0;
153
154         if (trans)
155                 transid = trans->transid;
156         else
157                 transid = inode->root->last_trans;
158
159         defrag = kmem_cache_zalloc(btrfs_inode_defrag_cachep, GFP_NOFS);
160         if (!defrag)
161                 return -ENOMEM;
162
163         defrag->ino = btrfs_ino(inode);
164         defrag->transid = transid;
165         defrag->root = root->root_key.objectid;
166         defrag->extent_thresh = extent_thresh;
167
168         spin_lock(&fs_info->defrag_inodes_lock);
169         if (!test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags)) {
170                 /*
171                  * If we set IN_DEFRAG flag and evict the inode from memory,
172                  * and then re-read this inode, this new inode doesn't have
173                  * IN_DEFRAG flag. At the case, we may find the existed defrag.
174                  */
175                 ret = __btrfs_add_inode_defrag(inode, defrag);
176                 if (ret)
177                         kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
178         } else {
179                 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
180         }
181         spin_unlock(&fs_info->defrag_inodes_lock);
182         return 0;
183 }
184
185 /*
186  * pick the defragable inode that we want, if it doesn't exist, we will get
187  * the next one.
188  */
189 static struct inode_defrag *
190 btrfs_pick_defrag_inode(struct btrfs_fs_info *fs_info, u64 root, u64 ino)
191 {
192         struct inode_defrag *entry = NULL;
193         struct inode_defrag tmp;
194         struct rb_node *p;
195         struct rb_node *parent = NULL;
196         int ret;
197
198         tmp.ino = ino;
199         tmp.root = root;
200
201         spin_lock(&fs_info->defrag_inodes_lock);
202         p = fs_info->defrag_inodes.rb_node;
203         while (p) {
204                 parent = p;
205                 entry = rb_entry(parent, struct inode_defrag, rb_node);
206
207                 ret = __compare_inode_defrag(&tmp, entry);
208                 if (ret < 0)
209                         p = parent->rb_left;
210                 else if (ret > 0)
211                         p = parent->rb_right;
212                 else
213                         goto out;
214         }
215
216         if (parent && __compare_inode_defrag(&tmp, entry) > 0) {
217                 parent = rb_next(parent);
218                 if (parent)
219                         entry = rb_entry(parent, struct inode_defrag, rb_node);
220                 else
221                         entry = NULL;
222         }
223 out:
224         if (entry)
225                 rb_erase(parent, &fs_info->defrag_inodes);
226         spin_unlock(&fs_info->defrag_inodes_lock);
227         return entry;
228 }
229
230 void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info *fs_info)
231 {
232         struct inode_defrag *defrag;
233         struct rb_node *node;
234
235         spin_lock(&fs_info->defrag_inodes_lock);
236         node = rb_first(&fs_info->defrag_inodes);
237         while (node) {
238                 rb_erase(node, &fs_info->defrag_inodes);
239                 defrag = rb_entry(node, struct inode_defrag, rb_node);
240                 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
241
242                 cond_resched_lock(&fs_info->defrag_inodes_lock);
243
244                 node = rb_first(&fs_info->defrag_inodes);
245         }
246         spin_unlock(&fs_info->defrag_inodes_lock);
247 }
248
249 #define BTRFS_DEFRAG_BATCH      1024
250
251 static int __btrfs_run_defrag_inode(struct btrfs_fs_info *fs_info,
252                                     struct inode_defrag *defrag)
253 {
254         struct btrfs_root *inode_root;
255         struct inode *inode;
256         struct btrfs_ioctl_defrag_range_args range;
257         int ret = 0;
258         u64 cur = 0;
259
260 again:
261         if (test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state))
262                 goto cleanup;
263         if (!__need_auto_defrag(fs_info))
264                 goto cleanup;
265
266         /* get the inode */
267         inode_root = btrfs_get_fs_root(fs_info, defrag->root, true);
268         if (IS_ERR(inode_root)) {
269                 ret = PTR_ERR(inode_root);
270                 goto cleanup;
271         }
272
273         inode = btrfs_iget(fs_info->sb, defrag->ino, inode_root);
274         btrfs_put_root(inode_root);
275         if (IS_ERR(inode)) {
276                 ret = PTR_ERR(inode);
277                 goto cleanup;
278         }
279
280         if (cur >= i_size_read(inode)) {
281                 iput(inode);
282                 goto cleanup;
283         }
284
285         /* do a chunk of defrag */
286         clear_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
287         memset(&range, 0, sizeof(range));
288         range.len = (u64)-1;
289         range.start = cur;
290         range.extent_thresh = defrag->extent_thresh;
291
292         sb_start_write(fs_info->sb);
293         ret = btrfs_defrag_file(inode, NULL, &range, defrag->transid,
294                                        BTRFS_DEFRAG_BATCH);
295         sb_end_write(fs_info->sb);
296         iput(inode);
297
298         if (ret < 0)
299                 goto cleanup;
300
301         cur = max(cur + fs_info->sectorsize, range.start);
302         goto again;
303
304 cleanup:
305         kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
306         return ret;
307 }
308
309 /*
310  * run through the list of inodes in the FS that need
311  * defragging
312  */
313 int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)
314 {
315         struct inode_defrag *defrag;
316         u64 first_ino = 0;
317         u64 root_objectid = 0;
318
319         atomic_inc(&fs_info->defrag_running);
320         while (1) {
321                 /* Pause the auto defragger. */
322                 if (test_bit(BTRFS_FS_STATE_REMOUNTING,
323                              &fs_info->fs_state))
324                         break;
325
326                 if (!__need_auto_defrag(fs_info))
327                         break;
328
329                 /* find an inode to defrag */
330                 defrag = btrfs_pick_defrag_inode(fs_info, root_objectid,
331                                                  first_ino);
332                 if (!defrag) {
333                         if (root_objectid || first_ino) {
334                                 root_objectid = 0;
335                                 first_ino = 0;
336                                 continue;
337                         } else {
338                                 break;
339                         }
340                 }
341
342                 first_ino = defrag->ino + 1;
343                 root_objectid = defrag->root;
344
345                 __btrfs_run_defrag_inode(fs_info, defrag);
346         }
347         atomic_dec(&fs_info->defrag_running);
348
349         /*
350          * during unmount, we use the transaction_wait queue to
351          * wait for the defragger to stop
352          */
353         wake_up(&fs_info->transaction_wait);
354         return 0;
355 }
356
357 /* simple helper to fault in pages and copy.  This should go away
358  * and be replaced with calls into generic code.
359  */
360 static noinline int btrfs_copy_from_user(loff_t pos, size_t write_bytes,
361                                          struct page **prepared_pages,
362                                          struct iov_iter *i)
363 {
364         size_t copied = 0;
365         size_t total_copied = 0;
366         int pg = 0;
367         int offset = offset_in_page(pos);
368
369         while (write_bytes > 0) {
370                 size_t count = min_t(size_t,
371                                      PAGE_SIZE - offset, write_bytes);
372                 struct page *page = prepared_pages[pg];
373                 /*
374                  * Copy data from userspace to the current page
375                  */
376                 copied = copy_page_from_iter_atomic(page, offset, count, i);
377
378                 /* Flush processor's dcache for this page */
379                 flush_dcache_page(page);
380
381                 /*
382                  * if we get a partial write, we can end up with
383                  * partially up to date pages.  These add
384                  * a lot of complexity, so make sure they don't
385                  * happen by forcing this copy to be retried.
386                  *
387                  * The rest of the btrfs_file_write code will fall
388                  * back to page at a time copies after we return 0.
389                  */
390                 if (unlikely(copied < count)) {
391                         if (!PageUptodate(page)) {
392                                 iov_iter_revert(i, copied);
393                                 copied = 0;
394                         }
395                         if (!copied)
396                                 break;
397                 }
398
399                 write_bytes -= copied;
400                 total_copied += copied;
401                 offset += copied;
402                 if (offset == PAGE_SIZE) {
403                         pg++;
404                         offset = 0;
405                 }
406         }
407         return total_copied;
408 }
409
410 /*
411  * unlocks pages after btrfs_file_write is done with them
412  */
413 static void btrfs_drop_pages(struct btrfs_fs_info *fs_info,
414                              struct page **pages, size_t num_pages,
415                              u64 pos, u64 copied)
416 {
417         size_t i;
418         u64 block_start = round_down(pos, fs_info->sectorsize);
419         u64 block_len = round_up(pos + copied, fs_info->sectorsize) - block_start;
420
421         ASSERT(block_len <= U32_MAX);
422         for (i = 0; i < num_pages; i++) {
423                 /* page checked is some magic around finding pages that
424                  * have been modified without going through btrfs_set_page_dirty
425                  * clear it here. There should be no need to mark the pages
426                  * accessed as prepare_pages should have marked them accessed
427                  * in prepare_pages via find_or_create_page()
428                  */
429                 btrfs_page_clamp_clear_checked(fs_info, pages[i], block_start,
430                                                block_len);
431                 unlock_page(pages[i]);
432                 put_page(pages[i]);
433         }
434 }
435
436 /*
437  * After btrfs_copy_from_user(), update the following things for delalloc:
438  * - Mark newly dirtied pages as DELALLOC in the io tree.
439  *   Used to advise which range is to be written back.
440  * - Mark modified pages as Uptodate/Dirty and not needing COW fixup
441  * - Update inode size for past EOF write
442  */
443 int btrfs_dirty_pages(struct btrfs_inode *inode, struct page **pages,
444                       size_t num_pages, loff_t pos, size_t write_bytes,
445                       struct extent_state **cached, bool noreserve)
446 {
447         struct btrfs_fs_info *fs_info = inode->root->fs_info;
448         int err = 0;
449         int i;
450         u64 num_bytes;
451         u64 start_pos;
452         u64 end_of_last_block;
453         u64 end_pos = pos + write_bytes;
454         loff_t isize = i_size_read(&inode->vfs_inode);
455         unsigned int extra_bits = 0;
456
457         if (write_bytes == 0)
458                 return 0;
459
460         if (noreserve)
461                 extra_bits |= EXTENT_NORESERVE;
462
463         start_pos = round_down(pos, fs_info->sectorsize);
464         num_bytes = round_up(write_bytes + pos - start_pos,
465                              fs_info->sectorsize);
466         ASSERT(num_bytes <= U32_MAX);
467
468         end_of_last_block = start_pos + num_bytes - 1;
469
470         /*
471          * The pages may have already been dirty, clear out old accounting so
472          * we can set things up properly
473          */
474         clear_extent_bit(&inode->io_tree, start_pos, end_of_last_block,
475                          EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
476                          cached);
477
478         err = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block,
479                                         extra_bits, cached);
480         if (err)
481                 return err;
482
483         for (i = 0; i < num_pages; i++) {
484                 struct page *p = pages[i];
485
486                 btrfs_page_clamp_set_uptodate(fs_info, p, start_pos, num_bytes);
487                 btrfs_page_clamp_clear_checked(fs_info, p, start_pos, num_bytes);
488                 btrfs_page_clamp_set_dirty(fs_info, p, start_pos, num_bytes);
489         }
490
491         /*
492          * we've only changed i_size in ram, and we haven't updated
493          * the disk i_size.  There is no need to log the inode
494          * at this time.
495          */
496         if (end_pos > isize)
497                 i_size_write(&inode->vfs_inode, end_pos);
498         return 0;
499 }
500
501 /*
502  * this is very complex, but the basic idea is to drop all extents
503  * in the range start - end.  hint_block is filled in with a block number
504  * that would be a good hint to the block allocator for this file.
505  *
506  * If an extent intersects the range but is not entirely inside the range
507  * it is either truncated or split.  Anything entirely inside the range
508  * is deleted from the tree.
509  *
510  * Note: the VFS' inode number of bytes is not updated, it's up to the caller
511  * to deal with that. We set the field 'bytes_found' of the arguments structure
512  * with the number of allocated bytes found in the target range, so that the
513  * caller can update the inode's number of bytes in an atomic way when
514  * replacing extents in a range to avoid races with stat(2).
515  */
516 int btrfs_drop_extents(struct btrfs_trans_handle *trans,
517                        struct btrfs_root *root, struct btrfs_inode *inode,
518                        struct btrfs_drop_extents_args *args)
519 {
520         struct btrfs_fs_info *fs_info = root->fs_info;
521         struct extent_buffer *leaf;
522         struct btrfs_file_extent_item *fi;
523         struct btrfs_ref ref = { 0 };
524         struct btrfs_key key;
525         struct btrfs_key new_key;
526         u64 ino = btrfs_ino(inode);
527         u64 search_start = args->start;
528         u64 disk_bytenr = 0;
529         u64 num_bytes = 0;
530         u64 extent_offset = 0;
531         u64 extent_end = 0;
532         u64 last_end = args->start;
533         int del_nr = 0;
534         int del_slot = 0;
535         int extent_type;
536         int recow;
537         int ret;
538         int modify_tree = -1;
539         int update_refs;
540         int found = 0;
541         struct btrfs_path *path = args->path;
542
543         args->bytes_found = 0;
544         args->extent_inserted = false;
545
546         /* Must always have a path if ->replace_extent is true */
547         ASSERT(!(args->replace_extent && !args->path));
548
549         if (!path) {
550                 path = btrfs_alloc_path();
551                 if (!path) {
552                         ret = -ENOMEM;
553                         goto out;
554                 }
555         }
556
557         if (args->drop_cache)
558                 btrfs_drop_extent_map_range(inode, args->start, args->end - 1, false);
559
560         if (args->start >= inode->disk_i_size && !args->replace_extent)
561                 modify_tree = 0;
562
563         update_refs = (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID);
564         while (1) {
565                 recow = 0;
566                 ret = btrfs_lookup_file_extent(trans, root, path, ino,
567                                                search_start, modify_tree);
568                 if (ret < 0)
569                         break;
570                 if (ret > 0 && path->slots[0] > 0 && search_start == args->start) {
571                         leaf = path->nodes[0];
572                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
573                         if (key.objectid == ino &&
574                             key.type == BTRFS_EXTENT_DATA_KEY)
575                                 path->slots[0]--;
576                 }
577                 ret = 0;
578 next_slot:
579                 leaf = path->nodes[0];
580                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
581                         BUG_ON(del_nr > 0);
582                         ret = btrfs_next_leaf(root, path);
583                         if (ret < 0)
584                                 break;
585                         if (ret > 0) {
586                                 ret = 0;
587                                 break;
588                         }
589                         leaf = path->nodes[0];
590                         recow = 1;
591                 }
592
593                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
594
595                 if (key.objectid > ino)
596                         break;
597                 if (WARN_ON_ONCE(key.objectid < ino) ||
598                     key.type < BTRFS_EXTENT_DATA_KEY) {
599                         ASSERT(del_nr == 0);
600                         path->slots[0]++;
601                         goto next_slot;
602                 }
603                 if (key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= args->end)
604                         break;
605
606                 fi = btrfs_item_ptr(leaf, path->slots[0],
607                                     struct btrfs_file_extent_item);
608                 extent_type = btrfs_file_extent_type(leaf, fi);
609
610                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
611                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
612                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
613                         num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
614                         extent_offset = btrfs_file_extent_offset(leaf, fi);
615                         extent_end = key.offset +
616                                 btrfs_file_extent_num_bytes(leaf, fi);
617                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
618                         extent_end = key.offset +
619                                 btrfs_file_extent_ram_bytes(leaf, fi);
620                 } else {
621                         /* can't happen */
622                         BUG();
623                 }
624
625                 /*
626                  * Don't skip extent items representing 0 byte lengths. They
627                  * used to be created (bug) if while punching holes we hit
628                  * -ENOSPC condition. So if we find one here, just ensure we
629                  * delete it, otherwise we would insert a new file extent item
630                  * with the same key (offset) as that 0 bytes length file
631                  * extent item in the call to setup_items_for_insert() later
632                  * in this function.
633                  */
634                 if (extent_end == key.offset && extent_end >= search_start) {
635                         last_end = extent_end;
636                         goto delete_extent_item;
637                 }
638
639                 if (extent_end <= search_start) {
640                         path->slots[0]++;
641                         goto next_slot;
642                 }
643
644                 found = 1;
645                 search_start = max(key.offset, args->start);
646                 if (recow || !modify_tree) {
647                         modify_tree = -1;
648                         btrfs_release_path(path);
649                         continue;
650                 }
651
652                 /*
653                  *     | - range to drop - |
654                  *  | -------- extent -------- |
655                  */
656                 if (args->start > key.offset && args->end < extent_end) {
657                         BUG_ON(del_nr > 0);
658                         if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
659                                 ret = -EOPNOTSUPP;
660                                 break;
661                         }
662
663                         memcpy(&new_key, &key, sizeof(new_key));
664                         new_key.offset = args->start;
665                         ret = btrfs_duplicate_item(trans, root, path,
666                                                    &new_key);
667                         if (ret == -EAGAIN) {
668                                 btrfs_release_path(path);
669                                 continue;
670                         }
671                         if (ret < 0)
672                                 break;
673
674                         leaf = path->nodes[0];
675                         fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
676                                             struct btrfs_file_extent_item);
677                         btrfs_set_file_extent_num_bytes(leaf, fi,
678                                                         args->start - key.offset);
679
680                         fi = btrfs_item_ptr(leaf, path->slots[0],
681                                             struct btrfs_file_extent_item);
682
683                         extent_offset += args->start - key.offset;
684                         btrfs_set_file_extent_offset(leaf, fi, extent_offset);
685                         btrfs_set_file_extent_num_bytes(leaf, fi,
686                                                         extent_end - args->start);
687                         btrfs_mark_buffer_dirty(leaf);
688
689                         if (update_refs && disk_bytenr > 0) {
690                                 btrfs_init_generic_ref(&ref,
691                                                 BTRFS_ADD_DELAYED_REF,
692                                                 disk_bytenr, num_bytes, 0);
693                                 btrfs_init_data_ref(&ref,
694                                                 root->root_key.objectid,
695                                                 new_key.objectid,
696                                                 args->start - extent_offset,
697                                                 0, false);
698                                 ret = btrfs_inc_extent_ref(trans, &ref);
699                                 if (ret) {
700                                         btrfs_abort_transaction(trans, ret);
701                                         break;
702                                 }
703                         }
704                         key.offset = args->start;
705                 }
706                 /*
707                  * From here on out we will have actually dropped something, so
708                  * last_end can be updated.
709                  */
710                 last_end = extent_end;
711
712                 /*
713                  *  | ---- range to drop ----- |
714                  *      | -------- extent -------- |
715                  */
716                 if (args->start <= key.offset && args->end < extent_end) {
717                         if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
718                                 ret = -EOPNOTSUPP;
719                                 break;
720                         }
721
722                         memcpy(&new_key, &key, sizeof(new_key));
723                         new_key.offset = args->end;
724                         btrfs_set_item_key_safe(fs_info, path, &new_key);
725
726                         extent_offset += args->end - key.offset;
727                         btrfs_set_file_extent_offset(leaf, fi, extent_offset);
728                         btrfs_set_file_extent_num_bytes(leaf, fi,
729                                                         extent_end - args->end);
730                         btrfs_mark_buffer_dirty(leaf);
731                         if (update_refs && disk_bytenr > 0)
732                                 args->bytes_found += args->end - key.offset;
733                         break;
734                 }
735
736                 search_start = extent_end;
737                 /*
738                  *       | ---- range to drop ----- |
739                  *  | -------- extent -------- |
740                  */
741                 if (args->start > key.offset && args->end >= extent_end) {
742                         BUG_ON(del_nr > 0);
743                         if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
744                                 ret = -EOPNOTSUPP;
745                                 break;
746                         }
747
748                         btrfs_set_file_extent_num_bytes(leaf, fi,
749                                                         args->start - key.offset);
750                         btrfs_mark_buffer_dirty(leaf);
751                         if (update_refs && disk_bytenr > 0)
752                                 args->bytes_found += extent_end - args->start;
753                         if (args->end == extent_end)
754                                 break;
755
756                         path->slots[0]++;
757                         goto next_slot;
758                 }
759
760                 /*
761                  *  | ---- range to drop ----- |
762                  *    | ------ extent ------ |
763                  */
764                 if (args->start <= key.offset && args->end >= extent_end) {
765 delete_extent_item:
766                         if (del_nr == 0) {
767                                 del_slot = path->slots[0];
768                                 del_nr = 1;
769                         } else {
770                                 BUG_ON(del_slot + del_nr != path->slots[0]);
771                                 del_nr++;
772                         }
773
774                         if (update_refs &&
775                             extent_type == BTRFS_FILE_EXTENT_INLINE) {
776                                 args->bytes_found += extent_end - key.offset;
777                                 extent_end = ALIGN(extent_end,
778                                                    fs_info->sectorsize);
779                         } else if (update_refs && disk_bytenr > 0) {
780                                 btrfs_init_generic_ref(&ref,
781                                                 BTRFS_DROP_DELAYED_REF,
782                                                 disk_bytenr, num_bytes, 0);
783                                 btrfs_init_data_ref(&ref,
784                                                 root->root_key.objectid,
785                                                 key.objectid,
786                                                 key.offset - extent_offset, 0,
787                                                 false);
788                                 ret = btrfs_free_extent(trans, &ref);
789                                 if (ret) {
790                                         btrfs_abort_transaction(trans, ret);
791                                         break;
792                                 }
793                                 args->bytes_found += extent_end - key.offset;
794                         }
795
796                         if (args->end == extent_end)
797                                 break;
798
799                         if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
800                                 path->slots[0]++;
801                                 goto next_slot;
802                         }
803
804                         ret = btrfs_del_items(trans, root, path, del_slot,
805                                               del_nr);
806                         if (ret) {
807                                 btrfs_abort_transaction(trans, ret);
808                                 break;
809                         }
810
811                         del_nr = 0;
812                         del_slot = 0;
813
814                         btrfs_release_path(path);
815                         continue;
816                 }
817
818                 BUG();
819         }
820
821         if (!ret && del_nr > 0) {
822                 /*
823                  * Set path->slots[0] to first slot, so that after the delete
824                  * if items are move off from our leaf to its immediate left or
825                  * right neighbor leafs, we end up with a correct and adjusted
826                  * path->slots[0] for our insertion (if args->replace_extent).
827                  */
828                 path->slots[0] = del_slot;
829                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
830                 if (ret)
831                         btrfs_abort_transaction(trans, ret);
832         }
833
834         leaf = path->nodes[0];
835         /*
836          * If btrfs_del_items() was called, it might have deleted a leaf, in
837          * which case it unlocked our path, so check path->locks[0] matches a
838          * write lock.
839          */
840         if (!ret && args->replace_extent &&
841             path->locks[0] == BTRFS_WRITE_LOCK &&
842             btrfs_leaf_free_space(leaf) >=
843             sizeof(struct btrfs_item) + args->extent_item_size) {
844
845                 key.objectid = ino;
846                 key.type = BTRFS_EXTENT_DATA_KEY;
847                 key.offset = args->start;
848                 if (!del_nr && path->slots[0] < btrfs_header_nritems(leaf)) {
849                         struct btrfs_key slot_key;
850
851                         btrfs_item_key_to_cpu(leaf, &slot_key, path->slots[0]);
852                         if (btrfs_comp_cpu_keys(&key, &slot_key) > 0)
853                                 path->slots[0]++;
854                 }
855                 btrfs_setup_item_for_insert(root, path, &key, args->extent_item_size);
856                 args->extent_inserted = true;
857         }
858
859         if (!args->path)
860                 btrfs_free_path(path);
861         else if (!args->extent_inserted)
862                 btrfs_release_path(path);
863 out:
864         args->drop_end = found ? min(args->end, last_end) : args->end;
865
866         return ret;
867 }
868
869 static int extent_mergeable(struct extent_buffer *leaf, int slot,
870                             u64 objectid, u64 bytenr, u64 orig_offset,
871                             u64 *start, u64 *end)
872 {
873         struct btrfs_file_extent_item *fi;
874         struct btrfs_key key;
875         u64 extent_end;
876
877         if (slot < 0 || slot >= btrfs_header_nritems(leaf))
878                 return 0;
879
880         btrfs_item_key_to_cpu(leaf, &key, slot);
881         if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
882                 return 0;
883
884         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
885         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
886             btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
887             btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
888             btrfs_file_extent_compression(leaf, fi) ||
889             btrfs_file_extent_encryption(leaf, fi) ||
890             btrfs_file_extent_other_encoding(leaf, fi))
891                 return 0;
892
893         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
894         if ((*start && *start != key.offset) || (*end && *end != extent_end))
895                 return 0;
896
897         *start = key.offset;
898         *end = extent_end;
899         return 1;
900 }
901
902 /*
903  * Mark extent in the range start - end as written.
904  *
905  * This changes extent type from 'pre-allocated' to 'regular'. If only
906  * part of extent is marked as written, the extent will be split into
907  * two or three.
908  */
909 int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
910                               struct btrfs_inode *inode, u64 start, u64 end)
911 {
912         struct btrfs_fs_info *fs_info = trans->fs_info;
913         struct btrfs_root *root = inode->root;
914         struct extent_buffer *leaf;
915         struct btrfs_path *path;
916         struct btrfs_file_extent_item *fi;
917         struct btrfs_ref ref = { 0 };
918         struct btrfs_key key;
919         struct btrfs_key new_key;
920         u64 bytenr;
921         u64 num_bytes;
922         u64 extent_end;
923         u64 orig_offset;
924         u64 other_start;
925         u64 other_end;
926         u64 split;
927         int del_nr = 0;
928         int del_slot = 0;
929         int recow;
930         int ret = 0;
931         u64 ino = btrfs_ino(inode);
932
933         path = btrfs_alloc_path();
934         if (!path)
935                 return -ENOMEM;
936 again:
937         recow = 0;
938         split = start;
939         key.objectid = ino;
940         key.type = BTRFS_EXTENT_DATA_KEY;
941         key.offset = split;
942
943         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
944         if (ret < 0)
945                 goto out;
946         if (ret > 0 && path->slots[0] > 0)
947                 path->slots[0]--;
948
949         leaf = path->nodes[0];
950         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
951         if (key.objectid != ino ||
952             key.type != BTRFS_EXTENT_DATA_KEY) {
953                 ret = -EINVAL;
954                 btrfs_abort_transaction(trans, ret);
955                 goto out;
956         }
957         fi = btrfs_item_ptr(leaf, path->slots[0],
958                             struct btrfs_file_extent_item);
959         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_PREALLOC) {
960                 ret = -EINVAL;
961                 btrfs_abort_transaction(trans, ret);
962                 goto out;
963         }
964         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
965         if (key.offset > start || extent_end < end) {
966                 ret = -EINVAL;
967                 btrfs_abort_transaction(trans, ret);
968                 goto out;
969         }
970
971         bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
972         num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
973         orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
974         memcpy(&new_key, &key, sizeof(new_key));
975
976         if (start == key.offset && end < extent_end) {
977                 other_start = 0;
978                 other_end = start;
979                 if (extent_mergeable(leaf, path->slots[0] - 1,
980                                      ino, bytenr, orig_offset,
981                                      &other_start, &other_end)) {
982                         new_key.offset = end;
983                         btrfs_set_item_key_safe(fs_info, path, &new_key);
984                         fi = btrfs_item_ptr(leaf, path->slots[0],
985                                             struct btrfs_file_extent_item);
986                         btrfs_set_file_extent_generation(leaf, fi,
987                                                          trans->transid);
988                         btrfs_set_file_extent_num_bytes(leaf, fi,
989                                                         extent_end - end);
990                         btrfs_set_file_extent_offset(leaf, fi,
991                                                      end - orig_offset);
992                         fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
993                                             struct btrfs_file_extent_item);
994                         btrfs_set_file_extent_generation(leaf, fi,
995                                                          trans->transid);
996                         btrfs_set_file_extent_num_bytes(leaf, fi,
997                                                         end - other_start);
998                         btrfs_mark_buffer_dirty(leaf);
999                         goto out;
1000                 }
1001         }
1002
1003         if (start > key.offset && end == extent_end) {
1004                 other_start = end;
1005                 other_end = 0;
1006                 if (extent_mergeable(leaf, path->slots[0] + 1,
1007                                      ino, bytenr, orig_offset,
1008                                      &other_start, &other_end)) {
1009                         fi = btrfs_item_ptr(leaf, path->slots[0],
1010                                             struct btrfs_file_extent_item);
1011                         btrfs_set_file_extent_num_bytes(leaf, fi,
1012                                                         start - key.offset);
1013                         btrfs_set_file_extent_generation(leaf, fi,
1014                                                          trans->transid);
1015                         path->slots[0]++;
1016                         new_key.offset = start;
1017                         btrfs_set_item_key_safe(fs_info, path, &new_key);
1018
1019                         fi = btrfs_item_ptr(leaf, path->slots[0],
1020                                             struct btrfs_file_extent_item);
1021                         btrfs_set_file_extent_generation(leaf, fi,
1022                                                          trans->transid);
1023                         btrfs_set_file_extent_num_bytes(leaf, fi,
1024                                                         other_end - start);
1025                         btrfs_set_file_extent_offset(leaf, fi,
1026                                                      start - orig_offset);
1027                         btrfs_mark_buffer_dirty(leaf);
1028                         goto out;
1029                 }
1030         }
1031
1032         while (start > key.offset || end < extent_end) {
1033                 if (key.offset == start)
1034                         split = end;
1035
1036                 new_key.offset = split;
1037                 ret = btrfs_duplicate_item(trans, root, path, &new_key);
1038                 if (ret == -EAGAIN) {
1039                         btrfs_release_path(path);
1040                         goto again;
1041                 }
1042                 if (ret < 0) {
1043                         btrfs_abort_transaction(trans, ret);
1044                         goto out;
1045                 }
1046
1047                 leaf = path->nodes[0];
1048                 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1049                                     struct btrfs_file_extent_item);
1050                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1051                 btrfs_set_file_extent_num_bytes(leaf, fi,
1052                                                 split - key.offset);
1053
1054                 fi = btrfs_item_ptr(leaf, path->slots[0],
1055                                     struct btrfs_file_extent_item);
1056
1057                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1058                 btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
1059                 btrfs_set_file_extent_num_bytes(leaf, fi,
1060                                                 extent_end - split);
1061                 btrfs_mark_buffer_dirty(leaf);
1062
1063                 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, bytenr,
1064                                        num_bytes, 0);
1065                 btrfs_init_data_ref(&ref, root->root_key.objectid, ino,
1066                                     orig_offset, 0, false);
1067                 ret = btrfs_inc_extent_ref(trans, &ref);
1068                 if (ret) {
1069                         btrfs_abort_transaction(trans, ret);
1070                         goto out;
1071                 }
1072
1073                 if (split == start) {
1074                         key.offset = start;
1075                 } else {
1076                         if (start != key.offset) {
1077                                 ret = -EINVAL;
1078                                 btrfs_abort_transaction(trans, ret);
1079                                 goto out;
1080                         }
1081                         path->slots[0]--;
1082                         extent_end = end;
1083                 }
1084                 recow = 1;
1085         }
1086
1087         other_start = end;
1088         other_end = 0;
1089         btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
1090                                num_bytes, 0);
1091         btrfs_init_data_ref(&ref, root->root_key.objectid, ino, orig_offset,
1092                             0, false);
1093         if (extent_mergeable(leaf, path->slots[0] + 1,
1094                              ino, bytenr, orig_offset,
1095                              &other_start, &other_end)) {
1096                 if (recow) {
1097                         btrfs_release_path(path);
1098                         goto again;
1099                 }
1100                 extent_end = other_end;
1101                 del_slot = path->slots[0] + 1;
1102                 del_nr++;
1103                 ret = btrfs_free_extent(trans, &ref);
1104                 if (ret) {
1105                         btrfs_abort_transaction(trans, ret);
1106                         goto out;
1107                 }
1108         }
1109         other_start = 0;
1110         other_end = start;
1111         if (extent_mergeable(leaf, path->slots[0] - 1,
1112                              ino, bytenr, orig_offset,
1113                              &other_start, &other_end)) {
1114                 if (recow) {
1115                         btrfs_release_path(path);
1116                         goto again;
1117                 }
1118                 key.offset = other_start;
1119                 del_slot = path->slots[0];
1120                 del_nr++;
1121                 ret = btrfs_free_extent(trans, &ref);
1122                 if (ret) {
1123                         btrfs_abort_transaction(trans, ret);
1124                         goto out;
1125                 }
1126         }
1127         if (del_nr == 0) {
1128                 fi = btrfs_item_ptr(leaf, path->slots[0],
1129                            struct btrfs_file_extent_item);
1130                 btrfs_set_file_extent_type(leaf, fi,
1131                                            BTRFS_FILE_EXTENT_REG);
1132                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1133                 btrfs_mark_buffer_dirty(leaf);
1134         } else {
1135                 fi = btrfs_item_ptr(leaf, del_slot - 1,
1136                            struct btrfs_file_extent_item);
1137                 btrfs_set_file_extent_type(leaf, fi,
1138                                            BTRFS_FILE_EXTENT_REG);
1139                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1140                 btrfs_set_file_extent_num_bytes(leaf, fi,
1141                                                 extent_end - key.offset);
1142                 btrfs_mark_buffer_dirty(leaf);
1143
1144                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
1145                 if (ret < 0) {
1146                         btrfs_abort_transaction(trans, ret);
1147                         goto out;
1148                 }
1149         }
1150 out:
1151         btrfs_free_path(path);
1152         return ret;
1153 }
1154
1155 /*
1156  * on error we return an unlocked page and the error value
1157  * on success we return a locked page and 0
1158  */
1159 static int prepare_uptodate_page(struct inode *inode,
1160                                  struct page *page, u64 pos,
1161                                  bool force_uptodate)
1162 {
1163         struct folio *folio = page_folio(page);
1164         int ret = 0;
1165
1166         if (((pos & (PAGE_SIZE - 1)) || force_uptodate) &&
1167             !PageUptodate(page)) {
1168                 ret = btrfs_read_folio(NULL, folio);
1169                 if (ret)
1170                         return ret;
1171                 lock_page(page);
1172                 if (!PageUptodate(page)) {
1173                         unlock_page(page);
1174                         return -EIO;
1175                 }
1176
1177                 /*
1178                  * Since btrfs_read_folio() will unlock the folio before it
1179                  * returns, there is a window where btrfs_release_folio() can be
1180                  * called to release the page.  Here we check both inode
1181                  * mapping and PagePrivate() to make sure the page was not
1182                  * released.
1183                  *
1184                  * The private flag check is essential for subpage as we need
1185                  * to store extra bitmap using page->private.
1186                  */
1187                 if (page->mapping != inode->i_mapping || !PagePrivate(page)) {
1188                         unlock_page(page);
1189                         return -EAGAIN;
1190                 }
1191         }
1192         return 0;
1193 }
1194
1195 static unsigned int get_prepare_fgp_flags(bool nowait)
1196 {
1197         unsigned int fgp_flags = FGP_LOCK | FGP_ACCESSED | FGP_CREAT;
1198
1199         if (nowait)
1200                 fgp_flags |= FGP_NOWAIT;
1201
1202         return fgp_flags;
1203 }
1204
1205 static gfp_t get_prepare_gfp_flags(struct inode *inode, bool nowait)
1206 {
1207         gfp_t gfp;
1208
1209         gfp = btrfs_alloc_write_mask(inode->i_mapping);
1210         if (nowait) {
1211                 gfp &= ~__GFP_DIRECT_RECLAIM;
1212                 gfp |= GFP_NOWAIT;
1213         }
1214
1215         return gfp;
1216 }
1217
1218 /*
1219  * this just gets pages into the page cache and locks them down.
1220  */
1221 static noinline int prepare_pages(struct inode *inode, struct page **pages,
1222                                   size_t num_pages, loff_t pos,
1223                                   size_t write_bytes, bool force_uptodate,
1224                                   bool nowait)
1225 {
1226         int i;
1227         unsigned long index = pos >> PAGE_SHIFT;
1228         gfp_t mask = get_prepare_gfp_flags(inode, nowait);
1229         unsigned int fgp_flags = get_prepare_fgp_flags(nowait);
1230         int err = 0;
1231         int faili;
1232
1233         for (i = 0; i < num_pages; i++) {
1234 again:
1235                 pages[i] = pagecache_get_page(inode->i_mapping, index + i,
1236                                               fgp_flags, mask | __GFP_WRITE);
1237                 if (!pages[i]) {
1238                         faili = i - 1;
1239                         if (nowait)
1240                                 err = -EAGAIN;
1241                         else
1242                                 err = -ENOMEM;
1243                         goto fail;
1244                 }
1245
1246                 err = set_page_extent_mapped(pages[i]);
1247                 if (err < 0) {
1248                         faili = i;
1249                         goto fail;
1250                 }
1251
1252                 if (i == 0)
1253                         err = prepare_uptodate_page(inode, pages[i], pos,
1254                                                     force_uptodate);
1255                 if (!err && i == num_pages - 1)
1256                         err = prepare_uptodate_page(inode, pages[i],
1257                                                     pos + write_bytes, false);
1258                 if (err) {
1259                         put_page(pages[i]);
1260                         if (!nowait && err == -EAGAIN) {
1261                                 err = 0;
1262                                 goto again;
1263                         }
1264                         faili = i - 1;
1265                         goto fail;
1266                 }
1267                 wait_on_page_writeback(pages[i]);
1268         }
1269
1270         return 0;
1271 fail:
1272         while (faili >= 0) {
1273                 unlock_page(pages[faili]);
1274                 put_page(pages[faili]);
1275                 faili--;
1276         }
1277         return err;
1278
1279 }
1280
1281 /*
1282  * This function locks the extent and properly waits for data=ordered extents
1283  * to finish before allowing the pages to be modified if need.
1284  *
1285  * The return value:
1286  * 1 - the extent is locked
1287  * 0 - the extent is not locked, and everything is OK
1288  * -EAGAIN - need re-prepare the pages
1289  * the other < 0 number - Something wrong happens
1290  */
1291 static noinline int
1292 lock_and_cleanup_extent_if_need(struct btrfs_inode *inode, struct page **pages,
1293                                 size_t num_pages, loff_t pos,
1294                                 size_t write_bytes,
1295                                 u64 *lockstart, u64 *lockend, bool nowait,
1296                                 struct extent_state **cached_state)
1297 {
1298         struct btrfs_fs_info *fs_info = inode->root->fs_info;
1299         u64 start_pos;
1300         u64 last_pos;
1301         int i;
1302         int ret = 0;
1303
1304         start_pos = round_down(pos, fs_info->sectorsize);
1305         last_pos = round_up(pos + write_bytes, fs_info->sectorsize) - 1;
1306
1307         if (start_pos < inode->vfs_inode.i_size) {
1308                 struct btrfs_ordered_extent *ordered;
1309
1310                 if (nowait) {
1311                         if (!try_lock_extent(&inode->io_tree, start_pos, last_pos)) {
1312                                 for (i = 0; i < num_pages; i++) {
1313                                         unlock_page(pages[i]);
1314                                         put_page(pages[i]);
1315                                         pages[i] = NULL;
1316                                 }
1317
1318                                 return -EAGAIN;
1319                         }
1320                 } else {
1321                         lock_extent(&inode->io_tree, start_pos, last_pos, cached_state);
1322                 }
1323
1324                 ordered = btrfs_lookup_ordered_range(inode, start_pos,
1325                                                      last_pos - start_pos + 1);
1326                 if (ordered &&
1327                     ordered->file_offset + ordered->num_bytes > start_pos &&
1328                     ordered->file_offset <= last_pos) {
1329                         unlock_extent(&inode->io_tree, start_pos, last_pos,
1330                                       cached_state);
1331                         for (i = 0; i < num_pages; i++) {
1332                                 unlock_page(pages[i]);
1333                                 put_page(pages[i]);
1334                         }
1335                         btrfs_start_ordered_extent(ordered, 1);
1336                         btrfs_put_ordered_extent(ordered);
1337                         return -EAGAIN;
1338                 }
1339                 if (ordered)
1340                         btrfs_put_ordered_extent(ordered);
1341
1342                 *lockstart = start_pos;
1343                 *lockend = last_pos;
1344                 ret = 1;
1345         }
1346
1347         /*
1348          * We should be called after prepare_pages() which should have locked
1349          * all pages in the range.
1350          */
1351         for (i = 0; i < num_pages; i++)
1352                 WARN_ON(!PageLocked(pages[i]));
1353
1354         return ret;
1355 }
1356
1357 /*
1358  * Check if we can do nocow write into the range [@pos, @pos + @write_bytes)
1359  *
1360  * @pos:         File offset.
1361  * @write_bytes: The length to write, will be updated to the nocow writeable
1362  *               range.
1363  *
1364  * This function will flush ordered extents in the range to ensure proper
1365  * nocow checks.
1366  *
1367  * Return:
1368  * > 0          If we can nocow, and updates @write_bytes.
1369  *  0           If we can't do a nocow write.
1370  * -EAGAIN      If we can't do a nocow write because snapshoting of the inode's
1371  *              root is in progress.
1372  * < 0          If an error happened.
1373  *
1374  * NOTE: Callers need to call btrfs_check_nocow_unlock() if we return > 0.
1375  */
1376 int btrfs_check_nocow_lock(struct btrfs_inode *inode, loff_t pos,
1377                            size_t *write_bytes, bool nowait)
1378 {
1379         struct btrfs_fs_info *fs_info = inode->root->fs_info;
1380         struct btrfs_root *root = inode->root;
1381         u64 lockstart, lockend;
1382         u64 num_bytes;
1383         int ret;
1384
1385         if (!(inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
1386                 return 0;
1387
1388         if (!btrfs_drew_try_write_lock(&root->snapshot_lock))
1389                 return -EAGAIN;
1390
1391         lockstart = round_down(pos, fs_info->sectorsize);
1392         lockend = round_up(pos + *write_bytes,
1393                            fs_info->sectorsize) - 1;
1394         num_bytes = lockend - lockstart + 1;
1395
1396         if (nowait) {
1397                 if (!btrfs_try_lock_ordered_range(inode, lockstart, lockend)) {
1398                         btrfs_drew_write_unlock(&root->snapshot_lock);
1399                         return -EAGAIN;
1400                 }
1401         } else {
1402                 btrfs_lock_and_flush_ordered_range(inode, lockstart, lockend, NULL);
1403         }
1404         ret = can_nocow_extent(&inode->vfs_inode, lockstart, &num_bytes,
1405                         NULL, NULL, NULL, nowait, false);
1406         if (ret <= 0)
1407                 btrfs_drew_write_unlock(&root->snapshot_lock);
1408         else
1409                 *write_bytes = min_t(size_t, *write_bytes ,
1410                                      num_bytes - pos + lockstart);
1411         unlock_extent(&inode->io_tree, lockstart, lockend, NULL);
1412
1413         return ret;
1414 }
1415
1416 void btrfs_check_nocow_unlock(struct btrfs_inode *inode)
1417 {
1418         btrfs_drew_write_unlock(&inode->root->snapshot_lock);
1419 }
1420
1421 static void update_time_for_write(struct inode *inode)
1422 {
1423         struct timespec64 now;
1424
1425         if (IS_NOCMTIME(inode))
1426                 return;
1427
1428         now = current_time(inode);
1429         if (!timespec64_equal(&inode->i_mtime, &now))
1430                 inode->i_mtime = now;
1431
1432         if (!timespec64_equal(&inode->i_ctime, &now))
1433                 inode->i_ctime = now;
1434
1435         if (IS_I_VERSION(inode))
1436                 inode_inc_iversion(inode);
1437 }
1438
1439 static int btrfs_write_check(struct kiocb *iocb, struct iov_iter *from,
1440                              size_t count)
1441 {
1442         struct file *file = iocb->ki_filp;
1443         struct inode *inode = file_inode(file);
1444         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1445         loff_t pos = iocb->ki_pos;
1446         int ret;
1447         loff_t oldsize;
1448         loff_t start_pos;
1449
1450         /*
1451          * Quickly bail out on NOWAIT writes if we don't have the nodatacow or
1452          * prealloc flags, as without those flags we always have to COW. We will
1453          * later check if we can really COW into the target range (using
1454          * can_nocow_extent() at btrfs_get_blocks_direct_write()).
1455          */
1456         if ((iocb->ki_flags & IOCB_NOWAIT) &&
1457             !(BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
1458                 return -EAGAIN;
1459
1460         current->backing_dev_info = inode_to_bdi(inode);
1461         ret = file_remove_privs(file);
1462         if (ret)
1463                 return ret;
1464
1465         /*
1466          * We reserve space for updating the inode when we reserve space for the
1467          * extent we are going to write, so we will enospc out there.  We don't
1468          * need to start yet another transaction to update the inode as we will
1469          * update the inode when we finish writing whatever data we write.
1470          */
1471         update_time_for_write(inode);
1472
1473         start_pos = round_down(pos, fs_info->sectorsize);
1474         oldsize = i_size_read(inode);
1475         if (start_pos > oldsize) {
1476                 /* Expand hole size to cover write data, preventing empty gap */
1477                 loff_t end_pos = round_up(pos + count, fs_info->sectorsize);
1478
1479                 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, end_pos);
1480                 if (ret) {
1481                         current->backing_dev_info = NULL;
1482                         return ret;
1483                 }
1484         }
1485
1486         return 0;
1487 }
1488
1489 static noinline ssize_t btrfs_buffered_write(struct kiocb *iocb,
1490                                                struct iov_iter *i)
1491 {
1492         struct file *file = iocb->ki_filp;
1493         loff_t pos;
1494         struct inode *inode = file_inode(file);
1495         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1496         struct page **pages = NULL;
1497         struct extent_changeset *data_reserved = NULL;
1498         u64 release_bytes = 0;
1499         u64 lockstart;
1500         u64 lockend;
1501         size_t num_written = 0;
1502         int nrptrs;
1503         ssize_t ret;
1504         bool only_release_metadata = false;
1505         bool force_page_uptodate = false;
1506         loff_t old_isize = i_size_read(inode);
1507         unsigned int ilock_flags = 0;
1508         const bool nowait = (iocb->ki_flags & IOCB_NOWAIT);
1509         unsigned int bdp_flags = (nowait ? BDP_ASYNC : 0);
1510
1511         if (nowait)
1512                 ilock_flags |= BTRFS_ILOCK_TRY;
1513
1514         ret = btrfs_inode_lock(inode, ilock_flags);
1515         if (ret < 0)
1516                 return ret;
1517
1518         ret = generic_write_checks(iocb, i);
1519         if (ret <= 0)
1520                 goto out;
1521
1522         ret = btrfs_write_check(iocb, i, ret);
1523         if (ret < 0)
1524                 goto out;
1525
1526         pos = iocb->ki_pos;
1527         nrptrs = min(DIV_ROUND_UP(iov_iter_count(i), PAGE_SIZE),
1528                         PAGE_SIZE / (sizeof(struct page *)));
1529         nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
1530         nrptrs = max(nrptrs, 8);
1531         pages = kmalloc_array(nrptrs, sizeof(struct page *), GFP_KERNEL);
1532         if (!pages) {
1533                 ret = -ENOMEM;
1534                 goto out;
1535         }
1536
1537         while (iov_iter_count(i) > 0) {
1538                 struct extent_state *cached_state = NULL;
1539                 size_t offset = offset_in_page(pos);
1540                 size_t sector_offset;
1541                 size_t write_bytes = min(iov_iter_count(i),
1542                                          nrptrs * (size_t)PAGE_SIZE -
1543                                          offset);
1544                 size_t num_pages;
1545                 size_t reserve_bytes;
1546                 size_t dirty_pages;
1547                 size_t copied;
1548                 size_t dirty_sectors;
1549                 size_t num_sectors;
1550                 int extents_locked;
1551
1552                 /*
1553                  * Fault pages before locking them in prepare_pages
1554                  * to avoid recursive lock
1555                  */
1556                 if (unlikely(fault_in_iov_iter_readable(i, write_bytes))) {
1557                         ret = -EFAULT;
1558                         break;
1559                 }
1560
1561                 only_release_metadata = false;
1562                 sector_offset = pos & (fs_info->sectorsize - 1);
1563
1564                 extent_changeset_release(data_reserved);
1565                 ret = btrfs_check_data_free_space(BTRFS_I(inode),
1566                                                   &data_reserved, pos,
1567                                                   write_bytes, nowait);
1568                 if (ret < 0) {
1569                         int can_nocow;
1570
1571                         if (nowait && (ret == -ENOSPC || ret == -EAGAIN)) {
1572                                 ret = -EAGAIN;
1573                                 break;
1574                         }
1575
1576                         /*
1577                          * If we don't have to COW at the offset, reserve
1578                          * metadata only. write_bytes may get smaller than
1579                          * requested here.
1580                          */
1581                         can_nocow = btrfs_check_nocow_lock(BTRFS_I(inode), pos,
1582                                                            &write_bytes, nowait);
1583                         if (can_nocow < 0)
1584                                 ret = can_nocow;
1585                         if (can_nocow > 0)
1586                                 ret = 0;
1587                         if (ret)
1588                                 break;
1589                         only_release_metadata = true;
1590                 }
1591
1592                 num_pages = DIV_ROUND_UP(write_bytes + offset, PAGE_SIZE);
1593                 WARN_ON(num_pages > nrptrs);
1594                 reserve_bytes = round_up(write_bytes + sector_offset,
1595                                          fs_info->sectorsize);
1596                 WARN_ON(reserve_bytes == 0);
1597                 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
1598                                                       reserve_bytes,
1599                                                       reserve_bytes, nowait);
1600                 if (ret) {
1601                         if (!only_release_metadata)
1602                                 btrfs_free_reserved_data_space(BTRFS_I(inode),
1603                                                 data_reserved, pos,
1604                                                 write_bytes);
1605                         else
1606                                 btrfs_check_nocow_unlock(BTRFS_I(inode));
1607
1608                         if (nowait && ret == -ENOSPC)
1609                                 ret = -EAGAIN;
1610                         break;
1611                 }
1612
1613                 release_bytes = reserve_bytes;
1614 again:
1615                 ret = balance_dirty_pages_ratelimited_flags(inode->i_mapping, bdp_flags);
1616                 if (ret) {
1617                         btrfs_delalloc_release_extents(BTRFS_I(inode), reserve_bytes);
1618                         break;
1619                 }
1620
1621                 /*
1622                  * This is going to setup the pages array with the number of
1623                  * pages we want, so we don't really need to worry about the
1624                  * contents of pages from loop to loop
1625                  */
1626                 ret = prepare_pages(inode, pages, num_pages,
1627                                     pos, write_bytes, force_page_uptodate, false);
1628                 if (ret) {
1629                         btrfs_delalloc_release_extents(BTRFS_I(inode),
1630                                                        reserve_bytes);
1631                         break;
1632                 }
1633
1634                 extents_locked = lock_and_cleanup_extent_if_need(
1635                                 BTRFS_I(inode), pages,
1636                                 num_pages, pos, write_bytes, &lockstart,
1637                                 &lockend, nowait, &cached_state);
1638                 if (extents_locked < 0) {
1639                         if (!nowait && extents_locked == -EAGAIN)
1640                                 goto again;
1641
1642                         btrfs_delalloc_release_extents(BTRFS_I(inode),
1643                                                        reserve_bytes);
1644                         ret = extents_locked;
1645                         break;
1646                 }
1647
1648                 copied = btrfs_copy_from_user(pos, write_bytes, pages, i);
1649
1650                 num_sectors = BTRFS_BYTES_TO_BLKS(fs_info, reserve_bytes);
1651                 dirty_sectors = round_up(copied + sector_offset,
1652                                         fs_info->sectorsize);
1653                 dirty_sectors = BTRFS_BYTES_TO_BLKS(fs_info, dirty_sectors);
1654
1655                 /*
1656                  * if we have trouble faulting in the pages, fall
1657                  * back to one page at a time
1658                  */
1659                 if (copied < write_bytes)
1660                         nrptrs = 1;
1661
1662                 if (copied == 0) {
1663                         force_page_uptodate = true;
1664                         dirty_sectors = 0;
1665                         dirty_pages = 0;
1666                 } else {
1667                         force_page_uptodate = false;
1668                         dirty_pages = DIV_ROUND_UP(copied + offset,
1669                                                    PAGE_SIZE);
1670                 }
1671
1672                 if (num_sectors > dirty_sectors) {
1673                         /* release everything except the sectors we dirtied */
1674                         release_bytes -= dirty_sectors << fs_info->sectorsize_bits;
1675                         if (only_release_metadata) {
1676                                 btrfs_delalloc_release_metadata(BTRFS_I(inode),
1677                                                         release_bytes, true);
1678                         } else {
1679                                 u64 __pos;
1680
1681                                 __pos = round_down(pos,
1682                                                    fs_info->sectorsize) +
1683                                         (dirty_pages << PAGE_SHIFT);
1684                                 btrfs_delalloc_release_space(BTRFS_I(inode),
1685                                                 data_reserved, __pos,
1686                                                 release_bytes, true);
1687                         }
1688                 }
1689
1690                 release_bytes = round_up(copied + sector_offset,
1691                                         fs_info->sectorsize);
1692
1693                 ret = btrfs_dirty_pages(BTRFS_I(inode), pages,
1694                                         dirty_pages, pos, copied,
1695                                         &cached_state, only_release_metadata);
1696
1697                 /*
1698                  * If we have not locked the extent range, because the range's
1699                  * start offset is >= i_size, we might still have a non-NULL
1700                  * cached extent state, acquired while marking the extent range
1701                  * as delalloc through btrfs_dirty_pages(). Therefore free any
1702                  * possible cached extent state to avoid a memory leak.
1703                  */
1704                 if (extents_locked)
1705                         unlock_extent(&BTRFS_I(inode)->io_tree, lockstart,
1706                                       lockend, &cached_state);
1707                 else
1708                         free_extent_state(cached_state);
1709
1710                 btrfs_delalloc_release_extents(BTRFS_I(inode), reserve_bytes);
1711                 if (ret) {
1712                         btrfs_drop_pages(fs_info, pages, num_pages, pos, copied);
1713                         break;
1714                 }
1715
1716                 release_bytes = 0;
1717                 if (only_release_metadata)
1718                         btrfs_check_nocow_unlock(BTRFS_I(inode));
1719
1720                 btrfs_drop_pages(fs_info, pages, num_pages, pos, copied);
1721
1722                 cond_resched();
1723
1724                 pos += copied;
1725                 num_written += copied;
1726         }
1727
1728         kfree(pages);
1729
1730         if (release_bytes) {
1731                 if (only_release_metadata) {
1732                         btrfs_check_nocow_unlock(BTRFS_I(inode));
1733                         btrfs_delalloc_release_metadata(BTRFS_I(inode),
1734                                         release_bytes, true);
1735                 } else {
1736                         btrfs_delalloc_release_space(BTRFS_I(inode),
1737                                         data_reserved,
1738                                         round_down(pos, fs_info->sectorsize),
1739                                         release_bytes, true);
1740                 }
1741         }
1742
1743         extent_changeset_free(data_reserved);
1744         if (num_written > 0) {
1745                 pagecache_isize_extended(inode, old_isize, iocb->ki_pos);
1746                 iocb->ki_pos += num_written;
1747         }
1748 out:
1749         btrfs_inode_unlock(inode, ilock_flags);
1750         return num_written ? num_written : ret;
1751 }
1752
1753 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
1754                                const struct iov_iter *iter, loff_t offset)
1755 {
1756         const u32 blocksize_mask = fs_info->sectorsize - 1;
1757
1758         if (offset & blocksize_mask)
1759                 return -EINVAL;
1760
1761         if (iov_iter_alignment(iter) & blocksize_mask)
1762                 return -EINVAL;
1763
1764         return 0;
1765 }
1766
1767 static ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from)
1768 {
1769         struct file *file = iocb->ki_filp;
1770         struct inode *inode = file_inode(file);
1771         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1772         loff_t pos;
1773         ssize_t written = 0;
1774         ssize_t written_buffered;
1775         size_t prev_left = 0;
1776         loff_t endbyte;
1777         ssize_t err;
1778         unsigned int ilock_flags = 0;
1779         struct iomap_dio *dio;
1780
1781         if (iocb->ki_flags & IOCB_NOWAIT)
1782                 ilock_flags |= BTRFS_ILOCK_TRY;
1783
1784         /* If the write DIO is within EOF, use a shared lock */
1785         if (iocb->ki_pos + iov_iter_count(from) <= i_size_read(inode))
1786                 ilock_flags |= BTRFS_ILOCK_SHARED;
1787
1788 relock:
1789         err = btrfs_inode_lock(inode, ilock_flags);
1790         if (err < 0)
1791                 return err;
1792
1793         err = generic_write_checks(iocb, from);
1794         if (err <= 0) {
1795                 btrfs_inode_unlock(inode, ilock_flags);
1796                 return err;
1797         }
1798
1799         err = btrfs_write_check(iocb, from, err);
1800         if (err < 0) {
1801                 btrfs_inode_unlock(inode, ilock_flags);
1802                 goto out;
1803         }
1804
1805         pos = iocb->ki_pos;
1806         /*
1807          * Re-check since file size may have changed just before taking the
1808          * lock or pos may have changed because of O_APPEND in generic_write_check()
1809          */
1810         if ((ilock_flags & BTRFS_ILOCK_SHARED) &&
1811             pos + iov_iter_count(from) > i_size_read(inode)) {
1812                 btrfs_inode_unlock(inode, ilock_flags);
1813                 ilock_flags &= ~BTRFS_ILOCK_SHARED;
1814                 goto relock;
1815         }
1816
1817         if (check_direct_IO(fs_info, from, pos)) {
1818                 btrfs_inode_unlock(inode, ilock_flags);
1819                 goto buffered;
1820         }
1821
1822         /*
1823          * The iov_iter can be mapped to the same file range we are writing to.
1824          * If that's the case, then we will deadlock in the iomap code, because
1825          * it first calls our callback btrfs_dio_iomap_begin(), which will create
1826          * an ordered extent, and after that it will fault in the pages that the
1827          * iov_iter refers to. During the fault in we end up in the readahead
1828          * pages code (starting at btrfs_readahead()), which will lock the range,
1829          * find that ordered extent and then wait for it to complete (at
1830          * btrfs_lock_and_flush_ordered_range()), resulting in a deadlock since
1831          * obviously the ordered extent can never complete as we didn't submit
1832          * yet the respective bio(s). This always happens when the buffer is
1833          * memory mapped to the same file range, since the iomap DIO code always
1834          * invalidates pages in the target file range (after starting and waiting
1835          * for any writeback).
1836          *
1837          * So here we disable page faults in the iov_iter and then retry if we
1838          * got -EFAULT, faulting in the pages before the retry.
1839          */
1840         from->nofault = true;
1841         dio = btrfs_dio_write(iocb, from, written);
1842         from->nofault = false;
1843
1844         /*
1845          * iomap_dio_complete() will call btrfs_sync_file() if we have a dsync
1846          * iocb, and that needs to lock the inode. So unlock it before calling
1847          * iomap_dio_complete() to avoid a deadlock.
1848          */
1849         btrfs_inode_unlock(inode, ilock_flags);
1850
1851         if (IS_ERR_OR_NULL(dio))
1852                 err = PTR_ERR_OR_ZERO(dio);
1853         else
1854                 err = iomap_dio_complete(dio);
1855
1856         /* No increment (+=) because iomap returns a cumulative value. */
1857         if (err > 0)
1858                 written = err;
1859
1860         if (iov_iter_count(from) > 0 && (err == -EFAULT || err > 0)) {
1861                 const size_t left = iov_iter_count(from);
1862                 /*
1863                  * We have more data left to write. Try to fault in as many as
1864                  * possible of the remainder pages and retry. We do this without
1865                  * releasing and locking again the inode, to prevent races with
1866                  * truncate.
1867                  *
1868                  * Also, in case the iov refers to pages in the file range of the
1869                  * file we want to write to (due to a mmap), we could enter an
1870                  * infinite loop if we retry after faulting the pages in, since
1871                  * iomap will invalidate any pages in the range early on, before
1872                  * it tries to fault in the pages of the iov. So we keep track of
1873                  * how much was left of iov in the previous EFAULT and fallback
1874                  * to buffered IO in case we haven't made any progress.
1875                  */
1876                 if (left == prev_left) {
1877                         err = -ENOTBLK;
1878                 } else {
1879                         fault_in_iov_iter_readable(from, left);
1880                         prev_left = left;
1881                         goto relock;
1882                 }
1883         }
1884
1885         /*
1886          * If 'err' is -ENOTBLK or we have not written all data, then it means
1887          * we must fallback to buffered IO.
1888          */
1889         if ((err < 0 && err != -ENOTBLK) || !iov_iter_count(from))
1890                 goto out;
1891
1892 buffered:
1893         /*
1894          * If we are in a NOWAIT context, then return -EAGAIN to signal the caller
1895          * it must retry the operation in a context where blocking is acceptable,
1896          * since we currently don't have NOWAIT semantics support for buffered IO
1897          * and may block there for many reasons (reserving space for example).
1898          */
1899         if (iocb->ki_flags & IOCB_NOWAIT) {
1900                 err = -EAGAIN;
1901                 goto out;
1902         }
1903
1904         pos = iocb->ki_pos;
1905         written_buffered = btrfs_buffered_write(iocb, from);
1906         if (written_buffered < 0) {
1907                 err = written_buffered;
1908                 goto out;
1909         }
1910         /*
1911          * Ensure all data is persisted. We want the next direct IO read to be
1912          * able to read what was just written.
1913          */
1914         endbyte = pos + written_buffered - 1;
1915         err = btrfs_fdatawrite_range(inode, pos, endbyte);
1916         if (err)
1917                 goto out;
1918         err = filemap_fdatawait_range(inode->i_mapping, pos, endbyte);
1919         if (err)
1920                 goto out;
1921         written += written_buffered;
1922         iocb->ki_pos = pos + written_buffered;
1923         invalidate_mapping_pages(file->f_mapping, pos >> PAGE_SHIFT,
1924                                  endbyte >> PAGE_SHIFT);
1925 out:
1926         return err < 0 ? err : written;
1927 }
1928
1929 static ssize_t btrfs_encoded_write(struct kiocb *iocb, struct iov_iter *from,
1930                         const struct btrfs_ioctl_encoded_io_args *encoded)
1931 {
1932         struct file *file = iocb->ki_filp;
1933         struct inode *inode = file_inode(file);
1934         loff_t count;
1935         ssize_t ret;
1936
1937         btrfs_inode_lock(inode, 0);
1938         count = encoded->len;
1939         ret = generic_write_checks_count(iocb, &count);
1940         if (ret == 0 && count != encoded->len) {
1941                 /*
1942                  * The write got truncated by generic_write_checks_count(). We
1943                  * can't do a partial encoded write.
1944                  */
1945                 ret = -EFBIG;
1946         }
1947         if (ret || encoded->len == 0)
1948                 goto out;
1949
1950         ret = btrfs_write_check(iocb, from, encoded->len);
1951         if (ret < 0)
1952                 goto out;
1953
1954         ret = btrfs_do_encoded_write(iocb, from, encoded);
1955 out:
1956         btrfs_inode_unlock(inode, 0);
1957         return ret;
1958 }
1959
1960 ssize_t btrfs_do_write_iter(struct kiocb *iocb, struct iov_iter *from,
1961                             const struct btrfs_ioctl_encoded_io_args *encoded)
1962 {
1963         struct file *file = iocb->ki_filp;
1964         struct btrfs_inode *inode = BTRFS_I(file_inode(file));
1965         ssize_t num_written, num_sync;
1966         const bool sync = iocb_is_dsync(iocb);
1967
1968         /*
1969          * If the fs flips readonly due to some impossible error, although we
1970          * have opened a file as writable, we have to stop this write operation
1971          * to ensure consistency.
1972          */
1973         if (BTRFS_FS_ERROR(inode->root->fs_info))
1974                 return -EROFS;
1975
1976         if (encoded && (iocb->ki_flags & IOCB_NOWAIT))
1977                 return -EOPNOTSUPP;
1978
1979         if (sync)
1980                 atomic_inc(&inode->sync_writers);
1981
1982         if (encoded) {
1983                 num_written = btrfs_encoded_write(iocb, from, encoded);
1984                 num_sync = encoded->len;
1985         } else if (iocb->ki_flags & IOCB_DIRECT) {
1986                 num_written = btrfs_direct_write(iocb, from);
1987                 num_sync = num_written;
1988         } else {
1989                 num_written = btrfs_buffered_write(iocb, from);
1990                 num_sync = num_written;
1991         }
1992
1993         btrfs_set_inode_last_sub_trans(inode);
1994
1995         if (num_sync > 0) {
1996                 num_sync = generic_write_sync(iocb, num_sync);
1997                 if (num_sync < 0)
1998                         num_written = num_sync;
1999         }
2000
2001         if (sync)
2002                 atomic_dec(&inode->sync_writers);
2003
2004         current->backing_dev_info = NULL;
2005         return num_written;
2006 }
2007
2008 static ssize_t btrfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
2009 {
2010         return btrfs_do_write_iter(iocb, from, NULL);
2011 }
2012
2013 int btrfs_release_file(struct inode *inode, struct file *filp)
2014 {
2015         struct btrfs_file_private *private = filp->private_data;
2016
2017         if (private && private->filldir_buf)
2018                 kfree(private->filldir_buf);
2019         kfree(private);
2020         filp->private_data = NULL;
2021
2022         /*
2023          * Set by setattr when we are about to truncate a file from a non-zero
2024          * size to a zero size.  This tries to flush down new bytes that may
2025          * have been written if the application were using truncate to replace
2026          * a file in place.
2027          */
2028         if (test_and_clear_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
2029                                &BTRFS_I(inode)->runtime_flags))
2030                         filemap_flush(inode->i_mapping);
2031         return 0;
2032 }
2033
2034 static int start_ordered_ops(struct inode *inode, loff_t start, loff_t end)
2035 {
2036         int ret;
2037         struct blk_plug plug;
2038
2039         /*
2040          * This is only called in fsync, which would do synchronous writes, so
2041          * a plug can merge adjacent IOs as much as possible.  Esp. in case of
2042          * multiple disks using raid profile, a large IO can be split to
2043          * several segments of stripe length (currently 64K).
2044          */
2045         blk_start_plug(&plug);
2046         atomic_inc(&BTRFS_I(inode)->sync_writers);
2047         ret = btrfs_fdatawrite_range(inode, start, end);
2048         atomic_dec(&BTRFS_I(inode)->sync_writers);
2049         blk_finish_plug(&plug);
2050
2051         return ret;
2052 }
2053
2054 static inline bool skip_inode_logging(const struct btrfs_log_ctx *ctx)
2055 {
2056         struct btrfs_inode *inode = BTRFS_I(ctx->inode);
2057         struct btrfs_fs_info *fs_info = inode->root->fs_info;
2058
2059         if (btrfs_inode_in_log(inode, fs_info->generation) &&
2060             list_empty(&ctx->ordered_extents))
2061                 return true;
2062
2063         /*
2064          * If we are doing a fast fsync we can not bail out if the inode's
2065          * last_trans is <= then the last committed transaction, because we only
2066          * update the last_trans of the inode during ordered extent completion,
2067          * and for a fast fsync we don't wait for that, we only wait for the
2068          * writeback to complete.
2069          */
2070         if (inode->last_trans <= fs_info->last_trans_committed &&
2071             (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags) ||
2072              list_empty(&ctx->ordered_extents)))
2073                 return true;
2074
2075         return false;
2076 }
2077
2078 /*
2079  * fsync call for both files and directories.  This logs the inode into
2080  * the tree log instead of forcing full commits whenever possible.
2081  *
2082  * It needs to call filemap_fdatawait so that all ordered extent updates are
2083  * in the metadata btree are up to date for copying to the log.
2084  *
2085  * It drops the inode mutex before doing the tree log commit.  This is an
2086  * important optimization for directories because holding the mutex prevents
2087  * new operations on the dir while we write to disk.
2088  */
2089 int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
2090 {
2091         struct dentry *dentry = file_dentry(file);
2092         struct inode *inode = d_inode(dentry);
2093         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2094         struct btrfs_root *root = BTRFS_I(inode)->root;
2095         struct btrfs_trans_handle *trans;
2096         struct btrfs_log_ctx ctx;
2097         int ret = 0, err;
2098         u64 len;
2099         bool full_sync;
2100
2101         trace_btrfs_sync_file(file, datasync);
2102
2103         btrfs_init_log_ctx(&ctx, inode);
2104
2105         /*
2106          * Always set the range to a full range, otherwise we can get into
2107          * several problems, from missing file extent items to represent holes
2108          * when not using the NO_HOLES feature, to log tree corruption due to
2109          * races between hole detection during logging and completion of ordered
2110          * extents outside the range, to missing checksums due to ordered extents
2111          * for which we flushed only a subset of their pages.
2112          */
2113         start = 0;
2114         end = LLONG_MAX;
2115         len = (u64)LLONG_MAX + 1;
2116
2117         /*
2118          * We write the dirty pages in the range and wait until they complete
2119          * out of the ->i_mutex. If so, we can flush the dirty pages by
2120          * multi-task, and make the performance up.  See
2121          * btrfs_wait_ordered_range for an explanation of the ASYNC check.
2122          */
2123         ret = start_ordered_ops(inode, start, end);
2124         if (ret)
2125                 goto out;
2126
2127         btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
2128
2129         atomic_inc(&root->log_batch);
2130
2131         /*
2132          * Before we acquired the inode's lock and the mmap lock, someone may
2133          * have dirtied more pages in the target range. We need to make sure
2134          * that writeback for any such pages does not start while we are logging
2135          * the inode, because if it does, any of the following might happen when
2136          * we are not doing a full inode sync:
2137          *
2138          * 1) We log an extent after its writeback finishes but before its
2139          *    checksums are added to the csum tree, leading to -EIO errors
2140          *    when attempting to read the extent after a log replay.
2141          *
2142          * 2) We can end up logging an extent before its writeback finishes.
2143          *    Therefore after the log replay we will have a file extent item
2144          *    pointing to an unwritten extent (and no data checksums as well).
2145          *
2146          * So trigger writeback for any eventual new dirty pages and then we
2147          * wait for all ordered extents to complete below.
2148          */
2149         ret = start_ordered_ops(inode, start, end);
2150         if (ret) {
2151                 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
2152                 goto out;
2153         }
2154
2155         /*
2156          * Always check for the full sync flag while holding the inode's lock,
2157          * to avoid races with other tasks. The flag must be either set all the
2158          * time during logging or always off all the time while logging.
2159          * We check the flag here after starting delalloc above, because when
2160          * running delalloc the full sync flag may be set if we need to drop
2161          * extra extent map ranges due to temporary memory allocation failures.
2162          */
2163         full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2164                              &BTRFS_I(inode)->runtime_flags);
2165
2166         /*
2167          * We have to do this here to avoid the priority inversion of waiting on
2168          * IO of a lower priority task while holding a transaction open.
2169          *
2170          * For a full fsync we wait for the ordered extents to complete while
2171          * for a fast fsync we wait just for writeback to complete, and then
2172          * attach the ordered extents to the transaction so that a transaction
2173          * commit waits for their completion, to avoid data loss if we fsync,
2174          * the current transaction commits before the ordered extents complete
2175          * and a power failure happens right after that.
2176          *
2177          * For zoned filesystem, if a write IO uses a ZONE_APPEND command, the
2178          * logical address recorded in the ordered extent may change. We need
2179          * to wait for the IO to stabilize the logical address.
2180          */
2181         if (full_sync || btrfs_is_zoned(fs_info)) {
2182                 ret = btrfs_wait_ordered_range(inode, start, len);
2183         } else {
2184                 /*
2185                  * Get our ordered extents as soon as possible to avoid doing
2186                  * checksum lookups in the csum tree, and use instead the
2187                  * checksums attached to the ordered extents.
2188                  */
2189                 btrfs_get_ordered_extents_for_logging(BTRFS_I(inode),
2190                                                       &ctx.ordered_extents);
2191                 ret = filemap_fdatawait_range(inode->i_mapping, start, end);
2192         }
2193
2194         if (ret)
2195                 goto out_release_extents;
2196
2197         atomic_inc(&root->log_batch);
2198
2199         smp_mb();
2200         if (skip_inode_logging(&ctx)) {
2201                 /*
2202                  * We've had everything committed since the last time we were
2203                  * modified so clear this flag in case it was set for whatever
2204                  * reason, it's no longer relevant.
2205                  */
2206                 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2207                           &BTRFS_I(inode)->runtime_flags);
2208                 /*
2209                  * An ordered extent might have started before and completed
2210                  * already with io errors, in which case the inode was not
2211                  * updated and we end up here. So check the inode's mapping
2212                  * for any errors that might have happened since we last
2213                  * checked called fsync.
2214                  */
2215                 ret = filemap_check_wb_err(inode->i_mapping, file->f_wb_err);
2216                 goto out_release_extents;
2217         }
2218
2219         /*
2220          * We use start here because we will need to wait on the IO to complete
2221          * in btrfs_sync_log, which could require joining a transaction (for
2222          * example checking cross references in the nocow path).  If we use join
2223          * here we could get into a situation where we're waiting on IO to
2224          * happen that is blocked on a transaction trying to commit.  With start
2225          * we inc the extwriter counter, so we wait for all extwriters to exit
2226          * before we start blocking joiners.  This comment is to keep somebody
2227          * from thinking they are super smart and changing this to
2228          * btrfs_join_transaction *cough*Josef*cough*.
2229          */
2230         trans = btrfs_start_transaction(root, 0);
2231         if (IS_ERR(trans)) {
2232                 ret = PTR_ERR(trans);
2233                 goto out_release_extents;
2234         }
2235         trans->in_fsync = true;
2236
2237         ret = btrfs_log_dentry_safe(trans, dentry, &ctx);
2238         btrfs_release_log_ctx_extents(&ctx);
2239         if (ret < 0) {
2240                 /* Fallthrough and commit/free transaction. */
2241                 ret = BTRFS_LOG_FORCE_COMMIT;
2242         }
2243
2244         /* we've logged all the items and now have a consistent
2245          * version of the file in the log.  It is possible that
2246          * someone will come in and modify the file, but that's
2247          * fine because the log is consistent on disk, and we
2248          * have references to all of the file's extents
2249          *
2250          * It is possible that someone will come in and log the
2251          * file again, but that will end up using the synchronization
2252          * inside btrfs_sync_log to keep things safe.
2253          */
2254         btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
2255
2256         if (ret == BTRFS_NO_LOG_SYNC) {
2257                 ret = btrfs_end_transaction(trans);
2258                 goto out;
2259         }
2260
2261         /* We successfully logged the inode, attempt to sync the log. */
2262         if (!ret) {
2263                 ret = btrfs_sync_log(trans, root, &ctx);
2264                 if (!ret) {
2265                         ret = btrfs_end_transaction(trans);
2266                         goto out;
2267                 }
2268         }
2269
2270         /*
2271          * At this point we need to commit the transaction because we had
2272          * btrfs_need_log_full_commit() or some other error.
2273          *
2274          * If we didn't do a full sync we have to stop the trans handle, wait on
2275          * the ordered extents, start it again and commit the transaction.  If
2276          * we attempt to wait on the ordered extents here we could deadlock with
2277          * something like fallocate() that is holding the extent lock trying to
2278          * start a transaction while some other thread is trying to commit the
2279          * transaction while we (fsync) are currently holding the transaction
2280          * open.
2281          */
2282         if (!full_sync) {
2283                 ret = btrfs_end_transaction(trans);
2284                 if (ret)
2285                         goto out;
2286                 ret = btrfs_wait_ordered_range(inode, start, len);
2287                 if (ret)
2288                         goto out;
2289
2290                 /*
2291                  * This is safe to use here because we're only interested in
2292                  * making sure the transaction that had the ordered extents is
2293                  * committed.  We aren't waiting on anything past this point,
2294                  * we're purely getting the transaction and committing it.
2295                  */
2296                 trans = btrfs_attach_transaction_barrier(root);
2297                 if (IS_ERR(trans)) {
2298                         ret = PTR_ERR(trans);
2299
2300                         /*
2301                          * We committed the transaction and there's no currently
2302                          * running transaction, this means everything we care
2303                          * about made it to disk and we are done.
2304                          */
2305                         if (ret == -ENOENT)
2306                                 ret = 0;
2307                         goto out;
2308                 }
2309         }
2310
2311         ret = btrfs_commit_transaction(trans);
2312 out:
2313         ASSERT(list_empty(&ctx.list));
2314         ASSERT(list_empty(&ctx.conflict_inodes));
2315         err = file_check_and_advance_wb_err(file);
2316         if (!ret)
2317                 ret = err;
2318         return ret > 0 ? -EIO : ret;
2319
2320 out_release_extents:
2321         btrfs_release_log_ctx_extents(&ctx);
2322         btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
2323         goto out;
2324 }
2325
2326 static const struct vm_operations_struct btrfs_file_vm_ops = {
2327         .fault          = filemap_fault,
2328         .map_pages      = filemap_map_pages,
2329         .page_mkwrite   = btrfs_page_mkwrite,
2330 };
2331
2332 static int btrfs_file_mmap(struct file  *filp, struct vm_area_struct *vma)
2333 {
2334         struct address_space *mapping = filp->f_mapping;
2335
2336         if (!mapping->a_ops->read_folio)
2337                 return -ENOEXEC;
2338
2339         file_accessed(filp);
2340         vma->vm_ops = &btrfs_file_vm_ops;
2341
2342         return 0;
2343 }
2344
2345 static int hole_mergeable(struct btrfs_inode *inode, struct extent_buffer *leaf,
2346                           int slot, u64 start, u64 end)
2347 {
2348         struct btrfs_file_extent_item *fi;
2349         struct btrfs_key key;
2350
2351         if (slot < 0 || slot >= btrfs_header_nritems(leaf))
2352                 return 0;
2353
2354         btrfs_item_key_to_cpu(leaf, &key, slot);
2355         if (key.objectid != btrfs_ino(inode) ||
2356             key.type != BTRFS_EXTENT_DATA_KEY)
2357                 return 0;
2358
2359         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
2360
2361         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2362                 return 0;
2363
2364         if (btrfs_file_extent_disk_bytenr(leaf, fi))
2365                 return 0;
2366
2367         if (key.offset == end)
2368                 return 1;
2369         if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
2370                 return 1;
2371         return 0;
2372 }
2373
2374 static int fill_holes(struct btrfs_trans_handle *trans,
2375                 struct btrfs_inode *inode,
2376                 struct btrfs_path *path, u64 offset, u64 end)
2377 {
2378         struct btrfs_fs_info *fs_info = trans->fs_info;
2379         struct btrfs_root *root = inode->root;
2380         struct extent_buffer *leaf;
2381         struct btrfs_file_extent_item *fi;
2382         struct extent_map *hole_em;
2383         struct btrfs_key key;
2384         int ret;
2385
2386         if (btrfs_fs_incompat(fs_info, NO_HOLES))
2387                 goto out;
2388
2389         key.objectid = btrfs_ino(inode);
2390         key.type = BTRFS_EXTENT_DATA_KEY;
2391         key.offset = offset;
2392
2393         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2394         if (ret <= 0) {
2395                 /*
2396                  * We should have dropped this offset, so if we find it then
2397                  * something has gone horribly wrong.
2398                  */
2399                 if (ret == 0)
2400                         ret = -EINVAL;
2401                 return ret;
2402         }
2403
2404         leaf = path->nodes[0];
2405         if (hole_mergeable(inode, leaf, path->slots[0] - 1, offset, end)) {
2406                 u64 num_bytes;
2407
2408                 path->slots[0]--;
2409                 fi = btrfs_item_ptr(leaf, path->slots[0],
2410                                     struct btrfs_file_extent_item);
2411                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
2412                         end - offset;
2413                 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2414                 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
2415                 btrfs_set_file_extent_offset(leaf, fi, 0);
2416                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2417                 btrfs_mark_buffer_dirty(leaf);
2418                 goto out;
2419         }
2420
2421         if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
2422                 u64 num_bytes;
2423
2424                 key.offset = offset;
2425                 btrfs_set_item_key_safe(fs_info, path, &key);
2426                 fi = btrfs_item_ptr(leaf, path->slots[0],
2427                                     struct btrfs_file_extent_item);
2428                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
2429                         offset;
2430                 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2431                 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
2432                 btrfs_set_file_extent_offset(leaf, fi, 0);
2433                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2434                 btrfs_mark_buffer_dirty(leaf);
2435                 goto out;
2436         }
2437         btrfs_release_path(path);
2438
2439         ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset,
2440                                        end - offset);
2441         if (ret)
2442                 return ret;
2443
2444 out:
2445         btrfs_release_path(path);
2446
2447         hole_em = alloc_extent_map();
2448         if (!hole_em) {
2449                 btrfs_drop_extent_map_range(inode, offset, end - 1, false);
2450                 btrfs_set_inode_full_sync(inode);
2451         } else {
2452                 hole_em->start = offset;
2453                 hole_em->len = end - offset;
2454                 hole_em->ram_bytes = hole_em->len;
2455                 hole_em->orig_start = offset;
2456
2457                 hole_em->block_start = EXTENT_MAP_HOLE;
2458                 hole_em->block_len = 0;
2459                 hole_em->orig_block_len = 0;
2460                 hole_em->compress_type = BTRFS_COMPRESS_NONE;
2461                 hole_em->generation = trans->transid;
2462
2463                 ret = btrfs_replace_extent_map_range(inode, hole_em, true);
2464                 free_extent_map(hole_em);
2465                 if (ret)
2466                         btrfs_set_inode_full_sync(inode);
2467         }
2468
2469         return 0;
2470 }
2471
2472 /*
2473  * Find a hole extent on given inode and change start/len to the end of hole
2474  * extent.(hole/vacuum extent whose em->start <= start &&
2475  *         em->start + em->len > start)
2476  * When a hole extent is found, return 1 and modify start/len.
2477  */
2478 static int find_first_non_hole(struct btrfs_inode *inode, u64 *start, u64 *len)
2479 {
2480         struct btrfs_fs_info *fs_info = inode->root->fs_info;
2481         struct extent_map *em;
2482         int ret = 0;
2483
2484         em = btrfs_get_extent(inode, NULL, 0,
2485                               round_down(*start, fs_info->sectorsize),
2486                               round_up(*len, fs_info->sectorsize));
2487         if (IS_ERR(em))
2488                 return PTR_ERR(em);
2489
2490         /* Hole or vacuum extent(only exists in no-hole mode) */
2491         if (em->block_start == EXTENT_MAP_HOLE) {
2492                 ret = 1;
2493                 *len = em->start + em->len > *start + *len ?
2494                        0 : *start + *len - em->start - em->len;
2495                 *start = em->start + em->len;
2496         }
2497         free_extent_map(em);
2498         return ret;
2499 }
2500
2501 static void btrfs_punch_hole_lock_range(struct inode *inode,
2502                                         const u64 lockstart,
2503                                         const u64 lockend,
2504                                         struct extent_state **cached_state)
2505 {
2506         /*
2507          * For subpage case, if the range is not at page boundary, we could
2508          * have pages at the leading/tailing part of the range.
2509          * This could lead to dead loop since filemap_range_has_page()
2510          * will always return true.
2511          * So here we need to do extra page alignment for
2512          * filemap_range_has_page().
2513          */
2514         const u64 page_lockstart = round_up(lockstart, PAGE_SIZE);
2515         const u64 page_lockend = round_down(lockend + 1, PAGE_SIZE) - 1;
2516
2517         while (1) {
2518                 truncate_pagecache_range(inode, lockstart, lockend);
2519
2520                 lock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2521                             cached_state);
2522                 /*
2523                  * We can't have ordered extents in the range, nor dirty/writeback
2524                  * pages, because we have locked the inode's VFS lock in exclusive
2525                  * mode, we have locked the inode's i_mmap_lock in exclusive mode,
2526                  * we have flushed all delalloc in the range and we have waited
2527                  * for any ordered extents in the range to complete.
2528                  * We can race with anyone reading pages from this range, so after
2529                  * locking the range check if we have pages in the range, and if
2530                  * we do, unlock the range and retry.
2531                  */
2532                 if (!filemap_range_has_page(inode->i_mapping, page_lockstart,
2533                                             page_lockend))
2534                         break;
2535
2536                 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2537                               cached_state);
2538         }
2539
2540         btrfs_assert_inode_range_clean(BTRFS_I(inode), lockstart, lockend);
2541 }
2542
2543 static int btrfs_insert_replace_extent(struct btrfs_trans_handle *trans,
2544                                      struct btrfs_inode *inode,
2545                                      struct btrfs_path *path,
2546                                      struct btrfs_replace_extent_info *extent_info,
2547                                      const u64 replace_len,
2548                                      const u64 bytes_to_drop)
2549 {
2550         struct btrfs_fs_info *fs_info = trans->fs_info;
2551         struct btrfs_root *root = inode->root;
2552         struct btrfs_file_extent_item *extent;
2553         struct extent_buffer *leaf;
2554         struct btrfs_key key;
2555         int slot;
2556         struct btrfs_ref ref = { 0 };
2557         int ret;
2558
2559         if (replace_len == 0)
2560                 return 0;
2561
2562         if (extent_info->disk_offset == 0 &&
2563             btrfs_fs_incompat(fs_info, NO_HOLES)) {
2564                 btrfs_update_inode_bytes(inode, 0, bytes_to_drop);
2565                 return 0;
2566         }
2567
2568         key.objectid = btrfs_ino(inode);
2569         key.type = BTRFS_EXTENT_DATA_KEY;
2570         key.offset = extent_info->file_offset;
2571         ret = btrfs_insert_empty_item(trans, root, path, &key,
2572                                       sizeof(struct btrfs_file_extent_item));
2573         if (ret)
2574                 return ret;
2575         leaf = path->nodes[0];
2576         slot = path->slots[0];
2577         write_extent_buffer(leaf, extent_info->extent_buf,
2578                             btrfs_item_ptr_offset(leaf, slot),
2579                             sizeof(struct btrfs_file_extent_item));
2580         extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
2581         ASSERT(btrfs_file_extent_type(leaf, extent) != BTRFS_FILE_EXTENT_INLINE);
2582         btrfs_set_file_extent_offset(leaf, extent, extent_info->data_offset);
2583         btrfs_set_file_extent_num_bytes(leaf, extent, replace_len);
2584         if (extent_info->is_new_extent)
2585                 btrfs_set_file_extent_generation(leaf, extent, trans->transid);
2586         btrfs_mark_buffer_dirty(leaf);
2587         btrfs_release_path(path);
2588
2589         ret = btrfs_inode_set_file_extent_range(inode, extent_info->file_offset,
2590                                                 replace_len);
2591         if (ret)
2592                 return ret;
2593
2594         /* If it's a hole, nothing more needs to be done. */
2595         if (extent_info->disk_offset == 0) {
2596                 btrfs_update_inode_bytes(inode, 0, bytes_to_drop);
2597                 return 0;
2598         }
2599
2600         btrfs_update_inode_bytes(inode, replace_len, bytes_to_drop);
2601
2602         if (extent_info->is_new_extent && extent_info->insertions == 0) {
2603                 key.objectid = extent_info->disk_offset;
2604                 key.type = BTRFS_EXTENT_ITEM_KEY;
2605                 key.offset = extent_info->disk_len;
2606                 ret = btrfs_alloc_reserved_file_extent(trans, root,
2607                                                        btrfs_ino(inode),
2608                                                        extent_info->file_offset,
2609                                                        extent_info->qgroup_reserved,
2610                                                        &key);
2611         } else {
2612                 u64 ref_offset;
2613
2614                 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF,
2615                                        extent_info->disk_offset,
2616                                        extent_info->disk_len, 0);
2617                 ref_offset = extent_info->file_offset - extent_info->data_offset;
2618                 btrfs_init_data_ref(&ref, root->root_key.objectid,
2619                                     btrfs_ino(inode), ref_offset, 0, false);
2620                 ret = btrfs_inc_extent_ref(trans, &ref);
2621         }
2622
2623         extent_info->insertions++;
2624
2625         return ret;
2626 }
2627
2628 /*
2629  * The respective range must have been previously locked, as well as the inode.
2630  * The end offset is inclusive (last byte of the range).
2631  * @extent_info is NULL for fallocate's hole punching and non-NULL when replacing
2632  * the file range with an extent.
2633  * When not punching a hole, we don't want to end up in a state where we dropped
2634  * extents without inserting a new one, so we must abort the transaction to avoid
2635  * a corruption.
2636  */
2637 int btrfs_replace_file_extents(struct btrfs_inode *inode,
2638                                struct btrfs_path *path, const u64 start,
2639                                const u64 end,
2640                                struct btrfs_replace_extent_info *extent_info,
2641                                struct btrfs_trans_handle **trans_out)
2642 {
2643         struct btrfs_drop_extents_args drop_args = { 0 };
2644         struct btrfs_root *root = inode->root;
2645         struct btrfs_fs_info *fs_info = root->fs_info;
2646         u64 min_size = btrfs_calc_insert_metadata_size(fs_info, 1);
2647         u64 ino_size = round_up(inode->vfs_inode.i_size, fs_info->sectorsize);
2648         struct btrfs_trans_handle *trans = NULL;
2649         struct btrfs_block_rsv *rsv;
2650         unsigned int rsv_count;
2651         u64 cur_offset;
2652         u64 len = end - start;
2653         int ret = 0;
2654
2655         if (end <= start)
2656                 return -EINVAL;
2657
2658         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
2659         if (!rsv) {
2660                 ret = -ENOMEM;
2661                 goto out;
2662         }
2663         rsv->size = btrfs_calc_insert_metadata_size(fs_info, 1);
2664         rsv->failfast = true;
2665
2666         /*
2667          * 1 - update the inode
2668          * 1 - removing the extents in the range
2669          * 1 - adding the hole extent if no_holes isn't set or if we are
2670          *     replacing the range with a new extent
2671          */
2672         if (!btrfs_fs_incompat(fs_info, NO_HOLES) || extent_info)
2673                 rsv_count = 3;
2674         else
2675                 rsv_count = 2;
2676
2677         trans = btrfs_start_transaction(root, rsv_count);
2678         if (IS_ERR(trans)) {
2679                 ret = PTR_ERR(trans);
2680                 trans = NULL;
2681                 goto out_free;
2682         }
2683
2684         ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
2685                                       min_size, false);
2686         if (WARN_ON(ret))
2687                 goto out_trans;
2688         trans->block_rsv = rsv;
2689
2690         cur_offset = start;
2691         drop_args.path = path;
2692         drop_args.end = end + 1;
2693         drop_args.drop_cache = true;
2694         while (cur_offset < end) {
2695                 drop_args.start = cur_offset;
2696                 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2697                 /* If we are punching a hole decrement the inode's byte count */
2698                 if (!extent_info)
2699                         btrfs_update_inode_bytes(inode, 0,
2700                                                  drop_args.bytes_found);
2701                 if (ret != -ENOSPC) {
2702                         /*
2703                          * The only time we don't want to abort is if we are
2704                          * attempting to clone a partial inline extent, in which
2705                          * case we'll get EOPNOTSUPP.  However if we aren't
2706                          * clone we need to abort no matter what, because if we
2707                          * got EOPNOTSUPP via prealloc then we messed up and
2708                          * need to abort.
2709                          */
2710                         if (ret &&
2711                             (ret != -EOPNOTSUPP ||
2712                              (extent_info && extent_info->is_new_extent)))
2713                                 btrfs_abort_transaction(trans, ret);
2714                         break;
2715                 }
2716
2717                 trans->block_rsv = &fs_info->trans_block_rsv;
2718
2719                 if (!extent_info && cur_offset < drop_args.drop_end &&
2720                     cur_offset < ino_size) {
2721                         ret = fill_holes(trans, inode, path, cur_offset,
2722                                          drop_args.drop_end);
2723                         if (ret) {
2724                                 /*
2725                                  * If we failed then we didn't insert our hole
2726                                  * entries for the area we dropped, so now the
2727                                  * fs is corrupted, so we must abort the
2728                                  * transaction.
2729                                  */
2730                                 btrfs_abort_transaction(trans, ret);
2731                                 break;
2732                         }
2733                 } else if (!extent_info && cur_offset < drop_args.drop_end) {
2734                         /*
2735                          * We are past the i_size here, but since we didn't
2736                          * insert holes we need to clear the mapped area so we
2737                          * know to not set disk_i_size in this area until a new
2738                          * file extent is inserted here.
2739                          */
2740                         ret = btrfs_inode_clear_file_extent_range(inode,
2741                                         cur_offset,
2742                                         drop_args.drop_end - cur_offset);
2743                         if (ret) {
2744                                 /*
2745                                  * We couldn't clear our area, so we could
2746                                  * presumably adjust up and corrupt the fs, so
2747                                  * we need to abort.
2748                                  */
2749                                 btrfs_abort_transaction(trans, ret);
2750                                 break;
2751                         }
2752                 }
2753
2754                 if (extent_info &&
2755                     drop_args.drop_end > extent_info->file_offset) {
2756                         u64 replace_len = drop_args.drop_end -
2757                                           extent_info->file_offset;
2758
2759                         ret = btrfs_insert_replace_extent(trans, inode, path,
2760                                         extent_info, replace_len,
2761                                         drop_args.bytes_found);
2762                         if (ret) {
2763                                 btrfs_abort_transaction(trans, ret);
2764                                 break;
2765                         }
2766                         extent_info->data_len -= replace_len;
2767                         extent_info->data_offset += replace_len;
2768                         extent_info->file_offset += replace_len;
2769                 }
2770
2771                 /*
2772                  * We are releasing our handle on the transaction, balance the
2773                  * dirty pages of the btree inode and flush delayed items, and
2774                  * then get a new transaction handle, which may now point to a
2775                  * new transaction in case someone else may have committed the
2776                  * transaction we used to replace/drop file extent items. So
2777                  * bump the inode's iversion and update mtime and ctime except
2778                  * if we are called from a dedupe context. This is because a
2779                  * power failure/crash may happen after the transaction is
2780                  * committed and before we finish replacing/dropping all the
2781                  * file extent items we need.
2782                  */
2783                 inode_inc_iversion(&inode->vfs_inode);
2784
2785                 if (!extent_info || extent_info->update_times) {
2786                         inode->vfs_inode.i_mtime = current_time(&inode->vfs_inode);
2787                         inode->vfs_inode.i_ctime = inode->vfs_inode.i_mtime;
2788                 }
2789
2790                 ret = btrfs_update_inode(trans, root, inode);
2791                 if (ret)
2792                         break;
2793
2794                 btrfs_end_transaction(trans);
2795                 btrfs_btree_balance_dirty(fs_info);
2796
2797                 trans = btrfs_start_transaction(root, rsv_count);
2798                 if (IS_ERR(trans)) {
2799                         ret = PTR_ERR(trans);
2800                         trans = NULL;
2801                         break;
2802                 }
2803
2804                 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
2805                                               rsv, min_size, false);
2806                 if (WARN_ON(ret))
2807                         break;
2808                 trans->block_rsv = rsv;
2809
2810                 cur_offset = drop_args.drop_end;
2811                 len = end - cur_offset;
2812                 if (!extent_info && len) {
2813                         ret = find_first_non_hole(inode, &cur_offset, &len);
2814                         if (unlikely(ret < 0))
2815                                 break;
2816                         if (ret && !len) {
2817                                 ret = 0;
2818                                 break;
2819                         }
2820                 }
2821         }
2822
2823         /*
2824          * If we were cloning, force the next fsync to be a full one since we
2825          * we replaced (or just dropped in the case of cloning holes when
2826          * NO_HOLES is enabled) file extent items and did not setup new extent
2827          * maps for the replacement extents (or holes).
2828          */
2829         if (extent_info && !extent_info->is_new_extent)
2830                 btrfs_set_inode_full_sync(inode);
2831
2832         if (ret)
2833                 goto out_trans;
2834
2835         trans->block_rsv = &fs_info->trans_block_rsv;
2836         /*
2837          * If we are using the NO_HOLES feature we might have had already an
2838          * hole that overlaps a part of the region [lockstart, lockend] and
2839          * ends at (or beyond) lockend. Since we have no file extent items to
2840          * represent holes, drop_end can be less than lockend and so we must
2841          * make sure we have an extent map representing the existing hole (the
2842          * call to __btrfs_drop_extents() might have dropped the existing extent
2843          * map representing the existing hole), otherwise the fast fsync path
2844          * will not record the existence of the hole region
2845          * [existing_hole_start, lockend].
2846          */
2847         if (drop_args.drop_end <= end)
2848                 drop_args.drop_end = end + 1;
2849         /*
2850          * Don't insert file hole extent item if it's for a range beyond eof
2851          * (because it's useless) or if it represents a 0 bytes range (when
2852          * cur_offset == drop_end).
2853          */
2854         if (!extent_info && cur_offset < ino_size &&
2855             cur_offset < drop_args.drop_end) {
2856                 ret = fill_holes(trans, inode, path, cur_offset,
2857                                  drop_args.drop_end);
2858                 if (ret) {
2859                         /* Same comment as above. */
2860                         btrfs_abort_transaction(trans, ret);
2861                         goto out_trans;
2862                 }
2863         } else if (!extent_info && cur_offset < drop_args.drop_end) {
2864                 /* See the comment in the loop above for the reasoning here. */
2865                 ret = btrfs_inode_clear_file_extent_range(inode, cur_offset,
2866                                         drop_args.drop_end - cur_offset);
2867                 if (ret) {
2868                         btrfs_abort_transaction(trans, ret);
2869                         goto out_trans;
2870                 }
2871
2872         }
2873         if (extent_info) {
2874                 ret = btrfs_insert_replace_extent(trans, inode, path,
2875                                 extent_info, extent_info->data_len,
2876                                 drop_args.bytes_found);
2877                 if (ret) {
2878                         btrfs_abort_transaction(trans, ret);
2879                         goto out_trans;
2880                 }
2881         }
2882
2883 out_trans:
2884         if (!trans)
2885                 goto out_free;
2886
2887         trans->block_rsv = &fs_info->trans_block_rsv;
2888         if (ret)
2889                 btrfs_end_transaction(trans);
2890         else
2891                 *trans_out = trans;
2892 out_free:
2893         btrfs_free_block_rsv(fs_info, rsv);
2894 out:
2895         return ret;
2896 }
2897
2898 static int btrfs_punch_hole(struct file *file, loff_t offset, loff_t len)
2899 {
2900         struct inode *inode = file_inode(file);
2901         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2902         struct btrfs_root *root = BTRFS_I(inode)->root;
2903         struct extent_state *cached_state = NULL;
2904         struct btrfs_path *path;
2905         struct btrfs_trans_handle *trans = NULL;
2906         u64 lockstart;
2907         u64 lockend;
2908         u64 tail_start;
2909         u64 tail_len;
2910         u64 orig_start = offset;
2911         int ret = 0;
2912         bool same_block;
2913         u64 ino_size;
2914         bool truncated_block = false;
2915         bool updated_inode = false;
2916
2917         btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
2918
2919         ret = btrfs_wait_ordered_range(inode, offset, len);
2920         if (ret)
2921                 goto out_only_mutex;
2922
2923         ino_size = round_up(inode->i_size, fs_info->sectorsize);
2924         ret = find_first_non_hole(BTRFS_I(inode), &offset, &len);
2925         if (ret < 0)
2926                 goto out_only_mutex;
2927         if (ret && !len) {
2928                 /* Already in a large hole */
2929                 ret = 0;
2930                 goto out_only_mutex;
2931         }
2932
2933         ret = file_modified(file);
2934         if (ret)
2935                 goto out_only_mutex;
2936
2937         lockstart = round_up(offset, fs_info->sectorsize);
2938         lockend = round_down(offset + len, fs_info->sectorsize) - 1;
2939         same_block = (BTRFS_BYTES_TO_BLKS(fs_info, offset))
2940                 == (BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1));
2941         /*
2942          * We needn't truncate any block which is beyond the end of the file
2943          * because we are sure there is no data there.
2944          */
2945         /*
2946          * Only do this if we are in the same block and we aren't doing the
2947          * entire block.
2948          */
2949         if (same_block && len < fs_info->sectorsize) {
2950                 if (offset < ino_size) {
2951                         truncated_block = true;
2952                         ret = btrfs_truncate_block(BTRFS_I(inode), offset, len,
2953                                                    0);
2954                 } else {
2955                         ret = 0;
2956                 }
2957                 goto out_only_mutex;
2958         }
2959
2960         /* zero back part of the first block */
2961         if (offset < ino_size) {
2962                 truncated_block = true;
2963                 ret = btrfs_truncate_block(BTRFS_I(inode), offset, 0, 0);
2964                 if (ret) {
2965                         btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
2966                         return ret;
2967                 }
2968         }
2969
2970         /* Check the aligned pages after the first unaligned page,
2971          * if offset != orig_start, which means the first unaligned page
2972          * including several following pages are already in holes,
2973          * the extra check can be skipped */
2974         if (offset == orig_start) {
2975                 /* after truncate page, check hole again */
2976                 len = offset + len - lockstart;
2977                 offset = lockstart;
2978                 ret = find_first_non_hole(BTRFS_I(inode), &offset, &len);
2979                 if (ret < 0)
2980                         goto out_only_mutex;
2981                 if (ret && !len) {
2982                         ret = 0;
2983                         goto out_only_mutex;
2984                 }
2985                 lockstart = offset;
2986         }
2987
2988         /* Check the tail unaligned part is in a hole */
2989         tail_start = lockend + 1;
2990         tail_len = offset + len - tail_start;
2991         if (tail_len) {
2992                 ret = find_first_non_hole(BTRFS_I(inode), &tail_start, &tail_len);
2993                 if (unlikely(ret < 0))
2994                         goto out_only_mutex;
2995                 if (!ret) {
2996                         /* zero the front end of the last page */
2997                         if (tail_start + tail_len < ino_size) {
2998                                 truncated_block = true;
2999                                 ret = btrfs_truncate_block(BTRFS_I(inode),
3000                                                         tail_start + tail_len,
3001                                                         0, 1);
3002                                 if (ret)
3003                                         goto out_only_mutex;
3004                         }
3005                 }
3006         }
3007
3008         if (lockend < lockstart) {
3009                 ret = 0;
3010                 goto out_only_mutex;
3011         }
3012
3013         btrfs_punch_hole_lock_range(inode, lockstart, lockend, &cached_state);
3014
3015         path = btrfs_alloc_path();
3016         if (!path) {
3017                 ret = -ENOMEM;
3018                 goto out;
3019         }
3020
3021         ret = btrfs_replace_file_extents(BTRFS_I(inode), path, lockstart,
3022                                          lockend, NULL, &trans);
3023         btrfs_free_path(path);
3024         if (ret)
3025                 goto out;
3026
3027         ASSERT(trans != NULL);
3028         inode_inc_iversion(inode);
3029         inode->i_mtime = current_time(inode);
3030         inode->i_ctime = inode->i_mtime;
3031         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
3032         updated_inode = true;
3033         btrfs_end_transaction(trans);
3034         btrfs_btree_balance_dirty(fs_info);
3035 out:
3036         unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
3037                       &cached_state);
3038 out_only_mutex:
3039         if (!updated_inode && truncated_block && !ret) {
3040                 /*
3041                  * If we only end up zeroing part of a page, we still need to
3042                  * update the inode item, so that all the time fields are
3043                  * updated as well as the necessary btrfs inode in memory fields
3044                  * for detecting, at fsync time, if the inode isn't yet in the
3045                  * log tree or it's there but not up to date.
3046                  */
3047                 struct timespec64 now = current_time(inode);
3048
3049                 inode_inc_iversion(inode);
3050                 inode->i_mtime = now;
3051                 inode->i_ctime = now;
3052                 trans = btrfs_start_transaction(root, 1);
3053                 if (IS_ERR(trans)) {
3054                         ret = PTR_ERR(trans);
3055                 } else {
3056                         int ret2;
3057
3058                         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
3059                         ret2 = btrfs_end_transaction(trans);
3060                         if (!ret)
3061                                 ret = ret2;
3062                 }
3063         }
3064         btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
3065         return ret;
3066 }
3067
3068 /* Helper structure to record which range is already reserved */
3069 struct falloc_range {
3070         struct list_head list;
3071         u64 start;
3072         u64 len;
3073 };
3074
3075 /*
3076  * Helper function to add falloc range
3077  *
3078  * Caller should have locked the larger range of extent containing
3079  * [start, len)
3080  */
3081 static int add_falloc_range(struct list_head *head, u64 start, u64 len)
3082 {
3083         struct falloc_range *range = NULL;
3084
3085         if (!list_empty(head)) {
3086                 /*
3087                  * As fallocate iterates by bytenr order, we only need to check
3088                  * the last range.
3089                  */
3090                 range = list_last_entry(head, struct falloc_range, list);
3091                 if (range->start + range->len == start) {
3092                         range->len += len;
3093                         return 0;
3094                 }
3095         }
3096
3097         range = kmalloc(sizeof(*range), GFP_KERNEL);
3098         if (!range)
3099                 return -ENOMEM;
3100         range->start = start;
3101         range->len = len;
3102         list_add_tail(&range->list, head);
3103         return 0;
3104 }
3105
3106 static int btrfs_fallocate_update_isize(struct inode *inode,
3107                                         const u64 end,
3108                                         const int mode)
3109 {
3110         struct btrfs_trans_handle *trans;
3111         struct btrfs_root *root = BTRFS_I(inode)->root;
3112         int ret;
3113         int ret2;
3114
3115         if (mode & FALLOC_FL_KEEP_SIZE || end <= i_size_read(inode))
3116                 return 0;
3117
3118         trans = btrfs_start_transaction(root, 1);
3119         if (IS_ERR(trans))
3120                 return PTR_ERR(trans);
3121
3122         inode->i_ctime = current_time(inode);
3123         i_size_write(inode, end);
3124         btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
3125         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
3126         ret2 = btrfs_end_transaction(trans);
3127
3128         return ret ? ret : ret2;
3129 }
3130
3131 enum {
3132         RANGE_BOUNDARY_WRITTEN_EXTENT,
3133         RANGE_BOUNDARY_PREALLOC_EXTENT,
3134         RANGE_BOUNDARY_HOLE,
3135 };
3136
3137 static int btrfs_zero_range_check_range_boundary(struct btrfs_inode *inode,
3138                                                  u64 offset)
3139 {
3140         const u64 sectorsize = inode->root->fs_info->sectorsize;
3141         struct extent_map *em;
3142         int ret;
3143
3144         offset = round_down(offset, sectorsize);
3145         em = btrfs_get_extent(inode, NULL, 0, offset, sectorsize);
3146         if (IS_ERR(em))
3147                 return PTR_ERR(em);
3148
3149         if (em->block_start == EXTENT_MAP_HOLE)
3150                 ret = RANGE_BOUNDARY_HOLE;
3151         else if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3152                 ret = RANGE_BOUNDARY_PREALLOC_EXTENT;
3153         else
3154                 ret = RANGE_BOUNDARY_WRITTEN_EXTENT;
3155
3156         free_extent_map(em);
3157         return ret;
3158 }
3159
3160 static int btrfs_zero_range(struct inode *inode,
3161                             loff_t offset,
3162                             loff_t len,
3163                             const int mode)
3164 {
3165         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3166         struct extent_map *em;
3167         struct extent_changeset *data_reserved = NULL;
3168         int ret;
3169         u64 alloc_hint = 0;
3170         const u64 sectorsize = fs_info->sectorsize;
3171         u64 alloc_start = round_down(offset, sectorsize);
3172         u64 alloc_end = round_up(offset + len, sectorsize);
3173         u64 bytes_to_reserve = 0;
3174         bool space_reserved = false;
3175
3176         em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, alloc_start,
3177                               alloc_end - alloc_start);
3178         if (IS_ERR(em)) {
3179                 ret = PTR_ERR(em);
3180                 goto out;
3181         }
3182
3183         /*
3184          * Avoid hole punching and extent allocation for some cases. More cases
3185          * could be considered, but these are unlikely common and we keep things
3186          * as simple as possible for now. Also, intentionally, if the target
3187          * range contains one or more prealloc extents together with regular
3188          * extents and holes, we drop all the existing extents and allocate a
3189          * new prealloc extent, so that we get a larger contiguous disk extent.
3190          */
3191         if (em->start <= alloc_start &&
3192             test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3193                 const u64 em_end = em->start + em->len;
3194
3195                 if (em_end >= offset + len) {
3196                         /*
3197                          * The whole range is already a prealloc extent,
3198                          * do nothing except updating the inode's i_size if
3199                          * needed.
3200                          */
3201                         free_extent_map(em);
3202                         ret = btrfs_fallocate_update_isize(inode, offset + len,
3203                                                            mode);
3204                         goto out;
3205                 }
3206                 /*
3207                  * Part of the range is already a prealloc extent, so operate
3208                  * only on the remaining part of the range.
3209                  */
3210                 alloc_start = em_end;
3211                 ASSERT(IS_ALIGNED(alloc_start, sectorsize));
3212                 len = offset + len - alloc_start;
3213                 offset = alloc_start;
3214                 alloc_hint = em->block_start + em->len;
3215         }
3216         free_extent_map(em);
3217
3218         if (BTRFS_BYTES_TO_BLKS(fs_info, offset) ==
3219             BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1)) {
3220                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, alloc_start,
3221                                       sectorsize);
3222                 if (IS_ERR(em)) {
3223                         ret = PTR_ERR(em);
3224                         goto out;
3225                 }
3226
3227                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3228                         free_extent_map(em);
3229                         ret = btrfs_fallocate_update_isize(inode, offset + len,
3230                                                            mode);
3231                         goto out;
3232                 }
3233                 if (len < sectorsize && em->block_start != EXTENT_MAP_HOLE) {
3234                         free_extent_map(em);
3235                         ret = btrfs_truncate_block(BTRFS_I(inode), offset, len,
3236                                                    0);
3237                         if (!ret)
3238                                 ret = btrfs_fallocate_update_isize(inode,
3239                                                                    offset + len,
3240                                                                    mode);
3241                         return ret;
3242                 }
3243                 free_extent_map(em);
3244                 alloc_start = round_down(offset, sectorsize);
3245                 alloc_end = alloc_start + sectorsize;
3246                 goto reserve_space;
3247         }
3248
3249         alloc_start = round_up(offset, sectorsize);
3250         alloc_end = round_down(offset + len, sectorsize);
3251
3252         /*
3253          * For unaligned ranges, check the pages at the boundaries, they might
3254          * map to an extent, in which case we need to partially zero them, or
3255          * they might map to a hole, in which case we need our allocation range
3256          * to cover them.
3257          */
3258         if (!IS_ALIGNED(offset, sectorsize)) {
3259                 ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode),
3260                                                             offset);
3261                 if (ret < 0)
3262                         goto out;
3263                 if (ret == RANGE_BOUNDARY_HOLE) {
3264                         alloc_start = round_down(offset, sectorsize);
3265                         ret = 0;
3266                 } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
3267                         ret = btrfs_truncate_block(BTRFS_I(inode), offset, 0, 0);
3268                         if (ret)
3269                                 goto out;
3270                 } else {
3271                         ret = 0;
3272                 }
3273         }
3274
3275         if (!IS_ALIGNED(offset + len, sectorsize)) {
3276                 ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode),
3277                                                             offset + len);
3278                 if (ret < 0)
3279                         goto out;
3280                 if (ret == RANGE_BOUNDARY_HOLE) {
3281                         alloc_end = round_up(offset + len, sectorsize);
3282                         ret = 0;
3283                 } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
3284                         ret = btrfs_truncate_block(BTRFS_I(inode), offset + len,
3285                                                    0, 1);
3286                         if (ret)
3287                                 goto out;
3288                 } else {
3289                         ret = 0;
3290                 }
3291         }
3292
3293 reserve_space:
3294         if (alloc_start < alloc_end) {
3295                 struct extent_state *cached_state = NULL;
3296                 const u64 lockstart = alloc_start;
3297                 const u64 lockend = alloc_end - 1;
3298
3299                 bytes_to_reserve = alloc_end - alloc_start;
3300                 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
3301                                                       bytes_to_reserve);
3302                 if (ret < 0)
3303                         goto out;
3304                 space_reserved = true;
3305                 btrfs_punch_hole_lock_range(inode, lockstart, lockend,
3306                                             &cached_state);
3307                 ret = btrfs_qgroup_reserve_data(BTRFS_I(inode), &data_reserved,
3308                                                 alloc_start, bytes_to_reserve);
3309                 if (ret) {
3310                         unlock_extent(&BTRFS_I(inode)->io_tree, lockstart,
3311                                       lockend, &cached_state);
3312                         goto out;
3313                 }
3314                 ret = btrfs_prealloc_file_range(inode, mode, alloc_start,
3315                                                 alloc_end - alloc_start,
3316                                                 i_blocksize(inode),
3317                                                 offset + len, &alloc_hint);
3318                 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
3319                               &cached_state);
3320                 /* btrfs_prealloc_file_range releases reserved space on error */
3321                 if (ret) {
3322                         space_reserved = false;
3323                         goto out;
3324                 }
3325         }
3326         ret = btrfs_fallocate_update_isize(inode, offset + len, mode);
3327  out:
3328         if (ret && space_reserved)
3329                 btrfs_free_reserved_data_space(BTRFS_I(inode), data_reserved,
3330                                                alloc_start, bytes_to_reserve);
3331         extent_changeset_free(data_reserved);
3332
3333         return ret;
3334 }
3335
3336 static long btrfs_fallocate(struct file *file, int mode,
3337                             loff_t offset, loff_t len)
3338 {
3339         struct inode *inode = file_inode(file);
3340         struct extent_state *cached_state = NULL;
3341         struct extent_changeset *data_reserved = NULL;
3342         struct falloc_range *range;
3343         struct falloc_range *tmp;
3344         struct list_head reserve_list;
3345         u64 cur_offset;
3346         u64 last_byte;
3347         u64 alloc_start;
3348         u64 alloc_end;
3349         u64 alloc_hint = 0;
3350         u64 locked_end;
3351         u64 actual_end = 0;
3352         u64 data_space_needed = 0;
3353         u64 data_space_reserved = 0;
3354         u64 qgroup_reserved = 0;
3355         struct extent_map *em;
3356         int blocksize = BTRFS_I(inode)->root->fs_info->sectorsize;
3357         int ret;
3358
3359         /* Do not allow fallocate in ZONED mode */
3360         if (btrfs_is_zoned(btrfs_sb(inode->i_sb)))
3361                 return -EOPNOTSUPP;
3362
3363         alloc_start = round_down(offset, blocksize);
3364         alloc_end = round_up(offset + len, blocksize);
3365         cur_offset = alloc_start;
3366
3367         /* Make sure we aren't being give some crap mode */
3368         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
3369                      FALLOC_FL_ZERO_RANGE))
3370                 return -EOPNOTSUPP;
3371
3372         if (mode & FALLOC_FL_PUNCH_HOLE)
3373                 return btrfs_punch_hole(file, offset, len);
3374
3375         btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
3376
3377         if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) {
3378                 ret = inode_newsize_ok(inode, offset + len);
3379                 if (ret)
3380                         goto out;
3381         }
3382
3383         ret = file_modified(file);
3384         if (ret)
3385                 goto out;
3386
3387         /*
3388          * TODO: Move these two operations after we have checked
3389          * accurate reserved space, or fallocate can still fail but
3390          * with page truncated or size expanded.
3391          *
3392          * But that's a minor problem and won't do much harm BTW.
3393          */
3394         if (alloc_start > inode->i_size) {
3395                 ret = btrfs_cont_expand(BTRFS_I(inode), i_size_read(inode),
3396                                         alloc_start);
3397                 if (ret)
3398                         goto out;
3399         } else if (offset + len > inode->i_size) {
3400                 /*
3401                  * If we are fallocating from the end of the file onward we
3402                  * need to zero out the end of the block if i_size lands in the
3403                  * middle of a block.
3404                  */
3405                 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
3406                 if (ret)
3407                         goto out;
3408         }
3409
3410         /*
3411          * We have locked the inode at the VFS level (in exclusive mode) and we
3412          * have locked the i_mmap_lock lock (in exclusive mode). Now before
3413          * locking the file range, flush all dealloc in the range and wait for
3414          * all ordered extents in the range to complete. After this we can lock
3415          * the file range and, due to the previous locking we did, we know there
3416          * can't be more delalloc or ordered extents in the range.
3417          */
3418         ret = btrfs_wait_ordered_range(inode, alloc_start,
3419                                        alloc_end - alloc_start);
3420         if (ret)
3421                 goto out;
3422
3423         if (mode & FALLOC_FL_ZERO_RANGE) {
3424                 ret = btrfs_zero_range(inode, offset, len, mode);
3425                 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
3426                 return ret;
3427         }
3428
3429         locked_end = alloc_end - 1;
3430         lock_extent(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
3431                     &cached_state);
3432
3433         btrfs_assert_inode_range_clean(BTRFS_I(inode), alloc_start, locked_end);
3434
3435         /* First, check if we exceed the qgroup limit */
3436         INIT_LIST_HEAD(&reserve_list);
3437         while (cur_offset < alloc_end) {
3438                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
3439                                       alloc_end - cur_offset);
3440                 if (IS_ERR(em)) {
3441                         ret = PTR_ERR(em);
3442                         break;
3443                 }
3444                 last_byte = min(extent_map_end(em), alloc_end);
3445                 actual_end = min_t(u64, extent_map_end(em), offset + len);
3446                 last_byte = ALIGN(last_byte, blocksize);
3447                 if (em->block_start == EXTENT_MAP_HOLE ||
3448                     (cur_offset >= inode->i_size &&
3449                      !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
3450                         const u64 range_len = last_byte - cur_offset;
3451
3452                         ret = add_falloc_range(&reserve_list, cur_offset, range_len);
3453                         if (ret < 0) {
3454                                 free_extent_map(em);
3455                                 break;
3456                         }
3457                         ret = btrfs_qgroup_reserve_data(BTRFS_I(inode),
3458                                         &data_reserved, cur_offset, range_len);
3459                         if (ret < 0) {
3460                                 free_extent_map(em);
3461                                 break;
3462                         }
3463                         qgroup_reserved += range_len;
3464                         data_space_needed += range_len;
3465                 }
3466                 free_extent_map(em);
3467                 cur_offset = last_byte;
3468         }
3469
3470         if (!ret && data_space_needed > 0) {
3471                 /*
3472                  * We are safe to reserve space here as we can't have delalloc
3473                  * in the range, see above.
3474                  */
3475                 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
3476                                                       data_space_needed);
3477                 if (!ret)
3478                         data_space_reserved = data_space_needed;
3479         }
3480
3481         /*
3482          * If ret is still 0, means we're OK to fallocate.
3483          * Or just cleanup the list and exit.
3484          */
3485         list_for_each_entry_safe(range, tmp, &reserve_list, list) {
3486                 if (!ret) {
3487                         ret = btrfs_prealloc_file_range(inode, mode,
3488                                         range->start,
3489                                         range->len, i_blocksize(inode),
3490                                         offset + len, &alloc_hint);
3491                         /*
3492                          * btrfs_prealloc_file_range() releases space even
3493                          * if it returns an error.
3494                          */
3495                         data_space_reserved -= range->len;
3496                         qgroup_reserved -= range->len;
3497                 } else if (data_space_reserved > 0) {
3498                         btrfs_free_reserved_data_space(BTRFS_I(inode),
3499                                                data_reserved, range->start,
3500                                                range->len);
3501                         data_space_reserved -= range->len;
3502                         qgroup_reserved -= range->len;
3503                 } else if (qgroup_reserved > 0) {
3504                         btrfs_qgroup_free_data(BTRFS_I(inode), data_reserved,
3505                                                range->start, range->len);
3506                         qgroup_reserved -= range->len;
3507                 }
3508                 list_del(&range->list);
3509                 kfree(range);
3510         }
3511         if (ret < 0)
3512                 goto out_unlock;
3513
3514         /*
3515          * We didn't need to allocate any more space, but we still extended the
3516          * size of the file so we need to update i_size and the inode item.
3517          */
3518         ret = btrfs_fallocate_update_isize(inode, actual_end, mode);
3519 out_unlock:
3520         unlock_extent(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
3521                       &cached_state);
3522 out:
3523         btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
3524         extent_changeset_free(data_reserved);
3525         return ret;
3526 }
3527
3528 /*
3529  * Helper for btrfs_find_delalloc_in_range(). Find a subrange in a given range
3530  * that has unflushed and/or flushing delalloc. There might be other adjacent
3531  * subranges after the one it found, so btrfs_find_delalloc_in_range() keeps
3532  * looping while it gets adjacent subranges, and merging them together.
3533  */
3534 static bool find_delalloc_subrange(struct btrfs_inode *inode, u64 start, u64 end,
3535                                    u64 *delalloc_start_ret, u64 *delalloc_end_ret)
3536 {
3537         const u64 len = end + 1 - start;
3538         struct extent_map_tree *em_tree = &inode->extent_tree;
3539         struct extent_map *em;
3540         u64 em_end;
3541         u64 delalloc_len;
3542
3543         /*
3544          * Search the io tree first for EXTENT_DELALLOC. If we find any, it
3545          * means we have delalloc (dirty pages) for which writeback has not
3546          * started yet.
3547          */
3548         *delalloc_start_ret = start;
3549         delalloc_len = count_range_bits(&inode->io_tree, delalloc_start_ret, end,
3550                                         len, EXTENT_DELALLOC, 1);
3551         /*
3552          * If delalloc was found then *delalloc_start_ret has a sector size
3553          * aligned value (rounded down).
3554          */
3555         if (delalloc_len > 0)
3556                 *delalloc_end_ret = *delalloc_start_ret + delalloc_len - 1;
3557
3558         /*
3559          * Now also check if there's any extent map in the range that does not
3560          * map to a hole or prealloc extent. We do this because:
3561          *
3562          * 1) When delalloc is flushed, the file range is locked, we clear the
3563          *    EXTENT_DELALLOC bit from the io tree and create an extent map for
3564          *    an allocated extent. So we might just have been called after
3565          *    delalloc is flushed and before the ordered extent completes and
3566          *    inserts the new file extent item in the subvolume's btree;
3567          *
3568          * 2) We may have an extent map created by flushing delalloc for a
3569          *    subrange that starts before the subrange we found marked with
3570          *    EXTENT_DELALLOC in the io tree.
3571          */
3572         read_lock(&em_tree->lock);
3573         em = lookup_extent_mapping(em_tree, start, len);
3574         read_unlock(&em_tree->lock);
3575
3576         /* extent_map_end() returns a non-inclusive end offset. */
3577         em_end = em ? extent_map_end(em) : 0;
3578
3579         /*
3580          * If we have a hole/prealloc extent map, check the next one if this one
3581          * ends before our range's end.
3582          */
3583         if (em && (em->block_start == EXTENT_MAP_HOLE ||
3584                    test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) && em_end < end) {
3585                 struct extent_map *next_em;
3586
3587                 read_lock(&em_tree->lock);
3588                 next_em = lookup_extent_mapping(em_tree, em_end, len - em_end);
3589                 read_unlock(&em_tree->lock);
3590
3591                 free_extent_map(em);
3592                 em_end = next_em ? extent_map_end(next_em) : 0;
3593                 em = next_em;
3594         }
3595
3596         if (em && (em->block_start == EXTENT_MAP_HOLE ||
3597                    test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
3598                 free_extent_map(em);
3599                 em = NULL;
3600         }
3601
3602         /*
3603          * No extent map or one for a hole or prealloc extent. Use the delalloc
3604          * range we found in the io tree if we have one.
3605          */
3606         if (!em)
3607                 return (delalloc_len > 0);
3608
3609         /*
3610          * We don't have any range as EXTENT_DELALLOC in the io tree, so the
3611          * extent map is the only subrange representing delalloc.
3612          */
3613         if (delalloc_len == 0) {
3614                 *delalloc_start_ret = em->start;
3615                 *delalloc_end_ret = min(end, em_end - 1);
3616                 free_extent_map(em);
3617                 return true;
3618         }
3619
3620         /*
3621          * The extent map represents a delalloc range that starts before the
3622          * delalloc range we found in the io tree.
3623          */
3624         if (em->start < *delalloc_start_ret) {
3625                 *delalloc_start_ret = em->start;
3626                 /*
3627                  * If the ranges are adjacent, return a combined range.
3628                  * Otherwise return the extent map's range.
3629                  */
3630                 if (em_end < *delalloc_start_ret)
3631                         *delalloc_end_ret = min(end, em_end - 1);
3632
3633                 free_extent_map(em);
3634                 return true;
3635         }
3636
3637         /*
3638          * The extent map starts after the delalloc range we found in the io
3639          * tree. If it's adjacent, return a combined range, otherwise return
3640          * the range found in the io tree.
3641          */
3642         if (*delalloc_end_ret + 1 == em->start)
3643                 *delalloc_end_ret = min(end, em_end - 1);
3644
3645         free_extent_map(em);
3646         return true;
3647 }
3648
3649 /*
3650  * Check if there's delalloc in a given range.
3651  *
3652  * @inode:               The inode.
3653  * @start:               The start offset of the range. It does not need to be
3654  *                       sector size aligned.
3655  * @end:                 The end offset (inclusive value) of the search range.
3656  *                       It does not need to be sector size aligned.
3657  * @delalloc_start_ret:  Output argument, set to the start offset of the
3658  *                       subrange found with delalloc (may not be sector size
3659  *                       aligned).
3660  * @delalloc_end_ret:    Output argument, set to he end offset (inclusive value)
3661  *                       of the subrange found with delalloc.
3662  *
3663  * Returns true if a subrange with delalloc is found within the given range, and
3664  * if so it sets @delalloc_start_ret and @delalloc_end_ret with the start and
3665  * end offsets of the subrange.
3666  */
3667 bool btrfs_find_delalloc_in_range(struct btrfs_inode *inode, u64 start, u64 end,
3668                                   u64 *delalloc_start_ret, u64 *delalloc_end_ret)
3669 {
3670         u64 cur_offset = round_down(start, inode->root->fs_info->sectorsize);
3671         u64 prev_delalloc_end = 0;
3672         bool ret = false;
3673
3674         while (cur_offset < end) {
3675                 u64 delalloc_start;
3676                 u64 delalloc_end;
3677                 bool delalloc;
3678
3679                 delalloc = find_delalloc_subrange(inode, cur_offset, end,
3680                                                   &delalloc_start,
3681                                                   &delalloc_end);
3682                 if (!delalloc)
3683                         break;
3684
3685                 if (prev_delalloc_end == 0) {
3686                         /* First subrange found. */
3687                         *delalloc_start_ret = max(delalloc_start, start);
3688                         *delalloc_end_ret = delalloc_end;
3689                         ret = true;
3690                 } else if (delalloc_start == prev_delalloc_end + 1) {
3691                         /* Subrange adjacent to the previous one, merge them. */
3692                         *delalloc_end_ret = delalloc_end;
3693                 } else {
3694                         /* Subrange not adjacent to the previous one, exit. */
3695                         break;
3696                 }
3697
3698                 prev_delalloc_end = delalloc_end;
3699                 cur_offset = delalloc_end + 1;
3700                 cond_resched();
3701         }
3702
3703         return ret;
3704 }
3705
3706 /*
3707  * Check if there's a hole or delalloc range in a range representing a hole (or
3708  * prealloc extent) found in the inode's subvolume btree.
3709  *
3710  * @inode:      The inode.
3711  * @whence:     Seek mode (SEEK_DATA or SEEK_HOLE).
3712  * @start:      Start offset of the hole region. It does not need to be sector
3713  *              size aligned.
3714  * @end:        End offset (inclusive value) of the hole region. It does not
3715  *              need to be sector size aligned.
3716  * @start_ret:  Return parameter, used to set the start of the subrange in the
3717  *              hole that matches the search criteria (seek mode), if such
3718  *              subrange is found (return value of the function is true).
3719  *              The value returned here may not be sector size aligned.
3720  *
3721  * Returns true if a subrange matching the given seek mode is found, and if one
3722  * is found, it updates @start_ret with the start of the subrange.
3723  */
3724 static bool find_desired_extent_in_hole(struct btrfs_inode *inode, int whence,
3725                                         u64 start, u64 end, u64 *start_ret)
3726 {
3727         u64 delalloc_start;
3728         u64 delalloc_end;
3729         bool delalloc;
3730
3731         delalloc = btrfs_find_delalloc_in_range(inode, start, end,
3732                                                 &delalloc_start, &delalloc_end);
3733         if (delalloc && whence == SEEK_DATA) {
3734                 *start_ret = delalloc_start;
3735                 return true;
3736         }
3737
3738         if (delalloc && whence == SEEK_HOLE) {
3739                 /*
3740                  * We found delalloc but it starts after out start offset. So we
3741                  * have a hole between our start offset and the delalloc start.
3742                  */
3743                 if (start < delalloc_start) {
3744                         *start_ret = start;
3745                         return true;
3746                 }
3747                 /*
3748                  * Delalloc range starts at our start offset.
3749                  * If the delalloc range's length is smaller than our range,
3750                  * then it means we have a hole that starts where the delalloc
3751                  * subrange ends.
3752                  */
3753                 if (delalloc_end < end) {
3754                         *start_ret = delalloc_end + 1;
3755                         return true;
3756                 }
3757
3758                 /* There's delalloc for the whole range. */
3759                 return false;
3760         }
3761
3762         if (!delalloc && whence == SEEK_HOLE) {
3763                 *start_ret = start;
3764                 return true;
3765         }
3766
3767         /*
3768          * No delalloc in the range and we are seeking for data. The caller has
3769          * to iterate to the next extent item in the subvolume btree.
3770          */
3771         return false;
3772 }
3773
3774 static loff_t find_desired_extent(struct btrfs_inode *inode, loff_t offset,
3775                                   int whence)
3776 {
3777         struct btrfs_fs_info *fs_info = inode->root->fs_info;
3778         struct extent_state *cached_state = NULL;
3779         const loff_t i_size = i_size_read(&inode->vfs_inode);
3780         const u64 ino = btrfs_ino(inode);
3781         struct btrfs_root *root = inode->root;
3782         struct btrfs_path *path;
3783         struct btrfs_key key;
3784         u64 last_extent_end;
3785         u64 lockstart;
3786         u64 lockend;
3787         u64 start;
3788         int ret;
3789         bool found = false;
3790
3791         if (i_size == 0 || offset >= i_size)
3792                 return -ENXIO;
3793
3794         /*
3795          * Quick path. If the inode has no prealloc extents and its number of
3796          * bytes used matches its i_size, then it can not have holes.
3797          */
3798         if (whence == SEEK_HOLE &&
3799             !(inode->flags & BTRFS_INODE_PREALLOC) &&
3800             inode_get_bytes(&inode->vfs_inode) == i_size)
3801                 return i_size;
3802
3803         /*
3804          * offset can be negative, in this case we start finding DATA/HOLE from
3805          * the very start of the file.
3806          */
3807         start = max_t(loff_t, 0, offset);
3808
3809         lockstart = round_down(start, fs_info->sectorsize);
3810         lockend = round_up(i_size, fs_info->sectorsize);
3811         if (lockend <= lockstart)
3812                 lockend = lockstart + fs_info->sectorsize;
3813         lockend--;
3814
3815         path = btrfs_alloc_path();
3816         if (!path)
3817                 return -ENOMEM;
3818         path->reada = READA_FORWARD;
3819
3820         key.objectid = ino;
3821         key.type = BTRFS_EXTENT_DATA_KEY;
3822         key.offset = start;
3823
3824         last_extent_end = lockstart;
3825
3826         lock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
3827
3828         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3829         if (ret < 0) {
3830                 goto out;
3831         } else if (ret > 0 && path->slots[0] > 0) {
3832                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
3833                 if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
3834                         path->slots[0]--;
3835         }
3836
3837         while (start < i_size) {
3838                 struct extent_buffer *leaf = path->nodes[0];
3839                 struct btrfs_file_extent_item *extent;
3840                 u64 extent_end;
3841
3842                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
3843                         ret = btrfs_next_leaf(root, path);
3844                         if (ret < 0)
3845                                 goto out;
3846                         else if (ret > 0)
3847                                 break;
3848
3849                         leaf = path->nodes[0];
3850                 }
3851
3852                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3853                 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3854                         break;
3855
3856                 extent_end = btrfs_file_extent_end(path);
3857
3858                 /*
3859                  * In the first iteration we may have a slot that points to an
3860                  * extent that ends before our start offset, so skip it.
3861                  */
3862                 if (extent_end <= start) {
3863                         path->slots[0]++;
3864                         continue;
3865                 }
3866
3867                 /* We have an implicit hole, NO_HOLES feature is likely set. */
3868                 if (last_extent_end < key.offset) {
3869                         u64 search_start = last_extent_end;
3870                         u64 found_start;
3871
3872                         /*
3873                          * First iteration, @start matches @offset and it's
3874                          * within the hole.
3875                          */
3876                         if (start == offset)
3877                                 search_start = offset;
3878
3879                         found = find_desired_extent_in_hole(inode, whence,
3880                                                             search_start,
3881                                                             key.offset - 1,
3882                                                             &found_start);
3883                         if (found) {
3884                                 start = found_start;
3885                                 break;
3886                         }
3887                         /*
3888                          * Didn't find data or a hole (due to delalloc) in the
3889                          * implicit hole range, so need to analyze the extent.
3890                          */
3891                 }
3892
3893                 extent = btrfs_item_ptr(leaf, path->slots[0],
3894                                         struct btrfs_file_extent_item);
3895
3896                 if (btrfs_file_extent_disk_bytenr(leaf, extent) == 0 ||
3897                     btrfs_file_extent_type(leaf, extent) ==
3898                     BTRFS_FILE_EXTENT_PREALLOC) {
3899                         /*
3900                          * Explicit hole or prealloc extent, search for delalloc.
3901                          * A prealloc extent is treated like a hole.
3902                          */
3903                         u64 search_start = key.offset;
3904                         u64 found_start;
3905
3906                         /*
3907                          * First iteration, @start matches @offset and it's
3908                          * within the hole.
3909                          */
3910                         if (start == offset)
3911                                 search_start = offset;
3912
3913                         found = find_desired_extent_in_hole(inode, whence,
3914                                                             search_start,
3915                                                             extent_end - 1,
3916                                                             &found_start);
3917                         if (found) {
3918                                 start = found_start;
3919                                 break;
3920                         }
3921                         /*
3922                          * Didn't find data or a hole (due to delalloc) in the
3923                          * implicit hole range, so need to analyze the next
3924                          * extent item.
3925                          */
3926                 } else {
3927                         /*
3928                          * Found a regular or inline extent.
3929                          * If we are seeking for data, adjust the start offset
3930                          * and stop, we're done.
3931                          */
3932                         if (whence == SEEK_DATA) {
3933                                 start = max_t(u64, key.offset, offset);
3934                                 found = true;
3935                                 break;
3936                         }
3937                         /*
3938                          * Else, we are seeking for a hole, check the next file
3939                          * extent item.
3940                          */
3941                 }
3942
3943                 start = extent_end;
3944                 last_extent_end = extent_end;
3945                 path->slots[0]++;
3946                 if (fatal_signal_pending(current)) {
3947                         ret = -EINTR;
3948                         goto out;
3949                 }
3950                 cond_resched();
3951         }
3952
3953         /* We have an implicit hole from the last extent found up to i_size. */
3954         if (!found && start < i_size) {
3955                 found = find_desired_extent_in_hole(inode, whence, start,
3956                                                     i_size - 1, &start);
3957                 if (!found)
3958                         start = i_size;
3959         }
3960
3961 out:
3962         unlock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
3963         btrfs_free_path(path);
3964
3965         if (ret < 0)
3966                 return ret;
3967
3968         if (whence == SEEK_DATA && start >= i_size)
3969                 return -ENXIO;
3970
3971         return min_t(loff_t, start, i_size);
3972 }
3973
3974 static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
3975 {
3976         struct inode *inode = file->f_mapping->host;
3977
3978         switch (whence) {
3979         default:
3980                 return generic_file_llseek(file, offset, whence);
3981         case SEEK_DATA:
3982         case SEEK_HOLE:
3983                 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
3984                 offset = find_desired_extent(BTRFS_I(inode), offset, whence);
3985                 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
3986                 break;
3987         }
3988
3989         if (offset < 0)
3990                 return offset;
3991
3992         return vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
3993 }
3994
3995 static int btrfs_file_open(struct inode *inode, struct file *filp)
3996 {
3997         int ret;
3998
3999         filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC | FMODE_BUF_WASYNC;
4000
4001         ret = fsverity_file_open(inode, filp);
4002         if (ret)
4003                 return ret;
4004         return generic_file_open(inode, filp);
4005 }
4006
4007 static int check_direct_read(struct btrfs_fs_info *fs_info,
4008                              const struct iov_iter *iter, loff_t offset)
4009 {
4010         int ret;
4011         int i, seg;
4012
4013         ret = check_direct_IO(fs_info, iter, offset);
4014         if (ret < 0)
4015                 return ret;
4016
4017         if (!iter_is_iovec(iter))
4018                 return 0;
4019
4020         for (seg = 0; seg < iter->nr_segs; seg++)
4021                 for (i = seg + 1; i < iter->nr_segs; i++)
4022                         if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
4023                                 return -EINVAL;
4024         return 0;
4025 }
4026
4027 static ssize_t btrfs_direct_read(struct kiocb *iocb, struct iov_iter *to)
4028 {
4029         struct inode *inode = file_inode(iocb->ki_filp);
4030         size_t prev_left = 0;
4031         ssize_t read = 0;
4032         ssize_t ret;
4033
4034         if (fsverity_active(inode))
4035                 return 0;
4036
4037         if (check_direct_read(btrfs_sb(inode->i_sb), to, iocb->ki_pos))
4038                 return 0;
4039
4040         btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
4041 again:
4042         /*
4043          * This is similar to what we do for direct IO writes, see the comment
4044          * at btrfs_direct_write(), but we also disable page faults in addition
4045          * to disabling them only at the iov_iter level. This is because when
4046          * reading from a hole or prealloc extent, iomap calls iov_iter_zero(),
4047          * which can still trigger page fault ins despite having set ->nofault
4048          * to true of our 'to' iov_iter.
4049          *
4050          * The difference to direct IO writes is that we deadlock when trying
4051          * to lock the extent range in the inode's tree during he page reads
4052          * triggered by the fault in (while for writes it is due to waiting for
4053          * our own ordered extent). This is because for direct IO reads,
4054          * btrfs_dio_iomap_begin() returns with the extent range locked, which
4055          * is only unlocked in the endio callback (end_bio_extent_readpage()).
4056          */
4057         pagefault_disable();
4058         to->nofault = true;
4059         ret = btrfs_dio_read(iocb, to, read);
4060         to->nofault = false;
4061         pagefault_enable();
4062
4063         /* No increment (+=) because iomap returns a cumulative value. */
4064         if (ret > 0)
4065                 read = ret;
4066
4067         if (iov_iter_count(to) > 0 && (ret == -EFAULT || ret > 0)) {
4068                 const size_t left = iov_iter_count(to);
4069
4070                 if (left == prev_left) {
4071                         /*
4072                          * We didn't make any progress since the last attempt,
4073                          * fallback to a buffered read for the remainder of the
4074                          * range. This is just to avoid any possibility of looping
4075                          * for too long.
4076                          */
4077                         ret = read;
4078                 } else {
4079                         /*
4080                          * We made some progress since the last retry or this is
4081                          * the first time we are retrying. Fault in as many pages
4082                          * as possible and retry.
4083                          */
4084                         fault_in_iov_iter_writeable(to, left);
4085                         prev_left = left;
4086                         goto again;
4087                 }
4088         }
4089         btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
4090         return ret < 0 ? ret : read;
4091 }
4092
4093 static ssize_t btrfs_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
4094 {
4095         ssize_t ret = 0;
4096
4097         if (iocb->ki_flags & IOCB_DIRECT) {
4098                 ret = btrfs_direct_read(iocb, to);
4099                 if (ret < 0 || !iov_iter_count(to) ||
4100                     iocb->ki_pos >= i_size_read(file_inode(iocb->ki_filp)))
4101                         return ret;
4102         }
4103
4104         return filemap_read(iocb, to, ret);
4105 }
4106
4107 const struct file_operations btrfs_file_operations = {
4108         .llseek         = btrfs_file_llseek,
4109         .read_iter      = btrfs_file_read_iter,
4110         .splice_read    = generic_file_splice_read,
4111         .write_iter     = btrfs_file_write_iter,
4112         .splice_write   = iter_file_splice_write,
4113         .mmap           = btrfs_file_mmap,
4114         .open           = btrfs_file_open,
4115         .release        = btrfs_release_file,
4116         .get_unmapped_area = thp_get_unmapped_area,
4117         .fsync          = btrfs_sync_file,
4118         .fallocate      = btrfs_fallocate,
4119         .unlocked_ioctl = btrfs_ioctl,
4120 #ifdef CONFIG_COMPAT
4121         .compat_ioctl   = btrfs_compat_ioctl,
4122 #endif
4123         .remap_file_range = btrfs_remap_file_range,
4124 };
4125
4126 void __cold btrfs_auto_defrag_exit(void)
4127 {
4128         kmem_cache_destroy(btrfs_inode_defrag_cachep);
4129 }
4130
4131 int __init btrfs_auto_defrag_init(void)
4132 {
4133         btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
4134                                         sizeof(struct inode_defrag), 0,
4135                                         SLAB_MEM_SPREAD,
4136                                         NULL);
4137         if (!btrfs_inode_defrag_cachep)
4138                 return -ENOMEM;
4139
4140         return 0;
4141 }
4142
4143 int btrfs_fdatawrite_range(struct inode *inode, loff_t start, loff_t end)
4144 {
4145         int ret;
4146
4147         /*
4148          * So with compression we will find and lock a dirty page and clear the
4149          * first one as dirty, setup an async extent, and immediately return
4150          * with the entire range locked but with nobody actually marked with
4151          * writeback.  So we can't just filemap_write_and_wait_range() and
4152          * expect it to work since it will just kick off a thread to do the
4153          * actual work.  So we need to call filemap_fdatawrite_range _again_
4154          * since it will wait on the page lock, which won't be unlocked until
4155          * after the pages have been marked as writeback and so we're good to go
4156          * from there.  We have to do this otherwise we'll miss the ordered
4157          * extents and that results in badness.  Please Josef, do not think you
4158          * know better and pull this out at some point in the future, it is
4159          * right and you are wrong.
4160          */
4161         ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
4162         if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
4163                              &BTRFS_I(inode)->runtime_flags))
4164                 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
4165
4166         return ret;
4167 }