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

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

Version: ~ [ linux-5.3-rc4 ] ~ [ linux-5.2.8 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.66 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.138 ] ~ [ 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.71 ] ~ [ 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                                 goto error;
1287                         if (ret > 0)
1288                                 break;
1289                         leaf = path->nodes[0];
1290                 }
1291 
1292                 nocow = 0;
1293                 disk_bytenr = 0;
1294                 num_bytes = 0;
1295                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1296 
1297                 if (found_key.objectid > ino)
1298                         break;
1299                 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1300                     found_key.type < BTRFS_EXTENT_DATA_KEY) {
1301                         path->slots[0]++;
1302                         goto next_slot;
1303                 }
1304                 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1305                     found_key.offset > end)
1306                         break;
1307 
1308                 if (found_key.offset > cur_offset) {
1309                         extent_end = found_key.offset;
1310                         extent_type = 0;
1311                         goto out_check;
1312                 }
1313 
1314                 fi = btrfs_item_ptr(leaf, path->slots[0],
1315                                     struct btrfs_file_extent_item);
1316                 extent_type = btrfs_file_extent_type(leaf, fi);
1317 
1318                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1319                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1320                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1321                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1322                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1323                         extent_end = found_key.offset +
1324                                 btrfs_file_extent_num_bytes(leaf, fi);
1325                         disk_num_bytes =
1326                                 btrfs_file_extent_disk_num_bytes(leaf, fi);
1327                         if (extent_end <= start) {
1328                                 path->slots[0]++;
1329                                 goto next_slot;
1330                         }
1331                         if (disk_bytenr == 0)
1332                                 goto out_check;
1333                         if (btrfs_file_extent_compression(leaf, fi) ||
1334                             btrfs_file_extent_encryption(leaf, fi) ||
1335                             btrfs_file_extent_other_encoding(leaf, fi))
1336                                 goto out_check;
1337                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1338                                 goto out_check;
1339                         if (btrfs_extent_readonly(root, disk_bytenr))
1340                                 goto out_check;
1341                         if (btrfs_cross_ref_exist(trans, root, ino,
1342                                                   found_key.offset -
1343                                                   extent_offset, disk_bytenr))
1344                                 goto out_check;
1345                         disk_bytenr += extent_offset;
1346                         disk_bytenr += cur_offset - found_key.offset;
1347                         num_bytes = min(end + 1, extent_end) - cur_offset;
1348                         /*
1349                          * if there are pending snapshots for this root,
1350                          * we fall into common COW way.
1351                          */
1352                         if (!nolock) {
1353                                 err = btrfs_start_write_no_snapshoting(root);
1354                                 if (!err)
1355                                         goto out_check;
1356                         }
1357                         /*
1358                          * force cow if csum exists in the range.
1359                          * this ensure that csum for a given extent are
1360                          * either valid or do not exist.
1361                          */
1362                         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1363                                 goto out_check;
1364                         nocow = 1;
1365                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1366                         extent_end = found_key.offset +
1367                                 btrfs_file_extent_inline_len(leaf,
1368                                                      path->slots[0], fi);
1369                         extent_end = ALIGN(extent_end, root->sectorsize);
1370                 } else {
1371                         BUG_ON(1);
1372                 }
1373 out_check:
1374                 if (extent_end <= start) {
1375                         path->slots[0]++;
1376                         if (!nolock && nocow)
1377                                 btrfs_end_write_no_snapshoting(root);
1378                         goto next_slot;
1379                 }
1380                 if (!nocow) {
1381                         if (cow_start == (u64)-1)
1382                                 cow_start = cur_offset;
1383                         cur_offset = extent_end;
1384                         if (cur_offset > end)
1385                                 break;
1386                         path->slots[0]++;
1387                         goto next_slot;
1388                 }
1389 
1390                 btrfs_release_path(path);
1391                 if (cow_start != (u64)-1) {
1392                         ret = cow_file_range(inode, locked_page,
1393                                              cow_start, found_key.offset - 1,
1394                                              page_started, nr_written, 1);
1395                         if (ret) {
1396                                 if (!nolock && nocow)
1397                                         btrfs_end_write_no_snapshoting(root);
1398                                 goto error;
1399                         }
1400                         cow_start = (u64)-1;
1401                 }
1402 
1403                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1404                         struct extent_map *em;
1405                         struct extent_map_tree *em_tree;
1406                         em_tree = &BTRFS_I(inode)->extent_tree;
1407                         em = alloc_extent_map();
1408                         BUG_ON(!em); /* -ENOMEM */
1409                         em->start = cur_offset;
1410                         em->orig_start = found_key.offset - extent_offset;
1411                         em->len = num_bytes;
1412                         em->block_len = num_bytes;
1413                         em->block_start = disk_bytenr;
1414                         em->orig_block_len = disk_num_bytes;
1415                         em->ram_bytes = ram_bytes;
1416                         em->bdev = root->fs_info->fs_devices->latest_bdev;
1417                         em->mod_start = em->start;
1418                         em->mod_len = em->len;
1419                         set_bit(EXTENT_FLAG_PINNED, &em->flags);
1420                         set_bit(EXTENT_FLAG_FILLING, &em->flags);
1421                         em->generation = -1;
1422                         while (1) {
1423                                 write_lock(&em_tree->lock);
1424                                 ret = add_extent_mapping(em_tree, em, 1);
1425                                 write_unlock(&em_tree->lock);
1426                                 if (ret != -EEXIST) {
1427                                         free_extent_map(em);
1428                                         break;
1429                                 }
1430                                 btrfs_drop_extent_cache(inode, em->start,
1431                                                 em->start + em->len - 1, 0);
1432                         }
1433                         type = BTRFS_ORDERED_PREALLOC;
1434                 } else {
1435                         type = BTRFS_ORDERED_NOCOW;
1436                 }
1437 
1438                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1439                                                num_bytes, num_bytes, type);
1440                 BUG_ON(ret); /* -ENOMEM */
1441 
1442                 if (root->root_key.objectid ==
1443                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1444                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1445                                                       num_bytes);
1446                         if (ret) {
1447                                 if (!nolock && nocow)
1448                                         btrfs_end_write_no_snapshoting(root);
1449                                 goto error;
1450                         }
1451                 }
1452 
1453                 extent_clear_unlock_delalloc(inode, cur_offset,
1454                                              cur_offset + num_bytes - 1,
1455                                              locked_page, EXTENT_LOCKED |
1456                                              EXTENT_DELALLOC, PAGE_UNLOCK |
1457                                              PAGE_SET_PRIVATE2);
1458                 if (!nolock && nocow)
1459                         btrfs_end_write_no_snapshoting(root);
1460                 cur_offset = extent_end;
1461                 if (cur_offset > end)
1462                         break;
1463         }
1464         btrfs_release_path(path);
1465 
1466         if (cur_offset <= end && cow_start == (u64)-1) {
1467                 cow_start = cur_offset;
1468                 cur_offset = end;
1469         }
1470 
1471         if (cow_start != (u64)-1) {
1472                 ret = cow_file_range(inode, locked_page, cow_start, end,
1473                                      page_started, nr_written, 1);
1474                 if (ret)
1475                         goto error;
1476         }
1477 
1478 error:
1479         err = btrfs_end_transaction(trans, root);
1480         if (!ret)
1481                 ret = err;
1482 
1483         if (ret && cur_offset < end)
1484                 extent_clear_unlock_delalloc(inode, cur_offset, end,
1485                                              locked_page, EXTENT_LOCKED |
1486                                              EXTENT_DELALLOC | EXTENT_DEFRAG |
1487                                              EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1488                                              PAGE_CLEAR_DIRTY |
1489                                              PAGE_SET_WRITEBACK |
1490                                              PAGE_END_WRITEBACK);
1491         btrfs_free_path(path);
1492         return ret;
1493 }
1494 
1495 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1496 {
1497 
1498         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1499             !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1500                 return 0;
1501 
1502         /*
1503          * @defrag_bytes is a hint value, no spinlock held here,
1504          * if is not zero, it means the file is defragging.
1505          * Force cow if given extent needs to be defragged.
1506          */
1507         if (BTRFS_I(inode)->defrag_bytes &&
1508             test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1509                            EXTENT_DEFRAG, 0, NULL))
1510                 return 1;
1511 
1512         return 0;
1513 }
1514 
1515 /*
1516  * extent_io.c call back to do delayed allocation processing
1517  */
1518 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1519                               u64 start, u64 end, int *page_started,
1520                               unsigned long *nr_written)
1521 {
1522         int ret;
1523         int force_cow = need_force_cow(inode, start, end);
1524 
1525         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1526                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1527                                          page_started, 1, nr_written);
1528         } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1529                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1530                                          page_started, 0, nr_written);
1531         } else if (!inode_need_compress(inode)) {
1532                 ret = cow_file_range(inode, locked_page, start, end,
1533                                       page_started, nr_written, 1);
1534         } else {
1535                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1536                         &BTRFS_I(inode)->runtime_flags);
1537                 ret = cow_file_range_async(inode, locked_page, start, end,
1538                                            page_started, nr_written);
1539         }
1540         return ret;
1541 }
1542 
1543 static void btrfs_split_extent_hook(struct inode *inode,
1544                                     struct extent_state *orig, u64 split)
1545 {
1546         u64 size;
1547 
1548         /* not delalloc, ignore it */
1549         if (!(orig->state & EXTENT_DELALLOC))
1550                 return;
1551 
1552         size = orig->end - orig->start + 1;
1553         if (size > BTRFS_MAX_EXTENT_SIZE) {
1554                 u64 num_extents;
1555                 u64 new_size;
1556 
1557                 /*
1558                  * See the explanation in btrfs_merge_extent_hook, the same
1559                  * applies here, just in reverse.
1560                  */
1561                 new_size = orig->end - split + 1;
1562                 num_extents = div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1563                                         BTRFS_MAX_EXTENT_SIZE);
1564                 new_size = split - orig->start;
1565                 num_extents += div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1566                                         BTRFS_MAX_EXTENT_SIZE);
1567                 if (div64_u64(size + BTRFS_MAX_EXTENT_SIZE - 1,
1568                               BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1569                         return;
1570         }
1571 
1572         spin_lock(&BTRFS_I(inode)->lock);
1573         BTRFS_I(inode)->outstanding_extents++;
1574         spin_unlock(&BTRFS_I(inode)->lock);
1575 }
1576 
1577 /*
1578  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1579  * extents so we can keep track of new extents that are just merged onto old
1580  * extents, such as when we are doing sequential writes, so we can properly
1581  * account for the metadata space we'll need.
1582  */
1583 static void btrfs_merge_extent_hook(struct inode *inode,
1584                                     struct extent_state *new,
1585                                     struct extent_state *other)
1586 {
1587         u64 new_size, old_size;
1588         u64 num_extents;
1589 
1590         /* not delalloc, ignore it */
1591         if (!(other->state & EXTENT_DELALLOC))
1592                 return;
1593 
1594         if (new->start > other->start)
1595                 new_size = new->end - other->start + 1;
1596         else
1597                 new_size = other->end - new->start + 1;
1598 
1599         /* we're not bigger than the max, unreserve the space and go */
1600         if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1601                 spin_lock(&BTRFS_I(inode)->lock);
1602                 BTRFS_I(inode)->outstanding_extents--;
1603                 spin_unlock(&BTRFS_I(inode)->lock);
1604                 return;
1605         }
1606 
1607         /*
1608          * We have to add up either side to figure out how many extents were
1609          * accounted for before we merged into one big extent.  If the number of
1610          * extents we accounted for is <= the amount we need for the new range
1611          * then we can return, otherwise drop.  Think of it like this
1612          *
1613          * [ 4k][MAX_SIZE]
1614          *
1615          * So we've grown the extent by a MAX_SIZE extent, this would mean we
1616          * need 2 outstanding extents, on one side we have 1 and the other side
1617          * we have 1 so they are == and we can return.  But in this case
1618          *
1619          * [MAX_SIZE+4k][MAX_SIZE+4k]
1620          *
1621          * Each range on their own accounts for 2 extents, but merged together
1622          * they are only 3 extents worth of accounting, so we need to drop in
1623          * this case.
1624          */
1625         old_size = other->end - other->start + 1;
1626         num_extents = div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1627                                 BTRFS_MAX_EXTENT_SIZE);
1628         old_size = new->end - new->start + 1;
1629         num_extents += div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1630                                  BTRFS_MAX_EXTENT_SIZE);
1631 
1632         if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1633                       BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1634                 return;
1635 
1636         spin_lock(&BTRFS_I(inode)->lock);
1637         BTRFS_I(inode)->outstanding_extents--;
1638         spin_unlock(&BTRFS_I(inode)->lock);
1639 }
1640 
1641 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1642                                       struct inode *inode)
1643 {
1644         spin_lock(&root->delalloc_lock);
1645         if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1646                 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1647                               &root->delalloc_inodes);
1648                 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1649                         &BTRFS_I(inode)->runtime_flags);
1650                 root->nr_delalloc_inodes++;
1651                 if (root->nr_delalloc_inodes == 1) {
1652                         spin_lock(&root->fs_info->delalloc_root_lock);
1653                         BUG_ON(!list_empty(&root->delalloc_root));
1654                         list_add_tail(&root->delalloc_root,
1655                                       &root->fs_info->delalloc_roots);
1656                         spin_unlock(&root->fs_info->delalloc_root_lock);
1657                 }
1658         }
1659         spin_unlock(&root->delalloc_lock);
1660 }
1661 
1662 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1663                                      struct inode *inode)
1664 {
1665         spin_lock(&root->delalloc_lock);
1666         if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1667                 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1668                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1669                           &BTRFS_I(inode)->runtime_flags);
1670                 root->nr_delalloc_inodes--;
1671                 if (!root->nr_delalloc_inodes) {
1672                         spin_lock(&root->fs_info->delalloc_root_lock);
1673                         BUG_ON(list_empty(&root->delalloc_root));
1674                         list_del_init(&root->delalloc_root);
1675                         spin_unlock(&root->fs_info->delalloc_root_lock);
1676                 }
1677         }
1678         spin_unlock(&root->delalloc_lock);
1679 }
1680 
1681 /*
1682  * extent_io.c set_bit_hook, used to track delayed allocation
1683  * bytes in this file, and to maintain the list of inodes that
1684  * have pending delalloc work to be done.
1685  */
1686 static void btrfs_set_bit_hook(struct inode *inode,
1687                                struct extent_state *state, unsigned *bits)
1688 {
1689 
1690         if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1691                 WARN_ON(1);
1692         /*
1693          * set_bit and clear bit hooks normally require _irqsave/restore
1694          * but in this case, we are only testing for the DELALLOC
1695          * bit, which is only set or cleared with irqs on
1696          */
1697         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1698                 struct btrfs_root *root = BTRFS_I(inode)->root;
1699                 u64 len = state->end + 1 - state->start;
1700                 bool do_list = !btrfs_is_free_space_inode(inode);
1701 
1702                 if (*bits & EXTENT_FIRST_DELALLOC) {
1703                         *bits &= ~EXTENT_FIRST_DELALLOC;
1704                 } else {
1705                         spin_lock(&BTRFS_I(inode)->lock);
1706                         BTRFS_I(inode)->outstanding_extents++;
1707                         spin_unlock(&BTRFS_I(inode)->lock);
1708                 }
1709 
1710                 /* For sanity tests */
1711                 if (btrfs_test_is_dummy_root(root))
1712                         return;
1713 
1714                 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1715                                      root->fs_info->delalloc_batch);
1716                 spin_lock(&BTRFS_I(inode)->lock);
1717                 BTRFS_I(inode)->delalloc_bytes += len;
1718                 if (*bits & EXTENT_DEFRAG)
1719                         BTRFS_I(inode)->defrag_bytes += len;
1720                 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1721                                          &BTRFS_I(inode)->runtime_flags))
1722                         btrfs_add_delalloc_inodes(root, inode);
1723                 spin_unlock(&BTRFS_I(inode)->lock);
1724         }
1725 }
1726 
1727 /*
1728  * extent_io.c clear_bit_hook, see set_bit_hook for why
1729  */
1730 static void btrfs_clear_bit_hook(struct inode *inode,
1731                                  struct extent_state *state,
1732                                  unsigned *bits)
1733 {
1734         u64 len = state->end + 1 - state->start;
1735         u64 num_extents = div64_u64(len + BTRFS_MAX_EXTENT_SIZE -1,
1736                                     BTRFS_MAX_EXTENT_SIZE);
1737 
1738         spin_lock(&BTRFS_I(inode)->lock);
1739         if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1740                 BTRFS_I(inode)->defrag_bytes -= len;
1741         spin_unlock(&BTRFS_I(inode)->lock);
1742 
1743         /*
1744          * set_bit and clear bit hooks normally require _irqsave/restore
1745          * but in this case, we are only testing for the DELALLOC
1746          * bit, which is only set or cleared with irqs on
1747          */
1748         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1749                 struct btrfs_root *root = BTRFS_I(inode)->root;
1750                 bool do_list = !btrfs_is_free_space_inode(inode);
1751 
1752                 if (*bits & EXTENT_FIRST_DELALLOC) {
1753                         *bits &= ~EXTENT_FIRST_DELALLOC;
1754                 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1755                         spin_lock(&BTRFS_I(inode)->lock);
1756                         BTRFS_I(inode)->outstanding_extents -= num_extents;
1757                         spin_unlock(&BTRFS_I(inode)->lock);
1758                 }
1759 
1760                 /*
1761                  * We don't reserve metadata space for space cache inodes so we
1762                  * don't need to call dellalloc_release_metadata if there is an
1763                  * error.
1764                  */
1765                 if (*bits & EXTENT_DO_ACCOUNTING &&
1766                     root != root->fs_info->tree_root)
1767                         btrfs_delalloc_release_metadata(inode, len);
1768 
1769                 /* For sanity tests. */
1770                 if (btrfs_test_is_dummy_root(root))
1771                         return;
1772 
1773                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1774                     && do_list && !(state->state & EXTENT_NORESERVE))
1775                         btrfs_free_reserved_data_space(inode, len);
1776 
1777                 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1778                                      root->fs_info->delalloc_batch);
1779                 spin_lock(&BTRFS_I(inode)->lock);
1780                 BTRFS_I(inode)->delalloc_bytes -= len;
1781                 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1782                     test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1783                              &BTRFS_I(inode)->runtime_flags))
1784                         btrfs_del_delalloc_inode(root, inode);
1785                 spin_unlock(&BTRFS_I(inode)->lock);
1786         }
1787 }
1788 
1789 /*
1790  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1791  * we don't create bios that span stripes or chunks
1792  */
1793 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1794                          size_t size, struct bio *bio,
1795                          unsigned long bio_flags)
1796 {
1797         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1798         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1799         u64 length = 0;
1800         u64 map_length;
1801         int ret;
1802 
1803         if (bio_flags & EXTENT_BIO_COMPRESSED)
1804                 return 0;
1805 
1806         length = bio->bi_iter.bi_size;
1807         map_length = length;
1808         ret = btrfs_map_block(root->fs_info, rw, logical,
1809                               &map_length, NULL, 0);
1810         /* Will always return 0 with map_multi == NULL */
1811         BUG_ON(ret < 0);
1812         if (map_length < length + size)
1813                 return 1;
1814         return 0;
1815 }
1816 
1817 /*
1818  * in order to insert checksums into the metadata in large chunks,
1819  * we wait until bio submission time.   All the pages in the bio are
1820  * checksummed and sums are attached onto the ordered extent record.
1821  *
1822  * At IO completion time the cums attached on the ordered extent record
1823  * are inserted into the btree
1824  */
1825 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1826                                     struct bio *bio, int mirror_num,
1827                                     unsigned long bio_flags,
1828                                     u64 bio_offset)
1829 {
1830         struct btrfs_root *root = BTRFS_I(inode)->root;
1831         int ret = 0;
1832 
1833         ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1834         BUG_ON(ret); /* -ENOMEM */
1835         return 0;
1836 }
1837 
1838 /*
1839  * in order to insert checksums into the metadata in large chunks,
1840  * we wait until bio submission time.   All the pages in the bio are
1841  * checksummed and sums are attached onto the ordered extent record.
1842  *
1843  * At IO completion time the cums attached on the ordered extent record
1844  * are inserted into the btree
1845  */
1846 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1847                           int mirror_num, unsigned long bio_flags,
1848                           u64 bio_offset)
1849 {
1850         struct btrfs_root *root = BTRFS_I(inode)->root;
1851         int ret;
1852 
1853         ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1854         if (ret)
1855                 bio_endio(bio, ret);
1856         return ret;
1857 }
1858 
1859 /*
1860  * extent_io.c submission hook. This does the right thing for csum calculation
1861  * on write, or reading the csums from the tree before a read
1862  */
1863 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1864                           int mirror_num, unsigned long bio_flags,
1865                           u64 bio_offset)
1866 {
1867         struct btrfs_root *root = BTRFS_I(inode)->root;
1868         int ret = 0;
1869         int skip_sum;
1870         int metadata = 0;
1871         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1872 
1873         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1874 
1875         if (btrfs_is_free_space_inode(inode))
1876                 metadata = 2;
1877 
1878         if (!(rw & REQ_WRITE)) {
1879                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1880                 if (ret)
1881                         goto out;
1882 
1883                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1884                         ret = btrfs_submit_compressed_read(inode, bio,
1885                                                            mirror_num,
1886                                                            bio_flags);
1887                         goto out;
1888                 } else if (!skip_sum) {
1889                         ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1890                         if (ret)
1891                                 goto out;
1892                 }
1893                 goto mapit;
1894         } else if (async && !skip_sum) {
1895                 /* csum items have already been cloned */
1896                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1897                         goto mapit;
1898                 /* we're doing a write, do the async checksumming */
1899                 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1900                                    inode, rw, bio, mirror_num,
1901                                    bio_flags, bio_offset,
1902                                    __btrfs_submit_bio_start,
1903                                    __btrfs_submit_bio_done);
1904                 goto out;
1905         } else if (!skip_sum) {
1906                 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1907                 if (ret)
1908                         goto out;
1909         }
1910 
1911 mapit:
1912         ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1913 
1914 out:
1915         if (ret < 0)
1916                 bio_endio(bio, ret);
1917         return ret;
1918 }
1919 
1920 /*
1921  * given a list of ordered sums record them in the inode.  This happens
1922  * at IO completion time based on sums calculated at bio submission time.
1923  */
1924 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1925                              struct inode *inode, u64 file_offset,
1926                              struct list_head *list)
1927 {
1928         struct btrfs_ordered_sum *sum;
1929 
1930         list_for_each_entry(sum, list, list) {
1931                 trans->adding_csums = 1;
1932                 btrfs_csum_file_blocks(trans,
1933                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
1934                 trans->adding_csums = 0;
1935         }
1936         return 0;
1937 }
1938 
1939 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1940                               struct extent_state **cached_state)
1941 {
1942         WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1943         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1944                                    cached_state, GFP_NOFS);
1945 }
1946 
1947 /* see btrfs_writepage_start_hook for details on why this is required */
1948 struct btrfs_writepage_fixup {
1949         struct page *page;
1950         struct btrfs_work work;
1951 };
1952 
1953 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1954 {
1955         struct btrfs_writepage_fixup *fixup;
1956         struct btrfs_ordered_extent *ordered;
1957         struct extent_state *cached_state = NULL;
1958         struct page *page;
1959         struct inode *inode;
1960         u64 page_start;
1961         u64 page_end;
1962         int ret;
1963 
1964         fixup = container_of(work, struct btrfs_writepage_fixup, work);
1965         page = fixup->page;
1966 again:
1967         lock_page(page);
1968         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1969                 ClearPageChecked(page);
1970                 goto out_page;
1971         }
1972 
1973         inode = page->mapping->host;
1974         page_start = page_offset(page);
1975         page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1976 
1977         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1978                          &cached_state);
1979 
1980         /* already ordered? We're done */
1981         if (PagePrivate2(page))
1982                 goto out;
1983 
1984         ordered = btrfs_lookup_ordered_extent(inode, page_start);
1985         if (ordered) {
1986                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1987                                      page_end, &cached_state, GFP_NOFS);
1988                 unlock_page(page);
1989                 btrfs_start_ordered_extent(inode, ordered, 1);
1990                 btrfs_put_ordered_extent(ordered);
1991                 goto again;
1992         }
1993 
1994         ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1995         if (ret) {
1996                 mapping_set_error(page->mapping, ret);
1997                 end_extent_writepage(page, ret, page_start, page_end);
1998                 ClearPageChecked(page);
1999                 goto out;
2000          }
2001 
2002         btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
2003         ClearPageChecked(page);
2004         set_page_dirty(page);
2005 out:
2006         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2007                              &cached_state, GFP_NOFS);
2008 out_page:
2009         unlock_page(page);
2010         page_cache_release(page);
2011         kfree(fixup);
2012 }
2013 
2014 /*
2015  * There are a few paths in the higher layers of the kernel that directly
2016  * set the page dirty bit without asking the filesystem if it is a
2017  * good idea.  This causes problems because we want to make sure COW
2018  * properly happens and the data=ordered rules are followed.
2019  *
2020  * In our case any range that doesn't have the ORDERED bit set
2021  * hasn't been properly setup for IO.  We kick off an async process
2022  * to fix it up.  The async helper will wait for ordered extents, set
2023  * the delalloc bit and make it safe to write the page.
2024  */
2025 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2026 {
2027         struct inode *inode = page->mapping->host;
2028         struct btrfs_writepage_fixup *fixup;
2029         struct btrfs_root *root = BTRFS_I(inode)->root;
2030 
2031         /* this page is properly in the ordered list */
2032         if (TestClearPagePrivate2(page))
2033                 return 0;
2034 
2035         if (PageChecked(page))
2036                 return -EAGAIN;
2037 
2038         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2039         if (!fixup)
2040                 return -EAGAIN;
2041 
2042         SetPageChecked(page);
2043         page_cache_get(page);
2044         btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2045                         btrfs_writepage_fixup_worker, NULL, NULL);
2046         fixup->page = page;
2047         btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
2048         return -EBUSY;
2049 }
2050 
2051 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2052                                        struct inode *inode, u64 file_pos,
2053                                        u64 disk_bytenr, u64 disk_num_bytes,
2054                                        u64 num_bytes, u64 ram_bytes,
2055                                        u8 compression, u8 encryption,
2056                                        u16 other_encoding, int extent_type)
2057 {
2058         struct btrfs_root *root = BTRFS_I(inode)->root;
2059         struct btrfs_file_extent_item *fi;
2060         struct btrfs_path *path;
2061         struct extent_buffer *leaf;
2062         struct btrfs_key ins;
2063         int extent_inserted = 0;
2064         int ret;
2065 
2066         path = btrfs_alloc_path();
2067         if (!path)
2068                 return -ENOMEM;
2069 
2070         /*
2071          * we may be replacing one extent in the tree with another.
2072          * The new extent is pinned in the extent map, and we don't want
2073          * to drop it from the cache until it is completely in the btree.
2074          *
2075          * So, tell btrfs_drop_extents to leave this extent in the cache.
2076          * the caller is expected to unpin it and allow it to be merged
2077          * with the others.
2078          */
2079         ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2080                                    file_pos + num_bytes, NULL, 0,
2081                                    1, sizeof(*fi), &extent_inserted);
2082         if (ret)
2083                 goto out;
2084 
2085         if (!extent_inserted) {
2086                 ins.objectid = btrfs_ino(inode);
2087                 ins.offset = file_pos;
2088                 ins.type = BTRFS_EXTENT_DATA_KEY;
2089 
2090                 path->leave_spinning = 1;
2091                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2092                                               sizeof(*fi));
2093                 if (ret)
2094                         goto out;
2095         }
2096         leaf = path->nodes[0];
2097         fi = btrfs_item_ptr(leaf, path->slots[0],
2098                             struct btrfs_file_extent_item);
2099         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2100         btrfs_set_file_extent_type(leaf, fi, extent_type);
2101         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2102         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2103         btrfs_set_file_extent_offset(leaf, fi, 0);
2104         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2105         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2106         btrfs_set_file_extent_compression(leaf, fi, compression);
2107         btrfs_set_file_extent_encryption(leaf, fi, encryption);
2108         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2109 
2110         btrfs_mark_buffer_dirty(leaf);
2111         btrfs_release_path(path);
2112 
2113         inode_add_bytes(inode, num_bytes);
2114 
2115         ins.objectid = disk_bytenr;
2116         ins.offset = disk_num_bytes;
2117         ins.type = BTRFS_EXTENT_ITEM_KEY;
2118         ret = btrfs_alloc_reserved_file_extent(trans, root,
2119                                         root->root_key.objectid,
2120                                         btrfs_ino(inode), file_pos, &ins);
2121 out:
2122         btrfs_free_path(path);
2123 
2124         return ret;
2125 }
2126 
2127 /* snapshot-aware defrag */
2128 struct sa_defrag_extent_backref {
2129         struct rb_node node;
2130         struct old_sa_defrag_extent *old;
2131         u64 root_id;
2132         u64 inum;
2133         u64 file_pos;
2134         u64 extent_offset;
2135         u64 num_bytes;
2136         u64 generation;
2137 };
2138 
2139 struct old_sa_defrag_extent {
2140         struct list_head list;
2141         struct new_sa_defrag_extent *new;
2142 
2143         u64 extent_offset;
2144         u64 bytenr;
2145         u64 offset;
2146         u64 len;
2147         int count;
2148 };
2149 
2150 struct new_sa_defrag_extent {
2151         struct rb_root root;
2152         struct list_head head;
2153         struct btrfs_path *path;
2154         struct inode *inode;
2155         u64 file_pos;
2156         u64 len;
2157         u64 bytenr;
2158         u64 disk_len;
2159         u8 compress_type;
2160 };
2161 
2162 static int backref_comp(struct sa_defrag_extent_backref *b1,
2163                         struct sa_defrag_extent_backref *b2)
2164 {
2165         if (b1->root_id < b2->root_id)
2166                 return -1;
2167         else if (b1->root_id > b2->root_id)
2168                 return 1;
2169 
2170         if (b1->inum < b2->inum)
2171                 return -1;
2172         else if (b1->inum > b2->inum)
2173                 return 1;
2174 
2175         if (b1->file_pos < b2->file_pos)
2176                 return -1;
2177         else if (b1->file_pos > b2->file_pos)
2178                 return 1;
2179 
2180         /*
2181          * [------------------------------] ===> (a range of space)
2182          *     |<--->|   |<---->| =============> (fs/file tree A)
2183          * |<---------------------------->| ===> (fs/file tree B)
2184          *
2185          * A range of space can refer to two file extents in one tree while
2186          * refer to only one file extent in another tree.
2187          *
2188          * So we may process a disk offset more than one time(two extents in A)
2189          * and locate at the same extent(one extent in B), then insert two same
2190          * backrefs(both refer to the extent in B).
2191          */
2192         return 0;
2193 }
2194 
2195 static void backref_insert(struct rb_root *root,
2196                            struct sa_defrag_extent_backref *backref)
2197 {
2198         struct rb_node **p = &root->rb_node;
2199         struct rb_node *parent = NULL;
2200         struct sa_defrag_extent_backref *entry;
2201         int ret;
2202 
2203         while (*p) {
2204                 parent = *p;
2205                 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2206 
2207                 ret = backref_comp(backref, entry);
2208                 if (ret < 0)
2209                         p = &(*p)->rb_left;
2210                 else
2211                         p = &(*p)->rb_right;
2212         }
2213 
2214         rb_link_node(&backref->node, parent, p);
2215         rb_insert_color(&backref->node, root);
2216 }
2217 
2218 /*
2219  * Note the backref might has changed, and in this case we just return 0.
2220  */
2221 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2222                                        void *ctx)
2223 {
2224         struct btrfs_file_extent_item *extent;
2225         struct btrfs_fs_info *fs_info;
2226         struct old_sa_defrag_extent *old = ctx;
2227         struct new_sa_defrag_extent *new = old->new;
2228         struct btrfs_path *path = new->path;
2229         struct btrfs_key key;
2230         struct btrfs_root *root;
2231         struct sa_defrag_extent_backref *backref;
2232         struct extent_buffer *leaf;
2233         struct inode *inode = new->inode;
2234         int slot;
2235         int ret;
2236         u64 extent_offset;
2237         u64 num_bytes;
2238 
2239         if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2240             inum == btrfs_ino(inode))
2241                 return 0;
2242 
2243         key.objectid = root_id;
2244         key.type = BTRFS_ROOT_ITEM_KEY;
2245         key.offset = (u64)-1;
2246 
2247         fs_info = BTRFS_I(inode)->root->fs_info;
2248         root = btrfs_read_fs_root_no_name(fs_info, &key);
2249         if (IS_ERR(root)) {
2250                 if (PTR_ERR(root) == -ENOENT)
2251                         return 0;
2252                 WARN_ON(1);
2253                 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2254                          inum, offset, root_id);
2255                 return PTR_ERR(root);
2256         }
2257 
2258         key.objectid = inum;
2259         key.type = BTRFS_EXTENT_DATA_KEY;
2260         if (offset > (u64)-1 << 32)
2261                 key.offset = 0;
2262         else
2263                 key.offset = offset;
2264 
2265         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2266         if (WARN_ON(ret < 0))
2267                 return ret;
2268         ret = 0;
2269 
2270         while (1) {
2271                 cond_resched();
2272 
2273                 leaf = path->nodes[0];
2274                 slot = path->slots[0];
2275 
2276                 if (slot >= btrfs_header_nritems(leaf)) {
2277                         ret = btrfs_next_leaf(root, path);
2278                         if (ret < 0) {
2279                                 goto out;
2280                         } else if (ret > 0) {
2281                                 ret = 0;
2282                                 goto out;
2283                         }
2284                         continue;
2285                 }
2286 
2287                 path->slots[0]++;
2288 
2289                 btrfs_item_key_to_cpu(leaf, &key, slot);
2290 
2291                 if (key.objectid > inum)
2292                         goto out;
2293 
2294                 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2295                         continue;
2296 
2297                 extent = btrfs_item_ptr(leaf, slot,
2298                                         struct btrfs_file_extent_item);
2299 
2300                 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2301                         continue;
2302 
2303                 /*
2304                  * 'offset' refers to the exact key.offset,
2305                  * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2306                  * (key.offset - extent_offset).
2307                  */
2308                 if (key.offset != offset)
2309                         continue;
2310 
2311                 extent_offset = btrfs_file_extent_offset(leaf, extent);
2312                 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2313 
2314                 if (extent_offset >= old->extent_offset + old->offset +
2315                     old->len || extent_offset + num_bytes <=
2316                     old->extent_offset + old->offset)
2317                         continue;
2318                 break;
2319         }
2320 
2321         backref = kmalloc(sizeof(*backref), GFP_NOFS);
2322         if (!backref) {
2323                 ret = -ENOENT;
2324                 goto out;
2325         }
2326 
2327         backref->root_id = root_id;
2328         backref->inum = inum;
2329         backref->file_pos = offset;
2330         backref->num_bytes = num_bytes;
2331         backref->extent_offset = extent_offset;
2332         backref->generation = btrfs_file_extent_generation(leaf, extent);
2333         backref->old = old;
2334         backref_insert(&new->root, backref);
2335         old->count++;
2336 out:
2337         btrfs_release_path(path);
2338         WARN_ON(ret);
2339         return ret;
2340 }
2341 
2342 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2343                                    struct new_sa_defrag_extent *new)
2344 {
2345         struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2346         struct old_sa_defrag_extent *old, *tmp;
2347         int ret;
2348 
2349         new->path = path;
2350 
2351         list_for_each_entry_safe(old, tmp, &new->head, list) {
2352                 ret = iterate_inodes_from_logical(old->bytenr +
2353                                                   old->extent_offset, fs_info,
2354                                                   path, record_one_backref,
2355                                                   old);
2356                 if (ret < 0 && ret != -ENOENT)
2357                         return false;
2358 
2359                 /* no backref to be processed for this extent */
2360                 if (!old->count) {
2361                         list_del(&old->list);
2362                         kfree(old);
2363                 }
2364         }
2365 
2366         if (list_empty(&new->head))
2367                 return false;
2368 
2369         return true;
2370 }
2371 
2372 static int relink_is_mergable(struct extent_buffer *leaf,
2373                               struct btrfs_file_extent_item *fi,
2374                               struct new_sa_defrag_extent *new)
2375 {
2376         if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2377                 return 0;
2378 
2379         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2380                 return 0;
2381 
2382         if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2383                 return 0;
2384 
2385         if (btrfs_file_extent_encryption(leaf, fi) ||
2386             btrfs_file_extent_other_encoding(leaf, fi))
2387                 return 0;
2388 
2389         return 1;
2390 }
2391 
2392 /*
2393  * Note the backref might has changed, and in this case we just return 0.
2394  */
2395 static noinline int relink_extent_backref(struct btrfs_path *path,
2396                                  struct sa_defrag_extent_backref *prev,
2397                                  struct sa_defrag_extent_backref *backref)
2398 {
2399         struct btrfs_file_extent_item *extent;
2400         struct btrfs_file_extent_item *item;
2401         struct btrfs_ordered_extent *ordered;
2402         struct btrfs_trans_handle *trans;
2403         struct btrfs_fs_info *fs_info;
2404         struct btrfs_root *root;
2405         struct btrfs_key key;
2406         struct extent_buffer *leaf;
2407         struct old_sa_defrag_extent *old = backref->old;
2408         struct new_sa_defrag_extent *new = old->new;
2409         struct inode *src_inode = new->inode;
2410         struct inode *inode;
2411         struct extent_state *cached = NULL;
2412         int ret = 0;
2413         u64 start;
2414         u64 len;
2415         u64 lock_start;
2416         u64 lock_end;
2417         bool merge = false;
2418         int index;
2419 
2420         if (prev && prev->root_id == backref->root_id &&
2421             prev->inum == backref->inum &&
2422             prev->file_pos + prev->num_bytes == backref->file_pos)
2423                 merge = true;
2424 
2425         /* step 1: get root */
2426         key.objectid = backref->root_id;
2427         key.type = BTRFS_ROOT_ITEM_KEY;
2428         key.offset = (u64)-1;
2429 
2430         fs_info = BTRFS_I(src_inode)->root->fs_info;
2431         index = srcu_read_lock(&fs_info->subvol_srcu);
2432 
2433         root = btrfs_read_fs_root_no_name(fs_info, &key);
2434         if (IS_ERR(root)) {
2435                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2436                 if (PTR_ERR(root) == -ENOENT)
2437                         return 0;
2438                 return PTR_ERR(root);
2439         }
2440 
2441         if (btrfs_root_readonly(root)) {
2442                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2443                 return 0;
2444         }
2445 
2446         /* step 2: get inode */
2447         key.objectid = backref->inum;
2448         key.type = BTRFS_INODE_ITEM_KEY;
2449         key.offset = 0;
2450 
2451         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2452         if (IS_ERR(inode)) {
2453                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2454                 return 0;
2455         }
2456 
2457         srcu_read_unlock(&fs_info->subvol_srcu, index);
2458 
2459         /* step 3: relink backref */
2460         lock_start = backref->file_pos;
2461         lock_end = backref->file_pos + backref->num_bytes - 1;
2462         lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2463                          0, &cached);
2464 
2465         ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2466         if (ordered) {
2467                 btrfs_put_ordered_extent(ordered);
2468                 goto out_unlock;
2469         }
2470 
2471         trans = btrfs_join_transaction(root);
2472         if (IS_ERR(trans)) {
2473                 ret = PTR_ERR(trans);
2474                 goto out_unlock;
2475         }
2476 
2477         key.objectid = backref->inum;
2478         key.type = BTRFS_EXTENT_DATA_KEY;
2479         key.offset = backref->file_pos;
2480 
2481         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2482         if (ret < 0) {
2483                 goto out_free_path;
2484         } else if (ret > 0) {
2485                 ret = 0;
2486                 goto out_free_path;
2487         }
2488 
2489         extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2490                                 struct btrfs_file_extent_item);
2491 
2492         if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2493             backref->generation)
2494                 goto out_free_path;
2495 
2496         btrfs_release_path(path);
2497 
2498         start = backref->file_pos;
2499         if (backref->extent_offset < old->extent_offset + old->offset)
2500                 start += old->extent_offset + old->offset -
2501                          backref->extent_offset;
2502 
2503         len = min(backref->extent_offset + backref->num_bytes,
2504                   old->extent_offset + old->offset + old->len);
2505         len -= max(backref->extent_offset, old->extent_offset + old->offset);
2506 
2507         ret = btrfs_drop_extents(trans, root, inode, start,
2508                                  start + len, 1);
2509         if (ret)
2510                 goto out_free_path;
2511 again:
2512         key.objectid = btrfs_ino(inode);
2513         key.type = BTRFS_EXTENT_DATA_KEY;
2514         key.offset = start;
2515 
2516         path->leave_spinning = 1;
2517         if (merge) {
2518                 struct btrfs_file_extent_item *fi;
2519                 u64 extent_len;
2520                 struct btrfs_key found_key;
2521 
2522                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2523                 if (ret < 0)
2524                         goto out_free_path;
2525 
2526                 path->slots[0]--;
2527                 leaf = path->nodes[0];
2528                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2529 
2530                 fi = btrfs_item_ptr(leaf, path->slots[0],
2531                                     struct btrfs_file_extent_item);
2532                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2533 
2534                 if (extent_len + found_key.offset == start &&
2535                     relink_is_mergable(leaf, fi, new)) {
2536                         btrfs_set_file_extent_num_bytes(leaf, fi,
2537                                                         extent_len + len);
2538                         btrfs_mark_buffer_dirty(leaf);
2539                         inode_add_bytes(inode, len);
2540 
2541                         ret = 1;
2542                         goto out_free_path;
2543                 } else {
2544                         merge = false;
2545                         btrfs_release_path(path);
2546                         goto again;
2547                 }
2548         }
2549 
2550         ret = btrfs_insert_empty_item(trans, root, path, &key,
2551                                         sizeof(*extent));
2552         if (ret) {
2553                 btrfs_abort_transaction(trans, root, ret);
2554                 goto out_free_path;
2555         }
2556 
2557         leaf = path->nodes[0];
2558         item = btrfs_item_ptr(leaf, path->slots[0],
2559                                 struct btrfs_file_extent_item);
2560         btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2561         btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2562         btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2563         btrfs_set_file_extent_num_bytes(leaf, item, len);
2564         btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2565         btrfs_set_file_extent_generation(leaf, item, trans->transid);
2566         btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2567         btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2568         btrfs_set_file_extent_encryption(leaf, item, 0);
2569         btrfs_set_file_extent_other_encoding(leaf, item, 0);
2570 
2571         btrfs_mark_buffer_dirty(leaf);
2572         inode_add_bytes(inode, len);
2573         btrfs_release_path(path);
2574 
2575         ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2576                         new->disk_len, 0,
2577                         backref->root_id, backref->inum,
2578                         new->file_pos); /* start - extent_offset */
2579         if (ret) {
2580                 btrfs_abort_transaction(trans, root, ret);
2581                 goto out_free_path;
2582         }
2583 
2584         ret = 1;
2585 out_free_path:
2586         btrfs_release_path(path);
2587         path->leave_spinning = 0;
2588         btrfs_end_transaction(trans, root);
2589 out_unlock:
2590         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2591                              &cached, GFP_NOFS);
2592         iput(inode);
2593         return ret;
2594 }
2595 
2596 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2597 {
2598         struct old_sa_defrag_extent *old, *tmp;
2599 
2600         if (!new)
2601                 return;
2602 
2603         list_for_each_entry_safe(old, tmp, &new->head, list) {
2604                 list_del(&old->list);
2605                 kfree(old);
2606         }
2607         kfree(new);
2608 }
2609 
2610 static void relink_file_extents(struct new_sa_defrag_extent *new)
2611 {
2612         struct btrfs_path *path;
2613         struct sa_defrag_extent_backref *backref;
2614         struct sa_defrag_extent_backref *prev = NULL;
2615         struct inode *inode;
2616         struct btrfs_root *root;
2617         struct rb_node *node;
2618         int ret;
2619 
2620         inode = new->inode;
2621         root = BTRFS_I(inode)->root;
2622 
2623         path = btrfs_alloc_path();
2624         if (!path)
2625                 return;
2626 
2627         if (!record_extent_backrefs(path, new)) {
2628                 btrfs_free_path(path);
2629                 goto out;
2630         }
2631         btrfs_release_path(path);
2632 
2633         while (1) {
2634                 node = rb_first(&new->root);
2635                 if (!node)
2636                         break;
2637                 rb_erase(node, &new->root);
2638 
2639                 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2640 
2641                 ret = relink_extent_backref(path, prev, backref);
2642                 WARN_ON(ret < 0);
2643 
2644                 kfree(prev);
2645 
2646                 if (ret == 1)
2647                         prev = backref;
2648                 else
2649                         prev = NULL;
2650                 cond_resched();
2651         }
2652         kfree(prev);
2653 
2654         btrfs_free_path(path);
2655 out:
2656         free_sa_defrag_extent(new);
2657 
2658         atomic_dec(&root->fs_info->defrag_running);
2659         wake_up(&root->fs_info->transaction_wait);
2660 }
2661 
2662 static struct new_sa_defrag_extent *
2663 record_old_file_extents(struct inode *inode,
2664                         struct btrfs_ordered_extent *ordered)
2665 {
2666         struct btrfs_root *root = BTRFS_I(inode)->root;
2667         struct btrfs_path *path;
2668         struct btrfs_key key;
2669         struct old_sa_defrag_extent *old;
2670         struct new_sa_defrag_extent *new;
2671         int ret;
2672 
2673         new = kmalloc(sizeof(*new), GFP_NOFS);
2674         if (!new)
2675                 return NULL;
2676 
2677         new->inode = inode;
2678         new->file_pos = ordered->file_offset;
2679         new->len = ordered->len;
2680         new->bytenr = ordered->start;
2681         new->disk_len = ordered->disk_len;
2682         new->compress_type = ordered->compress_type;
2683         new->root = RB_ROOT;
2684         INIT_LIST_HEAD(&new->head);
2685 
2686         path = btrfs_alloc_path();
2687         if (!path)
2688                 goto out_kfree;
2689 
2690         key.objectid = btrfs_ino(inode);
2691         key.type = BTRFS_EXTENT_DATA_KEY;
2692         key.offset = new->file_pos;
2693 
2694         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2695         if (ret < 0)
2696                 goto out_free_path;
2697         if (ret > 0 && path->slots[0] > 0)
2698                 path->slots[0]--;
2699 
2700         /* find out all the old extents for the file range */
2701         while (1) {
2702                 struct btrfs_file_extent_item *extent;
2703                 struct extent_buffer *l;
2704                 int slot;
2705                 u64 num_bytes;
2706                 u64 offset;
2707                 u64 end;
2708                 u64 disk_bytenr;
2709                 u64 extent_offset;
2710 
2711                 l = path->nodes[0];
2712                 slot = path->slots[0];
2713 
2714                 if (slot >= btrfs_header_nritems(l)) {
2715                         ret = btrfs_next_leaf(root, path);
2716                         if (ret < 0)
2717                                 goto out_free_path;
2718                         else if (ret > 0)
2719                                 break;
2720                         continue;
2721                 }
2722 
2723                 btrfs_item_key_to_cpu(l, &key, slot);
2724 
2725                 if (key.objectid != btrfs_ino(inode))
2726                         break;
2727                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2728                         break;
2729                 if (key.offset >= new->file_pos + new->len)
2730                         break;
2731 
2732                 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2733 
2734                 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2735                 if (key.offset + num_bytes < new->file_pos)
2736                         goto next;
2737 
2738                 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2739                 if (!disk_bytenr)
2740                         goto next;
2741 
2742                 extent_offset = btrfs_file_extent_offset(l, extent);
2743 
2744                 old = kmalloc(sizeof(*old), GFP_NOFS);
2745                 if (!old)
2746                         goto out_free_path;
2747 
2748                 offset = max(new->file_pos, key.offset);
2749                 end = min(new->file_pos + new->len, key.offset + num_bytes);
2750 
2751                 old->bytenr = disk_bytenr;
2752                 old->extent_offset = extent_offset;
2753                 old->offset = offset - key.offset;
2754                 old->len = end - offset;
2755                 old->new = new;
2756                 old->count = 0;
2757                 list_add_tail(&old->list, &new->head);
2758 next:
2759                 path->slots[0]++;
2760                 cond_resched();
2761         }
2762 
2763         btrfs_free_path(path);
2764         atomic_inc(&root->fs_info->defrag_running);
2765 
2766         return new;
2767 
2768 out_free_path:
2769         btrfs_free_path(path);
2770 out_kfree:
2771         free_sa_defrag_extent(new);
2772         return NULL;
2773 }
2774 
2775 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2776                                          u64 start, u64 len)
2777 {
2778         struct btrfs_block_group_cache *cache;
2779 
2780         cache = btrfs_lookup_block_group(root->fs_info, start);
2781         ASSERT(cache);
2782 
2783         spin_lock(&cache->lock);
2784         cache->delalloc_bytes -= len;
2785         spin_unlock(&cache->lock);
2786 
2787         btrfs_put_block_group(cache);
2788 }
2789 
2790 /* as ordered data IO finishes, this gets called so we can finish
2791  * an ordered extent if the range of bytes in the file it covers are
2792  * fully written.
2793  */
2794 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2795 {
2796         struct inode *inode = ordered_extent->inode;
2797         struct btrfs_root *root = BTRFS_I(inode)->root;
2798         struct btrfs_trans_handle *trans = NULL;
2799         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2800         struct extent_state *cached_state = NULL;
2801         struct new_sa_defrag_extent *new = NULL;
2802         int compress_type = 0;
2803         int ret = 0;
2804         u64 logical_len = ordered_extent->len;
2805         bool nolock;
2806         bool truncated = false;
2807 
2808         nolock = btrfs_is_free_space_inode(inode);
2809 
2810         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2811                 ret = -EIO;
2812                 goto out;
2813         }
2814 
2815         btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2816                                      ordered_extent->file_offset +
2817                                      ordered_extent->len - 1);
2818 
2819         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2820                 truncated = true;
2821                 logical_len = ordered_extent->truncated_len;
2822                 /* Truncated the entire extent, don't bother adding */
2823                 if (!logical_len)
2824                         goto out;
2825         }
2826 
2827         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2828                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2829                 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2830                 if (nolock)
2831                         trans = btrfs_join_transaction_nolock(root);
2832                 else
2833                         trans = btrfs_join_transaction(root);
2834                 if (IS_ERR(trans)) {
2835                         ret = PTR_ERR(trans);
2836                         trans = NULL;
2837                         goto out;
2838                 }
2839                 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2840                 ret = btrfs_update_inode_fallback(trans, root, inode);
2841                 if (ret) /* -ENOMEM or corruption */
2842                         btrfs_abort_transaction(trans, root, ret);
2843                 goto out;
2844         }
2845 
2846         lock_extent_bits(io_tree, ordered_extent->file_offset,
2847                          ordered_extent->file_offset + ordered_extent->len - 1,
2848                          0, &cached_state);
2849 
2850         ret = test_range_bit(io_tree, ordered_extent->file_offset,
2851                         ordered_extent->file_offset + ordered_extent->len - 1,
2852                         EXTENT_DEFRAG, 1, cached_state);
2853         if (ret) {
2854                 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2855                 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2856                         /* the inode is shared */
2857                         new = record_old_file_extents(inode, ordered_extent);
2858 
2859                 clear_extent_bit(io_tree, ordered_extent->file_offset,
2860                         ordered_extent->file_offset + ordered_extent->len - 1,
2861                         EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2862         }
2863 
2864         if (nolock)
2865                 trans = btrfs_join_transaction_nolock(root);
2866         else
2867                 trans = btrfs_join_transaction(root);
2868         if (IS_ERR(trans)) {
2869                 ret = PTR_ERR(trans);
2870                 trans = NULL;
2871                 goto out_unlock;
2872         }
2873 
2874         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2875 
2876         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2877                 compress_type = ordered_extent->compress_type;
2878         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2879                 BUG_ON(compress_type);
2880                 ret = btrfs_mark_extent_written(trans, inode,
2881                                                 ordered_extent->file_offset,
2882                                                 ordered_extent->file_offset +
2883                                                 logical_len);
2884         } else {
2885                 BUG_ON(root == root->fs_info->tree_root);
2886                 ret = insert_reserved_file_extent(trans, inode,
2887                                                 ordered_extent->file_offset,
2888                                                 ordered_extent->start,
2889                                                 ordered_extent->disk_len,
2890                                                 logical_len, logical_len,
2891                                                 compress_type, 0, 0,
2892                                                 BTRFS_FILE_EXTENT_REG);
2893                 if (!ret)
2894                         btrfs_release_delalloc_bytes(root,
2895                                                      ordered_extent->start,
2896                                                      ordered_extent->disk_len);
2897         }
2898         unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2899                            ordered_extent->file_offset, ordered_extent->len,
2900                            trans->transid);
2901         if (ret < 0) {
2902                 btrfs_abort_transaction(trans, root, ret);
2903                 goto out_unlock;
2904         }
2905 
2906         add_pending_csums(trans, inode, ordered_extent->file_offset,
2907                           &ordered_extent->list);
2908 
2909         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2910         ret = btrfs_update_inode_fallback(trans, root, inode);
2911         if (ret) { /* -ENOMEM or corruption */
2912                 btrfs_abort_transaction(trans, root, ret);
2913                 goto out_unlock;
2914         }
2915         ret = 0;
2916 out_unlock:
2917         unlock_extent_cached(io_tree, ordered_extent->file_offset,
2918                              ordered_extent->file_offset +
2919                              ordered_extent->len - 1, &cached_state, GFP_NOFS);
2920 out:
2921         if (root != root->fs_info->tree_root)
2922                 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2923         if (trans)
2924                 btrfs_end_transaction(trans, root);
2925 
2926         if (ret || truncated) {
2927                 u64 start, end;
2928 
2929                 if (truncated)
2930                         start = ordered_extent->file_offset + logical_len;
2931                 else
2932                         start = ordered_extent->file_offset;
2933                 end = ordered_extent->file_offset + ordered_extent->len - 1;
2934                 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2935 
2936                 /* Drop the cache for the part of the extent we didn't write. */
2937                 btrfs_drop_extent_cache(inode, start, end, 0);
2938 
2939                 /*
2940                  * If the ordered extent had an IOERR or something else went
2941                  * wrong we need to return the space for this ordered extent
2942                  * back to the allocator.  We only free the extent in the
2943                  * truncated case if we didn't write out the extent at all.
2944                  */
2945                 if ((ret || !logical_len) &&
2946                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2947                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2948                         btrfs_free_reserved_extent(root, ordered_extent->start,
2949                                                    ordered_extent->disk_len, 1);
2950         }
2951 
2952 
2953         /*
2954          * This needs to be done to make sure anybody waiting knows we are done
2955          * updating everything for this ordered extent.
2956          */
2957         btrfs_remove_ordered_extent(inode, ordered_extent);
2958 
2959         /* for snapshot-aware defrag */
2960         if (new) {
2961                 if (ret) {
2962                         free_sa_defrag_extent(new);
2963                         atomic_dec(&root->fs_info->defrag_running);
2964                 } else {
2965                         relink_file_extents(new);
2966                 }
2967         }
2968 
2969         /* once for us */
2970         btrfs_put_ordered_extent(ordered_extent);
2971         /* once for the tree */
2972         btrfs_put_ordered_extent(ordered_extent);
2973 
2974         return ret;
2975 }
2976 
2977 static void finish_ordered_fn(struct btrfs_work *work)
2978 {
2979         struct btrfs_ordered_extent *ordered_extent;
2980         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2981         btrfs_finish_ordered_io(ordered_extent);
2982 }
2983 
2984 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2985                                 struct extent_state *state, int uptodate)
2986 {
2987         struct inode *inode = page->mapping->host;
2988         struct btrfs_root *root = BTRFS_I(inode)->root;
2989         struct btrfs_ordered_extent *ordered_extent = NULL;
2990         struct btrfs_workqueue *wq;
2991         btrfs_work_func_t func;
2992 
2993         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2994 
2995         ClearPagePrivate2(page);
2996         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2997                                             end - start + 1, uptodate))
2998                 return 0;
2999 
3000         if (btrfs_is_free_space_inode(inode)) {
3001                 wq = root->fs_info->endio_freespace_worker;
3002                 func = btrfs_freespace_write_helper;
3003         } else {
3004                 wq = root->fs_info->endio_write_workers;
3005                 func = btrfs_endio_write_helper;
3006         }
3007 
3008         btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3009                         NULL);
3010         btrfs_queue_work(wq, &ordered_extent->work);
3011 
3012         return 0;
3013 }
3014 
3015 static int __readpage_endio_check(struct inode *inode,
3016                                   struct btrfs_io_bio *io_bio,
3017                                   int icsum, struct page *page,
3018                                   int pgoff, u64 start, size_t len)
3019 {
3020         char *kaddr;
3021         u32 csum_expected;
3022         u32 csum = ~(u32)0;
3023         static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
3024                                       DEFAULT_RATELIMIT_BURST);
3025 
3026         csum_expected = *(((u32 *)io_bio->csum) + icsum);
3027 
3028         kaddr = kmap_atomic(page);
3029         csum = btrfs_csum_data(kaddr + pgoff, csum,  len);
3030         btrfs_csum_final(csum, (char *)&csum);
3031         if (csum != csum_expected)
3032                 goto zeroit;
3033 
3034         kunmap_atomic(kaddr);
3035         return 0;
3036 zeroit:
3037         if (__ratelimit(&_rs))
3038                 btrfs_warn(BTRFS_I(inode)->root->fs_info,
3039                            "csum failed ino %llu off %llu csum %u expected csum %u",
3040                            btrfs_ino(inode), start, csum, csum_expected);
3041         memset(kaddr + pgoff, 1, len);
3042         flush_dcache_page(page);
3043         kunmap_atomic(kaddr);
3044         if (csum_expected == 0)
3045                 return 0;
3046         return -EIO;
3047 }
3048 
3049 /*
3050  * when reads are done, we need to check csums to verify the data is correct
3051  * if there's a match, we allow the bio to finish.  If not, the code in
3052  * extent_io.c will try to find good copies for us.
3053  */
3054 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3055                                       u64 phy_offset, struct page *page,
3056                                       u64 start, u64 end, int mirror)
3057 {
3058         size_t offset = start - page_offset(page);
3059         struct inode *inode = page->mapping->host;
3060         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3061         struct btrfs_root *root = BTRFS_I(inode)->root;
3062 
3063         if (PageChecked(page)) {
3064                 ClearPageChecked(page);
3065                 return 0;
3066         }
3067 
3068         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3069                 return 0;
3070 
3071         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3072             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3073                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
3074                                   GFP_NOFS);
3075                 return 0;
3076         }
3077 
3078         phy_offset >>= inode->i_sb->s_blocksize_bits;
3079         return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3080                                       start, (size_t)(end - start + 1));
3081 }
3082 
3083 struct delayed_iput {
3084         struct list_head list;
3085         struct inode *inode;
3086 };
3087 
3088 /* JDM: If this is fs-wide, why can't we add a pointer to
3089  * btrfs_inode instead and avoid the allocation? */
3090 void btrfs_add_delayed_iput(struct inode *inode)
3091 {
3092         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3093         struct delayed_iput *delayed;
3094 
3095         if (atomic_add_unless(&inode->i_count, -1, 1))
3096                 return;
3097 
3098         delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
3099         delayed->inode = inode;
3100 
3101         spin_lock(&fs_info->delayed_iput_lock);
3102         list_add_tail(&delayed->list, &fs_info->delayed_iputs);
3103         spin_unlock(&fs_info->delayed_iput_lock);
3104 }
3105 
3106 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3107 {
3108         LIST_HEAD(list);
3109         struct btrfs_fs_info *fs_info = root->fs_info;
3110         struct delayed_iput *delayed;
3111         int empty;
3112 
3113         spin_lock(&fs_info->delayed_iput_lock);
3114         empty = list_empty(&fs_info->delayed_iputs);
3115         spin_unlock(&fs_info->delayed_iput_lock);
3116         if (empty)
3117                 return;
3118 
3119         down_read(&fs_info->delayed_iput_sem);
3120 
3121         spin_lock(&fs_info->delayed_iput_lock);
3122         list_splice_init(&fs_info->delayed_iputs, &list);
3123         spin_unlock(&fs_info->delayed_iput_lock);
3124 
3125         while (!list_empty(&list)) {
3126                 delayed = list_entry(list.next, struct delayed_iput, list);
3127                 list_del(&delayed->list);
3128                 iput(delayed->inode);
3129                 kfree(delayed);
3130         }
3131 
3132         up_read(&root->fs_info->delayed_iput_sem);
3133 }
3134 
3135 /*
3136  * This is called in transaction commit time. If there are no orphan
3137  * files in the subvolume, it removes orphan item and frees block_rsv
3138  * structure.
3139  */
3140 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3141                               struct btrfs_root *root)
3142 {
3143         struct btrfs_block_rsv *block_rsv;
3144         int ret;
3145 
3146         if (atomic_read(&root->orphan_inodes) ||
3147             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3148                 return;
3149 
3150         spin_lock(&root->orphan_lock);
3151         if (atomic_read(&root->orphan_inodes)) {
3152                 spin_unlock(&root->orphan_lock);
3153                 return;
3154         }
3155 
3156         if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3157                 spin_unlock(&root->orphan_lock);
3158                 return;
3159         }
3160 
3161         block_rsv = root->orphan_block_rsv;
3162         root->orphan_block_rsv = NULL;
3163         spin_unlock(&root->orphan_lock);
3164 
3165         if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3166             btrfs_root_refs(&root->root_item) > 0) {
3167                 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3168                                             root->root_key.objectid);
3169                 if (ret)
3170                         btrfs_abort_transaction(trans, root, ret);
3171                 else
3172                         clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3173                                   &root->state);
3174         }
3175 
3176         if (block_rsv) {
3177                 WARN_ON(block_rsv->size > 0);
3178                 btrfs_free_block_rsv(root, block_rsv);
3179         }
3180 }
3181 
3182 /*
3183  * This creates an orphan entry for the given inode in case something goes
3184  * wrong in the middle of an unlink/truncate.
3185  *
3186  * NOTE: caller of this function should reserve 5 units of metadata for
3187  *       this function.
3188  */
3189 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3190 {
3191         struct btrfs_root *root = BTRFS_I(inode)->root;
3192         struct btrfs_block_rsv *block_rsv = NULL;
3193         int reserve = 0;
3194         int insert = 0;
3195         int ret;
3196 
3197         if (!root->orphan_block_rsv) {
3198                 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3199                 if (!block_rsv)
3200                         return -ENOMEM;
3201         }
3202 
3203         spin_lock(&root->orphan_lock);
3204         if (!root->orphan_block_rsv) {
3205                 root->orphan_block_rsv = block_rsv;
3206         } else if (block_rsv) {
3207                 btrfs_free_block_rsv(root, block_rsv);
3208                 block_rsv = NULL;
3209         }
3210 
3211         if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3212                               &BTRFS_I(inode)->runtime_flags)) {
3213 #if 0
3214                 /*
3215                  * For proper ENOSPC handling, we should do orphan
3216                  * cleanup when mounting. But this introduces backward
3217                  * compatibility issue.
3218                  */
3219                 if (!xchg(&root->orphan_item_inserted, 1))
3220                         insert = 2;
3221                 else
3222                         insert = 1;
3223 #endif
3224                 insert = 1;
3225                 atomic_inc(&root->orphan_inodes);
3226         }
3227 
3228         if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3229                               &BTRFS_I(inode)->runtime_flags))
3230                 reserve = 1;
3231         spin_unlock(&root->orphan_lock);
3232 
3233         /* grab metadata reservation from transaction handle */
3234         if (reserve) {
3235                 ret = btrfs_orphan_reserve_metadata(trans, inode);
3236                 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3237         }
3238 
3239         /* insert an orphan item to track this unlinked/truncated file */
3240         if (insert >= 1) {
3241                 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3242                 if (ret) {
3243                         atomic_dec(&root->orphan_inodes);
3244                         if (reserve) {
3245                                 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3246                                           &BTRFS_I(inode)->runtime_flags);
3247                                 btrfs_orphan_release_metadata(inode);
3248                         }
3249                         if (ret != -EEXIST) {
3250                                 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3251                                           &BTRFS_I(inode)->runtime_flags);
3252                                 btrfs_abort_transaction(trans, root, ret);
3253                                 return ret;
3254                         }
3255                 }
3256                 ret = 0;
3257         }
3258 
3259         /* insert an orphan item to track subvolume contains orphan files */
3260         if (insert >= 2) {
3261                 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3262                                                root->root_key.objectid);
3263                 if (ret && ret != -EEXIST) {
3264                         btrfs_abort_transaction(trans, root, ret);
3265                         return ret;
3266                 }
3267         }
3268         return 0;
3269 }
3270 
3271 /*
3272  * We have done the truncate/delete so we can go ahead and remove the orphan
3273  * item for this particular inode.
3274  */
3275 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3276                             struct inode *inode)
3277 {
3278         struct btrfs_root *root = BTRFS_I(inode)->root;
3279         int delete_item = 0;
3280         int release_rsv = 0;
3281         int ret = 0;
3282 
3283         spin_lock(&root->orphan_lock);
3284         if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3285                                &BTRFS_I(inode)->runtime_flags))
3286                 delete_item = 1;
3287 
3288         if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3289                                &BTRFS_I(inode)->runtime_flags))
3290                 release_rsv = 1;
3291         spin_unlock(&root->orphan_lock);
3292 
3293         if (delete_item) {
3294                 atomic_dec(&root->orphan_inodes);
3295                 if (trans)
3296                         ret = btrfs_del_orphan_item(trans, root,
3297                                                     btrfs_ino(inode));
3298         }
3299 
3300         if (release_rsv)
3301                 btrfs_orphan_release_metadata(inode);
3302 
3303         return ret;
3304 }
3305 
3306 /*
3307  * this cleans up any orphans that may be left on the list from the last use
3308  * of this root.
3309  */
3310 int btrfs_orphan_cleanup(struct btrfs_root *root)
3311 {
3312         struct btrfs_path *path;
3313         struct extent_buffer *leaf;
3314         struct btrfs_key key, found_key;
3315         struct btrfs_trans_handle *trans;
3316         struct inode *inode;
3317         u64 last_objectid = 0;
3318         int ret = 0, nr_unlink = 0, nr_truncate = 0;
3319 
3320         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3321                 return 0;
3322 
3323         path = btrfs_alloc_path();
3324         if (!path) {
3325                 ret = -ENOMEM;
3326                 goto out;
3327         }
3328         path->reada = -1;
3329 
3330         key.objectid = BTRFS_ORPHAN_OBJECTID;
3331         key.type = BTRFS_ORPHAN_ITEM_KEY;
3332         key.offset = (u64)-1;
3333 
3334         while (1) {
3335                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3336                 if (ret < 0)
3337                         goto out;
3338 
3339                 /*
3340                  * if ret == 0 means we found what we were searching for, which
3341                  * is weird, but possible, so only screw with path if we didn't
3342                  * find the key and see if we have stuff that matches
3343                  */
3344                 if (ret > 0) {
3345                         ret = 0;
3346                         if (path->slots[0] == 0)
3347                                 break;
3348                         path->slots[0]--;
3349                 }
3350 
3351                 /* pull out the item */
3352                 leaf = path->nodes[0];
3353                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3354 
3355                 /* make sure the item matches what we want */
3356                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3357                         break;
3358                 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3359                         break;
3360 
3361                 /* release the path since we're done with it */
3362                 btrfs_release_path(path);
3363 
3364                 /*
3365                  * this is where we are basically btrfs_lookup, without the
3366                  * crossing root thing.  we store the inode number in the
3367                  * offset of the orphan item.
3368                  */
3369 
3370                 if (found_key.offset == last_objectid) {
3371                         btrfs_err(root->fs_info,
3372                                 "Error removing orphan entry, stopping orphan cleanup");
3373                         ret = -EINVAL;
3374                         goto out;
3375                 }
3376 
3377                 last_objectid = found_key.offset;
3378 
3379                 found_key.objectid = found_key.offset;
3380                 found_key.type = BTRFS_INODE_ITEM_KEY;
3381                 found_key.offset = 0;
3382                 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3383                 ret = PTR_ERR_OR_ZERO(inode);
3384                 if (ret && ret != -ESTALE)
3385                         goto out;
3386 
3387                 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3388                         struct btrfs_root *dead_root;
3389                         struct btrfs_fs_info *fs_info = root->fs_info;
3390                         int is_dead_root = 0;
3391 
3392                         /*
3393                          * this is an orphan in the tree root. Currently these
3394                          * could come from 2 sources:
3395                          *  a) a snapshot deletion in progress
3396                          *  b) a free space cache inode
3397                          * We need to distinguish those two, as the snapshot
3398                          * orphan must not get deleted.
3399                          * find_dead_roots already ran before us, so if this
3400                          * is a snapshot deletion, we should find the root
3401                          * in the dead_roots list
3402                          */
3403                         spin_lock(&fs_info->trans_lock);
3404                         list_for_each_entry(dead_root, &fs_info->dead_roots,
3405                                             root_list) {
3406                                 if (dead_root->root_key.objectid ==
3407                                     found_key.objectid) {
3408                                         is_dead_root = 1;
3409                                         break;
3410                                 }
3411                         }
3412                         spin_unlock(&fs_info->trans_lock);
3413                         if (is_dead_root) {
3414                                 /* prevent this orphan from being found again */
3415                                 key.offset = found_key.objectid - 1;
3416                                 continue;
3417                         }
3418                 }
3419                 /*
3420                  * Inode is already gone but the orphan item is still there,
3421                  * kill the orphan item.
3422                  */
3423                 if (ret == -ESTALE) {
3424                         trans = btrfs_start_transaction(root, 1);
3425                         if (IS_ERR(trans)) {
3426                                 ret = PTR_ERR(trans);
3427                                 goto out;
3428                         }
3429                         btrfs_debug(root->fs_info, "auto deleting %Lu",
3430                                 found_key.objectid);
3431                         ret = btrfs_del_orphan_item(trans, root,
3432                                                     found_key.objectid);
3433                         btrfs_end_transaction(trans, root);
3434                         if (ret)
3435                                 goto out;
3436                         continue;
3437                 }
3438 
3439                 /*
3440                  * add this inode to the orphan list so btrfs_orphan_del does
3441                  * the proper thing when we hit it
3442                  */
3443                 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3444                         &BTRFS_I(inode)->runtime_flags);
3445                 atomic_inc(&root->orphan_inodes);
3446 
3447                 /* if we have links, this was a truncate, lets do that */
3448                 if (inode->i_nlink) {
3449                         if (WARN_ON(!S_ISREG(inode->i_mode))) {
3450                                 iput(inode);
3451                                 continue;
3452                         }
3453                         nr_truncate++;
3454 
3455                         /* 1 for the orphan item deletion. */
3456                         trans = btrfs_start_transaction(root, 1);
3457                         if (IS_ERR(trans)) {
3458                                 iput(inode);
3459                                 ret = PTR_ERR(trans);
3460                                 goto out;
3461                         }
3462                         ret = btrfs_orphan_add(trans, inode);
3463                         btrfs_end_transaction(trans, root);
3464                         if (ret) {
3465                                 iput(inode);
3466                                 goto out;
3467                         }
3468 
3469                         ret = btrfs_truncate(inode);
3470                         if (ret)
3471                                 btrfs_orphan_del(NULL, inode);
3472                 } else {
3473                         nr_unlink++;
3474                 }
3475 
3476                 /* this will do delete_inode and everything for us */
3477                 iput(inode);
3478                 if (ret)
3479                         goto out;
3480         }
3481         /* release the path since we're done with it */
3482         btrfs_release_path(path);
3483 
3484         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3485 
3486         if (root->orphan_block_rsv)
3487                 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3488                                         (u64)-1);
3489 
3490         if (root->orphan_block_rsv ||
3491             test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3492                 trans = btrfs_join_transaction(root);
3493                 if (!IS_ERR(trans))
3494                         btrfs_end_transaction(trans, root);
3495         }
3496 
3497         if (nr_unlink)
3498                 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3499         if (nr_truncate)
3500                 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3501 
3502 out:
3503         if (ret)
3504                 btrfs_err(root->fs_info,
3505                         "could not do orphan cleanup %d", ret);
3506         btrfs_free_path(path);
3507         return ret;
3508 }
3509 
3510 /*
3511  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3512  * don't find any xattrs, we know there can't be any acls.
3513  *
3514  * slot is the slot the inode is in, objectid is the objectid of the inode
3515  */
3516 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3517                                           int slot, u64 objectid,
3518                                           int *first_xattr_slot)
3519 {
3520         u32 nritems = btrfs_header_nritems(leaf);
3521         struct btrfs_key found_key;
3522         static u64 xattr_access = 0;
3523         static u64 xattr_default = 0;
3524         int scanned = 0;
3525 
3526         if (!xattr_access) {
3527                 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3528                                         strlen(POSIX_ACL_XATTR_ACCESS));
3529                 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3530                                         strlen(POSIX_ACL_XATTR_DEFAULT));
3531         }
3532 
3533         slot++;
3534         *first_xattr_slot = -1;
3535         while (slot < nritems) {
3536                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3537 
3538                 /* we found a different objectid, there must not be acls */
3539                 if (found_key.objectid != objectid)
3540                         return 0;
3541 
3542                 /* we found an xattr, assume we've got an acl */
3543                 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3544                         if (*first_xattr_slot == -1)
3545                                 *first_xattr_slot = slot;
3546                         if (found_key.offset == xattr_access ||
3547                             found_key.offset == xattr_default)
3548                                 return 1;
3549                 }
3550 
3551                 /*
3552                  * we found a key greater than an xattr key, there can't
3553                  * be any acls later on
3554                  */
3555                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3556                         return 0;
3557 
3558                 slot++;
3559                 scanned++;
3560 
3561                 /*
3562                  * it goes inode, inode backrefs, xattrs, extents,
3563                  * so if there are a ton of hard links to an inode there can
3564                  * be a lot of backrefs.  Don't waste time searching too hard,
3565                  * this is just an optimization
3566                  */
3567                 if (scanned >= 8)
3568                         break;
3569         }
3570         /* we hit the end of the leaf before we found an xattr or
3571          * something larger than an xattr.  We have to assume the inode
3572          * has acls
3573          */
3574         if (*first_xattr_slot == -1)
3575                 *first_xattr_slot = slot;
3576         return 1;
3577 }
3578 
3579 /*
3580  * read an inode from the btree into the in-memory inode
3581  */
3582 static void btrfs_read_locked_inode(struct inode *inode)
3583 {
3584         struct btrfs_path *path;
3585         struct extent_buffer *leaf;
3586         struct btrfs_inode_item *inode_item;
3587         struct btrfs_root *root = BTRFS_I(inode)->root;
3588         struct btrfs_key location;
3589         unsigned long ptr;
3590         int maybe_acls;
3591         u32 rdev;
3592         int ret;
3593         bool filled = false;
3594         int first_xattr_slot;
3595 
3596         ret = btrfs_fill_inode(inode, &rdev);
3597         if (!ret)
3598                 filled = true;
3599 
3600         path = btrfs_alloc_path();
3601         if (!path)
3602                 goto make_bad;
3603 
3604         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3605 
3606         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3607         if (ret)
3608                 goto make_bad;
3609 
3610         leaf = path->nodes[0];
3611 
3612         if (filled)
3613                 goto cache_index;
3614 
3615         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3616                                     struct btrfs_inode_item);
3617         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3618         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3619         i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3620         i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3621         btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3622 
3623         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3624         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3625 
3626         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3627         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3628 
3629         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3630         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3631 
3632         BTRFS_I(inode)->i_otime.tv_sec =
3633                 btrfs_timespec_sec(leaf, &inode_item->otime);
3634         BTRFS_I(inode)->i_otime.tv_nsec =
3635                 btrfs_timespec_nsec(leaf, &inode_item->otime);
3636 
3637         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3638         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3639         BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3640 
3641         inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3642         inode->i_generation = BTRFS_I(inode)->generation;
3643         inode->i_rdev = 0;
3644         rdev = btrfs_inode_rdev(leaf, inode_item);
3645 
3646         BTRFS_I(inode)->index_cnt = (u64)-1;
3647         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3648 
3649 cache_index:
3650         /*
3651          * If we were modified in the current generation and evicted from memory
3652          * and then re-read we need to do a full sync since we don't have any
3653          * idea about which extents were modified before we were evicted from
3654          * cache.
3655          *
3656          * This is required for both inode re-read from disk and delayed inode
3657          * in delayed_nodes_tree.
3658          */
3659         if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3660                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3661                         &BTRFS_I(inode)->runtime_flags);
3662 
3663         path->slots[0]++;
3664         if (inode->i_nlink != 1 ||
3665             path->slots[0] >= btrfs_header_nritems(leaf))
3666                 goto cache_acl;
3667 
3668         btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3669         if (location.objectid != btrfs_ino(inode))
3670                 goto cache_acl;
3671 
3672         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3673         if (location.type == BTRFS_INODE_REF_KEY) {
3674                 struct btrfs_inode_ref *ref;
3675 
3676                 ref = (struct btrfs_inode_ref *)ptr;
3677                 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3678         } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3679                 struct btrfs_inode_extref *extref;
3680 
3681                 extref = (struct btrfs_inode_extref *)ptr;
3682                 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3683                                                                      extref);
3684         }
3685 cache_acl:
3686         /*
3687          * try to precache a NULL acl entry for files that don't have
3688          * any xattrs or acls
3689          */
3690         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3691                                            btrfs_ino(inode), &first_xattr_slot);
3692         if (first_xattr_slot != -1) {
3693                 path->slots[0] = first_xattr_slot;
3694                 ret = btrfs_load_inode_props(inode, path);
3695                 if (ret)
3696                         btrfs_err(root->fs_info,
3697                                   "error loading props for ino %llu (root %llu): %d",
3698                                   btrfs_ino(inode),
3699                                   root->root_key.objectid, ret);
3700         }
3701         btrfs_free_path(path);
3702 
3703         if (!maybe_acls)
3704                 cache_no_acl(inode);
3705 
3706         switch (inode->i_mode & S_IFMT) {
3707         case S_IFREG:
3708                 inode->i_mapping->a_ops = &btrfs_aops;
3709                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3710                 inode->i_fop = &btrfs_file_operations;
3711                 inode->i_op = &btrfs_file_inode_operations;
3712                 break;
3713         case S_IFDIR:
3714                 inode->i_fop = &btrfs_dir_file_operations;
3715                 if (root == root->fs_info->tree_root)
3716                         inode->i_op = &btrfs_dir_ro_inode_operations;
3717                 else
3718                         inode->i_op = &btrfs_dir_inode_operations;
3719                 break;
3720         case S_IFLNK:
3721                 inode->i_op = &btrfs_symlink_inode_operations;
3722                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3723                 break;
3724         default:
3725                 inode->i_op = &btrfs_special_inode_operations;
3726                 init_special_inode(inode, inode->i_mode, rdev);
3727                 break;
3728         }
3729 
3730         btrfs_update_iflags(inode);
3731         return;
3732 
3733 make_bad:
3734         btrfs_free_path(path);
3735         make_bad_inode(inode);
3736 }
3737 
3738 /*
3739  * given a leaf and an inode, copy the inode fields into the leaf
3740  */
3741 static void fill_inode_item(struct btrfs_trans_handle *trans,
3742                             struct extent_buffer *leaf,
3743                             struct btrfs_inode_item *item,
3744                             struct inode *inode)
3745 {
3746         struct btrfs_map_token token;
3747 
3748         btrfs_init_map_token(&token);
3749 
3750         btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3751         btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3752         btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3753                                    &token);
3754         btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3755         btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3756 
3757         btrfs_set_token_timespec_sec(leaf, &item->atime,
3758                                      inode->i_atime.tv_sec, &token);
3759         btrfs_set_token_timespec_nsec(leaf, &item->atime,
3760                                       inode->i_atime.tv_nsec, &token);
3761 
3762         btrfs_set_token_timespec_sec(leaf, &item->mtime,
3763                                      inode->i_mtime.tv_sec, &token);
3764         btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3765                                       inode->i_mtime.tv_nsec, &token);
3766 
3767         btrfs_set_token_timespec_sec(leaf, &item->ctime,
3768                                      inode->i_ctime.tv_sec, &token);
3769         btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3770                                       inode->i_ctime.tv_nsec, &token);
3771 
3772         btrfs_set_token_timespec_sec(leaf, &item->otime,
3773                                      BTRFS_I(inode)->i_otime.tv_sec, &token);
3774         btrfs_set_token_timespec_nsec(leaf, &item->otime,
3775                                       BTRFS_I(inode)->i_otime.tv_nsec, &token);
3776 
3777         btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3778                                      &token);
3779         btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3780                                          &token);
3781         btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3782         btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3783         btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3784         btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3785         btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3786 }
3787 
3788 /*
3789  * copy everything in the in-memory inode into the btree.
3790  */
3791 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3792                                 struct btrfs_root *root, struct inode *inode)
3793 {
3794         struct btrfs_inode_item *inode_item;
3795         struct btrfs_path *path;
3796         struct extent_buffer *leaf;
3797         int ret;
3798 
3799         path = btrfs_alloc_path();
3800         if (!path)
3801                 return -ENOMEM;
3802 
3803         path->leave_spinning = 1;
3804         ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3805                                  1);
3806         if (ret) {
3807                 if (ret > 0)
3808                         ret = -ENOENT;
3809                 goto failed;
3810         }
3811 
3812         leaf = path->nodes[0];
3813         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3814                                     struct btrfs_inode_item);
3815 
3816         fill_inode_item(trans, leaf, inode_item, inode);
3817         btrfs_mark_buffer_dirty(leaf);
3818         btrfs_set_inode_last_trans(trans, inode);
3819         ret = 0;
3820 failed:
3821         btrfs_free_path(path);
3822         return ret;
3823 }
3824 
3825 /*
3826  * copy everything in the in-memory inode into the btree.
3827  */
3828 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3829                                 struct btrfs_root *root, struct inode *inode)
3830 {
3831         int ret;
3832 
3833         /*
3834          * If the inode is a free space inode, we can deadlock during commit
3835          * if we put it into the delayed code.
3836          *
3837          * The data relocation inode should also be directly updated
3838          * without delay
3839          */
3840         if (!btrfs_is_free_space_inode(inode)
3841             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3842             && !root->fs_info->log_root_recovering) {
3843                 btrfs_update_root_times(trans, root);
3844 
3845                 ret = btrfs_delayed_update_inode(trans, root, inode);
3846                 if (!ret)
3847                         btrfs_set_inode_last_trans(trans, inode);
3848                 return ret;
3849         }
3850 
3851         return btrfs_update_inode_item(trans, root, inode);
3852 }
3853 
3854 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3855                                          struct btrfs_root *root,
3856                                          struct inode *inode)
3857 {
3858         int ret;
3859 
3860         ret = btrfs_update_inode(trans, root, inode);
3861         if (ret == -ENOSPC)
3862                 return btrfs_update_inode_item(trans, root, inode);
3863         return ret;
3864 }
3865 
3866 /*
3867  * unlink helper that gets used here in inode.c and in the tree logging
3868  * recovery code.  It remove a link in a directory with a given name, and
3869  * also drops the back refs in the inode to the directory
3870  */
3871 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3872                                 struct btrfs_root *root,
3873                                 struct inode *dir, struct inode *inode,
3874                                 const char *name, int name_len)
3875 {
3876         struct btrfs_path *path;
3877         int ret = 0;
3878         struct extent_buffer *leaf;
3879         struct btrfs_dir_item *di;
3880         struct btrfs_key key;
3881         u64 index;
3882         u64 ino = btrfs_ino(inode);
3883         u64 dir_ino = btrfs_ino(dir);
3884 
3885         path = btrfs_alloc_path();
3886         if (!path) {
3887                 ret = -ENOMEM;
3888                 goto out;
3889         }
3890 
3891         path->leave_spinning = 1;
3892         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3893                                     name, name_len, -1);
3894         if (IS_ERR(di)) {
3895                 ret = PTR_ERR(di);
3896                 goto err;
3897         }
3898         if (!di) {
3899                 ret = -ENOENT;
3900                 goto err;
3901         }
3902         leaf = path->nodes[0];
3903         btrfs_dir_item_key_to_cpu(leaf, di, &key);
3904         ret = btrfs_delete_one_dir_name(trans, root, path, di);
3905         if (ret)
3906                 goto err;
3907         btrfs_release_path(path);
3908 
3909         /*
3910          * If we don't have dir index, we have to get it by looking up
3911          * the inode ref, since we get the inode ref, remove it directly,
3912          * it is unnecessary to do delayed deletion.
3913          *
3914          * But if we have dir index, needn't search inode ref to get it.
3915          * Since the inode ref is close to the inode item, it is better
3916          * that we delay to delete it, and just do this deletion when
3917          * we update the inode item.
3918          */
3919         if (BTRFS_I(inode)->dir_index) {
3920                 ret = btrfs_delayed_delete_inode_ref(inode);
3921                 if (!ret) {
3922                         index = BTRFS_I(inode)->dir_index;
3923                         goto skip_backref;
3924                 }
3925         }
3926 
3927         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3928                                   dir_ino, &index);
3929         if (ret) {
3930                 btrfs_info(root->fs_info,
3931                         "failed to delete reference to %.*s, inode %llu parent %llu",
3932                         name_len, name, ino, dir_ino);
3933                 btrfs_abort_transaction(trans, root, ret);
3934                 goto err;
3935         }
3936 skip_backref:
3937         ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3938         if (ret) {
3939                 btrfs_abort_transaction(trans, root, ret);
3940                 goto err;
3941         }
3942 
3943         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3944                                          inode, dir_ino);
3945         if (ret != 0 && ret != -ENOENT) {
3946                 btrfs_abort_transaction(trans, root, ret);
3947                 goto err;
3948         }
3949 
3950         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3951                                            dir, index);
3952         if (ret == -ENOENT)
3953                 ret = 0;
3954         else if (ret)
3955                 btrfs_abort_transaction(trans, root, ret);
3956 err:
3957         btrfs_free_path(path);
3958         if (ret)
3959                 goto out;
3960 
3961         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3962         inode_inc_iversion(inode);
3963         inode_inc_iversion(dir);
3964         inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3965         ret = btrfs_update_inode(trans, root, dir);
3966 out:
3967         return ret;
3968 }
3969 
3970 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3971                        struct btrfs_root *root,
3972                        struct inode *dir, struct inode *inode,
3973                        const char *name, int name_len)
3974 {
3975         int ret;
3976         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3977         if (!ret) {
3978                 drop_nlink(inode);
3979                 ret = btrfs_update_inode(trans, root, inode);
3980         }
3981         return ret;
3982 }
3983 
3984 /*
3985  * helper to start transaction for unlink and rmdir.
3986  *
3987  * unlink and rmdir are special in btrfs, they do not always free space, so
3988  * if we cannot make our reservations the normal way try and see if there is
3989  * plenty of slack room in the global reserve to migrate, otherwise we cannot
3990  * allow the unlink to occur.
3991  */
3992 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3993 {
3994         struct btrfs_trans_handle *trans;
3995         struct btrfs_root *root = BTRFS_I(dir)->root;
3996         int ret;
3997 
3998         /*
3999          * 1 for the possible orphan item
4000          * 1 for the dir item
4001          * 1 for the dir index
4002          * 1 for the inode ref
4003          * 1 for the inode
4004          */
4005         trans = btrfs_start_transaction(root, 5);
4006         if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
4007                 return trans;
4008 
4009         if (PTR_ERR(trans) == -ENOSPC) {
4010                 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
4011 
4012                 trans = btrfs_start_transaction(root, 0);
4013                 if (IS_ERR(trans))
4014                         return trans;
4015                 ret = btrfs_cond_migrate_bytes(root->fs_info,
4016                                                &root->fs_info->trans_block_rsv,
4017                                                num_bytes, 5);
4018                 if (ret) {
4019                         btrfs_end_transaction(trans, root);
4020                         return ERR_PTR(ret);
4021                 }
4022                 trans->block_rsv = &root->fs_info->trans_block_rsv;
4023                 trans->bytes_reserved = num_bytes;
4024         }
4025         return trans;
4026 }
4027 
4028 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4029 {
4030         struct btrfs_root *root = BTRFS_I(dir)->root;
4031         struct btrfs_trans_handle *trans;
4032         struct inode *inode = d_inode(dentry);
4033         int ret;
4034 
4035         trans = __unlink_start_trans(dir);
4036         if (IS_ERR(trans))
4037                 return PTR_ERR(trans);
4038 
4039         btrfs_record_unlink_dir(trans, dir, d_inode(dentry), 0);
4040 
4041         ret = btrfs_unlink_inode(trans, root, dir, d_inode(dentry),
4042                                  dentry->d_name.name, dentry->d_name.len);
4043         if (ret)
4044                 goto out;
4045 
4046         if (inode->i_nlink == 0) {
4047                 ret = btrfs_orphan_add(trans, inode);
4048                 if (ret)
4049                         goto out;
4050         }
4051 
4052 out:
4053         btrfs_end_transaction(trans, root);
4054         btrfs_btree_balance_dirty(root);
4055         return ret;
4056 }
4057 
4058 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4059                         struct btrfs_root *root,
4060                         struct inode *dir, u64 objectid,
4061                         const char *name, int name_len)
4062 {
4063         struct btrfs_path *path;
4064         struct extent_buffer *leaf;
4065         struct btrfs_dir_item *di;
4066         struct btrfs_key key;
4067         u64 index;
4068         int ret;
4069         u64 dir_ino = btrfs_ino(dir);
4070 
4071         path = btrfs_alloc_path();
4072         if (!path)
4073                 return -ENOMEM;
4074 
4075         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4076                                    name, name_len, -1);
4077         if (IS_ERR_OR_NULL(di)) {
4078                 if (!di)
4079                         ret = -ENOENT;
4080                 else
4081                         ret = PTR_ERR(di);
4082                 goto out;
4083         }
4084 
4085         leaf = path->nodes[0];
4086         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4087         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4088         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4089         if (ret) {
4090                 btrfs_abort_transaction(trans, root, ret);
4091                 goto out;
4092         }
4093         btrfs_release_path(path);
4094 
4095         ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4096                                  objectid, root->root_key.objectid,
4097                                  dir_ino, &index, name, name_len);
4098         if (ret < 0) {
4099                 if (ret != -ENOENT) {
4100                         btrfs_abort_transaction(trans, root, ret);
4101                         goto out;
4102                 }
4103                 di = btrfs_search_dir_index_item(root, path, dir_ino,
4104                                                  name, name_len);
4105                 if (IS_ERR_OR_NULL(di)) {
4106                         if (!di)
4107                                 ret = -ENOENT;
4108                         else
4109                                 ret = PTR_ERR(di);
4110                         btrfs_abort_transaction(trans, root, ret);
4111                         goto out;
4112                 }
4113 
4114                 leaf = path->nodes[0];
4115                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4116                 btrfs_release_path(path);
4117                 index = key.offset;
4118         }
4119         btrfs_release_path(path);
4120 
4121         ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4122         if (ret) {
4123                 btrfs_abort_transaction(trans, root, ret);
4124                 goto out;
4125         }
4126 
4127         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4128         inode_inc_iversion(dir);
4129         dir->i_mtime = dir->i_ctime = CURRENT_TIME;
4130         ret = btrfs_update_inode_fallback(trans, root, dir);
4131         if (ret)
4132                 btrfs_abort_transaction(trans, root, ret);
4133 out:
4134         btrfs_free_path(path);
4135         return ret;
4136 }
4137 
4138 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4139 {
4140         struct inode *inode = d_inode(dentry);
4141         int err = 0;
4142         struct btrfs_root *root = BTRFS_I(dir)->root;
4143         struct btrfs_trans_handle *trans;
4144 
4145         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4146                 return -ENOTEMPTY;
4147         if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4148                 return -EPERM;
4149 
4150         trans = __unlink_start_trans(dir);
4151         if (IS_ERR(trans))
4152                 return PTR_ERR(trans);
4153 
4154         if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4155                 err = btrfs_unlink_subvol(trans, root, dir,
4156                                           BTRFS_I(inode)->location.objectid,
4157                                           dentry->d_name.name,
4158                                           dentry->d_name.len);
4159                 goto out;
4160         }
4161 
4162         err = btrfs_orphan_add(trans, inode);
4163         if (err)
4164                 goto out;
4165 
4166         /* now the directory is empty */
4167         err = btrfs_unlink_inode(trans, root, dir, d_inode(dentry),
4168                                  dentry->d_name.name, dentry->d_name.len);
4169         if (!err)
4170                 btrfs_i_size_write(inode, 0);
4171 out:
4172         btrfs_end_transaction(trans, root);
4173         btrfs_btree_balance_dirty(root);
4174 
4175         return err;
4176 }
4177 
4178 static int truncate_space_check(struct btrfs_trans_handle *trans,
4179                                 struct btrfs_root *root,
4180                                 u64 bytes_deleted)
4181 {
4182         int ret;
4183 
4184         bytes_deleted = btrfs_csum_bytes_to_leaves(root, bytes_deleted);
4185         ret = btrfs_block_rsv_add(root, &root->fs_info->trans_block_rsv,
4186                                   bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4187         if (!ret)
4188                 trans->bytes_reserved += bytes_deleted;
4189         return ret;
4190 
4191 }
4192 
4193 static int truncate_inline_extent(struct inode *inode,
4194                                   struct btrfs_path *path,
4195                                   struct btrfs_key *found_key,
4196                                   const u64 item_end,
4197                                   const u64 new_size)
4198 {
4199         struct extent_buffer *leaf = path->nodes[0];
4200         int slot = path->slots[0];
4201         struct btrfs_file_extent_item *fi;
4202         u32 size = (u32)(new_size - found_key->offset);
4203         struct btrfs_root *root = BTRFS_I(inode)->root;
4204 
4205         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4206 
4207         if (btrfs_file_extent_compression(leaf, fi) != BTRFS_COMPRESS_NONE) {
4208                 loff_t offset = new_size;
4209                 loff_t page_end = ALIGN(offset, PAGE_CACHE_SIZE);
4210 
4211                 /*
4212                  * Zero out the remaining of the last page of our inline extent,
4213                  * instead of directly truncating our inline extent here - that
4214                  * would be much more complex (decompressing all the data, then
4215                  * compressing the truncated data, which might be bigger than
4216                  * the size of the inline extent, resize the extent, etc).
4217                  * We release the path because to get the page we might need to
4218                  * read the extent item from disk (data not in the page cache).
4219                  */
4220                 btrfs_release_path(path);
4221                 return btrfs_truncate_page(inode, offset, page_end - offset, 0);
4222         }
4223 
4224         btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4225         size = btrfs_file_extent_calc_inline_size(size);
4226         btrfs_truncate_item(root, path, size, 1);
4227 
4228         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4229                 inode_sub_bytes(inode, item_end + 1 - new_size);
4230 
4231         return 0;
4232 }
4233 
4234 /*
4235  * this can truncate away extent items, csum items and directory items.
4236  * It starts at a high offset and removes keys until it can't find
4237  * any higher than new_size
4238  *
4239  * csum items that cross the new i_size are truncated to the new size
4240  * as well.
4241  *
4242  * min_type is the minimum key type to truncate down to.  If set to 0, this
4243  * will kill all the items on this inode, including the INODE_ITEM_KEY.
4244  */
4245 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4246                                struct btrfs_root *root,
4247                                struct inode *inode,
4248                                u64 new_size, u32 min_type)
4249 {
4250         struct btrfs_path *path;
4251         struct extent_buffer *leaf;
4252         struct btrfs_file_extent_item *fi;
4253         struct btrfs_key key;
4254         struct btrfs_key found_key;
4255         u64 extent_start = 0;
4256         u64 extent_num_bytes = 0;
4257         u64 extent_offset = 0;
4258         u64 item_end = 0;
4259         u64 last_size = new_size;
4260         u32 found_type = (u8)-1;
4261         int found_extent;
4262         int del_item;
4263         int pending_del_nr = 0;
4264         int pending_del_slot = 0;
4265         int extent_type = -1;
4266         int ret;
4267         int err = 0;
4268         u64 ino = btrfs_ino(inode);
4269         u64 bytes_deleted = 0;
4270         bool be_nice = 0;
4271         bool should_throttle = 0;
4272         bool should_end = 0;
4273 
4274         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4275 
4276         /*
4277          * for non-free space inodes and ref cows, we want to back off from
4278          * time to time
4279          */
4280         if (!btrfs_is_free_space_inode(inode) &&
4281             test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4282                 be_nice = 1;
4283 
4284         path = btrfs_alloc_path();
4285         if (!path)
4286                 return -ENOMEM;
4287         path->reada = -1;
4288 
4289         /*
4290          * We want to drop from the next block forward in case this new size is
4291          * not block aligned since we will be keeping the last block of the
4292          * extent just the way it is.
4293          */
4294         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4295             root == root->fs_info->tree_root)
4296                 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4297                                         root->sectorsize), (u64)-1, 0);
4298 
4299         /*
4300          * This function is also used to drop the items in the log tree before
4301          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4302          * it is used to drop the loged items. So we shouldn't kill the delayed
4303          * items.
4304          */
4305         if (min_type == 0 && root == BTRFS_I(inode)->root)
4306                 btrfs_kill_delayed_inode_items(inode);
4307 
4308         key.objectid = ino;
4309         key.offset = (u64)-1;
4310         key.type = (u8)-1;
4311 
4312 search_again:
4313         /*
4314          * with a 16K leaf size and 128MB extents, you can actually queue
4315          * up a huge file in a single leaf.  Most of the time that
4316          * bytes_deleted is > 0, it will be huge by the time we get here
4317          */
4318         if (be_nice && bytes_deleted > 32 * 1024 * 1024) {
4319                 if (btrfs_should_end_transaction(trans, root)) {
4320                         err = -EAGAIN;
4321                         goto error;
4322                 }
4323         }
4324 
4325 
4326         path->leave_spinning = 1;
4327         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4328         if (ret < 0) {
4329                 err = ret;
4330                 goto out;
4331         }
4332 
4333         if (ret > 0) {
4334                 /* there are no items in the tree for us to truncate, we're
4335                  * done
4336                  */
4337                 if (path->slots[0] == 0)
4338                         goto out;
4339                 path->slots[0]--;
4340         }
4341 
4342         while (1) {
4343                 fi = NULL;
4344                 leaf = path->nodes[0];
4345                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4346                 found_type = found_key.type;
4347 
4348                 if (found_key.objectid != ino)
4349                         break;
4350 
4351                 if (found_type < min_type)
4352                         break;
4353 
4354                 item_end = found_key.offset;
4355                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4356                         fi = btrfs_item_ptr(leaf, path->slots[0],
4357                                             struct btrfs_file_extent_item);
4358                         extent_type = btrfs_file_extent_type(leaf, fi);
4359                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4360                                 item_end +=
4361                                     btrfs_file_extent_num_bytes(leaf, fi);
4362                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4363                                 item_end += btrfs_file_extent_inline_len(leaf,
4364                                                          path->slots[0], fi);
4365                         }
4366                         item_end--;
4367                 }
4368                 if (found_type > min_type) {
4369                         del_item = 1;
4370                 } else {
4371                         if (item_end < new_size)
4372                                 break;
4373                         if (found_key.offset >= new_size)
4374                                 del_item = 1;
4375                         else
4376                                 del_item = 0;
4377                 }
4378                 found_extent = 0;
4379                 /* FIXME, shrink the extent if the ref count is only 1 */
4380                 if (found_type != BTRFS_EXTENT_DATA_KEY)
4381                         goto delete;
4382 
4383                 if (del_item)
4384                         last_size = found_key.offset;
4385                 else
4386                         last_size = new_size;
4387 
4388                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4389                         u64 num_dec;
4390                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4391                         if (!del_item) {
4392                                 u64 orig_num_bytes =
4393                                         btrfs_file_extent_num_bytes(leaf, fi);
4394                                 extent_num_bytes = ALIGN(new_size -
4395                                                 found_key.offset,
4396                                                 root->sectorsize);
4397                                 btrfs_set_file_extent_num_bytes(leaf, fi,
4398                                                          extent_num_bytes);
4399                                 num_dec = (orig_num_bytes -
4400                                            extent_num_bytes);
4401                                 if (test_bit(BTRFS_ROOT_REF_COWS,
4402                                              &root->state) &&
4403                                     extent_start != 0)
4404                                         inode_sub_bytes(inode, num_dec);
4405                                 btrfs_mark_buffer_dirty(leaf);
4406                         } else {
4407                                 extent_num_bytes =
4408                                         btrfs_file_extent_disk_num_bytes(leaf,
4409                                                                          fi);
4410                                 extent_offset = found_key.offset -
4411                                         btrfs_file_extent_offset(leaf, fi);
4412 
4413                                 /* FIXME blocksize != 4096 */
4414                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4415                                 if (extent_start != 0) {
4416                                         found_extent = 1;
4417                                         if (test_bit(BTRFS_ROOT_REF_COWS,
4418                                                      &root->state))
4419                                                 inode_sub_bytes(inode, num_dec);
4420                                 }
4421                         }
4422                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4423                         /*
4424                          * we can't truncate inline items that have had
4425                          * special encodings
4426                          */
4427                         if (!del_item &&
4428                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
4429                             btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4430 
4431                                 /*
4432                                  * Need to release path in order to truncate a
4433                                  * compressed extent. So delete any accumulated
4434                                  * extent items so far.
4435                                  */
4436                                 if (btrfs_file_extent_compression(leaf, fi) !=
4437                                     BTRFS_COMPRESS_NONE && pending_del_nr) {
4438                                         err = btrfs_del_items(trans, root, path,
4439                                                               pending_del_slot,
4440                                                               pending_del_nr);
4441                                         if (err) {
4442                                                 btrfs_abort_transaction(trans,
4443                                                                         root,
4444                                                                         err);
4445                                                 goto error;
4446                                         }
4447                                         pending_del_nr = 0;
4448                                 }
4449 
4450                                 err = truncate_inline_extent(inode, path,
4451                                                              &found_key,
4452                                                              item_end,
4453                                                              new_size);
4454                                 if (err) {
4455                                         btrfs_abort_transaction(trans,
4456                                                                 root, err);
4457                                         goto error;
4458                                 }
4459                         } else if (test_bit(BTRFS_ROOT_REF_COWS,
4460                                             &root->state)) {
4461                                 inode_sub_bytes(inode, item_end + 1 - new_size);
4462                         }
4463                 }
4464 delete:
4465                 if (del_item) {
4466                         if (!pending_del_nr) {
4467                                 /* no pending yet, add ourselves */
4468                                 pending_del_slot = path->slots[0];
4469                                 pending_del_nr = 1;
4470                         } else if (pending_del_nr &&
4471                                    path->slots[0] + 1 == pending_del_slot) {
4472                                 /* hop on the pending chunk */
4473                                 pending_del_nr++;
4474                                 pending_del_slot = path->slots[0];
4475                         } else {
4476                                 BUG();
4477                         }
4478                 } else {
4479                         break;
4480                 }
4481                 should_throttle = 0;
4482 
4483                 if (found_extent &&
4484                     (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4485                      root == root->fs_info->tree_root)) {
4486                         btrfs_set_path_blocking(path);
4487                         bytes_deleted += extent_num_bytes;
4488                         ret = btrfs_free_extent(trans, root, extent_start,
4489                                                 extent_num_bytes, 0,
4490                                                 btrfs_header_owner(leaf),
4491                                                 ino, extent_offset);
4492                         BUG_ON(ret);
4493                         if (btrfs_should_throttle_delayed_refs(trans, root))
4494                                 btrfs_async_run_delayed_refs(root,
4495                                         trans->delayed_ref_updates * 2, 0);
4496                         if (be_nice) {
4497                                 if (truncate_space_check(trans, root,
4498                                                          extent_num_bytes)) {
4499                                         should_end = 1;
4500                                 }
4501                                 if (btrfs_should_throttle_delayed_refs(trans,
4502                                                                        root)) {
4503                                         should_throttle = 1;
4504                                 }
4505                         }
4506                 }
4507 
4508                 if (found_type == BTRFS_INODE_ITEM_KEY)
4509                         break;
4510 
4511                 if (path->slots[0] == 0 ||
4512                     path->slots[0] != pending_del_slot ||
4513                     should_throttle || should_end) {
4514                         if (pending_del_nr) {
4515                                 ret = btrfs_del_items(trans, root, path,
4516                                                 pending_del_slot,
4517                                                 pending_del_nr);
4518                                 if (ret) {
4519                                         btrfs_abort_transaction(trans,
4520                                                                 root, ret);
4521                                         goto error;
4522                                 }
4523                                 pending_del_nr = 0;
4524                         }
4525                         btrfs_release_path(path);
4526                         if (should_throttle) {
4527                                 unsigned long updates = trans->delayed_ref_updates;
4528                                 if (updates) {
4529                                         trans->delayed_ref_updates = 0;
4530                                         ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4531                                         if (ret && !err)
4532                                                 err = ret;
4533                                 }
4534                         }
4535                         /*
4536                          * if we failed to refill our space rsv, bail out
4537                          * and let the transaction restart
4538                          */
4539                         if (should_end) {
4540                                 err = -EAGAIN;
4541                                 goto error;
4542                         }
4543                         goto search_again;
4544                 } else {
4545                         path->slots[0]--;
4546                 }
4547         }
4548 out:
4549         if (pending_del_nr) {
4550                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4551                                       pending_del_nr);
4552                 if (ret)
4553                         btrfs_abort_transaction(trans, root, ret);
4554         }
4555 error:
4556         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4557                 btrfs_ordered_update_i_size(inode, last_size, NULL);
4558 
4559         btrfs_free_path(path);
4560 
4561         if (be_nice && bytes_deleted > 32 * 1024 * 1024) {
4562                 unsigned long updates = trans->delayed_ref_updates;
4563                 if (updates) {
4564                         trans->delayed_ref_updates = 0;
4565                         ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4566                         if (ret && !err)
4567                                 err = ret;
4568                 }
4569         }
4570         return err;
4571 }
4572 
4573 /*
4574  * btrfs_truncate_page - read, zero a chunk and write a page
4575  * @inode - inode that we're zeroing
4576  * @from - the offset to start zeroing
4577  * @len - the length to zero, 0 to zero the entire range respective to the
4578  *      offset
4579  * @front - zero up to the offset instead of from the offset on
4580  *
4581  * This will find the page for the "from" offset and cow the page and zero the
4582  * part we want to zero.  This is used with truncate and hole punching.
4583  */
4584 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4585                         int front)
4586 {
4587         struct address_space *mapping = inode->i_mapping;
4588         struct btrfs_root *root = BTRFS_I(inode)->root;
4589         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4590         struct btrfs_ordered_extent *ordered;
4591         struct extent_state *cached_state = NULL;
4592         char *kaddr;
4593         u32 blocksize = root->sectorsize;
4594         pgoff_t index = from >> PAGE_CACHE_SHIFT;
4595         unsigned offset = from & (PAGE_CACHE_SIZE-1);
4596         struct page *page;
4597         gfp_t mask = btrfs_alloc_write_mask(mapping);
4598         int ret = 0;
4599         u64 page_start;
4600         u64 page_end;
4601 
4602         if ((offset & (blocksize - 1)) == 0 &&
4603             (!len || ((len & (blocksize - 1)) == 0)))
4604                 goto out;
4605         ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4606         if (ret)
4607                 goto out;
4608 
4609 again:
4610         page = find_or_create_page(mapping, index, mask);
4611         if (!page) {
4612                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4613                 ret = -ENOMEM;
4614                 goto out;
4615         }
4616 
4617         page_start = page_offset(page);
4618         page_end = page_start + PAGE_CACHE_SIZE - 1;
4619 
4620         if (!PageUptodate(page)) {
4621                 ret = btrfs_readpage(NULL, page);
4622                 lock_page(page);
4623                 if (page->mapping != mapping) {
4624                         unlock_page(page);
4625                         page_cache_release(page);
4626                         goto again;
4627                 }
4628                 if (!PageUptodate(page)) {
4629                         ret = -EIO;
4630                         goto out_unlock;
4631                 }
4632         }
4633         wait_on_page_writeback(page);
4634 
4635         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4636         set_page_extent_mapped(page);
4637 
4638         ordered = btrfs_lookup_ordered_extent(inode, page_start);
4639         if (ordered) {
4640                 unlock_extent_cached(io_tree, page_start, page_end,
4641                                      &cached_state, GFP_NOFS);
4642                 unlock_page(page);
4643                 page_cache_release(page);
4644                 btrfs_start_ordered_extent(inode, ordered, 1);
4645                 btrfs_put_ordered_extent(ordered);
4646                 goto again;
4647         }
4648 
4649         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4650                           EXTENT_DIRTY | EXTENT_DELALLOC |
4651                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4652                           0, 0, &cached_state, GFP_NOFS);
4653 
4654         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4655                                         &cached_state);
4656         if (ret) {
4657                 unlock_extent_cached(io_tree, page_start, page_end,
4658                                      &cached_state, GFP_NOFS);
4659                 goto out_unlock;
4660         }
4661 
4662         if (offset != PAGE_CACHE_SIZE) {
4663                 if (!len)
4664                         len = PAGE_CACHE_SIZE - offset;
4665                 kaddr = kmap(page);
4666                 if (front)
4667                         memset(kaddr, 0, offset);
4668                 else
4669                         memset(kaddr + offset, 0, len);
4670                 flush_dcache_page(page);
4671                 kunmap(page);
4672         }
4673         ClearPageChecked(page);
4674         set_page_dirty(page);
4675         unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4676                              GFP_NOFS);
4677 
4678 out_unlock:
4679         if (ret)
4680                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4681         unlock_page(page);
4682         page_cache_release(page);
4683 out:
4684         return ret;
4685 }
4686 
4687 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4688                              u64 offset, u64 len)
4689 {
4690         struct btrfs_trans_handle *trans;
4691         int ret;
4692 
4693         /*
4694          * Still need to make sure the inode looks like it's been updated so
4695          * that any holes get logged if we fsync.
4696          */
4697         if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4698                 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4699                 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4700                 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4701                 return 0;
4702         }
4703 
4704         /*
4705          * 1 - for the one we're dropping
4706          * 1 - for the one we're adding
4707          * 1 - for updating the inode.
4708          */
4709         trans = btrfs_start_transaction(root, 3);
4710         if (IS_ERR(trans))
4711                 return PTR_ERR(trans);
4712 
4713         ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4714         if (ret) {
4715                 btrfs_abort_transaction(trans, root, ret);
4716                 btrfs_end_transaction(trans, root);
4717                 return ret;
4718         }
4719 
4720         ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4721                                        0, 0, len, 0, len, 0, 0, 0);
4722         if (ret)
4723                 btrfs_abort_transaction(trans, root, ret);
4724         else
4725                 btrfs_update_inode(trans, root, inode);
4726         btrfs_end_transaction(trans, root);
4727         return ret;
4728 }
4729 
4730 /*
4731  * This function puts in dummy file extents for the area we're creating a hole
4732  * for.  So if we are truncating this file to a larger size we need to insert
4733  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4734  * the range between oldsize and size
4735  */
4736 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4737 {
4738         struct btrfs_root *root = BTRFS_I(inode)->root;
4739         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4740         struct extent_map *em = NULL;
4741         struct extent_state *cached_state = NULL;
4742         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4743         u64 hole_start = ALIGN(oldsize, root->sectorsize);
4744         u64 block_end = ALIGN(size, root->sectorsize);
4745         u64 last_byte;
4746         u64 cur_offset;
4747         u64 hole_size;
4748         int err = 0;
4749 
4750         /*
4751          * If our size started in the middle of a page we need to zero out the
4752          * rest of the page before we expand the i_size, otherwise we could
4753          * expose stale data.
4754          */
4755         err = btrfs_truncate_page(inode, oldsize, 0, 0);
4756         if (err)
4757                 return err;
4758 
4759         if (size <= hole_start)
4760                 return 0;
4761 
4762         while (1) {
4763                 struct btrfs_ordered_extent *ordered;
4764 
4765                 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4766                                  &cached_state);
4767                 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4768                                                      block_end - hole_start);
4769                 if (!ordered)
4770                         break;
4771                 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4772                                      &cached_state, GFP_NOFS);
4773                 btrfs_start_ordered_extent(inode, ordered, 1);
4774                 btrfs_put_ordered_extent(ordered);
4775         }
4776 
4777         cur_offset = hole_start;
4778         while (1) {
4779                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4780                                 block_end - cur_offset, 0);
4781                 if (IS_ERR(em)) {
4782                         err = PTR_ERR(em);
4783                         em = NULL;
4784                         break;
4785                 }
4786                 last_byte = min(extent_map_end(em), block_end);
4787                 last_byte = ALIGN(last_byte , root->sectorsize);
4788                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4789                         struct extent_map *hole_em;
4790                         hole_size = last_byte - cur_offset;
4791 
4792                         err = maybe_insert_hole(root, inode, cur_offset,
4793                                                 hole_size);
4794                         if (err)
4795                                 break;
4796                         btrfs_drop_extent_cache(inode, cur_offset,
4797                                                 cur_offset + hole_size - 1, 0);
4798                         hole_em = alloc_extent_map();
4799                         if (!hole_em) {
4800                                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4801                                         &BTRFS_I(inode)->runtime_flags);
4802                                 goto next;
4803                         }
4804                         hole_em->start = cur_offset;
4805                         hole_em->len = hole_size;
4806                         hole_em->orig_start = cur_offset;
4807 
4808                         hole_em->block_start = EXTENT_MAP_HOLE;
4809                         hole_em->block_len = 0;
4810                         hole_em->orig_block_len = 0;
4811                         hole_em->ram_bytes = hole_size;
4812                         hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4813                         hole_em->compress_type = BTRFS_COMPRESS_NONE;
4814                         hole_em->generation = root->fs_info->generation;
4815 
4816                         while (1) {
4817                                 write_lock(&em_tree->lock);
4818                                 err = add_extent_mapping(em_tree, hole_em, 1);
4819                                 write_unlock(&em_tree->lock);
4820                                 if (err != -EEXIST)
4821                                         break;
4822                                 btrfs_drop_extent_cache(inode, cur_offset,
4823                                                         cur_offset +
4824                                                         hole_size - 1, 0);
4825                         }
4826                         free_extent_map(hole_em);
4827                 }
4828 next:
4829                 free_extent_map(em);
4830                 em = NULL;
4831                 cur_offset = last_byte;
4832                 if (cur_offset >= block_end)
4833                         break;
4834         }
4835         free_extent_map(em);
4836         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4837                              GFP_NOFS);
4838         return err;
4839 }
4840 
4841 static int wait_snapshoting_atomic_t(atomic_t *a)
4842 {
4843         schedule();
4844         return 0;
4845 }
4846 
4847 static void wait_for_snapshot_creation(struct btrfs_root *root)
4848 {
4849         while (true) {
4850                 int ret;
4851 
4852                 ret = btrfs_start_write_no_snapshoting(root);
4853                 if (ret)
4854                         break;
4855                 wait_on_atomic_t(&root->will_be_snapshoted,
4856                                  wait_snapshoting_atomic_t,
4857                                  TASK_UNINTERRUPTIBLE);
4858         }
4859 }
4860 
4861 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4862 {
4863         struct btrfs_root *root = BTRFS_I(inode)->root;
4864         struct btrfs_trans_handle *trans;
4865         loff_t oldsize = i_size_read(inode);
4866         loff_t newsize = attr->ia_size;
4867         int mask = attr->ia_valid;
4868         int ret;
4869 
4870         /*
4871          * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4872          * special case where we need to update the times despite not having
4873          * these flags set.  For all other operations the VFS set these flags
4874          * explicitly if it wants a timestamp update.
4875          */
4876         if (newsize != oldsize) {
4877                 inode_inc_iversion(inode);
4878                 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4879                         inode->i_ctime = inode->i_mtime =
4880                                 current_fs_time(inode->i_sb);
4881         }
4882 
4883         if (newsize > oldsize) {
4884                 truncate_pagecache(inode, newsize);
4885                 /*
4886                  * Don't do an expanding truncate while snapshoting is ongoing.
4887                  * This is to ensure the snapshot captures a fully consistent
4888                  * state of this file - if the snapshot captures this expanding
4889                  * truncation, it must capture all writes that happened before
4890                  * this truncation.
4891                  */
4892                 wait_for_snapshot_creation(root);
4893                 ret = btrfs_cont_expand(inode, oldsize, newsize);
4894                 if (ret) {
4895                         btrfs_end_write_no_snapshoting(root);
4896                         return ret;
4897                 }
4898 
4899                 trans = btrfs_start_transaction(root, 1);
4900                 if (IS_ERR(trans)) {
4901                         btrfs_end_write_no_snapshoting(root);
4902                         return PTR_ERR(trans);
4903                 }
4904 
4905                 i_size_write(inode, newsize);
4906                 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4907                 ret = btrfs_update_inode(trans, root, inode);
4908                 btrfs_end_write_no_snapshoting(root);
4909                 btrfs_end_transaction(trans, root);
4910         } else {
4911 
4912                 /*
4913                  * We're truncating a file that used to have good data down to
4914                  * zero. Make sure it gets into the ordered flush list so that
4915                  * any new writes get down to disk quickly.
4916                  */
4917                 if (newsize == 0)
4918                         set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4919                                 &BTRFS_I(inode)->runtime_flags);
4920 
4921                 /*
4922                  * 1 for the orphan item we're going to add
4923                  * 1 for the orphan item deletion.
4924                  */
4925                 trans = btrfs_start_transaction(root, 2);
4926                 if (IS_ERR(trans))
4927                         return PTR_ERR(trans);
4928 
4929                 /*
4930                  * We need to do this in case we fail at _any_ point during the
4931                  * actual truncate.  Once we do the truncate_setsize we could
4932                  * invalidate pages which forces any outstanding ordered io to
4933                  * be instantly completed which will give us extents that need
4934                  * to be truncated.  If we fail to get an orphan inode down we
4935                  * could have left over extents that were never meant to live,
4936                  * so we need to garuntee from this point on that everything
4937                  * will be consistent.
4938                  */
4939                 ret = btrfs_orphan_add(trans, inode);
4940                 btrfs_end_transaction(trans, root);
4941                 if (ret)
4942                         return ret;
4943 
4944                 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4945                 truncate_setsize(inode, newsize);
4946 
4947                 /* Disable nonlocked read DIO to avoid the end less truncate */
4948                 btrfs_inode_block_unlocked_dio(inode);
4949                 inode_dio_wait(inode);
4950                 btrfs_inode_resume_unlocked_dio(inode);
4951 
4952                 ret = btrfs_truncate(inode);
4953                 if (ret && inode->i_nlink) {
4954                         int err;
4955 
4956                         /*
4957                          * failed to truncate, disk_i_size is only adjusted down
4958                          * as we remove extents, so it should represent the true
4959                          * size of the inode, so reset the in memory size and
4960                          * delete our orphan entry.
4961                          */
4962                         trans = btrfs_join_transaction(root);
4963                         if (IS_ERR(trans)) {
4964                                 btrfs_orphan_del(NULL, inode);
4965                                 return ret;
4966                         }
4967                         i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4968                         err = btrfs_orphan_del(trans, inode);
4969                         if (err)
4970                                 btrfs_abort_transaction(trans, root, err);
4971                         btrfs_end_transaction(trans, root);
4972                 }
4973         }
4974 
4975         return ret;
4976 }
4977 
4978 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4979 {
4980         struct inode *inode = d_inode(dentry);
4981         struct btrfs_root *root = BTRFS_I(inode)->root;
4982         int err;
4983 
4984         if (btrfs_root_readonly(root))
4985                 return -EROFS;
4986 
4987         err = inode_change_ok(inode, attr);
4988         if (err)
4989                 return err;
4990 
4991         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4992                 err = btrfs_setsize(inode, attr);
4993                 if (err)
4994                         return err;
4995         }
4996 
4997         if (attr->ia_valid) {
4998                 setattr_copy(inode, attr);
4999                 inode_inc_iversion(inode);
5000                 err = btrfs_dirty_inode(inode);
5001 
5002                 if (!err && attr->ia_valid & ATTR_MODE)
5003                         err = posix_acl_chmod(inode, inode->i_mode);
5004         }
5005 
5006         return err;
5007 }
5008 
5009 /*
5010  * While truncating the inode pages during eviction, we get the VFS calling
5011  * btrfs_invalidatepage() against each page of the inode. This is slow because
5012  * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5013  * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5014  * extent_state structures over and over, wasting lots of time.
5015  *
5016  * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5017  * those expensive operations on a per page basis and do only the ordered io
5018  * finishing, while we release here the extent_map and extent_state structures,
5019  * without the excessive merging and splitting.
5020  */
5021 static void evict_inode_truncate_pages(struct inode *inode)
5022 {
5023         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5024         struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5025         struct rb_node *node;
5026 
5027         ASSERT(inode->i_state & I_FREEING);
5028         truncate_inode_pages_final(&inode->i_data);
5029 
5030         write_lock(&map_tree->lock);
5031         while (!RB_EMPTY_ROOT(&map_tree->map)) {
5032                 struct extent_map *em;
5033 
5034                 node = rb_first(&map_tree->map);
5035                 em = rb_entry(node, struct extent_map, rb_node);
5036                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5037                 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5038                 remove_extent_mapping(map_tree, em);
5039                 free_extent_map(em);
5040                 if (need_resched()) {
5041                         write_unlock(&map_tree->lock);
5042                         cond_resched();
5043                         write_lock(&map_tree->lock);
5044                 }
5045         }
5046         write_unlock(&map_tree->lock);
5047 
5048         /*
5049          * Keep looping until we have no more ranges in the io tree.
5050          * We can have ongoing bios started by readpages (called from readahead)
5051          * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5052          * still in progress (unlocked the pages in the bio but did not yet
5053          * unlocked the ranges in the io tree). Therefore this means some
5054          * ranges can still be locked and eviction started because before
5055          * submitting those bios, which are executed by a separate task (work
5056          * queue kthread), inode references (inode->i_count) were not taken
5057          * (which would be dropped in the end io callback of each bio).
5058          * Therefore here we effectively end up waiting for those bios and
5059          * anyone else holding locked ranges without having bumped the inode's
5060          * reference count - if we don't do it, when they access the inode's
5061          * io_tree to unlock a range it may be too late, leading to an
5062          * use-after-free issue.
5063          */
5064         spin_lock(&io_tree->lock);
5065         while (!RB_EMPTY_ROOT(&io_tree->state)) {
5066                 struct extent_state *state;
5067                 struct extent_state *cached_state = NULL;
5068                 u64 start;
5069                 u64 end;
5070 
5071                 node = rb_first(&io_tree->state);
5072                 state = rb_entry(node, struct extent_state, rb_node);
5073                 start = state->start;
5074                 end = state->end;
5075                 spin_unlock(&io_tree->lock);
5076 
5077                 lock_extent_bits(io_tree, start, end, 0, &cached_state);
5078                 clear_extent_bit(io_tree, start, end,
5079                                  EXTENT_LOCKED | EXTENT_DIRTY |
5080                                  EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5081                                  EXTENT_DEFRAG, 1, 1,
5082                                  &cached_state, GFP_NOFS);
5083 
5084                 cond_resched();
5085                 spin_lock(&io_tree->lock);
5086         }
5087         spin_unlock(&io_tree->lock);
5088 }
5089 
5090 void btrfs_evict_inode(struct inode *inode)
5091 {
5092         struct btrfs_trans_handle *trans;
5093         struct btrfs_root *root = BTRFS_I(inode)->root;
5094         struct btrfs_block_rsv *rsv, *global_rsv;
5095         int steal_from_global = 0;
5096         u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
5097         int ret;
5098 
5099         trace_btrfs_inode_evict(inode);
5100 
5101         evict_inode_truncate_pages(inode);
5102 
5103         if (inode->i_nlink &&
5104             ((btrfs_root_refs(&root->root_item) != 0 &&
5105               root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5106              btrfs_is_free_space_inode(inode)))
5107                 goto no_delete;
5108 
5109         if (is_bad_inode(inode)) {
5110                 btrfs_orphan_del(NULL, inode);
5111                 goto no_delete;
5112         }
5113         /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5114         if (!special_file(inode->i_mode))
5115                 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5116 
5117         btrfs_free_io_failure_record(inode, 0, (u64)-1);
5118 
5119         if (root->fs_info->log_root_recovering) {
5120                 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5121                                  &BTRFS_I(inode)->runtime_flags));
5122                 goto no_delete;
5123         }
5124 
5125         if (inode->i_nlink > 0) {
5126                 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5127                        root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5128                 goto no_delete;
5129         }
5130 
5131         ret = btrfs_commit_inode_delayed_inode(inode);
5132         if (ret) {
5133                 btrfs_orphan_del(NULL, inode);
5134                 goto no_delete;
5135         }
5136 
5137         rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
5138         if (!rsv) {
5139                 btrfs_orphan_del(NULL, inode);
5140                 goto no_delete;
5141         }
5142         rsv->size = min_size;
5143         rsv->failfast = 1;
5144         global_rsv = &root->fs_info->global_block_rsv;
5145 
5146         btrfs_i_size_write(inode, 0);
5147 
5148         /*
5149          * This is a bit simpler than btrfs_truncate since we've already
5150          * reserved our space for our orphan item in the unlink, so we just
5151          * need to reserve some slack space in case we add bytes and update
5152          * inode item when doing the truncate.
5153          */
5154         while (1) {
5155                 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5156                                              BTRFS_RESERVE_FLUSH_LIMIT);
5157 
5158                 /*
5159                  * Try and steal from the global reserve since we will
5160                  * likely not use this space anyway, we want to try as
5161                  * hard as possible to get this to work.
5162                  */
5163                 if (ret)
5164                         steal_from_global++;
5165                 else
5166                         steal_from_global = 0;
5167                 ret = 0;
5168 
5169                 /*
5170                  * steal_from_global == 0: we reserved stuff, hooray!
5171                  * steal_from_global == 1: we didn't reserve stuff, boo!
5172                  * steal_from_global == 2: we've committed, still not a lot of
5173                  * room but maybe we'll have room in the global reserve this
5174                  * time.
5175                  * steal_from_global == 3: abandon all hope!
5176                  */
5177                 if (steal_from_global > 2) {
5178                         btrfs_warn(root->fs_info,
5179                                 "Could not get space for a delete, will truncate on mount %d",
5180                                 ret);
5181                         btrfs_orphan_del(NULL, inode);
5182                         btrfs_free_block_rsv(root, rsv);
5183                         goto no_delete;
5184                 }
5185 
5186                 trans = btrfs_join_transaction(root);
5187                 if (IS_ERR(trans)) {
5188                         btrfs_orphan_del(NULL, inode);
5189                         btrfs_free_block_rsv(root, rsv);
5190                         goto no_delete;
5191                 }
5192 
5193                 /*
5194                  * We can't just steal from the global reserve, we need tomake
5195                  * sure there is room to do it, if not we need to commit and try
5196                  * again.
5197                  */
5198                 if (steal_from_global) {
5199                         if (!btrfs_check_space_for_delayed_refs(trans, root))
5200                                 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5201                                                               min_size);
5202                         else
5203                                 ret = -ENOSPC;
5204                 }
5205 
5206                 /*
5207                  * Couldn't steal from the global reserve, we have too much
5208                  * pending stuff built up, commit the transaction and try it
5209                  * again.
5210                  */
5211                 if (ret) {
5212                         ret = btrfs_commit_transaction(trans, root);
5213                         if (ret) {
5214                                 btrfs_orphan_del(NULL, inode);
5215                                 btrfs_free_block_rsv(root, rsv);
5216                                 goto no_delete;
5217                         }
5218                         continue;
5219                 } else {
5220                         steal_from_global = 0;
5221                 }
5222 
5223                 trans->block_rsv = rsv;
5224 
5225                 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5226                 if (ret != -ENOSPC && ret != -EAGAIN)
5227                         break;
5228 
5229                 trans->block_rsv = &root->fs_info->trans_block_rsv;
5230                 btrfs_end_transaction(trans, root);
5231                 trans = NULL;
5232                 btrfs_btree_balance_dirty(root);
5233         }
5234 
5235         btrfs_free_block_rsv(root, rsv);
5236 
5237         /*
5238          * Errors here aren't a big deal, it just means we leave orphan items
5239          * in the tree.  They will be cleaned up on the next mount.
5240          */
5241         if (ret == 0) {
5242                 trans->block_rsv = root->orphan_block_rsv;
5243                 btrfs_orphan_del(trans, inode);
5244         } else {
5245                 btrfs_orphan_del(NULL, inode);
5246         }
5247 
5248         trans->block_rsv = &root->fs_info->trans_block_rsv;
5249         if (!(root == root->fs_info->tree_root ||
5250               root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5251                 btrfs_return_ino(root, btrfs_ino(inode));
5252 
5253         btrfs_end_transaction(trans, root);
5254         btrfs_btree_balance_dirty(root);
5255 no_delete:
5256         btrfs_remove_delayed_node(inode);
5257         clear_inode(inode);
5258         return;
5259 }
5260 
5261 /*
5262  * this returns the key found in the dir entry in the location pointer.
5263  * If no dir entries were found, location->objectid is 0.
5264  */
5265 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5266                                struct btrfs_key *location)
5267 {
5268         const char *name = dentry->d_name.name;
5269         int namelen = dentry->d_name.len;
5270         struct btrfs_dir_item *di;
5271         struct btrfs_path *path;
5272         struct btrfs_root *root = BTRFS_I(dir)->root;
5273         int ret = 0;
5274 
5275         path = btrfs_alloc_path();
5276         if (!path)
5277                 return -ENOMEM;
5278 
5279         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
5280                                     namelen, 0);
5281         if (IS_ERR(di))
5282                 ret = PTR_ERR(di);
5283 
5284         if (IS_ERR_OR_NULL(di))
5285                 goto out_err;
5286 
5287         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5288 out:
5289         btrfs_free_path(path);
5290         return ret;
5291 out_err:
5292         location->objectid = 0;
5293         goto out;
5294 }
5295 
5296 /*
5297  * when we hit a tree root in a directory, the btrfs part of the inode
5298  * needs to be changed to reflect the root directory of the tree root.  This
5299  * is kind of like crossing a mount point.
5300  */
5301 static int fixup_tree_root_location(struct btrfs_root *root,
5302                                     struct inode *dir,
5303                                     struct dentry *dentry,
5304                                     struct btrfs_key *location,
5305                                     struct btrfs_root **sub_root)
5306 {
5307         struct btrfs_path *path;
5308         struct btrfs_root *new_root;
5309         struct btrfs_root_ref *ref;
5310         struct extent_buffer *leaf;
5311         struct btrfs_key key;
5312         int ret;
5313         int err = 0;
5314 
5315         path = btrfs_alloc_path();
5316         if (!path) {
5317                 err = -ENOMEM;
5318                 goto out;
5319         }
5320 
5321         err = -ENOENT;
5322         key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5323         key.type = BTRFS_ROOT_REF_KEY;
5324         key.offset = location->objectid;
5325 
5326         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, path,
5327                                 0, 0);
5328         if (ret) {
5329                 if (ret < 0)
5330                         err = ret;
5331                 goto out;
5332         }
5333 
5334         leaf = path->nodes[0];
5335         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5336         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5337             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5338                 goto out;
5339 
5340         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5341                                    (unsigned long)(ref + 1),
5342                                    dentry->d_name.len);
5343         if (ret)
5344                 goto out;
5345 
5346         btrfs_release_path(path);
5347 
5348         new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
5349         if (IS_ERR(new_root)) {
5350                 err = PTR_ERR(new_root);
5351                 goto out;
5352         }
5353 
5354         *sub_root = new_root;
5355         location->objectid = btrfs_root_dirid(&new_root->root_item);
5356         location->type = BTRFS_INODE_ITEM_KEY;
5357         location->offset = 0;
5358         err = 0;
5359 out:
5360         btrfs_free_path(path);
5361         return err;
5362 }
5363 
5364 static void inode_tree_add(struct inode *inode)
5365 {
5366         struct btrfs_root *root = BTRFS_I(inode)->root;
5367         struct btrfs_inode *entry;
5368         struct rb_node **p;
5369         struct rb_node *parent;
5370         struct rb_node *new = &BTRFS_I(inode)->rb_node;
5371         u64 ino = btrfs_ino(inode);
5372 
5373         if (inode_unhashed(inode))
5374                 return;
5375         parent = NULL;
5376         spin_lock(&root->inode_lock);
5377         p = &root->inode_tree.rb_node;
5378         while (*p) {
5379                 parent = *p;
5380                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5381 
5382                 if (ino < btrfs_ino(&entry->vfs_inode))
5383                         p = &parent->rb_left;
5384                 else if (ino > btrfs_ino(&entry->vfs_inode))
5385                         p = &parent->rb_right;
5386                 else {
5387                         WARN_ON(!(entry->vfs_inode.i_state &
5388                                   (I_WILL_FREE | I_FREEING)));
5389                         rb_replace_node(parent, new, &root->inode_tree);
5390                         RB_CLEAR_NODE(parent);
5391                         spin_unlock(&root->inode_lock);
5392                         return;
5393                 }
5394         }
5395         rb_link_node(new, parent, p);
5396         rb_insert_color(new, &root->inode_tree);
5397         spin_unlock(&root->inode_lock);
5398 }
5399 
5400 static void inode_tree_del(struct inode *inode)
5401 {
5402         struct btrfs_root *root = BTRFS_I(inode)->root;
5403         int empty = 0;
5404 
5405         spin_lock(&root->inode_lock);
5406         if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5407                 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5408                 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5409                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5410         }
5411         spin_unlock(&root->inode_lock);
5412 
5413         if (empty && btrfs_root_refs(&root->root_item) == 0) {
5414                 synchronize_srcu(&root->fs_info->subvol_srcu);
5415                 spin_lock(&root->inode_lock);
5416                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5417                 spin_unlock(&root->inode_lock);
5418                 if (empty)
5419                         btrfs_add_dead_root(root);
5420         }
5421 }
5422 
5423 void btrfs_invalidate_inodes(struct btrfs_root *root)
5424 {
5425         struct rb_node *node;
5426         struct rb_node *prev;
5427         struct btrfs_inode *entry;
5428         struct inode *inode;
5429         u64 objectid = 0;
5430 
5431         if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5432                 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5433 
5434         spin_lock(&root->inode_lock);
5435 again:
5436         node = root->inode_tree.rb_node;
5437         prev = NULL;
5438         while (node) {
5439                 prev = node;
5440                 entry = rb_entry(node, struct btrfs_inode, rb_node);
5441 
5442                 if (objectid < btrfs_ino(&entry->vfs_inode))
5443                         node = node->rb_left;
5444                 else if (objectid > btrfs_ino(&entry->vfs_inode))
5445                         node = node->rb_right;
5446                 else
5447                         break;
5448         }
5449         if (!node) {
5450                 while (prev) {
5451                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
5452                         if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5453                                 node = prev;
5454                                 break;
5455                         }
5456                         prev = rb_next(prev);
5457                 }
5458         }
5459         while (node) {
5460                 entry = rb_entry(node, struct btrfs_inode, rb_node);
5461                 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5462                 inode = igrab(&entry->vfs_inode);
5463                 if (inode) {
5464                         spin_unlock(&root->inode_lock);
5465                         if (atomic_read(&inode->i_count) > 1)
5466                                 d_prune_aliases(inode);
5467                         /*
5468                          * btrfs_drop_inode will have it removed from
5469                          * the inode cache when its usage count
5470                          * hits zero.
5471                          */
5472                         iput(inode);
5473                         cond_resched();
5474                         spin_lock(&root->inode_lock);
5475                         goto again;
5476                 }
5477 
5478                 if (cond_resched_lock(&root->inode_lock))
5479                         goto again;
5480 
5481                 node = rb_next(node);
5482         }
5483         spin_unlock(&root->inode_lock);
5484 }
5485 
5486 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5487 {
5488         struct btrfs_iget_args *args = p;
5489         inode->i_ino = args->location->objectid;
5490         memcpy(&BTRFS_I(inode)->location, args->location,
5491                sizeof(*args->location));
5492         BTRFS_I(inode)->root = args->root;
5493         return 0;
5494 }
5495 
5496 static int btrfs_find_actor(struct inode *inode, void *opaque)
5497 {
5498         struct btrfs_iget_args *args = opaque;
5499         return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5500                 args->root == BTRFS_I(inode)->root;
5501 }
5502 
5503 static struct inode *btrfs_iget_locked(struct super_block *s,
5504                                        struct btrfs_key *location,
5505                                        struct btrfs_root *root)
5506 {
5507         struct inode *inode;
5508         struct btrfs_iget_args args;
5509         unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5510 
5511         args.location = location;
5512         args.root = root;
5513 
5514         inode = iget5_locked(s, hashval, btrfs_find_actor,
5515                              btrfs_init_locked_inode,
5516                              (void *)&args);
5517         return inode;
5518 }
5519 
5520 /* Get an inode object given its location and corresponding root.
5521  * Returns in *is_new if the inode was read from disk
5522  */
5523 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5524                          struct btrfs_root *root, int *new)
5525 {
5526         struct inode *inode;
5527 
5528         inode = btrfs_iget_locked(s, location, root);
5529         if (!inode)
5530                 return ERR_PTR(-ENOMEM);
5531 
5532         if (inode->i_state & I_NEW) {
5533                 btrfs_read_locked_inode(inode);
5534                 if (!is_bad_inode(inode)) {
5535                         inode_tree_add(inode);
5536                         unlock_new_inode(inode);
5537                         if (new)
5538                                 *new = 1;
5539                 } else {
5540                         unlock_new_inode(inode);
5541                         iput(inode);
5542                         inode = ERR_PTR(-ESTALE);
5543                 }
5544         }
5545 
5546         return inode;
5547 }
5548 
5549 static struct inode *new_simple_dir(struct super_block *s,
5550                                     struct btrfs_key *key,
5551                                     struct btrfs_root *root)
5552 {
5553         struct inode *inode = new_inode(s);
5554 
5555         if (!inode)
5556                 return ERR_PTR(-ENOMEM);
5557 
5558         BTRFS_I(inode)->root = root;
5559         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5560         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5561 
5562         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5563         inode->i_op = &btrfs_dir_ro_inode_operations;
5564         inode->i_fop = &simple_dir_operations;
5565         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5566         inode->i_mtime = CURRENT_TIME;
5567         inode->i_atime = inode->i_mtime;
5568         inode->i_ctime = inode->i_mtime;
5569         BTRFS_I(inode)->i_otime = inode->i_mtime;
5570 
5571         return inode;
5572 }
5573 
5574 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5575 {
5576         struct inode *inode;
5577         struct btrfs_root *root = BTRFS_I(dir)->root;
5578         struct btrfs_root *sub_root = root;
5579         struct btrfs_key location;
5580         int index;
5581         int ret = 0;
5582 
5583         if (dentry->d_name.len > BTRFS_NAME_LEN)
5584                 return ERR_PTR(-ENAMETOOLONG);
5585 
5586         ret = btrfs_inode_by_name(dir, dentry, &location);
5587         if (ret < 0)
5588                 return ERR_PTR(ret);
5589 
5590         if (location.objectid == 0)
5591                 return ERR_PTR(-ENOENT);
5592 
5593         if (location.type == BTRFS_INODE_ITEM_KEY) {
5594                 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5595                 return inode;
5596         }
5597 
5598         BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5599 
5600         index = srcu_read_lock(&root->fs_info->subvol_srcu);
5601         ret = fixup_tree_root_location(root, dir, dentry,
5602                                        &location, &sub_root);
5603         if (ret < 0) {
5604                 if (ret != -ENOENT)
5605                         inode = ERR_PTR(ret);
5606                 else
5607                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
5608         } else {
5609                 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5610         }
5611         srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5612 
5613         if (!IS_ERR(inode) && root != sub_root) {
5614                 down_read(&root->fs_info->cleanup_work_sem);
5615                 if (!(inode->i_sb->s_flags & MS_RDONLY))
5616                         ret = btrfs_orphan_cleanup(sub_root);
5617                 up_read(&root->fs_info->cleanup_work_sem);
5618                 if (ret) {
5619                         iput(inode);
5620                         inode = ERR_PTR(ret);
5621                 }
5622         }
5623 
5624         return inode;
5625 }
5626 
5627 static int btrfs_dentry_delete(const struct dentry *dentry)
5628 {
5629         struct btrfs_root *root;
5630         struct inode *inode = d_inode(dentry);
5631 
5632         if (!inode && !IS_ROOT(dentry))
5633                 inode = d_inode(dentry->d_parent);
5634 
5635         if (inode) {
5636                 root = BTRFS_I(inode)->root;
5637                 if (btrfs_root_refs(&root->root_item) == 0)
5638                         return 1;
5639 
5640                 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5641                         return 1;
5642         }
5643         return 0;
5644 }
5645 
5646 static void btrfs_dentry_release(struct dentry *dentry)
5647 {
5648         kfree(dentry->d_fsdata);
5649 }
5650 
5651 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5652                                    unsigned int flags)
5653 {
5654         struct inode *inode;
5655 
5656         inode = btrfs_lookup_dentry(dir, dentry);
5657         if (IS_ERR(inode)) {
5658                 if (PTR_ERR(inode) == -ENOENT)
5659                         inode = NULL;
5660                 else
5661                         return ERR_CAST(inode);
5662         }
5663 
5664         return d_splice_alias(inode, dentry);
5665 }
5666 
5667 unsigned char btrfs_filetype_table[] = {
5668         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5669 };
5670 
5671 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5672 {
5673         struct inode *inode = file_inode(file);
5674         struct btrfs_root *root = BTRFS_I(inode)->root;
5675         struct btrfs_item *item;
5676         struct btrfs_dir_item *di;
5677         struct btrfs_key key;
5678         struct btrfs_key found_key;
5679         struct btrfs_path *path;
5680         struct list_head ins_list;
5681         struct list_head del_list;
5682         int ret;
5683         struct extent_buffer *leaf;
5684         int slot;
5685         unsigned char d_type;
5686         int over = 0;
5687         u32 di_cur;
5688         u32 di_total;
5689         u32 di_len;
5690         int key_type = BTRFS_DIR_INDEX_KEY;
5691         char tmp_name[32];
5692         char *name_ptr;
5693         int name_len;
5694         int is_curr = 0;        /* ctx->pos points to the current index? */
5695 
5696         /* FIXME, use a real flag for deciding about the key type */
5697         if (root->fs_info->tree_root == root)
5698                 key_type = BTRFS_DIR_ITEM_KEY;
5699 
5700         if (!dir_emit_dots(file, ctx))
5701                 return 0;
5702 
5703         path = btrfs_alloc_path();
5704         if (!path)
5705                 return -ENOMEM;
5706 
5707         path->reada = 1;
5708 
5709         if (key_type == BTRFS_DIR_INDEX_KEY) {
5710                 INIT_LIST_HEAD(&ins_list);
5711                 INIT_LIST_HEAD(&del_list);
5712                 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5713         }
5714 
5715         key.type = key_type;
5716         key.offset = ctx->pos;
5717         key.objectid = btrfs_ino(inode);
5718 
5719         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5720         if (ret < 0)
5721                 goto err;
5722 
5723         while (1) {
5724                 leaf = path->nodes[0];
5725                 slot = path->slots[0];
5726                 if (slot >= btrfs_header_nritems(leaf)) {
5727                         ret = btrfs_next_leaf(root, path);
5728                         if (ret < 0)
5729                                 goto err;
5730                         else if (ret > 0)
5731                                 break;
5732                         continue;
5733                 }
5734 
5735                 item = btrfs_item_nr(slot);
5736                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5737 
5738                 if (found_key.objectid != key.objectid)
5739                         break;
5740                 if (found_key.type != key_type)
5741                         break;
5742                 if (found_key.offset < ctx->pos)
5743                         goto next;
5744                 if (key_type == BTRFS_DIR_INDEX_KEY &&
5745                     btrfs_should_delete_dir_index(&del_list,
5746                                                   found_key.offset))
5747                         goto next;
5748 
5749                 ctx->pos = found_key.offset;
5750                 is_curr = 1;
5751 
5752                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5753                 di_cur = 0;
5754                 di_total = btrfs_item_size(leaf, item);
5755 
5756                 while (di_cur < di_total) {
5757                         struct btrfs_key location;
5758 
5759                         if (verify_dir_item(root, leaf, di))
5760                                 break;
5761 
5762                         name_len = btrfs_dir_name_len(leaf, di);
5763                         if (name_len <= sizeof(tmp_name)) {
5764                                 name_ptr = tmp_name;
5765                         } else {
5766                                 name_ptr = kmalloc(name_len, GFP_NOFS);
5767                                 if (!name_ptr) {
5768                                         ret = -ENOMEM;
5769                                         goto err;
5770                                 }
5771                         }
5772                         read_extent_buffer(leaf, name_ptr,
5773                                            (unsigned long)(di + 1), name_len);
5774 
5775                         d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5776                         btrfs_dir_item_key_to_cpu(leaf, di, &location);
5777 
5778 
5779                         /* is this a reference to our own snapshot? If so
5780                          * skip it.
5781                          *
5782                          * In contrast to old kernels, we insert the snapshot's
5783                          * dir item and dir index after it has been created, so
5784                          * we won't find a reference to our own snapshot. We
5785                          * still keep the following code for backward
5786                          * compatibility.
5787                          */
5788                         if (location.type == BTRFS_ROOT_ITEM_KEY &&
5789                             location.objectid == root->root_key.objectid) {
5790                                 over = 0;
5791                                 goto skip;
5792                         }
5793                         over = !dir_emit(ctx, name_ptr, name_len,
5794                                        location.objectid, d_type);
5795 
5796 skip:
5797                         if (name_ptr != tmp_name)
5798                                 kfree(name_ptr);
5799 
5800                         if (over)
5801                                 goto nopos;
5802                         di_len = btrfs_dir_name_len(leaf, di) +
5803                                  btrfs_dir_data_len(leaf, di) + sizeof(*di);
5804                         di_cur += di_len;
5805                         di = (struct