btrfs: add missing inode updates on each iteration when replacing extents
[sfrench/cifs-2.6.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                          0, 0, 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 drops all the extents in the cache that intersect the range
503  * [start, end].  Existing extents are split as required.
504  */
505 void btrfs_drop_extent_cache(struct btrfs_inode *inode, u64 start, u64 end,
506                              int skip_pinned)
507 {
508         struct extent_map *em;
509         struct extent_map *split = NULL;
510         struct extent_map *split2 = NULL;
511         struct extent_map_tree *em_tree = &inode->extent_tree;
512         u64 len = end - start + 1;
513         u64 gen;
514         int ret;
515         int testend = 1;
516         unsigned long flags;
517         int compressed = 0;
518         bool modified;
519
520         WARN_ON(end < start);
521         if (end == (u64)-1) {
522                 len = (u64)-1;
523                 testend = 0;
524         }
525         while (1) {
526                 int no_splits = 0;
527
528                 modified = false;
529                 if (!split)
530                         split = alloc_extent_map();
531                 if (!split2)
532                         split2 = alloc_extent_map();
533                 if (!split || !split2)
534                         no_splits = 1;
535
536                 write_lock(&em_tree->lock);
537                 em = lookup_extent_mapping(em_tree, start, len);
538                 if (!em) {
539                         write_unlock(&em_tree->lock);
540                         break;
541                 }
542                 flags = em->flags;
543                 gen = em->generation;
544                 if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
545                         if (testend && em->start + em->len >= start + len) {
546                                 free_extent_map(em);
547                                 write_unlock(&em_tree->lock);
548                                 break;
549                         }
550                         start = em->start + em->len;
551                         if (testend)
552                                 len = start + len - (em->start + em->len);
553                         free_extent_map(em);
554                         write_unlock(&em_tree->lock);
555                         continue;
556                 }
557                 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
558                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
559                 clear_bit(EXTENT_FLAG_LOGGING, &flags);
560                 modified = !list_empty(&em->list);
561                 if (no_splits)
562                         goto next;
563
564                 if (em->start < start) {
565                         split->start = em->start;
566                         split->len = start - em->start;
567
568                         if (em->block_start < EXTENT_MAP_LAST_BYTE) {
569                                 split->orig_start = em->orig_start;
570                                 split->block_start = em->block_start;
571
572                                 if (compressed)
573                                         split->block_len = em->block_len;
574                                 else
575                                         split->block_len = split->len;
576                                 split->orig_block_len = max(split->block_len,
577                                                 em->orig_block_len);
578                                 split->ram_bytes = em->ram_bytes;
579                         } else {
580                                 split->orig_start = split->start;
581                                 split->block_len = 0;
582                                 split->block_start = em->block_start;
583                                 split->orig_block_len = 0;
584                                 split->ram_bytes = split->len;
585                         }
586
587                         split->generation = gen;
588                         split->flags = flags;
589                         split->compress_type = em->compress_type;
590                         replace_extent_mapping(em_tree, em, split, modified);
591                         free_extent_map(split);
592                         split = split2;
593                         split2 = NULL;
594                 }
595                 if (testend && em->start + em->len > start + len) {
596                         u64 diff = start + len - em->start;
597
598                         split->start = start + len;
599                         split->len = em->start + em->len - (start + len);
600                         split->flags = flags;
601                         split->compress_type = em->compress_type;
602                         split->generation = gen;
603
604                         if (em->block_start < EXTENT_MAP_LAST_BYTE) {
605                                 split->orig_block_len = max(em->block_len,
606                                                     em->orig_block_len);
607
608                                 split->ram_bytes = em->ram_bytes;
609                                 if (compressed) {
610                                         split->block_len = em->block_len;
611                                         split->block_start = em->block_start;
612                                         split->orig_start = em->orig_start;
613                                 } else {
614                                         split->block_len = split->len;
615                                         split->block_start = em->block_start
616                                                 + diff;
617                                         split->orig_start = em->orig_start;
618                                 }
619                         } else {
620                                 split->ram_bytes = split->len;
621                                 split->orig_start = split->start;
622                                 split->block_len = 0;
623                                 split->block_start = em->block_start;
624                                 split->orig_block_len = 0;
625                         }
626
627                         if (extent_map_in_tree(em)) {
628                                 replace_extent_mapping(em_tree, em, split,
629                                                        modified);
630                         } else {
631                                 ret = add_extent_mapping(em_tree, split,
632                                                          modified);
633                                 ASSERT(ret == 0); /* Logic error */
634                         }
635                         free_extent_map(split);
636                         split = NULL;
637                 }
638 next:
639                 if (extent_map_in_tree(em))
640                         remove_extent_mapping(em_tree, em);
641                 write_unlock(&em_tree->lock);
642
643                 /* once for us */
644                 free_extent_map(em);
645                 /* once for the tree*/
646                 free_extent_map(em);
647         }
648         if (split)
649                 free_extent_map(split);
650         if (split2)
651                 free_extent_map(split2);
652 }
653
654 /*
655  * this is very complex, but the basic idea is to drop all extents
656  * in the range start - end.  hint_block is filled in with a block number
657  * that would be a good hint to the block allocator for this file.
658  *
659  * If an extent intersects the range but is not entirely inside the range
660  * it is either truncated or split.  Anything entirely inside the range
661  * is deleted from the tree.
662  *
663  * Note: the VFS' inode number of bytes is not updated, it's up to the caller
664  * to deal with that. We set the field 'bytes_found' of the arguments structure
665  * with the number of allocated bytes found in the target range, so that the
666  * caller can update the inode's number of bytes in an atomic way when
667  * replacing extents in a range to avoid races with stat(2).
668  */
669 int btrfs_drop_extents(struct btrfs_trans_handle *trans,
670                        struct btrfs_root *root, struct btrfs_inode *inode,
671                        struct btrfs_drop_extents_args *args)
672 {
673         struct btrfs_fs_info *fs_info = root->fs_info;
674         struct extent_buffer *leaf;
675         struct btrfs_file_extent_item *fi;
676         struct btrfs_ref ref = { 0 };
677         struct btrfs_key key;
678         struct btrfs_key new_key;
679         u64 ino = btrfs_ino(inode);
680         u64 search_start = args->start;
681         u64 disk_bytenr = 0;
682         u64 num_bytes = 0;
683         u64 extent_offset = 0;
684         u64 extent_end = 0;
685         u64 last_end = args->start;
686         int del_nr = 0;
687         int del_slot = 0;
688         int extent_type;
689         int recow;
690         int ret;
691         int modify_tree = -1;
692         int update_refs;
693         int found = 0;
694         struct btrfs_path *path = args->path;
695
696         args->bytes_found = 0;
697         args->extent_inserted = false;
698
699         /* Must always have a path if ->replace_extent is true */
700         ASSERT(!(args->replace_extent && !args->path));
701
702         if (!path) {
703                 path = btrfs_alloc_path();
704                 if (!path) {
705                         ret = -ENOMEM;
706                         goto out;
707                 }
708         }
709
710         if (args->drop_cache)
711                 btrfs_drop_extent_cache(inode, args->start, args->end - 1, 0);
712
713         if (args->start >= inode->disk_i_size && !args->replace_extent)
714                 modify_tree = 0;
715
716         update_refs = (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID);
717         while (1) {
718                 recow = 0;
719                 ret = btrfs_lookup_file_extent(trans, root, path, ino,
720                                                search_start, modify_tree);
721                 if (ret < 0)
722                         break;
723                 if (ret > 0 && path->slots[0] > 0 && search_start == args->start) {
724                         leaf = path->nodes[0];
725                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
726                         if (key.objectid == ino &&
727                             key.type == BTRFS_EXTENT_DATA_KEY)
728                                 path->slots[0]--;
729                 }
730                 ret = 0;
731 next_slot:
732                 leaf = path->nodes[0];
733                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
734                         BUG_ON(del_nr > 0);
735                         ret = btrfs_next_leaf(root, path);
736                         if (ret < 0)
737                                 break;
738                         if (ret > 0) {
739                                 ret = 0;
740                                 break;
741                         }
742                         leaf = path->nodes[0];
743                         recow = 1;
744                 }
745
746                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
747
748                 if (key.objectid > ino)
749                         break;
750                 if (WARN_ON_ONCE(key.objectid < ino) ||
751                     key.type < BTRFS_EXTENT_DATA_KEY) {
752                         ASSERT(del_nr == 0);
753                         path->slots[0]++;
754                         goto next_slot;
755                 }
756                 if (key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= args->end)
757                         break;
758
759                 fi = btrfs_item_ptr(leaf, path->slots[0],
760                                     struct btrfs_file_extent_item);
761                 extent_type = btrfs_file_extent_type(leaf, fi);
762
763                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
764                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
765                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
766                         num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
767                         extent_offset = btrfs_file_extent_offset(leaf, fi);
768                         extent_end = key.offset +
769                                 btrfs_file_extent_num_bytes(leaf, fi);
770                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
771                         extent_end = key.offset +
772                                 btrfs_file_extent_ram_bytes(leaf, fi);
773                 } else {
774                         /* can't happen */
775                         BUG();
776                 }
777
778                 /*
779                  * Don't skip extent items representing 0 byte lengths. They
780                  * used to be created (bug) if while punching holes we hit
781                  * -ENOSPC condition. So if we find one here, just ensure we
782                  * delete it, otherwise we would insert a new file extent item
783                  * with the same key (offset) as that 0 bytes length file
784                  * extent item in the call to setup_items_for_insert() later
785                  * in this function.
786                  */
787                 if (extent_end == key.offset && extent_end >= search_start) {
788                         last_end = extent_end;
789                         goto delete_extent_item;
790                 }
791
792                 if (extent_end <= search_start) {
793                         path->slots[0]++;
794                         goto next_slot;
795                 }
796
797                 found = 1;
798                 search_start = max(key.offset, args->start);
799                 if (recow || !modify_tree) {
800                         modify_tree = -1;
801                         btrfs_release_path(path);
802                         continue;
803                 }
804
805                 /*
806                  *     | - range to drop - |
807                  *  | -------- extent -------- |
808                  */
809                 if (args->start > key.offset && args->end < extent_end) {
810                         BUG_ON(del_nr > 0);
811                         if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
812                                 ret = -EOPNOTSUPP;
813                                 break;
814                         }
815
816                         memcpy(&new_key, &key, sizeof(new_key));
817                         new_key.offset = args->start;
818                         ret = btrfs_duplicate_item(trans, root, path,
819                                                    &new_key);
820                         if (ret == -EAGAIN) {
821                                 btrfs_release_path(path);
822                                 continue;
823                         }
824                         if (ret < 0)
825                                 break;
826
827                         leaf = path->nodes[0];
828                         fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
829                                             struct btrfs_file_extent_item);
830                         btrfs_set_file_extent_num_bytes(leaf, fi,
831                                                         args->start - key.offset);
832
833                         fi = btrfs_item_ptr(leaf, path->slots[0],
834                                             struct btrfs_file_extent_item);
835
836                         extent_offset += args->start - key.offset;
837                         btrfs_set_file_extent_offset(leaf, fi, extent_offset);
838                         btrfs_set_file_extent_num_bytes(leaf, fi,
839                                                         extent_end - args->start);
840                         btrfs_mark_buffer_dirty(leaf);
841
842                         if (update_refs && disk_bytenr > 0) {
843                                 btrfs_init_generic_ref(&ref,
844                                                 BTRFS_ADD_DELAYED_REF,
845                                                 disk_bytenr, num_bytes, 0);
846                                 btrfs_init_data_ref(&ref,
847                                                 root->root_key.objectid,
848                                                 new_key.objectid,
849                                                 args->start - extent_offset,
850                                                 0, false);
851                                 ret = btrfs_inc_extent_ref(trans, &ref);
852                                 BUG_ON(ret); /* -ENOMEM */
853                         }
854                         key.offset = args->start;
855                 }
856                 /*
857                  * From here on out we will have actually dropped something, so
858                  * last_end can be updated.
859                  */
860                 last_end = extent_end;
861
862                 /*
863                  *  | ---- range to drop ----- |
864                  *      | -------- extent -------- |
865                  */
866                 if (args->start <= key.offset && args->end < extent_end) {
867                         if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
868                                 ret = -EOPNOTSUPP;
869                                 break;
870                         }
871
872                         memcpy(&new_key, &key, sizeof(new_key));
873                         new_key.offset = args->end;
874                         btrfs_set_item_key_safe(fs_info, path, &new_key);
875
876                         extent_offset += args->end - key.offset;
877                         btrfs_set_file_extent_offset(leaf, fi, extent_offset);
878                         btrfs_set_file_extent_num_bytes(leaf, fi,
879                                                         extent_end - args->end);
880                         btrfs_mark_buffer_dirty(leaf);
881                         if (update_refs && disk_bytenr > 0)
882                                 args->bytes_found += args->end - key.offset;
883                         break;
884                 }
885
886                 search_start = extent_end;
887                 /*
888                  *       | ---- range to drop ----- |
889                  *  | -------- extent -------- |
890                  */
891                 if (args->start > key.offset && args->end >= extent_end) {
892                         BUG_ON(del_nr > 0);
893                         if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
894                                 ret = -EOPNOTSUPP;
895                                 break;
896                         }
897
898                         btrfs_set_file_extent_num_bytes(leaf, fi,
899                                                         args->start - key.offset);
900                         btrfs_mark_buffer_dirty(leaf);
901                         if (update_refs && disk_bytenr > 0)
902                                 args->bytes_found += extent_end - args->start;
903                         if (args->end == extent_end)
904                                 break;
905
906                         path->slots[0]++;
907                         goto next_slot;
908                 }
909
910                 /*
911                  *  | ---- range to drop ----- |
912                  *    | ------ extent ------ |
913                  */
914                 if (args->start <= key.offset && args->end >= extent_end) {
915 delete_extent_item:
916                         if (del_nr == 0) {
917                                 del_slot = path->slots[0];
918                                 del_nr = 1;
919                         } else {
920                                 BUG_ON(del_slot + del_nr != path->slots[0]);
921                                 del_nr++;
922                         }
923
924                         if (update_refs &&
925                             extent_type == BTRFS_FILE_EXTENT_INLINE) {
926                                 args->bytes_found += extent_end - key.offset;
927                                 extent_end = ALIGN(extent_end,
928                                                    fs_info->sectorsize);
929                         } else if (update_refs && disk_bytenr > 0) {
930                                 btrfs_init_generic_ref(&ref,
931                                                 BTRFS_DROP_DELAYED_REF,
932                                                 disk_bytenr, num_bytes, 0);
933                                 btrfs_init_data_ref(&ref,
934                                                 root->root_key.objectid,
935                                                 key.objectid,
936                                                 key.offset - extent_offset, 0,
937                                                 false);
938                                 ret = btrfs_free_extent(trans, &ref);
939                                 BUG_ON(ret); /* -ENOMEM */
940                                 args->bytes_found += extent_end - key.offset;
941                         }
942
943                         if (args->end == extent_end)
944                                 break;
945
946                         if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
947                                 path->slots[0]++;
948                                 goto next_slot;
949                         }
950
951                         ret = btrfs_del_items(trans, root, path, del_slot,
952                                               del_nr);
953                         if (ret) {
954                                 btrfs_abort_transaction(trans, ret);
955                                 break;
956                         }
957
958                         del_nr = 0;
959                         del_slot = 0;
960
961                         btrfs_release_path(path);
962                         continue;
963                 }
964
965                 BUG();
966         }
967
968         if (!ret && del_nr > 0) {
969                 /*
970                  * Set path->slots[0] to first slot, so that after the delete
971                  * if items are move off from our leaf to its immediate left or
972                  * right neighbor leafs, we end up with a correct and adjusted
973                  * path->slots[0] for our insertion (if args->replace_extent).
974                  */
975                 path->slots[0] = del_slot;
976                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
977                 if (ret)
978                         btrfs_abort_transaction(trans, ret);
979         }
980
981         leaf = path->nodes[0];
982         /*
983          * If btrfs_del_items() was called, it might have deleted a leaf, in
984          * which case it unlocked our path, so check path->locks[0] matches a
985          * write lock.
986          */
987         if (!ret && args->replace_extent &&
988             path->locks[0] == BTRFS_WRITE_LOCK &&
989             btrfs_leaf_free_space(leaf) >=
990             sizeof(struct btrfs_item) + args->extent_item_size) {
991
992                 key.objectid = ino;
993                 key.type = BTRFS_EXTENT_DATA_KEY;
994                 key.offset = args->start;
995                 if (!del_nr && path->slots[0] < btrfs_header_nritems(leaf)) {
996                         struct btrfs_key slot_key;
997
998                         btrfs_item_key_to_cpu(leaf, &slot_key, path->slots[0]);
999                         if (btrfs_comp_cpu_keys(&key, &slot_key) > 0)
1000                                 path->slots[0]++;
1001                 }
1002                 btrfs_setup_item_for_insert(root, path, &key, args->extent_item_size);
1003                 args->extent_inserted = true;
1004         }
1005
1006         if (!args->path)
1007                 btrfs_free_path(path);
1008         else if (!args->extent_inserted)
1009                 btrfs_release_path(path);
1010 out:
1011         args->drop_end = found ? min(args->end, last_end) : args->end;
1012
1013         return ret;
1014 }
1015
1016 static int extent_mergeable(struct extent_buffer *leaf, int slot,
1017                             u64 objectid, u64 bytenr, u64 orig_offset,
1018                             u64 *start, u64 *end)
1019 {
1020         struct btrfs_file_extent_item *fi;
1021         struct btrfs_key key;
1022         u64 extent_end;
1023
1024         if (slot < 0 || slot >= btrfs_header_nritems(leaf))
1025                 return 0;
1026
1027         btrfs_item_key_to_cpu(leaf, &key, slot);
1028         if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
1029                 return 0;
1030
1031         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
1032         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
1033             btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
1034             btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
1035             btrfs_file_extent_compression(leaf, fi) ||
1036             btrfs_file_extent_encryption(leaf, fi) ||
1037             btrfs_file_extent_other_encoding(leaf, fi))
1038                 return 0;
1039
1040         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
1041         if ((*start && *start != key.offset) || (*end && *end != extent_end))
1042                 return 0;
1043
1044         *start = key.offset;
1045         *end = extent_end;
1046         return 1;
1047 }
1048
1049 /*
1050  * Mark extent in the range start - end as written.
1051  *
1052  * This changes extent type from 'pre-allocated' to 'regular'. If only
1053  * part of extent is marked as written, the extent will be split into
1054  * two or three.
1055  */
1056 int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
1057                               struct btrfs_inode *inode, u64 start, u64 end)
1058 {
1059         struct btrfs_fs_info *fs_info = trans->fs_info;
1060         struct btrfs_root *root = inode->root;
1061         struct extent_buffer *leaf;
1062         struct btrfs_path *path;
1063         struct btrfs_file_extent_item *fi;
1064         struct btrfs_ref ref = { 0 };
1065         struct btrfs_key key;
1066         struct btrfs_key new_key;
1067         u64 bytenr;
1068         u64 num_bytes;
1069         u64 extent_end;
1070         u64 orig_offset;
1071         u64 other_start;
1072         u64 other_end;
1073         u64 split;
1074         int del_nr = 0;
1075         int del_slot = 0;
1076         int recow;
1077         int ret = 0;
1078         u64 ino = btrfs_ino(inode);
1079
1080         path = btrfs_alloc_path();
1081         if (!path)
1082                 return -ENOMEM;
1083 again:
1084         recow = 0;
1085         split = start;
1086         key.objectid = ino;
1087         key.type = BTRFS_EXTENT_DATA_KEY;
1088         key.offset = split;
1089
1090         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1091         if (ret < 0)
1092                 goto out;
1093         if (ret > 0 && path->slots[0] > 0)
1094                 path->slots[0]--;
1095
1096         leaf = path->nodes[0];
1097         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1098         if (key.objectid != ino ||
1099             key.type != BTRFS_EXTENT_DATA_KEY) {
1100                 ret = -EINVAL;
1101                 btrfs_abort_transaction(trans, ret);
1102                 goto out;
1103         }
1104         fi = btrfs_item_ptr(leaf, path->slots[0],
1105                             struct btrfs_file_extent_item);
1106         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_PREALLOC) {
1107                 ret = -EINVAL;
1108                 btrfs_abort_transaction(trans, ret);
1109                 goto out;
1110         }
1111         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
1112         if (key.offset > start || extent_end < end) {
1113                 ret = -EINVAL;
1114                 btrfs_abort_transaction(trans, ret);
1115                 goto out;
1116         }
1117
1118         bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1119         num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1120         orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
1121         memcpy(&new_key, &key, sizeof(new_key));
1122
1123         if (start == key.offset && end < extent_end) {
1124                 other_start = 0;
1125                 other_end = start;
1126                 if (extent_mergeable(leaf, path->slots[0] - 1,
1127                                      ino, bytenr, orig_offset,
1128                                      &other_start, &other_end)) {
1129                         new_key.offset = end;
1130                         btrfs_set_item_key_safe(fs_info, path, &new_key);
1131                         fi = btrfs_item_ptr(leaf, path->slots[0],
1132                                             struct btrfs_file_extent_item);
1133                         btrfs_set_file_extent_generation(leaf, fi,
1134                                                          trans->transid);
1135                         btrfs_set_file_extent_num_bytes(leaf, fi,
1136                                                         extent_end - end);
1137                         btrfs_set_file_extent_offset(leaf, fi,
1138                                                      end - orig_offset);
1139                         fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1140                                             struct btrfs_file_extent_item);
1141                         btrfs_set_file_extent_generation(leaf, fi,
1142                                                          trans->transid);
1143                         btrfs_set_file_extent_num_bytes(leaf, fi,
1144                                                         end - other_start);
1145                         btrfs_mark_buffer_dirty(leaf);
1146                         goto out;
1147                 }
1148         }
1149
1150         if (start > key.offset && end == extent_end) {
1151                 other_start = end;
1152                 other_end = 0;
1153                 if (extent_mergeable(leaf, path->slots[0] + 1,
1154                                      ino, bytenr, orig_offset,
1155                                      &other_start, &other_end)) {
1156                         fi = btrfs_item_ptr(leaf, path->slots[0],
1157                                             struct btrfs_file_extent_item);
1158                         btrfs_set_file_extent_num_bytes(leaf, fi,
1159                                                         start - key.offset);
1160                         btrfs_set_file_extent_generation(leaf, fi,
1161                                                          trans->transid);
1162                         path->slots[0]++;
1163                         new_key.offset = start;
1164                         btrfs_set_item_key_safe(fs_info, path, &new_key);
1165
1166                         fi = btrfs_item_ptr(leaf, path->slots[0],
1167                                             struct btrfs_file_extent_item);
1168                         btrfs_set_file_extent_generation(leaf, fi,
1169                                                          trans->transid);
1170                         btrfs_set_file_extent_num_bytes(leaf, fi,
1171                                                         other_end - start);
1172                         btrfs_set_file_extent_offset(leaf, fi,
1173                                                      start - orig_offset);
1174                         btrfs_mark_buffer_dirty(leaf);
1175                         goto out;
1176                 }
1177         }
1178
1179         while (start > key.offset || end < extent_end) {
1180                 if (key.offset == start)
1181                         split = end;
1182
1183                 new_key.offset = split;
1184                 ret = btrfs_duplicate_item(trans, root, path, &new_key);
1185                 if (ret == -EAGAIN) {
1186                         btrfs_release_path(path);
1187                         goto again;
1188                 }
1189                 if (ret < 0) {
1190                         btrfs_abort_transaction(trans, ret);
1191                         goto out;
1192                 }
1193
1194                 leaf = path->nodes[0];
1195                 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1196                                     struct btrfs_file_extent_item);
1197                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1198                 btrfs_set_file_extent_num_bytes(leaf, fi,
1199                                                 split - key.offset);
1200
1201                 fi = btrfs_item_ptr(leaf, path->slots[0],
1202                                     struct btrfs_file_extent_item);
1203
1204                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1205                 btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
1206                 btrfs_set_file_extent_num_bytes(leaf, fi,
1207                                                 extent_end - split);
1208                 btrfs_mark_buffer_dirty(leaf);
1209
1210                 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, bytenr,
1211                                        num_bytes, 0);
1212                 btrfs_init_data_ref(&ref, root->root_key.objectid, ino,
1213                                     orig_offset, 0, false);
1214                 ret = btrfs_inc_extent_ref(trans, &ref);
1215                 if (ret) {
1216                         btrfs_abort_transaction(trans, ret);
1217                         goto out;
1218                 }
1219
1220                 if (split == start) {
1221                         key.offset = start;
1222                 } else {
1223                         if (start != key.offset) {
1224                                 ret = -EINVAL;
1225                                 btrfs_abort_transaction(trans, ret);
1226                                 goto out;
1227                         }
1228                         path->slots[0]--;
1229                         extent_end = end;
1230                 }
1231                 recow = 1;
1232         }
1233
1234         other_start = end;
1235         other_end = 0;
1236         btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
1237                                num_bytes, 0);
1238         btrfs_init_data_ref(&ref, root->root_key.objectid, ino, orig_offset,
1239                             0, false);
1240         if (extent_mergeable(leaf, path->slots[0] + 1,
1241                              ino, bytenr, orig_offset,
1242                              &other_start, &other_end)) {
1243                 if (recow) {
1244                         btrfs_release_path(path);
1245                         goto again;
1246                 }
1247                 extent_end = other_end;
1248                 del_slot = path->slots[0] + 1;
1249                 del_nr++;
1250                 ret = btrfs_free_extent(trans, &ref);
1251                 if (ret) {
1252                         btrfs_abort_transaction(trans, ret);
1253                         goto out;
1254                 }
1255         }
1256         other_start = 0;
1257         other_end = start;
1258         if (extent_mergeable(leaf, path->slots[0] - 1,
1259                              ino, bytenr, orig_offset,
1260                              &other_start, &other_end)) {
1261                 if (recow) {
1262                         btrfs_release_path(path);
1263                         goto again;
1264                 }
1265                 key.offset = other_start;
1266                 del_slot = path->slots[0];
1267                 del_nr++;
1268                 ret = btrfs_free_extent(trans, &ref);
1269                 if (ret) {
1270                         btrfs_abort_transaction(trans, ret);
1271                         goto out;
1272                 }
1273         }
1274         if (del_nr == 0) {
1275                 fi = btrfs_item_ptr(leaf, path->slots[0],
1276                            struct btrfs_file_extent_item);
1277                 btrfs_set_file_extent_type(leaf, fi,
1278                                            BTRFS_FILE_EXTENT_REG);
1279                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1280                 btrfs_mark_buffer_dirty(leaf);
1281         } else {
1282                 fi = btrfs_item_ptr(leaf, del_slot - 1,
1283                            struct btrfs_file_extent_item);
1284                 btrfs_set_file_extent_type(leaf, fi,
1285                                            BTRFS_FILE_EXTENT_REG);
1286                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1287                 btrfs_set_file_extent_num_bytes(leaf, fi,
1288                                                 extent_end - key.offset);
1289                 btrfs_mark_buffer_dirty(leaf);
1290
1291                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
1292                 if (ret < 0) {
1293                         btrfs_abort_transaction(trans, ret);
1294                         goto out;
1295                 }
1296         }
1297 out:
1298         btrfs_free_path(path);
1299         return ret;
1300 }
1301
1302 /*
1303  * on error we return an unlocked page and the error value
1304  * on success we return a locked page and 0
1305  */
1306 static int prepare_uptodate_page(struct inode *inode,
1307                                  struct page *page, u64 pos,
1308                                  bool force_uptodate)
1309 {
1310         int ret = 0;
1311
1312         if (((pos & (PAGE_SIZE - 1)) || force_uptodate) &&
1313             !PageUptodate(page)) {
1314                 ret = btrfs_readpage(NULL, page);
1315                 if (ret)
1316                         return ret;
1317                 lock_page(page);
1318                 if (!PageUptodate(page)) {
1319                         unlock_page(page);
1320                         return -EIO;
1321                 }
1322
1323                 /*
1324                  * Since btrfs_readpage() will unlock the page before it
1325                  * returns, there is a window where btrfs_releasepage() can be
1326                  * called to release the page.  Here we check both inode
1327                  * mapping and PagePrivate() to make sure the page was not
1328                  * released.
1329                  *
1330                  * The private flag check is essential for subpage as we need
1331                  * to store extra bitmap using page->private.
1332                  */
1333                 if (page->mapping != inode->i_mapping || !PagePrivate(page)) {
1334                         unlock_page(page);
1335                         return -EAGAIN;
1336                 }
1337         }
1338         return 0;
1339 }
1340
1341 /*
1342  * this just gets pages into the page cache and locks them down.
1343  */
1344 static noinline int prepare_pages(struct inode *inode, struct page **pages,
1345                                   size_t num_pages, loff_t pos,
1346                                   size_t write_bytes, bool force_uptodate)
1347 {
1348         int i;
1349         unsigned long index = pos >> PAGE_SHIFT;
1350         gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1351         int err = 0;
1352         int faili;
1353
1354         for (i = 0; i < num_pages; i++) {
1355 again:
1356                 pages[i] = find_or_create_page(inode->i_mapping, index + i,
1357                                                mask | __GFP_WRITE);
1358                 if (!pages[i]) {
1359                         faili = i - 1;
1360                         err = -ENOMEM;
1361                         goto fail;
1362                 }
1363
1364                 err = set_page_extent_mapped(pages[i]);
1365                 if (err < 0) {
1366                         faili = i;
1367                         goto fail;
1368                 }
1369
1370                 if (i == 0)
1371                         err = prepare_uptodate_page(inode, pages[i], pos,
1372                                                     force_uptodate);
1373                 if (!err && i == num_pages - 1)
1374                         err = prepare_uptodate_page(inode, pages[i],
1375                                                     pos + write_bytes, false);
1376                 if (err) {
1377                         put_page(pages[i]);
1378                         if (err == -EAGAIN) {
1379                                 err = 0;
1380                                 goto again;
1381                         }
1382                         faili = i - 1;
1383                         goto fail;
1384                 }
1385                 wait_on_page_writeback(pages[i]);
1386         }
1387
1388         return 0;
1389 fail:
1390         while (faili >= 0) {
1391                 unlock_page(pages[faili]);
1392                 put_page(pages[faili]);
1393                 faili--;
1394         }
1395         return err;
1396
1397 }
1398
1399 /*
1400  * This function locks the extent and properly waits for data=ordered extents
1401  * to finish before allowing the pages to be modified if need.
1402  *
1403  * The return value:
1404  * 1 - the extent is locked
1405  * 0 - the extent is not locked, and everything is OK
1406  * -EAGAIN - need re-prepare the pages
1407  * the other < 0 number - Something wrong happens
1408  */
1409 static noinline int
1410 lock_and_cleanup_extent_if_need(struct btrfs_inode *inode, struct page **pages,
1411                                 size_t num_pages, loff_t pos,
1412                                 size_t write_bytes,
1413                                 u64 *lockstart, u64 *lockend,
1414                                 struct extent_state **cached_state)
1415 {
1416         struct btrfs_fs_info *fs_info = inode->root->fs_info;
1417         u64 start_pos;
1418         u64 last_pos;
1419         int i;
1420         int ret = 0;
1421
1422         start_pos = round_down(pos, fs_info->sectorsize);
1423         last_pos = round_up(pos + write_bytes, fs_info->sectorsize) - 1;
1424
1425         if (start_pos < inode->vfs_inode.i_size) {
1426                 struct btrfs_ordered_extent *ordered;
1427
1428                 lock_extent_bits(&inode->io_tree, start_pos, last_pos,
1429                                 cached_state);
1430                 ordered = btrfs_lookup_ordered_range(inode, start_pos,
1431                                                      last_pos - start_pos + 1);
1432                 if (ordered &&
1433                     ordered->file_offset + ordered->num_bytes > start_pos &&
1434                     ordered->file_offset <= last_pos) {
1435                         unlock_extent_cached(&inode->io_tree, start_pos,
1436                                         last_pos, cached_state);
1437                         for (i = 0; i < num_pages; i++) {
1438                                 unlock_page(pages[i]);
1439                                 put_page(pages[i]);
1440                         }
1441                         btrfs_start_ordered_extent(ordered, 1);
1442                         btrfs_put_ordered_extent(ordered);
1443                         return -EAGAIN;
1444                 }
1445                 if (ordered)
1446                         btrfs_put_ordered_extent(ordered);
1447
1448                 *lockstart = start_pos;
1449                 *lockend = last_pos;
1450                 ret = 1;
1451         }
1452
1453         /*
1454          * We should be called after prepare_pages() which should have locked
1455          * all pages in the range.
1456          */
1457         for (i = 0; i < num_pages; i++)
1458                 WARN_ON(!PageLocked(pages[i]));
1459
1460         return ret;
1461 }
1462
1463 /*
1464  * Check if we can do nocow write into the range [@pos, @pos + @write_bytes)
1465  *
1466  * @pos:         File offset.
1467  * @write_bytes: The length to write, will be updated to the nocow writeable
1468  *               range.
1469  *
1470  * This function will flush ordered extents in the range to ensure proper
1471  * nocow checks.
1472  *
1473  * Return:
1474  * > 0          If we can nocow, and updates @write_bytes.
1475  *  0           If we can't do a nocow write.
1476  * -EAGAIN      If we can't do a nocow write because snapshoting of the inode's
1477  *              root is in progress.
1478  * < 0          If an error happened.
1479  *
1480  * NOTE: Callers need to call btrfs_check_nocow_unlock() if we return > 0.
1481  */
1482 int btrfs_check_nocow_lock(struct btrfs_inode *inode, loff_t pos,
1483                            size_t *write_bytes)
1484 {
1485         struct btrfs_fs_info *fs_info = inode->root->fs_info;
1486         struct btrfs_root *root = inode->root;
1487         u64 lockstart, lockend;
1488         u64 num_bytes;
1489         int ret;
1490
1491         if (!(inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
1492                 return 0;
1493
1494         if (!btrfs_drew_try_write_lock(&root->snapshot_lock))
1495                 return -EAGAIN;
1496
1497         lockstart = round_down(pos, fs_info->sectorsize);
1498         lockend = round_up(pos + *write_bytes,
1499                            fs_info->sectorsize) - 1;
1500         num_bytes = lockend - lockstart + 1;
1501
1502         btrfs_lock_and_flush_ordered_range(inode, lockstart, lockend, NULL);
1503         ret = can_nocow_extent(&inode->vfs_inode, lockstart, &num_bytes,
1504                         NULL, NULL, NULL, false);
1505         if (ret <= 0) {
1506                 ret = 0;
1507                 btrfs_drew_write_unlock(&root->snapshot_lock);
1508         } else {
1509                 *write_bytes = min_t(size_t, *write_bytes ,
1510                                      num_bytes - pos + lockstart);
1511         }
1512         unlock_extent(&inode->io_tree, lockstart, lockend);
1513
1514         return ret;
1515 }
1516
1517 void btrfs_check_nocow_unlock(struct btrfs_inode *inode)
1518 {
1519         btrfs_drew_write_unlock(&inode->root->snapshot_lock);
1520 }
1521
1522 static void update_time_for_write(struct inode *inode)
1523 {
1524         struct timespec64 now;
1525
1526         if (IS_NOCMTIME(inode))
1527                 return;
1528
1529         now = current_time(inode);
1530         if (!timespec64_equal(&inode->i_mtime, &now))
1531                 inode->i_mtime = now;
1532
1533         if (!timespec64_equal(&inode->i_ctime, &now))
1534                 inode->i_ctime = now;
1535
1536         if (IS_I_VERSION(inode))
1537                 inode_inc_iversion(inode);
1538 }
1539
1540 static int btrfs_write_check(struct kiocb *iocb, struct iov_iter *from,
1541                              size_t count)
1542 {
1543         struct file *file = iocb->ki_filp;
1544         struct inode *inode = file_inode(file);
1545         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1546         loff_t pos = iocb->ki_pos;
1547         int ret;
1548         loff_t oldsize;
1549         loff_t start_pos;
1550
1551         /*
1552          * Quickly bail out on NOWAIT writes if we don't have the nodatacow or
1553          * prealloc flags, as without those flags we always have to COW. We will
1554          * later check if we can really COW into the target range (using
1555          * can_nocow_extent() at btrfs_get_blocks_direct_write()).
1556          */
1557         if ((iocb->ki_flags & IOCB_NOWAIT) &&
1558             !(BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
1559                 return -EAGAIN;
1560
1561         current->backing_dev_info = inode_to_bdi(inode);
1562         ret = file_remove_privs(file);
1563         if (ret)
1564                 return ret;
1565
1566         /*
1567          * We reserve space for updating the inode when we reserve space for the
1568          * extent we are going to write, so we will enospc out there.  We don't
1569          * need to start yet another transaction to update the inode as we will
1570          * update the inode when we finish writing whatever data we write.
1571          */
1572         update_time_for_write(inode);
1573
1574         start_pos = round_down(pos, fs_info->sectorsize);
1575         oldsize = i_size_read(inode);
1576         if (start_pos > oldsize) {
1577                 /* Expand hole size to cover write data, preventing empty gap */
1578                 loff_t end_pos = round_up(pos + count, fs_info->sectorsize);
1579
1580                 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, end_pos);
1581                 if (ret) {
1582                         current->backing_dev_info = NULL;
1583                         return ret;
1584                 }
1585         }
1586
1587         return 0;
1588 }
1589
1590 static noinline ssize_t btrfs_buffered_write(struct kiocb *iocb,
1591                                                struct iov_iter *i)
1592 {
1593         struct file *file = iocb->ki_filp;
1594         loff_t pos;
1595         struct inode *inode = file_inode(file);
1596         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1597         struct page **pages = NULL;
1598         struct extent_changeset *data_reserved = NULL;
1599         u64 release_bytes = 0;
1600         u64 lockstart;
1601         u64 lockend;
1602         size_t num_written = 0;
1603         int nrptrs;
1604         ssize_t ret;
1605         bool only_release_metadata = false;
1606         bool force_page_uptodate = false;
1607         loff_t old_isize = i_size_read(inode);
1608         unsigned int ilock_flags = 0;
1609
1610         if (iocb->ki_flags & IOCB_NOWAIT)
1611                 ilock_flags |= BTRFS_ILOCK_TRY;
1612
1613         ret = btrfs_inode_lock(inode, ilock_flags);
1614         if (ret < 0)
1615                 return ret;
1616
1617         ret = generic_write_checks(iocb, i);
1618         if (ret <= 0)
1619                 goto out;
1620
1621         ret = btrfs_write_check(iocb, i, ret);
1622         if (ret < 0)
1623                 goto out;
1624
1625         pos = iocb->ki_pos;
1626         nrptrs = min(DIV_ROUND_UP(iov_iter_count(i), PAGE_SIZE),
1627                         PAGE_SIZE / (sizeof(struct page *)));
1628         nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
1629         nrptrs = max(nrptrs, 8);
1630         pages = kmalloc_array(nrptrs, sizeof(struct page *), GFP_KERNEL);
1631         if (!pages) {
1632                 ret = -ENOMEM;
1633                 goto out;
1634         }
1635
1636         while (iov_iter_count(i) > 0) {
1637                 struct extent_state *cached_state = NULL;
1638                 size_t offset = offset_in_page(pos);
1639                 size_t sector_offset;
1640                 size_t write_bytes = min(iov_iter_count(i),
1641                                          nrptrs * (size_t)PAGE_SIZE -
1642                                          offset);
1643                 size_t num_pages;
1644                 size_t reserve_bytes;
1645                 size_t dirty_pages;
1646                 size_t copied;
1647                 size_t dirty_sectors;
1648                 size_t num_sectors;
1649                 int extents_locked;
1650
1651                 /*
1652                  * Fault pages before locking them in prepare_pages
1653                  * to avoid recursive lock
1654                  */
1655                 if (unlikely(fault_in_iov_iter_readable(i, write_bytes))) {
1656                         ret = -EFAULT;
1657                         break;
1658                 }
1659
1660                 only_release_metadata = false;
1661                 sector_offset = pos & (fs_info->sectorsize - 1);
1662
1663                 extent_changeset_release(data_reserved);
1664                 ret = btrfs_check_data_free_space(BTRFS_I(inode),
1665                                                   &data_reserved, pos,
1666                                                   write_bytes);
1667                 if (ret < 0) {
1668                         /*
1669                          * If we don't have to COW at the offset, reserve
1670                          * metadata only. write_bytes may get smaller than
1671                          * requested here.
1672                          */
1673                         if (btrfs_check_nocow_lock(BTRFS_I(inode), pos,
1674                                                    &write_bytes) > 0)
1675                                 only_release_metadata = true;
1676                         else
1677                                 break;
1678                 }
1679
1680                 num_pages = DIV_ROUND_UP(write_bytes + offset, PAGE_SIZE);
1681                 WARN_ON(num_pages > nrptrs);
1682                 reserve_bytes = round_up(write_bytes + sector_offset,
1683                                          fs_info->sectorsize);
1684                 WARN_ON(reserve_bytes == 0);
1685                 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
1686                                                       reserve_bytes,
1687                                                       reserve_bytes, false);
1688                 if (ret) {
1689                         if (!only_release_metadata)
1690                                 btrfs_free_reserved_data_space(BTRFS_I(inode),
1691                                                 data_reserved, pos,
1692                                                 write_bytes);
1693                         else
1694                                 btrfs_check_nocow_unlock(BTRFS_I(inode));
1695                         break;
1696                 }
1697
1698                 release_bytes = reserve_bytes;
1699 again:
1700                 /*
1701                  * This is going to setup the pages array with the number of
1702                  * pages we want, so we don't really need to worry about the
1703                  * contents of pages from loop to loop
1704                  */
1705                 ret = prepare_pages(inode, pages, num_pages,
1706                                     pos, write_bytes,
1707                                     force_page_uptodate);
1708                 if (ret) {
1709                         btrfs_delalloc_release_extents(BTRFS_I(inode),
1710                                                        reserve_bytes);
1711                         break;
1712                 }
1713
1714                 extents_locked = lock_and_cleanup_extent_if_need(
1715                                 BTRFS_I(inode), pages,
1716                                 num_pages, pos, write_bytes, &lockstart,
1717                                 &lockend, &cached_state);
1718                 if (extents_locked < 0) {
1719                         if (extents_locked == -EAGAIN)
1720                                 goto again;
1721                         btrfs_delalloc_release_extents(BTRFS_I(inode),
1722                                                        reserve_bytes);
1723                         ret = extents_locked;
1724                         break;
1725                 }
1726
1727                 copied = btrfs_copy_from_user(pos, write_bytes, pages, i);
1728
1729                 num_sectors = BTRFS_BYTES_TO_BLKS(fs_info, reserve_bytes);
1730                 dirty_sectors = round_up(copied + sector_offset,
1731                                         fs_info->sectorsize);
1732                 dirty_sectors = BTRFS_BYTES_TO_BLKS(fs_info, dirty_sectors);
1733
1734                 /*
1735                  * if we have trouble faulting in the pages, fall
1736                  * back to one page at a time
1737                  */
1738                 if (copied < write_bytes)
1739                         nrptrs = 1;
1740
1741                 if (copied == 0) {
1742                         force_page_uptodate = true;
1743                         dirty_sectors = 0;
1744                         dirty_pages = 0;
1745                 } else {
1746                         force_page_uptodate = false;
1747                         dirty_pages = DIV_ROUND_UP(copied + offset,
1748                                                    PAGE_SIZE);
1749                 }
1750
1751                 if (num_sectors > dirty_sectors) {
1752                         /* release everything except the sectors we dirtied */
1753                         release_bytes -= dirty_sectors << fs_info->sectorsize_bits;
1754                         if (only_release_metadata) {
1755                                 btrfs_delalloc_release_metadata(BTRFS_I(inode),
1756                                                         release_bytes, true);
1757                         } else {
1758                                 u64 __pos;
1759
1760                                 __pos = round_down(pos,
1761                                                    fs_info->sectorsize) +
1762                                         (dirty_pages << PAGE_SHIFT);
1763                                 btrfs_delalloc_release_space(BTRFS_I(inode),
1764                                                 data_reserved, __pos,
1765                                                 release_bytes, true);
1766                         }
1767                 }
1768
1769                 release_bytes = round_up(copied + sector_offset,
1770                                         fs_info->sectorsize);
1771
1772                 ret = btrfs_dirty_pages(BTRFS_I(inode), pages,
1773                                         dirty_pages, pos, copied,
1774                                         &cached_state, only_release_metadata);
1775
1776                 /*
1777                  * If we have not locked the extent range, because the range's
1778                  * start offset is >= i_size, we might still have a non-NULL
1779                  * cached extent state, acquired while marking the extent range
1780                  * as delalloc through btrfs_dirty_pages(). Therefore free any
1781                  * possible cached extent state to avoid a memory leak.
1782                  */
1783                 if (extents_locked)
1784                         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1785                                              lockstart, lockend, &cached_state);
1786                 else
1787                         free_extent_state(cached_state);
1788
1789                 btrfs_delalloc_release_extents(BTRFS_I(inode), reserve_bytes);
1790                 if (ret) {
1791                         btrfs_drop_pages(fs_info, pages, num_pages, pos, copied);
1792                         break;
1793                 }
1794
1795                 release_bytes = 0;
1796                 if (only_release_metadata)
1797                         btrfs_check_nocow_unlock(BTRFS_I(inode));
1798
1799                 btrfs_drop_pages(fs_info, pages, num_pages, pos, copied);
1800
1801                 cond_resched();
1802
1803                 balance_dirty_pages_ratelimited(inode->i_mapping);
1804
1805                 pos += copied;
1806                 num_written += copied;
1807         }
1808
1809         kfree(pages);
1810
1811         if (release_bytes) {
1812                 if (only_release_metadata) {
1813                         btrfs_check_nocow_unlock(BTRFS_I(inode));
1814                         btrfs_delalloc_release_metadata(BTRFS_I(inode),
1815                                         release_bytes, true);
1816                 } else {
1817                         btrfs_delalloc_release_space(BTRFS_I(inode),
1818                                         data_reserved,
1819                                         round_down(pos, fs_info->sectorsize),
1820                                         release_bytes, true);
1821                 }
1822         }
1823
1824         extent_changeset_free(data_reserved);
1825         if (num_written > 0) {
1826                 pagecache_isize_extended(inode, old_isize, iocb->ki_pos);
1827                 iocb->ki_pos += num_written;
1828         }
1829 out:
1830         btrfs_inode_unlock(inode, ilock_flags);
1831         return num_written ? num_written : ret;
1832 }
1833
1834 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
1835                                const struct iov_iter *iter, loff_t offset)
1836 {
1837         const u32 blocksize_mask = fs_info->sectorsize - 1;
1838
1839         if (offset & blocksize_mask)
1840                 return -EINVAL;
1841
1842         if (iov_iter_alignment(iter) & blocksize_mask)
1843                 return -EINVAL;
1844
1845         return 0;
1846 }
1847
1848 static ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from)
1849 {
1850         const bool is_sync_write = (iocb->ki_flags & IOCB_DSYNC);
1851         struct file *file = iocb->ki_filp;
1852         struct inode *inode = file_inode(file);
1853         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1854         loff_t pos;
1855         ssize_t written = 0;
1856         ssize_t written_buffered;
1857         size_t prev_left = 0;
1858         loff_t endbyte;
1859         ssize_t err;
1860         unsigned int ilock_flags = 0;
1861
1862         if (iocb->ki_flags & IOCB_NOWAIT)
1863                 ilock_flags |= BTRFS_ILOCK_TRY;
1864
1865         /* If the write DIO is within EOF, use a shared lock */
1866         if (iocb->ki_pos + iov_iter_count(from) <= i_size_read(inode))
1867                 ilock_flags |= BTRFS_ILOCK_SHARED;
1868
1869 relock:
1870         err = btrfs_inode_lock(inode, ilock_flags);
1871         if (err < 0)
1872                 return err;
1873
1874         err = generic_write_checks(iocb, from);
1875         if (err <= 0) {
1876                 btrfs_inode_unlock(inode, ilock_flags);
1877                 return err;
1878         }
1879
1880         err = btrfs_write_check(iocb, from, err);
1881         if (err < 0) {
1882                 btrfs_inode_unlock(inode, ilock_flags);
1883                 goto out;
1884         }
1885
1886         pos = iocb->ki_pos;
1887         /*
1888          * Re-check since file size may have changed just before taking the
1889          * lock or pos may have changed because of O_APPEND in generic_write_check()
1890          */
1891         if ((ilock_flags & BTRFS_ILOCK_SHARED) &&
1892             pos + iov_iter_count(from) > i_size_read(inode)) {
1893                 btrfs_inode_unlock(inode, ilock_flags);
1894                 ilock_flags &= ~BTRFS_ILOCK_SHARED;
1895                 goto relock;
1896         }
1897
1898         if (check_direct_IO(fs_info, from, pos)) {
1899                 btrfs_inode_unlock(inode, ilock_flags);
1900                 goto buffered;
1901         }
1902
1903         /*
1904          * We remove IOCB_DSYNC so that we don't deadlock when iomap_dio_rw()
1905          * calls generic_write_sync() (through iomap_dio_complete()), because
1906          * that results in calling fsync (btrfs_sync_file()) which will try to
1907          * lock the inode in exclusive/write mode.
1908          */
1909         if (is_sync_write)
1910                 iocb->ki_flags &= ~IOCB_DSYNC;
1911
1912         /*
1913          * The iov_iter can be mapped to the same file range we are writing to.
1914          * If that's the case, then we will deadlock in the iomap code, because
1915          * it first calls our callback btrfs_dio_iomap_begin(), which will create
1916          * an ordered extent, and after that it will fault in the pages that the
1917          * iov_iter refers to. During the fault in we end up in the readahead
1918          * pages code (starting at btrfs_readahead()), which will lock the range,
1919          * find that ordered extent and then wait for it to complete (at
1920          * btrfs_lock_and_flush_ordered_range()), resulting in a deadlock since
1921          * obviously the ordered extent can never complete as we didn't submit
1922          * yet the respective bio(s). This always happens when the buffer is
1923          * memory mapped to the same file range, since the iomap DIO code always
1924          * invalidates pages in the target file range (after starting and waiting
1925          * for any writeback).
1926          *
1927          * So here we disable page faults in the iov_iter and then retry if we
1928          * got -EFAULT, faulting in the pages before the retry.
1929          */
1930 again:
1931         from->nofault = true;
1932         err = btrfs_dio_rw(iocb, from, written);
1933         from->nofault = false;
1934
1935         /* No increment (+=) because iomap returns a cumulative value. */
1936         if (err > 0)
1937                 written = err;
1938
1939         if (iov_iter_count(from) > 0 && (err == -EFAULT || err > 0)) {
1940                 const size_t left = iov_iter_count(from);
1941                 /*
1942                  * We have more data left to write. Try to fault in as many as
1943                  * possible of the remainder pages and retry. We do this without
1944                  * releasing and locking again the inode, to prevent races with
1945                  * truncate.
1946                  *
1947                  * Also, in case the iov refers to pages in the file range of the
1948                  * file we want to write to (due to a mmap), we could enter an
1949                  * infinite loop if we retry after faulting the pages in, since
1950                  * iomap will invalidate any pages in the range early on, before
1951                  * it tries to fault in the pages of the iov. So we keep track of
1952                  * how much was left of iov in the previous EFAULT and fallback
1953                  * to buffered IO in case we haven't made any progress.
1954                  */
1955                 if (left == prev_left) {
1956                         err = -ENOTBLK;
1957                 } else {
1958                         fault_in_iov_iter_readable(from, left);
1959                         prev_left = left;
1960                         goto again;
1961                 }
1962         }
1963
1964         btrfs_inode_unlock(inode, ilock_flags);
1965
1966         /*
1967          * Add back IOCB_DSYNC. Our caller, btrfs_file_write_iter(), will do
1968          * the fsync (call generic_write_sync()).
1969          */
1970         if (is_sync_write)
1971                 iocb->ki_flags |= IOCB_DSYNC;
1972
1973         /* If 'err' is -ENOTBLK then it means we must fallback to buffered IO. */
1974         if ((err < 0 && err != -ENOTBLK) || !iov_iter_count(from))
1975                 goto out;
1976
1977 buffered:
1978         pos = iocb->ki_pos;
1979         written_buffered = btrfs_buffered_write(iocb, from);
1980         if (written_buffered < 0) {
1981                 err = written_buffered;
1982                 goto out;
1983         }
1984         /*
1985          * Ensure all data is persisted. We want the next direct IO read to be
1986          * able to read what was just written.
1987          */
1988         endbyte = pos + written_buffered - 1;
1989         err = btrfs_fdatawrite_range(inode, pos, endbyte);
1990         if (err)
1991                 goto out;
1992         err = filemap_fdatawait_range(inode->i_mapping, pos, endbyte);
1993         if (err)
1994                 goto out;
1995         written += written_buffered;
1996         iocb->ki_pos = pos + written_buffered;
1997         invalidate_mapping_pages(file->f_mapping, pos >> PAGE_SHIFT,
1998                                  endbyte >> PAGE_SHIFT);
1999 out:
2000         return err < 0 ? err : written;
2001 }
2002
2003 static ssize_t btrfs_encoded_write(struct kiocb *iocb, struct iov_iter *from,
2004                         const struct btrfs_ioctl_encoded_io_args *encoded)
2005 {
2006         struct file *file = iocb->ki_filp;
2007         struct inode *inode = file_inode(file);
2008         loff_t count;
2009         ssize_t ret;
2010
2011         btrfs_inode_lock(inode, 0);
2012         count = encoded->len;
2013         ret = generic_write_checks_count(iocb, &count);
2014         if (ret == 0 && count != encoded->len) {
2015                 /*
2016                  * The write got truncated by generic_write_checks_count(). We
2017                  * can't do a partial encoded write.
2018                  */
2019                 ret = -EFBIG;
2020         }
2021         if (ret || encoded->len == 0)
2022                 goto out;
2023
2024         ret = btrfs_write_check(iocb, from, encoded->len);
2025         if (ret < 0)
2026                 goto out;
2027
2028         ret = btrfs_do_encoded_write(iocb, from, encoded);
2029 out:
2030         btrfs_inode_unlock(inode, 0);
2031         return ret;
2032 }
2033
2034 ssize_t btrfs_do_write_iter(struct kiocb *iocb, struct iov_iter *from,
2035                             const struct btrfs_ioctl_encoded_io_args *encoded)
2036 {
2037         struct file *file = iocb->ki_filp;
2038         struct btrfs_inode *inode = BTRFS_I(file_inode(file));
2039         ssize_t num_written, num_sync;
2040         const bool sync = iocb->ki_flags & IOCB_DSYNC;
2041
2042         /*
2043          * If the fs flips readonly due to some impossible error, although we
2044          * have opened a file as writable, we have to stop this write operation
2045          * to ensure consistency.
2046          */
2047         if (BTRFS_FS_ERROR(inode->root->fs_info))
2048                 return -EROFS;
2049
2050         if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
2051                 return -EOPNOTSUPP;
2052
2053         if (sync)
2054                 atomic_inc(&inode->sync_writers);
2055
2056         if (encoded) {
2057                 num_written = btrfs_encoded_write(iocb, from, encoded);
2058                 num_sync = encoded->len;
2059         } else if (iocb->ki_flags & IOCB_DIRECT) {
2060                 num_written = num_sync = btrfs_direct_write(iocb, from);
2061         } else {
2062                 num_written = num_sync = btrfs_buffered_write(iocb, from);
2063         }
2064
2065         btrfs_set_inode_last_sub_trans(inode);
2066
2067         if (num_sync > 0) {
2068                 num_sync = generic_write_sync(iocb, num_sync);
2069                 if (num_sync < 0)
2070                         num_written = num_sync;
2071         }
2072
2073         if (sync)
2074                 atomic_dec(&inode->sync_writers);
2075
2076         current->backing_dev_info = NULL;
2077         return num_written;
2078 }
2079
2080 static ssize_t btrfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
2081 {
2082         return btrfs_do_write_iter(iocb, from, NULL);
2083 }
2084
2085 int btrfs_release_file(struct inode *inode, struct file *filp)
2086 {
2087         struct btrfs_file_private *private = filp->private_data;
2088
2089         if (private && private->filldir_buf)
2090                 kfree(private->filldir_buf);
2091         kfree(private);
2092         filp->private_data = NULL;
2093
2094         /*
2095          * Set by setattr when we are about to truncate a file from a non-zero
2096          * size to a zero size.  This tries to flush down new bytes that may
2097          * have been written if the application were using truncate to replace
2098          * a file in place.
2099          */
2100         if (test_and_clear_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
2101                                &BTRFS_I(inode)->runtime_flags))
2102                         filemap_flush(inode->i_mapping);
2103         return 0;
2104 }
2105
2106 static int start_ordered_ops(struct inode *inode, loff_t start, loff_t end)
2107 {
2108         int ret;
2109         struct blk_plug plug;
2110
2111         /*
2112          * This is only called in fsync, which would do synchronous writes, so
2113          * a plug can merge adjacent IOs as much as possible.  Esp. in case of
2114          * multiple disks using raid profile, a large IO can be split to
2115          * several segments of stripe length (currently 64K).
2116          */
2117         blk_start_plug(&plug);
2118         atomic_inc(&BTRFS_I(inode)->sync_writers);
2119         ret = btrfs_fdatawrite_range(inode, start, end);
2120         atomic_dec(&BTRFS_I(inode)->sync_writers);
2121         blk_finish_plug(&plug);
2122
2123         return ret;
2124 }
2125
2126 static inline bool skip_inode_logging(const struct btrfs_log_ctx *ctx)
2127 {
2128         struct btrfs_inode *inode = BTRFS_I(ctx->inode);
2129         struct btrfs_fs_info *fs_info = inode->root->fs_info;
2130
2131         if (btrfs_inode_in_log(inode, fs_info->generation) &&
2132             list_empty(&ctx->ordered_extents))
2133                 return true;
2134
2135         /*
2136          * If we are doing a fast fsync we can not bail out if the inode's
2137          * last_trans is <= then the last committed transaction, because we only
2138          * update the last_trans of the inode during ordered extent completion,
2139          * and for a fast fsync we don't wait for that, we only wait for the
2140          * writeback to complete.
2141          */
2142         if (inode->last_trans <= fs_info->last_trans_committed &&
2143             (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags) ||
2144              list_empty(&ctx->ordered_extents)))
2145                 return true;
2146
2147         return false;
2148 }
2149
2150 /*
2151  * fsync call for both files and directories.  This logs the inode into
2152  * the tree log instead of forcing full commits whenever possible.
2153  *
2154  * It needs to call filemap_fdatawait so that all ordered extent updates are
2155  * in the metadata btree are up to date for copying to the log.
2156  *
2157  * It drops the inode mutex before doing the tree log commit.  This is an
2158  * important optimization for directories because holding the mutex prevents
2159  * new operations on the dir while we write to disk.
2160  */
2161 int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
2162 {
2163         struct dentry *dentry = file_dentry(file);
2164         struct inode *inode = d_inode(dentry);
2165         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2166         struct btrfs_root *root = BTRFS_I(inode)->root;
2167         struct btrfs_trans_handle *trans;
2168         struct btrfs_log_ctx ctx;
2169         int ret = 0, err;
2170         u64 len;
2171         bool full_sync;
2172
2173         trace_btrfs_sync_file(file, datasync);
2174
2175         btrfs_init_log_ctx(&ctx, inode);
2176
2177         /*
2178          * Always set the range to a full range, otherwise we can get into
2179          * several problems, from missing file extent items to represent holes
2180          * when not using the NO_HOLES feature, to log tree corruption due to
2181          * races between hole detection during logging and completion of ordered
2182          * extents outside the range, to missing checksums due to ordered extents
2183          * for which we flushed only a subset of their pages.
2184          */
2185         start = 0;
2186         end = LLONG_MAX;
2187         len = (u64)LLONG_MAX + 1;
2188
2189         /*
2190          * We write the dirty pages in the range and wait until they complete
2191          * out of the ->i_mutex. If so, we can flush the dirty pages by
2192          * multi-task, and make the performance up.  See
2193          * btrfs_wait_ordered_range for an explanation of the ASYNC check.
2194          */
2195         ret = start_ordered_ops(inode, start, end);
2196         if (ret)
2197                 goto out;
2198
2199         btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
2200
2201         atomic_inc(&root->log_batch);
2202
2203         /*
2204          * Always check for the full sync flag while holding the inode's lock,
2205          * to avoid races with other tasks. The flag must be either set all the
2206          * time during logging or always off all the time while logging.
2207          */
2208         full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2209                              &BTRFS_I(inode)->runtime_flags);
2210
2211         /*
2212          * Before we acquired the inode's lock and the mmap lock, someone may
2213          * have dirtied more pages in the target range. We need to make sure
2214          * that writeback for any such pages does not start while we are logging
2215          * the inode, because if it does, any of the following might happen when
2216          * we are not doing a full inode sync:
2217          *
2218          * 1) We log an extent after its writeback finishes but before its
2219          *    checksums are added to the csum tree, leading to -EIO errors
2220          *    when attempting to read the extent after a log replay.
2221          *
2222          * 2) We can end up logging an extent before its writeback finishes.
2223          *    Therefore after the log replay we will have a file extent item
2224          *    pointing to an unwritten extent (and no data checksums as well).
2225          *
2226          * So trigger writeback for any eventual new dirty pages and then we
2227          * wait for all ordered extents to complete below.
2228          */
2229         ret = start_ordered_ops(inode, start, end);
2230         if (ret) {
2231                 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
2232                 goto out;
2233         }
2234
2235         /*
2236          * We have to do this here to avoid the priority inversion of waiting on
2237          * IO of a lower priority task while holding a transaction open.
2238          *
2239          * For a full fsync we wait for the ordered extents to complete while
2240          * for a fast fsync we wait just for writeback to complete, and then
2241          * attach the ordered extents to the transaction so that a transaction
2242          * commit waits for their completion, to avoid data loss if we fsync,
2243          * the current transaction commits before the ordered extents complete
2244          * and a power failure happens right after that.
2245          *
2246          * For zoned filesystem, if a write IO uses a ZONE_APPEND command, the
2247          * logical address recorded in the ordered extent may change. We need
2248          * to wait for the IO to stabilize the logical address.
2249          */
2250         if (full_sync || btrfs_is_zoned(fs_info)) {
2251                 ret = btrfs_wait_ordered_range(inode, start, len);
2252         } else {
2253                 /*
2254                  * Get our ordered extents as soon as possible to avoid doing
2255                  * checksum lookups in the csum tree, and use instead the
2256                  * checksums attached to the ordered extents.
2257                  */
2258                 btrfs_get_ordered_extents_for_logging(BTRFS_I(inode),
2259                                                       &ctx.ordered_extents);
2260                 ret = filemap_fdatawait_range(inode->i_mapping, start, end);
2261         }
2262
2263         if (ret)
2264                 goto out_release_extents;
2265
2266         atomic_inc(&root->log_batch);
2267
2268         smp_mb();
2269         if (skip_inode_logging(&ctx)) {
2270                 /*
2271                  * We've had everything committed since the last time we were
2272                  * modified so clear this flag in case it was set for whatever
2273                  * reason, it's no longer relevant.
2274                  */
2275                 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2276                           &BTRFS_I(inode)->runtime_flags);
2277                 /*
2278                  * An ordered extent might have started before and completed
2279                  * already with io errors, in which case the inode was not
2280                  * updated and we end up here. So check the inode's mapping
2281                  * for any errors that might have happened since we last
2282                  * checked called fsync.
2283                  */
2284                 ret = filemap_check_wb_err(inode->i_mapping, file->f_wb_err);
2285                 goto out_release_extents;
2286         }
2287
2288         /*
2289          * We use start here because we will need to wait on the IO to complete
2290          * in btrfs_sync_log, which could require joining a transaction (for
2291          * example checking cross references in the nocow path).  If we use join
2292          * here we could get into a situation where we're waiting on IO to
2293          * happen that is blocked on a transaction trying to commit.  With start
2294          * we inc the extwriter counter, so we wait for all extwriters to exit
2295          * before we start blocking joiners.  This comment is to keep somebody
2296          * from thinking they are super smart and changing this to
2297          * btrfs_join_transaction *cough*Josef*cough*.
2298          */
2299         trans = btrfs_start_transaction(root, 0);
2300         if (IS_ERR(trans)) {
2301                 ret = PTR_ERR(trans);
2302                 goto out_release_extents;
2303         }
2304         trans->in_fsync = true;
2305
2306         ret = btrfs_log_dentry_safe(trans, dentry, &ctx);
2307         btrfs_release_log_ctx_extents(&ctx);
2308         if (ret < 0) {
2309                 /* Fallthrough and commit/free transaction. */
2310                 ret = 1;
2311         }
2312
2313         /* we've logged all the items and now have a consistent
2314          * version of the file in the log.  It is possible that
2315          * someone will come in and modify the file, but that's
2316          * fine because the log is consistent on disk, and we
2317          * have references to all of the file's extents
2318          *
2319          * It is possible that someone will come in and log the
2320          * file again, but that will end up using the synchronization
2321          * inside btrfs_sync_log to keep things safe.
2322          */
2323         btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
2324
2325         if (ret != BTRFS_NO_LOG_SYNC) {
2326                 if (!ret) {
2327                         ret = btrfs_sync_log(trans, root, &ctx);
2328                         if (!ret) {
2329                                 ret = btrfs_end_transaction(trans);
2330                                 goto out;
2331                         }
2332                 }
2333                 if (!full_sync) {
2334                         ret = btrfs_wait_ordered_range(inode, start, len);
2335                         if (ret) {
2336                                 btrfs_end_transaction(trans);
2337                                 goto out;
2338                         }
2339                 }
2340                 ret = btrfs_commit_transaction(trans);
2341         } else {
2342                 ret = btrfs_end_transaction(trans);
2343         }
2344 out:
2345         ASSERT(list_empty(&ctx.list));
2346         err = file_check_and_advance_wb_err(file);
2347         if (!ret)
2348                 ret = err;
2349         return ret > 0 ? -EIO : ret;
2350
2351 out_release_extents:
2352         btrfs_release_log_ctx_extents(&ctx);
2353         btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
2354         goto out;
2355 }
2356
2357 static const struct vm_operations_struct btrfs_file_vm_ops = {
2358         .fault          = filemap_fault,
2359         .map_pages      = filemap_map_pages,
2360         .page_mkwrite   = btrfs_page_mkwrite,
2361 };
2362
2363 static int btrfs_file_mmap(struct file  *filp, struct vm_area_struct *vma)
2364 {
2365         struct address_space *mapping = filp->f_mapping;
2366
2367         if (!mapping->a_ops->readpage)
2368                 return -ENOEXEC;
2369
2370         file_accessed(filp);
2371         vma->vm_ops = &btrfs_file_vm_ops;
2372
2373         return 0;
2374 }
2375
2376 static int hole_mergeable(struct btrfs_inode *inode, struct extent_buffer *leaf,
2377                           int slot, u64 start, u64 end)
2378 {
2379         struct btrfs_file_extent_item *fi;
2380         struct btrfs_key key;
2381
2382         if (slot < 0 || slot >= btrfs_header_nritems(leaf))
2383                 return 0;
2384
2385         btrfs_item_key_to_cpu(leaf, &key, slot);
2386         if (key.objectid != btrfs_ino(inode) ||
2387             key.type != BTRFS_EXTENT_DATA_KEY)
2388                 return 0;
2389
2390         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
2391
2392         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2393                 return 0;
2394
2395         if (btrfs_file_extent_disk_bytenr(leaf, fi))
2396                 return 0;
2397
2398         if (key.offset == end)
2399                 return 1;
2400         if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
2401                 return 1;
2402         return 0;
2403 }
2404
2405 static int fill_holes(struct btrfs_trans_handle *trans,
2406                 struct btrfs_inode *inode,
2407                 struct btrfs_path *path, u64 offset, u64 end)
2408 {
2409         struct btrfs_fs_info *fs_info = trans->fs_info;
2410         struct btrfs_root *root = inode->root;
2411         struct extent_buffer *leaf;
2412         struct btrfs_file_extent_item *fi;
2413         struct extent_map *hole_em;
2414         struct extent_map_tree *em_tree = &inode->extent_tree;
2415         struct btrfs_key key;
2416         int ret;
2417
2418         if (btrfs_fs_incompat(fs_info, NO_HOLES))
2419                 goto out;
2420
2421         key.objectid = btrfs_ino(inode);
2422         key.type = BTRFS_EXTENT_DATA_KEY;
2423         key.offset = offset;
2424
2425         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2426         if (ret <= 0) {
2427                 /*
2428                  * We should have dropped this offset, so if we find it then
2429                  * something has gone horribly wrong.
2430                  */
2431                 if (ret == 0)
2432                         ret = -EINVAL;
2433                 return ret;
2434         }
2435
2436         leaf = path->nodes[0];
2437         if (hole_mergeable(inode, leaf, path->slots[0] - 1, offset, end)) {
2438                 u64 num_bytes;
2439
2440                 path->slots[0]--;
2441                 fi = btrfs_item_ptr(leaf, path->slots[0],
2442                                     struct btrfs_file_extent_item);
2443                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
2444                         end - offset;
2445                 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2446                 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
2447                 btrfs_set_file_extent_offset(leaf, fi, 0);
2448                 btrfs_mark_buffer_dirty(leaf);
2449                 goto out;
2450         }
2451
2452         if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
2453                 u64 num_bytes;
2454
2455                 key.offset = offset;
2456                 btrfs_set_item_key_safe(fs_info, path, &key);
2457                 fi = btrfs_item_ptr(leaf, path->slots[0],
2458                                     struct btrfs_file_extent_item);
2459                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
2460                         offset;
2461                 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2462                 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
2463                 btrfs_set_file_extent_offset(leaf, fi, 0);
2464                 btrfs_mark_buffer_dirty(leaf);
2465                 goto out;
2466         }
2467         btrfs_release_path(path);
2468
2469         ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
2470                         offset, 0, 0, end - offset, 0, end - offset, 0, 0, 0);
2471         if (ret)
2472                 return ret;
2473
2474 out:
2475         btrfs_release_path(path);
2476
2477         hole_em = alloc_extent_map();
2478         if (!hole_em) {
2479                 btrfs_drop_extent_cache(inode, offset, end - 1, 0);
2480                 btrfs_set_inode_full_sync(inode);
2481         } else {
2482                 hole_em->start = offset;
2483                 hole_em->len = end - offset;
2484                 hole_em->ram_bytes = hole_em->len;
2485                 hole_em->orig_start = offset;
2486
2487                 hole_em->block_start = EXTENT_MAP_HOLE;
2488                 hole_em->block_len = 0;
2489                 hole_em->orig_block_len = 0;
2490                 hole_em->compress_type = BTRFS_COMPRESS_NONE;
2491                 hole_em->generation = trans->transid;
2492
2493                 do {
2494                         btrfs_drop_extent_cache(inode, offset, end - 1, 0);
2495                         write_lock(&em_tree->lock);
2496                         ret = add_extent_mapping(em_tree, hole_em, 1);
2497                         write_unlock(&em_tree->lock);
2498                 } while (ret == -EEXIST);
2499                 free_extent_map(hole_em);
2500                 if (ret)
2501                         btrfs_set_inode_full_sync(inode);
2502         }
2503
2504         return 0;
2505 }
2506
2507 /*
2508  * Find a hole extent on given inode and change start/len to the end of hole
2509  * extent.(hole/vacuum extent whose em->start <= start &&
2510  *         em->start + em->len > start)
2511  * When a hole extent is found, return 1 and modify start/len.
2512  */
2513 static int find_first_non_hole(struct btrfs_inode *inode, u64 *start, u64 *len)
2514 {
2515         struct btrfs_fs_info *fs_info = inode->root->fs_info;
2516         struct extent_map *em;
2517         int ret = 0;
2518
2519         em = btrfs_get_extent(inode, NULL, 0,
2520                               round_down(*start, fs_info->sectorsize),
2521                               round_up(*len, fs_info->sectorsize));
2522         if (IS_ERR(em))
2523                 return PTR_ERR(em);
2524
2525         /* Hole or vacuum extent(only exists in no-hole mode) */
2526         if (em->block_start == EXTENT_MAP_HOLE) {
2527                 ret = 1;
2528                 *len = em->start + em->len > *start + *len ?
2529                        0 : *start + *len - em->start - em->len;
2530                 *start = em->start + em->len;
2531         }
2532         free_extent_map(em);
2533         return ret;
2534 }
2535
2536 static void btrfs_punch_hole_lock_range(struct inode *inode,
2537                                         const u64 lockstart,
2538                                         const u64 lockend,
2539                                         struct extent_state **cached_state)
2540 {
2541         /*
2542          * For subpage case, if the range is not at page boundary, we could
2543          * have pages at the leading/tailing part of the range.
2544          * This could lead to dead loop since filemap_range_has_page()
2545          * will always return true.
2546          * So here we need to do extra page alignment for
2547          * filemap_range_has_page().
2548          */
2549         const u64 page_lockstart = round_up(lockstart, PAGE_SIZE);
2550         const u64 page_lockend = round_down(lockend + 1, PAGE_SIZE) - 1;
2551
2552         while (1) {
2553                 truncate_pagecache_range(inode, lockstart, lockend);
2554
2555                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2556                                  cached_state);
2557                 /*
2558                  * We can't have ordered extents in the range, nor dirty/writeback
2559                  * pages, because we have locked the inode's VFS lock in exclusive
2560                  * mode, we have locked the inode's i_mmap_lock in exclusive mode,
2561                  * we have flushed all delalloc in the range and we have waited
2562                  * for any ordered extents in the range to complete.
2563                  * We can race with anyone reading pages from this range, so after
2564                  * locking the range check if we have pages in the range, and if
2565                  * we do, unlock the range and retry.
2566                  */
2567                 if (!filemap_range_has_page(inode->i_mapping, page_lockstart,
2568                                             page_lockend))
2569                         break;
2570
2571                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
2572                                      lockend, cached_state);
2573         }
2574
2575         btrfs_assert_inode_range_clean(BTRFS_I(inode), lockstart, lockend);
2576 }
2577
2578 static int btrfs_insert_replace_extent(struct btrfs_trans_handle *trans,
2579                                      struct btrfs_inode *inode,
2580                                      struct btrfs_path *path,
2581                                      struct btrfs_replace_extent_info *extent_info,
2582                                      const u64 replace_len,
2583                                      const u64 bytes_to_drop)
2584 {
2585         struct btrfs_fs_info *fs_info = trans->fs_info;
2586         struct btrfs_root *root = inode->root;
2587         struct btrfs_file_extent_item *extent;
2588         struct extent_buffer *leaf;
2589         struct btrfs_key key;
2590         int slot;
2591         struct btrfs_ref ref = { 0 };
2592         int ret;
2593
2594         if (replace_len == 0)
2595                 return 0;
2596
2597         if (extent_info->disk_offset == 0 &&
2598             btrfs_fs_incompat(fs_info, NO_HOLES)) {
2599                 btrfs_update_inode_bytes(inode, 0, bytes_to_drop);
2600                 return 0;
2601         }
2602
2603         key.objectid = btrfs_ino(inode);
2604         key.type = BTRFS_EXTENT_DATA_KEY;
2605         key.offset = extent_info->file_offset;
2606         ret = btrfs_insert_empty_item(trans, root, path, &key,
2607                                       sizeof(struct btrfs_file_extent_item));
2608         if (ret)
2609                 return ret;
2610         leaf = path->nodes[0];
2611         slot = path->slots[0];
2612         write_extent_buffer(leaf, extent_info->extent_buf,
2613                             btrfs_item_ptr_offset(leaf, slot),
2614                             sizeof(struct btrfs_file_extent_item));
2615         extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
2616         ASSERT(btrfs_file_extent_type(leaf, extent) != BTRFS_FILE_EXTENT_INLINE);
2617         btrfs_set_file_extent_offset(leaf, extent, extent_info->data_offset);
2618         btrfs_set_file_extent_num_bytes(leaf, extent, replace_len);
2619         if (extent_info->is_new_extent)
2620                 btrfs_set_file_extent_generation(leaf, extent, trans->transid);
2621         btrfs_mark_buffer_dirty(leaf);
2622         btrfs_release_path(path);
2623
2624         ret = btrfs_inode_set_file_extent_range(inode, extent_info->file_offset,
2625                                                 replace_len);
2626         if (ret)
2627                 return ret;
2628
2629         /* If it's a hole, nothing more needs to be done. */
2630         if (extent_info->disk_offset == 0) {
2631                 btrfs_update_inode_bytes(inode, 0, bytes_to_drop);
2632                 return 0;
2633         }
2634
2635         btrfs_update_inode_bytes(inode, replace_len, bytes_to_drop);
2636
2637         if (extent_info->is_new_extent && extent_info->insertions == 0) {
2638                 key.objectid = extent_info->disk_offset;
2639                 key.type = BTRFS_EXTENT_ITEM_KEY;
2640                 key.offset = extent_info->disk_len;
2641                 ret = btrfs_alloc_reserved_file_extent(trans, root,
2642                                                        btrfs_ino(inode),
2643                                                        extent_info->file_offset,
2644                                                        extent_info->qgroup_reserved,
2645                                                        &key);
2646         } else {
2647                 u64 ref_offset;
2648
2649                 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF,
2650                                        extent_info->disk_offset,
2651                                        extent_info->disk_len, 0);
2652                 ref_offset = extent_info->file_offset - extent_info->data_offset;
2653                 btrfs_init_data_ref(&ref, root->root_key.objectid,
2654                                     btrfs_ino(inode), ref_offset, 0, false);
2655                 ret = btrfs_inc_extent_ref(trans, &ref);
2656         }
2657
2658         extent_info->insertions++;
2659
2660         return ret;
2661 }
2662
2663 /*
2664  * The respective range must have been previously locked, as well as the inode.
2665  * The end offset is inclusive (last byte of the range).
2666  * @extent_info is NULL for fallocate's hole punching and non-NULL when replacing
2667  * the file range with an extent.
2668  * When not punching a hole, we don't want to end up in a state where we dropped
2669  * extents without inserting a new one, so we must abort the transaction to avoid
2670  * a corruption.
2671  */
2672 int btrfs_replace_file_extents(struct btrfs_inode *inode,
2673                                struct btrfs_path *path, const u64 start,
2674                                const u64 end,
2675                                struct btrfs_replace_extent_info *extent_info,
2676                                struct btrfs_trans_handle **trans_out)
2677 {
2678         struct btrfs_drop_extents_args drop_args = { 0 };
2679         struct btrfs_root *root = inode->root;
2680         struct btrfs_fs_info *fs_info = root->fs_info;
2681         u64 min_size = btrfs_calc_insert_metadata_size(fs_info, 1);
2682         u64 ino_size = round_up(inode->vfs_inode.i_size, fs_info->sectorsize);
2683         struct btrfs_trans_handle *trans = NULL;
2684         struct btrfs_block_rsv *rsv;
2685         unsigned int rsv_count;
2686         u64 cur_offset;
2687         u64 len = end - start;
2688         int ret = 0;
2689
2690         if (end <= start)
2691                 return -EINVAL;
2692
2693         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
2694         if (!rsv) {
2695                 ret = -ENOMEM;
2696                 goto out;
2697         }
2698         rsv->size = btrfs_calc_insert_metadata_size(fs_info, 1);
2699         rsv->failfast = 1;
2700
2701         /*
2702          * 1 - update the inode
2703          * 1 - removing the extents in the range
2704          * 1 - adding the hole extent if no_holes isn't set or if we are
2705          *     replacing the range with a new extent
2706          */
2707         if (!btrfs_fs_incompat(fs_info, NO_HOLES) || extent_info)
2708                 rsv_count = 3;
2709         else
2710                 rsv_count = 2;
2711
2712         trans = btrfs_start_transaction(root, rsv_count);
2713         if (IS_ERR(trans)) {
2714                 ret = PTR_ERR(trans);
2715                 trans = NULL;
2716                 goto out_free;
2717         }
2718
2719         ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
2720                                       min_size, false);
2721         BUG_ON(ret);
2722         trans->block_rsv = rsv;
2723
2724         cur_offset = start;
2725         drop_args.path = path;
2726         drop_args.end = end + 1;
2727         drop_args.drop_cache = true;
2728         while (cur_offset < end) {
2729                 drop_args.start = cur_offset;
2730                 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2731                 /* If we are punching a hole decrement the inode's byte count */
2732                 if (!extent_info)
2733                         btrfs_update_inode_bytes(inode, 0,
2734                                                  drop_args.bytes_found);
2735                 if (ret != -ENOSPC) {
2736                         /*
2737                          * The only time we don't want to abort is if we are
2738                          * attempting to clone a partial inline extent, in which
2739                          * case we'll get EOPNOTSUPP.  However if we aren't
2740                          * clone we need to abort no matter what, because if we
2741                          * got EOPNOTSUPP via prealloc then we messed up and
2742                          * need to abort.
2743                          */
2744                         if (ret &&
2745                             (ret != -EOPNOTSUPP ||
2746                              (extent_info && extent_info->is_new_extent)))
2747                                 btrfs_abort_transaction(trans, ret);
2748                         break;
2749                 }
2750
2751                 trans->block_rsv = &fs_info->trans_block_rsv;
2752
2753                 if (!extent_info && cur_offset < drop_args.drop_end &&
2754                     cur_offset < ino_size) {
2755                         ret = fill_holes(trans, inode, path, cur_offset,
2756                                          drop_args.drop_end);
2757                         if (ret) {
2758                                 /*
2759                                  * If we failed then we didn't insert our hole
2760                                  * entries for the area we dropped, so now the
2761                                  * fs is corrupted, so we must abort the
2762                                  * transaction.
2763                                  */
2764                                 btrfs_abort_transaction(trans, ret);
2765                                 break;
2766                         }
2767                 } else if (!extent_info && cur_offset < drop_args.drop_end) {
2768                         /*
2769                          * We are past the i_size here, but since we didn't
2770                          * insert holes we need to clear the mapped area so we
2771                          * know to not set disk_i_size in this area until a new
2772                          * file extent is inserted here.
2773                          */
2774                         ret = btrfs_inode_clear_file_extent_range(inode,
2775                                         cur_offset,
2776                                         drop_args.drop_end - cur_offset);
2777                         if (ret) {
2778                                 /*
2779                                  * We couldn't clear our area, so we could
2780                                  * presumably adjust up and corrupt the fs, so
2781                                  * we need to abort.
2782                                  */
2783                                 btrfs_abort_transaction(trans, ret);
2784                                 break;
2785                         }
2786                 }
2787
2788                 if (extent_info &&
2789                     drop_args.drop_end > extent_info->file_offset) {
2790                         u64 replace_len = drop_args.drop_end -
2791                                           extent_info->file_offset;
2792
2793                         ret = btrfs_insert_replace_extent(trans, inode, path,
2794                                         extent_info, replace_len,
2795                                         drop_args.bytes_found);
2796                         if (ret) {
2797                                 btrfs_abort_transaction(trans, ret);
2798                                 break;
2799                         }
2800                         extent_info->data_len -= replace_len;
2801                         extent_info->data_offset += replace_len;
2802                         extent_info->file_offset += replace_len;
2803                 }
2804
2805                 /*
2806                  * We are releasing our handle on the transaction, balance the
2807                  * dirty pages of the btree inode and flush delayed items, and
2808                  * then get a new transaction handle, which may now point to a
2809                  * new transaction in case someone else may have committed the
2810                  * transaction we used to replace/drop file extent items. So
2811                  * bump the inode's iversion and update mtime and ctime except
2812                  * if we are called from a dedupe context. This is because a
2813                  * power failure/crash may happen after the transaction is
2814                  * committed and before we finish replacing/dropping all the
2815                  * file extent items we need.
2816                  */
2817                 inode_inc_iversion(&inode->vfs_inode);
2818
2819                 if (!extent_info || extent_info->update_times) {
2820                         inode->vfs_inode.i_mtime = current_time(&inode->vfs_inode);
2821                         inode->vfs_inode.i_ctime = inode->vfs_inode.i_mtime;
2822                 }
2823
2824                 ret = btrfs_update_inode(trans, root, inode);
2825                 if (ret)
2826                         break;
2827
2828                 btrfs_end_transaction(trans);
2829                 btrfs_btree_balance_dirty(fs_info);
2830
2831                 trans = btrfs_start_transaction(root, rsv_count);
2832                 if (IS_ERR(trans)) {
2833                         ret = PTR_ERR(trans);
2834                         trans = NULL;
2835                         break;
2836                 }
2837
2838                 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
2839                                               rsv, min_size, false);
2840                 BUG_ON(ret);    /* shouldn't happen */
2841                 trans->block_rsv = rsv;
2842
2843                 cur_offset = drop_args.drop_end;
2844                 len = end - cur_offset;
2845                 if (!extent_info && len) {
2846                         ret = find_first_non_hole(inode, &cur_offset, &len);
2847                         if (unlikely(ret < 0))
2848                                 break;
2849                         if (ret && !len) {
2850                                 ret = 0;
2851                                 break;
2852                         }
2853                 }
2854         }
2855
2856         /*
2857          * If we were cloning, force the next fsync to be a full one since we
2858          * we replaced (or just dropped in the case of cloning holes when
2859          * NO_HOLES is enabled) file extent items and did not setup new extent
2860          * maps for the replacement extents (or holes).
2861          */
2862         if (extent_info && !extent_info->is_new_extent)
2863                 btrfs_set_inode_full_sync(inode);
2864
2865         if (ret)
2866                 goto out_trans;
2867
2868         trans->block_rsv = &fs_info->trans_block_rsv;
2869         /*
2870          * If we are using the NO_HOLES feature we might have had already an
2871          * hole that overlaps a part of the region [lockstart, lockend] and
2872          * ends at (or beyond) lockend. Since we have no file extent items to
2873          * represent holes, drop_end can be less than lockend and so we must
2874          * make sure we have an extent map representing the existing hole (the
2875          * call to __btrfs_drop_extents() might have dropped the existing extent
2876          * map representing the existing hole), otherwise the fast fsync path
2877          * will not record the existence of the hole region
2878          * [existing_hole_start, lockend].
2879          */
2880         if (drop_args.drop_end <= end)
2881                 drop_args.drop_end = end + 1;
2882         /*
2883          * Don't insert file hole extent item if it's for a range beyond eof
2884          * (because it's useless) or if it represents a 0 bytes range (when
2885          * cur_offset == drop_end).
2886          */
2887         if (!extent_info && cur_offset < ino_size &&
2888             cur_offset < drop_args.drop_end) {
2889                 ret = fill_holes(trans, inode, path, cur_offset,
2890                                  drop_args.drop_end);
2891                 if (ret) {
2892                         /* Same comment as above. */
2893                         btrfs_abort_transaction(trans, ret);
2894                         goto out_trans;
2895                 }
2896         } else if (!extent_info && cur_offset < drop_args.drop_end) {
2897                 /* See the comment in the loop above for the reasoning here. */
2898                 ret = btrfs_inode_clear_file_extent_range(inode, cur_offset,
2899                                         drop_args.drop_end - cur_offset);
2900                 if (ret) {
2901                         btrfs_abort_transaction(trans, ret);
2902                         goto out_trans;
2903                 }
2904
2905         }
2906         if (extent_info) {
2907                 ret = btrfs_insert_replace_extent(trans, inode, path,
2908                                 extent_info, extent_info->data_len,
2909                                 drop_args.bytes_found);
2910                 if (ret) {
2911                         btrfs_abort_transaction(trans, ret);
2912                         goto out_trans;
2913                 }
2914         }
2915
2916 out_trans:
2917         if (!trans)
2918                 goto out_free;
2919
2920         trans->block_rsv = &fs_info->trans_block_rsv;
2921         if (ret)
2922                 btrfs_end_transaction(trans);
2923         else
2924                 *trans_out = trans;
2925 out_free:
2926         btrfs_free_block_rsv(fs_info, rsv);
2927 out:
2928         return ret;
2929 }
2930
2931 static int btrfs_punch_hole(struct file *file, loff_t offset, loff_t len)
2932 {
2933         struct inode *inode = file_inode(file);
2934         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2935         struct btrfs_root *root = BTRFS_I(inode)->root;
2936         struct extent_state *cached_state = NULL;
2937         struct btrfs_path *path;
2938         struct btrfs_trans_handle *trans = NULL;
2939         u64 lockstart;
2940         u64 lockend;
2941         u64 tail_start;
2942         u64 tail_len;
2943         u64 orig_start = offset;
2944         int ret = 0;
2945         bool same_block;
2946         u64 ino_size;
2947         bool truncated_block = false;
2948         bool updated_inode = false;
2949
2950         btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
2951
2952         ret = btrfs_wait_ordered_range(inode, offset, len);
2953         if (ret)
2954                 goto out_only_mutex;
2955
2956         ino_size = round_up(inode->i_size, fs_info->sectorsize);
2957         ret = find_first_non_hole(BTRFS_I(inode), &offset, &len);
2958         if (ret < 0)
2959                 goto out_only_mutex;
2960         if (ret && !len) {
2961                 /* Already in a large hole */
2962                 ret = 0;
2963                 goto out_only_mutex;
2964         }
2965
2966         ret = file_modified(file);
2967         if (ret)
2968                 goto out_only_mutex;
2969
2970         lockstart = round_up(offset, btrfs_inode_sectorsize(BTRFS_I(inode)));
2971         lockend = round_down(offset + len,
2972                              btrfs_inode_sectorsize(BTRFS_I(inode))) - 1;
2973         same_block = (BTRFS_BYTES_TO_BLKS(fs_info, offset))
2974                 == (BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1));
2975         /*
2976          * We needn't truncate any block which is beyond the end of the file
2977          * because we are sure there is no data there.
2978          */
2979         /*
2980          * Only do this if we are in the same block and we aren't doing the
2981          * entire block.
2982          */
2983         if (same_block && len < fs_info->sectorsize) {
2984                 if (offset < ino_size) {
2985                         truncated_block = true;
2986                         ret = btrfs_truncate_block(BTRFS_I(inode), offset, len,
2987                                                    0);
2988                 } else {
2989                         ret = 0;
2990                 }
2991                 goto out_only_mutex;
2992         }
2993
2994         /* zero back part of the first block */
2995         if (offset < ino_size) {
2996                 truncated_block = true;
2997                 ret = btrfs_truncate_block(BTRFS_I(inode), offset, 0, 0);
2998                 if (ret) {
2999                         btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
3000                         return ret;
3001                 }
3002         }
3003
3004         /* Check the aligned pages after the first unaligned page,
3005          * if offset != orig_start, which means the first unaligned page
3006          * including several following pages are already in holes,
3007          * the extra check can be skipped */
3008         if (offset == orig_start) {
3009                 /* after truncate page, check hole again */
3010                 len = offset + len - lockstart;
3011                 offset = lockstart;
3012                 ret = find_first_non_hole(BTRFS_I(inode), &offset, &len);
3013                 if (ret < 0)
3014                         goto out_only_mutex;
3015                 if (ret && !len) {
3016                         ret = 0;
3017                         goto out_only_mutex;
3018                 }
3019                 lockstart = offset;
3020         }
3021
3022         /* Check the tail unaligned part is in a hole */
3023         tail_start = lockend + 1;
3024         tail_len = offset + len - tail_start;
3025         if (tail_len) {
3026                 ret = find_first_non_hole(BTRFS_I(inode), &tail_start, &tail_len);
3027                 if (unlikely(ret < 0))
3028                         goto out_only_mutex;
3029                 if (!ret) {
3030                         /* zero the front end of the last page */
3031                         if (tail_start + tail_len < ino_size) {
3032                                 truncated_block = true;
3033                                 ret = btrfs_truncate_block(BTRFS_I(inode),
3034                                                         tail_start + tail_len,
3035                                                         0, 1);
3036                                 if (ret)
3037                                         goto out_only_mutex;
3038                         }
3039                 }
3040         }
3041
3042         if (lockend < lockstart) {
3043                 ret = 0;
3044                 goto out_only_mutex;
3045         }
3046
3047         btrfs_punch_hole_lock_range(inode, lockstart, lockend, &cached_state);
3048
3049         path = btrfs_alloc_path();
3050         if (!path) {
3051                 ret = -ENOMEM;
3052                 goto out;
3053         }
3054
3055         ret = btrfs_replace_file_extents(BTRFS_I(inode), path, lockstart,
3056                                          lockend, NULL, &trans);
3057         btrfs_free_path(path);
3058         if (ret)
3059                 goto out;
3060
3061         ASSERT(trans != NULL);
3062         inode_inc_iversion(inode);
3063         inode->i_mtime = inode->i_ctime = current_time(inode);
3064         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
3065         updated_inode = true;
3066         btrfs_end_transaction(trans);
3067         btrfs_btree_balance_dirty(fs_info);
3068 out:
3069         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
3070                              &cached_state);
3071 out_only_mutex:
3072         if (!updated_inode && truncated_block && !ret) {
3073                 /*
3074                  * If we only end up zeroing part of a page, we still need to
3075                  * update the inode item, so that all the time fields are
3076                  * updated as well as the necessary btrfs inode in memory fields
3077                  * for detecting, at fsync time, if the inode isn't yet in the
3078                  * log tree or it's there but not up to date.
3079                  */
3080                 struct timespec64 now = current_time(inode);
3081
3082                 inode_inc_iversion(inode);
3083                 inode->i_mtime = now;
3084                 inode->i_ctime = now;
3085                 trans = btrfs_start_transaction(root, 1);
3086                 if (IS_ERR(trans)) {
3087                         ret = PTR_ERR(trans);
3088                 } else {
3089                         int ret2;
3090
3091                         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
3092                         ret2 = btrfs_end_transaction(trans);
3093                         if (!ret)
3094                                 ret = ret2;
3095                 }
3096         }
3097         btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
3098         return ret;
3099 }
3100
3101 /* Helper structure to record which range is already reserved */
3102 struct falloc_range {
3103         struct list_head list;
3104         u64 start;
3105         u64 len;
3106 };
3107
3108 /*
3109  * Helper function to add falloc range
3110  *
3111  * Caller should have locked the larger range of extent containing
3112  * [start, len)
3113  */
3114 static int add_falloc_range(struct list_head *head, u64 start, u64 len)
3115 {
3116         struct falloc_range *range = NULL;
3117
3118         if (!list_empty(head)) {
3119                 /*
3120                  * As fallocate iterates by bytenr order, we only need to check
3121                  * the last range.
3122                  */
3123                 range = list_last_entry(head, struct falloc_range, list);
3124                 if (range->start + range->len == start) {
3125                         range->len += len;
3126                         return 0;
3127                 }
3128         }
3129
3130         range = kmalloc(sizeof(*range), GFP_KERNEL);
3131         if (!range)
3132                 return -ENOMEM;
3133         range->start = start;
3134         range->len = len;
3135         list_add_tail(&range->list, head);
3136         return 0;
3137 }
3138
3139 static int btrfs_fallocate_update_isize(struct inode *inode,
3140                                         const u64 end,
3141                                         const int mode)
3142 {
3143         struct btrfs_trans_handle *trans;
3144         struct btrfs_root *root = BTRFS_I(inode)->root;
3145         int ret;
3146         int ret2;
3147
3148         if (mode & FALLOC_FL_KEEP_SIZE || end <= i_size_read(inode))
3149                 return 0;
3150
3151         trans = btrfs_start_transaction(root, 1);
3152         if (IS_ERR(trans))
3153                 return PTR_ERR(trans);
3154
3155         inode->i_ctime = current_time(inode);
3156         i_size_write(inode, end);
3157         btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
3158         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
3159         ret2 = btrfs_end_transaction(trans);
3160
3161         return ret ? ret : ret2;
3162 }
3163
3164 enum {
3165         RANGE_BOUNDARY_WRITTEN_EXTENT,
3166         RANGE_BOUNDARY_PREALLOC_EXTENT,
3167         RANGE_BOUNDARY_HOLE,
3168 };
3169
3170 static int btrfs_zero_range_check_range_boundary(struct btrfs_inode *inode,
3171                                                  u64 offset)
3172 {
3173         const u64 sectorsize = btrfs_inode_sectorsize(inode);
3174         struct extent_map *em;
3175         int ret;
3176
3177         offset = round_down(offset, sectorsize);
3178         em = btrfs_get_extent(inode, NULL, 0, offset, sectorsize);
3179         if (IS_ERR(em))
3180                 return PTR_ERR(em);
3181
3182         if (em->block_start == EXTENT_MAP_HOLE)
3183                 ret = RANGE_BOUNDARY_HOLE;
3184         else if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3185                 ret = RANGE_BOUNDARY_PREALLOC_EXTENT;
3186         else
3187                 ret = RANGE_BOUNDARY_WRITTEN_EXTENT;
3188
3189         free_extent_map(em);
3190         return ret;
3191 }
3192
3193 static int btrfs_zero_range(struct inode *inode,
3194                             loff_t offset,
3195                             loff_t len,
3196                             const int mode)
3197 {
3198         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3199         struct extent_map *em;
3200         struct extent_changeset *data_reserved = NULL;
3201         int ret;
3202         u64 alloc_hint = 0;
3203         const u64 sectorsize = btrfs_inode_sectorsize(BTRFS_I(inode));
3204         u64 alloc_start = round_down(offset, sectorsize);
3205         u64 alloc_end = round_up(offset + len, sectorsize);
3206         u64 bytes_to_reserve = 0;
3207         bool space_reserved = false;
3208
3209         em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, alloc_start,
3210                               alloc_end - alloc_start);
3211         if (IS_ERR(em)) {
3212                 ret = PTR_ERR(em);
3213                 goto out;
3214         }
3215
3216         /*
3217          * Avoid hole punching and extent allocation for some cases. More cases
3218          * could be considered, but these are unlikely common and we keep things
3219          * as simple as possible for now. Also, intentionally, if the target
3220          * range contains one or more prealloc extents together with regular
3221          * extents and holes, we drop all the existing extents and allocate a
3222          * new prealloc extent, so that we get a larger contiguous disk extent.
3223          */
3224         if (em->start <= alloc_start &&
3225             test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3226                 const u64 em_end = em->start + em->len;
3227
3228                 if (em_end >= offset + len) {
3229                         /*
3230                          * The whole range is already a prealloc extent,
3231                          * do nothing except updating the inode's i_size if
3232                          * needed.
3233                          */
3234                         free_extent_map(em);
3235                         ret = btrfs_fallocate_update_isize(inode, offset + len,
3236                                                            mode);
3237                         goto out;
3238                 }
3239                 /*
3240                  * Part of the range is already a prealloc extent, so operate
3241                  * only on the remaining part of the range.
3242                  */
3243                 alloc_start = em_end;
3244                 ASSERT(IS_ALIGNED(alloc_start, sectorsize));
3245                 len = offset + len - alloc_start;
3246                 offset = alloc_start;
3247                 alloc_hint = em->block_start + em->len;
3248         }
3249         free_extent_map(em);
3250
3251         if (BTRFS_BYTES_TO_BLKS(fs_info, offset) ==
3252             BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1)) {
3253                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, alloc_start,
3254                                       sectorsize);
3255                 if (IS_ERR(em)) {
3256                         ret = PTR_ERR(em);
3257                         goto out;
3258                 }
3259
3260                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3261                         free_extent_map(em);
3262                         ret = btrfs_fallocate_update_isize(inode, offset + len,
3263                                                            mode);
3264                         goto out;
3265                 }
3266                 if (len < sectorsize && em->block_start != EXTENT_MAP_HOLE) {
3267                         free_extent_map(em);
3268                         ret = btrfs_truncate_block(BTRFS_I(inode), offset, len,
3269                                                    0);
3270                         if (!ret)
3271                                 ret = btrfs_fallocate_update_isize(inode,
3272                                                                    offset + len,
3273                                                                    mode);
3274                         return ret;
3275                 }
3276                 free_extent_map(em);
3277                 alloc_start = round_down(offset, sectorsize);
3278                 alloc_end = alloc_start + sectorsize;
3279                 goto reserve_space;
3280         }
3281
3282         alloc_start = round_up(offset, sectorsize);
3283         alloc_end = round_down(offset + len, sectorsize);
3284
3285         /*
3286          * For unaligned ranges, check the pages at the boundaries, they might
3287          * map to an extent, in which case we need to partially zero them, or
3288          * they might map to a hole, in which case we need our allocation range
3289          * to cover them.
3290          */
3291         if (!IS_ALIGNED(offset, sectorsize)) {
3292                 ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode),
3293                                                             offset);
3294                 if (ret < 0)
3295                         goto out;
3296                 if (ret == RANGE_BOUNDARY_HOLE) {
3297                         alloc_start = round_down(offset, sectorsize);
3298                         ret = 0;
3299                 } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
3300                         ret = btrfs_truncate_block(BTRFS_I(inode), offset, 0, 0);
3301                         if (ret)
3302                                 goto out;
3303                 } else {
3304                         ret = 0;
3305                 }
3306         }
3307
3308         if (!IS_ALIGNED(offset + len, sectorsize)) {
3309                 ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode),
3310                                                             offset + len);
3311                 if (ret < 0)
3312                         goto out;
3313                 if (ret == RANGE_BOUNDARY_HOLE) {
3314                         alloc_end = round_up(offset + len, sectorsize);
3315                         ret = 0;
3316                 } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
3317                         ret = btrfs_truncate_block(BTRFS_I(inode), offset + len,
3318                                                    0, 1);
3319                         if (ret)
3320                                 goto out;
3321                 } else {
3322                         ret = 0;
3323                 }
3324         }
3325
3326 reserve_space:
3327         if (alloc_start < alloc_end) {
3328                 struct extent_state *cached_state = NULL;
3329                 const u64 lockstart = alloc_start;
3330                 const u64 lockend = alloc_end - 1;
3331
3332                 bytes_to_reserve = alloc_end - alloc_start;
3333                 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
3334                                                       bytes_to_reserve);
3335                 if (ret < 0)
3336                         goto out;
3337                 space_reserved = true;
3338                 btrfs_punch_hole_lock_range(inode, lockstart, lockend,
3339                                             &cached_state);
3340                 ret = btrfs_qgroup_reserve_data(BTRFS_I(inode), &data_reserved,
3341                                                 alloc_start, bytes_to_reserve);
3342                 if (ret) {
3343                         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
3344                                              lockend, &cached_state);
3345                         goto out;
3346                 }
3347                 ret = btrfs_prealloc_file_range(inode, mode, alloc_start,
3348                                                 alloc_end - alloc_start,
3349                                                 i_blocksize(inode),
3350                                                 offset + len, &alloc_hint);
3351                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
3352                                      lockend, &cached_state);
3353                 /* btrfs_prealloc_file_range releases reserved space on error */
3354                 if (ret) {
3355                         space_reserved = false;
3356                         goto out;
3357                 }
3358         }
3359         ret = btrfs_fallocate_update_isize(inode, offset + len, mode);
3360  out:
3361         if (ret && space_reserved)
3362                 btrfs_free_reserved_data_space(BTRFS_I(inode), data_reserved,
3363                                                alloc_start, bytes_to_reserve);
3364         extent_changeset_free(data_reserved);
3365
3366         return ret;
3367 }
3368
3369 static long btrfs_fallocate(struct file *file, int mode,
3370                             loff_t offset, loff_t len)
3371 {
3372         struct inode *inode = file_inode(file);
3373         struct extent_state *cached_state = NULL;
3374         struct extent_changeset *data_reserved = NULL;
3375         struct falloc_range *range;
3376         struct falloc_range *tmp;
3377         struct list_head reserve_list;
3378         u64 cur_offset;
3379         u64 last_byte;
3380         u64 alloc_start;
3381         u64 alloc_end;
3382         u64 alloc_hint = 0;
3383         u64 locked_end;
3384         u64 actual_end = 0;
3385         u64 data_space_needed = 0;
3386         u64 data_space_reserved = 0;
3387         u64 qgroup_reserved = 0;
3388         struct extent_map *em;
3389         int blocksize = btrfs_inode_sectorsize(BTRFS_I(inode));
3390         int ret;
3391
3392         /* Do not allow fallocate in ZONED mode */
3393         if (btrfs_is_zoned(btrfs_sb(inode->i_sb)))
3394                 return -EOPNOTSUPP;
3395
3396         alloc_start = round_down(offset, blocksize);
3397         alloc_end = round_up(offset + len, blocksize);
3398         cur_offset = alloc_start;
3399
3400         /* Make sure we aren't being give some crap mode */
3401         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
3402                      FALLOC_FL_ZERO_RANGE))
3403                 return -EOPNOTSUPP;
3404
3405         if (mode & FALLOC_FL_PUNCH_HOLE)
3406                 return btrfs_punch_hole(file, offset, len);
3407
3408         btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
3409
3410         if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) {
3411                 ret = inode_newsize_ok(inode, offset + len);
3412                 if (ret)
3413                         goto out;
3414         }
3415
3416         ret = file_modified(file);
3417         if (ret)
3418                 goto out;
3419
3420         /*
3421          * TODO: Move these two operations after we have checked
3422          * accurate reserved space, or fallocate can still fail but
3423          * with page truncated or size expanded.
3424          *
3425          * But that's a minor problem and won't do much harm BTW.
3426          */
3427         if (alloc_start > inode->i_size) {
3428                 ret = btrfs_cont_expand(BTRFS_I(inode), i_size_read(inode),
3429                                         alloc_start);
3430                 if (ret)
3431                         goto out;
3432         } else if (offset + len > inode->i_size) {
3433                 /*
3434                  * If we are fallocating from the end of the file onward we
3435                  * need to zero out the end of the block if i_size lands in the
3436                  * middle of a block.
3437                  */
3438                 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
3439                 if (ret)
3440                         goto out;
3441         }
3442
3443         /*
3444          * We have locked the inode at the VFS level (in exclusive mode) and we
3445          * have locked the i_mmap_lock lock (in exclusive mode). Now before
3446          * locking the file range, flush all dealloc in the range and wait for
3447          * all ordered extents in the range to complete. After this we can lock
3448          * the file range and, due to the previous locking we did, we know there
3449          * can't be more delalloc or ordered extents in the range.
3450          */
3451         ret = btrfs_wait_ordered_range(inode, alloc_start,
3452                                        alloc_end - alloc_start);
3453         if (ret)
3454                 goto out;
3455
3456         if (mode & FALLOC_FL_ZERO_RANGE) {
3457                 ret = btrfs_zero_range(inode, offset, len, mode);
3458                 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
3459                 return ret;
3460         }
3461
3462         locked_end = alloc_end - 1;
3463         lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
3464                          &cached_state);
3465
3466         btrfs_assert_inode_range_clean(BTRFS_I(inode), alloc_start, locked_end);
3467
3468         /* First, check if we exceed the qgroup limit */
3469         INIT_LIST_HEAD(&reserve_list);
3470         while (cur_offset < alloc_end) {
3471                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
3472                                       alloc_end - cur_offset);
3473                 if (IS_ERR(em)) {
3474                         ret = PTR_ERR(em);
3475                         break;
3476                 }
3477                 last_byte = min(extent_map_end(em), alloc_end);
3478                 actual_end = min_t(u64, extent_map_end(em), offset + len);
3479                 last_byte = ALIGN(last_byte, blocksize);
3480                 if (em->block_start == EXTENT_MAP_HOLE ||
3481                     (cur_offset >= inode->i_size &&
3482                      !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
3483                         const u64 range_len = last_byte - cur_offset;
3484
3485                         ret = add_falloc_range(&reserve_list, cur_offset, range_len);
3486                         if (ret < 0) {
3487                                 free_extent_map(em);
3488                                 break;
3489                         }
3490                         ret = btrfs_qgroup_reserve_data(BTRFS_I(inode),
3491                                         &data_reserved, cur_offset, range_len);
3492                         if (ret < 0) {
3493                                 free_extent_map(em);
3494                                 break;
3495                         }
3496                         qgroup_reserved += range_len;
3497                         data_space_needed += range_len;
3498                 }
3499                 free_extent_map(em);
3500                 cur_offset = last_byte;
3501         }
3502
3503         if (!ret && data_space_needed > 0) {
3504                 /*
3505                  * We are safe to reserve space here as we can't have delalloc
3506                  * in the range, see above.
3507                  */
3508                 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
3509                                                       data_space_needed);
3510                 if (!ret)
3511                         data_space_reserved = data_space_needed;
3512         }
3513
3514         /*
3515          * If ret is still 0, means we're OK to fallocate.
3516          * Or just cleanup the list and exit.
3517          */
3518         list_for_each_entry_safe(range, tmp, &reserve_list, list) {
3519                 if (!ret) {
3520                         ret = btrfs_prealloc_file_range(inode, mode,
3521                                         range->start,
3522                                         range->len, i_blocksize(inode),
3523                                         offset + len, &alloc_hint);
3524                         /*
3525                          * btrfs_prealloc_file_range() releases space even
3526                          * if it returns an error.
3527                          */
3528                         data_space_reserved -= range->len;
3529                         qgroup_reserved -= range->len;
3530                 } else if (data_space_reserved > 0) {
3531                         btrfs_free_reserved_data_space(BTRFS_I(inode),
3532                                                data_reserved, range->start,
3533                                                range->len);
3534                         data_space_reserved -= range->len;
3535                         qgroup_reserved -= range->len;
3536                 } else if (qgroup_reserved > 0) {
3537                         btrfs_qgroup_free_data(BTRFS_I(inode), data_reserved,
3538                                                range->start, range->len);
3539                         qgroup_reserved -= range->len;
3540                 }
3541                 list_del(&range->list);
3542                 kfree(range);
3543         }
3544         if (ret < 0)
3545                 goto out_unlock;
3546
3547         /*
3548          * We didn't need to allocate any more space, but we still extended the
3549          * size of the file so we need to update i_size and the inode item.
3550          */
3551         ret = btrfs_fallocate_update_isize(inode, actual_end, mode);
3552 out_unlock:
3553         unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
3554                              &cached_state);
3555 out:
3556         btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
3557         extent_changeset_free(data_reserved);
3558         return ret;
3559 }
3560
3561 static loff_t find_desired_extent(struct btrfs_inode *inode, loff_t offset,
3562                                   int whence)
3563 {
3564         struct btrfs_fs_info *fs_info = inode->root->fs_info;
3565         struct extent_map *em = NULL;
3566         struct extent_state *cached_state = NULL;
3567         loff_t i_size = inode->vfs_inode.i_size;
3568         u64 lockstart;
3569         u64 lockend;
3570         u64 start;
3571         u64 len;
3572         int ret = 0;
3573
3574         if (i_size == 0 || offset >= i_size)
3575                 return -ENXIO;
3576
3577         /*
3578          * offset can be negative, in this case we start finding DATA/HOLE from
3579          * the very start of the file.
3580          */
3581         start = max_t(loff_t, 0, offset);
3582
3583         lockstart = round_down(start, fs_info->sectorsize);
3584         lockend = round_up(i_size, fs_info->sectorsize);
3585         if (lockend <= lockstart)
3586                 lockend = lockstart + fs_info->sectorsize;
3587         lockend--;
3588         len = lockend - lockstart + 1;
3589
3590         lock_extent_bits(&inode->io_tree, lockstart, lockend, &cached_state);
3591
3592         while (start < i_size) {
3593                 em = btrfs_get_extent_fiemap(inode, start, len);
3594                 if (IS_ERR(em)) {
3595                         ret = PTR_ERR(em);
3596                         em = NULL;
3597                         break;
3598                 }
3599
3600                 if (whence == SEEK_HOLE &&
3601                     (em->block_start == EXTENT_MAP_HOLE ||
3602                      test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
3603                         break;
3604                 else if (whence == SEEK_DATA &&
3605                            (em->block_start != EXTENT_MAP_HOLE &&
3606                             !test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
3607                         break;
3608
3609                 start = em->start + em->len;
3610                 free_extent_map(em);
3611                 em = NULL;
3612                 cond_resched();
3613         }
3614         free_extent_map(em);
3615         unlock_extent_cached(&inode->io_tree, lockstart, lockend,
3616                              &cached_state);
3617         if (ret) {
3618                 offset = ret;
3619         } else {
3620                 if (whence == SEEK_DATA && start >= i_size)
3621                         offset = -ENXIO;
3622                 else
3623                         offset = min_t(loff_t, start, i_size);
3624         }
3625
3626         return offset;
3627 }
3628
3629 static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
3630 {
3631         struct inode *inode = file->f_mapping->host;
3632
3633         switch (whence) {
3634         default:
3635                 return generic_file_llseek(file, offset, whence);
3636         case SEEK_DATA:
3637         case SEEK_HOLE:
3638                 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
3639                 offset = find_desired_extent(BTRFS_I(inode), offset, whence);
3640                 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
3641                 break;
3642         }
3643
3644         if (offset < 0)
3645                 return offset;
3646
3647         return vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
3648 }
3649
3650 static int btrfs_file_open(struct inode *inode, struct file *filp)
3651 {
3652         int ret;
3653
3654         filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC;
3655
3656         ret = fsverity_file_open(inode, filp);
3657         if (ret)
3658                 return ret;
3659         return generic_file_open(inode, filp);
3660 }
3661
3662 static int check_direct_read(struct btrfs_fs_info *fs_info,
3663                              const struct iov_iter *iter, loff_t offset)
3664 {
3665         int ret;
3666         int i, seg;
3667
3668         ret = check_direct_IO(fs_info, iter, offset);
3669         if (ret < 0)
3670                 return ret;
3671
3672         if (!iter_is_iovec(iter))
3673                 return 0;
3674
3675         for (seg = 0; seg < iter->nr_segs; seg++)
3676                 for (i = seg + 1; i < iter->nr_segs; i++)
3677                         if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
3678                                 return -EINVAL;
3679         return 0;
3680 }
3681
3682 static ssize_t btrfs_direct_read(struct kiocb *iocb, struct iov_iter *to)
3683 {
3684         struct inode *inode = file_inode(iocb->ki_filp);
3685         size_t prev_left = 0;
3686         ssize_t read = 0;
3687         ssize_t ret;
3688
3689         if (fsverity_active(inode))
3690                 return 0;
3691
3692         if (check_direct_read(btrfs_sb(inode->i_sb), to, iocb->ki_pos))
3693                 return 0;
3694
3695         btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
3696 again:
3697         /*
3698          * This is similar to what we do for direct IO writes, see the comment
3699          * at btrfs_direct_write(), but we also disable page faults in addition
3700          * to disabling them only at the iov_iter level. This is because when
3701          * reading from a hole or prealloc extent, iomap calls iov_iter_zero(),
3702          * which can still trigger page fault ins despite having set ->nofault
3703          * to true of our 'to' iov_iter.
3704          *
3705          * The difference to direct IO writes is that we deadlock when trying
3706          * to lock the extent range in the inode's tree during he page reads
3707          * triggered by the fault in (while for writes it is due to waiting for
3708          * our own ordered extent). This is because for direct IO reads,
3709          * btrfs_dio_iomap_begin() returns with the extent range locked, which
3710          * is only unlocked in the endio callback (end_bio_extent_readpage()).
3711          */
3712         pagefault_disable();
3713         to->nofault = true;
3714         ret = btrfs_dio_rw(iocb, to, read);
3715         to->nofault = false;
3716         pagefault_enable();
3717
3718         /* No increment (+=) because iomap returns a cumulative value. */
3719         if (ret > 0)
3720                 read = ret;
3721
3722         if (iov_iter_count(to) > 0 && (ret == -EFAULT || ret > 0)) {
3723                 const size_t left = iov_iter_count(to);
3724
3725                 if (left == prev_left) {
3726                         /*
3727                          * We didn't make any progress since the last attempt,
3728                          * fallback to a buffered read for the remainder of the
3729                          * range. This is just to avoid any possibility of looping
3730                          * for too long.
3731                          */
3732                         ret = read;
3733                 } else {
3734                         /*
3735                          * We made some progress since the last retry or this is
3736                          * the first time we are retrying. Fault in as many pages
3737                          * as possible and retry.
3738                          */
3739                         fault_in_iov_iter_writeable(to, left);
3740                         prev_left = left;
3741                         goto again;
3742                 }
3743         }
3744         btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
3745         return ret < 0 ? ret : read;
3746 }
3747
3748 static ssize_t btrfs_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
3749 {
3750         ssize_t ret = 0;
3751
3752         if (iocb->ki_flags & IOCB_DIRECT) {
3753                 ret = btrfs_direct_read(iocb, to);
3754                 if (ret < 0 || !iov_iter_count(to) ||
3755                     iocb->ki_pos >= i_size_read(file_inode(iocb->ki_filp)))
3756                         return ret;
3757         }
3758
3759         return filemap_read(iocb, to, ret);
3760 }
3761
3762 const struct file_operations btrfs_file_operations = {
3763         .llseek         = btrfs_file_llseek,
3764         .read_iter      = btrfs_file_read_iter,
3765         .splice_read    = generic_file_splice_read,
3766         .write_iter     = btrfs_file_write_iter,
3767         .splice_write   = iter_file_splice_write,
3768         .mmap           = btrfs_file_mmap,
3769         .open           = btrfs_file_open,
3770         .release        = btrfs_release_file,
3771         .fsync          = btrfs_sync_file,
3772         .fallocate      = btrfs_fallocate,
3773         .unlocked_ioctl = btrfs_ioctl,
3774 #ifdef CONFIG_COMPAT
3775         .compat_ioctl   = btrfs_compat_ioctl,
3776 #endif
3777         .remap_file_range = btrfs_remap_file_range,
3778 };
3779
3780 void __cold btrfs_auto_defrag_exit(void)
3781 {
3782         kmem_cache_destroy(btrfs_inode_defrag_cachep);
3783 }
3784
3785 int __init btrfs_auto_defrag_init(void)
3786 {
3787         btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
3788                                         sizeof(struct inode_defrag), 0,
3789                                         SLAB_MEM_SPREAD,
3790                                         NULL);
3791         if (!btrfs_inode_defrag_cachep)
3792                 return -ENOMEM;
3793
3794         return 0;
3795 }
3796
3797 int btrfs_fdatawrite_range(struct inode *inode, loff_t start, loff_t end)
3798 {
3799         int ret;
3800
3801         /*
3802          * So with compression we will find and lock a dirty page and clear the
3803          * first one as dirty, setup an async extent, and immediately return
3804          * with the entire range locked but with nobody actually marked with
3805          * writeback.  So we can't just filemap_write_and_wait_range() and
3806          * expect it to work since it will just kick off a thread to do the
3807          * actual work.  So we need to call filemap_fdatawrite_range _again_
3808          * since it will wait on the page lock, which won't be unlocked until
3809          * after the pages have been marked as writeback and so we're good to go
3810          * from there.  We have to do this otherwise we'll miss the ordered
3811          * extents and that results in badness.  Please Josef, do not think you
3812          * know better and pull this out at some point in the future, it is
3813          * right and you are wrong.
3814          */
3815         ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
3816         if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
3817                              &BTRFS_I(inode)->runtime_flags))
3818                 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
3819
3820         return ret;
3821 }