~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/btrfs/inode.c

Version: ~ [ linux-5.15-rc5 ] ~ [ linux-5.14.11 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.72 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.152 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.210 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.250 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.286 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.288 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.18.140 ] ~ [ linux-3.16.85 ] ~ [ linux-3.14.79 ] ~ [ linux-3.12.74 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 // SPDX-License-Identifier: GPL-2.0
  2 /*
  3  * Copyright (C) 2007 Oracle.  All rights reserved.
  4  */
  5 
  6 #include <linux/kernel.h>
  7 #include <linux/bio.h>
  8 #include <linux/buffer_head.h>
  9 #include <linux/file.h>
 10 #include <linux/fs.h>
 11 #include <linux/pagemap.h>
 12 #include <linux/highmem.h>
 13 #include <linux/time.h>
 14 #include <linux/init.h>
 15 #include <linux/string.h>
 16 #include <linux/backing-dev.h>
 17 #include <linux/mpage.h>
 18 #include <linux/swap.h>
 19 #include <linux/writeback.h>
 20 #include <linux/compat.h>
 21 #include <linux/bit_spinlock.h>
 22 #include <linux/xattr.h>
 23 #include <linux/posix_acl.h>
 24 #include <linux/falloc.h>
 25 #include <linux/slab.h>
 26 #include <linux/ratelimit.h>
 27 #include <linux/mount.h>
 28 #include <linux/btrfs.h>
 29 #include <linux/blkdev.h>
 30 #include <linux/posix_acl_xattr.h>
 31 #include <linux/uio.h>
 32 #include <linux/magic.h>
 33 #include <linux/iversion.h>
 34 #include <asm/unaligned.h>
 35 #include "ctree.h"
 36 #include "disk-io.h"
 37 #include "transaction.h"
 38 #include "btrfs_inode.h"
 39 #include "print-tree.h"
 40 #include "ordered-data.h"
 41 #include "xattr.h"
 42 #include "tree-log.h"
 43 #include "volumes.h"
 44 #include "compression.h"
 45 #include "locking.h"
 46 #include "free-space-cache.h"
 47 #include "inode-map.h"
 48 #include "backref.h"
 49 #include "props.h"
 50 #include "qgroup.h"
 51 #include "dedupe.h"
 52 
 53 struct btrfs_iget_args {
 54         struct btrfs_key *location;
 55         struct btrfs_root *root;
 56 };
 57 
 58 struct btrfs_dio_data {
 59         u64 reserve;
 60         u64 unsubmitted_oe_range_start;
 61         u64 unsubmitted_oe_range_end;
 62         int overwrite;
 63 };
 64 
 65 static const struct inode_operations btrfs_dir_inode_operations;
 66 static const struct inode_operations btrfs_symlink_inode_operations;
 67 static const struct inode_operations btrfs_dir_ro_inode_operations;
 68 static const struct inode_operations btrfs_special_inode_operations;
 69 static const struct inode_operations btrfs_file_inode_operations;
 70 static const struct address_space_operations btrfs_aops;
 71 static const struct address_space_operations btrfs_symlink_aops;
 72 static const struct file_operations btrfs_dir_file_operations;
 73 static const struct extent_io_ops btrfs_extent_io_ops;
 74 
 75 static struct kmem_cache *btrfs_inode_cachep;
 76 struct kmem_cache *btrfs_trans_handle_cachep;
 77 struct kmem_cache *btrfs_path_cachep;
 78 struct kmem_cache *btrfs_free_space_cachep;
 79 
 80 #define S_SHIFT 12
 81 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
 82         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
 83         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
 84         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
 85         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
 86         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
 87         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
 88         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
 89 };
 90 
 91 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
 92 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
 93 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
 94 static noinline int cow_file_range(struct inode *inode,
 95                                    struct page *locked_page,
 96                                    u64 start, u64 end, u64 delalloc_end,
 97                                    int *page_started, unsigned long *nr_written,
 98                                    int unlock, struct btrfs_dedupe_hash *hash);
 99 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
100                                        u64 orig_start, u64 block_start,
101                                        u64 block_len, u64 orig_block_len,
102                                        u64 ram_bytes, int compress_type,
103                                        int type);
104 
105 static void __endio_write_update_ordered(struct inode *inode,
106                                          const u64 offset, const u64 bytes,
107                                          const bool uptodate);
108 
109 /*
110  * Cleanup all submitted ordered extents in specified range to handle errors
111  * from the fill_dellaloc() callback.
112  *
113  * NOTE: caller must ensure that when an error happens, it can not call
114  * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
115  * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
116  * to be released, which we want to happen only when finishing the ordered
117  * extent (btrfs_finish_ordered_io()). Also note that the caller of the
118  * fill_delalloc() callback already does proper cleanup for the first page of
119  * the range, that is, it invokes the callback writepage_end_io_hook() for the
120  * range of the first page.
121  */
122 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
123                                                  const u64 offset,
124                                                  const u64 bytes)
125 {
126         unsigned long index = offset >> PAGE_SHIFT;
127         unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
128         struct page *page;
129 
130         while (index <= end_index) {
131                 page = find_get_page(inode->i_mapping, index);
132                 index++;
133                 if (!page)
134                         continue;
135                 ClearPagePrivate2(page);
136                 put_page(page);
137         }
138         return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
139                                             bytes - PAGE_SIZE, false);
140 }
141 
142 static int btrfs_dirty_inode(struct inode *inode);
143 
144 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
145 void btrfs_test_inode_set_ops(struct inode *inode)
146 {
147         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
148 }
149 #endif
150 
151 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
152                                      struct inode *inode,  struct inode *dir,
153                                      const struct qstr *qstr)
154 {
155         int err;
156 
157         err = btrfs_init_acl(trans, inode, dir);
158         if (!err)
159                 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
160         return err;
161 }
162 
163 /*
164  * this does all the hard work for inserting an inline extent into
165  * the btree.  The caller should have done a btrfs_drop_extents so that
166  * no overlapping inline items exist in the btree
167  */
168 static int insert_inline_extent(struct btrfs_trans_handle *trans,
169                                 struct btrfs_path *path, int extent_inserted,
170                                 struct btrfs_root *root, struct inode *inode,
171                                 u64 start, size_t size, size_t compressed_size,
172                                 int compress_type,
173                                 struct page **compressed_pages)
174 {
175         struct extent_buffer *leaf;
176         struct page *page = NULL;
177         char *kaddr;
178         unsigned long ptr;
179         struct btrfs_file_extent_item *ei;
180         int ret;
181         size_t cur_size = size;
182         unsigned long offset;
183 
184         if (compressed_size && compressed_pages)
185                 cur_size = compressed_size;
186 
187         inode_add_bytes(inode, size);
188 
189         if (!extent_inserted) {
190                 struct btrfs_key key;
191                 size_t datasize;
192 
193                 key.objectid = btrfs_ino(BTRFS_I(inode));
194                 key.offset = start;
195                 key.type = BTRFS_EXTENT_DATA_KEY;
196 
197                 datasize = btrfs_file_extent_calc_inline_size(cur_size);
198                 path->leave_spinning = 1;
199                 ret = btrfs_insert_empty_item(trans, root, path, &key,
200                                               datasize);
201                 if (ret)
202                         goto fail;
203         }
204         leaf = path->nodes[0];
205         ei = btrfs_item_ptr(leaf, path->slots[0],
206                             struct btrfs_file_extent_item);
207         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
208         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
209         btrfs_set_file_extent_encryption(leaf, ei, 0);
210         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
211         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
212         ptr = btrfs_file_extent_inline_start(ei);
213 
214         if (compress_type != BTRFS_COMPRESS_NONE) {
215                 struct page *cpage;
216                 int i = 0;
217                 while (compressed_size > 0) {
218                         cpage = compressed_pages[i];
219                         cur_size = min_t(unsigned long, compressed_size,
220                                        PAGE_SIZE);
221 
222                         kaddr = kmap_atomic(cpage);
223                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
224                         kunmap_atomic(kaddr);
225 
226                         i++;
227                         ptr += cur_size;
228                         compressed_size -= cur_size;
229                 }
230                 btrfs_set_file_extent_compression(leaf, ei,
231                                                   compress_type);
232         } else {
233                 page = find_get_page(inode->i_mapping,
234                                      start >> PAGE_SHIFT);
235                 btrfs_set_file_extent_compression(leaf, ei, 0);
236                 kaddr = kmap_atomic(page);
237                 offset = start & (PAGE_SIZE - 1);
238                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
239                 kunmap_atomic(kaddr);
240                 put_page(page);
241         }
242         btrfs_mark_buffer_dirty(leaf);
243         btrfs_release_path(path);
244 
245         /*
246          * we're an inline extent, so nobody can
247          * extend the file past i_size without locking
248          * a page we already have locked.
249          *
250          * We must do any isize and inode updates
251          * before we unlock the pages.  Otherwise we
252          * could end up racing with unlink.
253          */
254         BTRFS_I(inode)->disk_i_size = inode->i_size;
255         ret = btrfs_update_inode(trans, root, inode);
256 
257 fail:
258         return ret;
259 }
260 
261 
262 /*
263  * conditionally insert an inline extent into the file.  This
264  * does the checks required to make sure the data is small enough
265  * to fit as an inline extent.
266  */
267 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
268                                           u64 end, size_t compressed_size,
269                                           int compress_type,
270                                           struct page **compressed_pages)
271 {
272         struct btrfs_root *root = BTRFS_I(inode)->root;
273         struct btrfs_fs_info *fs_info = root->fs_info;
274         struct btrfs_trans_handle *trans;
275         u64 isize = i_size_read(inode);
276         u64 actual_end = min(end + 1, isize);
277         u64 inline_len = actual_end - start;
278         u64 aligned_end = ALIGN(end, fs_info->sectorsize);
279         u64 data_len = inline_len;
280         int ret;
281         struct btrfs_path *path;
282         int extent_inserted = 0;
283         u32 extent_item_size;
284 
285         if (compressed_size)
286                 data_len = compressed_size;
287 
288         if (start > 0 ||
289             actual_end > fs_info->sectorsize ||
290             data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
291             (!compressed_size &&
292             (actual_end & (fs_info->sectorsize - 1)) == 0) ||
293             end + 1 < isize ||
294             data_len > fs_info->max_inline) {
295                 return 1;
296         }
297 
298         path = btrfs_alloc_path();
299         if (!path)
300                 return -ENOMEM;
301 
302         trans = btrfs_join_transaction(root);
303         if (IS_ERR(trans)) {
304                 btrfs_free_path(path);
305                 return PTR_ERR(trans);
306         }
307         trans->block_rsv = &BTRFS_I(inode)->block_rsv;
308 
309         if (compressed_size && compressed_pages)
310                 extent_item_size = btrfs_file_extent_calc_inline_size(
311                    compressed_size);
312         else
313                 extent_item_size = btrfs_file_extent_calc_inline_size(
314                     inline_len);
315 
316         ret = __btrfs_drop_extents(trans, root, inode, path,
317                                    start, aligned_end, NULL,
318                                    1, 1, extent_item_size, &extent_inserted);
319         if (ret) {
320                 btrfs_abort_transaction(trans, ret);
321                 goto out;
322         }
323 
324         if (isize > actual_end)
325                 inline_len = min_t(u64, isize, actual_end);
326         ret = insert_inline_extent(trans, path, extent_inserted,
327                                    root, inode, start,
328                                    inline_len, compressed_size,
329                                    compress_type, compressed_pages);
330         if (ret && ret != -ENOSPC) {
331                 btrfs_abort_transaction(trans, ret);
332                 goto out;
333         } else if (ret == -ENOSPC) {
334                 ret = 1;
335                 goto out;
336         }
337 
338         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
339         btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
340 out:
341         /*
342          * Don't forget to free the reserved space, as for inlined extent
343          * it won't count as data extent, free them directly here.
344          * And at reserve time, it's always aligned to page size, so
345          * just free one page here.
346          */
347         btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
348         btrfs_free_path(path);
349         btrfs_end_transaction(trans);
350         return ret;
351 }
352 
353 struct async_extent {
354         u64 start;
355         u64 ram_size;
356         u64 compressed_size;
357         struct page **pages;
358         unsigned long nr_pages;
359         int compress_type;
360         struct list_head list;
361 };
362 
363 struct async_cow {
364         struct inode *inode;
365         struct btrfs_root *root;
366         struct page *locked_page;
367         u64 start;
368         u64 end;
369         unsigned int write_flags;
370         struct list_head extents;
371         struct btrfs_work work;
372 };
373 
374 static noinline int add_async_extent(struct async_cow *cow,
375                                      u64 start, u64 ram_size,
376                                      u64 compressed_size,
377                                      struct page **pages,
378                                      unsigned long nr_pages,
379                                      int compress_type)
380 {
381         struct async_extent *async_extent;
382 
383         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
384         BUG_ON(!async_extent); /* -ENOMEM */
385         async_extent->start = start;
386         async_extent->ram_size = ram_size;
387         async_extent->compressed_size = compressed_size;
388         async_extent->pages = pages;
389         async_extent->nr_pages = nr_pages;
390         async_extent->compress_type = compress_type;
391         list_add_tail(&async_extent->list, &cow->extents);
392         return 0;
393 }
394 
395 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
396 {
397         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
398 
399         /* force compress */
400         if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
401                 return 1;
402         /* defrag ioctl */
403         if (BTRFS_I(inode)->defrag_compress)
404                 return 1;
405         /* bad compression ratios */
406         if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
407                 return 0;
408         if (btrfs_test_opt(fs_info, COMPRESS) ||
409             BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
410             BTRFS_I(inode)->prop_compress)
411                 return btrfs_compress_heuristic(inode, start, end);
412         return 0;
413 }
414 
415 static inline void inode_should_defrag(struct btrfs_inode *inode,
416                 u64 start, u64 end, u64 num_bytes, u64 small_write)
417 {
418         /* If this is a small write inside eof, kick off a defrag */
419         if (num_bytes < small_write &&
420             (start > 0 || end + 1 < inode->disk_i_size))
421                 btrfs_add_inode_defrag(NULL, inode);
422 }
423 
424 /*
425  * we create compressed extents in two phases.  The first
426  * phase compresses a range of pages that have already been
427  * locked (both pages and state bits are locked).
428  *
429  * This is done inside an ordered work queue, and the compression
430  * is spread across many cpus.  The actual IO submission is step
431  * two, and the ordered work queue takes care of making sure that
432  * happens in the same order things were put onto the queue by
433  * writepages and friends.
434  *
435  * If this code finds it can't get good compression, it puts an
436  * entry onto the work queue to write the uncompressed bytes.  This
437  * makes sure that both compressed inodes and uncompressed inodes
438  * are written in the same order that the flusher thread sent them
439  * down.
440  */
441 static noinline void compress_file_range(struct inode *inode,
442                                         struct page *locked_page,
443                                         u64 start, u64 end,
444                                         struct async_cow *async_cow,
445                                         int *num_added)
446 {
447         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
448         u64 blocksize = fs_info->sectorsize;
449         u64 actual_end;
450         u64 isize = i_size_read(inode);
451         int ret = 0;
452         struct page **pages = NULL;
453         unsigned long nr_pages;
454         unsigned long total_compressed = 0;
455         unsigned long total_in = 0;
456         int i;
457         int will_compress;
458         int compress_type = fs_info->compress_type;
459         int redirty = 0;
460 
461         inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
462                         SZ_16K);
463 
464         actual_end = min_t(u64, isize, end + 1);
465 again:
466         will_compress = 0;
467         nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
468         BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
469         nr_pages = min_t(unsigned long, nr_pages,
470                         BTRFS_MAX_COMPRESSED / PAGE_SIZE);
471 
472         /*
473          * we don't want to send crud past the end of i_size through
474          * compression, that's just a waste of CPU time.  So, if the
475          * end of the file is before the start of our current
476          * requested range of bytes, we bail out to the uncompressed
477          * cleanup code that can deal with all of this.
478          *
479          * It isn't really the fastest way to fix things, but this is a
480          * very uncommon corner.
481          */
482         if (actual_end <= start)
483                 goto cleanup_and_bail_uncompressed;
484 
485         total_compressed = actual_end - start;
486 
487         /*
488          * skip compression for a small file range(<=blocksize) that
489          * isn't an inline extent, since it doesn't save disk space at all.
490          */
491         if (total_compressed <= blocksize &&
492            (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
493                 goto cleanup_and_bail_uncompressed;
494 
495         total_compressed = min_t(unsigned long, total_compressed,
496                         BTRFS_MAX_UNCOMPRESSED);
497         total_in = 0;
498         ret = 0;
499 
500         /*
501          * we do compression for mount -o compress and when the
502          * inode has not been flagged as nocompress.  This flag can
503          * change at any time if we discover bad compression ratios.
504          */
505         if (inode_need_compress(inode, start, end)) {
506                 WARN_ON(pages);
507                 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
508                 if (!pages) {
509                         /* just bail out to the uncompressed code */
510                         goto cont;
511                 }
512 
513                 if (BTRFS_I(inode)->defrag_compress)
514                         compress_type = BTRFS_I(inode)->defrag_compress;
515                 else if (BTRFS_I(inode)->prop_compress)
516                         compress_type = BTRFS_I(inode)->prop_compress;
517 
518                 /*
519                  * we need to call clear_page_dirty_for_io on each
520                  * page in the range.  Otherwise applications with the file
521                  * mmap'd can wander in and change the page contents while
522                  * we are compressing them.
523                  *
524                  * If the compression fails for any reason, we set the pages
525                  * dirty again later on.
526                  *
527                  * Note that the remaining part is redirtied, the start pointer
528                  * has moved, the end is the original one.
529                  */
530                 if (!redirty) {
531                         extent_range_clear_dirty_for_io(inode, start, end);
532                         redirty = 1;
533                 }
534 
535                 /* Compression level is applied here and only here */
536                 ret = btrfs_compress_pages(
537                         compress_type | (fs_info->compress_level << 4),
538                                            inode->i_mapping, start,
539                                            pages,
540                                            &nr_pages,
541                                            &total_in,
542                                            &total_compressed);
543 
544                 if (!ret) {
545                         unsigned long offset = total_compressed &
546                                 (PAGE_SIZE - 1);
547                         struct page *page = pages[nr_pages - 1];
548                         char *kaddr;
549 
550                         /* zero the tail end of the last page, we might be
551                          * sending it down to disk
552                          */
553                         if (offset) {
554                                 kaddr = kmap_atomic(page);
555                                 memset(kaddr + offset, 0,
556                                        PAGE_SIZE - offset);
557                                 kunmap_atomic(kaddr);
558                         }
559                         will_compress = 1;
560                 }
561         }
562 cont:
563         if (start == 0) {
564                 /* lets try to make an inline extent */
565                 if (ret || total_in < actual_end) {
566                         /* we didn't compress the entire range, try
567                          * to make an uncompressed inline extent.
568                          */
569                         ret = cow_file_range_inline(inode, start, end, 0,
570                                                     BTRFS_COMPRESS_NONE, NULL);
571                 } else {
572                         /* try making a compressed inline extent */
573                         ret = cow_file_range_inline(inode, start, end,
574                                                     total_compressed,
575                                                     compress_type, pages);
576                 }
577                 if (ret <= 0) {
578                         unsigned long clear_flags = EXTENT_DELALLOC |
579                                 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
580                                 EXTENT_DO_ACCOUNTING;
581                         unsigned long page_error_op;
582 
583                         page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
584 
585                         /*
586                          * inline extent creation worked or returned error,
587                          * we don't need to create any more async work items.
588                          * Unlock and free up our temp pages.
589                          *
590                          * We use DO_ACCOUNTING here because we need the
591                          * delalloc_release_metadata to be done _after_ we drop
592                          * our outstanding extent for clearing delalloc for this
593                          * range.
594                          */
595                         extent_clear_unlock_delalloc(inode, start, end, end,
596                                                      NULL, clear_flags,
597                                                      PAGE_UNLOCK |
598                                                      PAGE_CLEAR_DIRTY |
599                                                      PAGE_SET_WRITEBACK |
600                                                      page_error_op |
601                                                      PAGE_END_WRITEBACK);
602                         goto free_pages_out;
603                 }
604         }
605 
606         if (will_compress) {
607                 /*
608                  * we aren't doing an inline extent round the compressed size
609                  * up to a block size boundary so the allocator does sane
610                  * things
611                  */
612                 total_compressed = ALIGN(total_compressed, blocksize);
613 
614                 /*
615                  * one last check to make sure the compression is really a
616                  * win, compare the page count read with the blocks on disk,
617                  * compression must free at least one sector size
618                  */
619                 total_in = ALIGN(total_in, PAGE_SIZE);
620                 if (total_compressed + blocksize <= total_in) {
621                         *num_added += 1;
622 
623                         /*
624                          * The async work queues will take care of doing actual
625                          * allocation on disk for these compressed pages, and
626                          * will submit them to the elevator.
627                          */
628                         add_async_extent(async_cow, start, total_in,
629                                         total_compressed, pages, nr_pages,
630                                         compress_type);
631 
632                         if (start + total_in < end) {
633                                 start += total_in;
634                                 pages = NULL;
635                                 cond_resched();
636                                 goto again;
637                         }
638                         return;
639                 }
640         }
641         if (pages) {
642                 /*
643                  * the compression code ran but failed to make things smaller,
644                  * free any pages it allocated and our page pointer array
645                  */
646                 for (i = 0; i < nr_pages; i++) {
647                         WARN_ON(pages[i]->mapping);
648                         put_page(pages[i]);
649                 }
650                 kfree(pages);
651                 pages = NULL;
652                 total_compressed = 0;
653                 nr_pages = 0;
654 
655                 /* flag the file so we don't compress in the future */
656                 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
657                     !(BTRFS_I(inode)->prop_compress)) {
658                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
659                 }
660         }
661 cleanup_and_bail_uncompressed:
662         /*
663          * No compression, but we still need to write the pages in the file
664          * we've been given so far.  redirty the locked page if it corresponds
665          * to our extent and set things up for the async work queue to run
666          * cow_file_range to do the normal delalloc dance.
667          */
668         if (page_offset(locked_page) >= start &&
669             page_offset(locked_page) <= end)
670                 __set_page_dirty_nobuffers(locked_page);
671                 /* unlocked later on in the async handlers */
672 
673         if (redirty)
674                 extent_range_redirty_for_io(inode, start, end);
675         add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
676                          BTRFS_COMPRESS_NONE);
677         *num_added += 1;
678 
679         return;
680 
681 free_pages_out:
682         for (i = 0; i < nr_pages; i++) {
683                 WARN_ON(pages[i]->mapping);
684                 put_page(pages[i]);
685         }
686         kfree(pages);
687 }
688 
689 static void free_async_extent_pages(struct async_extent *async_extent)
690 {
691         int i;
692 
693         if (!async_extent->pages)
694                 return;
695 
696         for (i = 0; i < async_extent->nr_pages; i++) {
697                 WARN_ON(async_extent->pages[i]->mapping);
698                 put_page(async_extent->pages[i]);
699         }
700         kfree(async_extent->pages);
701         async_extent->nr_pages = 0;
702         async_extent->pages = NULL;
703 }
704 
705 /*
706  * phase two of compressed writeback.  This is the ordered portion
707  * of the code, which only gets called in the order the work was
708  * queued.  We walk all the async extents created by compress_file_range
709  * and send them down to the disk.
710  */
711 static noinline void submit_compressed_extents(struct inode *inode,
712                                               struct async_cow *async_cow)
713 {
714         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
715         struct async_extent *async_extent;
716         u64 alloc_hint = 0;
717         struct btrfs_key ins;
718         struct extent_map *em;
719         struct btrfs_root *root = BTRFS_I(inode)->root;
720         struct extent_io_tree *io_tree;
721         int ret = 0;
722 
723 again:
724         while (!list_empty(&async_cow->extents)) {
725                 async_extent = list_entry(async_cow->extents.next,
726                                           struct async_extent, list);
727                 list_del(&async_extent->list);
728 
729                 io_tree = &BTRFS_I(inode)->io_tree;
730 
731 retry:
732                 /* did the compression code fall back to uncompressed IO? */
733                 if (!async_extent->pages) {
734                         int page_started = 0;
735                         unsigned long nr_written = 0;
736 
737                         lock_extent(io_tree, async_extent->start,
738                                          async_extent->start +
739                                          async_extent->ram_size - 1);
740 
741                         /* allocate blocks */
742                         ret = cow_file_range(inode, async_cow->locked_page,
743                                              async_extent->start,
744                                              async_extent->start +
745                                              async_extent->ram_size - 1,
746                                              async_extent->start +
747                                              async_extent->ram_size - 1,
748                                              &page_started, &nr_written, 0,
749                                              NULL);
750 
751                         /* JDM XXX */
752 
753                         /*
754                          * if page_started, cow_file_range inserted an
755                          * inline extent and took care of all the unlocking
756                          * and IO for us.  Otherwise, we need to submit
757                          * all those pages down to the drive.
758                          */
759                         if (!page_started && !ret)
760                                 extent_write_locked_range(inode,
761                                                   async_extent->start,
762                                                   async_extent->start +
763                                                   async_extent->ram_size - 1,
764                                                   WB_SYNC_ALL);
765                         else if (ret)
766                                 unlock_page(async_cow->locked_page);
767                         kfree(async_extent);
768                         cond_resched();
769                         continue;
770                 }
771 
772                 lock_extent(io_tree, async_extent->start,
773                             async_extent->start + async_extent->ram_size - 1);
774 
775                 ret = btrfs_reserve_extent(root, async_extent->ram_size,
776                                            async_extent->compressed_size,
777                                            async_extent->compressed_size,
778                                            0, alloc_hint, &ins, 1, 1);
779                 if (ret) {
780                         free_async_extent_pages(async_extent);
781 
782                         if (ret == -ENOSPC) {
783                                 unlock_extent(io_tree, async_extent->start,
784                                               async_extent->start +
785                                               async_extent->ram_size - 1);
786 
787                                 /*
788                                  * we need to redirty the pages if we decide to
789                                  * fallback to uncompressed IO, otherwise we
790                                  * will not submit these pages down to lower
791                                  * layers.
792                                  */
793                                 extent_range_redirty_for_io(inode,
794                                                 async_extent->start,
795                                                 async_extent->start +
796                                                 async_extent->ram_size - 1);
797 
798                                 goto retry;
799                         }
800                         goto out_free;
801                 }
802                 /*
803                  * here we're doing allocation and writeback of the
804                  * compressed pages
805                  */
806                 em = create_io_em(inode, async_extent->start,
807                                   async_extent->ram_size, /* len */
808                                   async_extent->start, /* orig_start */
809                                   ins.objectid, /* block_start */
810                                   ins.offset, /* block_len */
811                                   ins.offset, /* orig_block_len */
812                                   async_extent->ram_size, /* ram_bytes */
813                                   async_extent->compress_type,
814                                   BTRFS_ORDERED_COMPRESSED);
815                 if (IS_ERR(em))
816                         /* ret value is not necessary due to void function */
817                         goto out_free_reserve;
818                 free_extent_map(em);
819 
820                 ret = btrfs_add_ordered_extent_compress(inode,
821                                                 async_extent->start,
822                                                 ins.objectid,
823                                                 async_extent->ram_size,
824                                                 ins.offset,
825                                                 BTRFS_ORDERED_COMPRESSED,
826                                                 async_extent->compress_type);
827                 if (ret) {
828                         btrfs_drop_extent_cache(BTRFS_I(inode),
829                                                 async_extent->start,
830                                                 async_extent->start +
831                                                 async_extent->ram_size - 1, 0);
832                         goto out_free_reserve;
833                 }
834                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
835 
836                 /*
837                  * clear dirty, set writeback and unlock the pages.
838                  */
839                 extent_clear_unlock_delalloc(inode, async_extent->start,
840                                 async_extent->start +
841                                 async_extent->ram_size - 1,
842                                 async_extent->start +
843                                 async_extent->ram_size - 1,
844                                 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
845                                 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
846                                 PAGE_SET_WRITEBACK);
847                 if (btrfs_submit_compressed_write(inode,
848                                     async_extent->start,
849                                     async_extent->ram_size,
850                                     ins.objectid,
851                                     ins.offset, async_extent->pages,
852                                     async_extent->nr_pages,
853                                     async_cow->write_flags)) {
854                         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
855                         struct page *p = async_extent->pages[0];
856                         const u64 start = async_extent->start;
857                         const u64 end = start + async_extent->ram_size - 1;
858 
859                         p->mapping = inode->i_mapping;
860                         tree->ops->writepage_end_io_hook(p, start, end,
861                                                          NULL, 0);
862                         p->mapping = NULL;
863                         extent_clear_unlock_delalloc(inode, start, end, end,
864                                                      NULL, 0,
865                                                      PAGE_END_WRITEBACK |
866                                                      PAGE_SET_ERROR);
867                         free_async_extent_pages(async_extent);
868                 }
869                 alloc_hint = ins.objectid + ins.offset;
870                 kfree(async_extent);
871                 cond_resched();
872         }
873         return;
874 out_free_reserve:
875         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
876         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
877 out_free:
878         extent_clear_unlock_delalloc(inode, async_extent->start,
879                                      async_extent->start +
880                                      async_extent->ram_size - 1,
881                                      async_extent->start +
882                                      async_extent->ram_size - 1,
883                                      NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
884                                      EXTENT_DELALLOC_NEW |
885                                      EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
886                                      PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
887                                      PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
888                                      PAGE_SET_ERROR);
889         free_async_extent_pages(async_extent);
890         kfree(async_extent);
891         goto again;
892 }
893 
894 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
895                                       u64 num_bytes)
896 {
897         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
898         struct extent_map *em;
899         u64 alloc_hint = 0;
900 
901         read_lock(&em_tree->lock);
902         em = search_extent_mapping(em_tree, start, num_bytes);
903         if (em) {
904                 /*
905                  * if block start isn't an actual block number then find the
906                  * first block in this inode and use that as a hint.  If that
907                  * block is also bogus then just don't worry about it.
908                  */
909                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
910                         free_extent_map(em);
911                         em = search_extent_mapping(em_tree, 0, 0);
912                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
913                                 alloc_hint = em->block_start;
914                         if (em)
915                                 free_extent_map(em);
916                 } else {
917                         alloc_hint = em->block_start;
918                         free_extent_map(em);
919                 }
920         }
921         read_unlock(&em_tree->lock);
922 
923         return alloc_hint;
924 }
925 
926 /*
927  * when extent_io.c finds a delayed allocation range in the file,
928  * the call backs end up in this code.  The basic idea is to
929  * allocate extents on disk for the range, and create ordered data structs
930  * in ram to track those extents.
931  *
932  * locked_page is the page that writepage had locked already.  We use
933  * it to make sure we don't do extra locks or unlocks.
934  *
935  * *page_started is set to one if we unlock locked_page and do everything
936  * required to start IO on it.  It may be clean and already done with
937  * IO when we return.
938  */
939 static noinline int cow_file_range(struct inode *inode,
940                                    struct page *locked_page,
941                                    u64 start, u64 end, u64 delalloc_end,
942                                    int *page_started, unsigned long *nr_written,
943                                    int unlock, struct btrfs_dedupe_hash *hash)
944 {
945         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
946         struct btrfs_root *root = BTRFS_I(inode)->root;
947         u64 alloc_hint = 0;
948         u64 num_bytes;
949         unsigned long ram_size;
950         u64 cur_alloc_size = 0;
951         u64 blocksize = fs_info->sectorsize;
952         struct btrfs_key ins;
953         struct extent_map *em;
954         unsigned clear_bits;
955         unsigned long page_ops;
956         bool extent_reserved = false;
957         int ret = 0;
958 
959         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
960                 WARN_ON_ONCE(1);
961                 ret = -EINVAL;
962                 goto out_unlock;
963         }
964 
965         num_bytes = ALIGN(end - start + 1, blocksize);
966         num_bytes = max(blocksize,  num_bytes);
967         ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
968 
969         inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
970 
971         if (start == 0) {
972                 /* lets try to make an inline extent */
973                 ret = cow_file_range_inline(inode, start, end, 0,
974                                             BTRFS_COMPRESS_NONE, NULL);
975                 if (ret == 0) {
976                         /*
977                          * We use DO_ACCOUNTING here because we need the
978                          * delalloc_release_metadata to be run _after_ we drop
979                          * our outstanding extent for clearing delalloc for this
980                          * range.
981                          */
982                         extent_clear_unlock_delalloc(inode, start, end,
983                                      delalloc_end, NULL,
984                                      EXTENT_LOCKED | EXTENT_DELALLOC |
985                                      EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
986                                      EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
987                                      PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
988                                      PAGE_END_WRITEBACK);
989                         *nr_written = *nr_written +
990                              (end - start + PAGE_SIZE) / PAGE_SIZE;
991                         *page_started = 1;
992                         goto out;
993                 } else if (ret < 0) {
994                         goto out_unlock;
995                 }
996         }
997 
998         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
999         btrfs_drop_extent_cache(BTRFS_I(inode), start,
1000                         start + num_bytes - 1, 0);
1001 
1002         while (num_bytes > 0) {
1003                 cur_alloc_size = num_bytes;
1004                 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1005                                            fs_info->sectorsize, 0, alloc_hint,
1006                                            &ins, 1, 1);
1007                 if (ret < 0)
1008                         goto out_unlock;
1009                 cur_alloc_size = ins.offset;
1010                 extent_reserved = true;
1011 
1012                 ram_size = ins.offset;
1013                 em = create_io_em(inode, start, ins.offset, /* len */
1014                                   start, /* orig_start */
1015                                   ins.objectid, /* block_start */
1016                                   ins.offset, /* block_len */
1017                                   ins.offset, /* orig_block_len */
1018                                   ram_size, /* ram_bytes */
1019                                   BTRFS_COMPRESS_NONE, /* compress_type */
1020                                   BTRFS_ORDERED_REGULAR /* type */);
1021                 if (IS_ERR(em)) {
1022                         ret = PTR_ERR(em);
1023                         goto out_reserve;
1024                 }
1025                 free_extent_map(em);
1026 
1027                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1028                                                ram_size, cur_alloc_size, 0);
1029                 if (ret)
1030                         goto out_drop_extent_cache;
1031 
1032                 if (root->root_key.objectid ==
1033                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1034                         ret = btrfs_reloc_clone_csums(inode, start,
1035                                                       cur_alloc_size);
1036                         /*
1037                          * Only drop cache here, and process as normal.
1038                          *
1039                          * We must not allow extent_clear_unlock_delalloc()
1040                          * at out_unlock label to free meta of this ordered
1041                          * extent, as its meta should be freed by
1042                          * btrfs_finish_ordered_io().
1043                          *
1044                          * So we must continue until @start is increased to
1045                          * skip current ordered extent.
1046                          */
1047                         if (ret)
1048                                 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1049                                                 start + ram_size - 1, 0);
1050                 }
1051 
1052                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1053 
1054                 /* we're not doing compressed IO, don't unlock the first
1055                  * page (which the caller expects to stay locked), don't
1056                  * clear any dirty bits and don't set any writeback bits
1057                  *
1058                  * Do set the Private2 bit so we know this page was properly
1059                  * setup for writepage
1060                  */
1061                 page_ops = unlock ? PAGE_UNLOCK : 0;
1062                 page_ops |= PAGE_SET_PRIVATE2;
1063 
1064                 extent_clear_unlock_delalloc(inode, start,
1065                                              start + ram_size - 1,
1066                                              delalloc_end, locked_page,
1067                                              EXTENT_LOCKED | EXTENT_DELALLOC,
1068                                              page_ops);
1069                 if (num_bytes < cur_alloc_size)
1070                         num_bytes = 0;
1071                 else
1072                         num_bytes -= cur_alloc_size;
1073                 alloc_hint = ins.objectid + ins.offset;
1074                 start += cur_alloc_size;
1075                 extent_reserved = false;
1076 
1077                 /*
1078                  * btrfs_reloc_clone_csums() error, since start is increased
1079                  * extent_clear_unlock_delalloc() at out_unlock label won't
1080                  * free metadata of current ordered extent, we're OK to exit.
1081                  */
1082                 if (ret)
1083                         goto out_unlock;
1084         }
1085 out:
1086         return ret;
1087 
1088 out_drop_extent_cache:
1089         btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1090 out_reserve:
1091         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1092         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1093 out_unlock:
1094         clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1095                 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1096         page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1097                 PAGE_END_WRITEBACK;
1098         /*
1099          * If we reserved an extent for our delalloc range (or a subrange) and
1100          * failed to create the respective ordered extent, then it means that
1101          * when we reserved the extent we decremented the extent's size from
1102          * the data space_info's bytes_may_use counter and incremented the
1103          * space_info's bytes_reserved counter by the same amount. We must make
1104          * sure extent_clear_unlock_delalloc() does not try to decrement again
1105          * the data space_info's bytes_may_use counter, therefore we do not pass
1106          * it the flag EXTENT_CLEAR_DATA_RESV.
1107          */
1108         if (extent_reserved) {
1109                 extent_clear_unlock_delalloc(inode, start,
1110                                              start + cur_alloc_size,
1111                                              start + cur_alloc_size,
1112                                              locked_page,
1113                                              clear_bits,
1114                                              page_ops);
1115                 start += cur_alloc_size;
1116                 if (start >= end)
1117                         goto out;
1118         }
1119         extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1120                                      locked_page,
1121                                      clear_bits | EXTENT_CLEAR_DATA_RESV,
1122                                      page_ops);
1123         goto out;
1124 }
1125 
1126 /*
1127  * work queue call back to started compression on a file and pages
1128  */
1129 static noinline void async_cow_start(struct btrfs_work *work)
1130 {
1131         struct async_cow *async_cow;
1132         int num_added = 0;
1133         async_cow = container_of(work, struct async_cow, work);
1134 
1135         compress_file_range(async_cow->inode, async_cow->locked_page,
1136                             async_cow->start, async_cow->end, async_cow,
1137                             &num_added);
1138         if (num_added == 0) {
1139                 btrfs_add_delayed_iput(async_cow->inode);
1140                 async_cow->inode = NULL;
1141         }
1142 }
1143 
1144 /*
1145  * work queue call back to submit previously compressed pages
1146  */
1147 static noinline void async_cow_submit(struct btrfs_work *work)
1148 {
1149         struct btrfs_fs_info *fs_info;
1150         struct async_cow *async_cow;
1151         struct btrfs_root *root;
1152         unsigned long nr_pages;
1153 
1154         async_cow = container_of(work, struct async_cow, work);
1155 
1156         root = async_cow->root;
1157         fs_info = root->fs_info;
1158         nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1159                 PAGE_SHIFT;
1160 
1161         /*
1162          * atomic_sub_return implies a barrier for waitqueue_active
1163          */
1164         if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1165             5 * SZ_1M &&
1166             waitqueue_active(&fs_info->async_submit_wait))
1167                 wake_up(&fs_info->async_submit_wait);
1168 
1169         if (async_cow->inode)
1170                 submit_compressed_extents(async_cow->inode, async_cow);
1171 }
1172 
1173 static noinline void async_cow_free(struct btrfs_work *work)
1174 {
1175         struct async_cow *async_cow;
1176         async_cow = container_of(work, struct async_cow, work);
1177         if (async_cow->inode)
1178                 btrfs_add_delayed_iput(async_cow->inode);
1179         kfree(async_cow);
1180 }
1181 
1182 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1183                                 u64 start, u64 end, int *page_started,
1184                                 unsigned long *nr_written,
1185                                 unsigned int write_flags)
1186 {
1187         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1188         struct async_cow *async_cow;
1189         struct btrfs_root *root = BTRFS_I(inode)->root;
1190         unsigned long nr_pages;
1191         u64 cur_end;
1192 
1193         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1194                          1, 0, NULL);
1195         while (start < end) {
1196                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1197                 BUG_ON(!async_cow); /* -ENOMEM */
1198                 async_cow->inode = igrab(inode);
1199                 async_cow->root = root;
1200                 async_cow->locked_page = locked_page;
1201                 async_cow->start = start;
1202                 async_cow->write_flags = write_flags;
1203 
1204                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1205                     !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1206                         cur_end = end;
1207                 else
1208                         cur_end = min(end, start + SZ_512K - 1);
1209 
1210                 async_cow->end = cur_end;
1211                 INIT_LIST_HEAD(&async_cow->extents);
1212 
1213                 btrfs_init_work(&async_cow->work,
1214                                 btrfs_delalloc_helper,
1215                                 async_cow_start, async_cow_submit,
1216                                 async_cow_free);
1217 
1218                 nr_pages = (cur_end - start + PAGE_SIZE) >>
1219                         PAGE_SHIFT;
1220                 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1221 
1222                 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1223 
1224                 *nr_written += nr_pages;
1225                 start = cur_end + 1;
1226         }
1227         *page_started = 1;
1228         return 0;
1229 }
1230 
1231 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1232                                         u64 bytenr, u64 num_bytes)
1233 {
1234         int ret;
1235         struct btrfs_ordered_sum *sums;
1236         LIST_HEAD(list);
1237 
1238         ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1239                                        bytenr + num_bytes - 1, &list, 0);
1240         if (ret == 0 && list_empty(&list))
1241                 return 0;
1242 
1243         while (!list_empty(&list)) {
1244                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1245                 list_del(&sums->list);
1246                 kfree(sums);
1247         }
1248         if (ret < 0)
1249                 return ret;
1250         return 1;
1251 }
1252 
1253 /*
1254  * when nowcow writeback call back.  This checks for snapshots or COW copies
1255  * of the extents that exist in the file, and COWs the file as required.
1256  *
1257  * If no cow copies or snapshots exist, we write directly to the existing
1258  * blocks on disk
1259  */
1260 static noinline int run_delalloc_nocow(struct inode *inode,
1261                                        struct page *locked_page,
1262                               u64 start, u64 end, int *page_started, int force,
1263                               unsigned long *nr_written)
1264 {
1265         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1266         struct btrfs_root *root = BTRFS_I(inode)->root;
1267         struct extent_buffer *leaf;
1268         struct btrfs_path *path;
1269         struct btrfs_file_extent_item *fi;
1270         struct btrfs_key found_key;
1271         struct extent_map *em;
1272         u64 cow_start;
1273         u64 cur_offset;
1274         u64 extent_end;
1275         u64 extent_offset;
1276         u64 disk_bytenr;
1277         u64 num_bytes;
1278         u64 disk_num_bytes;
1279         u64 ram_bytes;
1280         int extent_type;
1281         int ret, err;
1282         int type;
1283         int nocow;
1284         int check_prev = 1;
1285         bool nolock;
1286         u64 ino = btrfs_ino(BTRFS_I(inode));
1287 
1288         path = btrfs_alloc_path();
1289         if (!path) {
1290                 extent_clear_unlock_delalloc(inode, start, end, end,
1291                                              locked_page,
1292                                              EXTENT_LOCKED | EXTENT_DELALLOC |
1293                                              EXTENT_DO_ACCOUNTING |
1294                                              EXTENT_DEFRAG, PAGE_UNLOCK |
1295                                              PAGE_CLEAR_DIRTY |
1296                                              PAGE_SET_WRITEBACK |
1297                                              PAGE_END_WRITEBACK);
1298                 return -ENOMEM;
1299         }
1300 
1301         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1302 
1303         cow_start = (u64)-1;
1304         cur_offset = start;
1305         while (1) {
1306                 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1307                                                cur_offset, 0);
1308                 if (ret < 0)
1309                         goto error;
1310                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1311                         leaf = path->nodes[0];
1312                         btrfs_item_key_to_cpu(leaf, &found_key,
1313                                               path->slots[0] - 1);
1314                         if (found_key.objectid == ino &&
1315                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1316                                 path->slots[0]--;
1317                 }
1318                 check_prev = 0;
1319 next_slot:
1320                 leaf = path->nodes[0];
1321                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1322                         ret = btrfs_next_leaf(root, path);
1323                         if (ret < 0) {
1324                                 if (cow_start != (u64)-1)
1325                                         cur_offset = cow_start;
1326                                 goto error;
1327                         }
1328                         if (ret > 0)
1329                                 break;
1330                         leaf = path->nodes[0];
1331                 }
1332 
1333                 nocow = 0;
1334                 disk_bytenr = 0;
1335                 num_bytes = 0;
1336                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1337 
1338                 if (found_key.objectid > ino)
1339                         break;
1340                 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1341                     found_key.type < BTRFS_EXTENT_DATA_KEY) {
1342                         path->slots[0]++;
1343                         goto next_slot;
1344                 }
1345                 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1346                     found_key.offset > end)
1347                         break;
1348 
1349                 if (found_key.offset > cur_offset) {
1350                         extent_end = found_key.offset;
1351                         extent_type = 0;
1352                         goto out_check;
1353                 }
1354 
1355                 fi = btrfs_item_ptr(leaf, path->slots[0],
1356                                     struct btrfs_file_extent_item);
1357                 extent_type = btrfs_file_extent_type(leaf, fi);
1358 
1359                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1360                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1361                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1362                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1363                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1364                         extent_end = found_key.offset +
1365                                 btrfs_file_extent_num_bytes(leaf, fi);
1366                         disk_num_bytes =
1367                                 btrfs_file_extent_disk_num_bytes(leaf, fi);
1368                         if (extent_end <= start) {
1369                                 path->slots[0]++;
1370                                 goto next_slot;
1371                         }
1372                         if (disk_bytenr == 0)
1373                                 goto out_check;
1374                         if (btrfs_file_extent_compression(leaf, fi) ||
1375                             btrfs_file_extent_encryption(leaf, fi) ||
1376                             btrfs_file_extent_other_encoding(leaf, fi))
1377                                 goto out_check;
1378                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1379                                 goto out_check;
1380                         if (btrfs_extent_readonly(fs_info, disk_bytenr))
1381                                 goto out_check;
1382                         ret = btrfs_cross_ref_exist(root, ino,
1383                                                     found_key.offset -
1384                                                     extent_offset, disk_bytenr);
1385                         if (ret) {
1386                                 /*
1387                                  * ret could be -EIO if the above fails to read
1388                                  * metadata.
1389                                  */
1390                                 if (ret < 0) {
1391                                         if (cow_start != (u64)-1)
1392                                                 cur_offset = cow_start;
1393                                         goto error;
1394                                 }
1395 
1396                                 WARN_ON_ONCE(nolock);
1397                                 goto out_check;
1398                         }
1399                         disk_bytenr += extent_offset;
1400                         disk_bytenr += cur_offset - found_key.offset;
1401                         num_bytes = min(end + 1, extent_end) - cur_offset;
1402                         /*
1403                          * if there are pending snapshots for this root,
1404                          * we fall into common COW way.
1405                          */
1406                         if (!nolock) {
1407                                 err = btrfs_start_write_no_snapshotting(root);
1408                                 if (!err)
1409                                         goto out_check;
1410                         }
1411                         /*
1412                          * force cow if csum exists in the range.
1413                          * this ensure that csum for a given extent are
1414                          * either valid or do not exist.
1415                          */
1416                         ret = csum_exist_in_range(fs_info, disk_bytenr,
1417                                                   num_bytes);
1418                         if (ret) {
1419                                 if (!nolock)
1420                                         btrfs_end_write_no_snapshotting(root);
1421 
1422                                 /*
1423                                  * ret could be -EIO if the above fails to read
1424                                  * metadata.
1425                                  */
1426                                 if (ret < 0) {
1427                                         if (cow_start != (u64)-1)
1428                                                 cur_offset = cow_start;
1429                                         goto error;
1430                                 }
1431                                 WARN_ON_ONCE(nolock);
1432                                 goto out_check;
1433                         }
1434                         if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1435                                 if (!nolock)
1436                                         btrfs_end_write_no_snapshotting(root);
1437                                 goto out_check;
1438                         }
1439                         nocow = 1;
1440                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1441                         extent_end = found_key.offset +
1442                                 btrfs_file_extent_inline_len(leaf,
1443                                                      path->slots[0], fi);
1444                         extent_end = ALIGN(extent_end,
1445                                            fs_info->sectorsize);
1446                 } else {
1447                         BUG_ON(1);
1448                 }
1449 out_check:
1450                 if (extent_end <= start) {
1451                         path->slots[0]++;
1452                         if (!nolock && nocow)
1453                                 btrfs_end_write_no_snapshotting(root);
1454                         if (nocow)
1455                                 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1456                         goto next_slot;
1457                 }
1458                 if (!nocow) {
1459                         if (cow_start == (u64)-1)
1460                                 cow_start = cur_offset;
1461                         cur_offset = extent_end;
1462                         if (cur_offset > end)
1463                                 break;
1464                         path->slots[0]++;
1465                         goto next_slot;
1466                 }
1467 
1468                 btrfs_release_path(path);
1469                 if (cow_start != (u64)-1) {
1470                         ret = cow_file_range(inode, locked_page,
1471                                              cow_start, found_key.offset - 1,
1472                                              end, page_started, nr_written, 1,
1473                                              NULL);
1474                         if (ret) {
1475                                 if (!nolock && nocow)
1476                                         btrfs_end_write_no_snapshotting(root);
1477                                 if (nocow)
1478                                         btrfs_dec_nocow_writers(fs_info,
1479                                                                 disk_bytenr);
1480                                 goto error;
1481                         }
1482                         cow_start = (u64)-1;
1483                 }
1484 
1485                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1486                         u64 orig_start = found_key.offset - extent_offset;
1487 
1488                         em = create_io_em(inode, cur_offset, num_bytes,
1489                                           orig_start,
1490                                           disk_bytenr, /* block_start */
1491                                           num_bytes, /* block_len */
1492                                           disk_num_bytes, /* orig_block_len */
1493                                           ram_bytes, BTRFS_COMPRESS_NONE,
1494                                           BTRFS_ORDERED_PREALLOC);
1495                         if (IS_ERR(em)) {
1496                                 if (!nolock && nocow)
1497                                         btrfs_end_write_no_snapshotting(root);
1498                                 if (nocow)
1499                                         btrfs_dec_nocow_writers(fs_info,
1500                                                                 disk_bytenr);
1501                                 ret = PTR_ERR(em);
1502                                 goto error;
1503                         }
1504                         free_extent_map(em);
1505                 }
1506 
1507                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1508                         type = BTRFS_ORDERED_PREALLOC;
1509                 } else {
1510                         type = BTRFS_ORDERED_NOCOW;
1511                 }
1512 
1513                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1514                                                num_bytes, num_bytes, type);
1515                 if (nocow)
1516                         btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1517                 BUG_ON(ret); /* -ENOMEM */
1518 
1519                 if (root->root_key.objectid ==
1520                     BTRFS_DATA_RELOC_TREE_OBJECTID)
1521                         /*
1522                          * Error handled later, as we must prevent
1523                          * extent_clear_unlock_delalloc() in error handler
1524                          * from freeing metadata of created ordered extent.
1525                          */
1526                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1527                                                       num_bytes);
1528 
1529                 extent_clear_unlock_delalloc(inode, cur_offset,
1530                                              cur_offset + num_bytes - 1, end,
1531                                              locked_page, EXTENT_LOCKED |
1532                                              EXTENT_DELALLOC |
1533                                              EXTENT_CLEAR_DATA_RESV,
1534                                              PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1535 
1536                 if (!nolock && nocow)
1537                         btrfs_end_write_no_snapshotting(root);
1538                 cur_offset = extent_end;
1539 
1540                 /*
1541                  * btrfs_reloc_clone_csums() error, now we're OK to call error
1542                  * handler, as metadata for created ordered extent will only
1543                  * be freed by btrfs_finish_ordered_io().
1544                  */
1545                 if (ret)
1546                         goto error;
1547                 if (cur_offset > end)
1548                         break;
1549         }
1550         btrfs_release_path(path);
1551 
1552         if (cur_offset <= end && cow_start == (u64)-1) {
1553                 cow_start = cur_offset;
1554                 cur_offset = end;
1555         }
1556 
1557         if (cow_start != (u64)-1) {
1558                 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1559                                      page_started, nr_written, 1, NULL);
1560                 if (ret)
1561                         goto error;
1562         }
1563 
1564 error:
1565         if (ret && cur_offset < end)
1566                 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1567                                              locked_page, EXTENT_LOCKED |
1568                                              EXTENT_DELALLOC | EXTENT_DEFRAG |
1569                                              EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1570                                              PAGE_CLEAR_DIRTY |
1571                                              PAGE_SET_WRITEBACK |
1572                                              PAGE_END_WRITEBACK);
1573         btrfs_free_path(path);
1574         return ret;
1575 }
1576 
1577 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1578 {
1579 
1580         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1581             !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1582                 return 0;
1583 
1584         /*
1585          * @defrag_bytes is a hint value, no spinlock held here,
1586          * if is not zero, it means the file is defragging.
1587          * Force cow if given extent needs to be defragged.
1588          */
1589         if (BTRFS_I(inode)->defrag_bytes &&
1590             test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1591                            EXTENT_DEFRAG, 0, NULL))
1592                 return 1;
1593 
1594         return 0;
1595 }
1596 
1597 /*
1598  * extent_io.c call back to do delayed allocation processing
1599  */
1600 static int run_delalloc_range(void *private_data, struct page *locked_page,
1601                               u64 start, u64 end, int *page_started,
1602                               unsigned long *nr_written,
1603                               struct writeback_control *wbc)
1604 {
1605         struct inode *inode = private_data;
1606         int ret;
1607         int force_cow = need_force_cow(inode, start, end);
1608         unsigned int write_flags = wbc_to_write_flags(wbc);
1609 
1610         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1611                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1612                                          page_started, 1, nr_written);
1613         } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1614                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1615                                          page_started, 0, nr_written);
1616         } else if (!inode_need_compress(inode, start, end)) {
1617                 ret = cow_file_range(inode, locked_page, start, end, end,
1618                                       page_started, nr_written, 1, NULL);
1619         } else {
1620                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1621                         &BTRFS_I(inode)->runtime_flags);
1622                 ret = cow_file_range_async(inode, locked_page, start, end,
1623                                            page_started, nr_written,
1624                                            write_flags);
1625         }
1626         if (ret)
1627                 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1628         return ret;
1629 }
1630 
1631 static void btrfs_split_extent_hook(void *private_data,
1632                                     struct extent_state *orig, u64 split)
1633 {
1634         struct inode *inode = private_data;
1635         u64 size;
1636 
1637         /* not delalloc, ignore it */
1638         if (!(orig->state & EXTENT_DELALLOC))
1639                 return;
1640 
1641         size = orig->end - orig->start + 1;
1642         if (size > BTRFS_MAX_EXTENT_SIZE) {
1643                 u32 num_extents;
1644                 u64 new_size;
1645 
1646                 /*
1647                  * See the explanation in btrfs_merge_extent_hook, the same
1648                  * applies here, just in reverse.
1649                  */
1650                 new_size = orig->end - split + 1;
1651                 num_extents = count_max_extents(new_size);
1652                 new_size = split - orig->start;
1653                 num_extents += count_max_extents(new_size);
1654                 if (count_max_extents(size) >= num_extents)
1655                         return;
1656         }
1657 
1658         spin_lock(&BTRFS_I(inode)->lock);
1659         btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1660         spin_unlock(&BTRFS_I(inode)->lock);
1661 }
1662 
1663 /*
1664  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1665  * extents so we can keep track of new extents that are just merged onto old
1666  * extents, such as when we are doing sequential writes, so we can properly
1667  * account for the metadata space we'll need.
1668  */
1669 static void btrfs_merge_extent_hook(void *private_data,
1670                                     struct extent_state *new,
1671                                     struct extent_state *other)
1672 {
1673         struct inode *inode = private_data;
1674         u64 new_size, old_size;
1675         u32 num_extents;
1676 
1677         /* not delalloc, ignore it */
1678         if (!(other->state & EXTENT_DELALLOC))
1679                 return;
1680 
1681         if (new->start > other->start)
1682                 new_size = new->end - other->start + 1;
1683         else
1684                 new_size = other->end - new->start + 1;
1685 
1686         /* we're not bigger than the max, unreserve the space and go */
1687         if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1688                 spin_lock(&BTRFS_I(inode)->lock);
1689                 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1690                 spin_unlock(&BTRFS_I(inode)->lock);
1691                 return;
1692         }
1693 
1694         /*
1695          * We have to add up either side to figure out how many extents were
1696          * accounted for before we merged into one big extent.  If the number of
1697          * extents we accounted for is <= the amount we need for the new range
1698          * then we can return, otherwise drop.  Think of it like this
1699          *
1700          * [ 4k][MAX_SIZE]
1701          *
1702          * So we've grown the extent by a MAX_SIZE extent, this would mean we
1703          * need 2 outstanding extents, on one side we have 1 and the other side
1704          * we have 1 so they are == and we can return.  But in this case
1705          *
1706          * [MAX_SIZE+4k][MAX_SIZE+4k]
1707          *
1708          * Each range on their own accounts for 2 extents, but merged together
1709          * they are only 3 extents worth of accounting, so we need to drop in
1710          * this case.
1711          */
1712         old_size = other->end - other->start + 1;
1713         num_extents = count_max_extents(old_size);
1714         old_size = new->end - new->start + 1;
1715         num_extents += count_max_extents(old_size);
1716         if (count_max_extents(new_size) >= num_extents)
1717                 return;
1718 
1719         spin_lock(&BTRFS_I(inode)->lock);
1720         btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1721         spin_unlock(&BTRFS_I(inode)->lock);
1722 }
1723 
1724 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1725                                       struct inode *inode)
1726 {
1727         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1728 
1729         spin_lock(&root->delalloc_lock);
1730         if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1731                 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1732                               &root->delalloc_inodes);
1733                 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1734                         &BTRFS_I(inode)->runtime_flags);
1735                 root->nr_delalloc_inodes++;
1736                 if (root->nr_delalloc_inodes == 1) {
1737                         spin_lock(&fs_info->delalloc_root_lock);
1738                         BUG_ON(!list_empty(&root->delalloc_root));
1739                         list_add_tail(&root->delalloc_root,
1740                                       &fs_info->delalloc_roots);
1741                         spin_unlock(&fs_info->delalloc_root_lock);
1742                 }
1743         }
1744         spin_unlock(&root->delalloc_lock);
1745 }
1746 
1747 
1748 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1749                                 struct btrfs_inode *inode)
1750 {
1751         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1752 
1753         if (!list_empty(&inode->delalloc_inodes)) {
1754                 list_del_init(&inode->delalloc_inodes);
1755                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1756                           &inode->runtime_flags);
1757                 root->nr_delalloc_inodes--;
1758                 if (!root->nr_delalloc_inodes) {
1759                         spin_lock(&fs_info->delalloc_root_lock);
1760                         BUG_ON(list_empty(&root->delalloc_root));
1761                         list_del_init(&root->delalloc_root);
1762                         spin_unlock(&fs_info->delalloc_root_lock);
1763                 }
1764         }
1765 }
1766 
1767 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1768                                      struct btrfs_inode *inode)
1769 {
1770         spin_lock(&root->delalloc_lock);
1771         __btrfs_del_delalloc_inode(root, inode);
1772         spin_unlock(&root->delalloc_lock);
1773 }
1774 
1775 /*
1776  * extent_io.c set_bit_hook, used to track delayed allocation
1777  * bytes in this file, and to maintain the list of inodes that
1778  * have pending delalloc work to be done.
1779  */
1780 static void btrfs_set_bit_hook(void *private_data,
1781                                struct extent_state *state, unsigned *bits)
1782 {
1783         struct inode *inode = private_data;
1784 
1785         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1786 
1787         if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1788                 WARN_ON(1);
1789         /*
1790          * set_bit and clear bit hooks normally require _irqsave/restore
1791          * but in this case, we are only testing for the DELALLOC
1792          * bit, which is only set or cleared with irqs on
1793          */
1794         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1795                 struct btrfs_root *root = BTRFS_I(inode)->root;
1796                 u64 len = state->end + 1 - state->start;
1797                 u32 num_extents = count_max_extents(len);
1798                 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1799 
1800                 spin_lock(&BTRFS_I(inode)->lock);
1801                 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1802                 spin_unlock(&BTRFS_I(inode)->lock);
1803 
1804                 /* For sanity tests */
1805                 if (btrfs_is_testing(fs_info))
1806                         return;
1807 
1808                 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1809                                          fs_info->delalloc_batch);
1810                 spin_lock(&BTRFS_I(inode)->lock);
1811                 BTRFS_I(inode)->delalloc_bytes += len;
1812                 if (*bits & EXTENT_DEFRAG)
1813                         BTRFS_I(inode)->defrag_bytes += len;
1814                 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1815                                          &BTRFS_I(inode)->runtime_flags))
1816                         btrfs_add_delalloc_inodes(root, inode);
1817                 spin_unlock(&BTRFS_I(inode)->lock);
1818         }
1819 
1820         if (!(state->state & EXTENT_DELALLOC_NEW) &&
1821             (*bits & EXTENT_DELALLOC_NEW)) {
1822                 spin_lock(&BTRFS_I(inode)->lock);
1823                 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1824                         state->start;
1825                 spin_unlock(&BTRFS_I(inode)->lock);
1826         }
1827 }
1828 
1829 /*
1830  * extent_io.c clear_bit_hook, see set_bit_hook for why
1831  */
1832 static void btrfs_clear_bit_hook(void *private_data,
1833                                  struct extent_state *state,
1834                                  unsigned *bits)
1835 {
1836         struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1837         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1838         u64 len = state->end + 1 - state->start;
1839         u32 num_extents = count_max_extents(len);
1840 
1841         if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1842                 spin_lock(&inode->lock);
1843                 inode->defrag_bytes -= len;
1844                 spin_unlock(&inode->lock);
1845         }
1846 
1847         /*
1848          * set_bit and clear bit hooks normally require _irqsave/restore
1849          * but in this case, we are only testing for the DELALLOC
1850          * bit, which is only set or cleared with irqs on
1851          */
1852         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1853                 struct btrfs_root *root = inode->root;
1854                 bool do_list = !btrfs_is_free_space_inode(inode);
1855 
1856                 spin_lock(&inode->lock);
1857                 btrfs_mod_outstanding_extents(inode, -num_extents);
1858                 spin_unlock(&inode->lock);
1859 
1860                 /*
1861                  * We don't reserve metadata space for space cache inodes so we
1862                  * don't need to call dellalloc_release_metadata if there is an
1863                  * error.
1864                  */
1865                 if (*bits & EXTENT_CLEAR_META_RESV &&
1866                     root != fs_info->tree_root)
1867                         btrfs_delalloc_release_metadata(inode, len, false);
1868 
1869                 /* For sanity tests. */
1870                 if (btrfs_is_testing(fs_info))
1871                         return;
1872 
1873                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1874                     do_list && !(state->state & EXTENT_NORESERVE) &&
1875                     (*bits & EXTENT_CLEAR_DATA_RESV))
1876                         btrfs_free_reserved_data_space_noquota(
1877                                         &inode->vfs_inode,
1878                                         state->start, len);
1879 
1880                 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1881                                          fs_info->delalloc_batch);
1882                 spin_lock(&inode->lock);
1883                 inode->delalloc_bytes -= len;
1884                 if (do_list && inode->delalloc_bytes == 0 &&
1885                     test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1886                                         &inode->runtime_flags))
1887                         btrfs_del_delalloc_inode(root, inode);
1888                 spin_unlock(&inode->lock);
1889         }
1890 
1891         if ((state->state & EXTENT_DELALLOC_NEW) &&
1892             (*bits & EXTENT_DELALLOC_NEW)) {
1893                 spin_lock(&inode->lock);
1894                 ASSERT(inode->new_delalloc_bytes >= len);
1895                 inode->new_delalloc_bytes -= len;
1896                 spin_unlock(&inode->lock);
1897         }
1898 }
1899 
1900 /*
1901  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1902  * we don't create bios that span stripes or chunks
1903  *
1904  * return 1 if page cannot be merged to bio
1905  * return 0 if page can be merged to bio
1906  * return error otherwise
1907  */
1908 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1909                          size_t size, struct bio *bio,
1910                          unsigned long bio_flags)
1911 {
1912         struct inode *inode = page->mapping->host;
1913         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1914         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1915         u64 length = 0;
1916         u64 map_length;
1917         int ret;
1918 
1919         if (bio_flags & EXTENT_BIO_COMPRESSED)
1920                 return 0;
1921 
1922         length = bio->bi_iter.bi_size;
1923         map_length = length;
1924         ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1925                               NULL, 0);
1926         if (ret < 0)
1927                 return ret;
1928         if (map_length < length + size)
1929                 return 1;
1930         return 0;
1931 }
1932 
1933 /*
1934  * in order to insert checksums into the metadata in large chunks,
1935  * we wait until bio submission time.   All the pages in the bio are
1936  * checksummed and sums are attached onto the ordered extent record.
1937  *
1938  * At IO completion time the cums attached on the ordered extent record
1939  * are inserted into the btree
1940  */
1941 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1942                                     u64 bio_offset)
1943 {
1944         struct inode *inode = private_data;
1945         blk_status_t ret = 0;
1946 
1947         ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1948         BUG_ON(ret); /* -ENOMEM */
1949         return 0;
1950 }
1951 
1952 /*
1953  * in order to insert checksums into the metadata in large chunks,
1954  * we wait until bio submission time.   All the pages in the bio are
1955  * checksummed and sums are attached onto the ordered extent record.
1956  *
1957  * At IO completion time the cums attached on the ordered extent record
1958  * are inserted into the btree
1959  */
1960 static blk_status_t btrfs_submit_bio_done(void *private_data, struct bio *bio,
1961                           int mirror_num)
1962 {
1963         struct inode *inode = private_data;
1964         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1965         blk_status_t ret;
1966 
1967         ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1968         if (ret) {
1969                 bio->bi_status = ret;
1970                 bio_endio(bio);
1971         }
1972         return ret;
1973 }
1974 
1975 /*
1976  * extent_io.c submission hook. This does the right thing for csum calculation
1977  * on write, or reading the csums from the tree before a read.
1978  *
1979  * Rules about async/sync submit,
1980  * a) read:                             sync submit
1981  *
1982  * b) write without checksum:           sync submit
1983  *
1984  * c) write with checksum:
1985  *    c-1) if bio is issued by fsync:   sync submit
1986  *         (sync_writers != 0)
1987  *
1988  *    c-2) if root is reloc root:       sync submit
1989  *         (only in case of buffered IO)
1990  *
1991  *    c-3) otherwise:                   async submit
1992  */
1993 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1994                                  int mirror_num, unsigned long bio_flags,
1995                                  u64 bio_offset)
1996 {
1997         struct inode *inode = private_data;
1998         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1999         struct btrfs_root *root = BTRFS_I(inode)->root;
2000         enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2001         blk_status_t ret = 0;
2002         int skip_sum;
2003         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2004 
2005         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2006 
2007         if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2008                 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2009 
2010         if (bio_op(bio) != REQ_OP_WRITE) {
2011                 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2012                 if (ret)
2013                         goto out;
2014 
2015                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2016                         ret = btrfs_submit_compressed_read(inode, bio,
2017                                                            mirror_num,
2018                                                            bio_flags);
2019                         goto out;
2020                 } else if (!skip_sum) {
2021                         ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2022                         if (ret)
2023                                 goto out;
2024                 }
2025                 goto mapit;
2026         } else if (async && !skip_sum) {
2027                 /* csum items have already been cloned */
2028                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2029                         goto mapit;
2030                 /* we're doing a write, do the async checksumming */
2031                 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2032                                           bio_offset, inode,
2033                                           btrfs_submit_bio_start,
2034                                           btrfs_submit_bio_done);
2035                 goto out;
2036         } else if (!skip_sum) {
2037                 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2038                 if (ret)
2039                         goto out;
2040         }
2041 
2042 mapit:
2043         ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2044 
2045 out:
2046         if (ret) {
2047                 bio->bi_status = ret;
2048                 bio_endio(bio);
2049         }
2050         return ret;
2051 }
2052 
2053 /*
2054  * given a list of ordered sums record them in the inode.  This happens
2055  * at IO completion time based on sums calculated at bio submission time.
2056  */
2057 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2058                              struct inode *inode, struct list_head *list)
2059 {
2060         struct btrfs_ordered_sum *sum;
2061         int ret;
2062 
2063         list_for_each_entry(sum, list, list) {
2064                 trans->adding_csums = true;
2065                 ret = btrfs_csum_file_blocks(trans,
2066                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
2067                 trans->adding_csums = false;
2068                 if (ret)
2069                         return ret;
2070         }
2071         return 0;
2072 }
2073 
2074 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2075                               unsigned int extra_bits,
2076                               struct extent_state **cached_state, int dedupe)
2077 {
2078         WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2079         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2080                                    extra_bits, cached_state);
2081 }
2082 
2083 /* see btrfs_writepage_start_hook for details on why this is required */
2084 struct btrfs_writepage_fixup {
2085         struct page *page;
2086         struct btrfs_work work;
2087 };
2088 
2089 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2090 {
2091         struct btrfs_writepage_fixup *fixup;
2092         struct btrfs_ordered_extent *ordered;
2093         struct extent_state *cached_state = NULL;
2094         struct extent_changeset *data_reserved = NULL;
2095         struct page *page;
2096         struct inode *inode;
2097         u64 page_start;
2098         u64 page_end;
2099         int ret;
2100 
2101         fixup = container_of(work, struct btrfs_writepage_fixup, work);
2102         page = fixup->page;
2103 again:
2104         lock_page(page);
2105         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2106                 ClearPageChecked(page);
2107                 goto out_page;
2108         }
2109 
2110         inode = page->mapping->host;
2111         page_start = page_offset(page);
2112         page_end = page_offset(page) + PAGE_SIZE - 1;
2113 
2114         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2115                          &cached_state);
2116 
2117         /* already ordered? We're done */
2118         if (PagePrivate2(page))
2119                 goto out;
2120 
2121         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2122                                         PAGE_SIZE);
2123         if (ordered) {
2124                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2125                                      page_end, &cached_state);
2126                 unlock_page(page);
2127                 btrfs_start_ordered_extent(inode, ordered, 1);
2128                 btrfs_put_ordered_extent(ordered);
2129                 goto again;
2130         }
2131 
2132         ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2133                                            PAGE_SIZE);
2134         if (ret) {
2135                 mapping_set_error(page->mapping, ret);
2136                 end_extent_writepage(page, ret, page_start, page_end);
2137                 ClearPageChecked(page);
2138                 goto out;
2139          }
2140 
2141         ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2142                                         &cached_state, 0);
2143         if (ret) {
2144                 mapping_set_error(page->mapping, ret);
2145                 end_extent_writepage(page, ret, page_start, page_end);
2146                 ClearPageChecked(page);
2147                 goto out;
2148         }
2149 
2150         ClearPageChecked(page);
2151         set_page_dirty(page);
2152         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2153 out:
2154         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2155                              &cached_state);
2156 out_page:
2157         unlock_page(page);
2158         put_page(page);
2159         kfree(fixup);
2160         extent_changeset_free(data_reserved);
2161 }
2162 
2163 /*
2164  * There are a few paths in the higher layers of the kernel that directly
2165  * set the page dirty bit without asking the filesystem if it is a
2166  * good idea.  This causes problems because we want to make sure COW
2167  * properly happens and the data=ordered rules are followed.
2168  *
2169  * In our case any range that doesn't have the ORDERED bit set
2170  * hasn't been properly setup for IO.  We kick off an async process
2171  * to fix it up.  The async helper will wait for ordered extents, set
2172  * the delalloc bit and make it safe to write the page.
2173  */
2174 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2175 {
2176         struct inode *inode = page->mapping->host;
2177         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2178         struct btrfs_writepage_fixup *fixup;
2179 
2180         /* this page is properly in the ordered list */
2181         if (TestClearPagePrivate2(page))
2182                 return 0;
2183 
2184         if (PageChecked(page))
2185                 return -EAGAIN;
2186 
2187         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2188         if (!fixup)
2189                 return -EAGAIN;
2190 
2191         SetPageChecked(page);
2192         get_page(page);
2193         btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2194                         btrfs_writepage_fixup_worker, NULL, NULL);
2195         fixup->page = page;
2196         btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2197         return -EBUSY;
2198 }
2199 
2200 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2201                                        struct inode *inode, u64 file_pos,
2202                                        u64 disk_bytenr, u64 disk_num_bytes,
2203                                        u64 num_bytes, u64 ram_bytes,
2204                                        u8 compression, u8 encryption,
2205                                        u16 other_encoding, int extent_type)
2206 {
2207         struct btrfs_root *root = BTRFS_I(inode)->root;
2208         struct btrfs_file_extent_item *fi;
2209         struct btrfs_path *path;
2210         struct extent_buffer *leaf;
2211         struct btrfs_key ins;
2212         u64 qg_released;
2213         int extent_inserted = 0;
2214         int ret;
2215 
2216         path = btrfs_alloc_path();
2217         if (!path)
2218                 return -ENOMEM;
2219 
2220         /*
2221          * we may be replacing one extent in the tree with another.
2222          * The new extent is pinned in the extent map, and we don't want
2223          * to drop it from the cache until it is completely in the btree.
2224          *
2225          * So, tell btrfs_drop_extents to leave this extent in the cache.
2226          * the caller is expected to unpin it and allow it to be merged
2227          * with the others.
2228          */
2229         ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2230                                    file_pos + num_bytes, NULL, 0,
2231                                    1, sizeof(*fi), &extent_inserted);
2232         if (ret)
2233                 goto out;
2234 
2235         if (!extent_inserted) {
2236                 ins.objectid = btrfs_ino(BTRFS_I(inode));
2237                 ins.offset = file_pos;
2238                 ins.type = BTRFS_EXTENT_DATA_KEY;
2239 
2240                 path->leave_spinning = 1;
2241                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2242                                               sizeof(*fi));
2243                 if (ret)
2244                         goto out;
2245         }
2246         leaf = path->nodes[0];
2247         fi = btrfs_item_ptr(leaf, path->slots[0],
2248                             struct btrfs_file_extent_item);
2249         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2250         btrfs_set_file_extent_type(leaf, fi, extent_type);
2251         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2252         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2253         btrfs_set_file_extent_offset(leaf, fi, 0);
2254         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2255         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2256         btrfs_set_file_extent_compression(leaf, fi, compression);
2257         btrfs_set_file_extent_encryption(leaf, fi, encryption);
2258         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2259 
2260         btrfs_mark_buffer_dirty(leaf);
2261         btrfs_release_path(path);
2262 
2263         inode_add_bytes(inode, num_bytes);
2264 
2265         ins.objectid = disk_bytenr;
2266         ins.offset = disk_num_bytes;
2267         ins.type = BTRFS_EXTENT_ITEM_KEY;
2268 
2269         /*
2270          * Release the reserved range from inode dirty range map, as it is
2271          * already moved into delayed_ref_head
2272          */
2273         ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2274         if (ret < 0)
2275                 goto out;
2276         qg_released = ret;
2277         ret = btrfs_alloc_reserved_file_extent(trans, root,
2278                                                btrfs_ino(BTRFS_I(inode)),
2279                                                file_pos, qg_released, &ins);
2280 out:
2281         btrfs_free_path(path);
2282 
2283         return ret;
2284 }
2285 
2286 /* snapshot-aware defrag */
2287 struct sa_defrag_extent_backref {
2288         struct rb_node node;
2289         struct old_sa_defrag_extent *old;
2290         u64 root_id;
2291         u64 inum;
2292         u64 file_pos;
2293         u64 extent_offset;
2294         u64 num_bytes;
2295         u64 generation;
2296 };
2297 
2298 struct old_sa_defrag_extent {
2299         struct list_head list;
2300         struct new_sa_defrag_extent *new;
2301 
2302         u64 extent_offset;
2303         u64 bytenr;
2304         u64 offset;
2305         u64 len;
2306         int count;
2307 };
2308 
2309 struct new_sa_defrag_extent {
2310         struct rb_root root;
2311         struct list_head head;
2312         struct btrfs_path *path;
2313         struct inode *inode;
2314         u64 file_pos;
2315         u64 len;
2316         u64 bytenr;
2317         u64 disk_len;
2318         u8 compress_type;
2319 };
2320 
2321 static int backref_comp(struct sa_defrag_extent_backref *b1,
2322                         struct sa_defrag_extent_backref *b2)
2323 {
2324         if (b1->root_id < b2->root_id)
2325                 return -1;
2326         else if (b1->root_id > b2->root_id)
2327                 return 1;
2328 
2329         if (b1->inum < b2->inum)
2330                 return -1;
2331         else if (b1->inum > b2->inum)
2332                 return 1;
2333 
2334         if (b1->file_pos < b2->file_pos)
2335                 return -1;
2336         else if (b1->file_pos > b2->file_pos)
2337                 return 1;
2338 
2339         /*
2340          * [------------------------------] ===> (a range of space)
2341          *     |<--->|   |<---->| =============> (fs/file tree A)
2342          * |<---------------------------->| ===> (fs/file tree B)
2343          *
2344          * A range of space can refer to two file extents in one tree while
2345          * refer to only one file extent in another tree.
2346          *
2347          * So we may process a disk offset more than one time(two extents in A)
2348          * and locate at the same extent(one extent in B), then insert two same
2349          * backrefs(both refer to the extent in B).
2350          */
2351         return 0;
2352 }
2353 
2354 static void backref_insert(struct rb_root *root,
2355                            struct sa_defrag_extent_backref *backref)
2356 {
2357         struct rb_node **p = &root->rb_node;
2358         struct rb_node *parent = NULL;
2359         struct sa_defrag_extent_backref *entry;
2360         int ret;
2361 
2362         while (*p) {
2363                 parent = *p;
2364                 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2365 
2366                 ret = backref_comp(backref, entry);
2367                 if (ret < 0)
2368                         p = &(*p)->rb_left;
2369                 else
2370                         p = &(*p)->rb_right;
2371         }
2372 
2373         rb_link_node(&backref->node, parent, p);
2374         rb_insert_color(&backref->node, root);
2375 }
2376 
2377 /*
2378  * Note the backref might has changed, and in this case we just return 0.
2379  */
2380 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2381                                        void *ctx)
2382 {
2383         struct btrfs_file_extent_item *extent;
2384         struct old_sa_defrag_extent *old = ctx;
2385         struct new_sa_defrag_extent *new = old->new;
2386         struct btrfs_path *path = new->path;
2387         struct btrfs_key key;
2388         struct btrfs_root *root;
2389         struct sa_defrag_extent_backref *backref;
2390         struct extent_buffer *leaf;
2391         struct inode *inode = new->inode;
2392         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2393         int slot;
2394         int ret;
2395         u64 extent_offset;
2396         u64 num_bytes;
2397 
2398         if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2399             inum == btrfs_ino(BTRFS_I(inode)))
2400                 return 0;
2401 
2402         key.objectid = root_id;
2403         key.type = BTRFS_ROOT_ITEM_KEY;
2404         key.offset = (u64)-1;
2405 
2406         root = btrfs_read_fs_root_no_name(fs_info, &key);
2407         if (IS_ERR(root)) {
2408                 if (PTR_ERR(root) == -ENOENT)
2409                         return 0;
2410                 WARN_ON(1);
2411                 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2412                          inum, offset, root_id);
2413                 return PTR_ERR(root);
2414         }
2415 
2416         key.objectid = inum;
2417         key.type = BTRFS_EXTENT_DATA_KEY;
2418         if (offset > (u64)-1 << 32)
2419                 key.offset = 0;
2420         else
2421                 key.offset = offset;
2422 
2423         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2424         if (WARN_ON(ret < 0))
2425                 return ret;
2426         ret = 0;
2427 
2428         while (1) {
2429                 cond_resched();
2430 
2431                 leaf = path->nodes[0];
2432                 slot = path->slots[0];
2433 
2434                 if (slot >= btrfs_header_nritems(leaf)) {
2435                         ret = btrfs_next_leaf(root, path);
2436                         if (ret < 0) {
2437                                 goto out;
2438                         } else if (ret > 0) {
2439                                 ret = 0;
2440                                 goto out;
2441                         }
2442                         continue;
2443                 }
2444 
2445                 path->slots[0]++;
2446 
2447                 btrfs_item_key_to_cpu(leaf, &key, slot);
2448 
2449                 if (key.objectid > inum)
2450                         goto out;
2451 
2452                 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2453                         continue;
2454 
2455                 extent = btrfs_item_ptr(leaf, slot,
2456                                         struct btrfs_file_extent_item);
2457 
2458                 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2459                         continue;
2460 
2461                 /*
2462                  * 'offset' refers to the exact key.offset,
2463                  * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2464                  * (key.offset - extent_offset).
2465                  */
2466                 if (key.offset != offset)
2467                         continue;
2468 
2469                 extent_offset = btrfs_file_extent_offset(leaf, extent);
2470                 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2471 
2472                 if (extent_offset >= old->extent_offset + old->offset +
2473                     old->len || extent_offset + num_bytes <=
2474                     old->extent_offset + old->offset)
2475                         continue;
2476                 break;
2477         }
2478 
2479         backref = kmalloc(sizeof(*backref), GFP_NOFS);
2480         if (!backref) {
2481                 ret = -ENOENT;
2482                 goto out;
2483         }
2484 
2485         backref->root_id = root_id;
2486         backref->inum = inum;
2487         backref->file_pos = offset;
2488         backref->num_bytes = num_bytes;
2489         backref->extent_offset = extent_offset;
2490         backref->generation = btrfs_file_extent_generation(leaf, extent);
2491         backref->old = old;
2492         backref_insert(&new->root, backref);
2493         old->count++;
2494 out:
2495         btrfs_release_path(path);
2496         WARN_ON(ret);
2497         return ret;
2498 }
2499 
2500 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2501                                    struct new_sa_defrag_extent *new)
2502 {
2503         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2504         struct old_sa_defrag_extent *old, *tmp;
2505         int ret;
2506 
2507         new->path = path;
2508 
2509         list_for_each_entry_safe(old, tmp, &new->head, list) {
2510                 ret = iterate_inodes_from_logical(old->bytenr +
2511                                                   old->extent_offset, fs_info,
2512                                                   path, record_one_backref,
2513                                                   old, false);
2514                 if (ret < 0 && ret != -ENOENT)
2515                         return false;
2516 
2517                 /* no backref to be processed for this extent */
2518                 if (!old->count) {
2519                         list_del(&old->list);
2520                         kfree(old);
2521                 }
2522         }
2523 
2524         if (list_empty(&new->head))
2525                 return false;
2526 
2527         return true;
2528 }
2529 
2530 static int relink_is_mergable(struct extent_buffer *leaf,
2531                               struct btrfs_file_extent_item *fi,
2532                               struct new_sa_defrag_extent *new)
2533 {
2534         if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2535                 return 0;
2536 
2537         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2538                 return 0;
2539 
2540         if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2541                 return 0;
2542 
2543         if (btrfs_file_extent_encryption(leaf, fi) ||
2544             btrfs_file_extent_other_encoding(leaf, fi))
2545                 return 0;
2546 
2547         return 1;
2548 }
2549 
2550 /*
2551  * Note the backref might has changed, and in this case we just return 0.
2552  */
2553 static noinline int relink_extent_backref(struct btrfs_path *path,
2554                                  struct sa_defrag_extent_backref *prev,
2555                                  struct sa_defrag_extent_backref *backref)
2556 {
2557         struct btrfs_file_extent_item *extent;
2558         struct btrfs_file_extent_item *item;
2559         struct btrfs_ordered_extent *ordered;
2560         struct btrfs_trans_handle *trans;
2561         struct btrfs_root *root;
2562         struct btrfs_key key;
2563         struct extent_buffer *leaf;
2564         struct old_sa_defrag_extent *old = backref->old;
2565         struct new_sa_defrag_extent *new = old->new;
2566         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2567         struct inode *inode;
2568         struct extent_state *cached = NULL;
2569         int ret = 0;
2570         u64 start;
2571         u64 len;
2572         u64 lock_start;
2573         u64 lock_end;
2574         bool merge = false;
2575         int index;
2576 
2577         if (prev && prev->root_id == backref->root_id &&
2578             prev->inum == backref->inum &&
2579             prev->file_pos + prev->num_bytes == backref->file_pos)
2580                 merge = true;
2581 
2582         /* step 1: get root */
2583         key.objectid = backref->root_id;
2584         key.type = BTRFS_ROOT_ITEM_KEY;
2585         key.offset = (u64)-1;
2586 
2587         index = srcu_read_lock(&fs_info->subvol_srcu);
2588 
2589         root = btrfs_read_fs_root_no_name(fs_info, &key);
2590         if (IS_ERR(root)) {
2591                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2592                 if (PTR_ERR(root) == -ENOENT)
2593                         return 0;
2594                 return PTR_ERR(root);
2595         }
2596 
2597         if (btrfs_root_readonly(root)) {
2598                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2599                 return 0;
2600         }
2601 
2602         /* step 2: get inode */
2603         key.objectid = backref->inum;
2604         key.type = BTRFS_INODE_ITEM_KEY;
2605         key.offset = 0;
2606 
2607         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2608         if (IS_ERR(inode)) {
2609                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2610                 return 0;
2611         }
2612 
2613         srcu_read_unlock(&fs_info->subvol_srcu, index);
2614 
2615         /* step 3: relink backref */
2616         lock_start = backref->file_pos;
2617         lock_end = backref->file_pos + backref->num_bytes - 1;
2618         lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2619                          &cached);
2620 
2621         ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2622         if (ordered) {
2623                 btrfs_put_ordered_extent(ordered);
2624                 goto out_unlock;
2625         }
2626 
2627         trans = btrfs_join_transaction(root);
2628         if (IS_ERR(trans)) {
2629                 ret = PTR_ERR(trans);
2630                 goto out_unlock;
2631         }
2632 
2633         key.objectid = backref->inum;
2634         key.type = BTRFS_EXTENT_DATA_KEY;
2635         key.offset = backref->file_pos;
2636 
2637         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2638         if (ret < 0) {
2639                 goto out_free_path;
2640         } else if (ret > 0) {
2641                 ret = 0;
2642                 goto out_free_path;
2643         }
2644 
2645         extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2646                                 struct btrfs_file_extent_item);
2647 
2648         if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2649             backref->generation)
2650                 goto out_free_path;
2651 
2652         btrfs_release_path(path);
2653 
2654         start = backref->file_pos;
2655         if (backref->extent_offset < old->extent_offset + old->offset)
2656                 start += old->extent_offset + old->offset -
2657                          backref->extent_offset;
2658 
2659         len = min(backref->extent_offset + backref->num_bytes,
2660                   old->extent_offset + old->offset + old->len);
2661         len -= max(backref->extent_offset, old->extent_offset + old->offset);
2662 
2663         ret = btrfs_drop_extents(trans, root, inode, start,
2664                                  start + len, 1);
2665         if (ret)
2666                 goto out_free_path;
2667 again:
2668         key.objectid = btrfs_ino(BTRFS_I(inode));
2669         key.type = BTRFS_EXTENT_DATA_KEY;
2670         key.offset = start;
2671 
2672         path->leave_spinning = 1;
2673         if (merge) {
2674                 struct btrfs_file_extent_item *fi;
2675                 u64 extent_len;
2676                 struct btrfs_key found_key;
2677 
2678                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2679                 if (ret < 0)
2680                         goto out_free_path;
2681 
2682                 path->slots[0]--;
2683                 leaf = path->nodes[0];
2684                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2685 
2686                 fi = btrfs_item_ptr(leaf, path->slots[0],
2687                                     struct btrfs_file_extent_item);
2688                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2689 
2690                 if (extent_len + found_key.offset == start &&
2691                     relink_is_mergable(leaf, fi, new)) {
2692                         btrfs_set_file_extent_num_bytes(leaf, fi,
2693                                                         extent_len + len);
2694                         btrfs_mark_buffer_dirty(leaf);
2695                         inode_add_bytes(inode, len);
2696 
2697                         ret = 1;
2698                         goto out_free_path;
2699                 } else {
2700                         merge = false;
2701                         btrfs_release_path(path);
2702                         goto again;
2703                 }
2704         }
2705 
2706         ret = btrfs_insert_empty_item(trans, root, path, &key,
2707                                         sizeof(*extent));
2708         if (ret) {
2709                 btrfs_abort_transaction(trans, ret);
2710                 goto out_free_path;
2711         }
2712 
2713         leaf = path->nodes[0];
2714         item = btrfs_item_ptr(leaf, path->slots[0],
2715                                 struct btrfs_file_extent_item);
2716         btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2717         btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2718         btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2719         btrfs_set_file_extent_num_bytes(leaf, item, len);
2720         btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2721         btrfs_set_file_extent_generation(leaf, item, trans->transid);
2722         btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2723         btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2724         btrfs_set_file_extent_encryption(leaf, item, 0);
2725         btrfs_set_file_extent_other_encoding(leaf, item, 0);
2726 
2727         btrfs_mark_buffer_dirty(leaf);
2728         inode_add_bytes(inode, len);
2729         btrfs_release_path(path);
2730 
2731         ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2732                         new->disk_len, 0,
2733                         backref->root_id, backref->inum,
2734                         new->file_pos); /* start - extent_offset */
2735         if (ret) {
2736                 btrfs_abort_transaction(trans, ret);
2737                 goto out_free_path;
2738         }
2739 
2740         ret = 1;
2741 out_free_path:
2742         btrfs_release_path(path);
2743         path->leave_spinning = 0;
2744         btrfs_end_transaction(trans);
2745 out_unlock:
2746         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2747                              &cached);
2748         iput(inode);
2749         return ret;
2750 }
2751 
2752 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2753 {
2754         struct old_sa_defrag_extent *old, *tmp;
2755 
2756         if (!new)
2757                 return;
2758 
2759         list_for_each_entry_safe(old, tmp, &new->head, list) {
2760                 kfree(old);
2761         }
2762         kfree(new);
2763 }
2764 
2765 static void relink_file_extents(struct new_sa_defrag_extent *new)
2766 {
2767         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2768         struct btrfs_path *path;
2769         struct sa_defrag_extent_backref *backref;
2770         struct sa_defrag_extent_backref *prev = NULL;
2771         struct inode *inode;
2772         struct rb_node *node;
2773         int ret;
2774 
2775         inode = new->inode;
2776 
2777         path = btrfs_alloc_path();
2778         if (!path)
2779                 return;
2780 
2781         if (!record_extent_backrefs(path, new)) {
2782                 btrfs_free_path(path);
2783                 goto out;
2784         }
2785         btrfs_release_path(path);
2786 
2787         while (1) {
2788                 node = rb_first(&new->root);
2789                 if (!node)
2790                         break;
2791                 rb_erase(node, &new->root);
2792 
2793                 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2794 
2795                 ret = relink_extent_backref(path, prev, backref);
2796                 WARN_ON(ret < 0);
2797 
2798                 kfree(prev);
2799 
2800                 if (ret == 1)
2801                         prev = backref;
2802                 else
2803                         prev = NULL;
2804                 cond_resched();
2805         }
2806         kfree(prev);
2807 
2808         btrfs_free_path(path);
2809 out:
2810         free_sa_defrag_extent(new);
2811 
2812         atomic_dec(&fs_info->defrag_running);
2813         wake_up(&fs_info->transaction_wait);
2814 }
2815 
2816 static struct new_sa_defrag_extent *
2817 record_old_file_extents(struct inode *inode,
2818                         struct btrfs_ordered_extent *ordered)
2819 {
2820         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2821         struct btrfs_root *root = BTRFS_I(inode)->root;
2822         struct btrfs_path *path;
2823         struct btrfs_key key;
2824         struct old_sa_defrag_extent *old;
2825         struct new_sa_defrag_extent *new;
2826         int ret;
2827 
2828         new = kmalloc(sizeof(*new), GFP_NOFS);
2829         if (!new)
2830                 return NULL;
2831 
2832         new->inode = inode;
2833         new->file_pos = ordered->file_offset;
2834         new->len = ordered->len;
2835         new->bytenr = ordered->start;
2836         new->disk_len = ordered->disk_len;
2837         new->compress_type = ordered->compress_type;
2838         new->root = RB_ROOT;
2839         INIT_LIST_HEAD(&new->head);
2840 
2841         path = btrfs_alloc_path();
2842         if (!path)
2843                 goto out_kfree;
2844 
2845         key.objectid = btrfs_ino(BTRFS_I(inode));
2846         key.type = BTRFS_EXTENT_DATA_KEY;
2847         key.offset = new->file_pos;
2848 
2849         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2850         if (ret < 0)
2851                 goto out_free_path;
2852         if (ret > 0 && path->slots[0] > 0)
2853                 path->slots[0]--;
2854 
2855         /* find out all the old extents for the file range */
2856         while (1) {
2857                 struct btrfs_file_extent_item *extent;
2858                 struct extent_buffer *l;
2859                 int slot;
2860                 u64 num_bytes;
2861                 u64 offset;
2862                 u64 end;
2863                 u64 disk_bytenr;
2864                 u64 extent_offset;
2865 
2866                 l = path->nodes[0];
2867                 slot = path->slots[0];
2868 
2869                 if (slot >= btrfs_header_nritems(l)) {
2870                         ret = btrfs_next_leaf(root, path);
2871                         if (ret < 0)
2872                                 goto out_free_path;
2873                         else if (ret > 0)
2874                                 break;
2875                         continue;
2876                 }
2877 
2878                 btrfs_item_key_to_cpu(l, &key, slot);
2879 
2880                 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2881                         break;
2882                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2883                         break;
2884                 if (key.offset >= new->file_pos + new->len)
2885                         break;
2886 
2887                 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2888 
2889                 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2890                 if (key.offset + num_bytes < new->file_pos)
2891                         goto next;
2892 
2893                 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2894                 if (!disk_bytenr)
2895                         goto next;
2896 
2897                 extent_offset = btrfs_file_extent_offset(l, extent);
2898 
2899                 old = kmalloc(sizeof(*old), GFP_NOFS);
2900                 if (!old)
2901                         goto out_free_path;
2902 
2903                 offset = max(new->file_pos, key.offset);
2904                 end = min(new->file_pos + new->len, key.offset + num_bytes);
2905 
2906                 old->bytenr = disk_bytenr;
2907                 old->extent_offset = extent_offset;
2908                 old->offset = offset - key.offset;
2909                 old->len = end - offset;
2910                 old->new = new;
2911                 old->count = 0;
2912                 list_add_tail(&old->list, &new->head);
2913 next:
2914                 path->slots[0]++;
2915                 cond_resched();
2916         }
2917 
2918         btrfs_free_path(path);
2919         atomic_inc(&fs_info->defrag_running);
2920 
2921         return new;
2922 
2923 out_free_path:
2924         btrfs_free_path(path);
2925 out_kfree:
2926         free_sa_defrag_extent(new);
2927         return NULL;
2928 }
2929 
2930 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2931                                          u64 start, u64 len)
2932 {
2933         struct btrfs_block_group_cache *cache;
2934 
2935         cache = btrfs_lookup_block_group(fs_info, start);
2936         ASSERT(cache);
2937 
2938         spin_lock(&cache->lock);
2939         cache->delalloc_bytes -= len;
2940         spin_unlock(&cache->lock);
2941 
2942         btrfs_put_block_group(cache);
2943 }
2944 
2945 /* as ordered data IO finishes, this gets called so we can finish
2946  * an ordered extent if the range of bytes in the file it covers are
2947  * fully written.
2948  */
2949 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2950 {
2951         struct inode *inode = ordered_extent->inode;
2952         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2953         struct btrfs_root *root = BTRFS_I(inode)->root;
2954         struct btrfs_trans_handle *trans = NULL;
2955         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2956         struct extent_state *cached_state = NULL;
2957         struct new_sa_defrag_extent *new = NULL;
2958         int compress_type = 0;
2959         int ret = 0;
2960         u64 logical_len = ordered_extent->len;
2961         bool nolock;
2962         bool truncated = false;
2963         bool range_locked = false;
2964         bool clear_new_delalloc_bytes = false;
2965 
2966         if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2967             !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2968             !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2969                 clear_new_delalloc_bytes = true;
2970 
2971         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2972 
2973         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2974                 ret = -EIO;
2975                 goto out;
2976         }
2977 
2978         btrfs_free_io_failure_record(BTRFS_I(inode),
2979                         ordered_extent->file_offset,
2980                         ordered_extent->file_offset +
2981                         ordered_extent->len - 1);
2982 
2983         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2984                 truncated = true;
2985                 logical_len = ordered_extent->truncated_len;
2986                 /* Truncated the entire extent, don't bother adding */
2987                 if (!logical_len)
2988                         goto out;
2989         }
2990 
2991         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2992                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2993 
2994                 /*
2995                  * For mwrite(mmap + memset to write) case, we still reserve
2996                  * space for NOCOW range.
2997                  * As NOCOW won't cause a new delayed ref, just free the space
2998                  */
2999                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3000                                        ordered_extent->len);
3001                 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3002                 if (nolock)
3003                         trans = btrfs_join_transaction_nolock(root);
3004                 else
3005                         trans = btrfs_join_transaction(root);
3006                 if (IS_ERR(trans)) {
3007                         ret = PTR_ERR(trans);
3008                         trans = NULL;
3009                         goto out;
3010                 }
3011                 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3012                 ret = btrfs_update_inode_fallback(trans, root, inode);
3013                 if (ret) /* -ENOMEM or corruption */
3014                         btrfs_abort_transaction(trans, ret);
3015                 goto out;
3016         }
3017 
3018         range_locked = true;
3019         lock_extent_bits(io_tree, ordered_extent->file_offset,
3020                          ordered_extent->file_offset + ordered_extent->len - 1,
3021                          &cached_state);
3022 
3023         ret = test_range_bit(io_tree, ordered_extent->file_offset,
3024                         ordered_extent->file_offset + ordered_extent->len - 1,
3025                         EXTENT_DEFRAG, 0, cached_state);
3026         if (ret) {
3027                 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3028                 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3029                         /* the inode is shared */
3030                         new = record_old_file_extents(inode, ordered_extent);
3031 
3032                 clear_extent_bit(io_tree, ordered_extent->file_offset,
3033                         ordered_extent->file_offset + ordered_extent->len - 1,
3034                         EXTENT_DEFRAG, 0, 0, &cached_state);
3035         }
3036 
3037         if (nolock)
3038                 trans = btrfs_join_transaction_nolock(root);
3039         else
3040                 trans = btrfs_join_transaction(root);
3041         if (IS_ERR(trans)) {
3042                 ret = PTR_ERR(trans);
3043                 trans = NULL;
3044                 goto out;
3045         }
3046 
3047         trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3048 
3049         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3050                 compress_type = ordered_extent->compress_type;
3051         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3052                 BUG_ON(compress_type);
3053                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3054                                        ordered_extent->len);
3055                 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3056                                                 ordered_extent->file_offset,
3057                                                 ordered_extent->file_offset +
3058                                                 logical_len);
3059         } else {
3060                 BUG_ON(root == fs_info->tree_root);
3061                 ret = insert_reserved_file_extent(trans, inode,
3062                                                 ordered_extent->file_offset,
3063                                                 ordered_extent->start,
3064                                                 ordered_extent->disk_len,
3065                                                 logical_len, logical_len,
3066                                                 compress_type, 0, 0,
3067                                                 BTRFS_FILE_EXTENT_REG);
3068                 if (!ret)
3069                         btrfs_release_delalloc_bytes(fs_info,
3070                                                      ordered_extent->start,
3071                                                      ordered_extent->disk_len);
3072         }
3073         unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3074                            ordered_extent->file_offset, ordered_extent->len,
3075                            trans->transid);
3076         if (ret < 0) {
3077                 btrfs_abort_transaction(trans, ret);
3078                 goto out;
3079         }
3080 
3081         ret = add_pending_csums(trans, inode, &ordered_extent->list);
3082         if (ret) {
3083                 btrfs_abort_transaction(trans, ret);
3084                 goto out;
3085         }
3086 
3087         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3088         ret = btrfs_update_inode_fallback(trans, root, inode);
3089         if (ret) { /* -ENOMEM or corruption */
3090                 btrfs_abort_transaction(trans, ret);
3091                 goto out;
3092         }
3093         ret = 0;
3094 out:
3095         if (range_locked || clear_new_delalloc_bytes) {
3096                 unsigned int clear_bits = 0;
3097 
3098                 if (range_locked)
3099                         clear_bits |= EXTENT_LOCKED;
3100                 if (clear_new_delalloc_bytes)
3101                         clear_bits |= EXTENT_DELALLOC_NEW;
3102                 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3103                                  ordered_extent->file_offset,
3104                                  ordered_extent->file_offset +
3105                                  ordered_extent->len - 1,
3106                                  clear_bits,
3107                                  (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3108                                  0, &cached_state);
3109         }
3110 
3111         if (trans)
3112                 btrfs_end_transaction(trans);
3113 
3114         if (ret || truncated) {
3115                 u64 start, end;
3116 
3117                 if (truncated)
3118                         start = ordered_extent->file_offset + logical_len;
3119                 else
3120                         start = ordered_extent->file_offset;
3121                 end = ordered_extent->file_offset + ordered_extent->len - 1;
3122                 clear_extent_uptodate(io_tree, start, end, NULL);
3123 
3124                 /* Drop the cache for the part of the extent we didn't write. */
3125                 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3126 
3127                 /*
3128                  * If the ordered extent had an IOERR or something else went
3129                  * wrong we need to return the space for this ordered extent
3130                  * back to the allocator.  We only free the extent in the
3131                  * truncated case if we didn't write out the extent at all.
3132                  */
3133                 if ((ret || !logical_len) &&
3134                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3135                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3136                         btrfs_free_reserved_extent(fs_info,
3137                                                    ordered_extent->start,
3138                                                    ordered_extent->disk_len, 1);
3139         }
3140 
3141 
3142         /*
3143          * This needs to be done to make sure anybody waiting knows we are done
3144          * updating everything for this ordered extent.
3145          */
3146         btrfs_remove_ordered_extent(inode, ordered_extent);
3147 
3148         /* for snapshot-aware defrag */
3149         if (new) {
3150                 if (ret) {
3151                         free_sa_defrag_extent(new);
3152                         atomic_dec(&fs_info->defrag_running);
3153                 } else {
3154                         relink_file_extents(new);
3155                 }
3156         }
3157 
3158         /* once for us */
3159         btrfs_put_ordered_extent(ordered_extent);
3160         /* once for the tree */
3161         btrfs_put_ordered_extent(ordered_extent);
3162 
3163         /* Try to release some metadata so we don't get an OOM but don't wait */
3164         btrfs_btree_balance_dirty_nodelay(fs_info);
3165 
3166         return ret;
3167 }
3168 
3169 static void finish_ordered_fn(struct btrfs_work *work)
3170 {
3171         struct btrfs_ordered_extent *ordered_extent;
3172         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3173         btrfs_finish_ordered_io(ordered_extent);
3174 }
3175 
3176 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3177                                 struct extent_state *state, int uptodate)
3178 {
3179         struct inode *inode = page->mapping->host;
3180         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3181         struct btrfs_ordered_extent *ordered_extent = NULL;
3182         struct btrfs_workqueue *wq;
3183         btrfs_work_func_t func;
3184 
3185         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3186 
3187         ClearPagePrivate2(page);
3188         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3189                                             end - start + 1, uptodate))
3190                 return;
3191 
3192         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3193                 wq = fs_info->endio_freespace_worker;
3194                 func = btrfs_freespace_write_helper;
3195         } else {
3196                 wq = fs_info->endio_write_workers;
3197                 func = btrfs_endio_write_helper;
3198         }
3199 
3200         btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3201                         NULL);
3202         btrfs_queue_work(wq, &ordered_extent->work);
3203 }
3204 
3205 static int __readpage_endio_check(struct inode *inode,
3206                                   struct btrfs_io_bio *io_bio,
3207                                   int icsum, struct page *page,
3208                                   int pgoff, u64 start, size_t len)
3209 {
3210         char *kaddr;
3211         u32 csum_expected;
3212         u32 csum = ~(u32)0;
3213 
3214         csum_expected = *(((u32 *)io_bio->csum) + icsum);
3215 
3216         kaddr = kmap_atomic(page);
3217         csum = btrfs_csum_data(kaddr + pgoff, csum,  len);
3218         btrfs_csum_final(csum, (u8 *)&csum);
3219         if (csum != csum_expected)
3220                 goto zeroit;
3221 
3222         kunmap_atomic(kaddr);
3223         return 0;
3224 zeroit:
3225         btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3226                                     io_bio->mirror_num);
3227         memset(kaddr + pgoff, 1, len);
3228         flush_dcache_page(page);
3229         kunmap_atomic(kaddr);
3230         return -EIO;
3231 }
3232 
3233 /*
3234  * when reads are done, we need to check csums to verify the data is correct
3235  * if there's a match, we allow the bio to finish.  If not, the code in
3236  * extent_io.c will try to find good copies for us.
3237  */
3238 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3239                                       u64 phy_offset, struct page *page,
3240                                       u64 start, u64 end, int mirror)
3241 {
3242         size_t offset = start - page_offset(page);
3243         struct inode *inode = page->mapping->host;
3244         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3245         struct btrfs_root *root = BTRFS_I(inode)->root;
3246 
3247         if (PageChecked(page)) {
3248                 ClearPageChecked(page);
3249                 return 0;
3250         }
3251 
3252         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3253                 return 0;
3254 
3255         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3256             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3257                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3258                 return 0;
3259         }
3260 
3261         phy_offset >>= inode->i_sb->s_blocksize_bits;
3262         return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3263                                       start, (size_t)(end - start + 1));
3264 }
3265 
3266 /*
3267  * btrfs_add_delayed_iput - perform a delayed iput on @inode
3268  *
3269  * @inode: The inode we want to perform iput on
3270  *
3271  * This function uses the generic vfs_inode::i_count to track whether we should
3272  * just decrement it (in case it's > 1) or if this is the last iput then link
3273  * the inode to the delayed iput machinery. Delayed iputs are processed at
3274  * transaction commit time/superblock commit/cleaner kthread.
3275  */
3276 void btrfs_add_delayed_iput(struct inode *inode)
3277 {
3278         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3279         struct btrfs_inode *binode = BTRFS_I(inode);
3280 
3281         if (atomic_add_unless(&inode->i_count, -1, 1))
3282                 return;
3283 
3284         spin_lock(&fs_info->delayed_iput_lock);
3285         ASSERT(list_empty(&binode->delayed_iput));
3286         list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3287         spin_unlock(&fs_info->delayed_iput_lock);
3288 }
3289 
3290 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3291 {
3292 
3293         spin_lock(&fs_info->delayed_iput_lock);
3294         while (!list_empty(&fs_info->delayed_iputs)) {
3295                 struct btrfs_inode *inode;
3296 
3297                 inode = list_first_entry(&fs_info->delayed_iputs,
3298                                 struct btrfs_inode, delayed_iput);
3299                 list_del_init(&inode->delayed_iput);
3300                 spin_unlock(&fs_info->delayed_iput_lock);
3301                 iput(&inode->vfs_inode);
3302                 spin_lock(&fs_info->delayed_iput_lock);
3303         }
3304         spin_unlock(&fs_info->delayed_iput_lock);
3305 }
3306 
3307 /*
3308  * This is called in transaction commit time. If there are no orphan
3309  * files in the subvolume, it removes orphan item and frees block_rsv
3310  * structure.
3311  */
3312 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3313                               struct btrfs_root *root)
3314 {
3315         struct btrfs_fs_info *fs_info = root->fs_info;
3316         struct btrfs_block_rsv *block_rsv;
3317         int ret;
3318 
3319         if (atomic_read(&root->orphan_inodes) ||
3320             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3321                 return;
3322 
3323         spin_lock(&root->orphan_lock);
3324         if (atomic_read(&root->orphan_inodes)) {
3325                 spin_unlock(&root->orphan_lock);
3326                 return;
3327         }
3328 
3329         if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3330                 spin_unlock(&root->orphan_lock);
3331                 return;
3332         }
3333 
3334         block_rsv = root->orphan_block_rsv;
3335         root->orphan_block_rsv = NULL;
3336         spin_unlock(&root->orphan_lock);
3337 
3338         if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3339             btrfs_root_refs(&root->root_item) > 0) {
3340                 ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
3341                                             root->root_key.objectid);
3342                 if (ret)
3343                         btrfs_abort_transaction(trans, ret);
3344                 else
3345                         clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3346                                   &root->state);
3347         }
3348 
3349         if (block_rsv) {
3350                 WARN_ON(block_rsv->size > 0);
3351                 btrfs_free_block_rsv(fs_info, block_rsv);
3352         }
3353 }
3354 
3355 /*
3356  * This creates an orphan entry for the given inode in case something goes
3357  * wrong in the middle of an unlink/truncate.
3358  *
3359  * NOTE: caller of this function should reserve 5 units of metadata for
3360  *       this function.
3361  */
3362 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3363                 struct btrfs_inode *inode)
3364 {
3365         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3366         struct btrfs_root *root = inode->root;
3367         struct btrfs_block_rsv *block_rsv = NULL;
3368         int reserve = 0;
3369         bool insert = false;
3370         int ret;
3371 
3372         if (!root->orphan_block_rsv) {
3373                 block_rsv = btrfs_alloc_block_rsv(fs_info,
3374                                                   BTRFS_BLOCK_RSV_TEMP);
3375                 if (!block_rsv)
3376                         return -ENOMEM;
3377         }
3378 
3379         if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3380                               &inode->runtime_flags))
3381                 insert = true;
3382 
3383         if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3384                               &inode->runtime_flags))
3385                 reserve = 1;
3386 
3387         spin_lock(&root->orphan_lock);
3388         /* If someone has created ->orphan_block_rsv, be happy to use it. */
3389         if (!root->orphan_block_rsv) {
3390                 root->orphan_block_rsv = block_rsv;
3391         } else if (block_rsv) {
3392                 btrfs_free_block_rsv(fs_info, block_rsv);
3393                 block_rsv = NULL;
3394         }
3395 
3396         if (insert)
3397                 atomic_inc(&root->orphan_inodes);
3398         spin_unlock(&root->orphan_lock);
3399 
3400         /* grab metadata reservation from transaction handle */
3401         if (reserve) {
3402                 ret = btrfs_orphan_reserve_metadata(trans, inode);
3403                 ASSERT(!ret);
3404                 if (ret) {
3405                         /*
3406                          * dec doesn't need spin_lock as ->orphan_block_rsv
3407                          * would be released only if ->orphan_inodes is
3408                          * zero.
3409                          */
3410                         atomic_dec(&root->orphan_inodes);
3411                         clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3412                                   &inode->runtime_flags);
3413                         if (insert)
3414                                 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3415                                           &inode->runtime_flags);
3416                         return ret;
3417                 }
3418         }
3419 
3420         /* insert an orphan item to track this unlinked/truncated file */
3421         if (insert) {
3422                 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3423                 if (ret) {
3424                         if (reserve) {
3425                                 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3426                                           &inode->runtime_flags);
3427                                 btrfs_orphan_release_metadata(inode);
3428                         }
3429                         /*
3430                          * btrfs_orphan_commit_root may race with us and set
3431                          * ->orphan_block_rsv to zero, in order to avoid that,
3432                          * decrease ->orphan_inodes after everything is done.
3433                          */
3434                         atomic_dec(&root->orphan_inodes);
3435                         if (ret != -EEXIST) {
3436                                 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3437                                           &inode->runtime_flags);
3438                                 btrfs_abort_transaction(trans, ret);
3439                                 return ret;
3440                         }
3441                 }
3442                 ret = 0;
3443         }
3444 
3445         return 0;
3446 }
3447 
3448 /*
3449  * We have done the truncate/delete so we can go ahead and remove the orphan
3450  * item for this particular inode.
3451  */
3452 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3453                             struct btrfs_inode *inode)
3454 {
3455         struct btrfs_root *root = inode->root;
3456         int delete_item = 0;
3457         int ret = 0;
3458 
3459         if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3460                                &inode->runtime_flags))
3461                 delete_item = 1;
3462 
3463         if (delete_item && trans)
3464                 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3465 
3466         if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3467                                &inode->runtime_flags))
3468                 btrfs_orphan_release_metadata(inode);
3469 
3470         /*
3471          * btrfs_orphan_commit_root may race with us and set ->orphan_block_rsv
3472          * to zero, in order to avoid that, decrease ->orphan_inodes after
3473          * everything is done.
3474          */
3475         if (delete_item)
3476                 atomic_dec(&root->orphan_inodes);
3477 
3478         return ret;
3479 }
3480 
3481 /*
3482  * this cleans up any orphans that may be left on the list from the last use
3483  * of this root.
3484  */
3485 int btrfs_orphan_cleanup(struct btrfs_root *root)
3486 {
3487         struct btrfs_fs_info *fs_info = root->fs_info;
3488         struct btrfs_path *path;
3489         struct extent_buffer *leaf;
3490         struct btrfs_key key, found_key;
3491         struct btrfs_trans_handle *trans;
3492         struct inode *inode;
3493         u64 last_objectid = 0;
3494         int ret = 0, nr_unlink = 0, nr_truncate = 0;
3495 
3496         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3497                 return 0;
3498 
3499         path = btrfs_alloc_path();
3500         if (!path) {
3501                 ret = -ENOMEM;
3502                 goto out;
3503         }
3504         path->reada = READA_BACK;
3505 
3506         key.objectid = BTRFS_ORPHAN_OBJECTID;
3507         key.type = BTRFS_ORPHAN_ITEM_KEY;
3508         key.offset = (u64)-1;
3509 
3510         while (1) {
3511                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3512                 if (ret < 0)
3513                         goto out;
3514 
3515                 /*
3516                  * if ret == 0 means we found what we were searching for, which
3517                  * is weird, but possible, so only screw with path if we didn't
3518                  * find the key and see if we have stuff that matches
3519                  */
3520                 if (ret > 0) {
3521                         ret = 0;
3522                         if (path->slots[0] == 0)
3523                                 break;
3524                         path->slots[0]--;
3525                 }
3526 
3527                 /* pull out the item */
3528                 leaf = path->nodes[0];
3529                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3530 
3531                 /* make sure the item matches what we want */
3532                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3533                         break;
3534                 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3535                         break;
3536 
3537                 /* release the path since we're done with it */
3538                 btrfs_release_path(path);
3539 
3540                 /*
3541                  * this is where we are basically btrfs_lookup, without the
3542                  * crossing root thing.  we store the inode number in the
3543                  * offset of the orphan item.
3544                  */
3545 
3546                 if (found_key.offset == last_objectid) {
3547                         btrfs_err(fs_info,
3548                                   "Error removing orphan entry, stopping orphan cleanup");
3549                         ret = -EINVAL;
3550                         goto out;
3551                 }
3552 
3553                 last_objectid = found_key.offset;
3554 
3555                 found_key.objectid = found_key.offset;
3556                 found_key.type = BTRFS_INODE_ITEM_KEY;
3557                 found_key.offset = 0;
3558                 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3559                 ret = PTR_ERR_OR_ZERO(inode);
3560                 if (ret && ret != -ENOENT)
3561                         goto out;
3562 
3563                 if (ret == -ENOENT && root == fs_info->tree_root) {
3564                         struct btrfs_root *dead_root;
3565                         struct btrfs_fs_info *fs_info = root->fs_info;
3566                         int is_dead_root = 0;
3567 
3568                         /*
3569                          * this is an orphan in the tree root. Currently these
3570                          * could come from 2 sources:
3571                          *  a) a snapshot deletion in progress
3572                          *  b) a free space cache inode
3573                          * We need to distinguish those two, as the snapshot
3574                          * orphan must not get deleted.
3575                          * find_dead_roots already ran before us, so if this
3576                          * is a snapshot deletion, we should find the root
3577                          * in the dead_roots list
3578                          */
3579                         spin_lock(&fs_info->trans_lock);
3580                         list_for_each_entry(dead_root, &fs_info->dead_roots,
3581                                             root_list) {
3582                                 if (dead_root->root_key.objectid ==
3583                                     found_key.objectid) {
3584                                         is_dead_root = 1;
3585                                         break;
3586                                 }
3587                         }
3588                         spin_unlock(&fs_info->trans_lock);
3589                         if (is_dead_root) {
3590                                 /* prevent this orphan from being found again */
3591                                 key.offset = found_key.objectid - 1;
3592                                 continue;
3593                         }
3594                 }
3595                 /*
3596                  * Inode is already gone but the orphan item is still there,
3597                  * kill the orphan item.
3598                  */
3599                 if (ret == -ENOENT) {
3600                         trans = btrfs_start_transaction(root, 1);
3601                         if (IS_ERR(trans)) {
3602                                 ret = PTR_ERR(trans);
3603                                 goto out;
3604                         }
3605                         btrfs_debug(fs_info, "auto deleting %Lu",
3606                                     found_key.objectid);
3607                         ret = btrfs_del_orphan_item(trans, root,
3608                                                     found_key.objectid);
3609                         btrfs_end_transaction(trans);
3610                         if (ret)
3611                                 goto out;
3612                         continue;
3613                 }
3614 
3615                 /*
3616                  * add this inode to the orphan list so btrfs_orphan_del does
3617                  * the proper thing when we hit it
3618                  */
3619                 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3620                         &BTRFS_I(inode)->runtime_flags);
3621                 atomic_inc(&root->orphan_inodes);
3622 
3623                 /* if we have links, this was a truncate, lets do that */
3624                 if (inode->i_nlink) {
3625                         if (WARN_ON(!S_ISREG(inode->i_mode))) {
3626                                 iput(inode);
3627                                 continue;
3628                         }
3629                         nr_truncate++;
3630 
3631                         /* 1 for the orphan item deletion. */
3632                         trans = btrfs_start_transaction(root, 1);
3633                         if (IS_ERR(trans)) {
3634                                 iput(inode);
3635                                 ret = PTR_ERR(trans);
3636                                 goto out;
3637                         }
3638                         ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3639                         btrfs_end_transaction(trans);
3640                         if (ret) {
3641                                 iput(inode);
3642                                 goto out;
3643                         }
3644 
3645                         ret = btrfs_truncate(inode, false);
3646                         if (ret)
3647                                 btrfs_orphan_del(NULL, BTRFS_I(inode));
3648                 } else {
3649                         nr_unlink++;
3650                 }
3651 
3652                 /* this will do delete_inode and everything for us */
3653                 iput(inode);
3654                 if (ret)
3655                         goto out;
3656         }
3657         /* release the path since we're done with it */
3658         btrfs_release_path(path);
3659 
3660         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3661 
3662         if (root->orphan_block_rsv)
3663                 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3664                                         (u64)-1);
3665 
3666         if (root->orphan_block_rsv ||
3667             test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3668                 trans = btrfs_join_transaction(root);
3669                 if (!IS_ERR(trans))
3670                         btrfs_end_transaction(trans);
3671         }
3672 
3673         if (nr_unlink)
3674                 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3675         if (nr_truncate)
3676                 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3677 
3678 out:
3679         if (ret)
3680                 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3681         btrfs_free_path(path);
3682         return ret;
3683 }
3684 
3685 /*
3686  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3687  * don't find any xattrs, we know there can't be any acls.
3688  *
3689  * slot is the slot the inode is in, objectid is the objectid of the inode
3690  */
3691 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3692                                           int slot, u64 objectid,
3693                                           int *first_xattr_slot)
3694 {
3695         u32 nritems = btrfs_header_nritems(leaf);
3696         struct btrfs_key found_key;
3697         static u64 xattr_access = 0;
3698         static u64 xattr_default = 0;
3699         int scanned = 0;
3700 
3701         if (!xattr_access) {
3702                 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3703                                         strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3704                 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3705                                         strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3706         }
3707 
3708         slot++;
3709         *first_xattr_slot = -1;
3710         while (slot < nritems) {
3711                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3712 
3713                 /* we found a different objectid, there must not be acls */
3714                 if (found_key.objectid != objectid)
3715                         return 0;
3716 
3717                 /* we found an xattr, assume we've got an acl */
3718                 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3719                         if (*first_xattr_slot == -1)
3720                                 *first_xattr_slot = slot;
3721                         if (found_key.offset == xattr_access ||
3722                             found_key.offset == xattr_default)
3723                                 return 1;
3724                 }
3725 
3726                 /*
3727                  * we found a key greater than an xattr key, there can't
3728                  * be any acls later on
3729                  */
3730                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3731                         return 0;
3732 
3733                 slot++;
3734                 scanned++;
3735 
3736                 /*
3737                  * it goes inode, inode backrefs, xattrs, extents,
3738                  * so if there are a ton of hard links to an inode there can
3739                  * be a lot of backrefs.  Don't waste time searching too hard,
3740                  * this is just an optimization
3741                  */
3742                 if (scanned >= 8)
3743                         break;
3744         }
3745         /* we hit the end of the leaf before we found an xattr or
3746          * something larger than an xattr.  We have to assume the inode
3747          * has acls
3748          */
3749         if (*first_xattr_slot == -1)
3750                 *first_xattr_slot = slot;
3751         return 1;
3752 }
3753 
3754 /*
3755  * read an inode from the btree into the in-memory inode
3756  */
3757 static int btrfs_read_locked_inode(struct inode *inode)
3758 {
3759         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3760         struct btrfs_path *path;
3761         struct extent_buffer *leaf;
3762         struct btrfs_inode_item *inode_item;
3763         struct btrfs_root *root = BTRFS_I(inode)->root;
3764         struct btrfs_key location;
3765         unsigned long ptr;
3766         int maybe_acls;
3767         u32 rdev;
3768         int ret;
3769         bool filled = false;
3770         int first_xattr_slot;
3771 
3772         ret = btrfs_fill_inode(inode, &rdev);
3773         if (!ret)
3774                 filled = true;
3775 
3776         path = btrfs_alloc_path();
3777         if (!path) {
3778                 ret = -ENOMEM;
3779                 goto make_bad;
3780         }
3781 
3782         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3783 
3784         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3785         if (ret) {
3786                 if (ret > 0)
3787                         ret = -ENOENT;
3788                 goto make_bad;
3789         }
3790 
3791         leaf = path->nodes[0];
3792 
3793         if (filled)
3794                 goto cache_index;
3795 
3796         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3797                                     struct btrfs_inode_item);
3798         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3799         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3800         i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3801         i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3802         btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3803 
3804         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3805         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3806 
3807         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3808         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3809 
3810         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3811         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3812 
3813         BTRFS_I(inode)->i_otime.tv_sec =
3814                 btrfs_timespec_sec(leaf, &inode_item->otime);
3815         BTRFS_I(inode)->i_otime.tv_nsec =
3816                 btrfs_timespec_nsec(leaf, &inode_item->otime);
3817 
3818         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3819         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3820         BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3821 
3822         inode_set_iversion_queried(inode,
3823                                    btrfs_inode_sequence(leaf, inode_item));
3824         inode->i_generation = BTRFS_I(inode)->generation;
3825         inode->i_rdev = 0;
3826         rdev = btrfs_inode_rdev(leaf, inode_item);
3827 
3828         BTRFS_I(inode)->index_cnt = (u64)-1;
3829         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3830 
3831 cache_index:
3832         /*
3833          * If we were modified in the current generation and evicted from memory
3834          * and then re-read we need to do a full sync since we don't have any
3835          * idea about which extents were modified before we were evicted from
3836          * cache.
3837          *
3838          * This is required for both inode re-read from disk and delayed inode
3839          * in delayed_nodes_tree.
3840          */
3841         if (BTRFS_I(inode)->last_trans == fs_info->generation)
3842                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3843                         &BTRFS_I(inode)->runtime_flags);
3844 
3845         /*
3846          * We don't persist the id of the transaction where an unlink operation
3847          * against the inode was last made. So here we assume the inode might
3848          * have been evicted, and therefore the exact value of last_unlink_trans
3849          * lost, and set it to last_trans to avoid metadata inconsistencies
3850          * between the inode and its parent if the inode is fsync'ed and the log
3851          * replayed. For example, in the scenario:
3852          *
3853          * touch mydir/foo
3854          * ln mydir/foo mydir/bar
3855          * sync
3856          * unlink mydir/bar
3857          * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
3858          * xfs_io -c fsync mydir/foo
3859          * <power failure>
3860          * mount fs, triggers fsync log replay
3861          *
3862          * We must make sure that when we fsync our inode foo we also log its
3863          * parent inode, otherwise after log replay the parent still has the
3864          * dentry with the "bar" name but our inode foo has a link count of 1
3865          * and doesn't have an inode ref with the name "bar" anymore.
3866          *
3867          * Setting last_unlink_trans to last_trans is a pessimistic approach,
3868          * but it guarantees correctness at the expense of occasional full
3869          * transaction commits on fsync if our inode is a directory, or if our
3870          * inode is not a directory, logging its parent unnecessarily.
3871          */
3872         BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3873 
3874         path->slots[0]++;
3875         if (inode->i_nlink != 1 ||
3876             path->slots[0] >= btrfs_header_nritems(leaf))
3877                 goto cache_acl;
3878 
3879         btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3880         if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3881                 goto cache_acl;
3882 
3883         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3884         if (location.type == BTRFS_INODE_REF_KEY) {
3885                 struct btrfs_inode_ref *ref;
3886 
3887                 ref = (struct btrfs_inode_ref *)ptr;
3888                 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3889         } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3890                 struct btrfs_inode_extref *extref;
3891 
3892                 extref = (struct btrfs_inode_extref *)ptr;
3893                 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3894                                                                      extref);
3895         }
3896 cache_acl:
3897         /*
3898          * try to precache a NULL acl entry for files that don't have
3899          * any xattrs or acls
3900          */
3901         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3902                         btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3903         if (first_xattr_slot != -1) {
3904                 path->slots[0] = first_xattr_slot;
3905                 ret = btrfs_load_inode_props(inode, path);
3906                 if (ret)
3907                         btrfs_err(fs_info,
3908                                   "error loading props for ino %llu (root %llu): %d",
3909                                   btrfs_ino(BTRFS_I(inode)),
3910                                   root->root_key.objectid, ret);
3911         }
3912         btrfs_free_path(path);
3913 
3914         if (!maybe_acls)
3915                 cache_no_acl(inode);
3916 
3917         switch (inode->i_mode & S_IFMT) {
3918         case S_IFREG:
3919                 inode->i_mapping->a_ops = &btrfs_aops;
3920                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3921                 inode->i_fop = &btrfs_file_operations;
3922                 inode->i_op = &btrfs_file_inode_operations;
3923                 break;
3924         case S_IFDIR:
3925                 inode->i_fop = &btrfs_dir_file_operations;
3926                 inode->i_op = &btrfs_dir_inode_operations;
3927                 break;
3928         case S_IFLNK:
3929                 inode->i_op = &btrfs_symlink_inode_operations;
3930                 inode_nohighmem(inode);
3931                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3932                 break;
3933         default:
3934                 inode->i_op = &btrfs_special_inode_operations;
3935                 init_special_inode(inode, inode->i_mode, rdev);
3936                 break;
3937         }
3938 
3939         btrfs_update_iflags(inode);
3940         return 0;
3941 
3942 make_bad:
3943         btrfs_free_path(path);
3944         make_bad_inode(inode);
3945         return ret;
3946 }
3947 
3948 /*
3949  * given a leaf and an inode, copy the inode fields into the leaf
3950  */
3951 static void fill_inode_item(struct btrfs_trans_handle *trans,
3952                             struct extent_buffer *leaf,
3953                             struct btrfs_inode_item *item,
3954                             struct inode *inode)
3955 {
3956         struct btrfs_map_token token;
3957 
3958         btrfs_init_map_token(&token);
3959 
3960         btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3961         btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3962         btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3963                                    &token);
3964         btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3965         btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3966 
3967         btrfs_set_token_timespec_sec(leaf, &item->atime,
3968                                      inode->i_atime.tv_sec, &token);
3969         btrfs_set_token_timespec_nsec(leaf, &item->atime,
3970                                       inode->i_atime.tv_nsec, &token);
3971 
3972         btrfs_set_token_timespec_sec(leaf, &item->mtime,
3973                                      inode->i_mtime.tv_sec, &token);
3974         btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3975                                       inode->i_mtime.tv_nsec, &token);
3976 
3977         btrfs_set_token_timespec_sec(leaf, &item->ctime,
3978                                      inode->i_ctime.tv_sec, &token);
3979         btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3980                                       inode->i_ctime.tv_nsec, &token);
3981 
3982         btrfs_set_token_timespec_sec(leaf, &item->otime,
3983                                      BTRFS_I(inode)->i_otime.tv_sec, &token);
3984         btrfs_set_token_timespec_nsec(leaf, &item->otime,
3985                                       BTRFS_I(inode)->i_otime.tv_nsec, &token);
3986 
3987         btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3988                                      &token);
3989         btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3990                                          &token);
3991         btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3992                                        &token);
3993         btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3994         btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3995         btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3996         btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3997 }
3998 
3999 /*
4000  * copy everything in the in-memory inode into the btree.
4001  */
4002 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4003                                 struct btrfs_root *root, struct inode *inode)
4004 {
4005         struct btrfs_inode_item *inode_item;
4006         struct btrfs_path *path;
4007         struct extent_buffer *leaf;
4008         int ret;
4009 
4010         path = btrfs_alloc_path();
4011         if (!path)
4012                 return -ENOMEM;
4013 
4014         path->leave_spinning = 1;
4015         ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
4016                                  1);
4017         if (ret) {
4018                 if (ret > 0)
4019                         ret = -ENOENT;
4020                 goto failed;
4021         }
4022 
4023         leaf = path->nodes[0];
4024         inode_item = btrfs_item_ptr(leaf, path->slots[0],
4025                                     struct btrfs_inode_item);
4026 
4027         fill_inode_item(trans, leaf, inode_item, inode);
4028         btrfs_mark_buffer_dirty(leaf);
4029         btrfs_set_inode_last_trans(trans, inode);
4030         ret = 0;
4031 failed:
4032         btrfs_free_path(path);
4033         return ret;
4034 }
4035 
4036 /*
4037  * copy everything in the in-memory inode into the btree.
4038  */
4039 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4040                                 struct btrfs_root *root, struct inode *inode)
4041 {
4042         struct btrfs_fs_info *fs_info = root->fs_info;
4043         int ret;
4044 
4045         /*
4046          * If the inode is a free space inode, we can deadlock during commit
4047          * if we put it into the delayed code.
4048          *
4049          * The data relocation inode should also be directly updated
4050          * without delay
4051          */
4052         if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4053             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4054             && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4055                 btrfs_update_root_times(trans, root);
4056 
4057                 ret = btrfs_delayed_update_inode(trans, root, inode);
4058                 if (!ret)
4059                         btrfs_set_inode_last_trans(trans, inode);
4060                 return ret;
4061         }
4062 
4063         return btrfs_update_inode_item(trans, root, inode);
4064 }
4065 
4066 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4067                                          struct btrfs_root *root,
4068                                          struct inode *inode)
4069 {
4070         int ret;
4071 
4072         ret = btrfs_update_inode(trans, root, inode);
4073         if (ret == -ENOSPC)
4074                 return btrfs_update_inode_item(trans, root, inode);
4075         return ret;
4076 }
4077 
4078 /*
4079  * unlink helper that gets used here in inode.c and in the tree logging
4080  * recovery code.  It remove a link in a directory with a given name, and
4081  * also drops the back refs in the inode to the directory
4082  */
4083 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4084                                 struct btrfs_root *root,
4085                                 struct btrfs_inode *dir,
4086                                 struct btrfs_inode *inode,
4087                                 const char *name, int name_len)
4088 {
4089         struct btrfs_fs_info *fs_info = root->fs_info;
4090         struct btrfs_path *path;
4091         int ret = 0;
4092         struct extent_buffer *leaf;
4093         struct btrfs_dir_item *di;
4094         struct btrfs_key key;
4095         u64 index;
4096         u64 ino = btrfs_ino(inode);
4097         u64 dir_ino = btrfs_ino(dir);
4098 
4099         path = btrfs_alloc_path();
4100         if (!path) {
4101                 ret = -ENOMEM;
4102                 goto out;
4103         }
4104 
4105         path->leave_spinning = 1;
4106         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4107                                     name, name_len, -1);
4108         if (IS_ERR(di)) {
4109                 ret = PTR_ERR(di);
4110                 goto err;
4111         }
4112         if (!di) {
4113                 ret = -ENOENT;
4114                 goto err;
4115         }
4116         leaf = path->nodes[0];
4117         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4118         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4119         if (ret)
4120                 goto err;
4121         btrfs_release_path(path);
4122 
4123         /*
4124          * If we don't have dir index, we have to get it by looking up
4125          * the inode ref, since we get the inode ref, remove it directly,
4126          * it is unnecessary to do delayed deletion.
4127          *
4128          * But if we have dir index, needn't search inode ref to get it.
4129          * Since the inode ref is close to the inode item, it is better
4130          * that we delay to delete it, and just do this deletion when
4131          * we update the inode item.
4132          */
4133         if (inode->dir_index) {
4134                 ret = btrfs_delayed_delete_inode_ref(inode);
4135                 if (!ret) {
4136                         index = inode->dir_index;
4137                         goto skip_backref;
4138                 }
4139         }
4140 
4141         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4142                                   dir_ino, &index);
4143         if (ret) {
4144                 btrfs_info(fs_info,
4145                         "failed to delete reference to %.*s, inode %llu parent %llu",
4146                         name_len, name, ino, dir_ino);
4147                 btrfs_abort_transaction(trans, ret);
4148                 goto err;
4149         }
4150 skip_backref:
4151         ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4152         if (ret) {
4153                 btrfs_abort_transaction(trans, ret);
4154                 goto err;
4155         }
4156 
4157         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4158                         dir_ino);
4159         if (ret != 0 && ret != -ENOENT) {
4160                 btrfs_abort_transaction(trans, ret);
4161                 goto err;
4162         }
4163 
4164         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4165                         index);
4166         if (ret == -ENOENT)
4167                 ret = 0;
4168         else if (ret)
4169                 btrfs_abort_transaction(trans, ret);
4170 err:
4171         btrfs_free_path(path);
4172         if (ret)
4173                 goto out;
4174 
4175         btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4176         inode_inc_iversion(&inode->vfs_inode);
4177         inode_inc_iversion(&dir->vfs_inode);
4178         inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4179                 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4180         ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4181 out:
4182         return ret;
4183 }
4184 
4185 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4186                        struct btrfs_root *root,
4187                        struct btrfs_inode *dir, struct btrfs_inode *inode,
4188                        const char *name, int name_len)
4189 {
4190         int ret;
4191         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4192         if (!ret) {
4193                 drop_nlink(&inode->vfs_inode);
4194                 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4195         }
4196         return ret;
4197 }
4198 
4199 /*
4200  * helper to start transaction for unlink and rmdir.
4201  *
4202  * unlink and rmdir are special in btrfs, they do not always free space, so
4203  * if we cannot make our reservations the normal way try and see if there is
4204  * plenty of slack room in the global reserve to migrate, otherwise we cannot
4205  * allow the unlink to occur.
4206  */
4207 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4208 {
4209         struct btrfs_root *root = BTRFS_I(dir)->root;
4210 
4211         /*
4212          * 1 for the possible orphan item
4213          * 1 for the dir item
4214          * 1 for the dir index
4215          * 1 for the inode ref
4216          * 1 for the inode
4217          */
4218         return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4219 }
4220 
4221 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4222 {
4223         struct btrfs_root *root = BTRFS_I(dir)->root;
4224         struct btrfs_trans_handle *trans;
4225         struct inode *inode = d_inode(dentry);
4226         int ret;
4227 
4228         trans = __unlink_start_trans(dir);
4229         if (IS_ERR(trans))
4230                 return PTR_ERR(trans);
4231 
4232         btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4233                         0);
4234 
4235         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4236                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4237                         dentry->d_name.len);
4238         if (ret)
4239                 goto out;
4240 
4241         if (inode->i_nlink == 0) {
4242                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4243                 if (ret)
4244                         goto out;
4245         }
4246 
4247 out:
4248         btrfs_end_transaction(trans);
4249         btrfs_btree_balance_dirty(root->fs_info);
4250         return ret;
4251 }
4252 
4253 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4254                         struct btrfs_root *root,
4255                         struct inode *dir, u64 objectid,
4256                         const char *name, int name_len)
4257 {
4258         struct btrfs_fs_info *fs_info = root->fs_info;
4259         struct btrfs_path *path;
4260         struct extent_buffer *leaf;
4261         struct btrfs_dir_item *di;
4262         struct btrfs_key key;
4263         u64 index;
4264         int ret;
4265         u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4266 
4267         path = btrfs_alloc_path();
4268         if (!path)
4269                 return -ENOMEM;
4270 
4271         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4272                                    name, name_len, -1);
4273         if (IS_ERR_OR_NULL(di)) {
4274                 if (!di)
4275                         ret = -ENOENT;
4276                 else
4277                         ret = PTR_ERR(di);
4278                 goto out;
4279         }
4280 
4281         leaf = path->nodes[0];
4282         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4283         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4284         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4285         if (ret) {
4286                 btrfs_abort_transaction(trans, ret);
4287                 goto out;
4288         }
4289         btrfs_release_path(path);
4290 
4291         ret = btrfs_del_root_ref(trans, fs_info, objectid,
4292                                  root->root_key.objectid, dir_ino,
4293                                  &index, name, name_len);
4294         if (ret < 0) {
4295                 if (ret != -ENOENT) {
4296                         btrfs_abort_transaction(trans, ret);
4297                         goto out;
4298                 }
4299                 di = btrfs_search_dir_index_item(root, path, dir_ino,
4300                                                  name, name_len);
4301                 if (IS_ERR_OR_NULL(di)) {
4302                         if (!di)
4303                                 ret = -ENOENT;
4304                         else
4305                                 ret = PTR_ERR(di);
4306                         btrfs_abort_transaction(trans, ret);
4307                         goto out;
4308                 }
4309 
4310                 leaf = path->nodes[0];
4311                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4312                 btrfs_release_path(path);
4313                 index = key.offset;
4314         }
4315         btrfs_release_path(path);
4316 
4317         ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4318         if (ret) {
4319                 btrfs_abort_transaction(trans, ret);
4320                 goto out;
4321         }
4322 
4323         btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4324         inode_inc_iversion(dir);
4325         dir->i_mtime = dir->i_ctime = current_time(dir);
4326         ret = btrfs_update_inode_fallback(trans, root, dir);
4327         if (ret)
4328                 btrfs_abort_transaction(trans, ret);
4329 out:
4330         btrfs_free_path(path);
4331         return ret;
4332 }
4333 
4334 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4335 {
4336         struct inode *inode = d_inode(dentry);
4337         int err = 0;
4338         struct btrfs_root *root = BTRFS_I(dir)->root;
4339         struct btrfs_trans_handle *trans;
4340         u64 last_unlink_trans;
4341 
4342         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4343                 return -ENOTEMPTY;
4344         if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4345                 return -EPERM;
4346 
4347         trans = __unlink_start_trans(dir);
4348         if (IS_ERR(trans))
4349                 return PTR_ERR(trans);
4350 
4351         if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4352                 err = btrfs_unlink_subvol(trans, root, dir,
4353                                           BTRFS_I(inode)->location.objectid,
4354                                           dentry->d_name.name,
4355                                           dentry->d_name.len);
4356                 goto out;
4357         }
4358 
4359         err = btrfs_orphan_add(trans, BTRFS_I(inode));
4360         if (err)
4361                 goto out;
4362 
4363         last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4364 
4365         /* now the directory is empty */
4366         err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4367                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4368                         dentry->d_name.len);
4369         if (!err) {
4370                 btrfs_i_size_write(BTRFS_I(inode), 0);
4371                 /*
4372                  * Propagate the last_unlink_trans value of the deleted dir to
4373                  * its parent directory. This is to prevent an unrecoverable
4374                  * log tree in the case we do something like this:
4375                  * 1) create dir foo
4376                  * 2) create snapshot under dir foo
4377                  * 3) delete the snapshot
4378                  * 4) rmdir foo
4379                  * 5) mkdir foo
4380                  * 6) fsync foo or some file inside foo
4381                  */
4382                 if (last_unlink_trans >= trans->transid)
4383                         BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4384         }
4385 out:
4386         btrfs_end_transaction(trans);
4387         btrfs_btree_balance_dirty(root->fs_info);
4388 
4389         return err;
4390 }
4391 
4392 static int truncate_space_check(struct btrfs_trans_handle *trans,
4393                                 struct btrfs_root *root,
4394                                 u64 bytes_deleted)
4395 {
4396         struct btrfs_fs_info *fs_info = root->fs_info;
4397         int ret;
4398 
4399         /*
4400          * This is only used to apply pressure to the enospc system, we don't
4401          * intend to use this reservation at all.
4402          */
4403         bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4404         bytes_deleted *= fs_info->nodesize;
4405         ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4406                                   bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4407         if (!ret) {
4408                 trace_btrfs_space_reservation(fs_info, "transaction",
4409                                               trans->transid,
4410                                               bytes_deleted, 1);
4411                 trans->bytes_reserved += bytes_deleted;
4412         }
4413         return ret;
4414 
4415 }
4416 
4417 /*
4418  * Return this if we need to call truncate_block for the last bit of the
4419  * truncate.
4420  */
4421 #define NEED_TRUNCATE_BLOCK 1
4422 
4423 /*
4424  * this can truncate away extent items, csum items and directory items.
4425  * It starts at a high offset and removes keys until it can't find
4426  * any higher than new_size
4427  *
4428  * csum items that cross the new i_size are truncated to the new size
4429  * as well.
4430  *
4431  * min_type is the minimum key type to truncate down to.  If set to 0, this
4432  * will kill all the items on this inode, including the INODE_ITEM_KEY.
4433  */
4434 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4435                                struct btrfs_root *root,
4436                                struct inode *inode,
4437                                u64 new_size, u32 min_type)
4438 {
4439         struct btrfs_fs_info *fs_info = root->fs_info;
4440         struct btrfs_path *path;
4441         struct extent_buffer *leaf;
4442         struct btrfs_file_extent_item *fi;
4443         struct btrfs_key key;
4444         struct btrfs_key found_key;
4445         u64 extent_start = 0;
4446         u64 extent_num_bytes = 0;
4447         u64 extent_offset = 0;
4448         u64 item_end = 0;
4449         u64 last_size = new_size;
4450         u32 found_type = (u8)-1;
4451         int found_extent;
4452         int del_item;
4453         int pending_del_nr = 0;
4454         int pending_del_slot = 0;
4455         int extent_type = -1;
4456         int ret;
4457         int err = 0;
4458         u64 ino = btrfs_ino(BTRFS_I(inode));
4459         u64 bytes_deleted = 0;
4460         bool be_nice = false;
4461         bool should_throttle = false;
4462         bool should_end = false;
4463 
4464         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4465 
4466         /*
4467          * for non-free space inodes and ref cows, we want to back off from
4468          * time to time
4469          */
4470         if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4471             test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4472                 be_nice = true;
4473 
4474         path = btrfs_alloc_path();
4475         if (!path)
4476                 return -ENOMEM;
4477         path->reada = READA_BACK;
4478 
4479         /*
4480          * We want to drop from the next block forward in case this new size is
4481          * not block aligned since we will be keeping the last block of the
4482          * extent just the way it is.
4483          */
4484         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4485             root == fs_info->tree_root)
4486                 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4487                                         fs_info->sectorsize),
4488                                         (u64)-1, 0);
4489 
4490         /*
4491          * This function is also used to drop the items in the log tree before
4492          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4493          * it is used to drop the loged items. So we shouldn't kill the delayed
4494          * items.
4495          */
4496         if (min_type == 0 && root == BTRFS_I(inode)->root)
4497                 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4498 
4499         key.objectid = ino;
4500         key.offset = (u64)-1;
4501         key.type = (u8)-1;
4502 
4503 search_again:
4504         /*
4505          * with a 16K leaf size and 128MB extents, you can actually queue
4506          * up a huge file in a single leaf.  Most of the time that
4507          * bytes_deleted is > 0, it will be huge by the time we get here
4508          */
4509         if (be_nice && bytes_deleted > SZ_32M) {
4510                 if (btrfs_should_end_transaction(trans)) {
4511                         err = -EAGAIN;
4512                         goto error;
4513                 }
4514         }
4515 
4516 
4517         path->leave_spinning = 1;
4518         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4519         if (ret < 0) {
4520                 err = ret;
4521                 goto out;
4522         }
4523 
4524         if (ret > 0) {
4525                 /* there are no items in the tree for us to truncate, we're
4526                  * done
4527                  */
4528                 if (path->slots[0] == 0)
4529                         goto out;
4530                 path->slots[0]--;
4531         }
4532 
4533         while (1) {
4534                 fi = NULL;
4535                 leaf = path->nodes[0];
4536                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4537                 found_type = found_key.type;
4538 
4539                 if (found_key.objectid != ino)
4540                         break;
4541 
4542                 if (found_type < min_type)
4543                         break;
4544 
4545                 item_end = found_key.offset;
4546                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4547                         fi = btrfs_item_ptr(leaf, path->slots[0],
4548                                             struct btrfs_file_extent_item);
4549                         extent_type = btrfs_file_extent_type(leaf, fi);
4550                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4551                                 item_end +=
4552                                     btrfs_file_extent_num_bytes(leaf, fi);
4553 
4554                                 trace_btrfs_truncate_show_fi_regular(
4555                                         BTRFS_I(inode), leaf, fi,
4556                                         found_key.offset);
4557                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4558                                 item_end += btrfs_file_extent_inline_len(leaf,
4559                                                          path->slots[0], fi);
4560 
4561                                 trace_btrfs_truncate_show_fi_inline(
4562                                         BTRFS_I(inode), leaf, fi, path->slots[0],
4563                                         found_key.offset);
4564                         }
4565                         item_end--;
4566                 }
4567                 if (found_type > min_type) {
4568                         del_item = 1;
4569                 } else {
4570                         if (item_end < new_size)
4571                                 break;
4572                         if (found_key.offset >= new_size)
4573                                 del_item = 1;
4574                         else
4575                                 del_item = 0;
4576                 }
4577                 found_extent = 0;
4578                 /* FIXME, shrink the extent if the ref count is only 1 */
4579                 if (found_type != BTRFS_EXTENT_DATA_KEY)
4580                         goto delete;
4581 
4582                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4583                         u64 num_dec;
4584                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4585                         if (!del_item) {
4586                                 u64 orig_num_bytes =
4587                                         btrfs_file_extent_num_bytes(leaf, fi);
4588                                 extent_num_bytes = ALIGN(new_size -
4589                                                 found_key.offset,
4590                                                 fs_info->sectorsize);
4591                                 btrfs_set_file_extent_num_bytes(leaf, fi,
4592                                                          extent_num_bytes);
4593                                 num_dec = (orig_num_bytes -
4594                                            extent_num_bytes);
4595                                 if (test_bit(BTRFS_ROOT_REF_COWS,
4596                                              &root->state) &&
4597                                     extent_start != 0)
4598                                         inode_sub_bytes(inode, num_dec);
4599                                 btrfs_mark_buffer_dirty(leaf);
4600                         } else {
4601                                 extent_num_bytes =
4602                                         btrfs_file_extent_disk_num_bytes(leaf,
4603                                                                          fi);
4604                                 extent_offset = found_key.offset -
4605                                         btrfs_file_extent_offset(leaf, fi);
4606 
4607                                 /* FIXME blocksize != 4096 */
4608                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4609                                 if (extent_start != 0) {
4610                                         found_extent = 1;
4611                                         if (test_bit(BTRFS_ROOT_REF_COWS,
4612                                                      &root->state))
4613                                                 inode_sub_bytes(inode, num_dec);
4614                                 }
4615                         }
4616                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4617                         /*
4618                          * we can't truncate inline items that have had
4619                          * special encodings
4620                          */
4621                         if (!del_item &&
4622                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
4623                             btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4624                             btrfs_file_extent_compression(leaf, fi) == 0) {
4625                                 u32 size = (u32)(new_size - found_key.offset);
4626 
4627                                 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4628                                 size = btrfs_file_extent_calc_inline_size(size);
4629                                 btrfs_truncate_item(root->fs_info, path, size, 1);
4630                         } else if (!del_item) {
4631                                 /*
4632                                  * We have to bail so the last_size is set to
4633                                  * just before this extent.
4634                                  */
4635                                 err = NEED_TRUNCATE_BLOCK;
4636                                 break;
4637                         }
4638 
4639                         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4640                                 inode_sub_bytes(inode, item_end + 1 - new_size);
4641                 }
4642 delete:
4643                 if (del_item)
4644                         last_size = found_key.offset;
4645                 else
4646                         last_size = new_size;
4647                 if (del_item) {
4648                         if (!pending_del_nr) {
4649                                 /* no pending yet, add ourselves */
4650                                 pending_del_slot = path->slots[0];
4651                                 pending_del_nr = 1;
4652                         } else if (pending_del_nr &&
4653                                    path->slots[0] + 1 == pending_del_slot) {
4654                                 /* hop on the pending chunk */
4655                                 pending_del_nr++;
4656                                 pending_del_slot = path->slots[0];
4657                         } else {
4658                                 BUG();
4659                         }
4660                 } else {
4661                         break;
4662                 }
4663                 should_throttle = false;
4664 
4665                 if (found_extent &&
4666                     (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4667                      root == fs_info->tree_root)) {
4668                         btrfs_set_path_blocking(path);
4669                         bytes_deleted += extent_num_bytes;
4670                         ret = btrfs_free_extent(trans, root, extent_start,
4671                                                 extent_num_bytes, 0,
4672                                                 btrfs_header_owner(leaf),
4673                                                 ino, extent_offset);
4674                         if (ret) {
4675                                 btrfs_abort_transaction(trans, ret);
4676                                 break;
4677                         }
4678                         if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4679                                 btrfs_async_run_delayed_refs(fs_info,
4680                                         trans->delayed_ref_updates * 2,
4681                                         trans->transid, 0);
4682                         if (be_nice) {
4683                                 if (truncate_space_check(trans, root,
4684                                                          extent_num_bytes)) {
4685                                         should_end = true;
4686                                 }
4687                                 if (btrfs_should_throttle_delayed_refs(trans,
4688                                                                        fs_info))
4689                                         should_throttle = true;
4690                         }
4691                 }
4692 
4693                 if (found_type == BTRFS_INODE_ITEM_KEY)
4694                         break;
4695 
4696                 if (path->slots[0] == 0 ||
4697                     path->slots[0] != pending_del_slot ||
4698                     should_throttle || should_end) {
4699                         if (pending_del_nr) {
4700                                 ret = btrfs_del_items(trans, root, path,
4701                                                 pending_del_slot,
4702                                                 pending_del_nr);
4703                                 if (ret) {
4704                                         btrfs_abort_transaction(trans, ret);
4705                                         goto error;
4706                                 }
4707                                 pending_del_nr = 0;
4708                         }
4709                         btrfs_release_path(path);
4710                         if (should_throttle) {
4711                                 unsigned long updates = trans->delayed_ref_updates;
4712                                 if (updates) {
4713                                         trans->delayed_ref_updates = 0;
4714                                         ret = btrfs_run_delayed_refs(trans,
4715                                                                    updates * 2);
4716                                         if (ret && !err)
4717                                                 err = ret;
4718                                 }
4719                         }
4720                         /*
4721                          * if we failed to refill our space rsv, bail out
4722                          * and let the transaction restart
4723                          */
4724                         if (should_end) {
4725                                 err = -EAGAIN;
4726                                 goto error;
4727                         }
4728                         goto search_again;
4729                 } else {
4730                         path->slots[0]--;
4731                 }
4732         }
4733 out:
4734         if (pending_del_nr) {
4735                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4736                                       pending_del_nr);
4737                 if (ret)
4738                         btrfs_abort_transaction(trans, ret);
4739         }
4740 error:
4741         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4742                 ASSERT(last_size >= new_size);
4743                 if (!err && last_size > new_size)
4744                         last_size = new_size;
4745                 btrfs_ordered_update_i_size(inode, last_size, NULL);
4746         }
4747 
4748         btrfs_free_path(path);
4749 
4750         if (be_nice && bytes_deleted > SZ_32M) {
4751                 unsigned long updates = trans->delayed_ref_updates;
4752                 if (updates) {
4753                         trans->delayed_ref_updates = 0;
4754                         ret = btrfs_run_delayed_refs(trans, updates * 2);
4755                         if (ret && !err)
4756                                 err = ret;
4757                 }
4758         }
4759         return err;
4760 }
4761 
4762 /*
4763  * btrfs_truncate_block - read, zero a chunk and write a block
4764  * @inode - inode that we're zeroing
4765  * @from - the offset to start zeroing
4766  * @len - the length to zero, 0 to zero the entire range respective to the
4767  *      offset
4768  * @front - zero up to the offset instead of from the offset on
4769  *
4770  * This will find the block for the "from" offset and cow the block and zero the
4771  * part we want to zero.  This is used with truncate and hole punching.
4772  */
4773 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4774                         int front)
4775 {
4776         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4777         struct address_space *mapping = inode->i_mapping;
4778         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4779         struct btrfs_ordered_extent *ordered;
4780         struct extent_state *cached_state = NULL;
4781         struct extent_changeset *data_reserved = NULL;
4782         char *kaddr;
4783         u32 blocksize = fs_info->sectorsize;
4784         pgoff_t index = from >> PAGE_SHIFT;
4785         unsigned offset = from & (blocksize - 1);
4786         struct page *page;
4787         gfp_t mask = btrfs_alloc_write_mask(mapping);
4788         int ret = 0;
4789         u64 block_start;
4790         u64 block_end;
4791 
4792         if (IS_ALIGNED(offset, blocksize) &&
4793             (!len || IS_ALIGNED(len, blocksize)))
4794                 goto out;
4795 
4796         block_start = round_down(from, blocksize);
4797         block_end = block_start + blocksize - 1;
4798 
4799         ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4800                                            block_start, blocksize);
4801         if (ret)
4802                 goto out;
4803 
4804 again:
4805         page = find_or_create_page(mapping, index, mask);
4806         if (!page) {
4807                 btrfs_delalloc_release_space(inode, data_reserved,
4808                                              block_start, blocksize, true);
4809                 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4810                 ret = -ENOMEM;
4811                 goto out;
4812         }
4813 
4814         if (!PageUptodate(page)) {
4815                 ret = btrfs_readpage(NULL, page);
4816                 lock_page(page);
4817                 if (page->mapping != mapping) {
4818                         unlock_page(page);
4819                         put_page(page);
4820                         goto again;
4821                 }
4822                 if (!PageUptodate(page)) {
4823                         ret = -EIO;
4824                         goto out_unlock;
4825                 }
4826         }
4827         wait_on_page_writeback(page);
4828 
4829         lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4830         set_page_extent_mapped(page);
4831 
4832         ordered = btrfs_lookup_ordered_extent(inode, block_start);
4833         if (ordered) {
4834                 unlock_extent_cached(io_tree, block_start, block_end,
4835                                      &cached_state);
4836                 unlock_page(page);
4837                 put_page(page);
4838                 btrfs_start_ordered_extent(inode, ordered, 1);
4839                 btrfs_put_ordered_extent(ordered);
4840                 goto again;
4841         }
4842 
4843         clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4844                           EXTENT_DIRTY | EXTENT_DELALLOC |
4845                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4846                           0, 0, &cached_state);
4847 
4848         ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4849                                         &cached_state, 0);
4850         if (ret) {
4851                 unlock_extent_cached(io_tree, block_start, block_end,
4852                                      &cached_state);
4853                 goto out_unlock;
4854         }
4855 
4856         if (offset != blocksize) {
4857                 if (!len)
4858                         len = blocksize - offset;
4859                 kaddr = kmap(page);
4860                 if (front)
4861                         memset(kaddr + (block_start - page_offset(page)),
4862                                 0, offset);
4863                 else
4864                         memset(kaddr + (block_start - page_offset(page)) +  offset,
4865                                 0, len);
4866                 flush_dcache_page(page);
4867                 kunmap(page);
4868         }
4869         ClearPageChecked(page);
4870         set_page_dirty(page);
4871         unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4872 
4873 out_unlock:
4874         if (ret)
4875                 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4876                                              blocksize, true);
4877         btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
4878         unlock_page(page);
4879         put_page(page);
4880 out:
4881         extent_changeset_free(data_reserved);
4882         return ret;
4883 }
4884 
4885 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4886                              u64 offset, u64 len)
4887 {
4888         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4889         struct btrfs_trans_handle *trans;
4890         int ret;
4891 
4892         /*
4893          * Still need to make sure the inode looks like it's been updated so
4894          * that any holes get logged if we fsync.
4895          */
4896         if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4897                 BTRFS_I(inode)->last_trans = fs_info->generation;
4898                 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4899                 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4900                 return 0;
4901         }
4902 
4903         /*
4904          * 1 - for the one we're dropping
4905          * 1 - for the one we're adding
4906          * 1 - for updating the inode.
4907          */
4908         trans = btrfs_start_transaction(root, 3);
4909         if (IS_ERR(trans))
4910                 return PTR_ERR(trans);
4911 
4912         ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4913         if (ret) {
4914                 btrfs_abort_transaction(trans, ret);
4915                 btrfs_end_transaction(trans);
4916                 return ret;
4917         }
4918 
4919         ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4920                         offset, 0, 0, len, 0, len, 0, 0, 0);
4921         if (ret)
4922                 btrfs_abort_transaction(trans, ret);
4923         else
4924                 btrfs_update_inode(trans, root, inode);
4925         btrfs_end_transaction(trans);
4926         return ret;
4927 }
4928 
4929 /*
4930  * This function puts in dummy file extents for the area we're creating a hole
4931  * for.  So if we are truncating this file to a larger size we need to insert
4932  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4933  * the range between oldsize and size
4934  */
4935 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4936 {
4937         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4938         struct btrfs_root *root = BTRFS_I(inode)->root;
4939         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4940         struct extent_map *em = NULL;
4941         struct extent_state *cached_state = NULL;
4942         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4943         u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4944         u64 block_end = ALIGN(size, fs_info->sectorsize);
4945         u64 last_byte;
4946         u64 cur_offset;
4947         u64 hole_size;
4948         int err = 0;
4949 
4950         /*
4951          * If our size started in the middle of a block we need to zero out the
4952          * rest of the block before we expand the i_size, otherwise we could
4953          * expose stale data.
4954          */
4955         err = btrfs_truncate_block(inode, oldsize, 0, 0);
4956         if (err)
4957                 return err;
4958 
4959         if (size <= hole_start)
4960                 return 0;
4961 
4962         while (1) {
4963                 struct btrfs_ordered_extent *ordered;
4964 
4965                 lock_extent_bits(io_tree, hole_start, block_end - 1,
4966                                  &cached_state);
4967                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
4968                                                      block_end - hole_start);
4969                 if (!ordered)
4970                         break;
4971                 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4972                                      &cached_state);
4973                 btrfs_start_ordered_extent(inode, ordered, 1);
4974                 btrfs_put_ordered_extent(ordered);
4975         }
4976 
4977         cur_offset = hole_start;
4978         while (1) {
4979                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4980                                 block_end - cur_offset, 0);
4981                 if (IS_ERR(em)) {
4982                         err = PTR_ERR(em);
4983                         em = NULL;
4984                         break;
4985                 }
4986                 last_byte = min(extent_map_end(em), block_end);
4987                 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4988                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4989                         struct extent_map *hole_em;
4990                         hole_size = last_byte - cur_offset;
4991 
4992                         err = maybe_insert_hole(root, inode, cur_offset,
4993                                                 hole_size);
4994                         if (err)
4995                                 break;
4996                         btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4997                                                 cur_offset + hole_size - 1, 0);
4998                         hole_em = alloc_extent_map();
4999                         if (!hole_em) {
5000                                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5001                                         &BTRFS_I(inode)->runtime_flags);
5002                                 goto next;
5003                         }
5004                         hole_em->start = cur_offset;
5005                         hole_em->len = hole_size;
5006                         hole_em->orig_start = cur_offset;
5007 
5008                         hole_em->block_start = EXTENT_MAP_HOLE;
5009                         hole_em->block_len = 0;
5010                         hole_em->orig_block_len = 0;
5011                         hole_em->ram_bytes = hole_size;
5012                         hole_em->bdev = fs_info->fs_devices->latest_bdev;
5013                         hole_em->compress_type = BTRFS_COMPRESS_NONE;
5014                         hole_em->generation = fs_info->generation;
5015 
5016                         while (1) {
5017                                 write_lock(&em_tree->lock);
5018                                 err = add_extent_mapping(em_tree, hole_em, 1);
5019                                 write_unlock(&em_tree->lock);
5020                                 if (err != -EEXIST)
5021                                         break;
5022                                 btrfs_drop_extent_cache(BTRFS_I(inode),
5023                                                         cur_offset,
5024                                                         cur_offset +
5025                                                         hole_size - 1, 0);
5026                         }
5027                         free_extent_map(hole_em);
5028                 }
5029 next:
5030                 free_extent_map(em);
5031                 em = NULL;
5032                 cur_offset = last_byte;
5033                 if (cur_offset >= block_end)
5034                         break;
5035         }
5036         free_extent_map(em);
5037         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5038         return err;
5039 }
5040 
5041 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5042 {
5043         struct btrfs_root *root = BTRFS_I(inode)->root;
5044         struct btrfs_trans_handle *trans;
5045         loff_t oldsize = i_size_read(inode);
5046         loff_t newsize = attr->ia_size;
5047         int mask = attr->ia_valid;
5048         int ret;
5049 
5050         /*
5051          * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5052          * special case where we need to update the times despite not having
5053          * these flags set.  For all other operations the VFS set these flags
5054          * explicitly if it wants a timestamp update.
5055          */
5056         if (newsize != oldsize) {
5057                 inode_inc_iversion(inode);
5058                 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5059                         inode->i_ctime = inode->i_mtime =
5060                                 current_time(inode);
5061         }
5062 
5063         if (newsize > oldsize) {
5064                 /*
5065                  * Don't do an expanding truncate while snapshotting is ongoing.
5066                  * This is to ensure the snapshot captures a fully consistent
5067                  * state of this file - if the snapshot captures this expanding
5068                  * truncation, it must capture all writes that happened before
5069                  * this truncation.
5070                  */
5071                 btrfs_wait_for_snapshot_creation(root);
5072                 ret = btrfs_cont_expand(inode, oldsize, newsize);
5073                 if (ret) {
5074                         btrfs_end_write_no_snapshotting(root);
5075                         return ret;
5076                 }
5077 
5078                 trans = btrfs_start_transaction(root, 1);
5079                 if (IS_ERR(trans)) {
5080                         btrfs_end_write_no_snapshotting(root);
5081                         return PTR_ERR(trans);
5082                 }
5083 
5084                 i_size_write(inode, newsize);
5085                 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5086                 pagecache_isize_extended(inode, oldsize, newsize);
5087                 ret = btrfs_update_inode(trans, root, inode);
5088                 btrfs_end_write_no_snapshotting(root);
5089                 btrfs_end_transaction(trans);
5090         } else {
5091 
5092                 /*
5093                  * We're truncating a file that used to have good data down to
5094                  * zero. Make sure it gets into the ordered flush list so that
5095                  * any new writes get down to disk quickly.
5096                  */
5097                 if (newsize == 0)
5098                         set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5099                                 &BTRFS_I(inode)->runtime_flags);
5100 
5101                 /*
5102                  * 1 for the orphan item we're going to add
5103                  * 1 for the orphan item deletion.
5104                  */
5105                 trans = btrfs_start_transaction(root, 2);
5106                 if (IS_ERR(trans))
5107                         return PTR_ERR(trans);
5108 
5109                 /*
5110                  * We need to do this in case we fail at _any_ point during the
5111                  * actual truncate.  Once we do the truncate_setsize we could
5112                  * invalidate pages which forces any outstanding ordered io to
5113                  * be instantly completed which will give us extents that need
5114                  * to be truncated.  If we fail to get an orphan inode down we
5115                  * could have left over extents that were never meant to live,
5116                  * so we need to guarantee from this point on that everything
5117                  * will be consistent.
5118                  */
5119                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5120                 btrfs_end_transaction(trans);
5121                 if (ret)
5122                         return ret;
5123 
5124                 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5125                 truncate_setsize(inode, newsize);
5126 
5127                 /* Disable nonlocked read DIO to avoid the end less truncate */
5128                 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5129                 inode_dio_wait(inode);
5130                 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5131 
5132                 ret = btrfs_truncate(inode, newsize == oldsize);
5133                 if (ret && inode->i_nlink) {
5134                         int err;
5135 
5136                         /* To get a stable disk_i_size */
5137                         err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5138                         if (err) {
5139                                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5140                                 return err;
5141                         }
5142 
5143                         /*
5144                          * failed to truncate, disk_i_size is only adjusted down
5145                          * as we remove extents, so it should represent the true
5146                          * size of the inode, so reset the in memory size and
5147                          * delete our orphan entry.
5148                          */
5149                         trans = btrfs_join_transaction(root);
5150                         if (IS_ERR(trans)) {
5151                                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5152                                 return ret;
5153                         }
5154                         i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5155                         err = btrfs_orphan_del(trans, BTRFS_I(inode));
5156                         if (err)
5157                                 btrfs_abort_transaction(trans, err);
5158                         btrfs_end_transaction(trans);
5159                 }
5160         }
5161 
5162         return ret;
5163 }
5164 
5165 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5166 {
5167         struct inode *inode = d_inode(dentry);
5168         struct btrfs_root *root = BTRFS_I(inode)->root;
5169         int err;
5170 
5171         if (btrfs_root_readonly(root))
5172                 return -EROFS;
5173 
5174         err = setattr_prepare(dentry, attr);
5175         if (err)
5176                 return err;
5177 
5178         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5179                 err = btrfs_setsize(inode, attr);
5180                 if (err)
5181                         return err;
5182         }
5183 
5184         if (attr->ia_valid) {
5185                 setattr_copy(inode, attr);
5186                 inode_inc_iversion(inode);
5187                 err = btrfs_dirty_inode(inode);
5188 
5189                 if (!err && attr->ia_valid & ATTR_MODE)
5190                         err = posix_acl_chmod(inode, inode->i_mode);
5191         }
5192 
5193         return err;
5194 }
5195 
5196 /*
5197  * While truncating the inode pages during eviction, we get the VFS calling
5198  * btrfs_invalidatepage() against each page of the inode. This is slow because
5199  * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5200  * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5201  * extent_state structures over and over, wasting lots of time.
5202  *
5203  * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5204  * those expensive operations on a per page basis and do only the ordered io
5205  * finishing, while we release here the extent_map and extent_state structures,
5206  * without the excessive merging and splitting.
5207  */
5208 static void evict_inode_truncate_pages(struct inode *inode)
5209 {
5210         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5211         struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5212         struct rb_node *node;
5213 
5214         ASSERT(inode->i_state & I_FREEING);
5215         truncate_inode_pages_final(&inode->i_data);
5216 
5217         write_lock(&map_tree->lock);
5218         while (!RB_EMPTY_ROOT(&map_tree->map)) {
5219                 struct extent_map *em;
5220 
5221                 node = rb_first(&map_tree->map);
5222                 em = rb_entry(node, struct extent_map, rb_node);
5223                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5224                 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5225                 remove_extent_mapping(map_tree, em);
5226                 free_extent_map(em);
5227                 if (need_resched()) {
5228                         write_unlock(&map_tree->lock);
5229                         cond_resched();
5230                         write_lock(&map_tree->lock);
5231                 }
5232         }
5233         write_unlock(&map_tree->lock);
5234 
5235         /*
5236          * Keep looping until we have no more ranges in the io tree.
5237          * We can have ongoing bios started by readpages (called from readahead)
5238          * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5239          * still in progress (unlocked the pages in the bio but did not yet
5240          * unlocked the ranges in the io tree). Therefore this means some
5241          * ranges can still be locked and eviction started because before
5242          * submitting those bios, which are executed by a separate task (work
5243          * queue kthread), inode references (inode->i_count) were not taken
5244          * (which would be dropped in the end io callback of each bio).
5245          * Therefore here we effectively end up waiting for those bios and
5246          * anyone else holding locked ranges without having bumped the inode's
5247          * reference count - if we don't do it, when they access the inode's
5248          * io_tree to unlock a range it may be too late, leading to an
5249          * use-after-free issue.
5250          */
5251         spin_lock(&io_tree->lock);
5252         while (!RB_EMPTY_ROOT(&io_tree->state)) {
5253                 struct extent_state *state;
5254                 struct extent_state *cached_state = NULL;
5255                 u64 start;
5256                 u64 end;
5257 
5258                 node = rb_first(&io_tree->state);
5259                 state = rb_entry(node, struct extent_state, rb_node);
5260                 start = state->start;
5261                 end = state->end;
5262                 spin_unlock(&io_tree->lock);
5263 
5264                 lock_extent_bits(io_tree, start, end, &cached_state);
5265 
5266                 /*
5267                  * If still has DELALLOC flag, the extent didn't reach disk,
5268                  * and its reserved space won't be freed by delayed_ref.
5269                  * So we need to free its reserved space here.
5270                  * (Refer to comment in btrfs_invalidatepage, case 2)
5271                  *
5272                  * Note, end is the bytenr of last byte, so we need + 1 here.
5273                  */
5274                 if (state->state & EXTENT_DELALLOC)
5275                         btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5276 
5277                 clear_extent_bit(io_tree, start, end,
5278                                  EXTENT_LOCKED | EXTENT_DIRTY |
5279                                  EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5280                                  EXTENT_DEFRAG, 1, 1, &cached_state);
5281 
5282                 cond_resched();
5283