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

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

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