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

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

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