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

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

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