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

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

Version: ~ [ linux-4.15-rc8 ] ~ [ linux-4.14.13 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.76 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.111 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.48 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.91 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.53 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.98 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.39.4 ] ~ [ linux-2.6.38.8 ] ~ [ linux-2.6.37.6 ] ~ [ linux-2.6.36.4 ] ~ [ linux-2.6.35.14 ] ~ [ linux-2.6.34.15 ] ~ [ linux-2.6.33.20 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.27.62 ] ~ [ 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/compat.h>
 34 #include <linux/bit_spinlock.h>
 35 #include <linux/xattr.h>
 36 #include <linux/posix_acl.h>
 37 #include <linux/falloc.h>
 38 #include <linux/slab.h>
 39 #include <linux/ratelimit.h>
 40 #include <linux/mount.h>
 41 #include <linux/btrfs.h>
 42 #include <linux/blkdev.h>
 43 #include <linux/posix_acl_xattr.h>
 44 #include <linux/uio.h>
 45 #include <linux/magic.h>
 46 #include "ctree.h"
 47 #include "disk-io.h"
 48 #include "transaction.h"
 49 #include "btrfs_inode.h"
 50 #include "print-tree.h"
 51 #include "ordered-data.h"
 52 #include "xattr.h"
 53 #include "tree-log.h"
 54 #include "volumes.h"
 55 #include "compression.h"
 56 #include "locking.h"
 57 #include "free-space-cache.h"
 58 #include "inode-map.h"
 59 #include "backref.h"
 60 #include "hash.h"
 61 #include "props.h"
 62 #include "qgroup.h"
 63 #include "dedupe.h"
 64 
 65 struct btrfs_iget_args {
 66         struct btrfs_key *location;
 67         struct btrfs_root *root;
 68 };
 69 
 70 struct btrfs_dio_data {
 71         u64 reserve;
 72         u64 unsubmitted_oe_range_start;
 73         u64 unsubmitted_oe_range_end;
 74         int overwrite;
 75 };
 76 
 77 static const struct inode_operations btrfs_dir_inode_operations;
 78 static const struct inode_operations btrfs_symlink_inode_operations;
 79 static const struct inode_operations btrfs_dir_ro_inode_operations;
 80 static const struct inode_operations btrfs_special_inode_operations;
 81 static const struct inode_operations btrfs_file_inode_operations;
 82 static const struct address_space_operations btrfs_aops;
 83 static const struct address_space_operations btrfs_symlink_aops;
 84 static const struct file_operations btrfs_dir_file_operations;
 85 static const struct extent_io_ops btrfs_extent_io_ops;
 86 
 87 static struct kmem_cache *btrfs_inode_cachep;
 88 struct kmem_cache *btrfs_trans_handle_cachep;
 89 struct kmem_cache *btrfs_path_cachep;
 90 struct kmem_cache *btrfs_free_space_cachep;
 91 
 92 #define S_SHIFT 12
 93 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
 94         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
 95         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
 96         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
 97         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
 98         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
 99         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
100         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
101 };
102 
103 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
104 static int btrfs_truncate(struct inode *inode);
105 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
106 static noinline int cow_file_range(struct inode *inode,
107                                    struct page *locked_page,
108                                    u64 start, u64 end, u64 delalloc_end,
109                                    int *page_started, unsigned long *nr_written,
110                                    int unlock, struct btrfs_dedupe_hash *hash);
111 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
112                                        u64 orig_start, u64 block_start,
113                                        u64 block_len, u64 orig_block_len,
114                                        u64 ram_bytes, int compress_type,
115                                        int type);
116 
117 static void __endio_write_update_ordered(struct inode *inode,
118                                          const u64 offset, const u64 bytes,
119                                          const bool uptodate);
120 
121 /*
122  * Cleanup all submitted ordered extents in specified range to handle errors
123  * from the fill_dellaloc() callback.
124  *
125  * NOTE: caller must ensure that when an error happens, it can not call
126  * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
127  * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
128  * to be released, which we want to happen only when finishing the ordered
129  * extent (btrfs_finish_ordered_io()). Also note that the caller of the
130  * fill_delalloc() callback already does proper cleanup for the first page of
131  * the range, that is, it invokes the callback writepage_end_io_hook() for the
132  * range of the first page.
133  */
134 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
135                                                  const u64 offset,
136                                                  const u64 bytes)
137 {
138         unsigned long index = offset >> PAGE_SHIFT;
139         unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
140         struct page *page;
141 
142         while (index <= end_index) {
143                 page = find_get_page(inode->i_mapping, index);
144                 index++;
145                 if (!page)
146                         continue;
147                 ClearPagePrivate2(page);
148                 put_page(page);
149         }
150         return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
151                                             bytes - PAGE_SIZE, false);
152 }
153 
154 static int btrfs_dirty_inode(struct inode *inode);
155 
156 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
157 void btrfs_test_inode_set_ops(struct inode *inode)
158 {
159         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
160 }
161 #endif
162 
163 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
164                                      struct inode *inode,  struct inode *dir,
165                                      const struct qstr *qstr)
166 {
167         int err;
168 
169         err = btrfs_init_acl(trans, inode, dir);
170         if (!err)
171                 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
172         return err;
173 }
174 
175 /*
176  * this does all the hard work for inserting an inline extent into
177  * the btree.  The caller should have done a btrfs_drop_extents so that
178  * no overlapping inline items exist in the btree
179  */
180 static int insert_inline_extent(struct btrfs_trans_handle *trans,
181                                 struct btrfs_path *path, int extent_inserted,
182                                 struct btrfs_root *root, struct inode *inode,
183                                 u64 start, size_t size, size_t compressed_size,
184                                 int compress_type,
185                                 struct page **compressed_pages)
186 {
187         struct extent_buffer *leaf;
188         struct page *page = NULL;
189         char *kaddr;
190         unsigned long ptr;
191         struct btrfs_file_extent_item *ei;
192         int ret;
193         size_t cur_size = size;
194         unsigned long offset;
195 
196         if (compressed_size && compressed_pages)
197                 cur_size = compressed_size;
198 
199         inode_add_bytes(inode, size);
200 
201         if (!extent_inserted) {
202                 struct btrfs_key key;
203                 size_t datasize;
204 
205                 key.objectid = btrfs_ino(BTRFS_I(inode));
206                 key.offset = start;
207                 key.type = BTRFS_EXTENT_DATA_KEY;
208 
209                 datasize = btrfs_file_extent_calc_inline_size(cur_size);
210                 path->leave_spinning = 1;
211                 ret = btrfs_insert_empty_item(trans, root, path, &key,
212                                               datasize);
213                 if (ret)
214                         goto fail;
215         }
216         leaf = path->nodes[0];
217         ei = btrfs_item_ptr(leaf, path->slots[0],
218                             struct btrfs_file_extent_item);
219         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
220         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
221         btrfs_set_file_extent_encryption(leaf, ei, 0);
222         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
223         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
224         ptr = btrfs_file_extent_inline_start(ei);
225 
226         if (compress_type != BTRFS_COMPRESS_NONE) {
227                 struct page *cpage;
228                 int i = 0;
229                 while (compressed_size > 0) {
230                         cpage = compressed_pages[i];
231                         cur_size = min_t(unsigned long, compressed_size,
232                                        PAGE_SIZE);
233 
234                         kaddr = kmap_atomic(cpage);
235                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
236                         kunmap_atomic(kaddr);
237 
238                         i++;
239                         ptr += cur_size;
240                         compressed_size -= cur_size;
241                 }
242                 btrfs_set_file_extent_compression(leaf, ei,
243                                                   compress_type);
244         } else {
245                 page = find_get_page(inode->i_mapping,
246                                      start >> PAGE_SHIFT);
247                 btrfs_set_file_extent_compression(leaf, ei, 0);
248                 kaddr = kmap_atomic(page);
249                 offset = start & (PAGE_SIZE - 1);
250                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
251                 kunmap_atomic(kaddr);
252                 put_page(page);
253         }
254         btrfs_mark_buffer_dirty(leaf);
255         btrfs_release_path(path);
256 
257         /*
258          * we're an inline extent, so nobody can
259          * extend the file past i_size without locking
260          * a page we already have locked.
261          *
262          * We must do any isize and inode updates
263          * before we unlock the pages.  Otherwise we
264          * could end up racing with unlink.
265          */
266         BTRFS_I(inode)->disk_i_size = inode->i_size;
267         ret = btrfs_update_inode(trans, root, inode);
268 
269 fail:
270         return ret;
271 }
272 
273 
274 /*
275  * conditionally insert an inline extent into the file.  This
276  * does the checks required to make sure the data is small enough
277  * to fit as an inline extent.
278  */
279 static noinline int cow_file_range_inline(struct btrfs_root *root,
280                                           struct inode *inode, u64 start,
281                                           u64 end, size_t compressed_size,
282                                           int compress_type,
283                                           struct page **compressed_pages)
284 {
285         struct btrfs_fs_info *fs_info = root->fs_info;
286         struct btrfs_trans_handle *trans;
287         u64 isize = i_size_read(inode);
288         u64 actual_end = min(end + 1, isize);
289         u64 inline_len = actual_end - start;
290         u64 aligned_end = ALIGN(end, fs_info->sectorsize);
291         u64 data_len = inline_len;
292         int ret;
293         struct btrfs_path *path;
294         int extent_inserted = 0;
295         u32 extent_item_size;
296 
297         if (compressed_size)
298                 data_len = compressed_size;
299 
300         if (start > 0 ||
301             actual_end > fs_info->sectorsize ||
302             data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
303             (!compressed_size &&
304             (actual_end & (fs_info->sectorsize - 1)) == 0) ||
305             end + 1 < isize ||
306             data_len > fs_info->max_inline) {
307                 return 1;
308         }
309 
310         path = btrfs_alloc_path();
311         if (!path)
312                 return -ENOMEM;
313 
314         trans = btrfs_join_transaction(root);
315         if (IS_ERR(trans)) {
316                 btrfs_free_path(path);
317                 return PTR_ERR(trans);
318         }
319         trans->block_rsv = &BTRFS_I(inode)->block_rsv;
320 
321         if (compressed_size && compressed_pages)
322                 extent_item_size = btrfs_file_extent_calc_inline_size(
323                    compressed_size);
324         else
325                 extent_item_size = btrfs_file_extent_calc_inline_size(
326                     inline_len);
327 
328         ret = __btrfs_drop_extents(trans, root, inode, path,
329                                    start, aligned_end, NULL,
330                                    1, 1, extent_item_size, &extent_inserted);
331         if (ret) {
332                 btrfs_abort_transaction(trans, ret);
333                 goto out;
334         }
335 
336         if (isize > actual_end)
337                 inline_len = min_t(u64, isize, actual_end);
338         ret = insert_inline_extent(trans, path, extent_inserted,
339                                    root, inode, start,
340                                    inline_len, compressed_size,
341                                    compress_type, compressed_pages);
342         if (ret && ret != -ENOSPC) {
343                 btrfs_abort_transaction(trans, ret);
344                 goto out;
345         } else if (ret == -ENOSPC) {
346                 ret = 1;
347                 goto out;
348         }
349 
350         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
351         btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
352 out:
353         /*
354          * Don't forget to free the reserved space, as for inlined extent
355          * it won't count as data extent, free them directly here.
356          * And at reserve time, it's always aligned to page size, so
357          * just free one page here.
358          */
359         btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
360         btrfs_free_path(path);
361         btrfs_end_transaction(trans);
362         return ret;
363 }
364 
365 struct async_extent {
366         u64 start;
367         u64 ram_size;
368         u64 compressed_size;
369         struct page **pages;
370         unsigned long nr_pages;
371         int compress_type;
372         struct list_head list;
373 };
374 
375 struct async_cow {
376         struct inode *inode;
377         struct btrfs_root *root;
378         struct page *locked_page;
379         u64 start;
380         u64 end;
381         unsigned int write_flags;
382         struct list_head extents;
383         struct btrfs_work work;
384 };
385 
386 static noinline int add_async_extent(struct async_cow *cow,
387                                      u64 start, u64 ram_size,
388                                      u64 compressed_size,
389                                      struct page **pages,
390                                      unsigned long nr_pages,
391                                      int compress_type)
392 {
393         struct async_extent *async_extent;
394 
395         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
396         BUG_ON(!async_extent); /* -ENOMEM */
397         async_extent->start = start;
398         async_extent->ram_size = ram_size;
399         async_extent->compressed_size = compressed_size;
400         async_extent->pages = pages;
401         async_extent->nr_pages = nr_pages;
402         async_extent->compress_type = compress_type;
403         list_add_tail(&async_extent->list, &cow->extents);
404         return 0;
405 }
406 
407 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
408 {
409         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
410 
411         /* force compress */
412         if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
413                 return 1;
414         /* defrag ioctl */
415         if (BTRFS_I(inode)->defrag_compress)
416                 return 1;
417         /* bad compression ratios */
418         if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
419                 return 0;
420         if (btrfs_test_opt(fs_info, COMPRESS) ||
421             BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
422             BTRFS_I(inode)->prop_compress)
423                 return btrfs_compress_heuristic(inode, start, end);
424         return 0;
425 }
426 
427 static inline void inode_should_defrag(struct btrfs_inode *inode,
428                 u64 start, u64 end, u64 num_bytes, u64 small_write)
429 {
430         /* If this is a small write inside eof, kick off a defrag */
431         if (num_bytes < small_write &&
432             (start > 0 || end + 1 < inode->disk_i_size))
433                 btrfs_add_inode_defrag(NULL, inode);
434 }
435 
436 /*
437  * we create compressed extents in two phases.  The first
438  * phase compresses a range of pages that have already been
439  * locked (both pages and state bits are locked).
440  *
441  * This is done inside an ordered work queue, and the compression
442  * is spread across many cpus.  The actual IO submission is step
443  * two, and the ordered work queue takes care of making sure that
444  * happens in the same order things were put onto the queue by
445  * writepages and friends.
446  *
447  * If this code finds it can't get good compression, it puts an
448  * entry onto the work queue to write the uncompressed bytes.  This
449  * makes sure that both compressed inodes and uncompressed inodes
450  * are written in the same order that the flusher thread sent them
451  * down.
452  */
453 static noinline void compress_file_range(struct inode *inode,
454                                         struct page *locked_page,
455                                         u64 start, u64 end,
456                                         struct async_cow *async_cow,
457                                         int *num_added)
458 {
459         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
460         struct btrfs_root *root = BTRFS_I(inode)->root;
461         u64 blocksize = fs_info->sectorsize;
462         u64 actual_end;
463         u64 isize = i_size_read(inode);
464         int ret = 0;
465         struct page **pages = NULL;
466         unsigned long nr_pages;
467         unsigned long total_compressed = 0;
468         unsigned long total_in = 0;
469         int i;
470         int will_compress;
471         int compress_type = fs_info->compress_type;
472         int redirty = 0;
473 
474         inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
475                         SZ_16K);
476 
477         actual_end = min_t(u64, isize, end + 1);
478 again:
479         will_compress = 0;
480         nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
481         BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
482         nr_pages = min_t(unsigned long, nr_pages,
483                         BTRFS_MAX_COMPRESSED / PAGE_SIZE);
484 
485         /*
486          * we don't want to send crud past the end of i_size through
487          * compression, that's just a waste of CPU time.  So, if the
488          * end of the file is before the start of our current
489          * requested range of bytes, we bail out to the uncompressed
490          * cleanup code that can deal with all of this.
491          *
492          * It isn't really the fastest way to fix things, but this is a
493          * very uncommon corner.
494          */
495         if (actual_end <= start)
496                 goto cleanup_and_bail_uncompressed;
497 
498         total_compressed = actual_end - start;
499 
500         /*
501          * skip compression for a small file range(<=blocksize) that
502          * isn't an inline extent, since it doesn't save disk space at all.
503          */
504         if (total_compressed <= blocksize &&
505            (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
506                 goto cleanup_and_bail_uncompressed;
507 
508         total_compressed = min_t(unsigned long, total_compressed,
509                         BTRFS_MAX_UNCOMPRESSED);
510         total_in = 0;
511         ret = 0;
512 
513         /*
514          * we do compression for mount -o compress and when the
515          * inode has not been flagged as nocompress.  This flag can
516          * change at any time if we discover bad compression ratios.
517          */
518         if (inode_need_compress(inode, start, end)) {
519                 WARN_ON(pages);
520                 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
521                 if (!pages) {
522                         /* just bail out to the uncompressed code */
523                         goto cont;
524                 }
525 
526                 if (BTRFS_I(inode)->defrag_compress)
527                         compress_type = BTRFS_I(inode)->defrag_compress;
528                 else if (BTRFS_I(inode)->prop_compress)
529                         compress_type = BTRFS_I(inode)->prop_compress;
530 
531                 /*
532                  * we need to call clear_page_dirty_for_io on each
533                  * page in the range.  Otherwise applications with the file
534                  * mmap'd can wander in and change the page contents while
535                  * we are compressing them.
536                  *
537                  * If the compression fails for any reason, we set the pages
538                  * dirty again later on.
539                  */
540                 extent_range_clear_dirty_for_io(inode, start, end);
541                 redirty = 1;
542 
543                 /* Compression level is applied here and only here */
544                 ret = btrfs_compress_pages(
545                         compress_type | (fs_info->compress_level << 4),
546                                            inode->i_mapping, start,
547                                            pages,
548                                            &nr_pages,
549                                            &total_in,
550                                            &total_compressed);
551 
552                 if (!ret) {
553                         unsigned long offset = total_compressed &
554                                 (PAGE_SIZE - 1);
555                         struct page *page = pages[nr_pages - 1];
556                         char *kaddr;
557 
558                         /* zero the tail end of the last page, we might be
559                          * sending it down to disk
560                          */
561                         if (offset) {
562                                 kaddr = kmap_atomic(page);
563                                 memset(kaddr + offset, 0,
564                                        PAGE_SIZE - offset);
565                                 kunmap_atomic(kaddr);
566                         }
567                         will_compress = 1;
568                 }
569         }
570 cont:
571         if (start == 0) {
572                 /* lets try to make an inline extent */
573                 if (ret || total_in < actual_end) {
574                         /* we didn't compress the entire range, try
575                          * to make an uncompressed inline extent.
576                          */
577                         ret = cow_file_range_inline(root, inode, start, end,
578                                             0, BTRFS_COMPRESS_NONE, NULL);
579                 } else {
580                         /* try making a compressed inline extent */
581                         ret = cow_file_range_inline(root, inode, start, end,
582                                                     total_compressed,
583                                                     compress_type, pages);
584                 }
585                 if (ret <= 0) {
586                         unsigned long clear_flags = EXTENT_DELALLOC |
587                                 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
588                                 EXTENT_DO_ACCOUNTING;
589                         unsigned long page_error_op;
590 
591                         page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
592 
593                         /*
594                          * inline extent creation worked or returned error,
595                          * we don't need to create any more async work items.
596                          * Unlock and free up our temp pages.
597                          *
598                          * We use DO_ACCOUNTING here because we need the
599                          * delalloc_release_metadata to be done _after_ we drop
600                          * our outstanding extent for clearing delalloc for this
601                          * range.
602                          */
603                         extent_clear_unlock_delalloc(inode, start, end, end,
604                                                      NULL, clear_flags,
605                                                      PAGE_UNLOCK |
606                                                      PAGE_CLEAR_DIRTY |
607                                                      PAGE_SET_WRITEBACK |
608                                                      page_error_op |
609                                                      PAGE_END_WRITEBACK);
610                         goto free_pages_out;
611                 }
612         }
613 
614         if (will_compress) {
615                 /*
616                  * we aren't doing an inline extent round the compressed size
617                  * up to a block size boundary so the allocator does sane
618                  * things
619                  */
620                 total_compressed = ALIGN(total_compressed, blocksize);
621 
622                 /*
623                  * one last check to make sure the compression is really a
624                  * win, compare the page count read with the blocks on disk,
625                  * compression must free at least one sector size
626                  */
627                 total_in = ALIGN(total_in, PAGE_SIZE);
628                 if (total_compressed + blocksize <= total_in) {
629                         *num_added += 1;
630 
631                         /*
632                          * The async work queues will take care of doing actual
633                          * allocation on disk for these compressed pages, and
634                          * will submit them to the elevator.
635                          */
636                         add_async_extent(async_cow, start, total_in,
637                                         total_compressed, pages, nr_pages,
638                                         compress_type);
639 
640                         if (start + total_in < end) {
641                                 start += total_in;
642                                 pages = NULL;
643                                 cond_resched();
644                                 goto again;
645                         }
646                         return;
647                 }
648         }
649         if (pages) {
650                 /*
651                  * the compression code ran but failed to make things smaller,
652                  * free any pages it allocated and our page pointer array
653                  */
654                 for (i = 0; i < nr_pages; i++) {
655                         WARN_ON(pages[i]->mapping);
656                         put_page(pages[i]);
657                 }
658                 kfree(pages);
659                 pages = NULL;
660                 total_compressed = 0;
661                 nr_pages = 0;
662 
663                 /* flag the file so we don't compress in the future */
664                 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
665                     !(BTRFS_I(inode)->prop_compress)) {
666                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
667                 }
668         }
669 cleanup_and_bail_uncompressed:
670         /*
671          * No compression, but we still need to write the pages in the file
672          * we've been given so far.  redirty the locked page if it corresponds
673          * to our extent and set things up for the async work queue to run
674          * cow_file_range to do the normal delalloc dance.
675          */
676         if (page_offset(locked_page) >= start &&
677             page_offset(locked_page) <= end)
678                 __set_page_dirty_nobuffers(locked_page);
679                 /* unlocked later on in the async handlers */
680 
681         if (redirty)
682                 extent_range_redirty_for_io(inode, start, end);
683         add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
684                          BTRFS_COMPRESS_NONE);
685         *num_added += 1;
686 
687         return;
688 
689 free_pages_out:
690         for (i = 0; i < nr_pages; i++) {
691                 WARN_ON(pages[i]->mapping);
692                 put_page(pages[i]);
693         }
694         kfree(pages);
695 }
696 
697 static void free_async_extent_pages(struct async_extent *async_extent)
698 {
699         int i;
700 
701         if (!async_extent->pages)
702                 return;
703 
704         for (i = 0; i < async_extent->nr_pages; i++) {
705                 WARN_ON(async_extent->pages[i]->mapping);
706                 put_page(async_extent->pages[i]);
707         }
708         kfree(async_extent->pages);
709         async_extent->nr_pages = 0;
710         async_extent->pages = NULL;
711 }
712 
713 /*
714  * phase two of compressed writeback.  This is the ordered portion
715  * of the code, which only gets called in the order the work was
716  * queued.  We walk all the async extents created by compress_file_range
717  * and send them down to the disk.
718  */
719 static noinline void submit_compressed_extents(struct inode *inode,
720                                               struct async_cow *async_cow)
721 {
722         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
723         struct async_extent *async_extent;
724         u64 alloc_hint = 0;
725         struct btrfs_key ins;
726         struct extent_map *em;
727         struct btrfs_root *root = BTRFS_I(inode)->root;
728         struct extent_io_tree *io_tree;
729         int ret = 0;
730 
731 again:
732         while (!list_empty(&async_cow->extents)) {
733                 async_extent = list_entry(async_cow->extents.next,
734                                           struct async_extent, list);
735                 list_del(&async_extent->list);
736 
737                 io_tree = &BTRFS_I(inode)->io_tree;
738 
739 retry:
740                 /* did the compression code fall back to uncompressed IO? */
741                 if (!async_extent->pages) {
742                         int page_started = 0;
743                         unsigned long nr_written = 0;
744 
745                         lock_extent(io_tree, async_extent->start,
746                                          async_extent->start +
747                                          async_extent->ram_size - 1);
748 
749                         /* allocate blocks */
750                         ret = cow_file_range(inode, async_cow->locked_page,
751                                              async_extent->start,
752                                              async_extent->start +
753                                              async_extent->ram_size - 1,
754                                              async_extent->start +
755                                              async_extent->ram_size - 1,
756                                              &page_started, &nr_written, 0,
757                                              NULL);
758 
759                         /* JDM XXX */
760 
761                         /*
762                          * if page_started, cow_file_range inserted an
763                          * inline extent and took care of all the unlocking
764                          * and IO for us.  Otherwise, we need to submit
765                          * all those pages down to the drive.
766                          */
767                         if (!page_started && !ret)
768                                 extent_write_locked_range(io_tree,
769                                                   inode, async_extent->start,
770                                                   async_extent->start +
771                                                   async_extent->ram_size - 1,
772                                                   btrfs_get_extent,
773                                                   WB_SYNC_ALL);
774                         else if (ret)
775                                 unlock_page(async_cow->locked_page);
776                         kfree(async_extent);
777                         cond_resched();
778                         continue;
779                 }
780 
781                 lock_extent(io_tree, async_extent->start,
782                             async_extent->start + async_extent->ram_size - 1);
783 
784                 ret = btrfs_reserve_extent(root, async_extent->ram_size,
785                                            async_extent->compressed_size,
786                                            async_extent->compressed_size,
787                                            0, alloc_hint, &ins, 1, 1);
788                 if (ret) {
789                         free_async_extent_pages(async_extent);
790 
791                         if (ret == -ENOSPC) {
792                                 unlock_extent(io_tree, async_extent->start,
793                                               async_extent->start +
794                                               async_extent->ram_size - 1);
795 
796                                 /*
797                                  * we need to redirty the pages if we decide to
798                                  * fallback to uncompressed IO, otherwise we
799                                  * will not submit these pages down to lower
800                                  * layers.
801                                  */
802                                 extent_range_redirty_for_io(inode,
803                                                 async_extent->start,
804                                                 async_extent->start +
805                                                 async_extent->ram_size - 1);
806 
807                                 goto retry;
808                         }
809                         goto out_free;
810                 }
811                 /*
812                  * here we're doing allocation and writeback of the
813                  * compressed pages
814                  */
815                 em = create_io_em(inode, async_extent->start,
816                                   async_extent->ram_size, /* len */
817                                   async_extent->start, /* orig_start */
818                                   ins.objectid, /* block_start */
819                                   ins.offset, /* block_len */
820                                   ins.offset, /* orig_block_len */
821                                   async_extent->ram_size, /* ram_bytes */
822                                   async_extent->compress_type,
823                                   BTRFS_ORDERED_COMPRESSED);
824                 if (IS_ERR(em))
825                         /* ret value is not necessary due to void function */
826                         goto out_free_reserve;
827                 free_extent_map(em);
828 
829                 ret = btrfs_add_ordered_extent_compress(inode,
830                                                 async_extent->start,
831                                                 ins.objectid,
832                                                 async_extent->ram_size,
833                                                 ins.offset,
834                                                 BTRFS_ORDERED_COMPRESSED,
835                                                 async_extent->compress_type);
836                 if (ret) {
837                         btrfs_drop_extent_cache(BTRFS_I(inode),
838                                                 async_extent->start,
839                                                 async_extent->start +
840                                                 async_extent->ram_size - 1, 0);
841                         goto out_free_reserve;
842                 }
843                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
844 
845                 /*
846                  * clear dirty, set writeback and unlock the pages.
847                  */
848                 extent_clear_unlock_delalloc(inode, async_extent->start,
849                                 async_extent->start +
850                                 async_extent->ram_size - 1,
851                                 async_extent->start +
852                                 async_extent->ram_size - 1,
853                                 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
854                                 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
855                                 PAGE_SET_WRITEBACK);
856                 if (btrfs_submit_compressed_write(inode,
857                                     async_extent->start,
858                                     async_extent->ram_size,
859                                     ins.objectid,
860                                     ins.offset, async_extent->pages,
861                                     async_extent->nr_pages,
862                                     async_cow->write_flags)) {
863                         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
864                         struct page *p = async_extent->pages[0];
865                         const u64 start = async_extent->start;
866                         const u64 end = start + async_extent->ram_size - 1;
867 
868                         p->mapping = inode->i_mapping;
869                         tree->ops->writepage_end_io_hook(p, start, end,
870                                                          NULL, 0);
871                         p->mapping = NULL;
872                         extent_clear_unlock_delalloc(inode, start, end, end,
873                                                      NULL, 0,
874                                                      PAGE_END_WRITEBACK |
875                                                      PAGE_SET_ERROR);
876                         free_async_extent_pages(async_extent);
877                 }
878                 alloc_hint = ins.objectid + ins.offset;
879                 kfree(async_extent);
880                 cond_resched();
881         }
882         return;
883 out_free_reserve:
884         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
885         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
886 out_free:
887         extent_clear_unlock_delalloc(inode, async_extent->start,
888                                      async_extent->start +
889                                      async_extent->ram_size - 1,
890                                      async_extent->start +
891                                      async_extent->ram_size - 1,
892                                      NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
893                                      EXTENT_DELALLOC_NEW |
894                                      EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
895                                      PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
896                                      PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
897                                      PAGE_SET_ERROR);
898         free_async_extent_pages(async_extent);
899         kfree(async_extent);
900         goto again;
901 }
902 
903 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
904                                       u64 num_bytes)
905 {
906         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
907         struct extent_map *em;
908         u64 alloc_hint = 0;
909 
910         read_lock(&em_tree->lock);
911         em = search_extent_mapping(em_tree, start, num_bytes);
912         if (em) {
913                 /*
914                  * if block start isn't an actual block number then find the
915                  * first block in this inode and use that as a hint.  If that
916                  * block is also bogus then just don't worry about it.
917                  */
918                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
919                         free_extent_map(em);
920                         em = search_extent_mapping(em_tree, 0, 0);
921                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
922                                 alloc_hint = em->block_start;
923                         if (em)
924                                 free_extent_map(em);
925                 } else {
926                         alloc_hint = em->block_start;
927                         free_extent_map(em);
928                 }
929         }
930         read_unlock(&em_tree->lock);
931 
932         return alloc_hint;
933 }
934 
935 /*
936  * when extent_io.c finds a delayed allocation range in the file,
937  * the call backs end up in this code.  The basic idea is to
938  * allocate extents on disk for the range, and create ordered data structs
939  * in ram to track those extents.
940  *
941  * locked_page is the page that writepage had locked already.  We use
942  * it to make sure we don't do extra locks or unlocks.
943  *
944  * *page_started is set to one if we unlock locked_page and do everything
945  * required to start IO on it.  It may be clean and already done with
946  * IO when we return.
947  */
948 static noinline int cow_file_range(struct inode *inode,
949                                    struct page *locked_page,
950                                    u64 start, u64 end, u64 delalloc_end,
951                                    int *page_started, unsigned long *nr_written,
952                                    int unlock, struct btrfs_dedupe_hash *hash)
953 {
954         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
955         struct btrfs_root *root = BTRFS_I(inode)->root;
956         u64 alloc_hint = 0;
957         u64 num_bytes;
958         unsigned long ram_size;
959         u64 disk_num_bytes;
960         u64 cur_alloc_size = 0;
961         u64 blocksize = fs_info->sectorsize;
962         struct btrfs_key ins;
963         struct extent_map *em;
964         unsigned clear_bits;
965         unsigned long page_ops;
966         bool extent_reserved = false;
967         int ret = 0;
968 
969         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
970                 WARN_ON_ONCE(1);
971                 ret = -EINVAL;
972                 goto out_unlock;
973         }
974 
975         num_bytes = ALIGN(end - start + 1, blocksize);
976         num_bytes = max(blocksize,  num_bytes);
977         disk_num_bytes = num_bytes;
978 
979         inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
980 
981         if (start == 0) {
982                 /* lets try to make an inline extent */
983                 ret = cow_file_range_inline(root, inode, start, end, 0,
984                                         BTRFS_COMPRESS_NONE, NULL);
985                 if (ret == 0) {
986                         /*
987                          * We use DO_ACCOUNTING here because we need the
988                          * delalloc_release_metadata to be run _after_ we drop
989                          * our outstanding extent for clearing delalloc for this
990                          * range.
991                          */
992                         extent_clear_unlock_delalloc(inode, start, end,
993                                      delalloc_end, NULL,
994                                      EXTENT_LOCKED | EXTENT_DELALLOC |
995                                      EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
996                                      EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
997                                      PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
998                                      PAGE_END_WRITEBACK);
999                         *nr_written = *nr_written +
1000                              (end - start + PAGE_SIZE) / PAGE_SIZE;
1001                         *page_started = 1;
1002                         goto out;
1003                 } else if (ret < 0) {
1004                         goto out_unlock;
1005                 }
1006         }
1007 
1008         BUG_ON(disk_num_bytes >
1009                btrfs_super_total_bytes(fs_info->super_copy));
1010 
1011         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1012         btrfs_drop_extent_cache(BTRFS_I(inode), start,
1013                         start + num_bytes - 1, 0);
1014 
1015         while (disk_num_bytes > 0) {
1016                 cur_alloc_size = disk_num_bytes;
1017                 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1018                                            fs_info->sectorsize, 0, alloc_hint,
1019                                            &ins, 1, 1);
1020                 if (ret < 0)
1021                         goto out_unlock;
1022                 cur_alloc_size = ins.offset;
1023                 extent_reserved = true;
1024 
1025                 ram_size = ins.offset;
1026                 em = create_io_em(inode, start, ins.offset, /* len */
1027                                   start, /* orig_start */
1028                                   ins.objectid, /* block_start */
1029                                   ins.offset, /* block_len */
1030                                   ins.offset, /* orig_block_len */
1031                                   ram_size, /* ram_bytes */
1032                                   BTRFS_COMPRESS_NONE, /* compress_type */
1033                                   BTRFS_ORDERED_REGULAR /* type */);
1034                 if (IS_ERR(em))
1035                         goto out_reserve;
1036                 free_extent_map(em);
1037 
1038                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1039                                                ram_size, cur_alloc_size, 0);
1040                 if (ret)
1041                         goto out_drop_extent_cache;
1042 
1043                 if (root->root_key.objectid ==
1044                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1045                         ret = btrfs_reloc_clone_csums(inode, start,
1046                                                       cur_alloc_size);
1047                         /*
1048                          * Only drop cache here, and process as normal.
1049                          *
1050                          * We must not allow extent_clear_unlock_delalloc()
1051                          * at out_unlock label to free meta of this ordered
1052                          * extent, as its meta should be freed by
1053                          * btrfs_finish_ordered_io().
1054                          *
1055                          * So we must continue until @start is increased to
1056                          * skip current ordered extent.
1057                          */
1058                         if (ret)
1059                                 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1060                                                 start + ram_size - 1, 0);
1061                 }
1062 
1063                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1064 
1065                 /* we're not doing compressed IO, don't unlock the first
1066                  * page (which the caller expects to stay locked), don't
1067                  * clear any dirty bits and don't set any writeback bits
1068                  *
1069                  * Do set the Private2 bit so we know this page was properly
1070                  * setup for writepage
1071                  */
1072                 page_ops = unlock ? PAGE_UNLOCK : 0;
1073                 page_ops |= PAGE_SET_PRIVATE2;
1074 
1075                 extent_clear_unlock_delalloc(inode, start,
1076                                              start + ram_size - 1,
1077                                              delalloc_end, locked_page,
1078                                              EXTENT_LOCKED | EXTENT_DELALLOC,
1079                                              page_ops);
1080                 if (disk_num_bytes < cur_alloc_size)
1081                         disk_num_bytes = 0;
1082                 else
1083                         disk_num_bytes -= cur_alloc_size;
1084                 num_bytes -= cur_alloc_size;
1085                 alloc_hint = ins.objectid + ins.offset;
1086                 start += cur_alloc_size;
1087                 extent_reserved = false;
1088 
1089                 /*
1090                  * btrfs_reloc_clone_csums() error, since start is increased
1091                  * extent_clear_unlock_delalloc() at out_unlock label won't
1092                  * free metadata of current ordered extent, we're OK to exit.
1093                  */
1094                 if (ret)
1095                         goto out_unlock;
1096         }
1097 out:
1098         return ret;
1099 
1100 out_drop_extent_cache:
1101         btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1102 out_reserve:
1103         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1104         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1105 out_unlock:
1106         clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1107                 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1108         page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1109                 PAGE_END_WRITEBACK;
1110         /*
1111          * If we reserved an extent for our delalloc range (or a subrange) and
1112          * failed to create the respective ordered extent, then it means that
1113          * when we reserved the extent we decremented the extent's size from
1114          * the data space_info's bytes_may_use counter and incremented the
1115          * space_info's bytes_reserved counter by the same amount. We must make
1116          * sure extent_clear_unlock_delalloc() does not try to decrement again
1117          * the data space_info's bytes_may_use counter, therefore we do not pass
1118          * it the flag EXTENT_CLEAR_DATA_RESV.
1119          */
1120         if (extent_reserved) {
1121                 extent_clear_unlock_delalloc(inode, start,
1122                                              start + cur_alloc_size,
1123                                              start + cur_alloc_size,
1124                                              locked_page,
1125                                              clear_bits,
1126                                              page_ops);
1127                 start += cur_alloc_size;
1128                 if (start >= end)
1129                         goto out;
1130         }
1131         extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1132                                      locked_page,
1133                                      clear_bits | EXTENT_CLEAR_DATA_RESV,
1134                                      page_ops);
1135         goto out;
1136 }
1137 
1138 /*
1139  * work queue call back to started compression on a file and pages
1140  */
1141 static noinline void async_cow_start(struct btrfs_work *work)
1142 {
1143         struct async_cow *async_cow;
1144         int num_added = 0;
1145         async_cow = container_of(work, struct async_cow, work);
1146 
1147         compress_file_range(async_cow->inode, async_cow->locked_page,
1148                             async_cow->start, async_cow->end, async_cow,
1149                             &num_added);
1150         if (num_added == 0) {
1151                 btrfs_add_delayed_iput(async_cow->inode);
1152                 async_cow->inode = NULL;
1153         }
1154 }
1155 
1156 /*
1157  * work queue call back to submit previously compressed pages
1158  */
1159 static noinline void async_cow_submit(struct btrfs_work *work)
1160 {
1161         struct btrfs_fs_info *fs_info;
1162         struct async_cow *async_cow;
1163         struct btrfs_root *root;
1164         unsigned long nr_pages;
1165 
1166         async_cow = container_of(work, struct async_cow, work);
1167 
1168         root = async_cow->root;
1169         fs_info = root->fs_info;
1170         nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1171                 PAGE_SHIFT;
1172 
1173         /*
1174          * atomic_sub_return implies a barrier for waitqueue_active
1175          */
1176         if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1177             5 * SZ_1M &&
1178             waitqueue_active(&fs_info->async_submit_wait))
1179                 wake_up(&fs_info->async_submit_wait);
1180 
1181         if (async_cow->inode)
1182                 submit_compressed_extents(async_cow->inode, async_cow);
1183 }
1184 
1185 static noinline void async_cow_free(struct btrfs_work *work)
1186 {
1187         struct async_cow *async_cow;
1188         async_cow = container_of(work, struct async_cow, work);
1189         if (async_cow->inode)
1190                 btrfs_add_delayed_iput(async_cow->inode);
1191         kfree(async_cow);
1192 }
1193 
1194 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1195                                 u64 start, u64 end, int *page_started,
1196                                 unsigned long *nr_written,
1197                                 unsigned int write_flags)
1198 {
1199         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1200         struct async_cow *async_cow;
1201         struct btrfs_root *root = BTRFS_I(inode)->root;
1202         unsigned long nr_pages;
1203         u64 cur_end;
1204 
1205         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1206                          1, 0, NULL, GFP_NOFS);
1207         while (start < end) {
1208                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1209                 BUG_ON(!async_cow); /* -ENOMEM */
1210                 async_cow->inode = igrab(inode);
1211                 async_cow->root = root;
1212                 async_cow->locked_page = locked_page;
1213                 async_cow->start = start;
1214                 async_cow->write_flags = write_flags;
1215 
1216                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1217                     !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1218                         cur_end = end;
1219                 else
1220                         cur_end = min(end, start + SZ_512K - 1);
1221 
1222                 async_cow->end = cur_end;
1223                 INIT_LIST_HEAD(&async_cow->extents);
1224 
1225                 btrfs_init_work(&async_cow->work,
1226                                 btrfs_delalloc_helper,
1227                                 async_cow_start, async_cow_submit,
1228                                 async_cow_free);
1229 
1230                 nr_pages = (cur_end - start + PAGE_SIZE) >>
1231                         PAGE_SHIFT;
1232                 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1233 
1234                 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1235 
1236                 *nr_written += nr_pages;
1237                 start = cur_end + 1;
1238         }
1239         *page_started = 1;
1240         return 0;
1241 }
1242 
1243 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1244                                         u64 bytenr, u64 num_bytes)
1245 {
1246         int ret;
1247         struct btrfs_ordered_sum *sums;
1248         LIST_HEAD(list);
1249 
1250         ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1251                                        bytenr + num_bytes - 1, &list, 0);
1252         if (ret == 0 && list_empty(&list))
1253                 return 0;
1254 
1255         while (!list_empty(&list)) {
1256                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1257                 list_del(&sums->list);
1258                 kfree(sums);
1259         }
1260         return 1;
1261 }
1262 
1263 /*
1264  * when nowcow writeback call back.  This checks for snapshots or COW copies
1265  * of the extents that exist in the file, and COWs the file as required.
1266  *
1267  * If no cow copies or snapshots exist, we write directly to the existing
1268  * blocks on disk
1269  */
1270 static noinline int run_delalloc_nocow(struct inode *inode,
1271                                        struct page *locked_page,
1272                               u64 start, u64 end, int *page_started, int force,
1273                               unsigned long *nr_written)
1274 {
1275         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1276         struct btrfs_root *root = BTRFS_I(inode)->root;
1277         struct extent_buffer *leaf;
1278         struct btrfs_path *path;
1279         struct btrfs_file_extent_item *fi;
1280         struct btrfs_key found_key;
1281         struct extent_map *em;
1282         u64 cow_start;
1283         u64 cur_offset;
1284         u64 extent_end;
1285         u64 extent_offset;
1286         u64 disk_bytenr;
1287         u64 num_bytes;
1288         u64 disk_num_bytes;
1289         u64 ram_bytes;
1290         int extent_type;
1291         int ret, err;
1292         int type;
1293         int nocow;
1294         int check_prev = 1;
1295         bool nolock;
1296         u64 ino = btrfs_ino(BTRFS_I(inode));
1297 
1298         path = btrfs_alloc_path();
1299         if (!path) {
1300                 extent_clear_unlock_delalloc(inode, start, end, end,
1301                                              locked_page,
1302                                              EXTENT_LOCKED | EXTENT_DELALLOC |
1303                                              EXTENT_DO_ACCOUNTING |
1304                                              EXTENT_DEFRAG, PAGE_UNLOCK |
1305                                              PAGE_CLEAR_DIRTY |
1306                                              PAGE_SET_WRITEBACK |
1307                                              PAGE_END_WRITEBACK);
1308                 return -ENOMEM;
1309         }
1310 
1311         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1312 
1313         cow_start = (u64)-1;
1314         cur_offset = start;
1315         while (1) {
1316                 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1317                                                cur_offset, 0);
1318                 if (ret < 0)
1319                         goto error;
1320                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1321                         leaf = path->nodes[0];
1322                         btrfs_item_key_to_cpu(leaf, &found_key,
1323                                               path->slots[0] - 1);
1324                         if (found_key.objectid == ino &&
1325                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1326                                 path->slots[0]--;
1327                 }
1328                 check_prev = 0;
1329 next_slot:
1330                 leaf = path->nodes[0];
1331                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1332                         ret = btrfs_next_leaf(root, path);
1333                         if (ret < 0)
1334                                 goto error;
1335                         if (ret > 0)
1336                                 break;
1337                         leaf = path->nodes[0];
1338                 }
1339 
1340                 nocow = 0;
1341                 disk_bytenr = 0;
1342                 num_bytes = 0;
1343                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1344 
1345                 if (found_key.objectid > ino)
1346                         break;
1347                 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1348                     found_key.type < BTRFS_EXTENT_DATA_KEY) {
1349                         path->slots[0]++;
1350                         goto next_slot;
1351                 }
1352                 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1353                     found_key.offset > end)
1354                         break;
1355 
1356                 if (found_key.offset > cur_offset) {
1357                         extent_end = found_key.offset;
1358                         extent_type = 0;
1359                         goto out_check;
1360                 }
1361 
1362                 fi = btrfs_item_ptr(leaf, path->slots[0],
1363                                     struct btrfs_file_extent_item);
1364                 extent_type = btrfs_file_extent_type(leaf, fi);
1365 
1366                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1367                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1368                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1369                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1370                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1371                         extent_end = found_key.offset +
1372                                 btrfs_file_extent_num_bytes(leaf, fi);
1373                         disk_num_bytes =
1374                                 btrfs_file_extent_disk_num_bytes(leaf, fi);
1375                         if (extent_end <= start) {
1376                                 path->slots[0]++;
1377                                 goto next_slot;
1378                         }
1379                         if (disk_bytenr == 0)
1380                                 goto out_check;
1381                         if (btrfs_file_extent_compression(leaf, fi) ||
1382                             btrfs_file_extent_encryption(leaf, fi) ||
1383                             btrfs_file_extent_other_encoding(leaf, fi))
1384                                 goto out_check;
1385                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1386                                 goto out_check;
1387                         if (btrfs_extent_readonly(fs_info, disk_bytenr))
1388                                 goto out_check;
1389                         if (btrfs_cross_ref_exist(root, ino,
1390                                                   found_key.offset -
1391                                                   extent_offset, disk_bytenr))
1392                                 goto out_check;
1393                         disk_bytenr += extent_offset;
1394                         disk_bytenr += cur_offset - found_key.offset;
1395                         num_bytes = min(end + 1, extent_end) - cur_offset;
1396                         /*
1397                          * if there are pending snapshots for this root,
1398                          * we fall into common COW way.
1399                          */
1400                         if (!nolock) {
1401                                 err = btrfs_start_write_no_snapshotting(root);
1402                                 if (!err)
1403                                         goto out_check;
1404                         }
1405                         /*
1406                          * force cow if csum exists in the range.
1407                          * this ensure that csum for a given extent are
1408                          * either valid or do not exist.
1409                          */
1410                         if (csum_exist_in_range(fs_info, disk_bytenr,
1411                                                 num_bytes)) {
1412                                 if (!nolock)
1413                                         btrfs_end_write_no_snapshotting(root);
1414                                 goto out_check;
1415                         }
1416                         if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1417                                 if (!nolock)
1418                                         btrfs_end_write_no_snapshotting(root);
1419                                 goto out_check;
1420                         }
1421                         nocow = 1;
1422                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1423                         extent_end = found_key.offset +
1424                                 btrfs_file_extent_inline_len(leaf,
1425                                                      path->slots[0], fi);
1426                         extent_end = ALIGN(extent_end,
1427                                            fs_info->sectorsize);
1428                 } else {
1429                         BUG_ON(1);
1430                 }
1431 out_check:
1432                 if (extent_end <= start) {
1433                         path->slots[0]++;
1434                         if (!nolock && nocow)
1435                                 btrfs_end_write_no_snapshotting(root);
1436                         if (nocow)
1437                                 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1438                         goto next_slot;
1439                 }
1440                 if (!nocow) {
1441                         if (cow_start == (u64)-1)
1442                                 cow_start = cur_offset;
1443                         cur_offset = extent_end;
1444                         if (cur_offset > end)
1445                                 break;
1446                         path->slots[0]++;
1447                         goto next_slot;
1448                 }
1449 
1450                 btrfs_release_path(path);
1451                 if (cow_start != (u64)-1) {
1452                         ret = cow_file_range(inode, locked_page,
1453                                              cow_start, found_key.offset - 1,
1454                                              end, page_started, nr_written, 1,
1455                                              NULL);
1456                         if (ret) {
1457                                 if (!nolock && nocow)
1458                                         btrfs_end_write_no_snapshotting(root);
1459                                 if (nocow)
1460                                         btrfs_dec_nocow_writers(fs_info,
1461                                                                 disk_bytenr);
1462                                 goto error;
1463                         }
1464                         cow_start = (u64)-1;
1465                 }
1466 
1467                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1468                         u64 orig_start = found_key.offset - extent_offset;
1469 
1470                         em = create_io_em(inode, cur_offset, num_bytes,
1471                                           orig_start,
1472                                           disk_bytenr, /* block_start */
1473                                           num_bytes, /* block_len */
1474                                           disk_num_bytes, /* orig_block_len */
1475                                           ram_bytes, BTRFS_COMPRESS_NONE,
1476                                           BTRFS_ORDERED_PREALLOC);
1477                         if (IS_ERR(em)) {
1478                                 if (!nolock && nocow)
1479                                         btrfs_end_write_no_snapshotting(root);
1480                                 if (nocow)
1481                                         btrfs_dec_nocow_writers(fs_info,
1482                                                                 disk_bytenr);
1483                                 ret = PTR_ERR(em);
1484                                 goto error;
1485                         }
1486                         free_extent_map(em);
1487                 }
1488 
1489                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1490                         type = BTRFS_ORDERED_PREALLOC;
1491                 } else {
1492                         type = BTRFS_ORDERED_NOCOW;
1493                 }
1494 
1495                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1496                                                num_bytes, num_bytes, type);
1497                 if (nocow)
1498                         btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1499                 BUG_ON(ret); /* -ENOMEM */
1500 
1501                 if (root->root_key.objectid ==
1502                     BTRFS_DATA_RELOC_TREE_OBJECTID)
1503                         /*
1504                          * Error handled later, as we must prevent
1505                          * extent_clear_unlock_delalloc() in error handler
1506                          * from freeing metadata of created ordered extent.
1507                          */
1508                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1509                                                       num_bytes);
1510 
1511                 extent_clear_unlock_delalloc(inode, cur_offset,
1512                                              cur_offset + num_bytes - 1, end,
1513                                              locked_page, EXTENT_LOCKED |
1514                                              EXTENT_DELALLOC |
1515                                              EXTENT_CLEAR_DATA_RESV,
1516                                              PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1517 
1518                 if (!nolock && nocow)
1519                         btrfs_end_write_no_snapshotting(root);
1520                 cur_offset = extent_end;
1521 
1522                 /*
1523                  * btrfs_reloc_clone_csums() error, now we're OK to call error
1524                  * handler, as metadata for created ordered extent will only
1525                  * be freed by btrfs_finish_ordered_io().
1526                  */
1527                 if (ret)
1528                         goto error;
1529                 if (cur_offset > end)
1530                         break;
1531         }
1532         btrfs_release_path(path);
1533 
1534         if (cur_offset <= end && cow_start == (u64)-1) {
1535                 cow_start = cur_offset;
1536                 cur_offset = end;
1537         }
1538 
1539         if (cow_start != (u64)-1) {
1540                 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1541                                      page_started, nr_written, 1, NULL);
1542                 if (ret)
1543                         goto error;
1544         }
1545 
1546 error:
1547         if (ret && cur_offset < end)
1548                 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1549                                              locked_page, EXTENT_LOCKED |
1550                                              EXTENT_DELALLOC | EXTENT_DEFRAG |
1551                                              EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1552                                              PAGE_CLEAR_DIRTY |
1553                                              PAGE_SET_WRITEBACK |
1554                                              PAGE_END_WRITEBACK);
1555         btrfs_free_path(path);
1556         return ret;
1557 }
1558 
1559 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1560 {
1561 
1562         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1563             !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1564                 return 0;
1565 
1566         /*
1567          * @defrag_bytes is a hint value, no spinlock held here,
1568          * if is not zero, it means the file is defragging.
1569          * Force cow if given extent needs to be defragged.
1570          */
1571         if (BTRFS_I(inode)->defrag_bytes &&
1572             test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1573                            EXTENT_DEFRAG, 0, NULL))
1574                 return 1;
1575 
1576         return 0;
1577 }
1578 
1579 /*
1580  * extent_io.c call back to do delayed allocation processing
1581  */
1582 static int run_delalloc_range(void *private_data, struct page *locked_page,
1583                               u64 start, u64 end, int *page_started,
1584                               unsigned long *nr_written,
1585                               struct writeback_control *wbc)
1586 {
1587         struct inode *inode = private_data;
1588         int ret;
1589         int force_cow = need_force_cow(inode, start, end);
1590         unsigned int write_flags = wbc_to_write_flags(wbc);
1591 
1592         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1593                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1594                                          page_started, 1, nr_written);
1595         } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1596                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1597                                          page_started, 0, nr_written);
1598         } else if (!inode_need_compress(inode, start, end)) {
1599                 ret = cow_file_range(inode, locked_page, start, end, end,
1600                                       page_started, nr_written, 1, NULL);
1601         } else {
1602                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1603                         &BTRFS_I(inode)->runtime_flags);
1604                 ret = cow_file_range_async(inode, locked_page, start, end,
1605                                            page_started, nr_written,
1606                                            write_flags);
1607         }
1608         if (ret)
1609                 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1610         return ret;
1611 }
1612 
1613 static void btrfs_split_extent_hook(void *private_data,
1614                                     struct extent_state *orig, u64 split)
1615 {
1616         struct inode *inode = private_data;
1617         u64 size;
1618 
1619         /* not delalloc, ignore it */
1620         if (!(orig->state & EXTENT_DELALLOC))
1621                 return;
1622 
1623         size = orig->end - orig->start + 1;
1624         if (size > BTRFS_MAX_EXTENT_SIZE) {
1625                 u32 num_extents;
1626                 u64 new_size;
1627 
1628                 /*
1629                  * See the explanation in btrfs_merge_extent_hook, the same
1630                  * applies here, just in reverse.
1631                  */
1632                 new_size = orig->end - split + 1;
1633                 num_extents = count_max_extents(new_size);
1634                 new_size = split - orig->start;
1635                 num_extents += count_max_extents(new_size);
1636                 if (count_max_extents(size) >= num_extents)
1637                         return;
1638         }
1639 
1640         spin_lock(&BTRFS_I(inode)->lock);
1641         btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1642         spin_unlock(&BTRFS_I(inode)->lock);
1643 }
1644 
1645 /*
1646  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1647  * extents so we can keep track of new extents that are just merged onto old
1648  * extents, such as when we are doing sequential writes, so we can properly
1649  * account for the metadata space we'll need.
1650  */
1651 static void btrfs_merge_extent_hook(void *private_data,
1652                                     struct extent_state *new,
1653                                     struct extent_state *other)
1654 {
1655         struct inode *inode = private_data;
1656         u64 new_size, old_size;
1657         u32 num_extents;
1658 
1659         /* not delalloc, ignore it */
1660         if (!(other->state & EXTENT_DELALLOC))
1661                 return;
1662 
1663         if (new->start > other->start)
1664                 new_size = new->end - other->start + 1;
1665         else
1666                 new_size = other->end - new->start + 1;
1667 
1668         /* we're not bigger than the max, unreserve the space and go */
1669         if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1670                 spin_lock(&BTRFS_I(inode)->lock);
1671                 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1672                 spin_unlock(&BTRFS_I(inode)->lock);
1673                 return;
1674         }
1675 
1676         /*
1677          * We have to add up either side to figure out how many extents were
1678          * accounted for before we merged into one big extent.  If the number of
1679          * extents we accounted for is <= the amount we need for the new range
1680          * then we can return, otherwise drop.  Think of it like this
1681          *
1682          * [ 4k][MAX_SIZE]
1683          *
1684          * So we've grown the extent by a MAX_SIZE extent, this would mean we
1685          * need 2 outstanding extents, on one side we have 1 and the other side
1686          * we have 1 so they are == and we can return.  But in this case
1687          *
1688          * [MAX_SIZE+4k][MAX_SIZE+4k]
1689          *
1690          * Each range on their own accounts for 2 extents, but merged together
1691          * they are only 3 extents worth of accounting, so we need to drop in
1692          * this case.
1693          */
1694         old_size = other->end - other->start + 1;
1695         num_extents = count_max_extents(old_size);
1696         old_size = new->end - new->start + 1;
1697         num_extents += count_max_extents(old_size);
1698         if (count_max_extents(new_size) >= num_extents)
1699                 return;
1700 
1701         spin_lock(&BTRFS_I(inode)->lock);
1702         btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1703         spin_unlock(&BTRFS_I(inode)->lock);
1704 }
1705 
1706 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1707                                       struct inode *inode)
1708 {
1709         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1710 
1711         spin_lock(&root->delalloc_lock);
1712         if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1713                 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1714                               &root->delalloc_inodes);
1715                 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1716                         &BTRFS_I(inode)->runtime_flags);
1717                 root->nr_delalloc_inodes++;
1718                 if (root->nr_delalloc_inodes == 1) {
1719                         spin_lock(&fs_info->delalloc_root_lock);
1720                         BUG_ON(!list_empty(&root->delalloc_root));
1721                         list_add_tail(&root->delalloc_root,
1722                                       &fs_info->delalloc_roots);
1723                         spin_unlock(&fs_info->delalloc_root_lock);
1724                 }
1725         }
1726         spin_unlock(&root->delalloc_lock);
1727 }
1728 
1729 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1730                                      struct btrfs_inode *inode)
1731 {
1732         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1733 
1734         spin_lock(&root->delalloc_lock);
1735         if (!list_empty(&inode->delalloc_inodes)) {
1736                 list_del_init(&inode->delalloc_inodes);
1737                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1738                           &inode->runtime_flags);
1739                 root->nr_delalloc_inodes--;
1740                 if (!root->nr_delalloc_inodes) {
1741                         spin_lock(&fs_info->delalloc_root_lock);
1742                         BUG_ON(list_empty(&root->delalloc_root));
1743                         list_del_init(&root->delalloc_root);
1744                         spin_unlock(&fs_info->delalloc_root_lock);
1745                 }
1746         }
1747         spin_unlock(&root->delalloc_lock);
1748 }
1749 
1750 /*
1751  * extent_io.c set_bit_hook, used to track delayed allocation
1752  * bytes in this file, and to maintain the list of inodes that
1753  * have pending delalloc work to be done.
1754  */
1755 static void btrfs_set_bit_hook(void *private_data,
1756                                struct extent_state *state, unsigned *bits)
1757 {
1758         struct inode *inode = private_data;
1759 
1760         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1761 
1762         if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1763                 WARN_ON(1);
1764         /*
1765          * set_bit and clear bit hooks normally require _irqsave/restore
1766          * but in this case, we are only testing for the DELALLOC
1767          * bit, which is only set or cleared with irqs on
1768          */
1769         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1770                 struct btrfs_root *root = BTRFS_I(inode)->root;
1771                 u64 len = state->end + 1 - state->start;
1772                 u32 num_extents = count_max_extents(len);
1773                 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1774 
1775                 spin_lock(&BTRFS_I(inode)->lock);
1776                 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1777                 spin_unlock(&BTRFS_I(inode)->lock);
1778 
1779                 /* For sanity tests */
1780                 if (btrfs_is_testing(fs_info))
1781                         return;
1782 
1783                 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1784                                          fs_info->delalloc_batch);
1785                 spin_lock(&BTRFS_I(inode)->lock);
1786                 BTRFS_I(inode)->delalloc_bytes += len;
1787                 if (*bits & EXTENT_DEFRAG)
1788                         BTRFS_I(inode)->defrag_bytes += len;
1789                 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1790                                          &BTRFS_I(inode)->runtime_flags))
1791                         btrfs_add_delalloc_inodes(root, inode);
1792                 spin_unlock(&BTRFS_I(inode)->lock);
1793         }
1794 
1795         if (!(state->state & EXTENT_DELALLOC_NEW) &&
1796             (*bits & EXTENT_DELALLOC_NEW)) {
1797                 spin_lock(&BTRFS_I(inode)->lock);
1798                 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1799                         state->start;
1800                 spin_unlock(&BTRFS_I(inode)->lock);
1801         }
1802 }
1803 
1804 /*
1805  * extent_io.c clear_bit_hook, see set_bit_hook for why
1806  */
1807 static void btrfs_clear_bit_hook(void *private_data,
1808                                  struct extent_state *state,
1809                                  unsigned *bits)
1810 {
1811         struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1812         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1813         u64 len = state->end + 1 - state->start;
1814         u32 num_extents = count_max_extents(len);
1815 
1816         if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1817                 spin_lock(&inode->lock);
1818                 inode->defrag_bytes -= len;
1819                 spin_unlock(&inode->lock);
1820         }
1821 
1822         /*
1823          * set_bit and clear bit hooks normally require _irqsave/restore
1824          * but in this case, we are only testing for the DELALLOC
1825          * bit, which is only set or cleared with irqs on
1826          */
1827         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1828                 struct btrfs_root *root = inode->root;
1829                 bool do_list = !btrfs_is_free_space_inode(inode);
1830 
1831                 spin_lock(&inode->lock);
1832                 btrfs_mod_outstanding_extents(inode, -num_extents);
1833                 spin_unlock(&inode->lock);
1834 
1835                 /*
1836                  * We don't reserve metadata space for space cache inodes so we
1837                  * don't need to call dellalloc_release_metadata if there is an
1838                  * error.
1839                  */
1840                 if (*bits & EXTENT_CLEAR_META_RESV &&
1841                     root != fs_info->tree_root)
1842                         btrfs_delalloc_release_metadata(inode, len);
1843 
1844                 /* For sanity tests. */
1845                 if (btrfs_is_testing(fs_info))
1846                         return;
1847 
1848                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1849                     do_list && !(state->state & EXTENT_NORESERVE) &&
1850                     (*bits & EXTENT_CLEAR_DATA_RESV))
1851                         btrfs_free_reserved_data_space_noquota(
1852                                         &inode->vfs_inode,
1853                                         state->start, len);
1854 
1855                 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1856                                          fs_info->delalloc_batch);
1857                 spin_lock(&inode->lock);
1858                 inode->delalloc_bytes -= len;
1859                 if (do_list && inode->delalloc_bytes == 0 &&
1860                     test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1861                                         &inode->runtime_flags))
1862                         btrfs_del_delalloc_inode(root, inode);
1863                 spin_unlock(&inode->lock);
1864         }
1865 
1866         if ((state->state & EXTENT_DELALLOC_NEW) &&
1867             (*bits & EXTENT_DELALLOC_NEW)) {
1868                 spin_lock(&inode->lock);
1869                 ASSERT(inode->new_delalloc_bytes >= len);
1870                 inode->new_delalloc_bytes -= len;
1871                 spin_unlock(&inode->lock);
1872         }
1873 }
1874 
1875 /*
1876  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1877  * we don't create bios that span stripes or chunks
1878  *
1879  * return 1 if page cannot be merged to bio
1880  * return 0 if page can be merged to bio
1881  * return error otherwise
1882  */
1883 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1884                          size_t size, struct bio *bio,
1885                          unsigned long bio_flags)
1886 {
1887         struct inode *inode = page->mapping->host;
1888         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1889         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1890         u64 length = 0;
1891         u64 map_length;
1892         int ret;
1893 
1894         if (bio_flags & EXTENT_BIO_COMPRESSED)
1895                 return 0;
1896 
1897         length = bio->bi_iter.bi_size;
1898         map_length = length;
1899         ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1900                               NULL, 0);
1901         if (ret < 0)
1902                 return ret;
1903         if (map_length < length + size)
1904                 return 1;
1905         return 0;
1906 }
1907 
1908 /*
1909  * in order to insert checksums into the metadata in large chunks,
1910  * we wait until bio submission time.   All the pages in the bio are
1911  * checksummed and sums are attached onto the ordered extent record.
1912  *
1913  * At IO completion time the cums attached on the ordered extent record
1914  * are inserted into the btree
1915  */
1916 static blk_status_t __btrfs_submit_bio_start(void *private_data, struct bio *bio,
1917                                     int mirror_num, unsigned long bio_flags,
1918                                     u64 bio_offset)
1919 {
1920         struct inode *inode = private_data;
1921         blk_status_t ret = 0;
1922 
1923         ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1924         BUG_ON(ret); /* -ENOMEM */
1925         return 0;
1926 }
1927 
1928 /*
1929  * in order to insert checksums into the metadata in large chunks,
1930  * we wait until bio submission time.   All the pages in the bio are
1931  * checksummed and sums are attached onto the ordered extent record.
1932  *
1933  * At IO completion time the cums attached on the ordered extent record
1934  * are inserted into the btree
1935  */
1936 static blk_status_t __btrfs_submit_bio_done(void *private_data, struct bio *bio,
1937                           int mirror_num, unsigned long bio_flags,
1938                           u64 bio_offset)
1939 {
1940         struct inode *inode = private_data;
1941         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1942         blk_status_t ret;
1943 
1944         ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1945         if (ret) {
1946                 bio->bi_status = ret;
1947                 bio_endio(bio);
1948         }
1949         return ret;
1950 }
1951 
1952 /*
1953  * extent_io.c submission hook. This does the right thing for csum calculation
1954  * on write, or reading the csums from the tree before a read
1955  */
1956 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1957                                  int mirror_num, unsigned long bio_flags,
1958                                  u64 bio_offset)
1959 {
1960         struct inode *inode = private_data;
1961         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1962         struct btrfs_root *root = BTRFS_I(inode)->root;
1963         enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1964         blk_status_t ret = 0;
1965         int skip_sum;
1966         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1967 
1968         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1969 
1970         if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1971                 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1972 
1973         if (bio_op(bio) != REQ_OP_WRITE) {
1974                 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1975                 if (ret)
1976                         goto out;
1977 
1978                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1979                         ret = btrfs_submit_compressed_read(inode, bio,
1980                                                            mirror_num,
1981                                                            bio_flags);
1982                         goto out;
1983                 } else if (!skip_sum) {
1984                         ret = btrfs_lookup_bio_sums(inode, bio, NULL);
1985                         if (ret)
1986                                 goto out;
1987                 }
1988                 goto mapit;
1989         } else if (async && !skip_sum) {
1990                 /* csum items have already been cloned */
1991                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1992                         goto mapit;
1993                 /* we're doing a write, do the async checksumming */
1994                 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
1995                                           bio_offset, inode,
1996                                           __btrfs_submit_bio_start,
1997                                           __btrfs_submit_bio_done);
1998                 goto out;
1999         } else if (!skip_sum) {
2000                 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2001                 if (ret)
2002                         goto out;
2003         }
2004 
2005 mapit:
2006         ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2007 
2008 out:
2009         if (ret) {
2010                 bio->bi_status = ret;
2011                 bio_endio(bio);
2012         }
2013         return ret;
2014 }
2015 
2016 /*
2017  * given a list of ordered sums record them in the inode.  This happens
2018  * at IO completion time based on sums calculated at bio submission time.
2019  */
2020 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2021                              struct inode *inode, struct list_head *list)
2022 {
2023         struct btrfs_ordered_sum *sum;
2024 
2025         list_for_each_entry(sum, list, list) {
2026                 trans->adding_csums = 1;
2027                 btrfs_csum_file_blocks(trans,
2028                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
2029                 trans->adding_csums = 0;
2030         }
2031         return 0;
2032 }
2033 
2034 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2035                               unsigned int extra_bits,
2036                               struct extent_state **cached_state, int dedupe)
2037 {
2038         WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2039         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2040                                    extra_bits, cached_state);
2041 }
2042 
2043 /* see btrfs_writepage_start_hook for details on why this is required */
2044 struct btrfs_writepage_fixup {
2045         struct page *page;
2046         struct btrfs_work work;
2047 };
2048 
2049 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2050 {
2051         struct btrfs_writepage_fixup *fixup;
2052         struct btrfs_ordered_extent *ordered;
2053         struct extent_state *cached_state = NULL;
2054         struct extent_changeset *data_reserved = NULL;
2055         struct page *page;
2056         struct inode *inode;
2057         u64 page_start;
2058         u64 page_end;
2059         int ret;
2060 
2061         fixup = container_of(work, struct btrfs_writepage_fixup, work);
2062         page = fixup->page;
2063 again:
2064         lock_page(page);
2065         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2066                 ClearPageChecked(page);
2067                 goto out_page;
2068         }
2069 
2070         inode = page->mapping->host;
2071         page_start = page_offset(page);
2072         page_end = page_offset(page) + PAGE_SIZE - 1;
2073 
2074         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2075                          &cached_state);
2076 
2077         /* already ordered? We're done */
2078         if (PagePrivate2(page))
2079                 goto out;
2080 
2081         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2082                                         PAGE_SIZE);
2083         if (ordered) {
2084                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2085                                      page_end, &cached_state, GFP_NOFS);
2086                 unlock_page(page);
2087                 btrfs_start_ordered_extent(inode, ordered, 1);
2088                 btrfs_put_ordered_extent(ordered);
2089                 goto again;
2090         }
2091 
2092         ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2093                                            PAGE_SIZE);
2094         if (ret) {
2095                 mapping_set_error(page->mapping, ret);
2096                 end_extent_writepage(page, ret, page_start, page_end);
2097                 ClearPageChecked(page);
2098                 goto out;
2099          }
2100 
2101         btrfs_set_extent_delalloc(inode, page_start, page_end, 0, &cached_state,
2102                                   0);
2103         ClearPageChecked(page);
2104         set_page_dirty(page);
2105         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2106 out:
2107         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2108                              &cached_state, GFP_NOFS);
2109 out_page:
2110         unlock_page(page);
2111         put_page(page);
2112         kfree(fixup);
2113         extent_changeset_free(data_reserved);
2114 }
2115 
2116 /*
2117  * There are a few paths in the higher layers of the kernel that directly
2118  * set the page dirty bit without asking the filesystem if it is a
2119  * good idea.  This causes problems because we want to make sure COW
2120  * properly happens and the data=ordered rules are followed.
2121  *
2122  * In our case any range that doesn't have the ORDERED bit set
2123  * hasn't been properly setup for IO.  We kick off an async process
2124  * to fix it up.  The async helper will wait for ordered extents, set
2125  * the delalloc bit and make it safe to write the page.
2126  */
2127 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2128 {
2129         struct inode *inode = page->mapping->host;
2130         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2131         struct btrfs_writepage_fixup *fixup;
2132 
2133         /* this page is properly in the ordered list */
2134         if (TestClearPagePrivate2(page))
2135                 return 0;
2136 
2137         if (PageChecked(page))
2138                 return -EAGAIN;
2139 
2140         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2141         if (!fixup)
2142                 return -EAGAIN;
2143 
2144         SetPageChecked(page);
2145         get_page(page);
2146         btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2147                         btrfs_writepage_fixup_worker, NULL, NULL);
2148         fixup->page = page;
2149         btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2150         return -EBUSY;
2151 }
2152 
2153 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2154                                        struct inode *inode, u64 file_pos,
2155                                        u64 disk_bytenr, u64 disk_num_bytes,
2156                                        u64 num_bytes, u64 ram_bytes,
2157                                        u8 compression, u8 encryption,
2158                                        u16 other_encoding, int extent_type)
2159 {
2160         struct btrfs_root *root = BTRFS_I(inode)->root;
2161         struct btrfs_file_extent_item *fi;
2162         struct btrfs_path *path;
2163         struct extent_buffer *leaf;
2164         struct btrfs_key ins;
2165         u64 qg_released;
2166         int extent_inserted = 0;
2167         int ret;
2168 
2169         path = btrfs_alloc_path();
2170         if (!path)
2171                 return -ENOMEM;
2172 
2173         /*
2174          * we may be replacing one extent in the tree with another.
2175          * The new extent is pinned in the extent map, and we don't want
2176          * to drop it from the cache until it is completely in the btree.
2177          *
2178          * So, tell btrfs_drop_extents to leave this extent in the cache.
2179          * the caller is expected to unpin it and allow it to be merged
2180          * with the others.
2181          */
2182         ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2183                                    file_pos + num_bytes, NULL, 0,
2184                                    1, sizeof(*fi), &extent_inserted);
2185         if (ret)
2186                 goto out;
2187 
2188         if (!extent_inserted) {
2189                 ins.objectid = btrfs_ino(BTRFS_I(inode));
2190                 ins.offset = file_pos;
2191                 ins.type = BTRFS_EXTENT_DATA_KEY;
2192 
2193                 path->leave_spinning = 1;
2194                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2195                                               sizeof(*fi));
2196                 if (ret)
2197                         goto out;
2198         }
2199         leaf = path->nodes[0];
2200         fi = btrfs_item_ptr(leaf, path->slots[0],
2201                             struct btrfs_file_extent_item);
2202         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2203         btrfs_set_file_extent_type(leaf, fi, extent_type);
2204         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2205         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2206         btrfs_set_file_extent_offset(leaf, fi, 0);
2207         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2208         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2209         btrfs_set_file_extent_compression(leaf, fi, compression);
2210         btrfs_set_file_extent_encryption(leaf, fi, encryption);
2211         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2212 
2213         btrfs_mark_buffer_dirty(leaf);
2214         btrfs_release_path(path);
2215 
2216         inode_add_bytes(inode, num_bytes);
2217 
2218         ins.objectid = disk_bytenr;
2219         ins.offset = disk_num_bytes;
2220         ins.type = BTRFS_EXTENT_ITEM_KEY;
2221 
2222         /*
2223          * Release the reserved range from inode dirty range map, as it is
2224          * already moved into delayed_ref_head
2225          */
2226         ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2227         if (ret < 0)
2228                 goto out;
2229         qg_released = ret;
2230         ret = btrfs_alloc_reserved_file_extent(trans, root,
2231                                                btrfs_ino(BTRFS_I(inode)),
2232                                                file_pos, qg_released, &ins);
2233 out:
2234         btrfs_free_path(path);
2235 
2236         return ret;
2237 }
2238 
2239 /* snapshot-aware defrag */
2240 struct sa_defrag_extent_backref {
2241         struct rb_node node;
2242         struct old_sa_defrag_extent *old;
2243         u64 root_id;
2244         u64 inum;
2245         u64 file_pos;
2246         u64 extent_offset;
2247         u64 num_bytes;
2248         u64 generation;
2249 };
2250 
2251 struct old_sa_defrag_extent {
2252         struct list_head list;
2253         struct new_sa_defrag_extent *new;
2254 
2255         u64 extent_offset;
2256         u64 bytenr;
2257         u64 offset;
2258         u64 len;
2259         int count;
2260 };
2261 
2262 struct new_sa_defrag_extent {
2263         struct rb_root root;
2264         struct list_head head;
2265         struct btrfs_path *path;
2266         struct inode *inode;
2267         u64 file_pos;
2268         u64 len;
2269         u64 bytenr;
2270         u64 disk_len;
2271         u8 compress_type;
2272 };
2273 
2274 static int backref_comp(struct sa_defrag_extent_backref *b1,
2275                         struct sa_defrag_extent_backref *b2)
2276 {
2277         if (b1->root_id < b2->root_id)
2278                 return -1;
2279         else if (b1->root_id > b2->root_id)
2280                 return 1;
2281 
2282         if (b1->inum < b2->inum)
2283                 return -1;
2284         else if (b1->inum > b2->inum)
2285                 return 1;
2286 
2287         if (b1->file_pos < b2->file_pos)
2288                 return -1;
2289         else if (b1->file_pos > b2->file_pos)
2290                 return 1;
2291 
2292         /*
2293          * [------------------------------] ===> (a range of space)
2294          *     |<--->|   |<---->| =============> (fs/file tree A)
2295          * |<---------------------------->| ===> (fs/file tree B)
2296          *
2297          * A range of space can refer to two file extents in one tree while
2298          * refer to only one file extent in another tree.
2299          *
2300          * So we may process a disk offset more than one time(two extents in A)
2301          * and locate at the same extent(one extent in B), then insert two same
2302          * backrefs(both refer to the extent in B).
2303          */
2304         return 0;
2305 }
2306 
2307 static void backref_insert(struct rb_root *root,
2308                            struct sa_defrag_extent_backref *backref)
2309 {
2310         struct rb_node **p = &root->rb_node;
2311         struct rb_node *parent = NULL;
2312         struct sa_defrag_extent_backref *entry;
2313         int ret;
2314 
2315         while (*p) {
2316                 parent = *p;
2317                 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2318 
2319                 ret = backref_comp(backref, entry);
2320                 if (ret < 0)
2321                         p = &(*p)->rb_left;
2322                 else
2323                         p = &(*p)->rb_right;
2324         }
2325 
2326         rb_link_node(&backref->node, parent, p);
2327         rb_insert_color(&backref->node, root);
2328 }
2329 
2330 /*
2331  * Note the backref might has changed, and in this case we just return 0.
2332  */
2333 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2334                                        void *ctx)
2335 {
2336         struct btrfs_file_extent_item *extent;
2337         struct old_sa_defrag_extent *old = ctx;
2338         struct new_sa_defrag_extent *new = old->new;
2339         struct btrfs_path *path = new->path;
2340         struct btrfs_key key;
2341         struct btrfs_root *root;
2342         struct sa_defrag_extent_backref *backref;
2343         struct extent_buffer *leaf;
2344         struct inode *inode = new->inode;
2345         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2346         int slot;
2347         int ret;
2348         u64 extent_offset;
2349         u64 num_bytes;
2350 
2351         if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2352             inum == btrfs_ino(BTRFS_I(inode)))
2353                 return 0;
2354 
2355         key.objectid = root_id;
2356         key.type = BTRFS_ROOT_ITEM_KEY;
2357         key.offset = (u64)-1;
2358 
2359         root = btrfs_read_fs_root_no_name(fs_info, &key);
2360         if (IS_ERR(root)) {
2361                 if (PTR_ERR(root) == -ENOENT)
2362                         return 0;
2363                 WARN_ON(1);
2364                 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2365                          inum, offset, root_id);
2366                 return PTR_ERR(root);
2367         }
2368 
2369         key.objectid = inum;
2370         key.type = BTRFS_EXTENT_DATA_KEY;
2371         if (offset > (u64)-1 << 32)
2372                 key.offset = 0;
2373         else
2374                 key.offset = offset;
2375 
2376         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2377         if (WARN_ON(ret < 0))
2378                 return ret;
2379         ret = 0;
2380 
2381         while (1) {
2382                 cond_resched();
2383 
2384                 leaf = path->nodes[0];
2385                 slot = path->slots[0];
2386 
2387                 if (slot >= btrfs_header_nritems(leaf)) {
2388                         ret = btrfs_next_leaf(root, path);
2389                         if (ret < 0) {
2390                                 goto out;
2391                         } else if (ret > 0) {
2392                                 ret = 0;
2393                                 goto out;
2394                         }
2395                         continue;
2396                 }
2397 
2398                 path->slots[0]++;
2399 
2400                 btrfs_item_key_to_cpu(leaf, &key, slot);
2401 
2402                 if (key.objectid > inum)
2403                         goto out;
2404 
2405                 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2406                         continue;
2407 
2408                 extent = btrfs_item_ptr(leaf, slot,
2409                                         struct btrfs_file_extent_item);
2410 
2411                 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2412                         continue;
2413 
2414                 /*
2415                  * 'offset' refers to the exact key.offset,
2416                  * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2417                  * (key.offset - extent_offset).
2418                  */
2419                 if (key.offset != offset)
2420                         continue;
2421 
2422                 extent_offset = btrfs_file_extent_offset(leaf, extent);
2423                 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2424 
2425                 if (extent_offset >= old->extent_offset + old->offset +
2426                     old->len || extent_offset + num_bytes <=
2427                     old->extent_offset + old->offset)
2428                         continue;
2429                 break;
2430         }
2431 
2432         backref = kmalloc(sizeof(*backref), GFP_NOFS);
2433         if (!backref) {
2434                 ret = -ENOENT;
2435                 goto out;
2436         }
2437 
2438         backref->root_id = root_id;
2439         backref->inum = inum;
2440         backref->file_pos = offset;
2441         backref->num_bytes = num_bytes;
2442         backref->extent_offset = extent_offset;
2443         backref->generation = btrfs_file_extent_generation(leaf, extent);
2444         backref->old = old;
2445         backref_insert(&new->root, backref);
2446         old->count++;
2447 out:
2448         btrfs_release_path(path);
2449         WARN_ON(ret);
2450         return ret;
2451 }
2452 
2453 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2454                                    struct new_sa_defrag_extent *new)
2455 {
2456         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2457         struct old_sa_defrag_extent *old, *tmp;
2458         int ret;
2459 
2460         new->path = path;
2461 
2462         list_for_each_entry_safe(old, tmp, &new->head, list) {
2463                 ret = iterate_inodes_from_logical(old->bytenr +
2464                                                   old->extent_offset, fs_info,
2465                                                   path, record_one_backref,
2466                                                   old, false);
2467                 if (ret < 0 && ret != -ENOENT)
2468                         return false;
2469 
2470                 /* no backref to be processed for this extent */
2471                 if (!old->count) {
2472                         list_del(&old->list);
2473                         kfree(old);
2474                 }
2475         }
2476 
2477         if (list_empty(&new->head))
2478                 return false;
2479 
2480         return true;
2481 }
2482 
2483 static int relink_is_mergable(struct extent_buffer *leaf,
2484                               struct btrfs_file_extent_item *fi,
2485                               struct new_sa_defrag_extent *new)
2486 {
2487         if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2488                 return 0;
2489 
2490         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2491                 return 0;
2492 
2493         if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2494                 return 0;
2495 
2496         if (btrfs_file_extent_encryption(leaf, fi) ||
2497             btrfs_file_extent_other_encoding(leaf, fi))
2498                 return 0;
2499 
2500         return 1;
2501 }
2502 
2503 /*
2504  * Note the backref might has changed, and in this case we just return 0.
2505  */
2506 static noinline int relink_extent_backref(struct btrfs_path *path,
2507                                  struct sa_defrag_extent_backref *prev,
2508                                  struct sa_defrag_extent_backref *backref)
2509 {
2510         struct btrfs_file_extent_item *extent;
2511         struct btrfs_file_extent_item *item;
2512         struct btrfs_ordered_extent *ordered;
2513         struct btrfs_trans_handle *trans;
2514         struct btrfs_root *root;
2515         struct btrfs_key key;
2516         struct extent_buffer *leaf;
2517         struct old_sa_defrag_extent *old = backref->old;
2518         struct new_sa_defrag_extent *new = old->new;
2519         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2520         struct inode *inode;
2521         struct extent_state *cached = NULL;
2522         int ret = 0;
2523         u64 start;
2524         u64 len;
2525         u64 lock_start;
2526         u64 lock_end;
2527         bool merge = false;
2528         int index;
2529 
2530         if (prev && prev->root_id == backref->root_id &&
2531             prev->inum == backref->inum &&
2532             prev->file_pos + prev->num_bytes == backref->file_pos)
2533                 merge = true;
2534 
2535         /* step 1: get root */
2536         key.objectid = backref->root_id;
2537         key.type = BTRFS_ROOT_ITEM_KEY;
2538         key.offset = (u64)-1;
2539 
2540         index = srcu_read_lock(&fs_info->subvol_srcu);
2541 
2542         root = btrfs_read_fs_root_no_name(fs_info, &key);
2543         if (IS_ERR(root)) {
2544                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2545                 if (PTR_ERR(root) == -ENOENT)
2546                         return 0;
2547                 return PTR_ERR(root);
2548         }
2549 
2550         if (btrfs_root_readonly(root)) {
2551                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2552                 return 0;
2553         }
2554 
2555         /* step 2: get inode */
2556         key.objectid = backref->inum;
2557         key.type = BTRFS_INODE_ITEM_KEY;
2558         key.offset = 0;
2559 
2560         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2561         if (IS_ERR(inode)) {
2562                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2563                 return 0;
2564         }
2565 
2566         srcu_read_unlock(&fs_info->subvol_srcu, index);
2567 
2568         /* step 3: relink backref */
2569         lock_start = backref->file_pos;
2570         lock_end = backref->file_pos + backref->num_bytes - 1;
2571         lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2572                          &cached);
2573 
2574         ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2575         if (ordered) {
2576                 btrfs_put_ordered_extent(ordered);
2577                 goto out_unlock;
2578         }
2579 
2580         trans = btrfs_join_transaction(root);
2581         if (IS_ERR(trans)) {
2582                 ret = PTR_ERR(trans);
2583                 goto out_unlock;
2584         }
2585 
2586         key.objectid = backref->inum;
2587         key.type = BTRFS_EXTENT_DATA_KEY;
2588         key.offset = backref->file_pos;
2589 
2590         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2591         if (ret < 0) {
2592                 goto out_free_path;
2593         } else if (ret > 0) {
2594                 ret = 0;
2595                 goto out_free_path;
2596         }
2597 
2598         extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2599                                 struct btrfs_file_extent_item);
2600 
2601         if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2602             backref->generation)
2603                 goto out_free_path;
2604 
2605         btrfs_release_path(path);
2606 
2607         start = backref->file_pos;
2608         if (backref->extent_offset < old->extent_offset + old->offset)
2609                 start += old->extent_offset + old->offset -
2610                          backref->extent_offset;
2611 
2612         len = min(backref->extent_offset + backref->num_bytes,
2613                   old->extent_offset + old->offset + old->len);
2614         len -= max(backref->extent_offset, old->extent_offset + old->offset);
2615 
2616         ret = btrfs_drop_extents(trans, root, inode, start,
2617                                  start + len, 1);
2618         if (ret)
2619                 goto out_free_path;
2620 again:
2621         key.objectid = btrfs_ino(BTRFS_I(inode));
2622         key.type = BTRFS_EXTENT_DATA_KEY;
2623         key.offset = start;
2624 
2625         path->leave_spinning = 1;
2626         if (merge) {
2627                 struct btrfs_file_extent_item *fi;
2628                 u64 extent_len;
2629                 struct btrfs_key found_key;
2630 
2631                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2632                 if (ret < 0)
2633                         goto out_free_path;
2634 
2635                 path->slots[0]--;
2636                 leaf = path->nodes[0];
2637                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2638 
2639                 fi = btrfs_item_ptr(leaf, path->slots[0],
2640                                     struct btrfs_file_extent_item);
2641                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2642 
2643                 if (extent_len + found_key.offset == start &&
2644                     relink_is_mergable(leaf, fi, new)) {
2645                         btrfs_set_file_extent_num_bytes(leaf, fi,
2646                                                         extent_len + len);
2647                         btrfs_mark_buffer_dirty(leaf);
2648                         inode_add_bytes(inode, len);
2649 
2650                         ret = 1;
2651                         goto out_free_path;
2652                 } else {
2653                         merge = false;
2654                         btrfs_release_path(path);
2655                         goto again;
2656                 }
2657         }
2658 
2659         ret = btrfs_insert_empty_item(trans, root, path, &key,
2660                                         sizeof(*extent));
2661         if (ret) {
2662                 btrfs_abort_transaction(trans, ret);
2663                 goto out_free_path;
2664         }
2665 
2666         leaf = path->nodes[0];
2667         item = btrfs_item_ptr(leaf, path->slots[0],
2668                                 struct btrfs_file_extent_item);
2669         btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2670         btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2671         btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2672         btrfs_set_file_extent_num_bytes(leaf, item, len);
2673         btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2674         btrfs_set_file_extent_generation(leaf, item, trans->transid);
2675         btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2676         btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2677         btrfs_set_file_extent_encryption(leaf, item, 0);
2678         btrfs_set_file_extent_other_encoding(leaf, item, 0);
2679 
2680         btrfs_mark_buffer_dirty(leaf);
2681         inode_add_bytes(inode, len);
2682         btrfs_release_path(path);
2683 
2684         ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2685                         new->disk_len, 0,
2686                         backref->root_id, backref->inum,
2687                         new->file_pos); /* start - extent_offset */
2688         if (ret) {
2689                 btrfs_abort_transaction(trans, ret);
2690                 goto out_free_path;
2691         }
2692 
2693         ret = 1;
2694 out_free_path:
2695         btrfs_release_path(path);
2696         path->leave_spinning = 0;
2697         btrfs_end_transaction(trans);
2698 out_unlock:
2699         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2700                              &cached, GFP_NOFS);
2701         iput(inode);
2702         return ret;
2703 }
2704 
2705 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2706 {
2707         struct old_sa_defrag_extent *old, *tmp;
2708 
2709         if (!new)
2710                 return;
2711 
2712         list_for_each_entry_safe(old, tmp, &new->head, list) {
2713                 kfree(old);
2714         }
2715         kfree(new);
2716 }
2717 
2718 static void relink_file_extents(struct new_sa_defrag_extent *new)
2719 {
2720         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2721         struct btrfs_path *path;
2722         struct sa_defrag_extent_backref *backref;
2723         struct sa_defrag_extent_backref *prev = NULL;
2724         struct inode *inode;
2725         struct btrfs_root *root;
2726         struct rb_node *node;
2727         int ret;
2728 
2729         inode = new->inode;
2730         root = BTRFS_I(inode)->root;
2731 
2732         path = btrfs_alloc_path();
2733         if (!path)
2734                 return;
2735 
2736         if (!record_extent_backrefs(path, new)) {
2737                 btrfs_free_path(path);
2738                 goto out;
2739         }
2740         btrfs_release_path(path);
2741 
2742         while (1) {
2743                 node = rb_first(&new->root);
2744                 if (!node)
2745                         break;
2746                 rb_erase(node, &new->root);
2747 
2748                 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2749 
2750                 ret = relink_extent_backref(path, prev, backref);
2751                 WARN_ON(ret < 0);
2752 
2753                 kfree(prev);
2754 
2755                 if (ret == 1)
2756                         prev = backref;
2757                 else
2758                         prev = NULL;
2759                 cond_resched();
2760         }
2761         kfree(prev);
2762 
2763         btrfs_free_path(path);
2764 out:
2765         free_sa_defrag_extent(new);
2766 
2767         atomic_dec(&fs_info->defrag_running);
2768         wake_up(&fs_info->transaction_wait);
2769 }
2770 
2771 static struct new_sa_defrag_extent *
2772 record_old_file_extents(struct inode *inode,
2773                         struct btrfs_ordered_extent *ordered)
2774 {
2775         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2776         struct btrfs_root *root = BTRFS_I(inode)->root;
2777         struct btrfs_path *path;
2778         struct btrfs_key key;
2779         struct old_sa_defrag_extent *old;
2780         struct new_sa_defrag_extent *new;
2781         int ret;
2782 
2783         new = kmalloc(sizeof(*new), GFP_NOFS);
2784         if (!new)
2785                 return NULL;
2786 
2787         new->inode = inode;
2788         new->file_pos = ordered->file_offset;
2789         new->len = ordered->len;
2790         new->bytenr = ordered->start;
2791         new->disk_len = ordered->disk_len;
2792         new->compress_type = ordered->compress_type;
2793         new->root = RB_ROOT;
2794         INIT_LIST_HEAD(&new->head);
2795 
2796         path = btrfs_alloc_path();
2797         if (!path)
2798                 goto out_kfree;
2799 
2800         key.objectid = btrfs_ino(BTRFS_I(inode));
2801         key.type = BTRFS_EXTENT_DATA_KEY;
2802         key.offset = new->file_pos;
2803 
2804         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2805         if (ret < 0)
2806                 goto out_free_path;
2807         if (ret > 0 && path->slots[0] > 0)
2808                 path->slots[0]--;
2809 
2810         /* find out all the old extents for the file range */
2811         while (1) {
2812                 struct btrfs_file_extent_item *extent;
2813                 struct extent_buffer *l;
2814                 int slot;
2815                 u64 num_bytes;
2816                 u64 offset;
2817                 u64 end;
2818                 u64 disk_bytenr;
2819                 u64 extent_offset;
2820 
2821                 l = path->nodes[0];
2822                 slot = path->slots[0];
2823 
2824                 if (slot >= btrfs_header_nritems(l)) {
2825                         ret = btrfs_next_leaf(root, path);
2826                         if (ret < 0)
2827                                 goto out_free_path;
2828                         else if (ret > 0)
2829                                 break;
2830                         continue;
2831                 }
2832 
2833                 btrfs_item_key_to_cpu(l, &key, slot);
2834 
2835                 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2836                         break;
2837                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2838                         break;
2839                 if (key.offset >= new->file_pos + new->len)
2840                         break;
2841 
2842                 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2843 
2844                 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2845                 if (key.offset + num_bytes < new->file_pos)
2846                         goto next;
2847 
2848                 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2849                 if (!disk_bytenr)
2850                         goto next;
2851 
2852                 extent_offset = btrfs_file_extent_offset(l, extent);
2853 
2854                 old = kmalloc(sizeof(*old), GFP_NOFS);
2855                 if (!old)
2856                         goto out_free_path;
2857 
2858                 offset = max(new->file_pos, key.offset);
2859                 end = min(new->file_pos + new->len, key.offset + num_bytes);
2860 
2861                 old->bytenr = disk_bytenr;
2862                 old->extent_offset = extent_offset;
2863                 old->offset = offset - key.offset;
2864                 old->len = end - offset;
2865                 old->new = new;
2866                 old->count = 0;
2867                 list_add_tail(&old->list, &new->head);
2868 next:
2869                 path->slots[0]++;
2870                 cond_resched();
2871         }
2872 
2873         btrfs_free_path(path);
2874         atomic_inc(&fs_info->defrag_running);
2875 
2876         return new;
2877 
2878 out_free_path:
2879         btrfs_free_path(path);
2880 out_kfree:
2881         free_sa_defrag_extent(new);
2882         return NULL;
2883 }
2884 
2885 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2886                                          u64 start, u64 len)
2887 {
2888         struct btrfs_block_group_cache *cache;
2889 
2890         cache = btrfs_lookup_block_group(fs_info, start);
2891         ASSERT(cache);
2892 
2893         spin_lock(&cache->lock);
2894         cache->delalloc_bytes -= len;
2895         spin_unlock(&cache->lock);
2896 
2897         btrfs_put_block_group(cache);
2898 }
2899 
2900 /* as ordered data IO finishes, this gets called so we can finish
2901  * an ordered extent if the range of bytes in the file it covers are
2902  * fully written.
2903  */
2904 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2905 {
2906         struct inode *inode = ordered_extent->inode;
2907         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2908         struct btrfs_root *root = BTRFS_I(inode)->root;
2909         struct btrfs_trans_handle *trans = NULL;
2910         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2911         struct extent_state *cached_state = NULL;
2912         struct new_sa_defrag_extent *new = NULL;
2913         int compress_type = 0;
2914         int ret = 0;
2915         u64 logical_len = ordered_extent->len;
2916         bool nolock;
2917         bool truncated = false;
2918         bool range_locked = false;
2919         bool clear_new_delalloc_bytes = false;
2920 
2921         if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2922             !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2923             !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2924                 clear_new_delalloc_bytes = true;
2925 
2926         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2927 
2928         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2929                 ret = -EIO;
2930                 goto out;
2931         }
2932 
2933         btrfs_free_io_failure_record(BTRFS_I(inode),
2934                         ordered_extent->file_offset,
2935                         ordered_extent->file_offset +
2936                         ordered_extent->len - 1);
2937 
2938         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2939                 truncated = true;
2940                 logical_len = ordered_extent->truncated_len;
2941                 /* Truncated the entire extent, don't bother adding */
2942                 if (!logical_len)
2943                         goto out;
2944         }
2945 
2946         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2947                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2948 
2949                 /*
2950                  * For mwrite(mmap + memset to write) case, we still reserve
2951                  * space for NOCOW range.
2952                  * As NOCOW won't cause a new delayed ref, just free the space
2953                  */
2954                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2955                                        ordered_extent->len);
2956                 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2957                 if (nolock)
2958                         trans = btrfs_join_transaction_nolock(root);
2959                 else
2960                         trans = btrfs_join_transaction(root);
2961                 if (IS_ERR(trans)) {
2962                         ret = PTR_ERR(trans);
2963                         trans = NULL;
2964                         goto out;
2965                 }
2966                 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2967                 ret = btrfs_update_inode_fallback(trans, root, inode);
2968                 if (ret) /* -ENOMEM or corruption */
2969                         btrfs_abort_transaction(trans, ret);
2970                 goto out;
2971         }
2972 
2973         range_locked = true;
2974         lock_extent_bits(io_tree, ordered_extent->file_offset,
2975                          ordered_extent->file_offset + ordered_extent->len - 1,
2976                          &cached_state);
2977 
2978         ret = test_range_bit(io_tree, ordered_extent->file_offset,
2979                         ordered_extent->file_offset + ordered_extent->len - 1,
2980                         EXTENT_DEFRAG, 0, cached_state);
2981         if (ret) {
2982                 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2983                 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2984                         /* the inode is shared */
2985                         new = record_old_file_extents(inode, ordered_extent);
2986 
2987                 clear_extent_bit(io_tree, ordered_extent->file_offset,
2988                         ordered_extent->file_offset + ordered_extent->len - 1,
2989                         EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2990         }
2991 
2992         if (nolock)
2993                 trans = btrfs_join_transaction_nolock(root);
2994         else
2995                 trans = btrfs_join_transaction(root);
2996         if (IS_ERR(trans)) {
2997                 ret = PTR_ERR(trans);
2998                 trans = NULL;
2999                 goto out;
3000         }
3001 
3002         trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3003 
3004         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3005                 compress_type = ordered_extent->compress_type;
3006         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3007                 BUG_ON(compress_type);
3008                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3009                                        ordered_extent->len);
3010                 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3011                                                 ordered_extent->file_offset,
3012                                                 ordered_extent->file_offset +
3013                                                 logical_len);
3014         } else {
3015                 BUG_ON(root == fs_info->tree_root);
3016                 ret = insert_reserved_file_extent(trans, inode,
3017                                                 ordered_extent->file_offset,
3018                                                 ordered_extent->start,
3019                                                 ordered_extent->disk_len,
3020                                                 logical_len, logical_len,
3021                                                 compress_type, 0, 0,
3022                                                 BTRFS_FILE_EXTENT_REG);
3023                 if (!ret)
3024                         btrfs_release_delalloc_bytes(fs_info,
3025                                                      ordered_extent->start,
3026                                                      ordered_extent->disk_len);
3027         }
3028         unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3029                            ordered_extent->file_offset, ordered_extent->len,
3030                            trans->transid);
3031         if (ret < 0) {
3032                 btrfs_abort_transaction(trans, ret);
3033                 goto out;
3034         }
3035 
3036         add_pending_csums(trans, inode, &ordered_extent->list);
3037 
3038         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3039         ret = btrfs_update_inode_fallback(trans, root, inode);
3040         if (ret) { /* -ENOMEM or corruption */
3041                 btrfs_abort_transaction(trans, ret);
3042                 goto out;
3043         }
3044         ret = 0;
3045 out:
3046         if (range_locked || clear_new_delalloc_bytes) {
3047                 unsigned int clear_bits = 0;
3048 
3049                 if (range_locked)
3050                         clear_bits |= EXTENT_LOCKED;
3051                 if (clear_new_delalloc_bytes)
3052                         clear_bits |= EXTENT_DELALLOC_NEW;
3053                 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3054                                  ordered_extent->file_offset,
3055                                  ordered_extent->file_offset +
3056                                  ordered_extent->len - 1,
3057                                  clear_bits,
3058                                  (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3059                                  0, &cached_state, GFP_NOFS);
3060         }
3061 
3062         if (trans)
3063                 btrfs_end_transaction(trans);
3064 
3065         if (ret || truncated) {
3066                 u64 start, end;
3067 
3068                 if (truncated)
3069                         start = ordered_extent->file_offset + logical_len;
3070                 else
3071                         start = ordered_extent->file_offset;
3072                 end = ordered_extent->file_offset + ordered_extent->len - 1;
3073                 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
3074 
3075                 /* Drop the cache for the part of the extent we didn't write. */
3076                 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3077 
3078                 /*
3079                  * If the ordered extent had an IOERR or something else went
3080                  * wrong we need to return the space for this ordered extent
3081                  * back to the allocator.  We only free the extent in the
3082                  * truncated case if we didn't write out the extent at all.
3083                  */
3084                 if ((ret || !logical_len) &&
3085                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3086                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3087                         btrfs_free_reserved_extent(fs_info,
3088                                                    ordered_extent->start,
3089                                                    ordered_extent->disk_len, 1);
3090         }
3091 
3092 
3093         /*
3094          * This needs to be done to make sure anybody waiting knows we are done
3095          * updating everything for this ordered extent.
3096          */
3097         btrfs_remove_ordered_extent(inode, ordered_extent);
3098 
3099         /* for snapshot-aware defrag */
3100         if (new) {
3101                 if (ret) {
3102                         free_sa_defrag_extent(new);
3103                         atomic_dec(&fs_info->defrag_running);
3104                 } else {
3105                         relink_file_extents(new);
3106                 }
3107         }
3108 
3109         /* once for us */
3110         btrfs_put_ordered_extent(ordered_extent);
3111         /* once for the tree */
3112         btrfs_put_ordered_extent(ordered_extent);
3113 
3114         return ret;
3115 }
3116 
3117 static void finish_ordered_fn(struct btrfs_work *work)
3118 {
3119         struct btrfs_ordered_extent *ordered_extent;
3120         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3121         btrfs_finish_ordered_io(ordered_extent);
3122 }
3123 
3124 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3125                                 struct extent_state *state, int uptodate)
3126 {
3127         struct inode *inode = page->mapping->host;
3128         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3129         struct btrfs_ordered_extent *ordered_extent = NULL;
3130         struct btrfs_workqueue *wq;
3131         btrfs_work_func_t func;
3132 
3133         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3134 
3135         ClearPagePrivate2(page);
3136         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3137                                             end - start + 1, uptodate))
3138                 return;
3139 
3140         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3141                 wq = fs_info->endio_freespace_worker;
3142                 func = btrfs_freespace_write_helper;
3143         } else {
3144                 wq = fs_info->endio_write_workers;
3145                 func = btrfs_endio_write_helper;
3146         }
3147 
3148         btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3149                         NULL);
3150         btrfs_queue_work(wq, &ordered_extent->work);
3151 }
3152 
3153 static int __readpage_endio_check(struct inode *inode,
3154                                   struct btrfs_io_bio *io_bio,
3155                                   int icsum, struct page *page,
3156                                   int pgoff, u64 start, size_t len)
3157 {
3158         char *kaddr;
3159         u32 csum_expected;
3160         u32 csum = ~(u32)0;
3161 
3162         csum_expected = *(((u32 *)io_bio->csum) + icsum);
3163 
3164         kaddr = kmap_atomic(page);
3165         csum = btrfs_csum_data(kaddr + pgoff, csum,  len);
3166         btrfs_csum_final(csum, (u8 *)&csum);
3167         if (csum != csum_expected)
3168                 goto zeroit;
3169 
3170         kunmap_atomic(kaddr);
3171         return 0;
3172 zeroit:
3173         btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3174                                     io_bio->mirror_num);
3175         memset(kaddr + pgoff, 1, len);
3176         flush_dcache_page(page);
3177         kunmap_atomic(kaddr);
3178         return -EIO;
3179 }
3180 
3181 /*
3182  * when reads are done, we need to check csums to verify the data is correct
3183  * if there's a match, we allow the bio to finish.  If not, the code in
3184  * extent_io.c will try to find good copies for us.
3185  */
3186 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3187                                       u64 phy_offset, struct page *page,
3188                                       u64 start, u64 end, int mirror)
3189 {
3190         size_t offset = start - page_offset(page);
3191         struct inode *inode = page->mapping->host;
3192         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3193         struct btrfs_root *root = BTRFS_I(inode)->root;
3194 
3195         if (PageChecked(page)) {
3196                 ClearPageChecked(page);
3197                 return 0;
3198         }
3199 
3200         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3201                 return 0;
3202 
3203         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3204             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3205                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3206                 return 0;
3207         }
3208 
3209         phy_offset >>= inode->i_sb->s_blocksize_bits;
3210         return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3211                                       start, (size_t)(end - start + 1));
3212 }
3213 
3214 void btrfs_add_delayed_iput(struct inode *inode)
3215 {
3216         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3217         struct btrfs_inode *binode = BTRFS_I(inode);
3218 
3219         if (atomic_add_unless(&inode->i_count, -1, 1))
3220                 return;
3221 
3222         spin_lock(&fs_info->delayed_iput_lock);
3223         if (binode->delayed_iput_count == 0) {
3224                 ASSERT(list_empty(&binode->delayed_iput));
3225                 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3226         } else {
3227                 binode->delayed_iput_count++;
3228         }
3229         spin_unlock(&fs_info->delayed_iput_lock);
3230 }
3231 
3232 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3233 {
3234 
3235         spin_lock(&fs_info->delayed_iput_lock);
3236         while (!list_empty(&fs_info->delayed_iputs)) {
3237                 struct btrfs_inode *inode;
3238 
3239                 inode = list_first_entry(&fs_info->delayed_iputs,
3240                                 struct btrfs_inode, delayed_iput);
3241                 if (inode->delayed_iput_count) {
3242                         inode->delayed_iput_count--;
3243                         list_move_tail(&inode->delayed_iput,
3244                                         &fs_info->delayed_iputs);
3245                 } else {
3246                         list_del_init(&inode->delayed_iput);
3247                 }
3248                 spin_unlock(&fs_info->delayed_iput_lock);
3249                 iput(&inode->vfs_inode);
3250                 spin_lock(&fs_info->delayed_iput_lock);
3251         }
3252         spin_unlock(&fs_info->delayed_iput_lock);
3253 }
3254 
3255 /*
3256  * This is called in transaction commit time. If there are no orphan
3257  * files in the subvolume, it removes orphan item and frees block_rsv
3258  * structure.
3259  */
3260 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3261                               struct btrfs_root *root)
3262 {
3263         struct btrfs_fs_info *fs_info = root->fs_info;
3264         struct btrfs_block_rsv *block_rsv;
3265         int ret;
3266 
3267         if (atomic_read(&root->orphan_inodes) ||
3268             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3269                 return;
3270 
3271         spin_lock(&root->orphan_lock);
3272         if (atomic_read(&root->orphan_inodes)) {
3273                 spin_unlock(&root->orphan_lock);
3274                 return;
3275         }
3276 
3277         if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3278                 spin_unlock(&root->orphan_lock);
3279                 return;
3280         }
3281 
3282         block_rsv = root->orphan_block_rsv;
3283         root->orphan_block_rsv = NULL;
3284         spin_unlock(&root->orphan_lock);
3285 
3286         if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3287             btrfs_root_refs(&root->root_item) > 0) {
3288                 ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
3289                                             root->root_key.objectid);
3290                 if (ret)
3291                         btrfs_abort_transaction(trans, ret);
3292                 else
3293                         clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3294                                   &root->state);
3295         }
3296 
3297         if (block_rsv) {
3298                 WARN_ON(block_rsv->size > 0);
3299                 btrfs_free_block_rsv(fs_info, block_rsv);
3300         }
3301 }
3302 
3303 /*
3304  * This creates an orphan entry for the given inode in case something goes
3305  * wrong in the middle of an unlink/truncate.
3306  *
3307  * NOTE: caller of this function should reserve 5 units of metadata for
3308  *       this function.
3309  */
3310 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3311                 struct btrfs_inode *inode)
3312 {
3313         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3314         struct btrfs_root *root = inode->root;
3315         struct btrfs_block_rsv *block_rsv = NULL;
3316         int reserve = 0;
3317         int insert = 0;
3318         int ret;
3319 
3320         if (!root->orphan_block_rsv) {
3321                 block_rsv = btrfs_alloc_block_rsv(fs_info,
3322                                                   BTRFS_BLOCK_RSV_TEMP);
3323                 if (!block_rsv)
3324                         return -ENOMEM;
3325         }
3326 
3327         spin_lock(&root->orphan_lock);
3328         if (!root->orphan_block_rsv) {
3329                 root->orphan_block_rsv = block_rsv;
3330         } else if (block_rsv) {
3331                 btrfs_free_block_rsv(fs_info, block_rsv);
3332                 block_rsv = NULL;
3333         }
3334 
3335         if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3336                               &inode->runtime_flags)) {
3337 #if 0
3338                 /*
3339                  * For proper ENOSPC handling, we should do orphan
3340                  * cleanup when mounting. But this introduces backward
3341                  * compatibility issue.
3342                  */
3343                 if (!xchg(&root->orphan_item_inserted, 1))
3344                         insert = 2;
3345                 else
3346                         insert = 1;
3347 #endif
3348                 insert = 1;
3349                 atomic_inc(&root->orphan_inodes);
3350         }
3351 
3352         if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3353                               &inode->runtime_flags))
3354                 reserve = 1;
3355         spin_unlock(&root->orphan_lock);
3356 
3357         /* grab metadata reservation from transaction handle */
3358         if (reserve) {
3359                 ret = btrfs_orphan_reserve_metadata(trans, inode);
3360                 ASSERT(!ret);
3361                 if (ret) {
3362                         atomic_dec(&root->orphan_inodes);
3363                         clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3364                                   &inode->runtime_flags);
3365                         if (insert)
3366                                 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3367                                           &inode->runtime_flags);
3368                         return ret;
3369                 }
3370         }
3371 
3372         /* insert an orphan item to track this unlinked/truncated file */
3373         if (insert >= 1) {
3374                 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3375                 if (ret) {
3376                         atomic_dec(&root->orphan_inodes);
3377                         if (reserve) {
3378                                 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3379                                           &inode->runtime_flags);
3380                                 btrfs_orphan_release_metadata(inode);
3381                         }
3382                         if (ret != -EEXIST) {
3383                                 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3384                                           &inode->runtime_flags);
3385                                 btrfs_abort_transaction(trans, ret);
3386                                 return ret;
3387                         }
3388                 }
3389                 ret = 0;
3390         }
3391 
3392         /* insert an orphan item to track subvolume contains orphan files */
3393         if (insert >= 2) {
3394                 ret = btrfs_insert_orphan_item(trans, fs_info->tree_root,
3395                                                root->root_key.objectid);
3396                 if (ret && ret != -EEXIST) {
3397                         btrfs_abort_transaction(trans, ret);
3398                         return ret;
3399                 }
3400         }
3401         return 0;
3402 }
3403 
3404 /*
3405  * We have done the truncate/delete so we can go ahead and remove the orphan
3406  * item for this particular inode.
3407  */
3408 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3409                             struct btrfs_inode *inode)
3410 {
3411         struct btrfs_root *root = inode->root;
3412         int delete_item = 0;
3413         int release_rsv = 0;
3414         int ret = 0;
3415 
3416         spin_lock(&root->orphan_lock);
3417         if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3418                                &inode->runtime_flags))
3419                 delete_item = 1;
3420 
3421         if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3422                                &inode->runtime_flags))
3423                 release_rsv = 1;
3424         spin_unlock(&root->orphan_lock);
3425 
3426         if (delete_item) {
3427                 atomic_dec(&root->orphan_inodes);
3428                 if (trans)
3429                         ret = btrfs_del_orphan_item(trans, root,
3430                                                     btrfs_ino(inode));
3431         }
3432 
3433         if (release_rsv)
3434                 btrfs_orphan_release_metadata(inode);
3435 
3436         return ret;
3437 }
3438 
3439 /*
3440  * this cleans up any orphans that may be left on the list from the last use
3441  * of this root.
3442  */
3443 int btrfs_orphan_cleanup(struct btrfs_root *root)
3444 {
3445         struct btrfs_fs_info *fs_info = root->fs_info;
3446         struct btrfs_path *path;
3447         struct extent_buffer *leaf;
3448         struct btrfs_key key, found_key;
3449         struct btrfs_trans_handle *trans;
3450         struct inode *inode;
3451         u64 last_objectid = 0;
3452         int ret = 0, nr_unlink = 0, nr_truncate = 0;
3453 
3454         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3455                 return 0;
3456 
3457         path = btrfs_alloc_path();
3458         if (!path) {
3459                 ret = -ENOMEM;
3460                 goto out;
3461         }
3462         path->reada = READA_BACK;
3463 
3464         key.objectid = BTRFS_ORPHAN_OBJECTID;
3465         key.type = BTRFS_ORPHAN_ITEM_KEY;
3466         key.offset = (u64)-1;
3467 
3468         while (1) {
3469                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3470                 if (ret < 0)
3471                         goto out;
3472 
3473                 /*
3474                  * if ret == 0 means we found what we were searching for, which
3475                  * is weird, but possible, so only screw with path if we didn't
3476                  * find the key and see if we have stuff that matches
3477                  */
3478                 if (ret > 0) {
3479                         ret = 0;
3480                         if (path->slots[0] == 0)
3481                                 break;
3482                         path->slots[0]--;
3483                 }
3484 
3485                 /* pull out the item */
3486                 leaf = path->nodes[0];
3487                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3488 
3489                 /* make sure the item matches what we want */
3490                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3491                         break;
3492                 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3493                         break;
3494 
3495                 /* release the path since we're done with it */
3496                 btrfs_release_path(path);
3497 
3498                 /*
3499                  * this is where we are basically btrfs_lookup, without the
3500                  * crossing root thing.  we store the inode number in the
3501                  * offset of the orphan item.
3502                  */
3503 
3504                 if (found_key.offset == last_objectid) {
3505                         btrfs_err(fs_info,
3506                                   "Error removing orphan entry, stopping orphan cleanup");
3507                         ret = -EINVAL;
3508                         goto out;
3509                 }
3510 
3511                 last_objectid = found_key.offset;
3512 
3513                 found_key.objectid = found_key.offset;
3514                 found_key.type = BTRFS_INODE_ITEM_KEY;
3515                 found_key.offset = 0;
3516                 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3517                 ret = PTR_ERR_OR_ZERO(inode);
3518                 if (ret && ret != -ENOENT)
3519                         goto out;
3520 
3521                 if (ret == -ENOENT && root == fs_info->tree_root) {
3522                         struct btrfs_root *dead_root;
3523                         struct btrfs_fs_info *fs_info = root->fs_info;
3524                         int is_dead_root = 0;
3525 
3526                         /*
3527                          * this is an orphan in the tree root. Currently these
3528                          * could come from 2 sources:
3529                          *  a) a snapshot deletion in progress
3530                          *  b) a free space cache inode
3531                          * We need to distinguish those two, as the snapshot
3532                          * orphan must not get deleted.
3533                          * find_dead_roots already ran before us, so if this
3534                          * is a snapshot deletion, we should find the root
3535                          * in the dead_roots list
3536                          */
3537                         spin_lock(&fs_info->trans_lock);
3538                         list_for_each_entry(dead_root, &fs_info->dead_roots,
3539                                             root_list) {
3540                                 if (dead_root->root_key.objectid ==
3541                                     found_key.objectid) {
3542                                         is_dead_root = 1;
3543                                         break;
3544                                 }
3545                         }
3546                         spin_unlock(&fs_info->trans_lock);
3547                         if (is_dead_root) {
3548                                 /* prevent this orphan from being found again */
3549                                 key.offset = found_key.objectid - 1;
3550                                 continue;
3551                         }
3552                 }
3553                 /*
3554                  * Inode is already gone but the orphan item is still there,
3555                  * kill the orphan item.
3556                  */
3557                 if (ret == -ENOENT) {
3558                         trans = btrfs_start_transaction(root, 1);
3559                         if (IS_ERR(trans)) {
3560                                 ret = PTR_ERR(trans);
3561                                 goto out;
3562                         }
3563                         btrfs_debug(fs_info, "auto deleting %Lu",
3564                                     found_key.objectid);
3565                         ret = btrfs_del_orphan_item(trans, root,
3566                                                     found_key.objectid);
3567                         btrfs_end_transaction(trans);
3568                         if (ret)
3569                                 goto out;
3570                         continue;
3571                 }
3572 
3573                 /*
3574                  * add this inode to the orphan list so btrfs_orphan_del does
3575                  * the proper thing when we hit it
3576                  */
3577                 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3578                         &BTRFS_I(inode)->runtime_flags);
3579                 atomic_inc(&root->orphan_inodes);
3580 
3581                 /* if we have links, this was a truncate, lets do that */
3582                 if (inode->i_nlink) {
3583                         if (WARN_ON(!S_ISREG(inode->i_mode))) {
3584                                 iput(inode);
3585                                 continue;
3586                         }
3587                         nr_truncate++;
3588 
3589                         /* 1 for the orphan item deletion. */
3590                         trans = btrfs_start_transaction(root, 1);
3591                         if (IS_ERR(trans)) {
3592                                 iput(inode);
3593                                 ret = PTR_ERR(trans);
3594                                 goto out;
3595                         }
3596                         ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3597                         btrfs_end_transaction(trans);
3598                         if (ret) {
3599                                 iput(inode);
3600                                 goto out;
3601                         }
3602 
3603                         ret = btrfs_truncate(inode);
3604                         if (ret)
3605                                 btrfs_orphan_del(NULL, BTRFS_I(inode));
3606                 } else {
3607                         nr_unlink++;
3608                 }
3609 
3610                 /* this will do delete_inode and everything for us */
3611                 iput(inode);
3612                 if (ret)
3613                         goto out;
3614         }
3615         /* release the path since we're done with it */
3616         btrfs_release_path(path);
3617 
3618         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3619 
3620         if (root->orphan_block_rsv)
3621                 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3622                                         (u64)-1);
3623 
3624         if (root->orphan_block_rsv ||
3625             test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3626                 trans = btrfs_join_transaction(root);
3627                 if (!IS_ERR(trans))
3628                         btrfs_end_transaction(trans);
3629         }
3630 
3631         if (nr_unlink)
3632                 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3633         if (nr_truncate)
3634                 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3635 
3636 out:
3637         if (ret)
3638                 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3639         btrfs_free_path(path);
3640         return ret;
3641 }
3642 
3643 /*
3644  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3645  * don't find any xattrs, we know there can't be any acls.
3646  *
3647  * slot is the slot the inode is in, objectid is the objectid of the inode
3648  */
3649 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3650                                           int slot, u64 objectid,
3651                                           int *first_xattr_slot)
3652 {
3653         u32 nritems = btrfs_header_nritems(leaf);
3654         struct btrfs_key found_key;
3655         static u64 xattr_access = 0;
3656         static u64 xattr_default = 0;
3657         int scanned = 0;
3658 
3659         if (!xattr_access) {
3660                 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3661                                         strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3662                 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3663                                         strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3664         }
3665 
3666         slot++;
3667         *first_xattr_slot = -1;
3668         while (slot < nritems) {
3669                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3670 
3671                 /* we found a different objectid, there must not be acls */
3672                 if (found_key.objectid != objectid)
3673                         return 0;
3674 
3675                 /* we found an xattr, assume we've got an acl */
3676                 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3677                         if (*first_xattr_slot == -1)
3678                                 *first_xattr_slot = slot;
3679                         if (found_key.offset == xattr_access ||
3680                             found_key.offset == xattr_default)
3681                                 return 1;
3682                 }
3683 
3684                 /*
3685                  * we found a key greater than an xattr key, there can't
3686                  * be any acls later on
3687                  */
3688                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3689                         return 0;
3690 
3691                 slot++;
3692                 scanned++;
3693 
3694                 /*
3695                  * it goes inode, inode backrefs, xattrs, extents,
3696                  * so if there are a ton of hard links to an inode there can
3697                  * be a lot of backrefs.  Don't waste time searching too hard,
3698                  * this is just an optimization
3699                  */
3700                 if (scanned >= 8)
3701                         break;
3702         }
3703         /* we hit the end of the leaf before we found an xattr or
3704          * something larger than an xattr.  We have to assume the inode
3705          * has acls
3706          */
3707         if (*first_xattr_slot == -1)
3708                 *first_xattr_slot = slot;
3709         return 1;
3710 }
3711 
3712 /*
3713  * read an inode from the btree into the in-memory inode
3714  */
3715 static int btrfs_read_locked_inode(struct inode *inode)
3716 {
3717         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3718         struct btrfs_path *path;
3719         struct extent_buffer *leaf;
3720         struct btrfs_inode_item *inode_item;
3721         struct btrfs_root *root = BTRFS_I(inode)->root;
3722         struct btrfs_key location;
3723         unsigned long ptr;
3724         int maybe_acls;
3725         u32 rdev;
3726         int ret;
3727         bool filled = false;
3728         int first_xattr_slot;
3729 
3730         ret = btrfs_fill_inode(inode, &rdev);
3731         if (!ret)
3732                 filled = true;
3733 
3734         path = btrfs_alloc_path();
3735         if (!path) {
3736                 ret = -ENOMEM;
3737                 goto make_bad;
3738         }
3739 
3740         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3741 
3742         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3743         if (ret) {
3744                 if (ret > 0)
3745                         ret = -ENOENT;
3746                 goto make_bad;
3747         }
3748 
3749         leaf = path->nodes[0];
3750 
3751         if (filled)
3752                 goto cache_index;
3753 
3754         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3755                                     struct btrfs_inode_item);
3756         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3757         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3758         i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3759         i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3760         btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3761 
3762         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3763         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3764 
3765         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3766         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3767 
3768         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3769         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3770 
3771         BTRFS_I(inode)->i_otime.tv_sec =
3772                 btrfs_timespec_sec(leaf, &inode_item->otime);
3773         BTRFS_I(inode)->i_otime.tv_nsec =
3774                 btrfs_timespec_nsec(leaf, &inode_item->otime);
3775 
3776         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3777         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3778         BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3779 
3780         inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3781         inode->i_generation = BTRFS_I(inode)->generation;
3782         inode->i_rdev = 0;
3783         rdev = btrfs_inode_rdev(leaf, inode_item);
3784 
3785         BTRFS_I(inode)->index_cnt = (u64)-1;
3786         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3787 
3788 cache_index:
3789         /*
3790          * If we were modified in the current generation and evicted from memory
3791          * and then re-read we need to do a full sync since we don't have any
3792          * idea about which extents were modified before we were evicted from
3793          * cache.
3794          *
3795          * This is required for both inode re-read from disk and delayed inode
3796          * in delayed_nodes_tree.
3797          */
3798         if (BTRFS_I(inode)->last_trans == fs_info->generation)
3799                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3800                         &BTRFS_I(inode)->runtime_flags);
3801 
3802         /*
3803          * We don't persist the id of the transaction where an unlink operation
3804          * against the inode was last made. So here we assume the inode might
3805          * have been evicted, and therefore the exact value of last_unlink_trans
3806          * lost, and set it to last_trans to avoid metadata inconsistencies
3807          * between the inode and its parent if the inode is fsync'ed and the log
3808          * replayed. For example, in the scenario:
3809          *
3810          * touch mydir/foo
3811          * ln mydir/foo mydir/bar
3812          * sync
3813          * unlink mydir/bar
3814          * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
3815          * xfs_io -c fsync mydir/foo
3816          * <power failure>
3817          * mount fs, triggers fsync log replay
3818          *
3819          * We must make sure that when we fsync our inode foo we also log its
3820          * parent inode, otherwise after log replay the parent still has the
3821          * dentry with the "bar" name but our inode foo has a link count of 1
3822          * and doesn't have an inode ref with the name "bar" anymore.
3823          *
3824          * Setting last_unlink_trans to last_trans is a pessimistic approach,
3825          * but it guarantees correctness at the expense of occasional full
3826          * transaction commits on fsync if our inode is a directory, or if our
3827          * inode is not a directory, logging its parent unnecessarily.
3828          */
3829         BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3830 
3831         path->slots[0]++;
3832         if (inode->i_nlink != 1 ||
3833             path->slots[0] >= btrfs_header_nritems(leaf))
3834                 goto cache_acl;
3835 
3836         btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3837         if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3838                 goto cache_acl;
3839 
3840         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3841         if (location.type == BTRFS_INODE_REF_KEY) {
3842                 struct btrfs_inode_ref *ref;
3843 
3844                 ref = (struct btrfs_inode_ref *)ptr;
3845                 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3846         } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3847                 struct btrfs_inode_extref *extref;
3848 
3849                 extref = (struct btrfs_inode_extref *)ptr;
3850                 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3851                                                                      extref);
3852         }
3853 cache_acl:
3854         /*
3855          * try to precache a NULL acl entry for files that don't have
3856          * any xattrs or acls
3857          */
3858         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3859                         btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3860         if (first_xattr_slot != -1) {
3861                 path->slots[0] = first_xattr_slot;
3862                 ret = btrfs_load_inode_props(inode, path);
3863                 if (ret)
3864                         btrfs_err(fs_info,
3865                                   "error loading props for ino %llu (root %llu): %d",
3866                                   btrfs_ino(BTRFS_I(inode)),
3867                                   root->root_key.objectid, ret);
3868         }
3869         btrfs_free_path(path);
3870 
3871         if (!maybe_acls)
3872                 cache_no_acl(inode);
3873 
3874         switch (inode->i_mode & S_IFMT) {
3875         case S_IFREG:
3876                 inode->i_mapping->a_ops = &btrfs_aops;
3877                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3878                 inode->i_fop = &btrfs_file_operations;
3879                 inode->i_op = &btrfs_file_inode_operations;
3880                 break;
3881         case S_IFDIR:
3882                 inode->i_fop = &btrfs_dir_file_operations;
3883                 inode->i_op = &btrfs_dir_inode_operations;
3884                 break;
3885         case S_IFLNK:
3886                 inode->i_op = &btrfs_symlink_inode_operations;
3887                 inode_nohighmem(inode);
3888                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3889                 break;
3890         default:
3891                 inode->i_op = &btrfs_special_inode_operations;
3892                 init_special_inode(inode, inode->i_mode, rdev);
3893                 break;
3894         }
3895 
3896         btrfs_update_iflags(inode);
3897         return 0;
3898 
3899 make_bad:
3900         btrfs_free_path(path);
3901         make_bad_inode(inode);
3902         return ret;
3903 }
3904 
3905 /*
3906  * given a leaf and an inode, copy the inode fields into the leaf
3907  */
3908 static void fill_inode_item(struct btrfs_trans_handle *trans,
3909                             struct extent_buffer *leaf,
3910                             struct btrfs_inode_item *item,
3911                             struct inode *inode)
3912 {
3913         struct btrfs_map_token token;
3914 
3915         btrfs_init_map_token(&token);
3916 
3917         btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3918         btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3919         btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3920                                    &token);
3921         btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3922         btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3923 
3924         btrfs_set_token_timespec_sec(leaf, &item->atime,
3925                                      inode->i_atime.tv_sec, &token);
3926         btrfs_set_token_timespec_nsec(leaf, &item->atime,
3927                                       inode->i_atime.tv_nsec, &token);
3928 
3929         btrfs_set_token_timespec_sec(leaf, &item->mtime,
3930                                      inode->i_mtime.tv_sec, &token);
3931         btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3932                                       inode->i_mtime.tv_nsec, &token);
3933 
3934         btrfs_set_token_timespec_sec(leaf, &item->ctime,
3935                                      inode->i_ctime.tv_sec, &token);
3936         btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3937                                       inode->i_ctime.tv_nsec, &token);
3938 
3939         btrfs_set_token_timespec_sec(leaf, &item->otime,
3940                                      BTRFS_I(inode)->i_otime.tv_sec, &token);
3941         btrfs_set_token_timespec_nsec(leaf, &item->otime,
3942                                       BTRFS_I(inode)->i_otime.tv_nsec, &token);
3943 
3944         btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3945                                      &token);
3946         btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3947                                          &token);
3948         btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3949         btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3950         btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3951         btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3952         btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3953 }
3954 
3955 /*
3956  * copy everything in the in-memory inode into the btree.
3957  */
3958 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3959                                 struct btrfs_root *root, struct inode *inode)
3960 {
3961         struct btrfs_inode_item *inode_item;
3962         struct btrfs_path *path;
3963         struct extent_buffer *leaf;
3964         int ret;
3965 
3966         path = btrfs_alloc_path();
3967         if (!path)
3968                 return -ENOMEM;
3969 
3970         path->leave_spinning = 1;
3971         ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3972                                  1);
3973         if (ret) {
3974                 if (ret > 0)
3975                         ret = -ENOENT;
3976                 goto failed;
3977         }
3978 
3979         leaf = path->nodes[0];
3980         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3981                                     struct btrfs_inode_item);
3982 
3983         fill_inode_item(trans, leaf, inode_item, inode);
3984         btrfs_mark_buffer_dirty(leaf);
3985         btrfs_set_inode_last_trans(trans, inode);
3986         ret = 0;
3987 failed:
3988         btrfs_free_path(path);
3989         return ret;
3990 }
3991 
3992 /*
3993  * copy everything in the in-memory inode into the btree.
3994  */
3995 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3996                                 struct btrfs_root *root, struct inode *inode)
3997 {
3998         struct btrfs_fs_info *fs_info = root->fs_info;
3999         int ret;
4000 
4001         /*
4002          * If the inode is a free space inode, we can deadlock during commit
4003          * if we put it into the delayed code.
4004          *
4005          * The data relocation inode should also be directly updated
4006          * without delay
4007          */
4008         if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4009             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4010             && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4011                 btrfs_update_root_times(trans, root);
4012 
4013                 ret = btrfs_delayed_update_inode(trans, root, inode);
4014                 if (!ret)
4015                         btrfs_set_inode_last_trans(trans, inode);
4016                 return ret;
4017         }
4018 
4019         return btrfs_update_inode_item(trans, root, inode);
4020 }
4021 
4022 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4023                                          struct btrfs_root *root,
4024                                          struct inode *inode)
4025 {
4026         int ret;
4027 
4028         ret = btrfs_update_inode(trans, root, inode);
4029         if (ret == -ENOSPC)
4030                 return btrfs_update_inode_item(trans, root, inode);
4031         return ret;
4032 }
4033 
4034 /*
4035  * unlink helper that gets used here in inode.c and in the tree logging
4036  * recovery code.  It remove a link in a directory with a given name, and
4037  * also drops the back refs in the inode to the directory
4038  */
4039 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4040                                 struct btrfs_root *root,
4041                                 struct btrfs_inode *dir,
4042                                 struct btrfs_inode *inode,
4043                                 const char *name, int name_len)
4044 {
4045         struct btrfs_fs_info *fs_info = root->fs_info;
4046         struct btrfs_path *path;
4047         int ret = 0;
4048         struct extent_buffer *leaf;
4049         struct btrfs_dir_item *di;
4050         struct btrfs_key key;
4051         u64 index;
4052         u64 ino = btrfs_ino(inode);
4053         u64 dir_ino = btrfs_ino(dir);
4054 
4055         path = btrfs_alloc_path();
4056         if (!path) {
4057                 ret = -ENOMEM;
4058                 goto out;
4059         }
4060 
4061         path->leave_spinning = 1;
4062         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4063                                     name, name_len, -1);
4064         if (IS_ERR(di)) {
4065                 ret = PTR_ERR(di);
4066                 goto err;
4067         }
4068         if (!di) {
4069                 ret = -ENOENT;
4070                 goto err;
4071         }
4072         leaf = path->nodes[0];
4073         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4074         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4075         if (ret)
4076                 goto err;
4077         btrfs_release_path(path);
4078 
4079         /*
4080          * If we don't have dir index, we have to get it by looking up
4081          * the inode ref, since we get the inode ref, remove it directly,
4082          * it is unnecessary to do delayed deletion.
4083          *
4084          * But if we have dir index, needn't search inode ref to get it.
4085          * Since the inode ref is close to the inode item, it is better
4086          * that we delay to delete it, and just do this deletion when
4087          * we update the inode item.
4088          */
4089         if (inode->dir_index) {
4090                 ret = btrfs_delayed_delete_inode_ref(inode);
4091                 if (!ret) {
4092                         index = inode->dir_index;
4093                         goto skip_backref;
4094                 }
4095         }
4096 
4097         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4098                                   dir_ino, &index);
4099         if (ret) {
4100                 btrfs_info(fs_info,
4101                         "failed to delete reference to %.*s, inode %llu parent %llu",
4102                         name_len, name, ino, dir_ino);
4103                 btrfs_abort_transaction(trans, ret);
4104                 goto err;
4105         }
4106 skip_backref:
4107         ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4108         if (ret) {
4109                 btrfs_abort_transaction(trans, ret);
4110                 goto err;
4111         }
4112 
4113         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4114                         dir_ino);
4115         if (ret != 0 && ret != -ENOENT) {
4116                 btrfs_abort_transaction(trans, ret);
4117                 goto err;
4118         }
4119 
4120         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4121                         index);
4122         if (ret == -ENOENT)
4123                 ret = 0;
4124         else if (ret)
4125                 btrfs_abort_transaction(trans, ret);
4126 err:
4127         btrfs_free_path(path);
4128         if (ret)
4129                 goto out;
4130 
4131         btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4132         inode_inc_iversion(&inode->vfs_inode);
4133         inode_inc_iversion(&dir->vfs_inode);
4134         inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4135                 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4136         ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4137 out:
4138         return ret;
4139 }
4140 
4141 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4142                        struct btrfs_root *root,
4143                        struct btrfs_inode *dir, struct btrfs_inode *inode,
4144                        const char *name, int name_len)
4145 {
4146         int ret;
4147         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4148         if (!ret) {
4149                 drop_nlink(&inode->vfs_inode);
4150                 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4151         }
4152         return ret;
4153 }
4154 
4155 /*
4156  * helper to start transaction for unlink and rmdir.
4157  *
4158  * unlink and rmdir are special in btrfs, they do not always free space, so
4159  * if we cannot make our reservations the normal way try and see if there is
4160  * plenty of slack room in the global reserve to migrate, otherwise we cannot
4161  * allow the unlink to occur.
4162  */
4163 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4164 {
4165         struct btrfs_root *root = BTRFS_I(dir)->root;
4166 
4167         /*
4168          * 1 for the possible orphan item
4169          * 1 for the dir item
4170          * 1 for the dir index
4171          * 1 for the inode ref
4172          * 1 for the inode
4173          */
4174         return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4175 }
4176 
4177 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4178 {
4179         struct btrfs_root *root = BTRFS_I(dir)->root;
4180         struct btrfs_trans_handle *trans;
4181         struct inode *inode = d_inode(dentry);
4182         int ret;
4183 
4184         trans = __unlink_start_trans(dir);
4185         if (IS_ERR(trans))
4186                 return PTR_ERR(trans);
4187 
4188         btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4189                         0);
4190 
4191         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4192                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4193                         dentry->d_name.len);
4194         if (ret)
4195                 goto out;
4196 
4197         if (inode->i_nlink == 0) {
4198                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4199                 if (ret)
4200                         goto out;
4201         }
4202 
4203 out:
4204         btrfs_end_transaction(trans);
4205         btrfs_btree_balance_dirty(root->fs_info);
4206         return ret;
4207 }
4208 
4209 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4210                         struct btrfs_root *root,
4211                         struct inode *dir, u64 objectid,
4212                         const char *name, int name_len)
4213 {
4214         struct btrfs_fs_info *fs_info = root->fs_info;
4215         struct btrfs_path *path;
4216         struct extent_buffer *leaf;
4217         struct btrfs_dir_item *di;
4218         struct btrfs_key key;
4219         u64 index;
4220         int ret;
4221         u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4222 
4223         path = btrfs_alloc_path();
4224         if (!path)
4225                 return -ENOMEM;
4226 
4227         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4228                                    name, name_len, -1);
4229         if (IS_ERR_OR_NULL(di)) {
4230                 if (!di)
4231                         ret = -ENOENT;
4232                 else
4233                         ret = PTR_ERR(di);
4234                 goto out;
4235         }
4236 
4237         leaf = path->nodes[0];
4238         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4239         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4240         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4241         if (ret) {
4242                 btrfs_abort_transaction(trans, ret);
4243                 goto out;
4244         }
4245         btrfs_release_path(path);
4246 
4247         ret = btrfs_del_root_ref(trans, fs_info, objectid,
4248                                  root->root_key.objectid, dir_ino,
4249                                  &index, name, name_len);
4250         if (ret < 0) {
4251                 if (ret != -ENOENT) {
4252                         btrfs_abort_transaction(trans, ret);
4253                         goto out;
4254                 }
4255                 di = btrfs_search_dir_index_item(root, path, dir_ino,
4256                                                  name, name_len);
4257                 if (IS_ERR_OR_NULL(di)) {
4258                         if (!di)
4259                                 ret = -ENOENT;
4260                         else
4261                                 ret = PTR_ERR(di);
4262                         btrfs_abort_transaction(trans, ret);
4263                         goto out;
4264                 }
4265 
4266                 leaf = path->nodes[0];
4267                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4268                 btrfs_release_path(path);
4269                 index = key.offset;
4270         }
4271         btrfs_release_path(path);
4272 
4273         ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4274         if (ret) {
4275                 btrfs_abort_transaction(trans, ret);
4276                 goto out;
4277         }
4278 
4279         btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4280         inode_inc_iversion(dir);
4281         dir->i_mtime = dir->i_ctime = current_time(dir);
4282         ret = btrfs_update_inode_fallback(trans, root, dir);
4283         if (ret)
4284                 btrfs_abort_transaction(trans, ret);
4285 out:
4286         btrfs_free_path(path);
4287         return ret;
4288 }
4289 
4290 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4291 {
4292         struct inode *inode = d_inode(dentry);
4293         int err = 0;
4294         struct btrfs_root *root = BTRFS_I(dir)->root;
4295         struct btrfs_trans_handle *trans;
4296         u64 last_unlink_trans;
4297 
4298         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4299                 return -ENOTEMPTY;
4300         if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4301                 return -EPERM;
4302 
4303         trans = __unlink_start_trans(dir);
4304         if (IS_ERR(trans))
4305                 return PTR_ERR(trans);
4306 
4307         if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4308                 err = btrfs_unlink_subvol(trans, root, dir,
4309                                           BTRFS_I(inode)->location.objectid,
4310                                           dentry->d_name.name,
4311                                           dentry->d_name.len);
4312                 goto out;
4313         }
4314 
4315         err = btrfs_orphan_add(trans, BTRFS_I(inode));
4316         if (err)
4317                 goto out;
4318 
4319         last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4320 
4321         /* now the directory is empty */
4322         err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4323                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4324                         dentry->d_name.len);
4325         if (!err) {
4326                 btrfs_i_size_write(BTRFS_I(inode), 0);
4327                 /*
4328                  * Propagate the last_unlink_trans value of the deleted dir to
4329                  * its parent directory. This is to prevent an unrecoverable
4330                  * log tree in the case we do something like this:
4331                  * 1) create dir foo
4332                  * 2) create snapshot under dir foo
4333                  * 3) delete the snapshot
4334                  * 4) rmdir foo
4335                  * 5) mkdir foo
4336                  * 6) fsync foo or some file inside foo
4337                  */
4338                 if (last_unlink_trans >= trans->transid)
4339                         BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4340         }
4341 out:
4342         btrfs_end_transaction(trans);
4343         btrfs_btree_balance_dirty(root->fs_info);
4344 
4345         return err;
4346 }
4347 
4348 static int truncate_space_check(struct btrfs_trans_handle *trans,
4349                                 struct btrfs_root *root,
4350                                 u64 bytes_deleted)
4351 {
4352         struct btrfs_fs_info *fs_info = root->fs_info;
4353         int ret;
4354 
4355         /*
4356          * This is only used to apply pressure to the enospc system, we don't
4357          * intend to use this reservation at all.
4358          */
4359         bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4360         bytes_deleted *= fs_info->nodesize;
4361         ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4362                                   bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4363         if (!ret) {
4364                 trace_btrfs_space_reservation(fs_info, "transaction",
4365                                               trans->transid,
4366                                               bytes_deleted, 1);
4367                 trans->bytes_reserved += bytes_deleted;
4368         }
4369         return ret;
4370 
4371 }
4372 
4373 /*
4374  * Return this if we need to call truncate_block for the last bit of the
4375  * truncate.
4376  */
4377 #define NEED_TRUNCATE_BLOCK 1
4378 
4379 /*
4380  * this can truncate away extent items, csum items and directory items.
4381  * It starts at a high offset and removes keys until it can't find
4382  * any higher than new_size
4383  *
4384  * csum items that cross the new i_size are truncated to the new size
4385  * as well.
4386  *
4387  * min_type is the minimum key type to truncate down to.  If set to 0, this
4388  * will kill all the items on this inode, including the INODE_ITEM_KEY.
4389  */
4390 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4391                                struct btrfs_root *root,
4392                                struct inode *inode,
4393                                u64 new_size, u32 min_type)
4394 {
4395         struct btrfs_fs_info *fs_info = root->fs_info;
4396         struct btrfs_path *path;
4397         struct extent_buffer *leaf;
4398         struct btrfs_file_extent_item *fi;
4399         struct btrfs_key key;
4400         struct btrfs_key found_key;
4401         u64 extent_start = 0;
4402         u64 extent_num_bytes = 0;
4403         u64 extent_offset = 0;
4404         u64 item_end = 0;
4405         u64 last_size = new_size;
4406         u32 found_type = (u8)-1;
4407         int found_extent;
4408         int del_item;
4409         int pending_del_nr = 0;
4410         int pending_del_slot = 0;
4411         int extent_type = -1;
4412         int ret;
4413         int err = 0;
4414         u64 ino = btrfs_ino(BTRFS_I(inode));
4415         u64 bytes_deleted = 0;
4416         bool be_nice = false;
4417         bool should_throttle = false;
4418         bool should_end = false;
4419 
4420         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4421 
4422         /*
4423          * for non-free space inodes and ref cows, we want to back off from
4424          * time to time
4425          */
4426         if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4427             test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4428                 be_nice = true;
4429 
4430         path = btrfs_alloc_path();
4431         if (!path)
4432                 return -ENOMEM;
4433         path->reada = READA_BACK;
4434 
4435         /*
4436          * We want to drop from the next block forward in case this new size is
4437          * not block aligned since we will be keeping the last block of the
4438          * extent just the way it is.
4439          */
4440         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4441             root == fs_info->tree_root)
4442                 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4443                                         fs_info->sectorsize),
4444                                         (u64)-1, 0);
4445 
4446         /*
4447          * This function is also used to drop the items in the log tree before
4448          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4449          * it is used to drop the loged items. So we shouldn't kill the delayed
4450          * items.
4451          */
4452         if (min_type == 0 && root == BTRFS_I(inode)->root)
4453                 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4454 
4455         key.objectid = ino;
4456         key.offset = (u64)-1;
4457         key.type = (u8)-1;
4458 
4459 search_again:
4460         /*
4461          * with a 16K leaf size and 128MB extents, you can actually queue
4462          * up a huge file in a single leaf.  Most of the time that
4463          * bytes_deleted is > 0, it will be huge by the time we get here
4464          */
4465         if (be_nice && bytes_deleted > SZ_32M) {
4466                 if (btrfs_should_end_transaction(trans)) {
4467                         err = -EAGAIN;
4468                         goto error;
4469                 }
4470         }
4471 
4472 
4473         path->leave_spinning = 1;
4474         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4475         if (ret < 0) {
4476                 err = ret;
4477                 goto out;
4478         }
4479 
4480         if (ret > 0) {
4481                 /* there are no items in the tree for us to truncate, we're
4482                  * done
4483                  */
4484                 if (path->slots[0] == 0)
4485                         goto out;
4486                 path->slots[0]--;
4487         }
4488 
4489         while (1) {
4490                 fi = NULL;
4491                 leaf = path->nodes[0];
4492                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4493                 found_type = found_key.type;
4494 
4495                 if (found_key.objectid != ino)
4496                         break;
4497 
4498                 if (found_type < min_type)
4499                         break;
4500 
4501                 item_end = found_key.offset;
4502                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4503                         fi = btrfs_item_ptr(leaf, path->slots[0],
4504                                             struct btrfs_file_extent_item);
4505                         extent_type = btrfs_file_extent_type(leaf, fi);
4506                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4507                                 item_end +=
4508                                     btrfs_file_extent_num_bytes(leaf, fi);
4509 
4510                                 trace_btrfs_truncate_show_fi_regular(
4511                                         BTRFS_I(inode), leaf, fi,
4512                                         found_key.offset);
4513                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4514                                 item_end += btrfs_file_extent_inline_len(leaf,
4515                                                          path->slots[0], fi);
4516 
4517                                 trace_btrfs_truncate_show_fi_inline(
4518                                         BTRFS_I(inode), leaf, fi, path->slots[0],
4519                                         found_key.offset);
4520                         }
4521                         item_end--;
4522                 }
4523                 if (found_type > min_type) {
4524                         del_item = 1;
4525                 } else {
4526                         if (item_end < new_size)
4527                                 break;
4528                         if (found_key.offset >= new_size)
4529                                 del_item = 1;
4530                         else
4531                                 del_item = 0;
4532                 }
4533                 found_extent = 0;
4534                 /* FIXME, shrink the extent if the ref count is only 1 */
4535                 if (found_type != BTRFS_EXTENT_DATA_KEY)
4536                         goto delete;
4537 
4538                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4539                         u64 num_dec;
4540                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4541                         if (!del_item) {
4542                                 u64 orig_num_bytes =
4543                                         btrfs_file_extent_num_bytes(leaf, fi);
4544                                 extent_num_bytes = ALIGN(new_size -
4545                                                 found_key.offset,
4546                                                 fs_info->sectorsize);
4547                                 btrfs_set_file_extent_num_bytes(leaf, fi,
4548                                                          extent_num_bytes);
4549                                 num_dec = (orig_num_bytes -
4550                                            extent_num_bytes);
4551                                 if (test_bit(BTRFS_ROOT_REF_COWS,
4552                                              &root->state) &&
4553                                     extent_start != 0)
4554                                         inode_sub_bytes(inode, num_dec);
4555                                 btrfs_mark_buffer_dirty(leaf);
4556                         } else {
4557                                 extent_num_bytes =
4558                                         btrfs_file_extent_disk_num_bytes(leaf,
4559                                                                          fi);
4560                                 extent_offset = found_key.offset -
4561                                         btrfs_file_extent_offset(leaf, fi);
4562 
4563                                 /* FIXME blocksize != 4096 */
4564                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4565                                 if (extent_start != 0) {
4566                                         found_extent = 1;
4567                                         if (test_bit(BTRFS_ROOT_REF_COWS,
4568                                                      &root->state))
4569                                                 inode_sub_bytes(inode, num_dec);
4570                                 }
4571                         }
4572                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4573                         /*
4574                          * we can't truncate inline items that have had
4575                          * special encodings
4576                          */
4577                         if (!del_item &&
4578                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
4579                             btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4580                             btrfs_file_extent_compression(leaf, fi) == 0) {
4581                                 u32 size = (u32)(new_size - found_key.offset);
4582 
4583                                 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4584                                 size = btrfs_file_extent_calc_inline_size(size);
4585                                 btrfs_truncate_item(root->fs_info, path, size, 1);
4586                         } else if (!del_item) {
4587                                 /*
4588                                  * We have to bail so the last_size is set to
4589                                  * just before this extent.
4590                                  */
4591                                 err = NEED_TRUNCATE_BLOCK;
4592                                 break;
4593                         }
4594 
4595                         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4596                                 inode_sub_bytes(inode, item_end + 1 - new_size);
4597                 }
4598 delete:
4599                 if (del_item)
4600                         last_size = found_key.offset;
4601                 else
4602                         last_size = new_size;
4603                 if (del_item) {
4604                         if (!pending_del_nr) {
4605                                 /* no pending yet, add ourselves */
4606                                 pending_del_slot = path->slots[0];
4607                                 pending_del_nr = 1;
4608                         } else if (pending_del_nr &&
4609                                    path->slots[0] + 1 == pending_del_slot) {
4610                                 /* hop on the pending chunk */
4611                                 pending_del_nr++;
4612                                 pending_del_slot = path->slots[0];
4613                         } else {
4614                                 BUG();
4615                         }
4616                 } else {
4617                         break;
4618                 }
4619                 should_throttle = false;
4620 
4621                 if (found_extent &&
4622                     (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4623                      root == fs_info->tree_root)) {
4624                         btrfs_set_path_blocking(path);
4625                         bytes_deleted += extent_num_bytes;
4626                         ret = btrfs_free_extent(trans, root, extent_start,
4627                                                 extent_num_bytes, 0,
4628                                                 btrfs_header_owner(leaf),
4629                                                 ino, extent_offset);
4630                         BUG_ON(ret);
4631                         if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4632                                 btrfs_async_run_delayed_refs(fs_info,
4633                                         trans->delayed_ref_updates * 2,
4634                                         trans->transid, 0);
4635                         if (be_nice) {
4636                                 if (truncate_space_check(trans, root,
4637                                                          extent_num_bytes)) {
4638                                         should_end = true;
4639                                 }
4640                                 if (btrfs_should_throttle_delayed_refs(trans,
4641                                                                        fs_info))
4642                                         should_throttle = true;
4643                         }
4644                 }
4645 
4646                 if (found_type == BTRFS_INODE_ITEM_KEY)
4647                         break;
4648 
4649                 if (path->slots[0] == 0 ||
4650                     path->slots[0] != pending_del_slot ||
4651                     should_throttle || should_end) {
4652                         if (pending_del_nr) {
4653                                 ret = btrfs_del_items(trans, root, path,
4654                                                 pending_del_slot,
4655                                                 pending_del_nr);
4656                                 if (ret) {
4657                                         btrfs_abort_transaction(trans, ret);
4658                                         goto error;
4659                                 }
4660                                 pending_del_nr = 0;
4661                         }
4662                         btrfs_release_path(path);
4663                         if (should_throttle) {
4664                                 unsigned long updates = trans->delayed_ref_updates;
4665                                 if (updates) {
4666                                         trans->delayed_ref_updates = 0;
4667                                         ret = btrfs_run_delayed_refs(trans,
4668                                                                    fs_info,
4669                                                                    updates * 2);
4670                                         if (ret && !err)
4671                                                 err = ret;
4672                                 }
4673                         }
4674                         /*
4675                          * if we failed to refill our space rsv, bail out
4676                          * and let the transaction restart
4677                          */
4678                         if (should_end) {
4679                                 err = -EAGAIN;
4680                                 goto error;
4681                         }
4682                         goto search_again;
4683                 } else {
4684                         path->slots[0]--;
4685                 }
4686         }
4687 out:
4688         if (pending_del_nr) {
4689                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4690                                       pending_del_nr);
4691                 if (ret)
4692                         btrfs_abort_transaction(trans, ret);
4693         }
4694 error:
4695         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4696                 ASSERT(last_size >= new_size);
4697                 if (!err && last_size > new_size)
4698                         last_size = new_size;
4699                 btrfs_ordered_update_i_size(inode, last_size, NULL);
4700         }
4701 
4702         btrfs_free_path(path);
4703 
4704         if (be_nice && bytes_deleted > SZ_32M) {
4705                 unsigned long updates = trans->delayed_ref_updates;
4706                 if (updates) {
4707                         trans->delayed_ref_updates = 0;
4708                         ret = btrfs_run_delayed_refs(trans, fs_info,
4709                                                      updates * 2);
4710                         if (ret && !err)
4711                                 err = ret;
4712                 }
4713         }
4714         return err;
4715 }
4716 
4717 /*
4718  * btrfs_truncate_block - read, zero a chunk and write a block
4719  * @inode - inode that we're zeroing
4720  * @from - the offset to start zeroing
4721  * @len - the length to zero, 0 to zero the entire range respective to the
4722  *      offset
4723  * @front - zero up to the offset instead of from the offset on
4724  *
4725  * This will find the block for the "from" offset and cow the block and zero the
4726  * part we want to zero.  This is used with truncate and hole punching.
4727  */
4728 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4729                         int front)
4730 {
4731         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4732         struct address_space *mapping = inode->i_mapping;
4733         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4734         struct btrfs_ordered_extent *ordered;
4735         struct extent_state *cached_state = NULL;
4736         struct extent_changeset *data_reserved = NULL;
4737         char *kaddr;
4738         u32 blocksize = fs_info->sectorsize;
4739         pgoff_t index = from >> PAGE_SHIFT;
4740         unsigned offset = from & (blocksize - 1);
4741         struct page *page;
4742         gfp_t mask = btrfs_alloc_write_mask(mapping);
4743         int ret = 0;
4744         u64 block_start;
4745         u64 block_end;
4746 
4747         if ((offset & (blocksize - 1)) == 0 &&
4748             (!len || ((len & (blocksize - 1)) == 0)))
4749                 goto out;
4750 
4751         block_start = round_down(from, blocksize);
4752         block_end = block_start + blocksize - 1;
4753 
4754         ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4755                                            block_start, blocksize);
4756         if (ret)
4757                 goto out;
4758 
4759 again:
4760         page = find_or_create_page(mapping, index, mask);
4761         if (!page) {
4762                 btrfs_delalloc_release_space(inode, data_reserved,
4763                                              block_start, blocksize);
4764                 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4765                 ret = -ENOMEM;
4766                 goto out;
4767         }
4768 
4769         if (!PageUptodate(page)) {
4770                 ret = btrfs_readpage(NULL, page);
4771                 lock_page(page);
4772                 if (page->mapping != mapping) {
4773                         unlock_page(page);
4774                         put_page(page);
4775                         goto again;
4776                 }
4777                 if (!PageUptodate(page)) {
4778                         ret = -EIO;
4779                         goto out_unlock;
4780                 }
4781         }
4782         wait_on_page_writeback(page);
4783 
4784         lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4785         set_page_extent_mapped(page);
4786 
4787         ordered = btrfs_lookup_ordered_extent(inode, block_start);
4788         if (ordered) {
4789                 unlock_extent_cached(io_tree, block_start, block_end,
4790                                      &cached_state, GFP_NOFS);
4791                 unlock_page(page);
4792                 put_page(page);
4793                 btrfs_start_ordered_extent(inode, ordered, 1);
4794                 btrfs_put_ordered_extent(ordered);
4795                 goto again;
4796         }
4797 
4798         clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4799                           EXTENT_DIRTY | EXTENT_DELALLOC |
4800                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4801                           0, 0, &cached_state, GFP_NOFS);
4802 
4803         ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4804                                         &cached_state, 0);
4805         if (ret) {
4806                 unlock_extent_cached(io_tree, block_start, block_end,
4807                                      &cached_state, GFP_NOFS);
4808                 goto out_unlock;
4809         }
4810 
4811         if (offset != blocksize) {
4812                 if (!len)
4813                         len = blocksize - offset;
4814                 kaddr = kmap(page);
4815                 if (front)
4816                         memset(kaddr + (block_start - page_offset(page)),
4817                                 0, offset);
4818                 else
4819                         memset(kaddr + (block_start - page_offset(page)) +  offset,
4820                                 0, len);
4821                 flush_dcache_page(page);
4822                 kunmap(page);
4823         }
4824         ClearPageChecked(page);
4825         set_page_dirty(page);
4826         unlock_extent_cached(io_tree, block_start, block_end, &cached_state,
4827                              GFP_NOFS);
4828 
4829 out_unlock:
4830         if (ret)
4831                 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4832                                              blocksize);
4833         btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4834         unlock_page(page);
4835         put_page(page);
4836 out:
4837         extent_changeset_free(data_reserved);
4838         return ret;
4839 }
4840 
4841 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4842                              u64 offset, u64 len)
4843 {
4844         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4845         struct btrfs_trans_handle *trans;
4846         int ret;
4847 
4848         /*
4849          * Still need to make sure the inode looks like it's been updated so
4850          * that any holes get logged if we fsync.
4851          */
4852         if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4853                 BTRFS_I(inode)->last_trans = fs_info->generation;
4854                 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4855                 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4856                 return 0;
4857         }
4858 
4859         /*
4860          * 1 - for the one we're dropping
4861          * 1 - for the one we're adding
4862          * 1 - for updating the inode.
4863          */
4864         trans = btrfs_start_transaction(root, 3);
4865         if (IS_ERR(trans))
4866                 return PTR_ERR(trans);
4867 
4868         ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4869         if (ret) {
4870                 btrfs_abort_transaction(trans, ret);
4871                 btrfs_end_transaction(trans);
4872                 return ret;
4873         }
4874 
4875         ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4876                         offset, 0, 0, len, 0, len, 0, 0, 0);
4877         if (ret)
4878                 btrfs_abort_transaction(trans, ret);
4879         else
4880                 btrfs_update_inode(trans, root, inode);
4881         btrfs_end_transaction(trans);
4882         return ret;
4883 }
4884 
4885 /*
4886  * This function puts in dummy file extents for the area we're creating a hole
4887  * for.  So if we are truncating this file to a larger size we need to insert
4888  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4889  * the range between oldsize and size
4890  */
4891 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4892 {
4893         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4894         struct btrfs_root *root = BTRFS_I(inode)->root;
4895         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4896         struct extent_map *em = NULL;
4897         struct extent_state *cached_state = NULL;
4898         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4899         u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4900         u64 block_end = ALIGN(size, fs_info->sectorsize);
4901         u64 last_byte;
4902         u64 cur_offset;
4903         u64 hole_size;
4904         int err = 0;
4905 
4906         /*
4907          * If our size started in the middle of a block we need to zero out the
4908          * rest of the block before we expand the i_size, otherwise we could
4909          * expose stale data.
4910          */
4911         err = btrfs_truncate_block(inode, oldsize, 0, 0);
4912         if (err)
4913                 return err;
4914 
4915         if (size <= hole_start)
4916                 return 0;
4917 
4918         while (1) {
4919                 struct btrfs_ordered_extent *ordered;
4920 
4921                 lock_extent_bits(io_tree, hole_start, block_end - 1,
4922                                  &cached_state);
4923                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
4924                                                      block_end - hole_start);
4925                 if (!ordered)
4926                         break;
4927                 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4928                                      &cached_state, GFP_NOFS);
4929                 btrfs_start_ordered_extent(inode, ordered, 1);
4930                 btrfs_put_ordered_extent(ordered);
4931         }
4932 
4933         cur_offset = hole_start;
4934         while (1) {
4935                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4936                                 block_end - cur_offset, 0);
4937                 if (IS_ERR(em)) {
4938                         err = PTR_ERR(em);
4939                         em = NULL;
4940                         break;
4941                 }
4942                 last_byte = min(extent_map_end(em), block_end);
4943                 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4944                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4945                         struct extent_map *hole_em;
4946                         hole_size = last_byte - cur_offset;
4947 
4948                         err = maybe_insert_hole(root, inode, cur_offset,
4949                                                 hole_size);
4950                         if (err)
4951                                 break;
4952                         btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4953                                                 cur_offset + hole_size - 1, 0);
4954                         hole_em = alloc_extent_map();
4955                         if (!hole_em) {
4956                                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4957                                         &BTRFS_I(inode)->runtime_flags);
4958                                 goto next;
4959                         }
4960                         hole_em->start = cur_offset;
4961                         hole_em->len = hole_size;
4962                         hole_em->orig_start = cur_offset;
4963 
4964                         hole_em->block_start = EXTENT_MAP_HOLE;
4965                         hole_em->block_len = 0;
4966                         hole_em->orig_block_len = 0;
4967                         hole_em->ram_bytes = hole_size;
4968                         hole_em->bdev = fs_info->fs_devices->latest_bdev;
4969                         hole_em->compress_type = BTRFS_COMPRESS_NONE;
4970                         hole_em->generation = fs_info->generation;
4971 
4972                         while (1) {
4973                                 write_lock(&em_tree->lock);
4974                                 err = add_extent_mapping(em_tree, hole_em, 1);
4975                                 write_unlock(&em_tree->lock);
4976                                 if (err != -EEXIST)
4977                                         break;
4978                                 btrfs_drop_extent_cache(BTRFS_I(inode),
4979                                                         cur_offset,
4980                                                         cur_offset +
4981                                                         hole_size - 1, 0);
4982                         }
4983                         free_extent_map(hole_em);
4984                 }
4985 next:
4986                 free_extent_map(em);
4987                 em = NULL;
4988                 cur_offset = last_byte;
4989                 if (cur_offset >= block_end)
4990                         break;
4991         }
4992         free_extent_map(em);
4993         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4994                              GFP_NOFS);
4995         return err;
4996 }
4997 
4998 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4999 {
5000         struct btrfs_root *root = BTRFS_I(inode)->root;
5001         struct btrfs_trans_handle *trans;
5002         loff_t oldsize = i_size_read(inode);
5003         loff_t newsize = attr->ia_size;
5004         int mask = attr->ia_valid;
5005         int ret;
5006 
5007         /*
5008          * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5009          * special case where we need to update the times despite not having
5010          * these flags set.  For all other operations the VFS set these flags
5011          * explicitly if it wants a timestamp update.
5012          */
5013         if (newsize != oldsize) {
5014                 inode_inc_iversion(inode);
5015                 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5016                         inode->i_ctime = inode->i_mtime =
5017                                 current_time(inode);
5018         }
5019 
5020         if (newsize > oldsize) {
5021                 /*
5022                  * Don't do an expanding truncate while snapshotting is ongoing.
5023                  * This is to ensure the snapshot captures a fully consistent
5024                  * state of this file - if the snapshot captures this expanding
5025                  * truncation, it must capture all writes that happened before
5026                  * this truncation.
5027                  */
5028                 btrfs_wait_for_snapshot_creation(root);
5029                 ret = btrfs_cont_expand(inode, oldsize, newsize);
5030                 if (ret) {
5031                         btrfs_end_write_no_snapshotting(root);
5032                         return ret;
5033                 }
5034 
5035                 trans = btrfs_start_transaction(root, 1);
5036                 if (IS_ERR(trans)) {
5037                         btrfs_end_write_no_snapshotting(root);
5038                         return PTR_ERR(trans);
5039                 }
5040 
5041                 i_size_write(inode, newsize);
5042                 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5043                 pagecache_isize_extended(inode, oldsize, newsize);
5044                 ret = btrfs_update_inode(trans, root, inode);
5045                 btrfs_end_write_no_snapshotting(root);
5046                 btrfs_end_transaction(trans);
5047         } else {
5048 
5049                 /*
5050                  * We're truncating a file that used to have good data down to
5051                  * zero. Make sure it gets into the ordered flush list so that
5052                  * any new writes get down to disk quickly.
5053                  */
5054                 if (newsize == 0)
5055                         set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5056                                 &BTRFS_I(inode)->runtime_flags);
5057 
5058                 /*
5059                  * 1 for the orphan item we're going to add
5060                  * 1 for the orphan item deletion.
5061                  */
5062                 trans = btrfs_start_transaction(root, 2);
5063                 if (IS_ERR(trans))
5064                         return PTR_ERR(trans);
5065 
5066                 /*
5067                  * We need to do this in case we fail at _any_ point during the
5068                  * actual truncate.  Once we do the truncate_setsize we could
5069                  * invalidate pages which forces any outstanding ordered io to
5070                  * be instantly completed which will give us extents that need
5071                  * to be truncated.  If we fail to get an orphan inode down we
5072                  * could have left over extents that were never meant to live,
5073                  * so we need to guarantee from this point on that everything
5074                  * will be consistent.
5075                  */
5076                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5077                 btrfs_end_transaction(trans);
5078                 if (ret)
5079                         return ret;
5080 
5081                 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5082                 truncate_setsize(inode, newsize);
5083 
5084                 /* Disable nonlocked read DIO to avoid the end less truncate */
5085                 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5086                 inode_dio_wait(inode);
5087                 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5088 
5089                 ret = btrfs_truncate(inode);
5090                 if (ret && inode->i_nlink) {
5091                         int err;
5092 
5093                         /* To get a stable disk_i_size */
5094                         err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5095                         if (err) {
5096                                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5097                                 return err;
5098                         }
5099 
5100                         /*
5101                          * failed to truncate, disk_i_size is only adjusted down
5102                          * as we remove extents, so it should represent the true
5103                          * size of the inode, so reset the in memory size and
5104                          * delete our orphan entry.
5105                          */
5106                         trans = btrfs_join_transaction(root);
5107                         if (IS_ERR(trans)) {
5108                                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5109                                 return ret;
5110                         }
5111                         i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5112                         err = btrfs_orphan_del(trans, BTRFS_I(inode));
5113                         if (err)
5114                                 btrfs_abort_transaction(trans, err);
5115                         btrfs_end_transaction(trans);
5116                 }
5117         }
5118 
5119         return ret;
5120 }
5121 
5122 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5123 {
5124         struct inode *inode = d_inode(dentry);
5125         struct btrfs_root *root = BTRFS_I(inode)->root;
5126         int err;
5127 
5128         if (btrfs_root_readonly(root))
5129                 return -EROFS;
5130 
5131         err = setattr_prepare(dentry, attr);
5132         if (err)
5133                 return err;
5134 
5135         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5136                 err = btrfs_setsize(inode, attr);
5137                 if (err)
5138                         return err;
5139         }
5140 
5141         if (attr->ia_valid) {
5142                 setattr_copy(inode, attr);
5143                 inode_inc_iversion(inode);
5144                 err = btrfs_dirty_inode(inode);
5145 
5146                 if (!err && attr->ia_valid & ATTR_MODE)
5147                         err = posix_acl_chmod(inode, inode->i_mode);
5148         }
5149 
5150         return err;
5151 }
5152 
5153 /*
5154  * While truncating the inode pages during eviction, we get the VFS calling
5155  * btrfs_invalidatepage() against each page of the inode. This is slow because
5156  * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5157  * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5158  * extent_state structures over and over, wasting lots of time.
5159  *
5160  * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5161  * those expensive operations on a per page basis and do only the ordered io
5162  * finishing, while we release here the extent_map and extent_state structures,
5163  * without the excessive merging and splitting.
5164  */
5165 static void evict_inode_truncate_pages(struct inode *inode)
5166 {
5167         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5168         struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5169         struct rb_node *node;
5170 
5171         ASSERT(inode->i_state & I_FREEING);
5172         truncate_inode_pages_final(&inode->i_data);
5173 
5174         write_lock(&map_tree->lock);
5175         while (!RB_EMPTY_ROOT(&map_tree->map)) {
5176                 struct extent_map *em;
5177 
5178                 node = rb_first(&map_tree->map);
5179                 em = rb_entry(node, struct extent_map, rb_node);
5180                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5181                 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5182                 remove_extent_mapping(map_tree, em);
5183                 free_extent_map(em);
5184                 if (need_resched()) {
5185                         write_unlock(&map_tree->lock);
5186                         cond_resched();
5187                         write_lock(&map_tree->lock);
5188                 }
5189         }
5190         write_unlock(&map_tree->lock);
5191 
5192         /*
5193          * Keep looping until we have no more ranges in the io tree.
5194          * We can have ongoing bios started by readpages (called from readahead)
5195          * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5196          * still in progress (unlocked the pages in the bio but did not yet
5197          * unlocked the ranges in the io tree). Therefore this means some
5198          * ranges can still be locked and eviction started because before
5199          * submitting those bios, which are executed by a separate task (work
5200          * queue kthread), inode references (inode->i_count) were not taken
5201          * (which would be dropped in the end io callback of each bio).
5202          * Therefore here we effectively end up waiting for those bios and
5203          * anyone else holding locked ranges without having bumped the inode's
5204          * reference count - if we don't do it, when they access the inode's
5205          * io_tree to unlock a range it may be too late, leading to an
5206          * use-after-free issue.
5207          */
5208         spin_lock(&io_tree->lock);
5209         while (!RB_EMPTY_ROOT(&io_tree->state)) {
5210                 struct extent_state *state;
5211                 struct extent_state *cached_state = NULL;
5212                 u64 start;
5213                 u64 end;
5214 
5215                 node = rb_first(&io_tree->state);
5216                 state = rb_entry(node, struct extent_state, rb_node);
5217                 start = state->start;
5218                 end = state->end;
5219                 spin_unlock(&io_tree->lock);
5220 
5221                 lock_extent_bits(io_tree, start, end, &cached_state);
5222 
5223                 /*
5224                  * If still has DELALLOC flag, the extent didn't reach disk,
5225                  * and its reserved space won't be freed by delayed_ref.
5226                  * So we need to free its reserved space here.
5227                  * (Refer to comment in btrfs_invalidatepage, case 2)
5228                  *
5229                  * Note, end is the bytenr of last byte, so we need + 1 here.
5230                  */
5231                 if (state->state & EXTENT_DELALLOC)
5232                         btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5233 
5234                 clear_extent_bit(io_tree, start, end,
5235                                  EXTENT_LOCKED | EXTENT_DIRTY |
5236                                  EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5237                                  EXTENT_DEFRAG, 1, 1,
5238                                  &cached_state, GFP_NOFS);
5239 
5240                 cond_resched();
5241                 spin_lock(&io_tree->lock);
5242         }
5243         spin_unlock(&io_tree->lock);
5244 }
5245 
5246 void btrfs_evict_inode(struct inode *inode)
5247 {
5248         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5249         struct btrfs_trans_handle *trans;
5250         struct btrfs_root *root = BTRFS_I(inode)->root;
5251         struct btrfs_block_rsv *rsv, *global_rsv;
5252         int steal_from_global = 0;
5253         u64 min_size;
5254         int ret;
5255 
5256         trace_btrfs_inode_evict(inode);
5257 
5258         if (!root) {
5259                 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
5260                 return;
5261         }
5262 
5263         min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5264 
5265         evict_inode_truncate_pages(inode);
5266 
5267         if (inode->i_nlink &&
5268             ((btrfs_root_refs(&root->root_item) != 0 &&
5269               root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5270              btrfs_is_free_space_inode(BTRFS_I(inode))))
5271                 goto no_delete;
5272 
5273         if (is_bad_inode(inode)) {
5274                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5275                 goto no_delete;
5276         }
5277         /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5278         if (!special_file(inode->i_mode))
5279                 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5280 
5281         btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5282 
5283         if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
5284                 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5285                                  &BTRFS_I(inode)->runtime_flags));
5286                 goto no_delete;
5287         }
5288 
5289         if (inode->i_nlink > 0) {
5290                 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5291                        root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5292                 goto no_delete;
5293         }
5294 
5295         ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5296         if (ret) {
5297                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5298                 goto no_delete;
5299         }
5300 
5301         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5302         if (!rsv) {
5303                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5304                 goto no_delete;
5305         }
5306         rsv->size = min_size;
5307         rsv->failfast = 1;
5308         global_rsv = &fs_info->global_block_rsv;
5309 
5310         btrfs_i_size_write(BTRFS_I(inode), 0);
5311 
5312         /*
5313          * This is a bit simpler than btrfs_truncate since we've already
5314          * reserved our space for our orphan item in the unlink, so we just
5315          * need to reserve some slack space in case we add bytes and update
5316          * inode item when doing the truncate.
5317          */
5318         while (1) {
5319                 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5320                                              BTRFS_RESERVE_FLUSH_LIMIT);
5321 
5322                 /*
5323                  * Try and steal from the global reserve since we will
5324                  * likely not use this space anyway, we want to try as
5325                  * hard as possible to get this to work.
5326                  */
5327                 if (ret)
5328                         steal_from_global++;
5329                 else
5330                         steal_from_global = 0;
5331                 ret = 0;
5332 
5333                 /*
5334                  * steal_from_global == 0: we reserved stuff, hooray!
5335                  * steal_from_global == 1: we didn't reserve stuff, boo!
5336                  * steal_from_global == 2: we've committed, still not a lot of
5337                  * room but maybe we'll have room in the global reserve this
5338                  * time.
5339                  * steal_from_global == 3: abandon all hope!
5340                  */
5341                 if (steal_from_global > 2) {
5342                         btrfs_warn(fs_info,
5343                                    "Could not get space for a delete, will truncate on mount %d",
5344                                    ret);
5345                         btrfs_orphan_del(NULL, BTRFS_I(inode));
5346                         btrfs_free_block_rsv(fs_info, rsv);
5347                         goto no_delete;
5348                 }
5349 
5350                 trans = btrfs_join_transaction(root);
5351                 if (IS_ERR(trans)) {
5352                         btrfs_orphan_del(NULL, BTRFS_I(inode));
5353                         btrfs_free_block_rsv(fs_info, rsv);
5354                         goto no_delete;
5355                 }
5356 
5357                 /*
5358                  * We can't just steal from the global reserve, we need to make
5359                  * sure there is room to do it, if not we need to commit and try
5360                  * again.
5361                  */
5362                 if (steal_from_global) {
5363                         if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5364                                 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5365                                                               min_size, 0);
5366                         else
5367                                 ret = -ENOSPC;
5368                 }
5369 
5370                 /*
5371                  * Couldn't steal from the global reserve, we have too much
5372                  * pending stuff built up, commit the transaction and try it
5373                  * again.
5374                  */
5375                 if (ret) {
5376                         ret = btrfs_commit_transaction(trans);
5377                         if (ret) {
5378                                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5379                                 btrfs_free_block_rsv(fs_info, rsv);
5380                                 goto no_delete;
5381                         }
5382                         continue;
5383                 } else {
5384                         steal_from_global = 0;
5385                 }
5386 
5387                 trans->block_rsv = rsv;
5388 
5389                 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5390                 if (ret != -ENOSPC && ret != -EAGAIN)
5391                         break;
5392 
5393                 trans->block_rsv = &fs_info->trans_block_rsv;
5394                 btrfs_end_transaction(trans);
5395                 trans = NULL;
5396                 btrfs_btree_balance_dirty(fs_info);
5397         }
5398 
5399         btrfs_free_block_rsv(fs_info, rsv);
5400 
5401         /*
5402          * Errors here aren't a big deal, it just means we leave orphan items
5403          * in the tree.  They will be cleaned up on the next mount.
5404          */
5405         if (ret == 0) {
5406                 trans->block_rsv = root->orphan_block_rsv;
5407                 btrfs_orphan_del(trans, BTRFS_I(inode));
5408         } else {
5409                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5410         }
5411 
5412         trans->block_rsv = &fs_info->trans_block_rsv;
5413         if (!(root == fs_info->tree_root ||
5414               root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5415                 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5416 
5417         btrfs_end_transaction(trans);
5418         btrfs_btree_balance_dirty(fs_info);
5419 no_delete:
5420         btrfs_remove_delayed_node(BTRFS_I(inode));
5421         clear_inode(inode);
5422 }
5423 
5424 /*
5425  * this returns the key found in the dir entry in the location pointer.
5426  * If no dir entries were found, location->objectid is 0.
5427  */
5428 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5429                                struct btrfs_key *location)
5430 {
5431         const char *name = dentry->d_name.name;
5432         int namelen = dentry->d_name.len;
5433         struct btrfs_dir_item *di;
5434         struct btrfs_path *path;
5435         struct btrfs_root *root = BTRFS_I(dir)->root;
5436         int ret = 0;
5437 
5438         path = btrfs_alloc_path();
5439         if (!path)
5440                 return -ENOMEM;
5441 
5442         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5443                         name, namelen, 0);
5444         if (IS_ERR(di))
5445                 ret = PTR_ERR(di);
5446 
5447         if (IS_ERR_OR_NULL(di))
5448                 goto out_err;
5449 
5450         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5451         if (location->type != BTRFS_INODE_ITEM_KEY &&
5452             location->type != BTRFS_ROOT_ITEM_KEY) {
5453                 btrfs_warn(root->fs_info,
5454 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5455                            __func__, name, btrfs_ino(BTRFS_I(dir)),
5456                            location->objectid, location->type, location->offset);
5457                 goto out_err;
5458         }
5459 out:
5460         btrfs_free_path(path);
5461         return ret;
5462 out_err:
5463         location->objectid = 0;
5464         goto out;
5465 }
5466 
5467 /*
5468  * when we hit a tree root in a directory, the btrfs part of the inode
5469  * needs to be changed to reflect the root directory of the tree root.  This
5470  * is kind of like crossing a mount point.
5471  */
5472 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5473                                     struct inode *dir,
5474                                     struct dentry *dentry,
5475                                     struct btrfs_key *location,
5476                                     struct btrfs_root **sub_root)
5477 {
5478         struct btrfs_path *path;
5479         struct btrfs_root *new_root;
5480         struct btrfs_root_ref *ref;
5481         struct extent_buffer *leaf;
5482         struct btrfs_key key;
5483         int ret;
5484         int err = 0;
5485 
5486         path = btrfs_alloc_path();
5487         if (!path) {
5488                 err = -ENOMEM;
5489                 goto out;
5490         }
5491 
5492         err = -ENOENT;
5493         key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5494         key.type = BTRFS_ROOT_REF_KEY;
5495         key.offset = location->objectid;
5496 
5497         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5498         if (ret) {
5499                 if (ret < 0)
5500                         err = ret;
5501                 goto out;
5502         }
5503 
5504         leaf = path->nodes[0];
5505         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5506         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5507             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5508                 goto out;
5509 
5510         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5511                                    (unsigned long)(ref + 1),
5512                                    dentry->d_name.len);
5513         if (ret)
5514                 goto out;
5515 
5516         btrfs_release_path(path);
5517 
5518         new_root = btrfs_read_fs_root_no_name(fs_info, location);
5519         if (IS_ERR(new_root)) {
5520                 err = PTR_ERR(new_root);
5521                 goto out;
5522         }
5523 
5524         *sub_root = new_root;
5525         location->objectid = btrfs_root_dirid(&new_root->root_item);
5526         location->type = BTRFS_INODE_ITEM_KEY;
5527         location->offset = 0;
5528         err = 0;
5529 out:
5530         btrfs_free_path(path);
5531         return err;
5532 }
5533 
5534 static void inode_tree_add(struct inode *inode)
5535 {
5536         struct btrfs_root *root = BTRFS_I(inode)->root;
5537         struct btrfs_inode *entry;
5538         struct rb_node **p;
5539         struct rb_node *parent;
5540         struct rb_node *new = &BTRFS_I(inode)->rb_node;
5541         u64 ino = btrfs_ino(BTRFS_I(inode));
5542 
5543         if (inode_unhashed(inode))
5544                 return;
5545         parent = NULL;
5546         spin_lock(&root->inode_lock);
5547         p = &root->inode_tree.rb_node;
5548         while (*p) {
5549                 parent = *p;
5550                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5551 
5552                 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5553                         p = &parent->rb_left;
5554                 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5555                         p = &parent->rb_right;
5556                 else {
5557                         WARN_ON(!(entry->vfs_inode.i_state &
5558                                   (I_WILL_FREE | I_FREEING)));
5559                         rb_replace_node(parent, new, &root->inode_tree);
5560                         RB_CLEAR_NODE(parent);
5561                         spin_unlock(&root->inode_lock);
5562                         return;
5563                 }
5564         }
5565         rb_link_node(new, parent, p);
5566         rb_insert_color(new, &root->inode_tree);
5567         spin_unlock(&root->inode_lock);
5568 }
5569 
5570 static void inode_tree_del(struct inode *inode)
5571 {
5572         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5573         struct btrfs_root *root = BTRFS_I(inode)->root;
5574         int empty = 0;
5575 
5576         spin_lock(&root->inode_lock);
5577         if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5578                 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5579                 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5580                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5581         }
5582         spin_unlock(&root->inode_lock);
5583 
5584         if (empty && btrfs_root_refs(&root->root_item) == 0) {
5585                 synchronize_srcu(&fs_info->subvol_srcu);
5586                 spin_lock(&root->inode_lock);
5587                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5588                 spin_unlock(&root->inode_lock);
5589                 if (empty)
5590                         btrfs_add_dead_root(root);
5591         }
5592 }
5593 
5594 void btrfs_invalidate_inodes(struct btrfs_root *root)
5595 {
5596         struct btrfs_fs_info *fs_info = root->fs_info;
5597         struct rb_node *node;
5598         struct rb_node *prev;
5599         struct btrfs_inode *entry;
5600         struct inode *inode;
5601         u64 objectid = 0;
5602 
5603         if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
5604                 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5605 
5606         spin_lock(&root->inode_lock);
5607 again:
5608         node = root->inode_tree.rb_node;
5609         prev = NULL;
5610         while (node) {
5611                 prev = node;
5612                 entry = rb_entry(node, struct btrfs_inode, rb_node);
5613 
5614                 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5615                         node = node->rb_left;
5616                 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5617                         node = node->rb_right;
5618                 else
5619                         break;
5620         }
5621         if (!node) {
5622                 while (prev) {
5623                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
5624                         if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
5625                                 node = prev;
5626                                 break;
5627                         }
5628                         prev = rb_next(prev);
5629                 }
5630         }
5631         while (node) {
5632                 entry = rb_entry(node, struct btrfs_inode, rb_node);
5633                 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
5634                 inode = igrab(&entry->vfs_inode);
5635                 if (inode) {
5636                         spin_unlock(&root->inode_lock);
5637                         if (atomic_read(&inode->i_count) > 1)
5638                                 d_prune_aliases(inode);
5639                         /*
5640                          * btrfs_drop_inode will have it removed from
5641                          * the inode cache when its usage count
5642                          * hits zero.
5643                          */
5644                         iput(inode);
5645                         cond_resched();
5646                         spin_lock(&root->inode_lock);
5647                         goto again;
5648                 }
5649 
5650                 if (cond_resched_lock(&root->inode_lock))
5651                         goto again;
5652 
5653                 node = rb_next(node);
5654         }
5655         spin_unlock(&root->inode_lock);
5656 }
5657 
5658 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5659 {
5660         struct btrfs_iget_args *args = p;
5661         inode->i_ino = args->location->objectid;
5662         memcpy(&BTRFS_I(inode)->location, args->location,
5663                sizeof(*args->location));
5664         BTRFS_I(inode)->root = args->root;
5665         return 0;
5666 }
5667 
5668 static int btrfs_find_actor(struct inode *inode, void *opaque)
5669 {
5670         struct btrfs_iget_args *args = opaque;
5671         return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5672                 args->root == BTRFS_I(inode)->root;
5673 }
5674 
5675 static struct inode *btrfs_iget_locked(struct super_block *s,
5676                                        struct btrfs_key *location,
5677                                        struct btrfs_root *root)
5678 {
5679         struct inode *inode;
5680         struct btrfs_iget_args args;
5681         unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5682 
5683         args.location = location;
5684         args.root = root;
5685 
5686         inode = iget5_locked(s, hashval, btrfs_find_actor,
5687                              btrfs_init_locked_inode,
5688                              (void *)&args);
5689         return inode;
5690 }
5691 
5692 /* Get an inode object given its location and corresponding root.
5693  * Returns in *is_new if the inode was read from disk
5694  */
5695 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5696                          struct btrfs_root *root, int *new)
5697 {
5698         struct inode *inode;
5699 
5700         inode = btrfs_iget_locked(s, location, root);
5701         if (!inode)
5702                 return ERR_PTR(-ENOMEM);
5703 
5704         if (inode->i_state & I_NEW) {
5705                 int ret;
5706 
5707                 ret = btrfs_read_locked_inode(inode);
5708                 if (!is_bad_inode(inode)) {
5709                         inode_tree_add(inode);
5710                         unlock_new_inode(inode);
5711                         if (new)
5712                                 *new = 1;
5713                 } else {
5714                         unlock_new_inode(inode);
5715                         iput(inode);
5716                         ASSERT(ret < 0);
5717                         inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5718                 }
5719         }
5720 
5721         return inode;
5722 }
5723 
5724 static struct inode *new_simple_dir(struct super_block *s,
5725                                     struct btrfs_key *key,
5726                                     struct btrfs_root *root)
5727 {
5728         struct inode *inode = new_inode(s);
5729 
5730         if (!inode)
5731                 return ERR_PTR(-ENOMEM);
5732 
5733         BTRFS_I(inode)->root = root;
5734         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5735         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5736 
5737         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5738         inode->i_op = &btrfs_dir_ro_inode_operations;
5739         inode->i_opflags &= ~IOP_XATTR;
5740         inode->i_fop = &simple_dir_operations;
5741         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5742         inode->i_mtime = current_time(inode);
5743         inode->i_atime = inode->i_mtime;
5744         inode->i_ctime = inode->i_mtime;
5745         BTRFS_I(inode)->i_otime = inode->i_mtime;
5746 
5747         return inode;
5748 }
5749 
5750 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5751 {
5752         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5753         struct inode *inode;
5754         struct btrfs_root *root = BTRFS_I(dir)->root;
5755         struct btrfs_root *sub_root = root;
5756         struct btrfs_key location;
5757         int index;
5758         int ret = 0;
5759 
5760         if (dentry->d_name.len > BTRFS_NAME_LEN)
5761                 return ERR_PTR(-ENAMETOOLONG);
5762 
5763         ret = btrfs_inode_by_name(dir, dentry, &location);
5764         if (ret < 0)
5765                 return ERR_PTR(ret);
5766 
5767         if (location.objectid == 0)
5768                 return ERR_PTR(-ENOENT);
5769 
5770         if (location.type == BTRFS_INODE_ITEM_KEY) {
5771                 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5772                 return inode;
5773         }
5774 
5775         index = srcu_read_lock(&fs_info->subvol_srcu);
5776         ret = fixup_tree_root_location(fs_info, dir, dentry,
5777                                        &location, &sub_root);
5778         if (ret < 0) {
5779                 if (ret != -ENOENT)
5780                         inode = ERR_PTR(ret);
5781                 else
5782                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
5783         } else {
5784                 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5785         }
5786         srcu_read_unlock(&fs_info->subvol_srcu, index);
5787 
5788         if (!IS_ERR(inode) && root != sub_root) {
5789                 down_read(&fs_info->cleanup_work_sem);
5790                 if (!sb_rdonly(inode->i_sb))
5791                         ret = btrfs_orphan_cleanup(sub_root);
5792                 up_read(&fs_info->cleanup_work_sem);
5793                 if (ret) {
5794                         iput(inode);
5795                         inode = ERR_PTR(ret);
5796                 }
5797         }
5798 
5799         return inode;
5800 }
5801 
5802 static int btrfs_dentry_delete(const struct dentry *dentry)
5803 {
5804         struct btrfs_root *root;
5805         struct inode *inode = d_inode(dentry);
5806 
5807         if (!inode && !IS_ROOT(dentry))
5808                 inode = d_inode(dentry->d_parent);
5809 
5810         if (inode) {
5811                 root = BTRFS_I(inode)->root;
5812                 if (btrfs_root_refs(&root->root_item) == 0)
5813                         return 1;
5814 
5815                 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5816                         return 1;
5817         }
5818         return 0;
5819 }
5820 
5821 static void btrfs_dentry_release(struct dentry *dentry)
5822 {
5823         kfree(dentry->d_fsdata);
5824 }
5825 
5826 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5827                                    unsigned int flags)
5828 {
5829         struct inode *inode;
5830 
5831         inode = btrfs_lookup_dentry(dir, dentry);
5832         if (IS_ERR(inode)) {
5833                 if (PTR_ERR(inode) == -ENOENT)
5834                         inode = NULL;
5835                 else
5836                         return ERR_CAST(inode);
5837         }
5838 
5839         return d_splice_alias(inode, dentry);
5840 }
5841 
5842 unsigned char btrfs_filetype_table[] = {
5843         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5844 };
5845 
5846 /*
5847  * All this infrastructure exists because dir_emit can fault, and we are holding
5848  * the tree lock when doing readdir.  For now just allocate a buffer and copy
5849  * our information into that, and then dir_emit from the buffer.  This is
5850  * similar to what NFS does, only we don't keep the buffer around in pagecache
5851  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
5852  * copy_to_user_inatomic so we don't have to worry about page faulting under the
5853  * tree lock.
5854  */
5855 static int btrfs_opendir(struct inode *inode, struct file *file)
5856 {
5857         struct btrfs_file_private *private;
5858 
5859         private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5860         if (!private)
5861                 return -ENOMEM;
5862         private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5863         if (!private->filldir_buf) {
5864                 kfree(private);
5865                 return -ENOMEM;
5866         }
5867         file->private_data = private;
5868         return 0;
5869 }
5870 
5871 struct dir_entry {
5872         u64 ino;
5873         u64 offset;
5874         unsigned type;
5875         int name_len;
5876 };
5877 
5878 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5879 {
5880         while (entries--) {
5881                 struct dir_entry *entry = addr;
5882                 char *name = (char *)(entry + 1);
5883 
5884                 ctx->pos = entry->offset;
5885                 if (!dir_emit(ctx, name, entry->name_len, entry->ino,
5886                               entry->type))
5887                         return 1;
5888                 addr += sizeof(struct dir_entry) + entry->name_len;
5889                 ctx->pos++;
5890         }
5891         return 0;
5892 }
5893 
5894 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5895 {
5896         struct inode *inode = file_inode(file);
5897         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5898         struct btrfs_root *root = BTRFS_I(inode)->root;
5899         struct btrfs_file_private *private = file->private_data;
5900         struct btrfs_dir_item *di;
5901         struct btrfs_key key;
5902         struct btrfs_key found_key;
5903         struct btrfs_path *path;
5904         void *addr;
5905         struct list_head ins_list;
5906         struct list_head del_list;
5907         int ret;
5908         struct extent_buffer *leaf;
5909         int slot;
5910         char *name_ptr;
5911         int name_len;
5912         int entries = 0;
5913         int total_len = 0;
5914         bool put = false;
5915         struct btrfs_key location;
5916 
5917         if (!dir_emit_dots(file, ctx))
5918                 return 0;
5919 
5920         path = btrfs_alloc_path();
5921         if (!path)
5922                 return -ENOMEM;
5923 
5924         addr = private->filldir_buf;
5925         path->reada = READA_FORWARD;
5926 
5927         INIT_LIST_HEAD(&ins_list);
5928         INIT_LIST_HEAD(&del_list);
5929         put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5930 
5931 again:
5932         key.type = BTRFS_DIR_INDEX_KEY;
5933         key.offset = ctx->pos;
5934         key.objectid = btrfs_ino(BTRFS_I(inode));
5935 
5936         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5937         if (ret < 0)
5938                 goto err;
5939 
5940         while (1) {
5941                 struct dir_entry *entry;
5942 
5943                 leaf = path->nodes[0];
5944                 slot = path->slots[0];
5945                 if (slot >= btrfs_header_nritems(leaf)) {
5946                         ret = btrfs_next_leaf(root, path);
5947                         if (ret < 0)
5948                                 goto err;
5949                         else if (ret > 0)
5950                                 break;
5951                         continue;
5952                 }
5953 
5954                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5955 
5956                 if (found_key.objectid != key.objectid)
5957                         break;
5958                 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5959                         break;
5960                 if (found_key.offset < ctx->pos)
5961                         goto next;
5962                 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5963                         goto next;
5964                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5965                 if (verify_dir_item(fs_info, leaf, slot, di))
5966                         goto next;
5967 
5968                 name_len = btrfs_dir_name_len(leaf, di);
5969                 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5970                     PAGE_SIZE) {
5971                         btrfs_release_path(path);
5972                         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5973                         if (ret)
5974                                 goto nopos;
5975                         addr = private->filldir_buf;
5976                         entries = 0;
5977                         total_len = 0;
5978                         goto again;
5979                 }
5980 
5981                 entry = addr;
5982                 entry->name_len = name_len;
5983                 name_ptr = (char *)(entry + 1);
5984                 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5985                                    name_len);
5986                 entry->type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5987                 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5988                 entry->ino = location.objectid;
5989                 entry->offset = found_key.offset;
5990                 entries++;
5991                 addr += sizeof(struct dir_entry) + name_len;
5992                 total_len += sizeof(struct dir_entry) + name_len;
5993 next:
5994                 path->slots[0]++;
5995         }
5996         btrfs_release_path(path);
5997 
5998         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5999         if (ret)
6000                 goto nopos;
6001 
6002         ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6003         if (ret)
6004                 goto nopos;
6005 
6006         /*
6007          * Stop new entries from being returned after we return the last
6008          * entry.
6009          *
6010          * New directory entries are assigned a strictly increasing
6011          * offset.  This means that new entries created during readdir
6012          * are *guaranteed* to be seen in the future by that readdir.
6013          * This has broken buggy programs which operate on names as
6014          * they're returned by readdir.  Until we re-use freed offsets
6015          * we have this hack to stop new entries from being returned
6016          * under the assumption that they'll never reach this huge
6017          * offset.
6018          *
6019          * This is being careful not to overflow 32bit loff_t unless the
6020          * last entry requires it because doing so has broken 32bit apps
6021          * in the past.
6022          */
6023         if (ctx->pos >= INT_MAX)
6024                 ctx->pos = LLONG_MAX;
6025         else
6026                 ctx->pos = INT_MAX;
6027 nopos:
6028         ret = 0;
6029 err:
6030         if (put)
6031                 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6032         btrfs_free_path(path);
6033         return ret;
6034 }
6035 
6036 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6037 {
6038         struct btrfs_root *root = BTRFS_I(inode)->root;
6039         struct btrfs_trans_handle *trans;
6040         int ret = 0;
6041         bool nolock = false;
6042 
6043         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6044                 return 0;
6045 
6046         if (btrfs_fs_closing(root->fs_info) &&
6047                         btrfs_is_free_space_inode(BTRFS_I(inode)))
6048                 nolock = true;
6049 
6050         if (wbc->sync_mode == WB_SYNC_ALL) {
6051                 if (nolock)
6052                         trans = btrfs_join_transaction_nolock(root);
6053                 else
6054                         trans = btrfs_join_transaction(root);
6055                 if (IS_ERR(trans))
6056                         return PTR_ERR(trans);
6057                 ret = btrfs_commit_transaction(trans);
6058         }
6059         return ret;
6060 }
6061 
6062 /*
6063  * This is somewhat expensive, updating the tree every time the
6064  * inode changes.  But, it is most likely to find the inode in cache.
6065  * FIXME, needs more benchmarking...there are no reasons other than performance
6066  * to keep or drop this code.
6067  */
6068 static int btrfs_dirty_inode(struct inode *inode)
6069 {
6070         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6071         struct btrfs_root *root = BTRFS_I(inode)->root;
6072         struct btrfs_trans_handle *trans;
6073         int ret;
6074 
6075         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6076                 return 0;
6077 
6078         trans = btrfs_join_transaction(root);
6079         if (IS_ERR(trans))
6080                 return PTR_ERR(trans);
6081 
6082         ret = btrfs_update_inode(trans, root, inode);
6083         if (ret && ret == -ENOSPC) {
6084                 /* whoops, lets try again with the full transaction */
6085                 btrfs_end_transaction(trans);
6086                 trans = btrfs_start_transaction(root, 1);
6087                 if (IS_ERR(trans))
6088                         return PTR_ERR(trans);
6089 
6090                 ret = btrfs_update_inode(trans, root, inode);
6091         }
6092         btrfs_end_transaction(trans);
6093         if (BTRFS_I(inode)->delayed_node)
6094                 btrfs_balance_delayed_items(fs_info);
6095 
6096         return ret;
6097 }
6098 
6099 /*
6100  * This is a copy of file_update_time.  We need this so we can return error on
6101  * ENOSPC for updating the inode in the case of file write and mmap writes.
6102  */
6103 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6104                              int flags)
6105 {
6106         struct btrfs_root *root = BTRFS_I(inode)->root;
6107 
6108         if (btrfs_root_readonly(root))
6109                 return -EROFS;
6110 
6111         if (flags & S_VERSION)
6112                 inode_inc_iversion(inode);
6113         if (flags & S_CTIME)
6114                 inode->i_ctime = *now;
6115         if (flags & S_MTIME)
6116                 inode->i_mtime = *now;
6117         if (flags & S_ATIME)
6118                 inode->i_atime = *now;
6119         return btrfs_dirty_inode(inode);
6120 }
6121 
6122 /*
6123  * find the highest existing sequence number in a directory
6124  * and then set the in-memory index_cnt variable to reflect
6125  * free sequence numbers
6126  */
6127 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6128 {
6129         struct btrfs_root *root = inode->root;
6130         struct btrfs_key key, found_key;
6131         struct btrfs_path *path;
6132         struct extent_buffer *leaf;
6133         int ret;
6134 
6135         key.objectid = btrfs_ino(inode);
6136         key.type = BTRFS_DIR_INDEX_KEY;
6137         key.offset = (u64)-1;
6138 
6139         path = btrfs_alloc_path();
6140         if (!path)
6141                 return -ENOMEM;
6142 
6143         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6144         if (ret < 0)
6145                 goto out;
6146         /* FIXME: we should be able to handle this */
6147         if (ret == 0)
6148                 goto out;
6149         ret = 0;
6150 
6151         /*
6152          * MAGIC NUMBER EXPLANATION:
6153          * since we search a directory based on f_pos we have to start at 2
6154          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6155          * else has to start at 2
6156          */
6157         if (path->slots[0] == 0) {
6158                 inode->index_cnt = 2;
6159                 goto out;
6160         }
6161 
6162         path->slots[0]--;
6163 
6164         leaf = path->nodes[0];
6165         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6166 
6167         if (found_key.objectid != btrfs_ino(inode) ||
6168             found_key.type != BTRFS_DIR_INDEX_KEY) {
6169                 inode->index_cnt = 2;
6170                 goto out;
6171         }
6172 
6173         inode->index_cnt = found_key.offset + 1;
6174 out:
6175         btrfs_free_path(path);
6176         return ret;
6177 }
6178 
6179 /*
6180  * helper to find a free sequence number in a given directory.  This current
6181  * code is very simple, later versions will do smarter things in the btree
6182  */
6183 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6184 {
6185         int ret = 0;
6186 
6187         if (dir->index_cnt == (u64)-1) {
6188                 ret = btrfs_inode_delayed_dir_index_count(dir);
6189                 if (ret) {
6190                         ret = btrfs_set_inode_index_count(dir);
6191                         if (ret)
6192                                 return ret;
6193                 }
6194         }
6195 
6196         *index = dir->index_cnt;
6197         dir->index_cnt++;
6198 
6199         return ret;
6200 }
6201 
6202 static int btrfs_insert_inode_locked(struct inode *inode)
6203 {
6204         struct btrfs_iget_args args;
6205         args.location = &BTRFS_I(inode)->location;
6206         args.root = BTRFS_I(inode)->root;
6207 
6208         return insert_inode_locked4(inode,
6209                    btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6210                    btrfs_find_actor, &args);
6211 }
6212 
6213 /*
6214  * Inherit flags from the parent inode.
6215  *
6216  * Currently only the compression flags and the cow flags are inherited.
6217  */
6218 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6219 {
6220         unsigned int flags;
6221 
6222         if (!dir)
6223                 return;
6224 
6225         flags = BTRFS_I(dir)->flags;
6226 
6227         if (flags & BTRFS_INODE_NOCOMPRESS) {
6228                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6229                 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6230         } else if (flags & BTRFS_INODE_COMPRESS) {
6231                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6232                 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6233         }
6234 
6235         if (flags & BTRFS_INODE_NODATACOW) {
6236                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6237                 if (S_ISREG(inode->i_mode))
6238                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6239         }
6240 
6241         btrfs_update_iflags(inode);
6242 }
6243 
6244 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6245                                      struct btrfs_root *root,
6246                                      struct inode *dir,
6247                                      const char *name, int name_len,
6248                                      u64 ref_objectid, u64 objectid,
6249                                      umode_t mode, u64 *index)
6250 {
6251         struct btrfs_fs_info *fs_info = root->fs_info;
6252         struct inode *inode;
6253         struct btrfs_inode_item *inode_item;
6254         struct btrfs_key *location;
6255         struct btrfs_path *path;
6256         struct btrfs_inode_ref *ref;
6257         struct btrfs_key key[2];
6258         u32 sizes[2];
6259         int nitems = name ? 2 : 1;
6260         unsigned long ptr;
6261         int ret;
6262 
6263         path = btrfs_alloc_path();
6264         if (!path)
6265                 return ERR_PTR(-ENOMEM);
6266 
6267         inode = new_inode(fs_info->sb);
6268         if (!inode) {
6269                 btrfs_free_path(path);
6270                 return ERR_PTR(-ENOMEM);
6271         }
6272 
6273         /*
6274          * O_TMPFILE, set link count to 0, so that after this point,
6275          * we fill in an inode item with the correct link count.
6276          */
6277         if (!name)
6278                 set_nlink(inode, 0);
6279 
6280         /*
6281          * we have to initialize this early, so we can reclaim the inode
6282          * number if we fail afterwards in this function.
6283          */
6284         inode->i_ino = objectid;
6285 
6286         if (dir && name) {
6287                 trace_btrfs_inode_request(dir);
6288 
6289                 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6290                 if (ret) {
6291                         btrfs_free_path(path);
6292                         iput(inode);
6293                         return ERR_PTR(ret);
6294                 }
6295         } else if (dir) {
6296                 *index = 0;
6297         }
6298         /*
6299          * index_cnt is ignored for everything but a dir,
6300          * btrfs_get_inode_index_count has an explanation for the magic
6301          * number
6302          */
6303         BTRFS_I(inode)->index_cnt = 2;
6304         BTRFS_I(inode)->dir_index = *index;
6305         BTRFS_I(inode)->root = root;
6306         BTRFS_I(inode)->generation = trans->transid;
6307         inode->i_generation = BTRFS_I(inode)->generation;
6308 
6309         /*
6310          * We could have gotten an inode number from somebody who was fsynced
6311          * and then removed in this same transaction, so let's just set full
6312          * sync since it will be a full sync anyway and this will blow away the
6313          * old info in the log.
6314          */
6315         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6316 
6317         key[0].objectid = objectid;
6318         key[0].type = BTRFS_INODE_ITEM_KEY;
6319         key[0].offset = 0;
6320 
6321         sizes[0] = sizeof(struct btrfs_inode_item);
6322 
6323         if (name) {
6324                 /*
6325                  * Start new inodes with an inode_ref. This is slightly more
6326                  * efficient for small numbers of hard links since they will
6327                  * be packed into one item. Extended refs will kick in if we
6328                  * add more hard links than can fit in the ref item.
6329                  */
6330                 key[1].objectid = objectid;
6331                 key[1].type = BTRFS_INODE_REF_KEY;
6332                 key[1].offset = ref_objectid;
6333 
6334                 sizes[1] = name_len + sizeof(*ref);
6335         }
6336 
6337         location = &BTRFS_I(inode)->location;
6338         location->objectid = objectid;
6339         location->offset = 0;
6340         location->type = BTRFS_INODE_ITEM_KEY;
6341 
6342         ret = btrfs_insert_inode_locked(inode);
6343         if (ret < 0)
6344                 goto fail;
6345 
6346         path->leave_spinning = 1;
6347         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6348         if (ret != 0)
6349                 goto fail_unlock;
6350 
6351         inode_init_owner(inode, dir, mode);
6352         inode_set_bytes(inode, 0);
6353 
6354         inode->i_mtime = current_time(inode);
6355         inode->i_atime = inode->i_mtime;
6356         inode->i_ctime = inode->i_mtime;
6357         BTRFS_I(inode)->i_otime = inode->i_mtime;
6358 
6359         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6360                                   struct btrfs_inode_item);
6361         memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6362                              sizeof(*inode_item));
6363         fill_inode_item(trans, path->nodes[0], inode_item, inode);
6364 
6365         if (name) {
6366                 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6367                                      struct btrfs_inode_ref);
6368                 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6369                 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6370                 ptr = (unsigned long)(ref + 1);
6371                 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6372         }
6373 
6374         btrfs_mark_buffer_dirty(path->nodes[0]);
6375         btrfs_free_path(path);
6376 
6377         btrfs_inherit_iflags(inode, dir);
6378 
6379         if (S_ISREG(mode)) {
6380                 if (btrfs_test_opt(fs_info, NODATASUM))
6381                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6382                 if (btrfs_test_opt(fs_info, NODATACOW))
6383                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6384                                 BTRFS_INODE_NODATASUM;
6385         }
6386 
6387         inode_tree_add(inode);
6388 
6389         trace_btrfs_inode_new(inode);
6390         btrfs_set_inode_last_trans(trans, inode);
6391 
6392         btrfs_update_root_times(trans, root);
6393 
6394         ret = btrfs_inode_inherit_props(trans, inode, dir);
6395         if (ret)
6396                 btrfs_err(fs_info,
6397                           "error inheriting props for ino %llu (root %llu): %d",
6398                         btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6399 
6400         return inode;
6401 
6402 fail_unlock:
6403         unlock_new_inode(inode);
6404 fail:
6405         if (dir && name)
6406                 BTRFS_I(dir)->index_cnt--;
6407         btrfs_free_path(path);
6408         iput(inode);
6409         return ERR_PTR(ret);
6410 }
6411 
6412 static inline u8 btrfs_inode_type(struct inode *inode)
6413 {
6414         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6415 }
6416 
6417 /*
6418  * utility function to add 'inode' into 'parent_inode' with
6419  * a give name and a given sequence number.
6420  * if 'add_backref' is true, also insert a backref from the
6421  * inode to the parent directory.
6422  */
6423 int btrfs_add_link(struct btrfs_trans_handle *trans,
6424                    struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6425                    const char *name, int name_len, int add_backref, u64 index)
6426 {
6427         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6428         int ret = 0;
6429         struct btrfs_key key;
6430         struct btrfs_root *root = parent_inode->root;
6431         u64 ino = btrfs_ino(inode);
6432         u64 parent_ino = btrfs_ino(parent_inode);
6433 
6434         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6435                 memcpy(&key, &inode->root->root_key, sizeof(key));
6436         } else {
6437                 key.objectid = ino;
6438                 key.type = BTRFS_INODE_ITEM_KEY;
6439                 key.offset = 0;
6440         }
6441 
6442         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6443                 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6444                                          root->root_key.objectid, parent_ino,
6445                                          index, name, name_len);
6446         } else if (add_backref) {
6447                 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6448                                              parent_ino, index);
6449         }
6450 
6451         /* Nothing to clean up yet */
6452         if (ret)
6453                 return ret;
6454 
6455         ret = btrfs_insert_dir_item(trans, root, name, name_len,
6456                                     parent_inode, &key,
6457                                     btrfs_inode_type(&inode->vfs_inode), index);
6458         if (ret == -EEXIST || ret == -EOVERFLOW)
6459                 goto fail_dir_item;
6460         else if (ret) {
6461                 btrfs_abort_transaction(trans, ret);
6462                 return ret;
6463         }
6464 
6465         btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6466                            name_len * 2);
6467         inode_inc_iversion(&parent_inode->vfs_inode);
6468         parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6469                 current_time(&parent_inode->vfs_inode);
6470         ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6471         if (ret)
6472                 btrfs_abort_transaction(trans, ret);
6473         return ret;
6474 
6475 fail_dir_item:
6476         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6477                 u64 local_index;
6478                 int err;
6479                 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6480                                          root->root_key.objectid, parent_ino,
6481                                          &local_index, name, name_len);
6482 
6483         } else if (add_backref) {
6484                 u64 local_index;
6485                 int err;
6486 
6487                 err = btrfs_del_inode_ref(trans, root, name, name_len,
6488                                           ino, parent_ino, &local_index);
6489         }
6490         return ret;
6491 }
6492 
6493 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6494                             struct btrfs_inode *dir, struct dentry *dentry,
6495                             struct btrfs_inode *inode, int backref, u64 index)
6496 {
6497         int err = btrfs_add_link(trans, dir, inode,
6498                                  dentry->d_name.name, dentry->d_name.len,
6499                                  backref, index);
6500         if (err > 0)
6501                 err = -EEXIST;
6502         return err;
6503 }
6504 
6505 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6506                         umode_t mode, dev_t rdev)
6507 {
6508         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6509         struct btrfs_trans_handle *trans;
6510         struct btrfs_root *root = BTRFS_I(dir)->root;
6511         struct inode *inode = NULL;
6512         int err;
6513         int drop_inode = 0;
6514         u64 objectid;
6515         u64 index = 0;
6516 
6517         /*
6518          * 2 for inode item and ref
6519          * 2 for dir items
6520          * 1 for xattr if selinux is on
6521          */
6522         trans = btrfs_start_transaction(root, 5);
6523         if (IS_ERR(trans))
6524                 return PTR_ERR(trans);
6525 
6526         err = btrfs_find_free_ino(root, &objectid);
6527         if (err)
6528                 goto out_unlock;
6529 
6530         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6531                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6532                         mode, &index);
6533         if (IS_ERR(inode)) {
6534                 err = PTR_ERR(inode);
6535                 goto out_unlock;
6536         }
6537 
6538         /*
6539         * If the active LSM wants to access the inode during
6540         * d_instantiate it needs these. Smack checks to see
6541         * if the filesystem supports xattrs by looking at the
6542         * ops vector.
6543         */
6544         inode->i_op = &btrfs_special_inode_operations;
6545         init_special_inode(inode, inode->i_mode, rdev);
6546 
6547         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6548         if (err)
6549                 goto out_unlock_inode;
6550 
6551         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6552                         0, index);
6553         if (err) {
6554                 goto out_unlock_inode;
6555         } else {
6556                 btrfs_update_inode(trans, root, inode);
6557                 unlock_new_inode(inode);
6558                 d_instantiate(dentry, inode);
6559         }
6560 
6561 out_unlock:
6562         btrfs_end_transaction(trans);
6563         btrfs_balance_delayed_items(fs_info);
6564         btrfs_btree_balance_dirty(fs_info);
6565         if (drop_inode) {
6566                 inode_dec_link_count(inode);
6567                 iput(inode);
6568         }
6569         return err;
6570 
6571 out_unlock_inode:
6572         drop_inode = 1;
6573         unlock_new_inode(inode);
6574         goto out_unlock;
6575 
6576 }
6577 
6578 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6579                         umode_t mode, bool excl)
6580 {
6581         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6582         struct btrfs_trans_handle *trans;
6583         struct btrfs_root *root = BTRFS_I(dir)->root;
6584         struct inode *inode = NULL;
6585         int drop_inode_on_err = 0;
6586         int err;
6587         u64 objectid;
6588         u64 index = 0;
6589 
6590         /*
6591          * 2 for inode item and ref
6592          * 2 for dir items
6593          * 1 for xattr if selinux is on
6594          */
6595         trans = btrfs_start_transaction(root, 5);
6596         if (IS_ERR(trans))
6597                 return PTR_ERR(trans);
6598 
6599         err = btrfs_find_free_ino(root, &objectid);
6600         if (err)
6601                 goto out_unlock;
6602 
6603         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6604                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6605                         mode, &index);
6606         if (IS_ERR(inode)) {
6607                 err = PTR_ERR(inode);
6608                 goto out_unlock;
6609         }
6610         drop_inode_on_err = 1;
6611         /*
6612         * If the active LSM wants to access the inode during
6613         * d_instantiate it needs these. Smack checks to see
6614         * if the filesystem supports xattrs by looking at the
6615         * ops vector.
6616         */
6617         inode->i_fop = &btrfs_file_operations;
6618         inode->i_op = &btrfs_file_inode_operations;
6619         inode->i_mapping->a_ops = &btrfs_aops;
6620 
6621         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6622         if (err)
6623                 goto out_unlock_inode;
6624 
6625         err = btrfs_update_inode(trans, root, inode);
6626         if (err)
6627                 goto out_unlock_inode;
6628 
6629         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6630                         0, index);
6631         if (err)
6632                 goto out_unlock_inode;
6633 
6634         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6635         unlock_new_inode(inode);
6636         d_instantiate(dentry, inode);
6637 
6638 out_unlock:
6639         btrfs_end_transaction(trans);
6640         if (err && drop_inode_on_err) {
6641                 inode_dec_link_count(inode);
6642                 iput(inode);
6643         }
6644         btrfs_balance_delayed_items(fs_info);
6645         btrfs_btree_balance_dirty(fs_info);
6646         return err;
6647 
6648 out_unlock_inode:
6649         unlock_new_inode(inode);
6650         goto out_unlock;
6651 
6652 }
6653 
6654 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6655                       struct dentry *dentry)
6656 {
6657         struct btrfs_trans_handle *trans = NULL;
6658         struct btrfs_root *root = BTRFS_I(dir)->root;
6659         struct inode *inode = d_inode(old_dentry);
6660         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6661         u64 index;
6662         int err;
6663         int drop_inode = 0;
6664 
6665         /* do not allow sys_link's with other subvols of the same device */
6666         if (root->objectid != BTRFS_I(inode)->root->objectid)
6667                 return -EXDEV;
6668 
6669         if (inode->i_nlink >= BTRFS_LINK_MAX)
6670                 return -EMLINK;
6671 
6672         err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6673         if (err)
6674                 goto fail;
6675 
6676         /*
6677          * 2 items for inode and inode ref
6678          * 2 items for dir items
6679          * 1 item for parent inode
6680          */
6681         trans = btrfs_start_transaction(root, 5);
6682         if (IS_ERR(trans)) {
6683                 err = PTR_ERR(trans);
6684                 trans = NULL;
6685                 goto fail;
6686         }
6687 
6688         /* There are several dir indexes for this inode, clear the cache. */
6689         BTRFS_I(inode)->dir_index = 0ULL;
6690         inc_nlink(inode);
6691         inode_inc_iversion(inode);
6692         inode->i_ctime = current_time(inode);
6693         ihold(inode);
6694         set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6695 
6696         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6697                         1, index);
6698 
6699         if (err) {
6700                 drop_inode = 1;
6701         } else {
6702                 struct dentry *parent = dentry->d_parent;
6703                 err = btrfs_update_inode(trans, root, inode);
6704                 if (err)
6705                         goto fail;
6706                 if (inode->i_nlink == 1) {
6707                         /*
6708                          * If new hard link count is 1, it's a file created
6709                          * with open(2) O_TMPFILE flag.
6710                          */
6711                         err = btrfs_orphan_del(trans, BTRFS_I(inode));
6712                         if (err)
6713                                 goto fail;
6714                 }
6715                 d_instantiate(dentry, inode);
6716                 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6717         }
6718 
6719         btrfs_balance_delayed_items(fs_info);
6720 fail:
6721         if (trans)
6722                 btrfs_end_transaction(trans);
6723         if (drop_inode) {
6724                 inode_dec_link_count(inode);
6725                 iput(inode);
6726         }
6727         btrfs_btree_balance_dirty(fs_info);
6728         return err;
6729 }
6730 
6731 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6732 {
6733         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6734         struct inode *inode = NULL;
6735         struct btrfs_trans_handle *trans;
6736         struct btrfs_root *root = BTRFS_I(dir)->root;
6737         int err = 0;
6738         int drop_on_err = 0;
6739         u64 objectid = 0;
6740         u64 index = 0;
6741 
6742         /*
6743          * 2 items for inode and ref
6744          * 2 items for dir items
6745          * 1 for xattr if selinux is on
6746          */
6747         trans = btrfs_start_transaction(root, 5);
6748         if (IS_ERR(trans))
6749                 return PTR_ERR(trans);
6750 
6751         err = btrfs_find_free_ino(root, &objectid);
6752         if (err)
6753                 goto out_fail;
6754 
6755         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6756                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6757                         S_IFDIR | mode, &index);
6758         if (IS_ERR(inode)) {
6759                 err = PTR_ERR(inode);
6760                 goto out_fail;
6761         }
6762 
6763         drop_on_err = 1;
6764         /* these must be set before we unlock the inode */
6765         inode->i_op = &btrfs_dir_inode_operations;
6766         inode->i_fop = &btrfs_dir_file_operations;
6767 
6768         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6769         if (err)
6770                 goto out_fail_inode;
6771 
6772         btrfs_i_size_write(BTRFS_I(inode), 0);
6773         err = btrfs_update_inode(trans, root, inode);
6774         if (err)
6775                 goto out_fail_inode;
6776 
6777         err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6778                         dentry->d_name.name,
6779                         dentry->d_name.len, 0, index);
6780         if (err)
6781                 goto out_fail_inode;
6782 
6783         d_instantiate(dentry, inode);
6784         /*
6785          * mkdir is special.  We're unlocking after we call d_instantiate
6786          * to avoid a race with nfsd calling d_instantiate.
6787          */
6788         unlock_new_inode(inode);
6789         drop_on_err = 0;
6790 
6791 out_fail:
6792         btrfs_end_transaction(trans);
6793         if (drop_on_err) {
6794                 inode_dec_link_count(inode);
6795                 iput(inode);
6796         }
6797         btrfs_balance_delayed_items(fs_info);
6798         btrfs_btree_balance_dirty(fs_info);
6799         return err;
6800 
6801 out_fail_inode:
6802         unlock_new_inode(inode);
6803         goto out_fail;
6804 }
6805 
6806 /* Find next extent map of a given extent map, caller needs to ensure locks */
6807 static struct extent_map *next_extent_map(struct extent_map *em)
6808 {
6809         struct rb_node *next;
6810 
6811         next = rb_next(&em->rb_node);
6812         if (!next)
6813                 return NULL;
6814         return container_of(next, struct extent_map, rb_node);
6815 }
6816 
6817 static struct extent_map *prev_extent_map(struct extent_map *em)
6818 {
6819         struct rb_node *prev;
6820 
6821         prev = rb_prev(&em->rb_node);
6822         if (!prev)
6823                 return NULL;
6824         return container_of(prev, struct extent_map, rb_node);
6825 }
6826 
6827 /* helper for btfs_get_extent.  Given an existing extent in the tree,
6828  * the existing extent is the nearest extent to map_start,
6829  * and an extent that you want to insert, deal with overlap and insert
6830  * the best fitted new extent into the tree.
6831  */
6832 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6833                                 struct extent_map *existing,
6834                                 struct extent_map *em,
6835                                 u64 map_start)
6836 {
6837         struct extent_map *prev;
6838         struct extent_map *next;
6839         u64 start;
6840         u64 end;
6841         u64 start_diff;
6842 
6843         BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6844 
6845         if (existing->start > map_start) {
6846                 next = existing;
6847                 prev = prev_extent_map(next);
6848         } else {
6849                 prev = existing;
6850                 next = next_extent_map(prev);
6851         }
6852 
6853         start = prev ? extent_map_end(prev) : em->start;
6854         start = max_t(u64, start, em->start);
6855         end = next ? next->start : extent_map_end(em);
6856         end = min_t(u64, end, extent_map_end(em));
6857         start_diff = start - em->start;
6858         em->start = start;
6859         em->len = end - start;
6860         if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6861             !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6862                 em->block_start += start_diff;
6863                 em->block_len -= start_diff;
6864         }
6865         return add_extent_mapping(em_tree, em, 0);
6866 }
6867 
6868 static noinline int uncompress_inline(struct btrfs_path *path,
6869                                       struct page *page,
6870                                       size_t pg_offset, u64 extent_offset,
6871                                       struct btrfs_file_extent_item *item)
6872 {
6873         int ret;
6874         struct extent_buffer *leaf = path->nodes[0];
6875         char *tmp;
6876         size_t max_size;
6877         unsigned long inline_size;
6878         unsigned long ptr;
6879         int compress_type;
6880 
6881         WARN_ON(pg_offset != 0);
6882         compress_type = btrfs_file_extent_compression(leaf, item);
6883         max_size = btrfs_file_extent_ram_bytes(leaf, item);
6884         inline_size = btrfs_file_extent_inline_item_len(leaf,
6885                                         btrfs_item_nr(path->slots[0]));
6886         tmp = kmalloc(inline_size, GFP_NOFS);
6887         if (!tmp)
6888                 return -ENOMEM;
6889         ptr = btrfs_file_extent_inline_start(item);
6890 
6891         read_extent_buffer(leaf, tmp, ptr, inline_size);
6892 
6893         max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6894         ret = btrfs_decompress(compress_type, tmp, page,
6895                                extent_offset, inline_size, max_size);
6896 
6897         /*
6898          * decompression code contains a memset to fill in any space between the end
6899          * of the uncompressed data and the end of max_size in case the decompressed
6900          * data ends up shorter than ram_bytes.  That doesn't cover the hole between
6901          * the end of an inline extent and the beginning of the next block, so we
6902          * cover that region here.
6903          */
6904 
6905         if (max_size + pg_offset < PAGE_SIZE) {
6906                 char *map = kmap(page);
6907                 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6908                 kunmap(page);
6909         }
6910         kfree(tmp);
6911         return ret;
6912 }
6913 
6914 /*
6915  * a bit scary, this does extent mapping from logical file offset to the disk.
6916  * the ugly parts come from merging extents from the disk with the in-ram
6917  * representation.  This gets more complex because of the data=ordered code,
6918  * where the in-ram extents might be locked pending data=ordered completion.
6919  *
6920  * This also copies inline extents directly into the page.
6921  */
6922 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6923                 struct page *page,
6924             size_t pg_offset, u64 start, u64 len,
6925                 int create)
6926 {
6927         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6928         int ret;
6929         int err = 0;
6930         u64 extent_start = 0;
6931         u64 extent_end = 0;
6932         u64 objectid = btrfs_ino(inode);
6933         u32 found_type;
6934         struct btrfs_path *path = NULL;
6935         struct btrfs_root *root = inode->root;
6936         struct btrfs_file_extent_item *item;
6937         struct extent_buffer *leaf;
6938         struct btrfs_key found_key;
6939         struct extent_map *em = NULL;
6940         struct extent_map_tree *em_tree = &inode->extent_tree;
6941         struct extent_io_tree *io_tree = &inode->io_tree;
6942         struct btrfs_trans_handle *trans = NULL;
6943         const bool new_inline = !page || create;
6944 
6945 again:
6946         read_lock(&em_tree->lock);
6947         em = lookup_extent_mapping(em_tree, start, len);
6948         if (em)
6949                 em->bdev = fs_info->fs_devices->latest_bdev;
6950         read_unlock(&em_tree->lock);
6951 
6952         if (em) {
6953                 if (em->start > start || em->start + em->len <= start)
6954                         free_extent_map(em);
6955                 else if (em->block_start == EXTENT_MAP_INLINE && page)
6956                         free_extent_map(em);
6957                 else
6958                         goto out;
6959         }
6960         em = alloc_extent_map();
6961         if (!em) {
6962                 err = -ENOMEM;
6963                 goto out;
6964         }
6965         em->bdev = fs_info->fs_devices->latest_bdev;
6966         em->start = EXTENT_MAP_HOLE;
6967         em->orig_start = EXTENT_MAP_HOLE;
6968         em->len = (u64)-1;
6969         em->block_len = (u64)-1;
6970 
6971         if (!path) {
6972                 path = btrfs_alloc_path();
6973                 if (!path) {
6974                         err = -ENOMEM;
6975                         goto out;
6976                 }
6977                 /*
6978                  * Chances are we'll be called again, so go ahead and do
6979                  * readahead
6980                  */
6981                 path->reada = READA_FORWARD;
6982         }
6983 
6984         ret = btrfs_lookup_file_extent(trans, root, path,
6985                                        objectid, start, trans != NULL);
6986         if (ret < 0) {
6987                 err = ret;
6988                 goto out;
6989         }
6990 
6991         if (ret != 0) {
6992                 if (path->slots[0] == 0)
6993                         goto not_found;
6994                 path->slots[0]--;
6995         }
6996 
6997         leaf = path->nodes[0];
6998         item = btrfs_item_ptr(leaf, path->slots[0],
6999                               struct btrfs_file_extent_item);
7000         /* are we inside the extent that was found? */
7001         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7002         found_type = found_key.type;
7003         if (found_key.objectid != objectid ||
7004             found_type != BTRFS_EXTENT_DATA_KEY) {
7005                 /*
7006                  * If we backup past the first extent we want to move forward
7007                  * and see if there is an extent in front of us, otherwise we'll
7008                  * say there is a hole for our whole search range which can
7009                  * cause problems.
7010                  */
7011                 extent_end = start;
7012                 goto next;
7013         }
7014 
7015         found_type = btrfs_file_extent_type(leaf, item);
7016         extent_start = found_key.offset;
7017         if (found_type == BTRFS_FILE_EXTENT_REG ||
7018             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7019                 extent_end = extent_start +
7020                        btrfs_file_extent_num_bytes(leaf, item);
7021 
7022                 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7023                                                        extent_start);
7024         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7025                 size_t size;
7026                 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7027                 extent_end = ALIGN(extent_start + size,
7028                                    fs_info->sectorsize);
7029 
7030                 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7031                                                       path->slots[0],
7032                                                       extent_start);
7033         }
7034 next:
7035         if (start >= extent_end) {
7036                 path->slots[0]++;
7037                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7038                         ret = btrfs_next_leaf(root, path);
7039                         if (ret < 0) {
7040                                 err = ret;
7041                                 goto out;
7042                         }
7043                         if (ret > 0)
7044                                 goto not_found;
7045                         leaf = path->nodes[0];
7046                 }
7047                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7048                 if (found_key.objectid != objectid ||
7049                     found_key.type != BTRFS_EXTENT_DATA_KEY)
7050                         goto not_found;
7051                 if (start + len <= found_key.offset)
7052                         goto not_found;
7053                 if (start > found_key.offset)
7054                         goto next;
7055                 em->start = start;
7056                 em->orig_start = start;
7057                 em->len = found_key.offset - start;
7058                 goto not_found_em;
7059         }
7060 
7061         btrfs_extent_item_to_extent_map(inode, path, item,
7062                         new_inline, em);
7063 
7064         if (found_type == BTRFS_FILE_EXTENT_REG ||
7065             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7066                 goto insert;
7067         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7068                 unsigned long ptr;
7069                 char *map;
7070                 size_t size;
7071                 size_t extent_offset;
7072                 size_t copy_size;
7073 
7074                 if (new_inline)
7075                         goto out;
7076 
7077                 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7078                 extent_offset = page_offset(page) + pg_offset - extent_start;
7079                 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7080                                   size - extent_offset);
7081                 em->start = extent_start + extent_offset;
7082                 em->len = ALIGN(copy_size, fs_info->sectorsize);
7083                 em->orig_block_len = em->len;
7084                 em->orig_start = em->start;
7085                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7086                 if (create == 0 && !PageUptodate(page)) {
7087                         if (btrfs_file_extent_compression(leaf, item) !=
7088                             BTRFS_COMPRESS_NONE) {
7089                                 ret = uncompress_inline(path, page, pg_offset,
7090                                                         extent_offset, item);
7091                                 if (ret) {
7092                                         err = ret;
7093                                         goto out;
7094                                 }
7095                         } else {
7096                                 map = kmap(page);
7097                                 read_extent_buffer(leaf, map + pg_offset, ptr,
7098                                                    copy_size);
7099                                 if (pg_offset + copy_size < PAGE_SIZE) {
7100                                         memset(map + pg_offset + copy_size, 0,
7101                                                PAGE_SIZE - pg_offset -
7102                                                copy_size);
7103                                 }
7104                                 kunmap(page);
7105                         }
7106                         flush_dcache_page(page);
7107                 } else if (create && PageUptodate(page)) {
7108                         BUG();
7109                         if (!trans) {
7110                                 kunmap(page);
7111                                 free_extent_map(em);
7112                                 em = NULL;
7113 
7114                                 btrfs_release_path(path);
7115                                 trans = btrfs_join_transaction(root);
7116 
7117                                 if (IS_ERR(trans))
7118                                         return ERR_CAST(trans);
7119                                 goto again;
7120                         }
7121                         map = kmap(page);
7122                         write_extent_buffer(leaf, map + pg_offset, ptr,
7123                                             copy_size);
7124                         kunmap(page);
7125                         btrfs_mark_buffer_dirty(leaf);
7126                 }
7127                 set_extent_uptodate(io_tree, em->start,
7128                                     extent_map_end(em) - 1, NULL, GFP_NOFS);
7129                 goto insert;
7130         }
7131 not_found:
7132         em->start = start;
7133         em->orig_start = start;
7134         em->len = len;
7135 not_found_em:
7136         em->block_start = EXTENT_MAP_HOLE;
7137         set_bit(EXTENT_FLAG_VACANCY, &em->flags);
7138 insert:
7139         btrfs_release_path(path);
7140         if (em->start > start || extent_map_end(em) <= start) {
7141                 btrfs_err(fs_info,
7142                           "bad extent! em: [%llu %llu] passed [%llu %llu]",
7143                           em->start, em->len, start, len);
7144                 err = -EIO;
7145                 goto out;
7146         }
7147 
7148         err = 0;
7149         write_lock(&em_tree->lock);
7150         ret = add_extent_mapping(em_tree, em, 0);
7151         /* it is possible that someone inserted the extent into the tree
7152          * while we had the lock dropped.  It is also possible that
7153          * an overlapping map exists in the tree
7154          */
7155         if (ret == -EEXIST) {
7156                 struct extent_map *existing;
7157 
7158                 ret = 0;
7159 
7160                 existing = search_extent_mapping(em_tree, start, len);
7161                 /*
7162                  * existing will always be non-NULL, since there must be
7163                  * extent causing the -EEXIST.
7164                  */
7165                 if (existing->start == em->start &&
7166                     extent_map_end(existing) >= extent_map_end(em) &&
7167                     em->block_start == existing->block_start) {
7168                         /*
7169                          * The existing extent map already encompasses the
7170                          * entire extent map we tried to add.
7171                          */
7172                         free_extent_map(em);
7173                         em = existing;
7174                         err = 0;
7175 
7176                 } else if (start >= extent_map_end(existing) ||
7177                     start <= existing->start) {
7178                         /*
7179                          * The existing extent map is the one nearest to
7180                          * the [start, start + len) range which overlaps
7181                          */
7182                         err = merge_extent_mapping(em_tree, existing,
7183                                                    em, start);
7184                         free_extent_map(existing);
7185                         if (err) {
7186                                 free_extent_map(em);
7187                                 em = NULL;
7188                         }
7189                 } else {
7190                         free_extent_map(em);
7191                         em = existing;
7192                         err = 0;
7193                 }
7194         }
7195         write_unlock(&em_tree->lock);
7196 out:
7197 
7198         trace_btrfs_get_extent(root, inode, em);
7199 
7200         btrfs_free_path(path);
7201         if (trans) {
7202                 ret = btrfs_end_transaction(trans);
7203                 if (!err)
7204                         err = ret;
7205         }
7206         if (err) {
7207                 free_extent_map(em);
7208                 return ERR_PTR(err);
7209         }
7210         BUG_ON(!em); /* Error is always set */
7211         return em;
7212 }
7213 
7214 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7215                 struct page *page,
7216                 size_t pg_offset, u64 start, u64 len,
7217                 int create)
7218 {
7219         struct extent_map *em;
7220         struct extent_map *hole_em = NULL;
7221         u64 range_start = start;
7222         u64 end;
7223         u64 found;
7224         u64 found_end;
7225         int err = 0;
7226 
7227         em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7228         if (IS_ERR(em))
7229                 return em;
7230         /*
7231          * If our em maps to:
7232          * - a hole or
7233          * - a pre-alloc extent,
7234          * there might actually be delalloc bytes behind it.
7235          */
7236         if (em->block_start != EXTENT_MAP_HOLE &&
7237             !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7238                 return em;
7239         else
7240                 hole_em = em;
7241 
7242         /* check to see if we've wrapped (len == -1 or similar) */
7243         end = start + len;
7244         if (end < start)
7245                 end = (u64)-1;
7246         else
7247                 end -= 1;
7248 
7249         em = NULL;
7250 
7251         /* ok, we didn't find anything, lets look for delalloc */
7252         found = count_range_bits(&inode->io_tree, &range_start,
7253                                  end, len, EXTENT_DELALLOC, 1);
7254         found_end = range_start + found;
7255         if (found_end < range_start)
7256                 found_end = (u64)-1;
7257 
7258         /*
7259          * we didn't find anything useful, return
7260          * the original results from get_extent()
7261          */
7262         if (range_start > end || found_end <= start) {
7263                 em = hole_em;
7264                 hole_em = NULL;
7265                 goto out;
7266         }
7267 
7268         /* adjust the range_start to make sure it doesn't
7269          * go backwards from the start they passed in
7270          */
7271         range_start = max(start, range_start);
7272         found = found_end - range_start;
7273 
7274         if (found > 0) {
7275                 u64 hole_start = start;
7276                 u64 hole_len = len;
7277 
7278                 em = alloc_extent_map();
7279                 if (!em) {
7280                         err = -ENOMEM;
7281                         goto out;
7282                 }
7283                 /*
7284                  * when btrfs_get_extent can't find anything it
7285                  * returns one huge hole
7286                  *
7287                  * make sure what it found really fits our range, and
7288                  * adjust to make sure it is based on the start from
7289                  * the caller
7290                  */
7291                 if (hole_em) {
7292                         u64 calc_end = extent_map_end(hole_em);
7293 
7294                         if (calc_end <= start || (hole_em->start > end)) {
7295                                 free_extent_map(hole_em);
7296                                 hole_em = NULL;
7297                         } else {
7298                                 hole_start = max(hole_em->start, start);
7299                                 hole_len = calc_end - hole_start;
7300                         }
7301                 }
7302                 em->bdev = NULL;
7303                 if (hole_em && range_start > hole_start) {
7304                         /* our hole starts before our delalloc, so we
7305                          * have to return just the parts of the hole
7306                          * that go until  the delalloc starts
7307                          */
7308                         em->len = min(hole_len,
7309                                       range_start - hole_start);
7310                         em->start = hole_start;
7311                         em->orig_start = hole_start;
7312                         /*
7313                          * don't adjust block start at all,
7314                          * it is fixed at EXTENT_MAP_HOLE
7315                          */
7316                         em->block_start = hole_em->block_start;
7317                         em->block_len = hole_len;
7318                         if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7319                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7320                 } else {
7321                         em->start = range_start;
7322                         em->len = found;
7323                         em->orig_start = range_start;
7324                         em->block_start = EXTENT_MAP_DELALLOC;
7325                         em->block_len = found;
7326                 }
7327         } else if (hole_em) {
7328                 return hole_em;
7329         }
7330 out:
7331 
7332         free_extent_map(hole_em);
7333         if (err) {
7334                 free_extent_map(em);
7335                 return ERR_PTR(err);
7336         }
7337         return em;
7338 }
7339 
7340 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7341                                                   const u64 start,
7342                                                   const u64 len,
7343                                                   const u64 orig_start,
7344                                                   const u64 block_start,
7345                                                   const u64 block_len,
7346                                                   const u64 orig_block_len,
7347                                                   const u64 ram_bytes,
7348                                                   const int type)
7349 {
7350         struct extent_map *em = NULL;
7351         int ret;
7352 
7353         if (type != BTRFS_ORDERED_NOCOW) {
7354                 em = create_io_em(inode, start, len, orig_start,
7355                                   block_start, block_len, orig_block_len,
7356                                   ram_bytes,
7357                                   BTRFS_COMPRESS_NONE, /* compress_type */
7358                                   type);
7359                 if (IS_ERR(em))
7360                         goto out;
7361         }
7362         ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7363                                            len, block_len, type);
7364         if (ret) {
7365                 if (em) {
7366                         free_extent_map(em);
7367                         btrfs_drop_extent_cache(BTRFS_I(inode), start,
7368                                                 start + len - 1, 0);
7369                 }
7370                 em = ERR_PTR(ret);
7371         }
7372  out:
7373 
7374         return em;
7375 }
7376 
7377 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7378                                                   u64 start, u64 len)
7379 {
7380         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7381         struct btrfs_root *root = BTRFS_I(inode)->root;
7382         struct extent_map *em;
7383         struct btrfs_key ins;
7384         u64 alloc_hint;
7385         int ret;
7386 
7387         alloc_hint = get_extent_allocation_hint(inode, start, len);
7388         ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7389                                    0, alloc_hint, &ins, 1, 1);
7390         if (ret)
7391                 return ERR_PTR(ret);
7392 
7393         em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7394                                      ins.objectid, ins.offset, ins.offset,
7395                                      ins.offset, BTRFS_ORDERED_REGULAR);
7396         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7397         if (IS_ERR(em))
7398                 btrfs_free_reserved_extent(fs_info, ins.objectid,
7399                                            ins.offset, 1);
7400 
7401         return em;
7402 }
7403 
7404 /*
7405  * returns 1 when the nocow is safe, < 1 on error, 0 if the
7406  * block must be cow'd
7407  */
7408 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7409                               u64 *orig_start, u64 *orig_block_len,
7410                               u64 *ram_bytes)
7411 {
7412         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7413         struct btrfs_path *path;
7414         int ret;
7415         struct extent_buffer *leaf;
7416         struct btrfs_root *root = BTRFS_I(inode)->root;
7417         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7418         struct btrfs_file_extent_item *fi;
7419         struct btrfs_key key;
7420         u64 disk_bytenr;
7421         u64 backref_offset;
7422         u64 extent_end;
7423         u64 num_bytes;
7424         int slot;
7425         int found_type;
7426         bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7427 
7428         path = btrfs_alloc_path();
7429         if (!path)
7430                 return -ENOMEM;
7431 
7432         ret = btrfs_lookup_file_extent(NULL, root, path,
7433                         btrfs_ino(BTRFS_I(inode)), offset, 0);
7434         if (ret < 0)
7435                 goto out;
7436 
7437         slot = path->slots[0];
7438         if (ret == 1) {
7439                 if (slot == 0) {
7440                         /* can't find the item, must cow */
7441                         ret = 0;
7442                         goto out;
7443                 }
7444                 slot--;
7445         }
7446         ret = 0;
7447         leaf = path->nodes[0];
7448         btrfs_item_key_to_cpu(leaf, &key, slot);
7449         if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7450             key.type != BTRFS_EXTENT_DATA_KEY) {
7451                 /* not our file or wrong item type, must cow */
7452                 goto out;
7453         }
7454 
7455         if (key.offset > offset) {
7456                 /* Wrong offset, must cow */
7457                 goto out;
7458         }
7459 
7460         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7461         found_type = btrfs_file_extent_type(leaf, fi);
7462         if (found_type != BTRFS_FILE_EXTENT_REG &&
7463             found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7464                 /* not a regular extent, must cow */
7465                 goto out;