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