btrfs: drop btrfs_device::can_discard to query directly
[linux-block.git] / fs / btrfs / inode.c
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                                                   WB_SYNC_ALL);
773                         else if (ret)
774                                 unlock_page(async_cow->locked_page);
775                         kfree(async_extent);
776                         cond_resched();
777                         continue;
778                 }
779
780                 lock_extent(io_tree, async_extent->start,
781                             async_extent->start + async_extent->ram_size - 1);
782
783                 ret = btrfs_reserve_extent(root, async_extent->ram_size,
784                                            async_extent->compressed_size,
785                                            async_extent->compressed_size,
786                                            0, alloc_hint, &ins, 1, 1);
787                 if (ret) {
788                         free_async_extent_pages(async_extent);
789
790                         if (ret == -ENOSPC) {
791                                 unlock_extent(io_tree, async_extent->start,
792                                               async_extent->start +
793                                               async_extent->ram_size - 1);
794
795                                 /*
796                                  * we need to redirty the pages if we decide to
797                                  * fallback to uncompressed IO, otherwise we
798                                  * will not submit these pages down to lower
799                                  * layers.
800                                  */
801                                 extent_range_redirty_for_io(inode,
802                                                 async_extent->start,
803                                                 async_extent->start +
804                                                 async_extent->ram_size - 1);
805
806                                 goto retry;
807                         }
808                         goto out_free;
809                 }
810                 /*
811                  * here we're doing allocation and writeback of the
812                  * compressed pages
813                  */
814                 em = create_io_em(inode, async_extent->start,
815                                   async_extent->ram_size, /* len */
816                                   async_extent->start, /* orig_start */
817                                   ins.objectid, /* block_start */
818                                   ins.offset, /* block_len */
819                                   ins.offset, /* orig_block_len */
820                                   async_extent->ram_size, /* ram_bytes */
821                                   async_extent->compress_type,
822                                   BTRFS_ORDERED_COMPRESSED);
823                 if (IS_ERR(em))
824                         /* ret value is not necessary due to void function */
825                         goto out_free_reserve;
826                 free_extent_map(em);
827
828                 ret = btrfs_add_ordered_extent_compress(inode,
829                                                 async_extent->start,
830                                                 ins.objectid,
831                                                 async_extent->ram_size,
832                                                 ins.offset,
833                                                 BTRFS_ORDERED_COMPRESSED,
834                                                 async_extent->compress_type);
835                 if (ret) {
836                         btrfs_drop_extent_cache(BTRFS_I(inode),
837                                                 async_extent->start,
838                                                 async_extent->start +
839                                                 async_extent->ram_size - 1, 0);
840                         goto out_free_reserve;
841                 }
842                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
843
844                 /*
845                  * clear dirty, set writeback and unlock the pages.
846                  */
847                 extent_clear_unlock_delalloc(inode, async_extent->start,
848                                 async_extent->start +
849                                 async_extent->ram_size - 1,
850                                 async_extent->start +
851                                 async_extent->ram_size - 1,
852                                 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
853                                 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
854                                 PAGE_SET_WRITEBACK);
855                 if (btrfs_submit_compressed_write(inode,
856                                     async_extent->start,
857                                     async_extent->ram_size,
858                                     ins.objectid,
859                                     ins.offset, async_extent->pages,
860                                     async_extent->nr_pages,
861                                     async_cow->write_flags)) {
862                         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
863                         struct page *p = async_extent->pages[0];
864                         const u64 start = async_extent->start;
865                         const u64 end = start + async_extent->ram_size - 1;
866
867                         p->mapping = inode->i_mapping;
868                         tree->ops->writepage_end_io_hook(p, start, end,
869                                                          NULL, 0);
870                         p->mapping = NULL;
871                         extent_clear_unlock_delalloc(inode, start, end, end,
872                                                      NULL, 0,
873                                                      PAGE_END_WRITEBACK |
874                                                      PAGE_SET_ERROR);
875                         free_async_extent_pages(async_extent);
876                 }
877                 alloc_hint = ins.objectid + ins.offset;
878                 kfree(async_extent);
879                 cond_resched();
880         }
881         return;
882 out_free_reserve:
883         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
884         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
885 out_free:
886         extent_clear_unlock_delalloc(inode, async_extent->start,
887                                      async_extent->start +
888                                      async_extent->ram_size - 1,
889                                      async_extent->start +
890                                      async_extent->ram_size - 1,
891                                      NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
892                                      EXTENT_DELALLOC_NEW |
893                                      EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
894                                      PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
895                                      PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
896                                      PAGE_SET_ERROR);
897         free_async_extent_pages(async_extent);
898         kfree(async_extent);
899         goto again;
900 }
901
902 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
903                                       u64 num_bytes)
904 {
905         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
906         struct extent_map *em;
907         u64 alloc_hint = 0;
908
909         read_lock(&em_tree->lock);
910         em = search_extent_mapping(em_tree, start, num_bytes);
911         if (em) {
912                 /*
913                  * if block start isn't an actual block number then find the
914                  * first block in this inode and use that as a hint.  If that
915                  * block is also bogus then just don't worry about it.
916                  */
917                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
918                         free_extent_map(em);
919                         em = search_extent_mapping(em_tree, 0, 0);
920                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
921                                 alloc_hint = em->block_start;
922                         if (em)
923                                 free_extent_map(em);
924                 } else {
925                         alloc_hint = em->block_start;
926                         free_extent_map(em);
927                 }
928         }
929         read_unlock(&em_tree->lock);
930
931         return alloc_hint;
932 }
933
934 /*
935  * when extent_io.c finds a delayed allocation range in the file,
936  * the call backs end up in this code.  The basic idea is to
937  * allocate extents on disk for the range, and create ordered data structs
938  * in ram to track those extents.
939  *
940  * locked_page is the page that writepage had locked already.  We use
941  * it to make sure we don't do extra locks or unlocks.
942  *
943  * *page_started is set to one if we unlock locked_page and do everything
944  * required to start IO on it.  It may be clean and already done with
945  * IO when we return.
946  */
947 static noinline int cow_file_range(struct inode *inode,
948                                    struct page *locked_page,
949                                    u64 start, u64 end, u64 delalloc_end,
950                                    int *page_started, unsigned long *nr_written,
951                                    int unlock, struct btrfs_dedupe_hash *hash)
952 {
953         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
954         struct btrfs_root *root = BTRFS_I(inode)->root;
955         u64 alloc_hint = 0;
956         u64 num_bytes;
957         unsigned long ram_size;
958         u64 disk_num_bytes;
959         u64 cur_alloc_size = 0;
960         u64 blocksize = fs_info->sectorsize;
961         struct btrfs_key ins;
962         struct extent_map *em;
963         unsigned clear_bits;
964         unsigned long page_ops;
965         bool extent_reserved = false;
966         int ret = 0;
967
968         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
969                 WARN_ON_ONCE(1);
970                 ret = -EINVAL;
971                 goto out_unlock;
972         }
973
974         num_bytes = ALIGN(end - start + 1, blocksize);
975         num_bytes = max(blocksize,  num_bytes);
976         disk_num_bytes = num_bytes;
977
978         inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
979
980         if (start == 0) {
981                 /* lets try to make an inline extent */
982                 ret = cow_file_range_inline(root, inode, start, end, 0,
983                                         BTRFS_COMPRESS_NONE, NULL);
984                 if (ret == 0) {
985                         /*
986                          * We use DO_ACCOUNTING here because we need the
987                          * delalloc_release_metadata to be run _after_ we drop
988                          * our outstanding extent for clearing delalloc for this
989                          * range.
990                          */
991                         extent_clear_unlock_delalloc(inode, start, end,
992                                      delalloc_end, NULL,
993                                      EXTENT_LOCKED | EXTENT_DELALLOC |
994                                      EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
995                                      EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
996                                      PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
997                                      PAGE_END_WRITEBACK);
998                         *nr_written = *nr_written +
999                              (end - start + PAGE_SIZE) / PAGE_SIZE;
1000                         *page_started = 1;
1001                         goto out;
1002                 } else if (ret < 0) {
1003                         goto out_unlock;
1004                 }
1005         }
1006
1007         BUG_ON(disk_num_bytes >
1008                btrfs_super_total_bytes(fs_info->super_copy));
1009
1010         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1011         btrfs_drop_extent_cache(BTRFS_I(inode), start,
1012                         start + num_bytes - 1, 0);
1013
1014         while (disk_num_bytes > 0) {
1015                 cur_alloc_size = disk_num_bytes;
1016                 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1017                                            fs_info->sectorsize, 0, alloc_hint,
1018                                            &ins, 1, 1);
1019                 if (ret < 0)
1020                         goto out_unlock;
1021                 cur_alloc_size = ins.offset;
1022                 extent_reserved = true;
1023
1024                 ram_size = ins.offset;
1025                 em = create_io_em(inode, start, ins.offset, /* len */
1026                                   start, /* orig_start */
1027                                   ins.objectid, /* block_start */
1028                                   ins.offset, /* block_len */
1029                                   ins.offset, /* orig_block_len */
1030                                   ram_size, /* ram_bytes */
1031                                   BTRFS_COMPRESS_NONE, /* compress_type */
1032                                   BTRFS_ORDERED_REGULAR /* type */);
1033                 if (IS_ERR(em))
1034                         goto out_reserve;
1035                 free_extent_map(em);
1036
1037                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1038                                                ram_size, cur_alloc_size, 0);
1039                 if (ret)
1040                         goto out_drop_extent_cache;
1041
1042                 if (root->root_key.objectid ==
1043                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1044                         ret = btrfs_reloc_clone_csums(inode, start,
1045                                                       cur_alloc_size);
1046                         /*
1047                          * Only drop cache here, and process as normal.
1048                          *
1049                          * We must not allow extent_clear_unlock_delalloc()
1050                          * at out_unlock label to free meta of this ordered
1051                          * extent, as its meta should be freed by
1052                          * btrfs_finish_ordered_io().
1053                          *
1054                          * So we must continue until @start is increased to
1055                          * skip current ordered extent.
1056                          */
1057                         if (ret)
1058                                 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1059                                                 start + ram_size - 1, 0);
1060                 }
1061
1062                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1063
1064                 /* we're not doing compressed IO, don't unlock the first
1065                  * page (which the caller expects to stay locked), don't
1066                  * clear any dirty bits and don't set any writeback bits
1067                  *
1068                  * Do set the Private2 bit so we know this page was properly
1069                  * setup for writepage
1070                  */
1071                 page_ops = unlock ? PAGE_UNLOCK : 0;
1072                 page_ops |= PAGE_SET_PRIVATE2;
1073
1074                 extent_clear_unlock_delalloc(inode, start,
1075                                              start + ram_size - 1,
1076                                              delalloc_end, locked_page,
1077                                              EXTENT_LOCKED | EXTENT_DELALLOC,
1078                                              page_ops);
1079                 if (disk_num_bytes < cur_alloc_size)
1080                         disk_num_bytes = 0;
1081                 else
1082                         disk_num_bytes -= cur_alloc_size;
1083                 num_bytes -= cur_alloc_size;
1084                 alloc_hint = ins.objectid + ins.offset;
1085                 start += cur_alloc_size;
1086                 extent_reserved = false;
1087
1088                 /*
1089                  * btrfs_reloc_clone_csums() error, since start is increased
1090                  * extent_clear_unlock_delalloc() at out_unlock label won't
1091                  * free metadata of current ordered extent, we're OK to exit.
1092                  */
1093                 if (ret)
1094                         goto out_unlock;
1095         }
1096 out:
1097         return ret;
1098
1099 out_drop_extent_cache:
1100         btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1101 out_reserve:
1102         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1103         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1104 out_unlock:
1105         clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1106                 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1107         page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1108                 PAGE_END_WRITEBACK;
1109         /*
1110          * If we reserved an extent for our delalloc range (or a subrange) and
1111          * failed to create the respective ordered extent, then it means that
1112          * when we reserved the extent we decremented the extent's size from
1113          * the data space_info's bytes_may_use counter and incremented the
1114          * space_info's bytes_reserved counter by the same amount. We must make
1115          * sure extent_clear_unlock_delalloc() does not try to decrement again
1116          * the data space_info's bytes_may_use counter, therefore we do not pass
1117          * it the flag EXTENT_CLEAR_DATA_RESV.
1118          */
1119         if (extent_reserved) {
1120                 extent_clear_unlock_delalloc(inode, start,
1121                                              start + cur_alloc_size,
1122                                              start + cur_alloc_size,
1123                                              locked_page,
1124                                              clear_bits,
1125                                              page_ops);
1126                 start += cur_alloc_size;
1127                 if (start >= end)
1128                         goto out;
1129         }
1130         extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1131                                      locked_page,
1132                                      clear_bits | EXTENT_CLEAR_DATA_RESV,
1133                                      page_ops);
1134         goto out;
1135 }
1136
1137 /*
1138  * work queue call back to started compression on a file and pages
1139  */
1140 static noinline void async_cow_start(struct btrfs_work *work)
1141 {
1142         struct async_cow *async_cow;
1143         int num_added = 0;
1144         async_cow = container_of(work, struct async_cow, work);
1145
1146         compress_file_range(async_cow->inode, async_cow->locked_page,
1147                             async_cow->start, async_cow->end, async_cow,
1148                             &num_added);
1149         if (num_added == 0) {
1150                 btrfs_add_delayed_iput(async_cow->inode);
1151                 async_cow->inode = NULL;
1152         }
1153 }
1154
1155 /*
1156  * work queue call back to submit previously compressed pages
1157  */
1158 static noinline void async_cow_submit(struct btrfs_work *work)
1159 {
1160         struct btrfs_fs_info *fs_info;
1161         struct async_cow *async_cow;
1162         struct btrfs_root *root;
1163         unsigned long nr_pages;
1164
1165         async_cow = container_of(work, struct async_cow, work);
1166
1167         root = async_cow->root;
1168         fs_info = root->fs_info;
1169         nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1170                 PAGE_SHIFT;
1171
1172         /*
1173          * atomic_sub_return implies a barrier for waitqueue_active
1174          */
1175         if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1176             5 * SZ_1M &&
1177             waitqueue_active(&fs_info->async_submit_wait))
1178                 wake_up(&fs_info->async_submit_wait);
1179
1180         if (async_cow->inode)
1181                 submit_compressed_extents(async_cow->inode, async_cow);
1182 }
1183
1184 static noinline void async_cow_free(struct btrfs_work *work)
1185 {
1186         struct async_cow *async_cow;
1187         async_cow = container_of(work, struct async_cow, work);
1188         if (async_cow->inode)
1189                 btrfs_add_delayed_iput(async_cow->inode);
1190         kfree(async_cow);
1191 }
1192
1193 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1194                                 u64 start, u64 end, int *page_started,
1195                                 unsigned long *nr_written,
1196                                 unsigned int write_flags)
1197 {
1198         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1199         struct async_cow *async_cow;
1200         struct btrfs_root *root = BTRFS_I(inode)->root;
1201         unsigned long nr_pages;
1202         u64 cur_end;
1203
1204         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1205                          1, 0, NULL);
1206         while (start < end) {
1207                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1208                 BUG_ON(!async_cow); /* -ENOMEM */
1209                 async_cow->inode = igrab(inode);
1210                 async_cow->root = root;
1211                 async_cow->locked_page = locked_page;
1212                 async_cow->start = start;
1213                 async_cow->write_flags = write_flags;
1214
1215                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1216                     !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1217                         cur_end = end;
1218                 else
1219                         cur_end = min(end, start + SZ_512K - 1);
1220
1221                 async_cow->end = cur_end;
1222                 INIT_LIST_HEAD(&async_cow->extents);
1223
1224                 btrfs_init_work(&async_cow->work,
1225                                 btrfs_delalloc_helper,
1226                                 async_cow_start, async_cow_submit,
1227                                 async_cow_free);
1228
1229                 nr_pages = (cur_end - start + PAGE_SIZE) >>
1230                         PAGE_SHIFT;
1231                 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1232
1233                 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1234
1235                 *nr_written += nr_pages;
1236                 start = cur_end + 1;
1237         }
1238         *page_started = 1;
1239         return 0;
1240 }
1241
1242 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1243                                         u64 bytenr, u64 num_bytes)
1244 {
1245         int ret;
1246         struct btrfs_ordered_sum *sums;
1247         LIST_HEAD(list);
1248
1249         ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1250                                        bytenr + num_bytes - 1, &list, 0);
1251         if (ret == 0 && list_empty(&list))
1252                 return 0;
1253
1254         while (!list_empty(&list)) {
1255                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1256                 list_del(&sums->list);
1257                 kfree(sums);
1258         }
1259         return 1;
1260 }
1261
1262 /*
1263  * when nowcow writeback call back.  This checks for snapshots or COW copies
1264  * of the extents that exist in the file, and COWs the file as required.
1265  *
1266  * If no cow copies or snapshots exist, we write directly to the existing
1267  * blocks on disk
1268  */
1269 static noinline int run_delalloc_nocow(struct inode *inode,
1270                                        struct page *locked_page,
1271                               u64 start, u64 end, int *page_started, int force,
1272                               unsigned long *nr_written)
1273 {
1274         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1275         struct btrfs_root *root = BTRFS_I(inode)->root;
1276         struct extent_buffer *leaf;
1277         struct btrfs_path *path;
1278         struct btrfs_file_extent_item *fi;
1279         struct btrfs_key found_key;
1280         struct extent_map *em;
1281         u64 cow_start;
1282         u64 cur_offset;
1283         u64 extent_end;
1284         u64 extent_offset;
1285         u64 disk_bytenr;
1286         u64 num_bytes;
1287         u64 disk_num_bytes;
1288         u64 ram_bytes;
1289         int extent_type;
1290         int ret, err;
1291         int type;
1292         int nocow;
1293         int check_prev = 1;
1294         bool nolock;
1295         u64 ino = btrfs_ino(BTRFS_I(inode));
1296
1297         path = btrfs_alloc_path();
1298         if (!path) {
1299                 extent_clear_unlock_delalloc(inode, start, end, end,
1300                                              locked_page,
1301                                              EXTENT_LOCKED | EXTENT_DELALLOC |
1302                                              EXTENT_DO_ACCOUNTING |
1303                                              EXTENT_DEFRAG, PAGE_UNLOCK |
1304                                              PAGE_CLEAR_DIRTY |
1305                                              PAGE_SET_WRITEBACK |
1306                                              PAGE_END_WRITEBACK);
1307                 return -ENOMEM;
1308         }
1309
1310         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1311
1312         cow_start = (u64)-1;
1313         cur_offset = start;
1314         while (1) {
1315                 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1316                                                cur_offset, 0);
1317                 if (ret < 0)
1318                         goto error;
1319                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1320                         leaf = path->nodes[0];
1321                         btrfs_item_key_to_cpu(leaf, &found_key,
1322                                               path->slots[0] - 1);
1323                         if (found_key.objectid == ino &&
1324                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1325                                 path->slots[0]--;
1326                 }
1327                 check_prev = 0;
1328 next_slot:
1329                 leaf = path->nodes[0];
1330                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1331                         ret = btrfs_next_leaf(root, path);
1332                         if (ret < 0)
1333                                 goto error;
1334                         if (ret > 0)
1335                                 break;
1336                         leaf = path->nodes[0];
1337                 }
1338
1339                 nocow = 0;
1340                 disk_bytenr = 0;
1341                 num_bytes = 0;
1342                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1343
1344                 if (found_key.objectid > ino)
1345                         break;
1346                 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1347                     found_key.type < BTRFS_EXTENT_DATA_KEY) {
1348                         path->slots[0]++;
1349                         goto next_slot;
1350                 }
1351                 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1352                     found_key.offset > end)
1353                         break;
1354
1355                 if (found_key.offset > cur_offset) {
1356                         extent_end = found_key.offset;
1357                         extent_type = 0;
1358                         goto out_check;
1359                 }
1360
1361                 fi = btrfs_item_ptr(leaf, path->slots[0],
1362                                     struct btrfs_file_extent_item);
1363                 extent_type = btrfs_file_extent_type(leaf, fi);
1364
1365                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1366                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1367                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1368                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1369                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1370                         extent_end = found_key.offset +
1371                                 btrfs_file_extent_num_bytes(leaf, fi);
1372                         disk_num_bytes =
1373                                 btrfs_file_extent_disk_num_bytes(leaf, fi);
1374                         if (extent_end <= start) {
1375                                 path->slots[0]++;
1376                                 goto next_slot;
1377                         }
1378                         if (disk_bytenr == 0)
1379                                 goto out_check;
1380                         if (btrfs_file_extent_compression(leaf, fi) ||
1381                             btrfs_file_extent_encryption(leaf, fi) ||
1382                             btrfs_file_extent_other_encoding(leaf, fi))
1383                                 goto out_check;
1384                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1385                                 goto out_check;
1386                         if (btrfs_extent_readonly(fs_info, disk_bytenr))
1387                                 goto out_check;
1388                         if (btrfs_cross_ref_exist(root, ino,
1389                                                   found_key.offset -
1390                                                   extent_offset, disk_bytenr))
1391                                 goto out_check;
1392                         disk_bytenr += extent_offset;
1393                         disk_bytenr += cur_offset - found_key.offset;
1394                         num_bytes = min(end + 1, extent_end) - cur_offset;
1395                         /*
1396                          * if there are pending snapshots for this root,
1397                          * we fall into common COW way.
1398                          */
1399                         if (!nolock) {
1400                                 err = btrfs_start_write_no_snapshotting(root);
1401                                 if (!err)
1402                                         goto out_check;
1403                         }
1404                         /*
1405                          * force cow if csum exists in the range.
1406                          * this ensure that csum for a given extent are
1407                          * either valid or do not exist.
1408                          */
1409                         if (csum_exist_in_range(fs_info, disk_bytenr,
1410                                                 num_bytes)) {
1411                                 if (!nolock)
1412                                         btrfs_end_write_no_snapshotting(root);
1413                                 goto out_check;
1414                         }
1415                         if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1416                                 if (!nolock)
1417                                         btrfs_end_write_no_snapshotting(root);
1418                                 goto out_check;
1419                         }
1420                         nocow = 1;
1421                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1422                         extent_end = found_key.offset +
1423                                 btrfs_file_extent_inline_len(leaf,
1424                                                      path->slots[0], fi);
1425                         extent_end = ALIGN(extent_end,
1426                                            fs_info->sectorsize);
1427                 } else {
1428                         BUG_ON(1);
1429                 }
1430 out_check:
1431                 if (extent_end <= start) {
1432                         path->slots[0]++;
1433                         if (!nolock && nocow)
1434                                 btrfs_end_write_no_snapshotting(root);
1435                         if (nocow)
1436                                 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1437                         goto next_slot;
1438                 }
1439                 if (!nocow) {
1440                         if (cow_start == (u64)-1)
1441                                 cow_start = cur_offset;
1442                         cur_offset = extent_end;
1443                         if (cur_offset > end)
1444                                 break;
1445                         path->slots[0]++;
1446                         goto next_slot;
1447                 }
1448
1449                 btrfs_release_path(path);
1450                 if (cow_start != (u64)-1) {
1451                         ret = cow_file_range(inode, locked_page,
1452                                              cow_start, found_key.offset - 1,
1453                                              end, page_started, nr_written, 1,
1454                                              NULL);
1455                         if (ret) {
1456                                 if (!nolock && nocow)
1457                                         btrfs_end_write_no_snapshotting(root);
1458                                 if (nocow)
1459                                         btrfs_dec_nocow_writers(fs_info,
1460                                                                 disk_bytenr);
1461                                 goto error;
1462                         }
1463                         cow_start = (u64)-1;
1464                 }
1465
1466                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1467                         u64 orig_start = found_key.offset - extent_offset;
1468
1469                         em = create_io_em(inode, cur_offset, num_bytes,
1470                                           orig_start,
1471                                           disk_bytenr, /* block_start */
1472                                           num_bytes, /* block_len */
1473                                           disk_num_bytes, /* orig_block_len */
1474                                           ram_bytes, BTRFS_COMPRESS_NONE,
1475                                           BTRFS_ORDERED_PREALLOC);
1476                         if (IS_ERR(em)) {
1477                                 if (!nolock && nocow)
1478                                         btrfs_end_write_no_snapshotting(root);
1479                                 if (nocow)
1480                                         btrfs_dec_nocow_writers(fs_info,
1481                                                                 disk_bytenr);
1482                                 ret = PTR_ERR(em);
1483                                 goto error;
1484                         }
1485                         free_extent_map(em);
1486                 }
1487
1488                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1489                         type = BTRFS_ORDERED_PREALLOC;
1490                 } else {
1491                         type = BTRFS_ORDERED_NOCOW;
1492                 }
1493
1494                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1495                                                num_bytes, num_bytes, type);
1496                 if (nocow)
1497                         btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1498                 BUG_ON(ret); /* -ENOMEM */
1499
1500                 if (root->root_key.objectid ==
1501                     BTRFS_DATA_RELOC_TREE_OBJECTID)
1502                         /*
1503                          * Error handled later, as we must prevent
1504                          * extent_clear_unlock_delalloc() in error handler
1505                          * from freeing metadata of created ordered extent.
1506                          */
1507                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1508                                                       num_bytes);
1509
1510                 extent_clear_unlock_delalloc(inode, cur_offset,
1511                                              cur_offset + num_bytes - 1, end,
1512                                              locked_page, EXTENT_LOCKED |
1513                                              EXTENT_DELALLOC |
1514                                              EXTENT_CLEAR_DATA_RESV,
1515                                              PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1516
1517                 if (!nolock && nocow)
1518                         btrfs_end_write_no_snapshotting(root);
1519                 cur_offset = extent_end;
1520
1521                 /*
1522                  * btrfs_reloc_clone_csums() error, now we're OK to call error
1523                  * handler, as metadata for created ordered extent will only
1524                  * be freed by btrfs_finish_ordered_io().
1525                  */
1526                 if (ret)
1527                         goto error;
1528                 if (cur_offset > end)
1529                         break;
1530         }
1531         btrfs_release_path(path);
1532
1533         if (cur_offset <= end && cow_start == (u64)-1) {
1534                 cow_start = cur_offset;
1535                 cur_offset = end;
1536         }
1537
1538         if (cow_start != (u64)-1) {
1539                 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1540                                      page_started, nr_written, 1, NULL);
1541                 if (ret)
1542                         goto error;
1543         }
1544
1545 error:
1546         if (ret && cur_offset < end)
1547                 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1548                                              locked_page, EXTENT_LOCKED |
1549                                              EXTENT_DELALLOC | EXTENT_DEFRAG |
1550                                              EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1551                                              PAGE_CLEAR_DIRTY |
1552                                              PAGE_SET_WRITEBACK |
1553                                              PAGE_END_WRITEBACK);
1554         btrfs_free_path(path);
1555         return ret;
1556 }
1557
1558 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1559 {
1560
1561         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1562             !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1563                 return 0;
1564
1565         /*
1566          * @defrag_bytes is a hint value, no spinlock held here,
1567          * if is not zero, it means the file is defragging.
1568          * Force cow if given extent needs to be defragged.
1569          */
1570         if (BTRFS_I(inode)->defrag_bytes &&
1571             test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1572                            EXTENT_DEFRAG, 0, NULL))
1573                 return 1;
1574
1575         return 0;
1576 }
1577
1578 /*
1579  * extent_io.c call back to do delayed allocation processing
1580  */
1581 static int run_delalloc_range(void *private_data, struct page *locked_page,
1582                               u64 start, u64 end, int *page_started,
1583                               unsigned long *nr_written,
1584                               struct writeback_control *wbc)
1585 {
1586         struct inode *inode = private_data;
1587         int ret;
1588         int force_cow = need_force_cow(inode, start, end);
1589         unsigned int write_flags = wbc_to_write_flags(wbc);
1590
1591         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1592                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1593                                          page_started, 1, nr_written);
1594         } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1595                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1596                                          page_started, 0, nr_written);
1597         } else if (!inode_need_compress(inode, start, end)) {
1598                 ret = cow_file_range(inode, locked_page, start, end, end,
1599                                       page_started, nr_written, 1, NULL);
1600         } else {
1601                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1602                         &BTRFS_I(inode)->runtime_flags);
1603                 ret = cow_file_range_async(inode, locked_page, start, end,
1604                                            page_started, nr_written,
1605                                            write_flags);
1606         }
1607         if (ret)
1608                 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1609         return ret;
1610 }
1611
1612 static void btrfs_split_extent_hook(void *private_data,
1613                                     struct extent_state *orig, u64 split)
1614 {
1615         struct inode *inode = private_data;
1616         u64 size;
1617
1618         /* not delalloc, ignore it */
1619         if (!(orig->state & EXTENT_DELALLOC))
1620                 return;
1621
1622         size = orig->end - orig->start + 1;
1623         if (size > BTRFS_MAX_EXTENT_SIZE) {
1624                 u32 num_extents;
1625                 u64 new_size;
1626
1627                 /*
1628                  * See the explanation in btrfs_merge_extent_hook, the same
1629                  * applies here, just in reverse.
1630                  */
1631                 new_size = orig->end - split + 1;
1632                 num_extents = count_max_extents(new_size);
1633                 new_size = split - orig->start;
1634                 num_extents += count_max_extents(new_size);
1635                 if (count_max_extents(size) >= num_extents)
1636                         return;
1637         }
1638
1639         spin_lock(&BTRFS_I(inode)->lock);
1640         btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1641         spin_unlock(&BTRFS_I(inode)->lock);
1642 }
1643
1644 /*
1645  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1646  * extents so we can keep track of new extents that are just merged onto old
1647  * extents, such as when we are doing sequential writes, so we can properly
1648  * account for the metadata space we'll need.
1649  */
1650 static void btrfs_merge_extent_hook(void *private_data,
1651                                     struct extent_state *new,
1652                                     struct extent_state *other)
1653 {
1654         struct inode *inode = private_data;
1655         u64 new_size, old_size;
1656         u32 num_extents;
1657
1658         /* not delalloc, ignore it */
1659         if (!(other->state & EXTENT_DELALLOC))
1660                 return;
1661
1662         if (new->start > other->start)
1663                 new_size = new->end - other->start + 1;
1664         else
1665                 new_size = other->end - new->start + 1;
1666
1667         /* we're not bigger than the max, unreserve the space and go */
1668         if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1669                 spin_lock(&BTRFS_I(inode)->lock);
1670                 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1671                 spin_unlock(&BTRFS_I(inode)->lock);
1672                 return;
1673         }
1674
1675         /*
1676          * We have to add up either side to figure out how many extents were
1677          * accounted for before we merged into one big extent.  If the number of
1678          * extents we accounted for is <= the amount we need for the new range
1679          * then we can return, otherwise drop.  Think of it like this
1680          *
1681          * [ 4k][MAX_SIZE]
1682          *
1683          * So we've grown the extent by a MAX_SIZE extent, this would mean we
1684          * need 2 outstanding extents, on one side we have 1 and the other side
1685          * we have 1 so they are == and we can return.  But in this case
1686          *
1687          * [MAX_SIZE+4k][MAX_SIZE+4k]
1688          *
1689          * Each range on their own accounts for 2 extents, but merged together
1690          * they are only 3 extents worth of accounting, so we need to drop in
1691          * this case.
1692          */
1693         old_size = other->end - other->start + 1;
1694         num_extents = count_max_extents(old_size);
1695         old_size = new->end - new->start + 1;
1696         num_extents += count_max_extents(old_size);
1697         if (count_max_extents(new_size) >= num_extents)
1698                 return;
1699
1700         spin_lock(&BTRFS_I(inode)->lock);
1701         btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1702         spin_unlock(&BTRFS_I(inode)->lock);
1703 }
1704
1705 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1706                                       struct inode *inode)
1707 {
1708         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1709
1710         spin_lock(&root->delalloc_lock);
1711         if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1712                 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1713                               &root->delalloc_inodes);
1714                 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1715                         &BTRFS_I(inode)->runtime_flags);
1716                 root->nr_delalloc_inodes++;
1717                 if (root->nr_delalloc_inodes == 1) {
1718                         spin_lock(&fs_info->delalloc_root_lock);
1719                         BUG_ON(!list_empty(&root->delalloc_root));
1720                         list_add_tail(&root->delalloc_root,
1721                                       &fs_info->delalloc_roots);
1722                         spin_unlock(&fs_info->delalloc_root_lock);
1723                 }
1724         }
1725         spin_unlock(&root->delalloc_lock);
1726 }
1727
1728 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1729                                      struct btrfs_inode *inode)
1730 {
1731         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1732
1733         spin_lock(&root->delalloc_lock);
1734         if (!list_empty(&inode->delalloc_inodes)) {
1735                 list_del_init(&inode->delalloc_inodes);
1736                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1737                           &inode->runtime_flags);
1738                 root->nr_delalloc_inodes--;
1739                 if (!root->nr_delalloc_inodes) {
1740                         spin_lock(&fs_info->delalloc_root_lock);
1741                         BUG_ON(list_empty(&root->delalloc_root));
1742                         list_del_init(&root->delalloc_root);
1743                         spin_unlock(&fs_info->delalloc_root_lock);
1744                 }
1745         }
1746         spin_unlock(&root->delalloc_lock);
1747 }
1748
1749 /*
1750  * extent_io.c set_bit_hook, used to track delayed allocation
1751  * bytes in this file, and to maintain the list of inodes that
1752  * have pending delalloc work to be done.
1753  */
1754 static void btrfs_set_bit_hook(void *private_data,
1755                                struct extent_state *state, unsigned *bits)
1756 {
1757         struct inode *inode = private_data;
1758
1759         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1760
1761         if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1762                 WARN_ON(1);
1763         /*
1764          * set_bit and clear bit hooks normally require _irqsave/restore
1765          * but in this case, we are only testing for the DELALLOC
1766          * bit, which is only set or cleared with irqs on
1767          */
1768         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1769                 struct btrfs_root *root = BTRFS_I(inode)->root;
1770                 u64 len = state->end + 1 - state->start;
1771                 u32 num_extents = count_max_extents(len);
1772                 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1773
1774                 spin_lock(&BTRFS_I(inode)->lock);
1775                 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1776                 spin_unlock(&BTRFS_I(inode)->lock);
1777
1778                 /* For sanity tests */
1779                 if (btrfs_is_testing(fs_info))
1780                         return;
1781
1782                 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1783                                          fs_info->delalloc_batch);
1784                 spin_lock(&BTRFS_I(inode)->lock);
1785                 BTRFS_I(inode)->delalloc_bytes += len;
1786                 if (*bits & EXTENT_DEFRAG)
1787                         BTRFS_I(inode)->defrag_bytes += len;
1788                 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1789                                          &BTRFS_I(inode)->runtime_flags))
1790                         btrfs_add_delalloc_inodes(root, inode);
1791                 spin_unlock(&BTRFS_I(inode)->lock);
1792         }
1793
1794         if (!(state->state & EXTENT_DELALLOC_NEW) &&
1795             (*bits & EXTENT_DELALLOC_NEW)) {
1796                 spin_lock(&BTRFS_I(inode)->lock);
1797                 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1798                         state->start;
1799                 spin_unlock(&BTRFS_I(inode)->lock);
1800         }
1801 }
1802
1803 /*
1804  * extent_io.c clear_bit_hook, see set_bit_hook for why
1805  */
1806 static void btrfs_clear_bit_hook(void *private_data,
1807                                  struct extent_state *state,
1808                                  unsigned *bits)
1809 {
1810         struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1811         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1812         u64 len = state->end + 1 - state->start;
1813         u32 num_extents = count_max_extents(len);
1814
1815         if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1816                 spin_lock(&inode->lock);
1817                 inode->defrag_bytes -= len;
1818                 spin_unlock(&inode->lock);
1819         }
1820
1821         /*
1822          * set_bit and clear bit hooks normally require _irqsave/restore
1823          * but in this case, we are only testing for the DELALLOC
1824          * bit, which is only set or cleared with irqs on
1825          */
1826         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1827                 struct btrfs_root *root = inode->root;
1828                 bool do_list = !btrfs_is_free_space_inode(inode);
1829
1830                 spin_lock(&inode->lock);
1831                 btrfs_mod_outstanding_extents(inode, -num_extents);
1832                 spin_unlock(&inode->lock);
1833
1834                 /*
1835                  * We don't reserve metadata space for space cache inodes so we
1836                  * don't need to call dellalloc_release_metadata if there is an
1837                  * error.
1838                  */
1839                 if (*bits & EXTENT_CLEAR_META_RESV &&
1840                     root != fs_info->tree_root)
1841                         btrfs_delalloc_release_metadata(inode, len);
1842
1843                 /* For sanity tests. */
1844                 if (btrfs_is_testing(fs_info))
1845                         return;
1846
1847                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1848                     do_list && !(state->state & EXTENT_NORESERVE) &&
1849                     (*bits & EXTENT_CLEAR_DATA_RESV))
1850                         btrfs_free_reserved_data_space_noquota(
1851                                         &inode->vfs_inode,
1852                                         state->start, len);
1853
1854                 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1855                                          fs_info->delalloc_batch);
1856                 spin_lock(&inode->lock);
1857                 inode->delalloc_bytes -= len;
1858                 if (do_list && inode->delalloc_bytes == 0 &&
1859                     test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1860                                         &inode->runtime_flags))
1861                         btrfs_del_delalloc_inode(root, inode);
1862                 spin_unlock(&inode->lock);
1863         }
1864
1865         if ((state->state & EXTENT_DELALLOC_NEW) &&
1866             (*bits & EXTENT_DELALLOC_NEW)) {
1867                 spin_lock(&inode->lock);
1868                 ASSERT(inode->new_delalloc_bytes >= len);
1869                 inode->new_delalloc_bytes -= len;
1870                 spin_unlock(&inode->lock);
1871         }
1872 }
1873
1874 /*
1875  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1876  * we don't create bios that span stripes or chunks
1877  *
1878  * return 1 if page cannot be merged to bio
1879  * return 0 if page can be merged to bio
1880  * return error otherwise
1881  */
1882 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1883                          size_t size, struct bio *bio,
1884                          unsigned long bio_flags)
1885 {
1886         struct inode *inode = page->mapping->host;
1887         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1888         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1889         u64 length = 0;
1890         u64 map_length;
1891         int ret;
1892
1893         if (bio_flags & EXTENT_BIO_COMPRESSED)
1894                 return 0;
1895
1896         length = bio->bi_iter.bi_size;
1897         map_length = length;
1898         ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1899                               NULL, 0);
1900         if (ret < 0)
1901                 return ret;
1902         if (map_length < length + size)
1903                 return 1;
1904         return 0;
1905 }
1906
1907 /*
1908  * in order to insert checksums into the metadata in large chunks,
1909  * we wait until bio submission time.   All the pages in the bio are
1910  * checksummed and sums are attached onto the ordered extent record.
1911  *
1912  * At IO completion time the cums attached on the ordered extent record
1913  * are inserted into the btree
1914  */
1915 static blk_status_t __btrfs_submit_bio_start(void *private_data, struct bio *bio,
1916                                     int mirror_num, unsigned long bio_flags,
1917                                     u64 bio_offset)
1918 {
1919         struct inode *inode = private_data;
1920         blk_status_t ret = 0;
1921
1922         ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1923         BUG_ON(ret); /* -ENOMEM */
1924         return 0;
1925 }
1926
1927 /*
1928  * in order to insert checksums into the metadata in large chunks,
1929  * we wait until bio submission time.   All the pages in the bio are
1930  * checksummed and sums are attached onto the ordered extent record.
1931  *
1932  * At IO completion time the cums attached on the ordered extent record
1933  * are inserted into the btree
1934  */
1935 static blk_status_t __btrfs_submit_bio_done(void *private_data, struct bio *bio,
1936                           int mirror_num, unsigned long bio_flags,
1937                           u64 bio_offset)
1938 {
1939         struct inode *inode = private_data;
1940         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1941         blk_status_t ret;
1942
1943         ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1944         if (ret) {
1945                 bio->bi_status = ret;
1946                 bio_endio(bio);
1947         }
1948         return ret;
1949 }
1950
1951 /*
1952  * extent_io.c submission hook. This does the right thing for csum calculation
1953  * on write, or reading the csums from the tree before a read.
1954  *
1955  * Rules about async/sync submit,
1956  * a) read:                             sync submit
1957  *
1958  * b) write without checksum:           sync submit
1959  *
1960  * c) write with checksum:
1961  *    c-1) if bio is issued by fsync:   sync submit
1962  *         (sync_writers != 0)
1963  *
1964  *    c-2) if root is reloc root:       sync submit
1965  *         (only in case of buffered IO)
1966  *
1967  *    c-3) otherwise:                   async submit
1968  */
1969 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1970                                  int mirror_num, unsigned long bio_flags,
1971                                  u64 bio_offset)
1972 {
1973         struct inode *inode = private_data;
1974         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1975         struct btrfs_root *root = BTRFS_I(inode)->root;
1976         enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1977         blk_status_t ret = 0;
1978         int skip_sum;
1979         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1980
1981         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1982
1983         if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1984                 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1985
1986         if (bio_op(bio) != REQ_OP_WRITE) {
1987                 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1988                 if (ret)
1989                         goto out;
1990
1991                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1992                         ret = btrfs_submit_compressed_read(inode, bio,
1993                                                            mirror_num,
1994                                                            bio_flags);
1995                         goto out;
1996                 } else if (!skip_sum) {
1997                         ret = btrfs_lookup_bio_sums(inode, bio, NULL);
1998                         if (ret)
1999                                 goto out;
2000                 }
2001                 goto mapit;
2002         } else if (async && !skip_sum) {
2003                 /* csum items have already been cloned */
2004                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2005                         goto mapit;
2006                 /* we're doing a write, do the async checksumming */
2007                 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2008                                           bio_offset, inode,
2009                                           __btrfs_submit_bio_start,
2010                                           __btrfs_submit_bio_done);
2011                 goto out;
2012         } else if (!skip_sum) {
2013                 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2014                 if (ret)
2015                         goto out;
2016         }
2017
2018 mapit:
2019         ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2020
2021 out:
2022         if (ret) {
2023                 bio->bi_status = ret;
2024                 bio_endio(bio);
2025         }
2026         return ret;
2027 }
2028
2029 /*
2030  * given a list of ordered sums record them in the inode.  This happens
2031  * at IO completion time based on sums calculated at bio submission time.
2032  */
2033 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2034                              struct inode *inode, struct list_head *list)
2035 {
2036         struct btrfs_ordered_sum *sum;
2037
2038         list_for_each_entry(sum, list, list) {
2039                 trans->adding_csums = true;
2040                 btrfs_csum_file_blocks(trans,
2041                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
2042                 trans->adding_csums = false;
2043         }
2044         return 0;
2045 }
2046
2047 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2048                               unsigned int extra_bits,
2049                               struct extent_state **cached_state, int dedupe)
2050 {
2051         WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2052         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2053                                    extra_bits, cached_state);
2054 }
2055
2056 /* see btrfs_writepage_start_hook for details on why this is required */
2057 struct btrfs_writepage_fixup {
2058         struct page *page;
2059         struct btrfs_work work;
2060 };
2061
2062 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2063 {
2064         struct btrfs_writepage_fixup *fixup;
2065         struct btrfs_ordered_extent *ordered;
2066         struct extent_state *cached_state = NULL;
2067         struct extent_changeset *data_reserved = NULL;
2068         struct page *page;
2069         struct inode *inode;
2070         u64 page_start;
2071         u64 page_end;
2072         int ret;
2073
2074         fixup = container_of(work, struct btrfs_writepage_fixup, work);
2075         page = fixup->page;
2076 again:
2077         lock_page(page);
2078         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2079                 ClearPageChecked(page);
2080                 goto out_page;
2081         }
2082
2083         inode = page->mapping->host;
2084         page_start = page_offset(page);
2085         page_end = page_offset(page) + PAGE_SIZE - 1;
2086
2087         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2088                          &cached_state);
2089
2090         /* already ordered? We're done */
2091         if (PagePrivate2(page))
2092                 goto out;
2093
2094         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2095                                         PAGE_SIZE);
2096         if (ordered) {
2097                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2098                                      page_end, &cached_state, GFP_NOFS);
2099                 unlock_page(page);
2100                 btrfs_start_ordered_extent(inode, ordered, 1);
2101                 btrfs_put_ordered_extent(ordered);
2102                 goto again;
2103         }
2104
2105         ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2106                                            PAGE_SIZE);
2107         if (ret) {
2108                 mapping_set_error(page->mapping, ret);
2109                 end_extent_writepage(page, ret, page_start, page_end);
2110                 ClearPageChecked(page);
2111                 goto out;
2112          }
2113
2114         btrfs_set_extent_delalloc(inode, page_start, page_end, 0, &cached_state,
2115                                   0);
2116         ClearPageChecked(page);
2117         set_page_dirty(page);
2118         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2119 out:
2120         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2121                              &cached_state, GFP_NOFS);
2122 out_page:
2123         unlock_page(page);
2124         put_page(page);
2125         kfree(fixup);
2126         extent_changeset_free(data_reserved);
2127 }
2128
2129 /*
2130  * There are a few paths in the higher layers of the kernel that directly
2131  * set the page dirty bit without asking the filesystem if it is a
2132  * good idea.  This causes problems because we want to make sure COW
2133  * properly happens and the data=ordered rules are followed.
2134  *
2135  * In our case any range that doesn't have the ORDERED bit set
2136  * hasn't been properly setup for IO.  We kick off an async process
2137  * to fix it up.  The async helper will wait for ordered extents, set
2138  * the delalloc bit and make it safe to write the page.
2139  */
2140 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2141 {
2142         struct inode *inode = page->mapping->host;
2143         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2144         struct btrfs_writepage_fixup *fixup;
2145
2146         /* this page is properly in the ordered list */
2147         if (TestClearPagePrivate2(page))
2148                 return 0;
2149
2150         if (PageChecked(page))
2151                 return -EAGAIN;
2152
2153         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2154         if (!fixup)
2155                 return -EAGAIN;
2156
2157         SetPageChecked(page);
2158         get_page(page);
2159         btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2160                         btrfs_writepage_fixup_worker, NULL, NULL);
2161         fixup->page = page;
2162         btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2163         return -EBUSY;
2164 }
2165
2166 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2167                                        struct inode *inode, u64 file_pos,
2168                                        u64 disk_bytenr, u64 disk_num_bytes,
2169                                        u64 num_bytes, u64 ram_bytes,
2170                                        u8 compression, u8 encryption,
2171                                        u16 other_encoding, int extent_type)
2172 {
2173         struct btrfs_root *root = BTRFS_I(inode)->root;
2174         struct btrfs_file_extent_item *fi;
2175         struct btrfs_path *path;
2176         struct extent_buffer *leaf;
2177         struct btrfs_key ins;
2178         u64 qg_released;
2179         int extent_inserted = 0;
2180         int ret;
2181
2182         path = btrfs_alloc_path();
2183         if (!path)
2184                 return -ENOMEM;
2185
2186         /*
2187          * we may be replacing one extent in the tree with another.
2188          * The new extent is pinned in the extent map, and we don't want
2189          * to drop it from the cache until it is completely in the btree.
2190          *
2191          * So, tell btrfs_drop_extents to leave this extent in the cache.
2192          * the caller is expected to unpin it and allow it to be merged
2193          * with the others.
2194          */
2195         ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2196                                    file_pos + num_bytes, NULL, 0,
2197                                    1, sizeof(*fi), &extent_inserted);
2198         if (ret)
2199                 goto out;
2200
2201         if (!extent_inserted) {
2202                 ins.objectid = btrfs_ino(BTRFS_I(inode));
2203                 ins.offset = file_pos;
2204                 ins.type = BTRFS_EXTENT_DATA_KEY;
2205
2206                 path->leave_spinning = 1;
2207                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2208                                               sizeof(*fi));
2209                 if (ret)
2210                         goto out;
2211         }
2212         leaf = path->nodes[0];
2213         fi = btrfs_item_ptr(leaf, path->slots[0],
2214                             struct btrfs_file_extent_item);
2215         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2216         btrfs_set_file_extent_type(leaf, fi, extent_type);
2217         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2218         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2219         btrfs_set_file_extent_offset(leaf, fi, 0);
2220         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2221         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2222         btrfs_set_file_extent_compression(leaf, fi, compression);
2223         btrfs_set_file_extent_encryption(leaf, fi, encryption);
2224         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2225
2226         btrfs_mark_buffer_dirty(leaf);
2227         btrfs_release_path(path);
2228
2229         inode_add_bytes(inode, num_bytes);
2230
2231         ins.objectid = disk_bytenr;
2232         ins.offset = disk_num_bytes;
2233         ins.type = BTRFS_EXTENT_ITEM_KEY;
2234
2235         /*
2236          * Release the reserved range from inode dirty range map, as it is
2237          * already moved into delayed_ref_head
2238          */
2239         ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2240         if (ret < 0)
2241                 goto out;
2242         qg_released = ret;
2243         ret = btrfs_alloc_reserved_file_extent(trans, root,
2244                                                btrfs_ino(BTRFS_I(inode)),
2245                                                file_pos, qg_released, &ins);
2246 out:
2247         btrfs_free_path(path);
2248
2249         return ret;
2250 }
2251
2252 /* snapshot-aware defrag */
2253 struct sa_defrag_extent_backref {
2254         struct rb_node node;
2255         struct old_sa_defrag_extent *old;
2256         u64 root_id;
2257         u64 inum;
2258         u64 file_pos;
2259         u64 extent_offset;
2260         u64 num_bytes;
2261         u64 generation;
2262 };
2263
2264 struct old_sa_defrag_extent {
2265         struct list_head list;
2266         struct new_sa_defrag_extent *new;
2267
2268         u64 extent_offset;
2269         u64 bytenr;
2270         u64 offset;
2271         u64 len;
2272         int count;
2273 };
2274
2275 struct new_sa_defrag_extent {
2276         struct rb_root root;
2277         struct list_head head;
2278         struct btrfs_path *path;
2279         struct inode *inode;
2280         u64 file_pos;
2281         u64 len;
2282         u64 bytenr;
2283         u64 disk_len;
2284         u8 compress_type;
2285 };
2286
2287 static int backref_comp(struct sa_defrag_extent_backref *b1,
2288                         struct sa_defrag_extent_backref *b2)
2289 {
2290         if (b1->root_id < b2->root_id)
2291                 return -1;
2292         else if (b1->root_id > b2->root_id)
2293                 return 1;
2294
2295         if (b1->inum < b2->inum)
2296                 return -1;
2297         else if (b1->inum > b2->inum)
2298                 return 1;
2299
2300         if (b1->file_pos < b2->file_pos)
2301                 return -1;
2302         else if (b1->file_pos > b2->file_pos)
2303                 return 1;
2304
2305         /*
2306          * [------------------------------] ===> (a range of space)
2307          *     |<--->|   |<---->| =============> (fs/file tree A)
2308          * |<---------------------------->| ===> (fs/file tree B)
2309          *
2310          * A range of space can refer to two file extents in one tree while
2311          * refer to only one file extent in another tree.
2312          *
2313          * So we may process a disk offset more than one time(two extents in A)
2314          * and locate at the same extent(one extent in B), then insert two same
2315          * backrefs(both refer to the extent in B).
2316          */
2317         return 0;
2318 }
2319
2320 static void backref_insert(struct rb_root *root,
2321                            struct sa_defrag_extent_backref *backref)
2322 {
2323         struct rb_node **p = &root->rb_node;
2324         struct rb_node *parent = NULL;
2325         struct sa_defrag_extent_backref *entry;
2326         int ret;
2327
2328         while (*p) {
2329                 parent = *p;
2330                 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2331
2332                 ret = backref_comp(backref, entry);
2333                 if (ret < 0)
2334                         p = &(*p)->rb_left;
2335                 else
2336                         p = &(*p)->rb_right;
2337         }
2338
2339         rb_link_node(&backref->node, parent, p);
2340         rb_insert_color(&backref->node, root);
2341 }
2342
2343 /*
2344  * Note the backref might has changed, and in this case we just return 0.
2345  */
2346 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2347                                        void *ctx)
2348 {
2349         struct btrfs_file_extent_item *extent;
2350         struct old_sa_defrag_extent *old = ctx;
2351         struct new_sa_defrag_extent *new = old->new;
2352         struct btrfs_path *path = new->path;
2353         struct btrfs_key key;
2354         struct btrfs_root *root;
2355         struct sa_defrag_extent_backref *backref;
2356         struct extent_buffer *leaf;
2357         struct inode *inode = new->inode;
2358         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2359         int slot;
2360         int ret;
2361         u64 extent_offset;
2362         u64 num_bytes;
2363
2364         if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2365             inum == btrfs_ino(BTRFS_I(inode)))
2366                 return 0;
2367
2368         key.objectid = root_id;
2369         key.type = BTRFS_ROOT_ITEM_KEY;
2370         key.offset = (u64)-1;
2371
2372         root = btrfs_read_fs_root_no_name(fs_info, &key);
2373         if (IS_ERR(root)) {
2374                 if (PTR_ERR(root) == -ENOENT)
2375                         return 0;
2376                 WARN_ON(1);
2377                 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2378                          inum, offset, root_id);
2379                 return PTR_ERR(root);
2380         }
2381
2382         key.objectid = inum;
2383         key.type = BTRFS_EXTENT_DATA_KEY;
2384         if (offset > (u64)-1 << 32)
2385                 key.offset = 0;
2386         else
2387                 key.offset = offset;
2388
2389         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2390         if (WARN_ON(ret < 0))
2391                 return ret;
2392         ret = 0;
2393
2394         while (1) {
2395                 cond_resched();
2396
2397                 leaf = path->nodes[0];
2398                 slot = path->slots[0];
2399
2400                 if (slot >= btrfs_header_nritems(leaf)) {
2401                         ret = btrfs_next_leaf(root, path);
2402                         if (ret < 0) {
2403                                 goto out;
2404                         } else if (ret > 0) {
2405                                 ret = 0;
2406                                 goto out;
2407                         }
2408                         continue;
2409                 }
2410
2411                 path->slots[0]++;
2412
2413                 btrfs_item_key_to_cpu(leaf, &key, slot);
2414
2415                 if (key.objectid > inum)
2416                         goto out;
2417
2418                 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2419                         continue;
2420
2421                 extent = btrfs_item_ptr(leaf, slot,
2422                                         struct btrfs_file_extent_item);
2423
2424                 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2425                         continue;
2426
2427                 /*
2428                  * 'offset' refers to the exact key.offset,
2429                  * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2430                  * (key.offset - extent_offset).
2431                  */
2432                 if (key.offset != offset)
2433                         continue;
2434
2435                 extent_offset = btrfs_file_extent_offset(leaf, extent);
2436                 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2437
2438                 if (extent_offset >= old->extent_offset + old->offset +
2439                     old->len || extent_offset + num_bytes <=
2440                     old->extent_offset + old->offset)
2441                         continue;
2442                 break;
2443         }
2444
2445         backref = kmalloc(sizeof(*backref), GFP_NOFS);
2446         if (!backref) {
2447                 ret = -ENOENT;
2448                 goto out;
2449         }
2450
2451         backref->root_id = root_id;
2452         backref->inum = inum;
2453         backref->file_pos = offset;
2454         backref->num_bytes = num_bytes;
2455         backref->extent_offset = extent_offset;
2456         backref->generation = btrfs_file_extent_generation(leaf, extent);
2457         backref->old = old;
2458         backref_insert(&new->root, backref);
2459         old->count++;
2460 out:
2461         btrfs_release_path(path);
2462         WARN_ON(ret);
2463         return ret;
2464 }
2465
2466 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2467                                    struct new_sa_defrag_extent *new)
2468 {
2469         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2470         struct old_sa_defrag_extent *old, *tmp;
2471         int ret;
2472
2473         new->path = path;
2474
2475         list_for_each_entry_safe(old, tmp, &new->head, list) {
2476                 ret = iterate_inodes_from_logical(old->bytenr +
2477                                                   old->extent_offset, fs_info,
2478                                                   path, record_one_backref,
2479                                                   old, false);
2480                 if (ret < 0 && ret != -ENOENT)
2481                         return false;
2482
2483                 /* no backref to be processed for this extent */
2484                 if (!old->count) {
2485                         list_del(&old->list);
2486                         kfree(old);
2487                 }
2488         }
2489
2490         if (list_empty(&new->head))
2491                 return false;
2492
2493         return true;
2494 }
2495
2496 static int relink_is_mergable(struct extent_buffer *leaf,
2497                               struct btrfs_file_extent_item *fi,
2498                               struct new_sa_defrag_extent *new)
2499 {
2500         if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2501                 return 0;
2502
2503         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2504                 return 0;
2505
2506         if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2507                 return 0;
2508
2509         if (btrfs_file_extent_encryption(leaf, fi) ||
2510             btrfs_file_extent_other_encoding(leaf, fi))
2511                 return 0;
2512
2513         return 1;
2514 }
2515
2516 /*
2517  * Note the backref might has changed, and in this case we just return 0.
2518  */
2519 static noinline int relink_extent_backref(struct btrfs_path *path,
2520                                  struct sa_defrag_extent_backref *prev,
2521                                  struct sa_defrag_extent_backref *backref)
2522 {
2523         struct btrfs_file_extent_item *extent;
2524         struct btrfs_file_extent_item *item;
2525         struct btrfs_ordered_extent *ordered;
2526         struct btrfs_trans_handle *trans;
2527         struct btrfs_root *root;
2528         struct btrfs_key key;
2529         struct extent_buffer *leaf;
2530         struct old_sa_defrag_extent *old = backref->old;
2531         struct new_sa_defrag_extent *new = old->new;
2532         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2533         struct inode *inode;
2534         struct extent_state *cached = NULL;
2535         int ret = 0;
2536         u64 start;
2537         u64 len;
2538         u64 lock_start;
2539         u64 lock_end;
2540         bool merge = false;
2541         int index;
2542
2543         if (prev && prev->root_id == backref->root_id &&
2544             prev->inum == backref->inum &&
2545             prev->file_pos + prev->num_bytes == backref->file_pos)
2546                 merge = true;
2547
2548         /* step 1: get root */
2549         key.objectid = backref->root_id;
2550         key.type = BTRFS_ROOT_ITEM_KEY;
2551         key.offset = (u64)-1;
2552
2553         index = srcu_read_lock(&fs_info->subvol_srcu);
2554
2555         root = btrfs_read_fs_root_no_name(fs_info, &key);
2556         if (IS_ERR(root)) {
2557                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2558                 if (PTR_ERR(root) == -ENOENT)
2559                         return 0;
2560                 return PTR_ERR(root);
2561         }
2562
2563         if (btrfs_root_readonly(root)) {
2564                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2565                 return 0;
2566         }
2567
2568         /* step 2: get inode */
2569         key.objectid = backref->inum;
2570         key.type = BTRFS_INODE_ITEM_KEY;
2571         key.offset = 0;
2572
2573         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2574         if (IS_ERR(inode)) {
2575                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2576                 return 0;
2577         }
2578
2579         srcu_read_unlock(&fs_info->subvol_srcu, index);
2580
2581         /* step 3: relink backref */
2582         lock_start = backref->file_pos;
2583         lock_end = backref->file_pos + backref->num_bytes - 1;
2584         lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2585                          &cached);
2586
2587         ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2588         if (ordered) {
2589                 btrfs_put_ordered_extent(ordered);
2590                 goto out_unlock;
2591         }
2592
2593         trans = btrfs_join_transaction(root);
2594         if (IS_ERR(trans)) {
2595                 ret = PTR_ERR(trans);
2596                 goto out_unlock;
2597         }
2598
2599         key.objectid = backref->inum;
2600         key.type = BTRFS_EXTENT_DATA_KEY;
2601         key.offset = backref->file_pos;
2602
2603         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2604         if (ret < 0) {
2605                 goto out_free_path;
2606         } else if (ret > 0) {
2607                 ret = 0;
2608                 goto out_free_path;
2609         }
2610
2611         extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2612                                 struct btrfs_file_extent_item);
2613
2614         if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2615             backref->generation)
2616                 goto out_free_path;
2617
2618         btrfs_release_path(path);
2619
2620         start = backref->file_pos;
2621         if (backref->extent_offset < old->extent_offset + old->offset)
2622                 start += old->extent_offset + old->offset -
2623                          backref->extent_offset;
2624
2625         len = min(backref->extent_offset + backref->num_bytes,
2626                   old->extent_offset + old->offset + old->len);
2627         len -= max(backref->extent_offset, old->extent_offset + old->offset);
2628
2629         ret = btrfs_drop_extents(trans, root, inode, start,
2630                                  start + len, 1);
2631         if (ret)
2632                 goto out_free_path;
2633 again:
2634         key.objectid = btrfs_ino(BTRFS_I(inode));
2635         key.type = BTRFS_EXTENT_DATA_KEY;
2636         key.offset = start;
2637
2638         path->leave_spinning = 1;
2639         if (merge) {
2640                 struct btrfs_file_extent_item *fi;
2641                 u64 extent_len;
2642                 struct btrfs_key found_key;
2643
2644                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2645                 if (ret < 0)
2646                         goto out_free_path;
2647
2648                 path->slots[0]--;
2649                 leaf = path->nodes[0];
2650                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2651
2652                 fi = btrfs_item_ptr(leaf, path->slots[0],
2653                                     struct btrfs_file_extent_item);
2654                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2655
2656                 if (extent_len + found_key.offset == start &&
2657                     relink_is_mergable(leaf, fi, new)) {
2658                         btrfs_set_file_extent_num_bytes(leaf, fi,
2659                                                         extent_len + len);
2660                         btrfs_mark_buffer_dirty(leaf);
2661                         inode_add_bytes(inode, len);
2662
2663                         ret = 1;
2664                         goto out_free_path;
2665                 } else {
2666                         merge = false;
2667                         btrfs_release_path(path);
2668                         goto again;
2669                 }
2670         }
2671
2672         ret = btrfs_insert_empty_item(trans, root, path, &key,
2673                                         sizeof(*extent));
2674         if (ret) {
2675                 btrfs_abort_transaction(trans, ret);
2676                 goto out_free_path;
2677         }
2678
2679         leaf = path->nodes[0];
2680         item = btrfs_item_ptr(leaf, path->slots[0],
2681                                 struct btrfs_file_extent_item);
2682         btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2683         btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2684         btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2685         btrfs_set_file_extent_num_bytes(leaf, item, len);
2686         btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2687         btrfs_set_file_extent_generation(leaf, item, trans->transid);
2688         btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2689         btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2690         btrfs_set_file_extent_encryption(leaf, item, 0);
2691         btrfs_set_file_extent_other_encoding(leaf, item, 0);
2692
2693         btrfs_mark_buffer_dirty(leaf);
2694         inode_add_bytes(inode, len);
2695         btrfs_release_path(path);
2696
2697         ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2698                         new->disk_len, 0,
2699                         backref->root_id, backref->inum,
2700                         new->file_pos); /* start - extent_offset */
2701         if (ret) {
2702                 btrfs_abort_transaction(trans, ret);
2703                 goto out_free_path;
2704         }
2705
2706         ret = 1;
2707 out_free_path:
2708         btrfs_release_path(path);
2709         path->leave_spinning = 0;
2710         btrfs_end_transaction(trans);
2711 out_unlock:
2712         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2713                              &cached, GFP_NOFS);
2714         iput(inode);
2715         return ret;
2716 }
2717
2718 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2719 {
2720         struct old_sa_defrag_extent *old, *tmp;
2721
2722         if (!new)
2723                 return;
2724
2725         list_for_each_entry_safe(old, tmp, &new->head, list) {
2726                 kfree(old);
2727         }
2728         kfree(new);
2729 }
2730
2731 static void relink_file_extents(struct new_sa_defrag_extent *new)
2732 {
2733         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2734         struct btrfs_path *path;
2735         struct sa_defrag_extent_backref *backref;
2736         struct sa_defrag_extent_backref *prev = NULL;
2737         struct inode *inode;
2738         struct btrfs_root *root;
2739         struct rb_node *node;
2740         int ret;
2741
2742         inode = new->inode;
2743         root = BTRFS_I(inode)->root;
2744
2745         path = btrfs_alloc_path();
2746         if (!path)
2747                 return;
2748
2749         if (!record_extent_backrefs(path, new)) {
2750                 btrfs_free_path(path);
2751                 goto out;
2752         }
2753         btrfs_release_path(path);
2754
2755         while (1) {
2756                 node = rb_first(&new->root);
2757                 if (!node)
2758                         break;
2759                 rb_erase(node, &new->root);
2760
2761                 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2762
2763                 ret = relink_extent_backref(path, prev, backref);
2764                 WARN_ON(ret < 0);
2765
2766                 kfree(prev);
2767
2768                 if (ret == 1)
2769                         prev = backref;
2770                 else
2771                         prev = NULL;
2772                 cond_resched();
2773         }
2774         kfree(prev);
2775
2776         btrfs_free_path(path);
2777 out:
2778         free_sa_defrag_extent(new);
2779
2780         atomic_dec(&fs_info->defrag_running);
2781         wake_up(&fs_info->transaction_wait);
2782 }
2783
2784 static struct new_sa_defrag_extent *
2785 record_old_file_extents(struct inode *inode,
2786                         struct btrfs_ordered_extent *ordered)
2787 {
2788         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2789         struct btrfs_root *root = BTRFS_I(inode)->root;
2790         struct btrfs_path *path;
2791         struct btrfs_key key;
2792         struct old_sa_defrag_extent *old;
2793         struct new_sa_defrag_extent *new;
2794         int ret;
2795
2796         new = kmalloc(sizeof(*new), GFP_NOFS);
2797         if (!new)
2798                 return NULL;
2799
2800         new->inode = inode;
2801         new->file_pos = ordered->file_offset;
2802         new->len = ordered->len;
2803         new->bytenr = ordered->start;
2804         new->disk_len = ordered->disk_len;
2805         new->compress_type = ordered->compress_type;
2806         new->root = RB_ROOT;
2807         INIT_LIST_HEAD(&new->head);
2808
2809         path = btrfs_alloc_path();
2810         if (!path)
2811                 goto out_kfree;
2812
2813         key.objectid = btrfs_ino(BTRFS_I(inode));
2814         key.type = BTRFS_EXTENT_DATA_KEY;
2815         key.offset = new->file_pos;
2816
2817         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2818         if (ret < 0)
2819                 goto out_free_path;
2820         if (ret > 0 && path->slots[0] > 0)
2821                 path->slots[0]--;
2822
2823         /* find out all the old extents for the file range */
2824         while (1) {
2825                 struct btrfs_file_extent_item *extent;
2826                 struct extent_buffer *l;
2827                 int slot;
2828                 u64 num_bytes;
2829                 u64 offset;
2830                 u64 end;
2831                 u64 disk_bytenr;
2832                 u64 extent_offset;
2833
2834                 l = path->nodes[0];
2835                 slot = path->slots[0];
2836
2837                 if (slot >= btrfs_header_nritems(l)) {
2838                         ret = btrfs_next_leaf(root, path);
2839                         if (ret < 0)
2840                                 goto out_free_path;
2841                         else if (ret > 0)
2842                                 break;
2843                         continue;
2844                 }
2845
2846                 btrfs_item_key_to_cpu(l, &key, slot);
2847
2848                 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2849                         break;
2850                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2851                         break;
2852                 if (key.offset >= new->file_pos + new->len)
2853                         break;
2854
2855                 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2856
2857                 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2858                 if (key.offset + num_bytes < new->file_pos)
2859                         goto next;
2860
2861                 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2862                 if (!disk_bytenr)
2863                         goto next;
2864
2865                 extent_offset = btrfs_file_extent_offset(l, extent);
2866
2867                 old = kmalloc(sizeof(*old), GFP_NOFS);
2868                 if (!old)
2869                         goto out_free_path;
2870
2871                 offset = max(new->file_pos, key.offset);
2872                 end = min(new->file_pos + new->len, key.offset + num_bytes);
2873
2874                 old->bytenr = disk_bytenr;
2875                 old->extent_offset = extent_offset;
2876                 old->offset = offset - key.offset;
2877                 old->len = end - offset;
2878                 old->new = new;
2879                 old->count = 0;
2880                 list_add_tail(&old->list, &new->head);
2881 next:
2882                 path->slots[0]++;
2883                 cond_resched();
2884         }
2885
2886         btrfs_free_path(path);
2887         atomic_inc(&fs_info->defrag_running);
2888
2889         return new;
2890
2891 out_free_path:
2892         btrfs_free_path(path);
2893 out_kfree:
2894         free_sa_defrag_extent(new);
2895         return NULL;
2896 }
2897
2898 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2899                                          u64 start, u64 len)
2900 {
2901         struct btrfs_block_group_cache *cache;
2902
2903         cache = btrfs_lookup_block_group(fs_info, start);
2904         ASSERT(cache);
2905
2906         spin_lock(&cache->lock);
2907         cache->delalloc_bytes -= len;
2908         spin_unlock(&cache->lock);
2909
2910         btrfs_put_block_group(cache);
2911 }
2912
2913 /* as ordered data IO finishes, this gets called so we can finish
2914  * an ordered extent if the range of bytes in the file it covers are
2915  * fully written.
2916  */
2917 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2918 {
2919         struct inode *inode = ordered_extent->inode;
2920         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2921         struct btrfs_root *root = BTRFS_I(inode)->root;
2922         struct btrfs_trans_handle *trans = NULL;
2923         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2924         struct extent_state *cached_state = NULL;
2925         struct new_sa_defrag_extent *new = NULL;
2926         int compress_type = 0;
2927         int ret = 0;
2928         u64 logical_len = ordered_extent->len;
2929         bool nolock;
2930         bool truncated = false;
2931         bool range_locked = false;
2932         bool clear_new_delalloc_bytes = false;
2933
2934         if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2935             !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2936             !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2937                 clear_new_delalloc_bytes = true;
2938
2939         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2940
2941         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2942                 ret = -EIO;
2943                 goto out;
2944         }
2945
2946         btrfs_free_io_failure_record(BTRFS_I(inode),
2947                         ordered_extent->file_offset,
2948                         ordered_extent->file_offset +
2949                         ordered_extent->len - 1);
2950
2951         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2952                 truncated = true;
2953                 logical_len = ordered_extent->truncated_len;
2954                 /* Truncated the entire extent, don't bother adding */
2955                 if (!logical_len)
2956                         goto out;
2957         }
2958
2959         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2960                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2961
2962                 /*
2963                  * For mwrite(mmap + memset to write) case, we still reserve
2964                  * space for NOCOW range.
2965                  * As NOCOW won't cause a new delayed ref, just free the space
2966                  */
2967                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2968                                        ordered_extent->len);
2969                 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2970                 if (nolock)
2971                         trans = btrfs_join_transaction_nolock(root);
2972                 else
2973                         trans = btrfs_join_transaction(root);
2974                 if (IS_ERR(trans)) {
2975                         ret = PTR_ERR(trans);
2976                         trans = NULL;
2977                         goto out;
2978                 }
2979                 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2980                 ret = btrfs_update_inode_fallback(trans, root, inode);
2981                 if (ret) /* -ENOMEM or corruption */
2982                         btrfs_abort_transaction(trans, ret);
2983                 goto out;
2984         }
2985
2986         range_locked = true;
2987         lock_extent_bits(io_tree, ordered_extent->file_offset,
2988                          ordered_extent->file_offset + ordered_extent->len - 1,
2989                          &cached_state);
2990
2991         ret = test_range_bit(io_tree, ordered_extent->file_offset,
2992                         ordered_extent->file_offset + ordered_extent->len - 1,
2993                         EXTENT_DEFRAG, 0, cached_state);
2994         if (ret) {
2995                 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2996                 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2997                         /* the inode is shared */
2998                         new = record_old_file_extents(inode, ordered_extent);
2999
3000                 clear_extent_bit(io_tree, ordered_extent->file_offset,
3001                         ordered_extent->file_offset + ordered_extent->len - 1,
3002                         EXTENT_DEFRAG, 0, 0, &cached_state);
3003         }
3004
3005         if (nolock)
3006                 trans = btrfs_join_transaction_nolock(root);
3007         else
3008                 trans = btrfs_join_transaction(root);
3009         if (IS_ERR(trans)) {
3010                 ret = PTR_ERR(trans);
3011                 trans = NULL;
3012                 goto out;
3013         }
3014
3015         trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3016
3017         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3018                 compress_type = ordered_extent->compress_type;
3019         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3020                 BUG_ON(compress_type);
3021                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3022                                        ordered_extent->len);
3023                 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3024                                                 ordered_extent->file_offset,
3025                                                 ordered_extent->file_offset +
3026                                                 logical_len);
3027         } else {
3028                 BUG_ON(root == fs_info->tree_root);
3029                 ret = insert_reserved_file_extent(trans, inode,
3030                                                 ordered_extent->file_offset,
3031                                                 ordered_extent->start,
3032                                                 ordered_extent->disk_len,
3033                                                 logical_len, logical_len,
3034                                                 compress_type, 0, 0,
3035                                                 BTRFS_FILE_EXTENT_REG);
3036                 if (!ret)
3037                         btrfs_release_delalloc_bytes(fs_info,
3038                                                      ordered_extent->start,
3039                                                      ordered_extent->disk_len);
3040         }
3041         unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3042                            ordered_extent->file_offset, ordered_extent->len,
3043                            trans->transid);
3044         if (ret < 0) {
3045                 btrfs_abort_transaction(trans, ret);
3046                 goto out;
3047         }
3048
3049         add_pending_csums(trans, inode, &ordered_extent->list);
3050
3051         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3052         ret = btrfs_update_inode_fallback(trans, root, inode);
3053         if (ret) { /* -ENOMEM or corruption */
3054                 btrfs_abort_transaction(trans, ret);
3055                 goto out;
3056         }
3057         ret = 0;
3058 out:
3059         if (range_locked || clear_new_delalloc_bytes) {
3060                 unsigned int clear_bits = 0;
3061
3062                 if (range_locked)
3063                         clear_bits |= EXTENT_LOCKED;
3064                 if (clear_new_delalloc_bytes)
3065                         clear_bits |= EXTENT_DELALLOC_NEW;
3066                 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3067                                  ordered_extent->file_offset,
3068                                  ordered_extent->file_offset +
3069                                  ordered_extent->len - 1,
3070                                  clear_bits,
3071                                  (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3072                                  0, &cached_state);
3073         }
3074
3075         if (trans)
3076                 btrfs_end_transaction(trans);
3077
3078         if (ret || truncated) {
3079                 u64 start, end;
3080
3081                 if (truncated)
3082                         start = ordered_extent->file_offset + logical_len;
3083                 else
3084                         start = ordered_extent->file_offset;
3085                 end = ordered_extent->file_offset + ordered_extent->len - 1;
3086                 clear_extent_uptodate(io_tree, start, end, NULL);
3087
3088                 /* Drop the cache for the part of the extent we didn't write. */
3089                 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3090
3091                 /*
3092                  * If the ordered extent had an IOERR or something else went
3093                  * wrong we need to return the space for this ordered extent
3094                  * back to the allocator.  We only free the extent in the
3095                  * truncated case if we didn't write out the extent at all.
3096                  */
3097                 if ((ret || !logical_len) &&
3098                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3099                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3100                         btrfs_free_reserved_extent(fs_info,
3101                                                    ordered_extent->start,
3102                                                    ordered_extent->disk_len, 1);
3103         }
3104
3105
3106         /*
3107          * This needs to be done to make sure anybody waiting knows we are done
3108          * updating everything for this ordered extent.
3109          */
3110         btrfs_remove_ordered_extent(inode, ordered_extent);
3111
3112         /* for snapshot-aware defrag */
3113         if (new) {
3114                 if (ret) {
3115                         free_sa_defrag_extent(new);
3116                         atomic_dec(&fs_info->defrag_running);
3117                 } else {
3118                         relink_file_extents(new);
3119                 }
3120         }
3121
3122         /* once for us */
3123         btrfs_put_ordered_extent(ordered_extent);
3124         /* once for the tree */
3125         btrfs_put_ordered_extent(ordered_extent);
3126
3127         return ret;
3128 }
3129
3130 static void finish_ordered_fn(struct btrfs_work *work)
3131 {
3132         struct btrfs_ordered_extent *ordered_extent;
3133         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3134         btrfs_finish_ordered_io(ordered_extent);
3135 }
3136
3137 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3138                                 struct extent_state *state, int uptodate)
3139 {
3140         struct inode *inode = page->mapping->host;
3141         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3142         struct btrfs_ordered_extent *ordered_extent = NULL;
3143         struct btrfs_workqueue *wq;
3144         btrfs_work_func_t func;
3145
3146         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3147
3148         ClearPagePrivate2(page);
3149         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3150                                             end - start + 1, uptodate))
3151                 return;
3152
3153         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3154                 wq = fs_info->endio_freespace_worker;
3155                 func = btrfs_freespace_write_helper;
3156         } else {
3157                 wq = fs_info->endio_write_workers;
3158                 func = btrfs_endio_write_helper;
3159         }
3160
3161         btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3162                         NULL);
3163         btrfs_queue_work(wq, &ordered_extent->work);
3164 }
3165
3166 static int __readpage_endio_check(struct inode *inode,
3167                                   struct btrfs_io_bio *io_bio,
3168                                   int icsum, struct page *page,
3169                                   int pgoff, u64 start, size_t len)
3170 {
3171         char *kaddr;
3172         u32 csum_expected;
3173         u32 csum = ~(u32)0;
3174
3175         csum_expected = *(((u32 *)io_bio->csum) + icsum);
3176
3177         kaddr = kmap_atomic(page);
3178         csum = btrfs_csum_data(kaddr + pgoff, csum,  len);
3179         btrfs_csum_final(csum, (u8 *)&csum);
3180         if (csum != csum_expected)
3181                 goto zeroit;
3182
3183         kunmap_atomic(kaddr);
3184         return 0;
3185 zeroit:
3186         btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3187                                     io_bio->mirror_num);
3188         memset(kaddr + pgoff, 1, len);
3189         flush_dcache_page(page);
3190         kunmap_atomic(kaddr);
3191         return -EIO;
3192 }
3193
3194 /*
3195  * when reads are done, we need to check csums to verify the data is correct
3196  * if there's a match, we allow the bio to finish.  If not, the code in
3197  * extent_io.c will try to find good copies for us.
3198  */
3199 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3200                                       u64 phy_offset, struct page *page,
3201                                       u64 start, u64 end, int mirror)
3202 {
3203         size_t offset = start - page_offset(page);
3204         struct inode *inode = page->mapping->host;
3205         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3206         struct btrfs_root *root = BTRFS_I(inode)->root;
3207
3208         if (PageChecked(page)) {
3209                 ClearPageChecked(page);
3210                 return 0;
3211         }
3212
3213         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3214                 return 0;
3215
3216         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3217             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3218                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3219                 return 0;
3220         }
3221
3222         phy_offset >>= inode->i_sb->s_blocksize_bits;
3223         return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3224                                       start, (size_t)(end - start + 1));
3225 }
3226
3227 void btrfs_add_delayed_iput(struct inode *inode)
3228 {
3229         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3230         struct btrfs_inode *binode = BTRFS_I(inode);
3231
3232         if (atomic_add_unless(&inode->i_count, -1, 1))
3233                 return;
3234
3235         spin_lock(&fs_info->delayed_iput_lock);
3236         if (binode->delayed_iput_count == 0) {
3237                 ASSERT(list_empty(&binode->delayed_iput));
3238                 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3239         } else {
3240                 binode->delayed_iput_count++;
3241         }
3242         spin_unlock(&fs_info->delayed_iput_lock);
3243 }
3244
3245 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3246 {
3247
3248         spin_lock(&fs_info->delayed_iput_lock);
3249         while (!list_empty(&fs_info->delayed_iputs)) {
3250                 struct btrfs_inode *inode;
3251
3252                 inode = list_first_entry(&fs_info->delayed_iputs,
3253                                 struct btrfs_inode, delayed_iput);
3254                 if (inode->delayed_iput_count) {
3255                         inode->delayed_iput_count--;
3256                         list_move_tail(&inode->delayed_iput,
3257                                         &fs_info->delayed_iputs);
3258                 } else {
3259                         list_del_init(&inode->delayed_iput);
3260                 }
3261                 spin_unlock(&fs_info->delayed_iput_lock);
3262                 iput(&inode->vfs_inode);
3263                 spin_lock(&fs_info->delayed_iput_lock);
3264         }
3265         spin_unlock(&fs_info->delayed_iput_lock);
3266 }
3267
3268 /*
3269  * This is called in transaction commit time. If there are no orphan
3270  * files in the subvolume, it removes orphan item and frees block_rsv
3271  * structure.
3272  */
3273 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3274                               struct btrfs_root *root)
3275 {
3276         struct btrfs_fs_info *fs_info = root->fs_info;
3277         struct btrfs_block_rsv *block_rsv;
3278         int ret;
3279
3280         if (atomic_read(&root->orphan_inodes) ||
3281             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3282                 return;
3283
3284         spin_lock(&root->orphan_lock);
3285         if (atomic_read(&root->orphan_inodes)) {
3286                 spin_unlock(&root->orphan_lock);
3287                 return;
3288         }
3289
3290         if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3291                 spin_unlock(&root->orphan_lock);
3292                 return;
3293         }
3294
3295         block_rsv = root->orphan_block_rsv;
3296         root->orphan_block_rsv = NULL;
3297         spin_unlock(&root->orphan_lock);
3298
3299         if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3300             btrfs_root_refs(&root->root_item) > 0) {
3301                 ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
3302                                             root->root_key.objectid);
3303                 if (ret)
3304                         btrfs_abort_transaction(trans, ret);
3305                 else
3306                         clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3307                                   &root->state);
3308         }
3309
3310         if (block_rsv) {
3311                 WARN_ON(block_rsv->size > 0);
3312                 btrfs_free_block_rsv(fs_info, block_rsv);
3313         }
3314 }
3315
3316 /*
3317  * This creates an orphan entry for the given inode in case something goes
3318  * wrong in the middle of an unlink/truncate.
3319  *
3320  * NOTE: caller of this function should reserve 5 units of metadata for
3321  *       this function.
3322  */
3323 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3324                 struct btrfs_inode *inode)
3325 {
3326         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3327         struct btrfs_root *root = inode->root;
3328         struct btrfs_block_rsv *block_rsv = NULL;
3329         int reserve = 0;
3330         int insert = 0;
3331         int ret;
3332
3333         if (!root->orphan_block_rsv) {
3334                 block_rsv = btrfs_alloc_block_rsv(fs_info,
3335                                                   BTRFS_BLOCK_RSV_TEMP);
3336                 if (!block_rsv)
3337                         return -ENOMEM;
3338         }
3339
3340         spin_lock(&root->orphan_lock);
3341         if (!root->orphan_block_rsv) {
3342                 root->orphan_block_rsv = block_rsv;
3343         } else if (block_rsv) {
3344                 btrfs_free_block_rsv(fs_info, block_rsv);
3345                 block_rsv = NULL;
3346         }
3347
3348         if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3349                               &inode->runtime_flags)) {
3350 #if 0
3351                 /*
3352                  * For proper ENOSPC handling, we should do orphan
3353                  * cleanup when mounting. But this introduces backward
3354                  * compatibility issue.
3355                  */
3356                 if (!xchg(&root->orphan_item_inserted, 1))
3357                         insert = 2;
3358                 else
3359                         insert = 1;
3360 #endif
3361                 insert = 1;
3362                 atomic_inc(&root->orphan_inodes);
3363         }
3364
3365         if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3366                               &inode->runtime_flags))
3367                 reserve = 1;
3368         spin_unlock(&root->orphan_lock);
3369
3370         /* grab metadata reservation from transaction handle */
3371         if (reserve) {
3372                 ret = btrfs_orphan_reserve_metadata(trans, inode);
3373                 ASSERT(!ret);
3374                 if (ret) {
3375                         atomic_dec(&root->orphan_inodes);
3376                         clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3377                                   &inode->runtime_flags);
3378                         if (insert)
3379                                 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3380                                           &inode->runtime_flags);
3381                         return ret;
3382                 }
3383         }
3384
3385         /* insert an orphan item to track this unlinked/truncated file */
3386         if (insert >= 1) {
3387                 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3388                 if (ret) {
3389                         atomic_dec(&root->orphan_inodes);
3390                         if (reserve) {
3391                                 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3392                                           &inode->runtime_flags);
3393                                 btrfs_orphan_release_metadata(inode);
3394                         }
3395                         if (ret != -EEXIST) {
3396                                 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3397                                           &inode->runtime_flags);
3398                                 btrfs_abort_transaction(trans, ret);
3399                                 return ret;
3400                         }
3401                 }
3402                 ret = 0;
3403         }
3404
3405         /* insert an orphan item to track subvolume contains orphan files */
3406         if (insert >= 2) {
3407                 ret = btrfs_insert_orphan_item(trans, fs_info->tree_root,
3408                                                root->root_key.objectid);
3409                 if (ret && ret != -EEXIST) {
3410                         btrfs_abort_transaction(trans, ret);
3411                         return ret;
3412                 }
3413         }
3414         return 0;
3415 }
3416
3417 /*
3418  * We have done the truncate/delete so we can go ahead and remove the orphan
3419  * item for this particular inode.
3420  */
3421 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3422                             struct btrfs_inode *inode)
3423 {
3424         struct btrfs_root *root = inode->root;
3425         int delete_item = 0;
3426         int release_rsv = 0;
3427         int ret = 0;
3428
3429         spin_lock(&root->orphan_lock);
3430         if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3431                                &inode->runtime_flags))
3432                 delete_item = 1;
3433
3434         if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3435                                &inode->runtime_flags))
3436                 release_rsv = 1;
3437         spin_unlock(&root->orphan_lock);
3438
3439         if (delete_item) {
3440                 atomic_dec(&root->orphan_inodes);
3441                 if (trans)
3442                         ret = btrfs_del_orphan_item(trans, root,
3443                                                     btrfs_ino(inode));
3444         }
3445
3446         if (release_rsv)
3447                 btrfs_orphan_release_metadata(inode);
3448
3449         return ret;
3450 }
3451
3452 /*
3453  * this cleans up any orphans that may be left on the list from the last use
3454  * of this root.
3455  */
3456 int btrfs_orphan_cleanup(struct btrfs_root *root)
3457 {
3458         struct btrfs_fs_info *fs_info = root->fs_info;
3459         struct btrfs_path *path;
3460         struct extent_buffer *leaf;
3461         struct btrfs_key key, found_key;
3462         struct btrfs_trans_handle *trans;
3463         struct inode *inode;
3464         u64 last_objectid = 0;
3465         int ret = 0, nr_unlink = 0, nr_truncate = 0;
3466
3467         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3468                 return 0;
3469
3470         path = btrfs_alloc_path();
3471         if (!path) {
3472                 ret = -ENOMEM;
3473                 goto out;
3474         }
3475         path->reada = READA_BACK;
3476
3477         key.objectid = BTRFS_ORPHAN_OBJECTID;
3478         key.type = BTRFS_ORPHAN_ITEM_KEY;
3479         key.offset = (u64)-1;
3480
3481         while (1) {
3482                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3483                 if (ret < 0)
3484                         goto out;
3485
3486                 /*
3487                  * if ret == 0 means we found what we were searching for, which
3488                  * is weird, but possible, so only screw with path if we didn't
3489                  * find the key and see if we have stuff that matches
3490                  */
3491                 if (ret > 0) {
3492                         ret = 0;
3493                         if (path->slots[0] == 0)
3494                                 break;
3495                         path->slots[0]--;
3496                 }
3497
3498                 /* pull out the item */
3499                 leaf = path->nodes[0];
3500                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3501
3502                 /* make sure the item matches what we want */
3503                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3504                         break;
3505                 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3506                         break;
3507
3508                 /* release the path since we're done with it */
3509                 btrfs_release_path(path);
3510
3511                 /*
3512                  * this is where we are basically btrfs_lookup, without the
3513                  * crossing root thing.  we store the inode number in the
3514                  * offset of the orphan item.
3515                  */
3516
3517                 if (found_key.offset == last_objectid) {
3518                         btrfs_err(fs_info,
3519                                   "Error removing orphan entry, stopping orphan cleanup");
3520                         ret = -EINVAL;
3521                         goto out;
3522                 }
3523
3524                 last_objectid = found_key.offset;
3525
3526                 found_key.objectid = found_key.offset;
3527                 found_key.type = BTRFS_INODE_ITEM_KEY;
3528                 found_key.offset = 0;
3529                 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3530                 ret = PTR_ERR_OR_ZERO(inode);
3531                 if (ret && ret != -ENOENT)
3532                         goto out;
3533
3534                 if (ret == -ENOENT && root == fs_info->tree_root) {
3535                         struct btrfs_root *dead_root;
3536                         struct btrfs_fs_info *fs_info = root->fs_info;
3537                         int is_dead_root = 0;
3538
3539                         /*
3540                          * this is an orphan in the tree root. Currently these
3541                          * could come from 2 sources:
3542                          *  a) a snapshot deletion in progress
3543                          *  b) a free space cache inode
3544                          * We need to distinguish those two, as the snapshot
3545                          * orphan must not get deleted.
3546                          * find_dead_roots already ran before us, so if this
3547                          * is a snapshot deletion, we should find the root
3548                          * in the dead_roots list
3549                          */
3550                         spin_lock(&fs_info->trans_lock);
3551                         list_for_each_entry(dead_root, &fs_info->dead_roots,
3552                                             root_list) {
3553                                 if (dead_root->root_key.objectid ==
3554                                     found_key.objectid) {
3555                                         is_dead_root = 1;
3556                                         break;
3557                                 }
3558                         }
3559                         spin_unlock(&fs_info->trans_lock);
3560                         if (is_dead_root) {
3561                                 /* prevent this orphan from being found again */
3562                                 key.offset = found_key.objectid - 1;
3563                                 continue;
3564                         }
3565                 }
3566                 /*
3567                  * Inode is already gone but the orphan item is still there,
3568                  * kill the orphan item.
3569                  */
3570                 if (ret == -ENOENT) {
3571                         trans = btrfs_start_transaction(root, 1);
3572                         if (IS_ERR(trans)) {
3573                                 ret = PTR_ERR(trans);
3574                                 goto out;
3575                         }
3576                         btrfs_debug(fs_info, "auto deleting %Lu",
3577                                     found_key.objectid);
3578                         ret = btrfs_del_orphan_item(trans, root,
3579                                                     found_key.objectid);
3580                         btrfs_end_transaction(trans);
3581                         if (ret)
3582                                 goto out;
3583                         continue;
3584                 }
3585
3586                 /*
3587                  * add this inode to the orphan list so btrfs_orphan_del does
3588                  * the proper thing when we hit it
3589                  */
3590                 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3591                         &BTRFS_I(inode)->runtime_flags);
3592                 atomic_inc(&root->orphan_inodes);
3593
3594                 /* if we have links, this was a truncate, lets do that */
3595                 if (inode->i_nlink) {
3596                         if (WARN_ON(!S_ISREG(inode->i_mode))) {
3597                                 iput(inode);
3598                                 continue;
3599                         }
3600                         nr_truncate++;
3601
3602                         /* 1 for the orphan item deletion. */
3603                         trans = btrfs_start_transaction(root, 1);
3604                         if (IS_ERR(trans)) {
3605                                 iput(inode);
3606                                 ret = PTR_ERR(trans);
3607                                 goto out;
3608                         }
3609                         ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3610                         btrfs_end_transaction(trans);
3611                         if (ret) {
3612                                 iput(inode);
3613                                 goto out;
3614                         }
3615
3616                         ret = btrfs_truncate(inode);
3617                         if (ret)
3618                                 btrfs_orphan_del(NULL, BTRFS_I(inode));
3619                 } else {
3620                         nr_unlink++;
3621                 }
3622
3623                 /* this will do delete_inode and everything for us */
3624                 iput(inode);
3625                 if (ret)
3626                         goto out;
3627         }
3628         /* release the path since we're done with it */
3629         btrfs_release_path(path);
3630
3631         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3632
3633         if (root->orphan_block_rsv)
3634                 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3635                                         (u64)-1);
3636
3637         if (root->orphan_block_rsv ||
3638             test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3639                 trans = btrfs_join_transaction(root);
3640                 if (!IS_ERR(trans))
3641                         btrfs_end_transaction(trans);
3642         }
3643
3644         if (nr_unlink)
3645                 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3646         if (nr_truncate)
3647                 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3648
3649 out:
3650         if (ret)
3651                 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3652         btrfs_free_path(path);
3653         return ret;
3654 }
3655
3656 /*
3657  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3658  * don't find any xattrs, we know there can't be any acls.
3659  *
3660  * slot is the slot the inode is in, objectid is the objectid of the inode
3661  */
3662 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3663                                           int slot, u64 objectid,
3664                                           int *first_xattr_slot)
3665 {
3666         u32 nritems = btrfs_header_nritems(leaf);
3667         struct btrfs_key found_key;
3668         static u64 xattr_access = 0;
3669         static u64 xattr_default = 0;
3670         int scanned = 0;
3671
3672         if (!xattr_access) {
3673                 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3674                                         strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3675                 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3676                                         strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3677         }
3678
3679         slot++;
3680         *first_xattr_slot = -1;
3681         while (slot < nritems) {
3682                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3683
3684                 /* we found a different objectid, there must not be acls */
3685                 if (found_key.objectid != objectid)
3686                         return 0;
3687
3688                 /* we found an xattr, assume we've got an acl */
3689                 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3690                         if (*first_xattr_slot == -1)
3691                                 *first_xattr_slot = slot;
3692                         if (found_key.offset == xattr_access ||
3693                             found_key.offset == xattr_default)
3694                                 return 1;
3695                 }
3696
3697                 /*
3698                  * we found a key greater than an xattr key, there can't
3699                  * be any acls later on
3700                  */
3701                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3702                         return 0;
3703
3704                 slot++;
3705                 scanned++;
3706
3707                 /*
3708                  * it goes inode, inode backrefs, xattrs, extents,
3709                  * so if there are a ton of hard links to an inode there can
3710                  * be a lot of backrefs.  Don't waste time searching too hard,
3711                  * this is just an optimization
3712                  */
3713                 if (scanned >= 8)
3714                         break;
3715         }
3716         /* we hit the end of the leaf before we found an xattr or
3717          * something larger than an xattr.  We have to assume the inode
3718          * has acls
3719          */
3720         if (*first_xattr_slot == -1)
3721                 *first_xattr_slot = slot;
3722         return 1;
3723 }
3724
3725 /*
3726  * read an inode from the btree into the in-memory inode
3727  */
3728 static int btrfs_read_locked_inode(struct inode *inode)
3729 {
3730         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3731         struct btrfs_path *path;
3732         struct extent_buffer *leaf;
3733         struct btrfs_inode_item *inode_item;
3734         struct btrfs_root *root = BTRFS_I(inode)->root;
3735         struct btrfs_key location;
3736         unsigned long ptr;
3737         int maybe_acls;
3738         u32 rdev;
3739         int ret;
3740         bool filled = false;
3741         int first_xattr_slot;
3742
3743         ret = btrfs_fill_inode(inode, &rdev);
3744         if (!ret)
3745                 filled = true;
3746
3747         path = btrfs_alloc_path();
3748         if (!path) {
3749                 ret = -ENOMEM;
3750                 goto make_bad;
3751         }
3752
3753         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3754
3755         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3756         if (ret) {
3757                 if (ret > 0)
3758                         ret = -ENOENT;
3759                 goto make_bad;
3760         }
3761
3762         leaf = path->nodes[0];
3763
3764         if (filled)
3765                 goto cache_index;
3766
3767         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3768                                     struct btrfs_inode_item);
3769         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3770         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3771         i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3772         i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3773         btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3774
3775         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3776         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3777
3778         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3779         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3780
3781         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3782         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3783
3784         BTRFS_I(inode)->i_otime.tv_sec =
3785                 btrfs_timespec_sec(leaf, &inode_item->otime);
3786         BTRFS_I(inode)->i_otime.tv_nsec =
3787                 btrfs_timespec_nsec(leaf, &inode_item->otime);
3788
3789         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3790         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3791         BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3792
3793         inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3794         inode->i_generation = BTRFS_I(inode)->generation;
3795         inode->i_rdev = 0;
3796         rdev = btrfs_inode_rdev(leaf, inode_item);
3797
3798         BTRFS_I(inode)->index_cnt = (u64)-1;
3799         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3800
3801 cache_index:
3802         /*
3803          * If we were modified in the current generation and evicted from memory
3804          * and then re-read we need to do a full sync since we don't have any
3805          * idea about which extents were modified before we were evicted from
3806          * cache.
3807          *
3808          * This is required for both inode re-read from disk and delayed inode
3809          * in delayed_nodes_tree.
3810          */
3811         if (BTRFS_I(inode)->last_trans == fs_info->generation)
3812                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3813                         &BTRFS_I(inode)->runtime_flags);
3814
3815         /*
3816          * We don't persist the id of the transaction where an unlink operation
3817          * against the inode was last made. So here we assume the inode might
3818          * have been evicted, and therefore the exact value of last_unlink_trans
3819          * lost, and set it to last_trans to avoid metadata inconsistencies
3820          * between the inode and its parent if the inode is fsync'ed and the log
3821          * replayed. For example, in the scenario:
3822          *
3823          * touch mydir/foo
3824          * ln mydir/foo mydir/bar
3825          * sync
3826          * unlink mydir/bar
3827          * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
3828          * xfs_io -c fsync mydir/foo
3829          * <power failure>
3830          * mount fs, triggers fsync log replay
3831          *
3832          * We must make sure that when we fsync our inode foo we also log its
3833          * parent inode, otherwise after log replay the parent still has the
3834          * dentry with the "bar" name but our inode foo has a link count of 1
3835          * and doesn't have an inode ref with the name "bar" anymore.
3836          *
3837          * Setting last_unlink_trans to last_trans is a pessimistic approach,
3838          * but it guarantees correctness at the expense of occasional full
3839          * transaction commits on fsync if our inode is a directory, or if our
3840          * inode is not a directory, logging its parent unnecessarily.
3841          */
3842         BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3843
3844         path->slots[0]++;
3845         if (inode->i_nlink != 1 ||
3846             path->slots[0] >= btrfs_header_nritems(leaf))
3847                 goto cache_acl;
3848
3849         btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3850         if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3851                 goto cache_acl;
3852
3853         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3854         if (location.type == BTRFS_INODE_REF_KEY) {
3855                 struct btrfs_inode_ref *ref;
3856
3857                 ref = (struct btrfs_inode_ref *)ptr;
3858                 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3859         } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3860                 struct btrfs_inode_extref *extref;
3861
3862                 extref = (struct btrfs_inode_extref *)ptr;
3863                 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3864                                                                      extref);
3865         }
3866 cache_acl:
3867         /*
3868          * try to precache a NULL acl entry for files that don't have
3869          * any xattrs or acls
3870          */
3871         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3872                         btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3873         if (first_xattr_slot != -1) {
3874                 path->slots[0] = first_xattr_slot;
3875                 ret = btrfs_load_inode_props(inode, path);
3876                 if (ret)
3877                         btrfs_err(fs_info,
3878                                   "error loading props for ino %llu (root %llu): %d",
3879                                   btrfs_ino(BTRFS_I(inode)),
3880                                   root->root_key.objectid, ret);
3881         }
3882         btrfs_free_path(path);
3883
3884         if (!maybe_acls)
3885                 cache_no_acl(inode);
3886
3887         switch (inode->i_mode & S_IFMT) {
3888         case S_IFREG:
3889                 inode->i_mapping->a_ops = &btrfs_aops;
3890                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3891                 inode->i_fop = &btrfs_file_operations;
3892                 inode->i_op = &btrfs_file_inode_operations;
3893                 break;
3894         case S_IFDIR:
3895                 inode->i_fop = &btrfs_dir_file_operations;
3896                 inode->i_op = &btrfs_dir_inode_operations;
3897                 break;
3898         case S_IFLNK:
3899                 inode->i_op = &btrfs_symlink_inode_operations;
3900                 inode_nohighmem(inode);
3901                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3902                 break;
3903         default:
3904                 inode->i_op = &btrfs_special_inode_operations;
3905                 init_special_inode(inode, inode->i_mode, rdev);
3906                 break;
3907         }
3908
3909         btrfs_update_iflags(inode);
3910         return 0;
3911
3912 make_bad:
3913         btrfs_free_path(path);
3914         make_bad_inode(inode);
3915         return ret;
3916 }
3917
3918 /*
3919  * given a leaf and an inode, copy the inode fields into the leaf
3920  */
3921 static void fill_inode_item(struct btrfs_trans_handle *trans,
3922                             struct extent_buffer *leaf,
3923                             struct btrfs_inode_item *item,
3924                             struct inode *inode)
3925 {
3926         struct btrfs_map_token token;
3927
3928         btrfs_init_map_token(&token);
3929
3930         btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3931         btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3932         btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3933                                    &token);
3934         btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3935         btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3936
3937         btrfs_set_token_timespec_sec(leaf, &item->atime,
3938                                      inode->i_atime.tv_sec, &token);
3939         btrfs_set_token_timespec_nsec(leaf, &item->atime,
3940                                       inode->i_atime.tv_nsec, &token);
3941
3942         btrfs_set_token_timespec_sec(leaf, &item->mtime,
3943                                      inode->i_mtime.tv_sec, &token);
3944         btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3945                                       inode->i_mtime.tv_nsec, &token);
3946
3947         btrfs_set_token_timespec_sec(leaf, &item->ctime,
3948                                      inode->i_ctime.tv_sec, &token);
3949         btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3950                                       inode->i_ctime.tv_nsec, &token);
3951
3952         btrfs_set_token_timespec_sec(leaf, &item->otime,
3953                                      BTRFS_I(inode)->i_otime.tv_sec, &token);
3954         btrfs_set_token_timespec_nsec(leaf, &item->otime,
3955                                       BTRFS_I(inode)->i_otime.tv_nsec, &token);
3956
3957         btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3958                                      &token);
3959         btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3960                                          &token);
3961         btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3962         btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3963         btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3964         btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3965         btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3966 }
3967
3968 /*
3969  * copy everything in the in-memory inode into the btree.
3970  */
3971 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3972                                 struct btrfs_root *root, struct inode *inode)
3973 {
3974         struct btrfs_inode_item *inode_item;
3975         struct btrfs_path *path;
3976         struct extent_buffer *leaf;
3977         int ret;
3978
3979         path = btrfs_alloc_path();
3980         if (!path)
3981                 return -ENOMEM;
3982
3983         path->leave_spinning = 1;
3984         ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3985                                  1);
3986         if (ret) {
3987                 if (ret > 0)
3988                         ret = -ENOENT;
3989                 goto failed;
3990         }
3991
3992         leaf = path->nodes[0];
3993         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3994                                     struct btrfs_inode_item);
3995
3996         fill_inode_item(trans, leaf, inode_item, inode);
3997         btrfs_mark_buffer_dirty(leaf);
3998         btrfs_set_inode_last_trans(trans, inode);
3999         ret = 0;
4000 failed:
4001         btrfs_free_path(path);
4002         return ret;
4003 }
4004
4005 /*
4006  * copy everything in the in-memory inode into the btree.
4007  */
4008 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4009                                 struct btrfs_root *root, struct inode *inode)
4010 {
4011         struct btrfs_fs_info *fs_info = root->fs_info;
4012         int ret;
4013
4014         /*
4015          * If the inode is a free space inode, we can deadlock during commit
4016          * if we put it into the delayed code.
4017          *
4018          * The data relocation inode should also be directly updated
4019          * without delay
4020          */
4021         if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4022             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4023             && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4024                 btrfs_update_root_times(trans, root);
4025
4026                 ret = btrfs_delayed_update_inode(trans, root, inode);
4027                 if (!ret)
4028                         btrfs_set_inode_last_trans(trans, inode);
4029                 return ret;
4030         }
4031
4032         return btrfs_update_inode_item(trans, root, inode);
4033 }
4034
4035 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4036                                          struct btrfs_root *root,
4037                                          struct inode *inode)
4038 {
4039         int ret;
4040
4041         ret = btrfs_update_inode(trans, root, inode);
4042         if (ret == -ENOSPC)
4043                 return btrfs_update_inode_item(trans, root, inode);
4044         return ret;
4045 }
4046
4047 /*
4048  * unlink helper that gets used here in inode.c and in the tree logging
4049  * recovery code.  It remove a link in a directory with a given name, and
4050  * also drops the back refs in the inode to the directory
4051  */
4052 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4053                                 struct btrfs_root *root,
4054                                 struct btrfs_inode *dir,
4055                                 struct btrfs_inode *inode,
4056                                 const char *name, int name_len)
4057 {
4058         struct btrfs_fs_info *fs_info = root->fs_info;
4059         struct btrfs_path *path;
4060         int ret = 0;
4061         struct extent_buffer *leaf;
4062         struct btrfs_dir_item *di;
4063         struct btrfs_key key;
4064         u64 index;
4065         u64 ino = btrfs_ino(inode);
4066         u64 dir_ino = btrfs_ino(dir);
4067
4068         path = btrfs_alloc_path();
4069         if (!path) {
4070                 ret = -ENOMEM;
4071                 goto out;
4072         }
4073
4074         path->leave_spinning = 1;
4075         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4076                                     name, name_len, -1);
4077         if (IS_ERR(di)) {
4078                 ret = PTR_ERR(di);
4079                 goto err;
4080         }
4081         if (!di) {
4082                 ret = -ENOENT;
4083                 goto err;
4084         }
4085         leaf = path->nodes[0];
4086         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4087         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4088         if (ret)
4089                 goto err;
4090         btrfs_release_path(path);
4091
4092         /*
4093          * If we don't have dir index, we have to get it by looking up
4094          * the inode ref, since we get the inode ref, remove it directly,
4095          * it is unnecessary to do delayed deletion.
4096          *
4097          * But if we have dir index, needn't search inode ref to get it.
4098          * Since the inode ref is close to the inode item, it is better
4099          * that we delay to delete it, and just do this deletion when
4100          * we update the inode item.
4101          */
4102         if (inode->dir_index) {
4103                 ret = btrfs_delayed_delete_inode_ref(inode);
4104                 if (!ret) {
4105                         index = inode->dir_index;
4106                         goto skip_backref;
4107                 }
4108         }
4109
4110         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4111                                   dir_ino, &index);
4112         if (ret) {
4113                 btrfs_info(fs_info,
4114                         "failed to delete reference to %.*s, inode %llu parent %llu",
4115                         name_len, name, ino, dir_ino);
4116                 btrfs_abort_transaction(trans, ret);
4117                 goto err;
4118         }
4119 skip_backref:
4120         ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4121         if (ret) {
4122                 btrfs_abort_transaction(trans, ret);
4123                 goto err;
4124         }
4125
4126         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4127                         dir_ino);
4128         if (ret != 0 && ret != -ENOENT) {
4129                 btrfs_abort_transaction(trans, ret);
4130                 goto err;
4131         }
4132
4133         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4134                         index);
4135         if (ret == -ENOENT)
4136                 ret = 0;
4137         else if (ret)
4138                 btrfs_abort_transaction(trans, ret);
4139 err:
4140         btrfs_free_path(path);
4141         if (ret)
4142                 goto out;
4143
4144         btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4145         inode_inc_iversion(&inode->vfs_inode);
4146         inode_inc_iversion(&dir->vfs_inode);
4147         inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4148                 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4149         ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4150 out:
4151         return ret;
4152 }
4153
4154 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4155                        struct btrfs_root *root,
4156                        struct btrfs_inode *dir, struct btrfs_inode *inode,
4157                        const char *name, int name_len)
4158 {
4159         int ret;
4160         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4161         if (!ret) {
4162                 drop_nlink(&inode->vfs_inode);
4163                 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4164         }
4165         return ret;
4166 }
4167
4168 /*
4169  * helper to start transaction for unlink and rmdir.
4170  *
4171  * unlink and rmdir are special in btrfs, they do not always free space, so
4172  * if we cannot make our reservations the normal way try and see if there is
4173  * plenty of slack room in the global reserve to migrate, otherwise we cannot
4174  * allow the unlink to occur.
4175  */
4176 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4177 {
4178         struct btrfs_root *root = BTRFS_I(dir)->root;
4179
4180         /*
4181          * 1 for the possible orphan item
4182          * 1 for the dir item
4183          * 1 for the dir index
4184          * 1 for the inode ref
4185          * 1 for the inode
4186          */
4187         return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4188 }
4189
4190 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4191 {
4192         struct btrfs_root *root = BTRFS_I(dir)->root;
4193         struct btrfs_trans_handle *trans;
4194         struct inode *inode = d_inode(dentry);
4195         int ret;
4196
4197         trans = __unlink_start_trans(dir);
4198         if (IS_ERR(trans))
4199                 return PTR_ERR(trans);
4200
4201         btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4202                         0);
4203
4204         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4205                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4206                         dentry->d_name.len);
4207         if (ret)
4208                 goto out;
4209
4210         if (inode->i_nlink == 0) {
4211                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4212                 if (ret)
4213                         goto out;
4214         }
4215
4216 out:
4217         btrfs_end_transaction(trans);
4218         btrfs_btree_balance_dirty(root->fs_info);
4219         return ret;
4220 }
4221
4222 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4223                         struct btrfs_root *root,
4224                         struct inode *dir, u64 objectid,
4225                         const char *name, int name_len)
4226 {
4227         struct btrfs_fs_info *fs_info = root->fs_info;
4228         struct btrfs_path *path;
4229         struct extent_buffer *leaf;
4230         struct btrfs_dir_item *di;
4231         struct btrfs_key key;
4232         u64 index;
4233         int ret;
4234         u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4235
4236         path = btrfs_alloc_path();
4237         if (!path)
4238                 return -ENOMEM;
4239
4240         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4241                                    name, name_len, -1);
4242         if (IS_ERR_OR_NULL(di)) {
4243                 if (!di)
4244                         ret = -ENOENT;
4245                 else
4246                         ret = PTR_ERR(di);
4247                 goto out;
4248         }
4249
4250         leaf = path->nodes[0];
4251         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4252         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4253         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4254         if (ret) {
4255                 btrfs_abort_transaction(trans, ret);
4256                 goto out;
4257         }
4258         btrfs_release_path(path);
4259
4260         ret = btrfs_del_root_ref(trans, fs_info, objectid,
4261                                  root->root_key.objectid, dir_ino,
4262                                  &index, name, name_len);
4263         if (ret < 0) {
4264                 if (ret != -ENOENT) {
4265                         btrfs_abort_transaction(trans, ret);
4266                         goto out;
4267                 }
4268                 di = btrfs_search_dir_index_item(root, path, dir_ino,
4269                                                  name, name_len);
4270                 if (IS_ERR_OR_NULL(di)) {
4271                         if (!di)
4272                                 ret = -ENOENT;
4273                         else
4274                                 ret = PTR_ERR(di);
4275                         btrfs_abort_transaction(trans, ret);
4276                         goto out;
4277                 }
4278
4279                 leaf = path->nodes[0];
4280                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4281                 btrfs_release_path(path);
4282                 index = key.offset;
4283         }
4284         btrfs_release_path(path);
4285
4286         ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4287         if (ret) {
4288                 btrfs_abort_transaction(trans, ret);
4289                 goto out;
4290         }
4291
4292         btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4293         inode_inc_iversion(dir);
4294         dir->i_mtime = dir->i_ctime = current_time(dir);
4295         ret = btrfs_update_inode_fallback(trans, root, dir);
4296         if (ret)
4297                 btrfs_abort_transaction(trans, ret);
4298 out:
4299         btrfs_free_path(path);
4300         return ret;
4301 }
4302
4303 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4304 {
4305         struct inode *inode = d_inode(dentry);
4306         int err = 0;
4307         struct btrfs_root *root = BTRFS_I(dir)->root;
4308         struct btrfs_trans_handle *trans;
4309         u64 last_unlink_trans;
4310
4311         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4312                 return -ENOTEMPTY;
4313         if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4314                 return -EPERM;
4315
4316         trans = __unlink_start_trans(dir);
4317         if (IS_ERR(trans))
4318                 return PTR_ERR(trans);
4319
4320         if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4321                 err = btrfs_unlink_subvol(trans, root, dir,
4322                                           BTRFS_I(inode)->location.objectid,
4323                                           dentry->d_name.name,
4324                                           dentry->d_name.len);
4325                 goto out;
4326         }
4327
4328         err = btrfs_orphan_add(trans, BTRFS_I(inode));
4329         if (err)
4330                 goto out;
4331
4332         last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4333
4334         /* now the directory is empty */
4335         err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4336                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4337                         dentry->d_name.len);
4338         if (!err) {
4339                 btrfs_i_size_write(BTRFS_I(inode), 0);
4340                 /*
4341                  * Propagate the last_unlink_trans value of the deleted dir to
4342                  * its parent directory. This is to prevent an unrecoverable
4343                  * log tree in the case we do something like this:
4344                  * 1) create dir foo
4345                  * 2) create snapshot under dir foo
4346                  * 3) delete the snapshot
4347                  * 4) rmdir foo
4348                  * 5) mkdir foo
4349                  * 6) fsync foo or some file inside foo
4350                  */
4351                 if (last_unlink_trans >= trans->transid)
4352                         BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4353         }
4354 out:
4355         btrfs_end_transaction(trans);
4356         btrfs_btree_balance_dirty(root->fs_info);
4357
4358         return err;
4359 }
4360
4361 static int truncate_space_check(struct btrfs_trans_handle *trans,
4362                                 struct btrfs_root *root,
4363                                 u64 bytes_deleted)
4364 {
4365         struct btrfs_fs_info *fs_info = root->fs_info;
4366         int ret;
4367
4368         /*
4369          * This is only used to apply pressure to the enospc system, we don't
4370          * intend to use this reservation at all.
4371          */
4372         bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4373         bytes_deleted *= fs_info->nodesize;
4374         ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4375                                   bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4376         if (!ret) {
4377                 trace_btrfs_space_reservation(fs_info, "transaction",
4378                                               trans->transid,
4379                                               bytes_deleted, 1);
4380                 trans->bytes_reserved += bytes_deleted;
4381         }
4382         return ret;
4383
4384 }
4385
4386 /*
4387  * Return this if we need to call truncate_block for the last bit of the
4388  * truncate.
4389  */
4390 #define NEED_TRUNCATE_BLOCK 1
4391
4392 /*
4393  * this can truncate away extent items, csum items and directory items.
4394  * It starts at a high offset and removes keys until it can't find
4395  * any higher than new_size
4396  *
4397  * csum items that cross the new i_size are truncated to the new size
4398  * as well.
4399  *
4400  * min_type is the minimum key type to truncate down to.  If set to 0, this
4401  * will kill all the items on this inode, including the INODE_ITEM_KEY.
4402  */
4403 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4404                                struct btrfs_root *root,
4405                                struct inode *inode,
4406                                u64 new_size, u32 min_type)
4407 {
4408         struct btrfs_fs_info *fs_info = root->fs_info;
4409         struct btrfs_path *path;
4410         struct extent_buffer *leaf;
4411         struct btrfs_file_extent_item *fi;
4412         struct btrfs_key key;
4413         struct btrfs_key found_key;
4414         u64 extent_start = 0;
4415         u64 extent_num_bytes = 0;
4416         u64 extent_offset = 0;
4417         u64 item_end = 0;
4418         u64 last_size = new_size;
4419         u32 found_type = (u8)-1;
4420         int found_extent;
4421         int del_item;
4422         int pending_del_nr = 0;
4423         int pending_del_slot = 0;
4424         int extent_type = -1;
4425         int ret;
4426         int err = 0;
4427         u64 ino = btrfs_ino(BTRFS_I(inode));
4428         u64 bytes_deleted = 0;
4429         bool be_nice = false;
4430         bool should_throttle = false;
4431         bool should_end = false;
4432
4433         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4434
4435         /*
4436          * for non-free space inodes and ref cows, we want to back off from
4437          * time to time
4438          */
4439         if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4440             test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4441                 be_nice = true;
4442
4443         path = btrfs_alloc_path();
4444         if (!path)
4445                 return -ENOMEM;
4446         path->reada = READA_BACK;
4447
4448         /*
4449          * We want to drop from the next block forward in case this new size is
4450          * not block aligned since we will be keeping the last block of the
4451          * extent just the way it is.
4452          */
4453         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4454             root == fs_info->tree_root)
4455                 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4456                                         fs_info->sectorsize),
4457                                         (u64)-1, 0);
4458
4459         /*
4460          * This function is also used to drop the items in the log tree before
4461          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4462          * it is used to drop the loged items. So we shouldn't kill the delayed
4463          * items.
4464          */
4465         if (min_type == 0 && root == BTRFS_I(inode)->root)
4466                 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4467
4468         key.objectid = ino;
4469         key.offset = (u64)-1;
4470         key.type = (u8)-1;
4471
4472 search_again:
4473         /*
4474          * with a 16K leaf size and 128MB extents, you can actually queue
4475          * up a huge file in a single leaf.  Most of the time that
4476          * bytes_deleted is > 0, it will be huge by the time we get here
4477          */
4478         if (be_nice && bytes_deleted > SZ_32M) {
4479                 if (btrfs_should_end_transaction(trans)) {
4480                         err = -EAGAIN;
4481                         goto error;
4482                 }
4483         }
4484
4485
4486         path->leave_spinning = 1;
4487         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4488         if (ret < 0) {
4489                 err = ret;
4490                 goto out;
4491         }
4492
4493         if (ret > 0) {
4494                 /* there are no items in the tree for us to truncate, we're
4495                  * done
4496                  */
4497                 if (path->slots[0] == 0)
4498                         goto out;
4499                 path->slots[0]--;
4500         }
4501
4502         while (1) {
4503                 fi = NULL;
4504                 leaf = path->nodes[0];
4505                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4506                 found_type = found_key.type;
4507
4508                 if (found_key.objectid != ino)
4509                         break;
4510
4511                 if (found_type < min_type)
4512                         break;
4513
4514                 item_end = found_key.offset;
4515                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4516                         fi = btrfs_item_ptr(leaf, path->slots[0],
4517                                             struct btrfs_file_extent_item);
4518                         extent_type = btrfs_file_extent_type(leaf, fi);
4519                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4520                                 item_end +=
4521                                     btrfs_file_extent_num_bytes(leaf, fi);
4522
4523                                 trace_btrfs_truncate_show_fi_regular(
4524                                         BTRFS_I(inode), leaf, fi,
4525                                         found_key.offset);
4526                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4527                                 item_end += btrfs_file_extent_inline_len(leaf,
4528                                                          path->slots[0], fi);
4529
4530                                 trace_btrfs_truncate_show_fi_inline(
4531                                         BTRFS_I(inode), leaf, fi, path->slots[0],
4532                                         found_key.offset);
4533                         }
4534                         item_end--;
4535                 }
4536                 if (found_type > min_type) {
4537                         del_item = 1;
4538                 } else {
4539                         if (item_end < new_size)
4540                                 break;
4541                         if (found_key.offset >= new_size)
4542                                 del_item = 1;
4543                         else
4544                                 del_item = 0;
4545                 }
4546                 found_extent = 0;
4547                 /* FIXME, shrink the extent if the ref count is only 1 */
4548                 if (found_type != BTRFS_EXTENT_DATA_KEY)
4549                         goto delete;
4550
4551                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4552                         u64 num_dec;
4553                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4554                         if (!del_item) {
4555                                 u64 orig_num_bytes =
4556                                         btrfs_file_extent_num_bytes(leaf, fi);
4557                                 extent_num_bytes = ALIGN(new_size -
4558                                                 found_key.offset,
4559                                                 fs_info->sectorsize);
4560                                 btrfs_set_file_extent_num_bytes(leaf, fi,
4561                                                          extent_num_bytes);
4562                                 num_dec = (orig_num_bytes -
4563                                            extent_num_bytes);
4564                                 if (test_bit(BTRFS_ROOT_REF_COWS,
4565                                              &root->state) &&
4566                                     extent_start != 0)
4567                                         inode_sub_bytes(inode, num_dec);
4568                                 btrfs_mark_buffer_dirty(leaf);
4569                         } else {
4570                                 extent_num_bytes =
4571                                         btrfs_file_extent_disk_num_bytes(leaf,
4572                                                                          fi);
4573                                 extent_offset = found_key.offset -
4574                                         btrfs_file_extent_offset(leaf, fi);
4575
4576                                 /* FIXME blocksize != 4096 */
4577                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4578                                 if (extent_start != 0) {
4579                                         found_extent = 1;
4580                                         if (test_bit(BTRFS_ROOT_REF_COWS,
4581                                                      &root->state))
4582                                                 inode_sub_bytes(inode, num_dec);
4583                                 }
4584                         }
4585                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4586                         /*
4587                          * we can't truncate inline items that have had
4588                          * special encodings
4589                          */
4590                         if (!del_item &&
4591                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
4592                             btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4593                             btrfs_file_extent_compression(leaf, fi) == 0) {
4594                                 u32 size = (u32)(new_size - found_key.offset);
4595
4596                                 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4597                                 size = btrfs_file_extent_calc_inline_size(size);
4598                                 btrfs_truncate_item(root->fs_info, path, size, 1);
4599                         } else if (!del_item) {
4600                                 /*
4601                                  * We have to bail so the last_size is set to
4602                                  * just before this extent.
4603                                  */
4604                                 err = NEED_TRUNCATE_BLOCK;
4605                                 break;
4606                         }
4607
4608                         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4609                                 inode_sub_bytes(inode, item_end + 1 - new_size);
4610                 }
4611 delete:
4612                 if (del_item)
4613                         last_size = found_key.offset;
4614                 else
4615                         last_size = new_size;
4616                 if (del_item) {
4617                         if (!pending_del_nr) {
4618                                 /* no pending yet, add ourselves */
4619                                 pending_del_slot = path->slots[0];
4620                                 pending_del_nr = 1;
4621                         } else if (pending_del_nr &&
4622                                    path->slots[0] + 1 == pending_del_slot) {
4623                                 /* hop on the pending chunk */
4624                                 pending_del_nr++;
4625                                 pending_del_slot = path->slots[0];
4626                         } else {
4627                                 BUG();
4628                         }
4629                 } else {
4630                         break;
4631                 }
4632                 should_throttle = false;
4633
4634                 if (found_extent &&
4635                     (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4636                      root == fs_info->tree_root)) {
4637                         btrfs_set_path_blocking(path);
4638                         bytes_deleted += extent_num_bytes;
4639                         ret = btrfs_free_extent(trans, root, extent_start,
4640                                                 extent_num_bytes, 0,
4641                                                 btrfs_header_owner(leaf),
4642                                                 ino, extent_offset);
4643                         BUG_ON(ret);
4644                         if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4645                                 btrfs_async_run_delayed_refs(fs_info,
4646                                         trans->delayed_ref_updates * 2,
4647                                         trans->transid, 0);
4648                         if (be_nice) {
4649                                 if (truncate_space_check(trans, root,
4650                                                          extent_num_bytes)) {
4651                                         should_end = true;
4652                                 }
4653                                 if (btrfs_should_throttle_delayed_refs(trans,
4654                                                                        fs_info))
4655                                         should_throttle = true;
4656                         }
4657                 }
4658
4659                 if (found_type == BTRFS_INODE_ITEM_KEY)
4660                         break;
4661
4662                 if (path->slots[0] == 0 ||
4663                     path->slots[0] != pending_del_slot ||
4664                     should_throttle || should_end) {
4665                         if (pending_del_nr) {
4666                                 ret = btrfs_del_items(trans, root, path,
4667                                                 pending_del_slot,
4668                                                 pending_del_nr);
4669                                 if (ret) {
4670                                         btrfs_abort_transaction(trans, ret);
4671                                         goto error;
4672                                 }
4673                                 pending_del_nr = 0;
4674                         }
4675                         btrfs_release_path(path);
4676                         if (should_throttle) {
4677                                 unsigned long updates = trans->delayed_ref_updates;
4678                                 if (updates) {
4679                                         trans->delayed_ref_updates = 0;
4680                                         ret = btrfs_run_delayed_refs(trans,
4681                                                                    fs_info,
4682                                                                    updates * 2);
4683                                         if (ret && !err)
4684                                                 err = ret;
4685                                 }
4686                         }
4687                         /*
4688                          * if we failed to refill our space rsv, bail out
4689                          * and let the transaction restart
4690                          */
4691                         if (should_end) {
4692                                 err = -EAGAIN;
4693                                 goto error;
4694                         }
4695                         goto search_again;
4696                 } else {
4697                         path->slots[0]--;
4698                 }
4699         }
4700 out:
4701         if (pending_del_nr) {
4702                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4703                                       pending_del_nr);
4704                 if (ret)
4705                         btrfs_abort_transaction(trans, ret);
4706         }
4707 error:
4708         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4709                 ASSERT(last_size >= new_size);
4710                 if (!err && last_size > new_size)
4711                         last_size = new_size;
4712                 btrfs_ordered_update_i_size(inode, last_size, NULL);
4713         }
4714
4715         btrfs_free_path(path);
4716
4717         if (be_nice && bytes_deleted > SZ_32M) {
4718                 unsigned long updates = trans->delayed_ref_updates;
4719                 if (updates) {
4720                         trans->delayed_ref_updates = 0;
4721                         ret = btrfs_run_delayed_refs(trans, fs_info,
4722                                                      updates * 2);
4723                         if (ret && !err)
4724                                 err = ret;
4725                 }
4726         }
4727         return err;
4728 }
4729
4730 /*
4731  * btrfs_truncate_block - read, zero a chunk and write a block
4732  * @inode - inode that we're zeroing
4733  * @from - the offset to start zeroing
4734  * @len - the length to zero, 0 to zero the entire range respective to the
4735  *      offset
4736  * @front - zero up to the offset instead of from the offset on
4737  *
4738  * This will find the block for the "from" offset and cow the block and zero the
4739  * part we want to zero.  This is used with truncate and hole punching.
4740  */
4741 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4742                         int front)
4743 {
4744         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4745         struct address_space *mapping = inode->i_mapping;
4746         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4747         struct btrfs_ordered_extent *ordered;
4748         struct extent_state *cached_state = NULL;
4749         struct extent_changeset *data_reserved = NULL;
4750         char *kaddr;
4751         u32 blocksize = fs_info->sectorsize;
4752         pgoff_t index = from >> PAGE_SHIFT;
4753         unsigned offset = from & (blocksize - 1);
4754         struct page *page;
4755         gfp_t mask = btrfs_alloc_write_mask(mapping);
4756         int ret = 0;
4757         u64 block_start;
4758         u64 block_end;
4759
4760         if ((offset & (blocksize - 1)) == 0 &&
4761             (!len || ((len & (blocksize - 1)) == 0)))
4762                 goto out;
4763
4764         block_start = round_down(from, blocksize);
4765         block_end = block_start + blocksize - 1;
4766
4767         ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4768                                            block_start, blocksize);
4769         if (ret)
4770                 goto out;
4771
4772 again:
4773         page = find_or_create_page(mapping, index, mask);
4774         if (!page) {
4775                 btrfs_delalloc_release_space(inode, data_reserved,
4776                                              block_start, blocksize);
4777                 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4778                 ret = -ENOMEM;
4779                 goto out;
4780         }
4781
4782         if (!PageUptodate(page)) {
4783                 ret = btrfs_readpage(NULL, page);
4784                 lock_page(page);
4785                 if (page->mapping != mapping) {
4786                         unlock_page(page);
4787                         put_page(page);
4788                         goto again;
4789                 }
4790                 if (!PageUptodate(page)) {
4791                         ret = -EIO;
4792                         goto out_unlock;
4793                 }
4794         }
4795         wait_on_page_writeback(page);
4796
4797         lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4798         set_page_extent_mapped(page);
4799
4800         ordered = btrfs_lookup_ordered_extent(inode, block_start);
4801         if (ordered) {
4802                 unlock_extent_cached(io_tree, block_start, block_end,
4803                                      &cached_state, GFP_NOFS);
4804                 unlock_page(page);
4805                 put_page(page);
4806                 btrfs_start_ordered_extent(inode, ordered, 1);
4807                 btrfs_put_ordered_extent(ordered);
4808                 goto again;
4809         }
4810
4811         clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4812                           EXTENT_DIRTY | EXTENT_DELALLOC |
4813                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4814                           0, 0, &cached_state);
4815
4816         ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4817                                         &cached_state, 0);
4818         if (ret) {
4819                 unlock_extent_cached(io_tree, block_start, block_end,
4820                                      &cached_state, GFP_NOFS);
4821                 goto out_unlock;
4822         }
4823
4824         if (offset != blocksize) {
4825                 if (!len)
4826                         len = blocksize - offset;
4827                 kaddr = kmap(page);
4828                 if (front)
4829                         memset(kaddr + (block_start - page_offset(page)),
4830                                 0, offset);
4831                 else
4832                         memset(kaddr + (block_start - page_offset(page)) +  offset,
4833                                 0, len);
4834                 flush_dcache_page(page);
4835                 kunmap(page);
4836         }
4837         ClearPageChecked(page);
4838         set_page_dirty(page);
4839         unlock_extent_cached(io_tree, block_start, block_end, &cached_state,
4840                              GFP_NOFS);
4841
4842 out_unlock:
4843         if (ret)
4844                 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4845                                              blocksize);
4846         btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4847         unlock_page(page);
4848         put_page(page);
4849 out:
4850         extent_changeset_free(data_reserved);
4851         return ret;
4852 }
4853
4854 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4855                              u64 offset, u64 len)
4856 {
4857         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4858         struct btrfs_trans_handle *trans;
4859         int ret;
4860
4861         /*
4862          * Still need to make sure the inode looks like it's been updated so
4863          * that any holes get logged if we fsync.
4864          */
4865         if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4866                 BTRFS_I(inode)->last_trans = fs_info->generation;
4867                 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4868                 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4869                 return 0;
4870         }
4871
4872         /*
4873          * 1 - for the one we're dropping
4874          * 1 - for the one we're adding
4875          * 1 - for updating the inode.
4876          */
4877         trans = btrfs_start_transaction(root, 3);
4878         if (IS_ERR(trans))
4879                 return PTR_ERR(trans);
4880
4881         ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4882         if (ret) {
4883                 btrfs_abort_transaction(trans, ret);
4884                 btrfs_end_transaction(trans);
4885                 return ret;
4886         }
4887
4888         ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4889                         offset, 0, 0, len, 0, len, 0, 0, 0);
4890         if (ret)
4891                 btrfs_abort_transaction(trans, ret);
4892         else
4893                 btrfs_update_inode(trans, root, inode);
4894         btrfs_end_transaction(trans);
4895         return ret;
4896 }
4897
4898 /*
4899  * This function puts in dummy file extents for the area we're creating a hole
4900  * for.  So if we are truncating this file to a larger size we need to insert
4901  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4902  * the range between oldsize and size
4903  */
4904 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4905 {
4906         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4907         struct btrfs_root *root = BTRFS_I(inode)->root;
4908         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4909         struct extent_map *em = NULL;
4910         struct extent_state *cached_state = NULL;
4911         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4912         u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4913         u64 block_end = ALIGN(size, fs_info->sectorsize);
4914         u64 last_byte;
4915         u64 cur_offset;
4916         u64 hole_size;
4917         int err = 0;
4918
4919         /*
4920          * If our size started in the middle of a block we need to zero out the
4921          * rest of the block before we expand the i_size, otherwise we could
4922          * expose stale data.
4923          */
4924         err = btrfs_truncate_block(inode, oldsize, 0, 0);
4925         if (err)
4926                 return err;
4927
4928         if (size <= hole_start)
4929                 return 0;
4930
4931         while (1) {
4932                 struct btrfs_ordered_extent *ordered;
4933
4934                 lock_extent_bits(io_tree, hole_start, block_end - 1,
4935                                  &cached_state);
4936                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
4937                                                      block_end - hole_start);
4938                 if (!ordered)
4939                         break;
4940                 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4941                                      &cached_state, GFP_NOFS);
4942                 btrfs_start_ordered_extent(inode, ordered, 1);
4943                 btrfs_put_ordered_extent(ordered);
4944         }
4945
4946         cur_offset = hole_start;
4947         while (1) {
4948                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4949                                 block_end - cur_offset, 0);
4950                 if (IS_ERR(em)) {
4951                         err = PTR_ERR(em);
4952                         em = NULL;
4953                         break;
4954                 }
4955                 last_byte = min(extent_map_end(em), block_end);
4956                 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4957                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4958                         struct extent_map *hole_em;
4959                         hole_size = last_byte - cur_offset;
4960
4961                         err = maybe_insert_hole(root, inode, cur_offset,
4962                                                 hole_size);
4963                         if (err)
4964                                 break;
4965                         btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4966                                                 cur_offset + hole_size - 1, 0);
4967                         hole_em = alloc_extent_map();
4968                         if (!hole_em) {
4969                                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4970                                         &BTRFS_I(inode)->runtime_flags);
4971                                 goto next;
4972                         }
4973                         hole_em->start = cur_offset;
4974                         hole_em->len = hole_size;
4975                         hole_em->orig_start = cur_offset;
4976
4977                         hole_em->block_start = EXTENT_MAP_HOLE;
4978                         hole_em->block_len = 0;
4979                         hole_em->orig_block_len = 0;
4980                         hole_em->ram_bytes = hole_size;
4981                         hole_em->bdev = fs_info->fs_devices->latest_bdev;
4982                         hole_em->compress_type = BTRFS_COMPRESS_NONE;
4983                         hole_em->generation = fs_info->generation;
4984
4985                         while (1) {
4986                                 write_lock(&em_tree->lock);
4987                                 err = add_extent_mapping(em_tree, hole_em, 1);
4988                                 write_unlock(&em_tree->lock);
4989                                 if (err != -EEXIST)
4990                                         break;
4991                                 btrfs_drop_extent_cache(BTRFS_I(inode),
4992                                                         cur_offset,
4993                                                         cur_offset +
4994                                                         hole_size - 1, 0);
4995                         }
4996                         free_extent_map(hole_em);
4997                 }
4998 next:
4999                 free_extent_map(em);
5000                 em = NULL;
5001                 cur_offset = last_byte;
5002                 if (cur_offset >= block_end)
5003                         break;
5004         }
5005         free_extent_map(em);
5006         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
5007                              GFP_NOFS);
5008         return err;
5009 }
5010
5011 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5012 {
5013         struct btrfs_root *root = BTRFS_I(inode)->root;
5014         struct btrfs_trans_handle *trans;
5015         loff_t oldsize = i_size_read(inode);
5016         loff_t newsize = attr->ia_size;
5017         int mask = attr->ia_valid;
5018         int ret;
5019
5020         /*
5021          * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5022          * special case where we need to update the times despite not having
5023          * these flags set.  For all other operations the VFS set these flags
5024          * explicitly if it wants a timestamp update.
5025          */
5026         if (newsize != oldsize) {
5027                 inode_inc_iversion(inode);
5028                 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5029                         inode->i_ctime = inode->i_mtime =
5030                                 current_time(inode);
5031         }
5032
5033         if (newsize > oldsize) {
5034                 /*
5035                  * Don't do an expanding truncate while snapshotting is ongoing.
5036                  * This is to ensure the snapshot captures a fully consistent
5037                  * state of this file - if the snapshot captures this expanding
5038                  * truncation, it must capture all writes that happened before
5039                  * this truncation.
5040                  */
5041                 btrfs_wait_for_snapshot_creation(root);
5042                 ret = btrfs_cont_expand(inode, oldsize, newsize);
5043                 if (ret) {
5044                         btrfs_end_write_no_snapshotting(root);
5045                         return ret;
5046                 }
5047
5048                 trans = btrfs_start_transaction(root, 1);
5049                 if (IS_ERR(trans)) {
5050                         btrfs_end_write_no_snapshotting(root);
5051                         return PTR_ERR(trans);
5052                 }
5053
5054                 i_size_write(inode, newsize);
5055                 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5056                 pagecache_isize_extended(inode, oldsize, newsize);
5057                 ret = btrfs_update_inode(trans, root, inode);
5058                 btrfs_end_write_no_snapshotting(root);
5059                 btrfs_end_transaction(trans);
5060         } else {
5061
5062                 /*
5063                  * We're truncating a file that used to have good data down to
5064                  * zero. Make sure it gets into the ordered flush list so that
5065                  * any new writes get down to disk quickly.
5066                  */
5067                 if (newsize == 0)
5068                         set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5069                                 &BTRFS_I(inode)->runtime_flags);
5070
5071                 /*
5072                  * 1 for the orphan item we're going to add
5073                  * 1 for the orphan item deletion.
5074                  */
5075                 trans = btrfs_start_transaction(root, 2);
5076                 if (IS_ERR(trans))
5077                         return PTR_ERR(trans);
5078
5079                 /*
5080                  * We need to do this in case we fail at _any_ point during the
5081                  * actual truncate.  Once we do the truncate_setsize we could
5082                  * invalidate pages which forces any outstanding ordered io to
5083                  * be instantly completed which will give us extents that need
5084                  * to be truncated.  If we fail to get an orphan inode down we
5085                  * could have left over extents that were never meant to live,
5086                  * so we need to guarantee from this point on that everything
5087                  * will be consistent.
5088                  */
5089                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5090                 btrfs_end_transaction(trans);
5091                 if (ret)
5092                         return ret;
5093
5094                 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5095                 truncate_setsize(inode, newsize);
5096
5097                 /* Disable nonlocked read DIO to avoid the end less truncate */
5098                 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5099                 inode_dio_wait(inode);
5100                 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5101
5102                 ret = btrfs_truncate(inode);
5103                 if (ret && inode->i_nlink) {
5104                         int err;
5105
5106                         /* To get a stable disk_i_size */
5107                         err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5108                         if (err) {
5109                                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5110                                 return err;
5111                         }
5112
5113                         /*
5114                          * failed to truncate, disk_i_size is only adjusted down
5115                          * as we remove extents, so it should represent the true
5116                          * size of the inode, so reset the in memory size and
5117                          * delete our orphan entry.
5118                          */
5119                         trans = btrfs_join_transaction(root);
5120                         if (IS_ERR(trans)) {
5121                                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5122                                 return ret;
5123                         }
5124                         i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5125                         err = btrfs_orphan_del(trans, BTRFS_I(inode));
5126                         if (err)
5127                                 btrfs_abort_transaction(trans, err);
5128                         btrfs_end_transaction(trans);
5129                 }
5130         }
5131
5132         return ret;
5133 }
5134
5135 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5136 {
5137         struct inode *inode = d_inode(dentry);
5138         struct btrfs_root *root = BTRFS_I(inode)->root;
5139         int err;
5140
5141         if (btrfs_root_readonly(root))
5142                 return -EROFS;
5143
5144         err = setattr_prepare(dentry, attr);
5145         if (err)
5146                 return err;
5147
5148         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5149                 err = btrfs_setsize(inode, attr);
5150                 if (err)
5151                         return err;
5152         }
5153
5154         if (attr->ia_valid) {
5155                 setattr_copy(inode, attr);
5156                 inode_inc_iversion(inode);
5157                 err = btrfs_dirty_inode(inode);
5158
5159                 if (!err && attr->ia_valid & ATTR_MODE)
5160                         err = posix_acl_chmod(inode, inode->i_mode);
5161         }
5162
5163         return err;
5164 }
5165
5166 /*
5167  * While truncating the inode pages during eviction, we get the VFS calling
5168  * btrfs_invalidatepage() against each page of the inode. This is slow because
5169  * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5170  * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5171  * extent_state structures over and over, wasting lots of time.
5172  *
5173  * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5174  * those expensive operations on a per page basis and do only the ordered io
5175  * finishing, while we release here the extent_map and extent_state structures,
5176  * without the excessive merging and splitting.
5177  */
5178 static void evict_inode_truncate_pages(struct inode *inode)
5179 {
5180         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5181         struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5182         struct rb_node *node;
5183
5184         ASSERT(inode->i_state & I_FREEING);
5185         truncate_inode_pages_final(&inode->i_data);
5186
5187         write_lock(&map_tree->lock);
5188         while (!RB_EMPTY_ROOT(&map_tree->map)) {
5189                 struct extent_map *em;
5190
5191                 node = rb_first(&map_tree->map);
5192                 em = rb_entry(node, struct extent_map, rb_node);
5193                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5194                 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5195                 remove_extent_mapping(map_tree, em);
5196                 free_extent_map(em);
5197                 if (need_resched()) {
5198                         write_unlock(&map_tree->lock);
5199                         cond_resched();
5200                         write_lock(&map_tree->lock);
5201                 }
5202         }
5203         write_unlock(&map_tree->lock);
5204
5205         /*
5206          * Keep looping until we have no more ranges in the io tree.
5207          * We can have ongoing bios started by readpages (called from readahead)
5208          * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5209          * still in progress (unlocked the pages in the bio but did not yet
5210          * unlocked the ranges in the io tree). Therefore this means some
5211          * ranges can still be locked and eviction started because before
5212          * submitting those bios, which are executed by a separate task (work
5213          * queue kthread), inode references (inode->i_count) were not taken
5214          * (which would be dropped in the end io callback of each bio).
5215          * Therefore here we effectively end up waiting for those bios and
5216          * anyone else holding locked ranges without having bumped the inode's
5217          * reference count - if we don't do it, when they access the inode's
5218          * io_tree to unlock a range it may be too late, leading to an
5219          * use-after-free issue.
5220          */
5221         spin_lock(&io_tree->lock);
5222         while (!RB_EMPTY_ROOT(&io_tree->state)) {
5223                 struct extent_state *state;
5224                 struct extent_state *cached_state = NULL;
5225                 u64 start;
5226                 u64 end;
5227
5228                 node = rb_first(&io_tree->state);
5229                 state = rb_entry(node, struct extent_state, rb_node);
5230                 start = state->start;
5231                 end = state->end;
5232                 spin_unlock(&io_tree->lock);
5233
5234                 lock_extent_bits(io_tree, start, end, &cached_state);
5235
5236                 /*
5237                  * If still has DELALLOC flag, the extent didn't reach disk,
5238                  * and its reserved space won't be freed by delayed_ref.
5239                  * So we need to free its reserved space here.
5240                  * (Refer to comment in btrfs_invalidatepage, case 2)
5241                  *
5242                  * Note, end is the bytenr of last byte, so we need + 1 here.
5243                  */
5244                 if (state->state & EXTENT_DELALLOC)
5245                         btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5246
5247                 clear_extent_bit(io_tree, start, end,
5248                                  EXTENT_LOCKED | EXTENT_DIRTY |
5249                                  EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5250                                  EXTENT_DEFRAG, 1, 1, &cached_state);
5251
5252                 cond_resched();
5253                 spin_lock(&io_tree->lock);
5254         }
5255         spin_unlock(&io_tree->lock);
5256 }
5257
5258 void btrfs_evict_inode(struct inode *inode)
5259 {
5260         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5261         struct btrfs_trans_handle *trans;
5262         struct btrfs_root *root = BTRFS_I(inode)->root;
5263         struct btrfs_block_rsv *rsv, *global_rsv;
5264         int steal_from_global = 0;
5265         u64 min_size;
5266         int ret;
5267
5268         trace_btrfs_inode_evict(inode);
5269
5270         if (!root) {
5271                 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
5272                 return;
5273         }
5274
5275         min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5276
5277         evict_inode_truncate_pages(inode);
5278
5279         if (inode->i_nlink &&
5280             ((btrfs_root_refs(&root->root_item) != 0 &&
5281               root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5282              btrfs_is_free_space_inode(BTRFS_I(inode))))
5283                 goto no_delete;
5284
5285         if (is_bad_inode(inode)) {
5286                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5287                 goto no_delete;
5288         }
5289         /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5290         if (!special_file(inode->i_mode))
5291                 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5292
5293         btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5294
5295         if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
5296                 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5297                                  &BTRFS_I(inode)->runtime_flags));
5298                 goto no_delete;
5299         }
5300
5301         if (inode->i_nlink > 0) {
5302                 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5303                        root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5304                 goto no_delete;
5305         }
5306
5307         ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5308         if (ret) {
5309                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5310                 goto no_delete;
5311         }
5312
5313         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5314         if (!rsv) {
5315                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5316                 goto no_delete;
5317         }
5318         rsv->size = min_size;
5319         rsv->failfast = 1;
5320         global_rsv = &fs_info->global_block_rsv;
5321
5322         btrfs_i_size_write(BTRFS_I(inode), 0);
5323
5324         /*
5325          * This is a bit simpler than btrfs_truncate since we've already
5326          * reserved our space for our orphan item in the unlink, so we just
5327          * need to reserve some slack space in case we add bytes and update
5328          * inode item when doing the truncate.
5329          */
5330         while (1) {
5331                 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5332                                              BTRFS_RESERVE_FLUSH_LIMIT);
5333
5334                 /*
5335                  * Try and steal from the global reserve since we will
5336                  * likely not use this space anyway, we want to try as
5337                  * hard as possible to get this to work.
5338                  */
5339                 if (ret)
5340                         steal_from_global++;
5341                 else
5342                         steal_from_global = 0;
5343                 ret = 0;
5344
5345                 /*
5346                  * steal_from_global == 0: we reserved stuff, hooray!
5347                  * steal_from_global == 1: we didn't reserve stuff, boo!
5348                  * steal_from_global == 2: we've committed, still not a lot of
5349                  * room but maybe we'll have room in the global reserve this
5350                  * time.
5351                  * steal_from_global == 3: abandon all hope!
5352                  */
5353                 if (steal_from_global > 2) {
5354                         btrfs_warn(fs_info,
5355                                    "Could not get space for a delete, will truncate on mount %d",
5356                                    ret);
5357                         btrfs_orphan_del(NULL, BTRFS_I(inode));
5358                         btrfs_free_block_rsv(fs_info, rsv);
5359                         goto no_delete;
5360                 }
5361
5362                 trans = btrfs_join_transaction(root);
5363                 if (IS_ERR(trans)) {
5364                         btrfs_orphan_del(NULL, BTRFS_I(inode));
5365                         btrfs_free_block_rsv(fs_info, rsv);
5366                         goto no_delete;
5367                 }
5368
5369                 /*
5370                  * We can't just steal from the global reserve, we need to make
5371                  * sure there is room to do it, if not we need to commit and try
5372                  * again.
5373                  */
5374                 if (steal_from_global) {
5375                         if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5376                                 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5377                                                               min_size, 0);
5378                         else
5379                                 ret = -ENOSPC;
5380                 }
5381
5382                 /*
5383                  * Couldn't steal from the global reserve, we have too much
5384                  * pending stuff built up, commit the transaction and try it
5385                  * again.
5386                  */
5387                 if (ret) {
5388                         ret = btrfs_commit_transaction(trans);
5389                         if (ret) {
5390                                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5391                                 btrfs_free_block_rsv(fs_info, rsv);
5392                                 goto no_delete;
5393                         }
5394                         continue;
5395                 } else {
5396                         steal_from_global = 0;
5397                 }
5398
5399                 trans->block_rsv = rsv;
5400
5401                 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5402                 if (ret != -ENOSPC && ret != -EAGAIN)
5403                         break;
5404
5405                 trans->block_rsv = &fs_info->trans_block_rsv;
5406                 btrfs_end_transaction(trans);
5407                 trans = NULL;
5408                 btrfs_btree_balance_dirty(fs_info);
5409         }
5410
5411         btrfs_free_block_rsv(fs_info, rsv);
5412
5413         /*
5414          * Errors here aren't a big deal, it just means we leave orphan items
5415          * in the tree.  They will be cleaned up on the next mount.
5416          */
5417         if (ret == 0) {
5418                 trans->block_rsv = root->orphan_block_rsv;
5419                 btrfs_orphan_del(trans, BTRFS_I(inode));
5420         } else {
5421                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5422         }
5423
5424         trans->block_rsv = &fs_info->trans_block_rsv;
5425         if (!(root == fs_info->tree_root ||
5426               root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5427                 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5428
5429         btrfs_end_transaction(trans);
5430         btrfs_btree_balance_dirty(fs_info);
5431 no_delete:
5432         btrfs_remove_delayed_node(BTRFS_I(inode));
5433         clear_inode(inode);
5434 }
5435
5436 /*
5437  * this returns the key found in the dir entry in the location pointer.
5438  * If no dir entries were found, location->objectid is 0.
5439  */
5440 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5441                                struct btrfs_key *location)
5442 {
5443         const char *name = dentry->d_name.name;
5444         int namelen = dentry->d_name.len;
5445         struct btrfs_dir_item *di;
5446         struct btrfs_path *path;
5447         struct btrfs_root *root = BTRFS_I(dir)->root;
5448         int ret = 0;
5449
5450         path = btrfs_alloc_path();
5451         if (!path)
5452                 return -ENOMEM;
5453
5454         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5455                         name, namelen, 0);
5456         if (IS_ERR(di))
5457                 ret = PTR_ERR(di);
5458
5459         if (IS_ERR_OR_NULL(di))
5460                 goto out_err;
5461
5462         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5463         if (location->type != BTRFS_INODE_ITEM_KEY &&
5464             location->type != BTRFS_ROOT_ITEM_KEY) {
5465                 btrfs_warn(root->fs_info,
5466 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5467                            __func__, name, btrfs_ino(BTRFS_I(dir)),
5468                            location->objectid, location->type, location->offset);
5469                 goto out_err;
5470         }
5471 out:
5472         btrfs_free_path(path);
5473         return ret;
5474 out_err:
5475         location->objectid = 0;
5476         goto out;
5477 }
5478
5479 /*
5480  * when we hit a tree root in a directory, the btrfs part of the inode
5481  * needs to be changed to reflect the root directory of the tree root.  This
5482  * is kind of like crossing a mount point.
5483  */
5484 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5485                                     struct inode *dir,
5486                                     struct dentry *dentry,
5487                                     struct btrfs_key *location,
5488                                     struct btrfs_root **sub_root)
5489 {
5490         struct btrfs_path *path;
5491         struct btrfs_root *new_root;
5492         struct btrfs_root_ref *ref;
5493         struct extent_buffer *leaf;
5494         struct btrfs_key key;
5495         int ret;
5496         int err = 0;
5497
5498         path = btrfs_alloc_path();
5499         if (!path) {
5500                 err = -ENOMEM;
5501                 goto out;
5502         }
5503
5504         err = -ENOENT;
5505         key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5506         key.type = BTRFS_ROOT_REF_KEY;
5507         key.offset = location->objectid;
5508
5509         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5510         if (ret) {
5511                 if (ret < 0)
5512                         err = ret;
5513                 goto out;
5514         }
5515
5516         leaf = path->nodes[0];
5517         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5518         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5519             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5520                 goto out;
5521
5522         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5523                                    (unsigned long)(ref + 1),
5524                                    dentry->d_name.len);
5525         if (ret)
5526                 goto out;
5527
5528         btrfs_release_path(path);
5529
5530         new_root = btrfs_read_fs_root_no_name(fs_info, location);
5531         if (IS_ERR(new_root)) {
5532                 err = PTR_ERR(new_root);
5533                 goto out;
5534         }
5535
5536         *sub_root = new_root;
5537         location->objectid = btrfs_root_dirid(&new_root->root_item);
5538         location->type = BTRFS_INODE_ITEM_KEY;
5539         location->offset = 0;
5540         err = 0;
5541 out:
5542         btrfs_free_path(path);
5543         return err;
5544 }
5545
5546 static void inode_tree_add(struct inode *inode)
5547 {
5548         struct btrfs_root *root = BTRFS_I(inode)->root;
5549         struct btrfs_inode *entry;
5550         struct rb_node **p;
5551         struct rb_node *parent;
5552         struct rb_node *new = &BTRFS_I(inode)->rb_node;
5553         u64 ino = btrfs_ino(BTRFS_I(inode));
5554
5555         if (inode_unhashed(inode))
5556                 return;
5557         parent = NULL;
5558         spin_lock(&root->inode_lock);
5559         p = &root->inode_tree.rb_node;
5560         while (*p) {
5561                 parent = *p;
5562                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5563
5564                 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5565                         p = &parent->rb_left;
5566                 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5567                         p = &parent->rb_right;
5568                 else {
5569                         WARN_ON(!(entry->vfs_inode.i_state &
5570                                   (I_WILL_FREE | I_FREEING)));
5571                         rb_replace_node(parent, new, &root->inode_tree);
5572                         RB_CLEAR_NODE(parent);
5573                         spin_unlock(&root->inode_lock);
5574                         return;
5575                 }
5576         }
5577         rb_link_node(new, parent, p);
5578         rb_insert_color(new, &root->inode_tree);
5579         spin_unlock(&root->inode_lock);
5580 }
5581
5582 static void inode_tree_del(struct inode *inode)
5583 {
5584         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5585         struct btrfs_root *root = BTRFS_I(inode)->root;
5586         int empty = 0;
5587
5588         spin_lock(&root->inode_lock);
5589         if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5590                 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5591                 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5592                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5593         }
5594         spin_unlock(&root->inode_lock);
5595
5596         if (empty && btrfs_root_refs(&root->root_item) == 0) {
5597                 synchronize_srcu(&fs_info->subvol_srcu);
5598                 spin_lock(&root->inode_lock);
5599                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5600                 spin_unlock(&root->inode_lock);
5601                 if (empty)
5602                         btrfs_add_dead_root(root);
5603         }
5604 }
5605
5606 void btrfs_invalidate_inodes(struct btrfs_root *root)
5607 {
5608         struct btrfs_fs_info *fs_info = root->fs_info;
5609         struct rb_node *node;
5610         struct rb_node *prev;
5611         struct btrfs_inode *entry;
5612         struct inode *inode;
5613         u64 objectid = 0;
5614
5615         if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
5616                 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5617
5618         spin_lock(&root->inode_lock);
5619 again:
5620         node = root->inode_tree.rb_node;
5621         prev = NULL;
5622         while (node) {
5623                 prev = node;
5624                 entry = rb_entry(node, struct btrfs_inode, rb_node);
5625
5626                 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5627                         node = node->rb_left;
5628                 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5629                         node = node->rb_right;
5630                 else
5631                         break;
5632         }
5633         if (!node) {
5634                 while (prev) {
5635                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
5636                         if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
5637                                 node = prev;
5638                                 break;
5639                         }
5640                         prev = rb_next(prev);
5641                 }
5642         }
5643         while (node) {
5644                 entry = rb_entry(node, struct btrfs_inode, rb_node);
5645                 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
5646                 inode = igrab(&entry->vfs_inode);
5647                 if (inode) {
5648                         spin_unlock(&root->inode_lock);
5649                         if (atomic_read(&inode->i_count) > 1)
5650                                 d_prune_aliases(inode);
5651                         /*
5652                          * btrfs_drop_inode will have it removed from
5653                          * the inode cache when its usage count
5654                          * hits zero.
5655                          */
5656                         iput(inode);
5657                         cond_resched();
5658                         spin_lock(&root->inode_lock);
5659                         goto again;
5660                 }
5661
5662                 if (cond_resched_lock(&root->inode_lock))
5663                         goto again;
5664
5665                 node = rb_next(node);
5666         }
5667         spin_unlock(&root->inode_lock);
5668 }
5669
5670 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5671 {
5672         struct btrfs_iget_args *args = p;
5673         inode->i_ino = args->location->objectid;
5674         memcpy(&BTRFS_I(inode)->location, args->location,
5675                sizeof(*args->location));
5676         BTRFS_I(inode)->root = args->root;
5677         return 0;
5678 }
5679
5680 static int btrfs_find_actor(struct inode *inode, void *opaque)
5681 {
5682         struct btrfs_iget_args *args = opaque;
5683         return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5684                 args->root == BTRFS_I(inode)->root;
5685 }
5686
5687 static struct inode *btrfs_iget_locked(struct super_block *s,
5688                                        struct btrfs_key *location,
5689                                        struct btrfs_root *root)
5690 {
5691         struct inode *inode;
5692         struct btrfs_iget_args args;
5693         unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5694
5695         args.location = location;
5696         args.root = root;
5697
5698         inode = iget5_locked(s, hashval, btrfs_find_actor,
5699                              btrfs_init_locked_inode,
5700                              (void *)&args);
5701         return inode;
5702 }
5703
5704 /* Get an inode object given its location and corresponding root.
5705  * Returns in *is_new if the inode was read from disk
5706  */
5707 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5708                          struct btrfs_root *root, int *new)
5709 {
5710         struct inode *inode;
5711
5712         inode = btrfs_iget_locked(s, location, root);
5713         if (!inode)
5714                 return ERR_PTR(-ENOMEM);
5715
5716         if (inode->i_state & I_NEW) {
5717                 int ret;
5718
5719                 ret = btrfs_read_locked_inode(inode);
5720                 if (!is_bad_inode(inode)) {
5721                         inode_tree_add(inode);
5722                         unlock_new_inode(inode);
5723                         if (new)
5724                                 *new = 1;
5725                 } else {
5726                         unlock_new_inode(inode);
5727                         iput(inode);
5728                         ASSERT(ret < 0);
5729                         inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5730                 }
5731         }
5732
5733         return inode;
5734 }
5735
5736 static struct inode *new_simple_dir(struct super_block *s,
5737                                     struct btrfs_key *key,
5738                                     struct btrfs_root *root)
5739 {
5740         struct inode *inode = new_inode(s);
5741
5742         if (!inode)
5743                 return ERR_PTR(-ENOMEM);
5744
5745         BTRFS_I(inode)->root = root;
5746         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5747         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5748
5749         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5750         inode->i_op = &btrfs_dir_ro_inode_operations;
5751         inode->i_opflags &= ~IOP_XATTR;
5752         inode->i_fop = &simple_dir_operations;
5753         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5754         inode->i_mtime = current_time(inode);
5755         inode->i_atime = inode->i_mtime;
5756         inode->i_ctime = inode->i_mtime;
5757         BTRFS_I(inode)->i_otime = inode->i_mtime;
5758
5759         return inode;
5760 }
5761
5762 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5763 {
5764         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5765         struct inode *inode;
5766         struct btrfs_root *root = BTRFS_I(dir)->root;
5767         struct btrfs_root *sub_root = root;
5768         struct btrfs_key location;
5769         int index;
5770         int ret = 0;
5771
5772         if (dentry->d_name.len > BTRFS_NAME_LEN)
5773                 return ERR_PTR(-ENAMETOOLONG);
5774
5775         ret = btrfs_inode_by_name(dir, dentry, &location);
5776         if (ret < 0)
5777                 return ERR_PTR(ret);
5778
5779         if (location.objectid == 0)
5780                 return ERR_PTR(-ENOENT);
5781
5782         if (location.type == BTRFS_INODE_ITEM_KEY) {
5783                 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5784                 return inode;
5785         }
5786
5787         index = srcu_read_lock(&fs_info->subvol_srcu);
5788         ret = fixup_tree_root_location(fs_info, dir, dentry,
5789                                        &location, &sub_root);
5790         if (ret < 0) {
5791                 if (ret != -ENOENT)
5792                         inode = ERR_PTR(ret);
5793                 else
5794                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
5795         } else {
5796                 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5797         }
5798         srcu_read_unlock(&fs_info->subvol_srcu, index);
5799
5800         if (!IS_ERR(inode) && root != sub_root) {
5801                 down_read(&fs_info->cleanup_work_sem);
5802                 if (!sb_rdonly(inode->i_sb))
5803                         ret = btrfs_orphan_cleanup(sub_root);
5804                 up_read(&fs_info->cleanup_work_sem);
5805                 if (ret) {
5806                         iput(inode);
5807                         inode = ERR_PTR(ret);
5808                 }
5809         }
5810
5811         return inode;
5812 }
5813
5814 static int btrfs_dentry_delete(const struct dentry *dentry)
5815 {
5816         struct btrfs_root *root;
5817         struct inode *inode = d_inode(dentry);
5818
5819         if (!inode && !IS_ROOT(dentry))
5820                 inode = d_inode(dentry->d_parent);
5821
5822         if (inode) {
5823                 root = BTRFS_I(inode)->root;
5824                 if (btrfs_root_refs(&root->root_item) == 0)
5825                         return 1;
5826
5827                 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5828                         return 1;
5829         }
5830         return 0;
5831 }
5832
5833 static void btrfs_dentry_release(struct dentry *dentry)
5834 {
5835         kfree(dentry->d_fsdata);
5836 }
5837
5838 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5839                                    unsigned int flags)
5840 {
5841         struct inode *inode;
5842
5843         inode = btrfs_lookup_dentry(dir, dentry);
5844         if (IS_ERR(inode)) {
5845                 if (PTR_ERR(inode) == -ENOENT)
5846                         inode = NULL;
5847                 else
5848                         return ERR_CAST(inode);
5849         }
5850
5851         return d_splice_alias(inode, dentry);
5852 }
5853
5854 unsigned char btrfs_filetype_table[] = {
5855         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5856 };
5857
5858 /*
5859  * All this infrastructure exists because dir_emit can fault, and we are holding
5860  * the tree lock when doing readdir.  For now just allocate a buffer and copy
5861  * our information into that, and then dir_emit from the buffer.  This is
5862  * similar to what NFS does, only we don't keep the buffer around in pagecache
5863  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
5864  * copy_to_user_inatomic so we don't have to worry about page faulting under the
5865  * tree lock.
5866  */
5867 static int btrfs_opendir(struct inode *inode, struct file *file)
5868 {
5869         struct btrfs_file_private *private;
5870
5871         private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5872         if (!private)
5873                 return -ENOMEM;
5874         private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5875         if (!private->filldir_buf) {
5876                 kfree(private);
5877                 return -ENOMEM;
5878         }
5879         file->private_data = private;
5880         return 0;
5881 }
5882
5883 struct dir_entry {
5884         u64 ino;
5885         u64 offset;
5886         unsigned type;
5887         int name_len;
5888 };
5889
5890 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5891 {
5892         while (entries--) {
5893                 struct dir_entry *entry = addr;
5894                 char *name = (char *)(entry + 1);
5895
5896                 ctx->pos = entry->offset;
5897                 if (!dir_emit(ctx, name, entry->name_len, entry->ino,
5898                               entry->type))
5899                         return 1;
5900                 addr += sizeof(struct dir_entry) + entry->name_len;
5901                 ctx->pos++;
5902         }
5903         return 0;
5904 }
5905
5906 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5907 {
5908         struct inode *inode = file_inode(file);
5909         struct btrfs_root *root = BTRFS_I(inode)->root;
5910         struct btrfs_file_private *private = file->private_data;
5911         struct btrfs_dir_item *di;
5912         struct btrfs_key key;
5913         struct btrfs_key found_key;
5914         struct btrfs_path *path;
5915         void *addr;
5916         struct list_head ins_list;
5917         struct list_head del_list;
5918         int ret;
5919         struct extent_buffer *leaf;
5920         int slot;
5921         char *name_ptr;
5922         int name_len;
5923         int entries = 0;
5924         int total_len = 0;
5925         bool put = false;
5926         struct btrfs_key location;
5927
5928         if (!dir_emit_dots(file, ctx))
5929                 return 0;
5930
5931         path = btrfs_alloc_path();
5932         if (!path)
5933                 return -ENOMEM;
5934
5935         addr = private->filldir_buf;
5936         path->reada = READA_FORWARD;
5937
5938         INIT_LIST_HEAD(&ins_list);
5939         INIT_LIST_HEAD(&del_list);
5940         put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5941
5942 again:
5943         key.type = BTRFS_DIR_INDEX_KEY;
5944         key.offset = ctx->pos;
5945         key.objectid = btrfs_ino(BTRFS_I(inode));
5946
5947         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5948         if (ret < 0)
5949                 goto err;
5950
5951         while (1) {
5952                 struct dir_entry *entry;
5953
5954                 leaf = path->nodes[0];
5955                 slot = path->slots[0];
5956                 if (slot >= btrfs_header_nritems(leaf)) {
5957                         ret = btrfs_next_leaf(root, path);
5958                         if (ret < 0)
5959                                 goto err;
5960                         else if (ret > 0)
5961                                 break;
5962                         continue;
5963                 }
5964
5965                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5966
5967                 if (found_key.objectid != key.objectid)
5968                         break;
5969                 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5970                         break;
5971                 if (found_key.offset < ctx->pos)
5972                         goto next;
5973                 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5974                         goto next;
5975                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5976                 name_len = btrfs_dir_name_len(leaf, di);
5977                 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5978                     PAGE_SIZE) {
5979                         btrfs_release_path(path);
5980                         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5981                         if (ret)
5982                                 goto nopos;
5983                         addr = private->filldir_buf;
5984                         entries = 0;
5985                         total_len = 0;
5986                         goto again;
5987                 }
5988
5989                 entry = addr;
5990                 entry->name_len = name_len;
5991                 name_ptr = (char *)(entry + 1);
5992                 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5993                                    name_len);
5994                 entry->type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5995                 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5996                 entry->ino = location.objectid;
5997                 entry->offset = found_key.offset;
5998                 entries++;
5999                 addr += sizeof(struct dir_entry) + name_len;
6000                 total_len += sizeof(struct dir_entry) + name_len;
6001 next:
6002                 path->slots[0]++;
6003         }
6004         btrfs_release_path(path);
6005
6006         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6007         if (ret)
6008                 goto nopos;
6009
6010         ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6011         if (ret)
6012                 goto nopos;
6013
6014         /*
6015          * Stop new entries from being returned after we return the last
6016          * entry.
6017          *
6018          * New directory entries are assigned a strictly increasing
6019          * offset.  This means that new entries created during readdir
6020          * are *guaranteed* to be seen in the future by that readdir.
6021          * This has broken buggy programs which operate on names as
6022          * they're returned by readdir.  Until we re-use freed offsets
6023          * we have this hack to stop new entries from being returned
6024          * under the assumption that they'll never reach this huge
6025          * offset.
6026          *
6027          * This is being careful not to overflow 32bit loff_t unless the
6028          * last entry requires it because doing so has broken 32bit apps
6029          * in the past.
6030          */
6031         if (ctx->pos >= INT_MAX)
6032                 ctx->pos = LLONG_MAX;
6033         else
6034                 ctx->pos = INT_MAX;
6035 nopos:
6036         ret = 0;
6037 err:
6038         if (put)
6039                 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6040         btrfs_free_path(path);
6041         return ret;
6042 }
6043
6044 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6045 {
6046         struct btrfs_root *root = BTRFS_I(inode)->root;
6047         struct btrfs_trans_handle *trans;
6048         int ret = 0;
6049         bool nolock = false;
6050
6051         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6052                 return 0;
6053
6054         if (btrfs_fs_closing(root->fs_info) &&
6055                         btrfs_is_free_space_inode(BTRFS_I(inode)))
6056                 nolock = true;
6057
6058         if (wbc->sync_mode == WB_SYNC_ALL) {
6059                 if (nolock)
6060                         trans = btrfs_join_transaction_nolock(root);
6061                 else
6062                         trans = btrfs_join_transaction(root);
6063                 if (IS_ERR(trans))
6064                         return PTR_ERR(trans);
6065                 ret = btrfs_commit_transaction(trans);
6066         }
6067         return ret;
6068 }
6069
6070 /*
6071  * This is somewhat expensive, updating the tree every time the
6072  * inode changes.  But, it is most likely to find the inode in cache.
6073  * FIXME, needs more benchmarking...there are no reasons other than performance
6074  * to keep or drop this code.
6075  */
6076 static int btrfs_dirty_inode(struct inode *inode)
6077 {
6078         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6079         struct btrfs_root *root = BTRFS_I(inode)->root;
6080         struct btrfs_trans_handle *trans;
6081         int ret;
6082
6083         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6084                 return 0;
6085
6086         trans = btrfs_join_transaction(root);
6087         if (IS_ERR(trans))
6088                 return PTR_ERR(trans);
6089
6090         ret = btrfs_update_inode(trans, root, inode);
6091         if (ret && ret == -ENOSPC) {
6092                 /* whoops, lets try again with the full transaction */
6093                 btrfs_end_transaction(trans);
6094                 trans = btrfs_start_transaction(root, 1);
6095                 if (IS_ERR(trans))
6096                         return PTR_ERR(trans);
6097
6098                 ret = btrfs_update_inode(trans, root, inode);
6099         }
6100         btrfs_end_transaction(trans);
6101         if (BTRFS_I(inode)->delayed_node)
6102                 btrfs_balance_delayed_items(fs_info);
6103
6104         return ret;
6105 }
6106
6107 /*
6108  * This is a copy of file_update_time.  We need this so we can return error on
6109  * ENOSPC for updating the inode in the case of file write and mmap writes.
6110  */
6111 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6112                              int flags)
6113 {
6114         struct btrfs_root *root = BTRFS_I(inode)->root;
6115
6116         if (btrfs_root_readonly(root))
6117                 return -EROFS;
6118
6119         if (flags & S_VERSION)
6120                 inode_inc_iversion(inode);
6121         if (flags & S_CTIME)
6122                 inode->i_ctime = *now;
6123         if (flags & S_MTIME)
6124                 inode->i_mtime = *now;
6125         if (flags & S_ATIME)
6126                 inode->i_atime = *now;
6127         return btrfs_dirty_inode(inode);
6128 }
6129
6130 /*
6131  * find the highest existing sequence number in a directory
6132  * and then set the in-memory index_cnt variable to reflect
6133  * free sequence numbers
6134  */
6135 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6136 {
6137         struct btrfs_root *root = inode->root;
6138         struct btrfs_key key, found_key;
6139         struct btrfs_path *path;
6140         struct extent_buffer *leaf;
6141         int ret;
6142
6143         key.objectid = btrfs_ino(inode);
6144         key.type = BTRFS_DIR_INDEX_KEY;
6145         key.offset = (u64)-1;
6146
6147         path = btrfs_alloc_path();
6148         if (!path)
6149                 return -ENOMEM;
6150
6151         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6152         if (ret < 0)
6153                 goto out;
6154         /* FIXME: we should be able to handle this */
6155         if (ret == 0)
6156                 goto out;
6157         ret = 0;
6158
6159         /*
6160          * MAGIC NUMBER EXPLANATION:
6161          * since we search a directory based on f_pos we have to start at 2
6162          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6163          * else has to start at 2
6164          */
6165         if (path->slots[0] == 0) {
6166                 inode->index_cnt = 2;
6167                 goto out;
6168         }
6169
6170         path->slots[0]--;
6171
6172         leaf = path->nodes[0];
6173         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6174
6175         if (found_key.objectid != btrfs_ino(inode) ||
6176             found_key.type != BTRFS_DIR_INDEX_KEY) {
6177                 inode->index_cnt = 2;
6178                 goto out;
6179         }
6180
6181         inode->index_cnt = found_key.offset + 1;
6182 out:
6183         btrfs_free_path(path);
6184         return ret;
6185 }
6186
6187 /*
6188  * helper to find a free sequence number in a given directory.  This current
6189  * code is very simple, later versions will do smarter things in the btree
6190  */
6191 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6192 {
6193         int ret = 0;
6194
6195         if (dir->index_cnt == (u64)-1) {
6196                 ret = btrfs_inode_delayed_dir_index_count(dir);
6197                 if (ret) {
6198                         ret = btrfs_set_inode_index_count(dir);
6199                         if (ret)
6200                                 return ret;
6201                 }
6202         }
6203
6204         *index = dir->index_cnt;
6205         dir->index_cnt++;
6206
6207         return ret;
6208 }
6209
6210 static int btrfs_insert_inode_locked(struct inode *inode)
6211 {
6212         struct btrfs_iget_args args;
6213         args.location = &BTRFS_I(inode)->location;
6214         args.root = BTRFS_I(inode)->root;
6215
6216         return insert_inode_locked4(inode,
6217                    btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6218                    btrfs_find_actor, &args);
6219 }
6220
6221 /*
6222  * Inherit flags from the parent inode.
6223  *
6224  * Currently only the compression flags and the cow flags are inherited.
6225  */
6226 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6227 {
6228         unsigned int flags;
6229
6230         if (!dir)
6231                 return;
6232
6233         flags = BTRFS_I(dir)->flags;
6234
6235         if (flags & BTRFS_INODE_NOCOMPRESS) {
6236                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6237                 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6238         } else if (flags & BTRFS_INODE_COMPRESS) {
6239                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6240                 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6241         }
6242
6243         if (flags & BTRFS_INODE_NODATACOW) {
6244                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6245                 if (S_ISREG(inode->i_mode))
6246                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6247         }
6248
6249         btrfs_update_iflags(inode);
6250 }
6251
6252 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6253                                      struct btrfs_root *root,
6254                                      struct inode *dir,
6255                                      const char *name, int name_len,
6256                                      u64 ref_objectid, u64 objectid,
6257                                      umode_t mode, u64 *index)
6258 {
6259         struct btrfs_fs_info *fs_info = root->fs_info;
6260         struct inode *inode;
6261         struct btrfs_inode_item *inode_item;
6262         struct btrfs_key *location;
6263         struct btrfs_path *path;
6264         struct btrfs_inode_ref *ref;
6265         struct btrfs_key key[2];
6266         u32 sizes[2];
6267         int nitems = name ? 2 : 1;
6268         unsigned long ptr;
6269         int ret;
6270
6271         path = btrfs_alloc_path();
6272         if (!path)
6273                 return ERR_PTR(-ENOMEM);
6274
6275         inode = new_inode(fs_info->sb);
6276         if (!inode) {
6277                 btrfs_free_path(path);
6278                 return ERR_PTR(-ENOMEM);
6279         }
6280
6281         /*
6282          * O_TMPFILE, set link count to 0, so that after this point,
6283          * we fill in an inode item with the correct link count.
6284          */
6285         if (!name)
6286                 set_nlink(inode, 0);
6287
6288         /*
6289          * we have to initialize this early, so we can reclaim the inode
6290          * number if we fail afterwards in this function.
6291          */
6292         inode->i_ino = objectid;
6293
6294         if (dir && name) {
6295                 trace_btrfs_inode_request(dir);
6296
6297                 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6298                 if (ret) {
6299                         btrfs_free_path(path);
6300                         iput(inode);
6301                         return ERR_PTR(ret);
6302                 }
6303         } else if (dir) {
6304                 *index = 0;
6305         }
6306         /*
6307          * index_cnt is ignored for everything but a dir,
6308          * btrfs_get_inode_index_count has an explanation for the magic
6309          * number
6310          */
6311         BTRFS_I(inode)->index_cnt = 2;
6312         BTRFS_I(inode)->dir_index = *index;
6313         BTRFS_I(inode)->root = root;
6314         BTRFS_I(inode)->generation = trans->transid;
6315         inode->i_generation = BTRFS_I(inode)->generation;
6316
6317         /*
6318          * We could have gotten an inode number from somebody who was fsynced
6319          * and then removed in this same transaction, so let's just set full
6320          * sync since it will be a full sync anyway and this will blow away the
6321          * old info in the log.
6322          */
6323         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6324
6325         key[0].objectid = objectid;
6326         key[0].type = BTRFS_INODE_ITEM_KEY;
6327         key[0].offset = 0;
6328
6329         sizes[0] = sizeof(struct btrfs_inode_item);
6330
6331         if (name) {
6332                 /*
6333                  * Start new inodes with an inode_ref. This is slightly more
6334                  * efficient for small numbers of hard links since they will
6335                  * be packed into one item. Extended refs will kick in if we
6336                  * add more hard links than can fit in the ref item.
6337                  */
6338                 key[1].objectid = objectid;
6339                 key[1].type = BTRFS_INODE_REF_KEY;
6340                 key[1].offset = ref_objectid;
6341
6342                 sizes[1] = name_len + sizeof(*ref);
6343         }
6344
6345         location = &BTRFS_I(inode)->location;
6346         location->objectid = objectid;
6347         location->offset = 0;
6348         location->type = BTRFS_INODE_ITEM_KEY;
6349
6350         ret = btrfs_insert_inode_locked(inode);
6351         if (ret < 0)
6352                 goto fail;
6353
6354         path->leave_spinning = 1;
6355         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6356         if (ret != 0)
6357                 goto fail_unlock;
6358
6359         inode_init_owner(inode, dir, mode);
6360         inode_set_bytes(inode, 0);
6361
6362         inode->i_mtime = current_time(inode);
6363         inode->i_atime = inode->i_mtime;
6364         inode->i_ctime = inode->i_mtime;
6365         BTRFS_I(inode)->i_otime = inode->i_mtime;
6366
6367         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6368                                   struct btrfs_inode_item);
6369         memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6370                              sizeof(*inode_item));
6371         fill_inode_item(trans, path->nodes[0], inode_item, inode);
6372
6373         if (name) {
6374                 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6375                                      struct btrfs_inode_ref);
6376                 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6377                 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6378                 ptr = (unsigned long)(ref + 1);
6379                 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6380         }
6381
6382         btrfs_mark_buffer_dirty(path->nodes[0]);
6383         btrfs_free_path(path);
6384
6385         btrfs_inherit_iflags(inode, dir);
6386
6387         if (S_ISREG(mode)) {
6388                 if (btrfs_test_opt(fs_info, NODATASUM))
6389                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6390                 if (btrfs_test_opt(fs_info, NODATACOW))
6391                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6392                                 BTRFS_INODE_NODATASUM;
6393         }
6394
6395         inode_tree_add(inode);
6396
6397         trace_btrfs_inode_new(inode);
6398         btrfs_set_inode_last_trans(trans, inode);
6399
6400         btrfs_update_root_times(trans, root);
6401
6402         ret = btrfs_inode_inherit_props(trans, inode, dir);
6403         if (ret)
6404                 btrfs_err(fs_info,
6405                           "error inheriting props for ino %llu (root %llu): %d",
6406                         btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6407
6408         return inode;
6409
6410 fail_unlock:
6411         unlock_new_inode(inode);
6412 fail:
6413         if (dir && name)
6414                 BTRFS_I(dir)->index_cnt--;
6415         btrfs_free_path(path);
6416         iput(inode);
6417         return ERR_PTR(ret);
6418 }
6419
6420 static inline u8 btrfs_inode_type(struct inode *inode)
6421 {
6422         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6423 }
6424
6425 /*
6426  * utility function to add 'inode' into 'parent_inode' with
6427  * a give name and a given sequence number.
6428  * if 'add_backref' is true, also insert a backref from the
6429  * inode to the parent directory.
6430  */
6431 int btrfs_add_link(struct btrfs_trans_handle *trans,
6432                    struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6433                    const char *name, int name_len, int add_backref, u64 index)
6434 {
6435         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6436         int ret = 0;
6437         struct btrfs_key key;
6438         struct btrfs_root *root = parent_inode->root;
6439         u64 ino = btrfs_ino(inode);
6440         u64 parent_ino = btrfs_ino(parent_inode);
6441
6442         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6443                 memcpy(&key, &inode->root->root_key, sizeof(key));
6444         } else {
6445                 key.objectid = ino;
6446                 key.type = BTRFS_INODE_ITEM_KEY;
6447                 key.offset = 0;
6448         }
6449
6450         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6451                 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6452                                          root->root_key.objectid, parent_ino,
6453                                          index, name, name_len);
6454         } else if (add_backref) {
6455                 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6456                                              parent_ino, index);
6457         }
6458
6459         /* Nothing to clean up yet */
6460         if (ret)
6461                 return ret;
6462
6463         ret = btrfs_insert_dir_item(trans, root, name, name_len,
6464                                     parent_inode, &key,
6465                                     btrfs_inode_type(&inode->vfs_inode), index);
6466         if (ret == -EEXIST || ret == -EOVERFLOW)
6467                 goto fail_dir_item;
6468         else if (ret) {
6469                 btrfs_abort_transaction(trans, ret);
6470                 return ret;
6471         }
6472
6473         btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6474                            name_len * 2);
6475         inode_inc_iversion(&parent_inode->vfs_inode);
6476         parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6477                 current_time(&parent_inode->vfs_inode);
6478         ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6479         if (ret)
6480                 btrfs_abort_transaction(trans, ret);
6481         return ret;
6482
6483 fail_dir_item:
6484         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6485                 u64 local_index;
6486                 int err;
6487                 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6488                                          root->root_key.objectid, parent_ino,
6489                                          &local_index, name, name_len);
6490
6491         } else if (add_backref) {
6492                 u64 local_index;
6493                 int err;
6494
6495                 err = btrfs_del_inode_ref(trans, root, name, name_len,
6496                                           ino, parent_ino, &local_index);
6497         }
6498         return ret;
6499 }
6500
6501 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6502                             struct btrfs_inode *dir, struct dentry *dentry,
6503                             struct btrfs_inode *inode, int backref, u64 index)
6504 {
6505         int err = btrfs_add_link(trans, dir, inode,
6506                                  dentry->d_name.name, dentry->d_name.len,
6507                                  backref, index);
6508         if (err > 0)
6509                 err = -EEXIST;
6510         return err;
6511 }
6512
6513 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6514                         umode_t mode, dev_t rdev)
6515 {
6516         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6517         struct btrfs_trans_handle *trans;
6518         struct btrfs_root *root = BTRFS_I(dir)->root;
6519         struct inode *inode = NULL;
6520         int err;
6521         int drop_inode = 0;
6522         u64 objectid;
6523         u64 index = 0;
6524
6525         /*
6526          * 2 for inode item and ref
6527          * 2 for dir items
6528          * 1 for xattr if selinux is on
6529          */
6530         trans = btrfs_start_transaction(root, 5);
6531         if (IS_ERR(trans))
6532                 return PTR_ERR(trans);
6533
6534         err = btrfs_find_free_ino(root, &objectid);
6535         if (err)
6536                 goto out_unlock;
6537
6538         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6539                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6540                         mode, &index);
6541         if (IS_ERR(inode)) {
6542                 err = PTR_ERR(inode);
6543                 goto out_unlock;
6544         }
6545
6546         /*
6547         * If the active LSM wants to access the inode during
6548         * d_instantiate it needs these. Smack checks to see
6549         * if the filesystem supports xattrs by looking at the
6550         * ops vector.
6551         */
6552         inode->i_op = &btrfs_special_inode_operations;
6553         init_special_inode(inode, inode->i_mode, rdev);
6554
6555         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6556         if (err)
6557                 goto out_unlock_inode;
6558
6559         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6560                         0, index);
6561         if (err) {
6562                 goto out_unlock_inode;
6563         } else {
6564                 btrfs_update_inode(trans, root, inode);
6565                 unlock_new_inode(inode);
6566                 d_instantiate(dentry, inode);
6567         }
6568
6569 out_unlock:
6570         btrfs_end_transaction(trans);
6571         btrfs_btree_balance_dirty(fs_info);
6572         if (drop_inode) {
6573                 inode_dec_link_count(inode);
6574                 iput(inode);
6575         }
6576         return err;
6577
6578 out_unlock_inode:
6579         drop_inode = 1;
6580         unlock_new_inode(inode);
6581         goto out_unlock;
6582
6583 }
6584
6585 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6586                         umode_t mode, bool excl)
6587 {
6588         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6589         struct btrfs_trans_handle *trans;
6590         struct btrfs_root *root = BTRFS_I(dir)->root;
6591         struct inode *inode = NULL;
6592         int drop_inode_on_err = 0;
6593         int err;
6594         u64 objectid;
6595         u64 index = 0;
6596
6597         /*
6598          * 2 for inode item and ref
6599          * 2 for dir items
6600          * 1 for xattr if selinux is on
6601          */
6602         trans = btrfs_start_transaction(root, 5);
6603         if (IS_ERR(trans))
6604                 return PTR_ERR(trans);
6605
6606         err = btrfs_find_free_ino(root, &objectid);
6607         if (err)
6608                 goto out_unlock;
6609
6610         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6611                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6612                         mode, &index);
6613         if (IS_ERR(inode)) {
6614                 err = PTR_ERR(inode);
6615                 goto out_unlock;
6616         }
6617         drop_inode_on_err = 1;
6618         /*
6619         * If the active LSM wants to access the inode during
6620         * d_instantiate it needs these. Smack checks to see
6621         * if the filesystem supports xattrs by looking at the
6622         * ops vector.
6623         */
6624         inode->i_fop = &btrfs_file_operations;
6625         inode->i_op = &btrfs_file_inode_operations;
6626         inode->i_mapping->a_ops = &btrfs_aops;
6627
6628         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6629         if (err)
6630                 goto out_unlock_inode;
6631
6632         err = btrfs_update_inode(trans, root, inode);
6633         if (err)
6634                 goto out_unlock_inode;
6635
6636         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6637                         0, index);
6638         if (err)
6639                 goto out_unlock_inode;
6640
6641         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6642         unlock_new_inode(inode);
6643         d_instantiate(dentry, inode);
6644
6645 out_unlock:
6646         btrfs_end_transaction(trans);
6647         if (err && drop_inode_on_err) {
6648                 inode_dec_link_count(inode);
6649                 iput(inode);
6650         }
6651         btrfs_btree_balance_dirty(fs_info);
6652         return err;
6653
6654 out_unlock_inode:
6655         unlock_new_inode(inode);
6656         goto out_unlock;
6657
6658 }
6659
6660 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6661                       struct dentry *dentry)
6662 {
6663         struct btrfs_trans_handle *trans = NULL;
6664         struct btrfs_root *root = BTRFS_I(dir)->root;
6665         struct inode *inode = d_inode(old_dentry);
6666         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6667         u64 index;
6668         int err;
6669         int drop_inode = 0;
6670
6671         /* do not allow sys_link's with other subvols of the same device */
6672         if (root->objectid != BTRFS_I(inode)->root->objectid)
6673                 return -EXDEV;
6674
6675         if (inode->i_nlink >= BTRFS_LINK_MAX)
6676                 return -EMLINK;
6677
6678         err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6679         if (err)
6680                 goto fail;
6681
6682         /*
6683          * 2 items for inode and inode ref
6684          * 2 items for dir items
6685          * 1 item for parent inode
6686          */
6687         trans = btrfs_start_transaction(root, 5);
6688         if (IS_ERR(trans)) {
6689                 err = PTR_ERR(trans);
6690                 trans = NULL;
6691                 goto fail;
6692         }
6693
6694         /* There are several dir indexes for this inode, clear the cache. */
6695         BTRFS_I(inode)->dir_index = 0ULL;
6696         inc_nlink(inode);
6697         inode_inc_iversion(inode);
6698         inode->i_ctime = current_time(inode);
6699         ihold(inode);
6700         set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6701
6702         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6703                         1, index);
6704
6705         if (err) {
6706                 drop_inode = 1;
6707         } else {
6708                 struct dentry *parent = dentry->d_parent;
6709                 err = btrfs_update_inode(trans, root, inode);
6710                 if (err)
6711                         goto fail;
6712                 if (inode->i_nlink == 1) {
6713                         /*
6714                          * If new hard link count is 1, it's a file created
6715                          * with open(2) O_TMPFILE flag.
6716                          */
6717                         err = btrfs_orphan_del(trans, BTRFS_I(inode));
6718                         if (err)
6719                                 goto fail;
6720                 }
6721                 d_instantiate(dentry, inode);
6722                 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6723         }
6724
6725 fail:
6726         if (trans)
6727                 btrfs_end_transaction(trans);
6728         if (drop_inode) {
6729                 inode_dec_link_count(inode);
6730                 iput(inode);
6731         }
6732         btrfs_btree_balance_dirty(fs_info);
6733         return err;
6734 }
6735
6736 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6737 {
6738         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6739         struct inode *inode = NULL;
6740         struct btrfs_trans_handle *trans;
6741         struct btrfs_root *root = BTRFS_I(dir)->root;
6742         int err = 0;
6743         int drop_on_err = 0;
6744         u64 objectid = 0;
6745         u64 index = 0;
6746
6747         /*
6748          * 2 items for inode and ref
6749          * 2 items for dir items
6750          * 1 for xattr if selinux is on
6751          */
6752         trans = btrfs_start_transaction(root, 5);
6753         if (IS_ERR(trans))
6754                 return PTR_ERR(trans);
6755
6756         err = btrfs_find_free_ino(root, &objectid);
6757         if (err)
6758                 goto out_fail;
6759
6760         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6761                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6762                         S_IFDIR | mode, &index);
6763         if (IS_ERR(inode)) {
6764                 err = PTR_ERR(inode);
6765                 goto out_fail;
6766         }
6767
6768         drop_on_err = 1;
6769         /* these must be set before we unlock the inode */
6770         inode->i_op = &btrfs_dir_inode_operations;
6771         inode->i_fop = &btrfs_dir_file_operations;
6772
6773         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6774         if (err)
6775                 goto out_fail_inode;
6776
6777         btrfs_i_size_write(BTRFS_I(inode), 0);
6778         err = btrfs_update_inode(trans, root, inode);
6779         if (err)
6780                 goto out_fail_inode;
6781
6782         err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6783                         dentry->d_name.name,
6784                         dentry->d_name.len, 0, index);
6785         if (err)
6786                 goto out_fail_inode;
6787
6788         d_instantiate(dentry, inode);
6789         /*
6790          * mkdir is special.  We're unlocking after we call d_instantiate
6791          * to avoid a race with nfsd calling d_instantiate.
6792          */
6793         unlock_new_inode(inode);
6794         drop_on_err = 0;
6795
6796 out_fail:
6797         btrfs_end_transaction(trans);
6798         if (drop_on_err) {
6799                 inode_dec_link_count(inode);
6800                 iput(inode);
6801         }
6802         btrfs_btree_balance_dirty(fs_info);
6803         return err;
6804
6805 out_fail_inode:
6806         unlock_new_inode(inode);
6807         goto out_fail;
6808 }
6809
6810 /* Find next extent map of a given extent map, caller needs to ensure locks */
6811 static struct extent_map *next_extent_map(struct extent_map *em)
6812 {
6813         struct rb_node *next;
6814
6815         next = rb_next(&em->rb_node);
6816         if (!next)
6817                 return NULL;
6818         return container_of(next, struct extent_map, rb_node);
6819 }
6820
6821 static struct extent_map *prev_extent_map(struct extent_map *em)
6822 {
6823         struct rb_node *prev;
6824
6825         prev = rb_prev(&em->rb_node);
6826         if (!prev)
6827                 return NULL;
6828         return container_of(prev, struct extent_map, rb_node);
6829 }
6830
6831 /* helper for btfs_get_extent.  Given an existing extent in the tree,
6832  * the existing extent is the nearest extent to map_start,
6833  * and an extent that you want to insert, deal with overlap and insert
6834  * the best fitted new extent into the tree.
6835  */
6836 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6837                                 struct extent_map *existing,
6838                                 struct extent_map *em,
6839                                 u64 map_start)
6840 {
6841         struct extent_map *prev;
6842         struct extent_map *next;
6843         u64 start;
6844         u64 end;
6845         u64 start_diff;
6846
6847         BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6848
6849         if (existing->start > map_start) {
6850                 next = existing;
6851                 prev = prev_extent_map(next);
6852         } else {
6853                 prev = existing;
6854                 next = next_extent_map(prev);
6855         }
6856
6857         start = prev ? extent_map_end(prev) : em->start;
6858         start = max_t(u64, start, em->start);
6859         end = next ? next->start : extent_map_end(em);
6860         end = min_t(u64, end, extent_map_end(em));
6861         start_diff = start - em->start;
6862         em->start = start;
6863         em->len = end - start;
6864         if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6865             !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6866                 em->block_start += start_diff;
6867                 em->block_len -= start_diff;
6868         }
6869         return add_extent_mapping(em_tree, em, 0);
6870 }
6871
6872 static noinline int uncompress_inline(struct btrfs_path *path,
6873                                       struct page *page,
6874                                       size_t pg_offset, u64 extent_offset,
6875                                       struct btrfs_file_extent_item *item)
6876 {
6877         int ret;
6878         struct extent_buffer *leaf = path->nodes[0];
6879         char *tmp;
6880         size_t max_size;
6881         unsigned long inline_size;
6882         unsigned long ptr;
6883         int compress_type;
6884
6885         WARN_ON(pg_offset != 0);
6886         compress_type = btrfs_file_extent_compression(leaf, item);
6887         max_size = btrfs_file_extent_ram_bytes(leaf, item);
6888         inline_size = btrfs_file_extent_inline_item_len(leaf,
6889                                         btrfs_item_nr(path->slots[0]));
6890         tmp = kmalloc(inline_size, GFP_NOFS);
6891         if (!tmp)
6892                 return -ENOMEM;
6893         ptr = btrfs_file_extent_inline_start(item);
6894
6895         read_extent_buffer(leaf, tmp, ptr, inline_size);
6896
6897         max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6898         ret = btrfs_decompress(compress_type, tmp, page,
6899                                extent_offset, inline_size, max_size);
6900
6901         /*
6902          * decompression code contains a memset to fill in any space between the end
6903          * of the uncompressed data and the end of max_size in case the decompressed
6904          * data ends up shorter than ram_bytes.  That doesn't cover the hole between
6905          * the end of an inline extent and the beginning of the next block, so we
6906          * cover that region here.
6907          */
6908
6909         if (max_size + pg_offset < PAGE_SIZE) {
6910                 char *map = kmap(page);
6911                 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6912                 kunmap(page);
6913         }
6914         kfree(tmp);
6915         return ret;
6916 }
6917
6918 /*
6919  * a bit scary, this does extent mapping from logical file offset to the disk.
6920  * the ugly parts come from merging extents from the disk with the in-ram
6921  * representation.  This gets more complex because of the data=ordered code,
6922  * where the in-ram extents might be locked pending data=ordered completion.
6923  *
6924  * This also copies inline extents directly into the page.
6925  */
6926 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6927                 struct page *page,
6928             size_t pg_offset, u64 start, u64 len,
6929                 int create)
6930 {
6931         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6932         int ret;
6933         int err = 0;
6934         u64 extent_start = 0;
6935         u64 extent_end = 0;
6936         u64 objectid = btrfs_ino(inode);
6937         u32 found_type;
6938         struct btrfs_path *path = NULL;
6939         struct btrfs_root *root = inode->root;
6940         struct btrfs_file_extent_item *item;
6941         struct extent_buffer *leaf;
6942         struct btrfs_key found_key;
6943         struct extent_map *em = NULL;
6944         struct extent_map_tree *em_tree = &inode->extent_tree;
6945         struct extent_io_tree *io_tree = &inode->io_tree;
6946         struct btrfs_trans_handle *trans = NULL;
6947         const bool new_inline = !page || create;
6948
6949         read_lock(&em_tree->lock);
6950         em = lookup_extent_mapping(em_tree, start, len);
6951         if (em)
6952                 em->bdev = fs_info->fs_devices->latest_bdev;
6953         read_unlock(&em_tree->lock);
6954
6955         if (em) {
6956                 if (em->start > start || em->start + em->len <= start)
6957                         free_extent_map(em);
6958                 else if (em->block_start == EXTENT_MAP_INLINE && page)
6959                         free_extent_map(em);
6960                 else
6961                         goto out;
6962         }
6963         em = alloc_extent_map();
6964         if (!em) {
6965                 err = -ENOMEM;
6966                 goto out;
6967         }
6968         em->bdev = fs_info->fs_devices->latest_bdev;
6969         em->start = EXTENT_MAP_HOLE;
6970         em->orig_start = EXTENT_MAP_HOLE;
6971         em->len = (u64)-1;
6972         em->block_len = (u64)-1;
6973
6974         if (!path) {
6975                 path = btrfs_alloc_path();
6976                 if (!path) {
6977                         err = -ENOMEM;
6978                         goto out;
6979                 }
6980                 /*
6981                  * Chances are we'll be called again, so go ahead and do
6982                  * readahead
6983                  */
6984                 path->reada = READA_FORWARD;
6985         }
6986
6987         ret = btrfs_lookup_file_extent(trans, root, path,
6988                                        objectid, start, trans != NULL);
6989         if (ret < 0) {
6990                 err = ret;
6991                 goto out;
6992         }
6993
6994         if (ret != 0) {
6995                 if (path->slots[0] == 0)
6996                         goto not_found;
6997                 path->slots[0]--;
6998         }
6999
7000         leaf = path->nodes[0];
7001         item = btrfs_item_ptr(leaf, path->slots[0],
7002                               struct btrfs_file_extent_item);
7003         /* are we inside the extent that was found? */
7004         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7005         found_type = found_key.type;
7006         if (found_key.objectid != objectid ||
7007             found_type != BTRFS_EXTENT_DATA_KEY) {
7008                 /*
7009                  * If we backup past the first extent we want to move forward
7010                  * and see if there is an extent in front of us, otherwise we'll
7011                  * say there is a hole for our whole search range which can
7012                  * cause problems.
7013                  */
7014                 extent_end = start;
7015                 goto next;
7016         }
7017
7018         found_type = btrfs_file_extent_type(leaf, item);
7019         extent_start = found_key.offset;
7020         if (found_type == BTRFS_FILE_EXTENT_REG ||
7021             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7022                 extent_end = extent_start +
7023                        btrfs_file_extent_num_bytes(leaf, item);
7024
7025                 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7026                                                        extent_start);
7027         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7028                 size_t size;
7029                 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7030                 extent_end = ALIGN(extent_start + size,
7031                                    fs_info->sectorsize);
7032
7033                 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7034                                                       path->slots[0],
7035                                                       extent_start);
7036         }
7037 next:
7038         if (start >= extent_end) {
7039                 path->slots[0]++;
7040                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7041                         ret = btrfs_next_leaf(root, path);
7042                         if (ret < 0) {
7043                                 err = ret;
7044                                 goto out;
7045                         }
7046                         if (ret > 0)
7047                                 goto not_found;
7048                         leaf = path->nodes[0];
7049                 }
7050                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7051                 if (found_key.objectid != objectid ||
7052                     found_key.type != BTRFS_EXTENT_DATA_KEY)
7053                         goto not_found;
7054                 if (start + len <= found_key.offset)
7055                         goto not_found;
7056                 if (start > found_key.offset)
7057                         goto next;
7058                 em->start = start;
7059                 em->orig_start = start;
7060                 em->len = found_key.offset - start;
7061                 goto not_found_em;
7062         }
7063
7064         btrfs_extent_item_to_extent_map(inode, path, item,
7065                         new_inline, em);
7066
7067         if (found_type == BTRFS_FILE_EXTENT_REG ||
7068             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7069                 goto insert;
7070         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7071                 unsigned long ptr;
7072                 char *map;
7073                 size_t size;
7074                 size_t extent_offset;
7075                 size_t copy_size;
7076
7077                 if (new_inline)
7078                         goto out;
7079
7080                 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7081                 extent_offset = page_offset(page) + pg_offset - extent_start;
7082                 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7083                                   size - extent_offset);
7084                 em->start = extent_start + extent_offset;
7085                 em->len = ALIGN(copy_size, fs_info->sectorsize);
7086                 em->orig_block_len = em->len;
7087                 em->orig_start = em->start;
7088                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7089                 if (!PageUptodate(page)) {
7090                         if (btrfs_file_extent_compression(leaf, item) !=
7091                             BTRFS_COMPRESS_NONE) {
7092                                 ret = uncompress_inline(path, page, pg_offset,
7093                                                         extent_offset, item);
7094                                 if (ret) {
7095                                         err = ret;
7096                                         goto out;
7097                                 }
7098                         } else {
7099                                 map = kmap(page);
7100                                 read_extent_buffer(leaf, map + pg_offset, ptr,
7101                                                    copy_size);
7102                                 if (pg_offset + copy_size < PAGE_SIZE) {
7103                                         memset(map + pg_offset + copy_size, 0,
7104                                                PAGE_SIZE - pg_offset -
7105                                                copy_size);
7106                                 }
7107                                 kunmap(page);
7108                         }
7109                         flush_dcache_page(page);
7110                 }
7111                 set_extent_uptodate(io_tree, em->start,
7112                                     extent_map_end(em) - 1, NULL, GFP_NOFS);
7113                 goto insert;
7114         }
7115 not_found:
7116         em->start = start;
7117         em->orig_start = start;
7118         em->len = len;
7119 not_found_em:
7120         em->block_start = EXTENT_MAP_HOLE;
7121 insert:
7122         btrfs_release_path(path);
7123         if (em->start > start || extent_map_end(em) <= start) {
7124                 btrfs_err(fs_info,
7125                           "bad extent! em: [%llu %llu] passed [%llu %llu]",
7126                           em->start, em->len, start, len);
7127                 err = -EIO;
7128                 goto out;
7129         }
7130
7131         err = 0;
7132         write_lock(&em_tree->lock);
7133         ret = add_extent_mapping(em_tree, em, 0);
7134         /* it is possible that someone inserted the extent into the tree
7135          * while we had the lock dropped.  It is also possible that
7136          * an overlapping map exists in the tree
7137          */
7138         if (ret == -EEXIST) {
7139                 struct extent_map *existing;
7140
7141                 ret = 0;
7142
7143                 existing = search_extent_mapping(em_tree, start, len);
7144                 /*
7145                  * existing will always be non-NULL, since there must be
7146                  * extent causing the -EEXIST.
7147                  */
7148                 if (existing->start == em->start &&
7149                     extent_map_end(existing) >= extent_map_end(em) &&
7150                     em->block_start == existing->block_start) {
7151                         /*
7152                          * The existing extent map already encompasses the
7153                          * entire extent map we tried to add.
7154                          */
7155                         free_extent_map(em);
7156                         em = existing;
7157                         err = 0;
7158
7159                 } else if (start >= extent_map_end(existing) ||
7160                     start <= existing->start) {
7161                         /*
7162                          * The existing extent map is the one nearest to
7163                          * the [start, start + len) range which overlaps
7164                          */
7165                         err = merge_extent_mapping(em_tree, existing,
7166                                                    em, start);
7167                         free_extent_map(existing);
7168                         if (err) {
7169                                 free_extent_map(em);
7170                                 em = NULL;
7171                         }
7172                 } else {
7173                         free_extent_map(em);
7174                         em = existing;
7175                         err = 0;
7176                 }
7177         }
7178         write_unlock(&em_tree->lock);
7179 out:
7180
7181         trace_btrfs_get_extent(root, inode, em);
7182
7183         btrfs_free_path(path);
7184         if (trans) {
7185                 ret = btrfs_end_transaction(trans);
7186                 if (!err)
7187                         err = ret;
7188         }
7189         if (err) {
7190                 free_extent_map(em);
7191                 return ERR_PTR(err);
7192         }
7193         BUG_ON(!em); /* Error is always set */
7194         return em;
7195 }
7196
7197 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7198                 struct page *page,
7199                 size_t pg_offset, u64 start, u64 len,
7200                 int create)
7201 {
7202         struct extent_map *em;
7203         struct extent_map *hole_em = NULL;
7204         u64 range_start = start;
7205         u64 end;
7206         u64 found;
7207         u64 found_end;
7208         int err = 0;
7209
7210         em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7211         if (IS_ERR(em))
7212                 return em;
7213         /*
7214          * If our em maps to:
7215          * - a hole or
7216          * - a pre-alloc extent,
7217          * there might actually be delalloc bytes behind it.
7218          */
7219         if (em->block_start != EXTENT_MAP_HOLE &&
7220             !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7221                 return em;
7222         else
7223                 hole_em = em;
7224
7225         /* check to see if we've wrapped (len == -1 or similar) */
7226         end = start + len;
7227         if (end < start)
7228                 end = (u64)-1;
7229         else
7230                 end -= 1;
7231
7232         em = NULL;
7233
7234         /* ok, we didn't find anything, lets look for delalloc */
7235         found = count_range_bits(&inode->io_tree, &range_start,
7236                                  end, len, EXTENT_DELALLOC, 1);
7237         found_end = range_start + found;
7238         if (found_end < range_start)
7239                 found_end = (u64)-1;
7240
7241         /*
7242          * we didn't find anything useful, return
7243          * the original results from get_extent()
7244          */
7245         if (range_start > end || found_end <= start) {
7246                 em = hole_em;
7247                 hole_em = NULL;
7248                 goto out;
7249         }
7250
7251         /* adjust the range_start to make sure it doesn't
7252          * go backwards from the start they passed in
7253          */
7254         range_start = max(start, range_start);
7255         found = found_end - range_start;
7256
7257         if (found > 0) {
7258                 u64 hole_start = start;
7259                 u64 hole_len = len;
7260
7261                 em = alloc_extent_map();
7262                 if (!em) {
7263                         err = -ENOMEM;
7264                         goto out;
7265                 }
7266                 /*
7267                  * when btrfs_get_extent can't find anything it
7268                  * returns one huge hole
7269                  *
7270                  * make sure what it found really fits our range, and
7271                  * adjust to make sure it is based on the start from
7272                  * the caller
7273                  */
7274                 if (hole_em) {
7275                         u64 calc_end = extent_map_end(hole_em);
7276
7277                         if (calc_end <= start || (hole_em->start > end)) {
7278                                 free_extent_map(hole_em);
7279                                 hole_em = NULL;
7280                         } else {
7281                                 hole_start = max(hole_em->start, start);
7282                                 hole_len = calc_end - hole_start;
7283                         }
7284                 }
7285                 em->bdev = NULL;
7286                 if (hole_em && range_start > hole_start) {
7287                         /* our hole starts before our delalloc, so we
7288                          * have to return just the parts of the hole
7289                          * that go until  the delalloc starts
7290                          */
7291                         em->len = min(hole_len,
7292                                       range_start - hole_start);
7293                         em->start = hole_start;
7294                         em->orig_start = hole_start;
7295                         /*
7296                          * don't adjust block start at all,
7297                          * it is fixed at EXTENT_MAP_HOLE
7298                          */
7299                         em->block_start = hole_em->block_start;
7300                         em->block_len = hole_len;
7301                         if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7302                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7303                 } else {
7304                         em->start = range_start;
7305                         em->len = found;
7306                         em->orig_start = range_start;
7307                         em->block_start = EXTENT_MAP_DELALLOC;
7308                         em->block_len = found;
7309                 }
7310         } else if (hole_em) {
7311                 return hole_em;
7312         }
7313 out:
7314
7315         free_extent_map(hole_em);
7316         if (err) {
7317                 free_extent_map(em);
7318                 return ERR_PTR(err);
7319         }
7320         return em;
7321 }
7322
7323 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7324                                                   const u64 start,
7325                                                   const u64 len,
7326                                                   const u64 orig_start,
7327                                                   const u64 block_start,
7328                                                   const u64 block_len,
7329                                                   const u64 orig_block_len,
7330                                                   const u64 ram_bytes,
7331                                                   const int type)
7332 {
7333         struct extent_map *em = NULL;
7334         int ret;
7335
7336         if (type != BTRFS_ORDERED_NOCOW) {
7337                 em = create_io_em(inode, start, len, orig_start,
7338                                   block_start, block_len, orig_block_len,
7339                                   ram_bytes,
7340                                   BTRFS_COMPRESS_NONE, /* compress_type */
7341                                   type);
7342                 if (IS_ERR(em))
7343                         goto out;
7344         }
7345         ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7346                                            len, block_len, type);
7347         if (ret) {
7348                 if (em) {
7349                         free_extent_map(em);
7350                         btrfs_drop_extent_cache(BTRFS_I(inode), start,
7351                                                 start + len - 1, 0);
7352                 }
7353                 em = ERR_PTR(ret);
7354         }
7355  out:
7356
7357         return em;
7358 }
7359
7360 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7361                                                   u64 start, u64 len)
7362 {
7363         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7364         struct btrfs_root *root = BTRFS_I(inode)->root;
7365         struct extent_map *em;
7366         struct btrfs_key ins;
7367         u64 alloc_hint;
7368         int ret;
7369
7370         alloc_hint = get_extent_allocation_hint(inode, start, len);
7371         ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7372                                    0, alloc_hint, &ins, 1, 1);
7373         if (ret)
7374                 return ERR_PTR(ret);
7375
7376         em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7377                                      ins.objectid, ins.offset, ins.offset,
7378                                      ins.offset, BTRFS_ORDERED_REGULAR);
7379         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7380         if (IS_ERR(em))
7381                 btrfs_free_reserved_extent(fs_info, ins.objectid,
7382                                            ins.offset, 1);
7383
7384         return em;
7385 }
7386
7387 /*
7388  * returns 1 when the nocow is safe, < 1 on error, 0 if the
7389  * block must be cow'd
7390  */
7391 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7392                               u64 *orig_start, u64 *orig_block_len,
7393                               u64 *ram_bytes)
7394 {
7395         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7396         struct btrfs_path *path;
7397         int ret;
7398         struct extent_buffer *leaf;
7399         struct btrfs_root *root = BTRFS_I(inode)->root;
7400         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7401         struct btrfs_file_extent_item *fi;
7402         struct btrfs_key key;
7403         u64 disk_bytenr;
7404         u64 backref_offset;
7405         u64 extent_end;
7406         u64 num_bytes;
7407         int slot;
7408         int found_type;
7409         bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7410
7411         path = btrfs_alloc_path();
7412         if (!path)
7413                 return -ENOMEM;
7414
7415         ret = btrfs_lookup_file_extent(NULL, root, path,
7416                         btrfs_ino(BTRFS_I(inode)), offset, 0);
7417         if (ret < 0)
7418                 goto out;
7419
7420         slot = path->slots[0];
7421         if (ret == 1) {
7422                 if (slot == 0) {
7423                         /* can't find the item, must cow */
7424                         ret = 0;
7425                         goto out;
7426                 }
7427                 slot--;
7428         }
7429         ret = 0;
7430         leaf = path->nodes[0];
7431         btrfs_item_key_to_cpu(leaf, &key, slot);
7432         if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7433             key.type != BTRFS_EXTENT_DATA_KEY) {
7434                 /* not our file or wrong item type, must cow */
7435                 goto out;
7436         }
7437
7438         if (key.offset > offset) {
7439                 /* Wrong offset, must cow */
7440                 goto out;
7441         }
7442
7443         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7444         found_type = btrfs_file_extent_type(leaf, fi);
7445         if (found_type != BTRFS_FILE_EXTENT_REG &&
7446             found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7447                 /* not a regular extent, must cow */
7448                 goto out;
7449         }
7450
7451         if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7452                 goto out;
7453
7454         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7455         if (extent_end <= offset)
7456                 goto out;
7457
7458         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7459         if (disk_bytenr == 0)
7460                 goto out;
7461
7462         if (btrfs_file_extent_compression(leaf, fi) ||
7463             btrfs_file_extent_encryption(leaf, fi) ||
7464             btrfs_file_extent_other_encoding(leaf, fi))
7465                 goto out;
7466
7467         backref_offset = btrfs_file_extent_offset(leaf, fi);
7468
7469         if (orig_start) {
7470                 *orig_start = key.offset - backref_offset;
7471                 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7472                 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7473         }
7474
7475         if (btrfs_extent_readonly(fs_info, disk_bytenr))
7476                 goto out;
7477
7478         num_bytes = min(offset + *len, extent_end) - offset;
7479         if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7480                 u64 range_end;
7481
7482                 range_end = round_up(offset + num_bytes,
7483                                      root->fs_info->sectorsize) - 1;
7484                 ret = test_range_bit(io_tree, offset, range_end,
7485                                      EXTENT_DELALLOC, 0, NULL);
7486                 if (ret) {
7487                         ret = -EAGAIN;
7488                         goto out;
7489                 }
7490         }
7491
7492         btrfs_release_path(path);
7493
7494         /*
7495          * look for other files referencing this extent, if we
7496          * find any we must cow
7497          */
7498
7499         ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7500                                     key.offset - backref_offset, disk_bytenr);
7501         if (ret) {
7502                 ret = 0;
7503                 goto out;
7504         }
7505
7506         /*
7507          * adjust disk_bytenr and num_bytes to cover just the bytes
7508          * in this extent we are about to write.  If there
7509          * are any csums in that range we have to cow in order
7510          * to keep the csums correct
7511          */
7512         disk_bytenr += backref_offset;
7513         disk_bytenr += offset - key.offset;
7514         if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7515                 goto out;
7516         /*
7517          * all of the above have passed, it is safe to overwrite this extent
7518          * without cow
7519          */
7520         *len = num_bytes;
7521         ret = 1;
7522 out:
7523         btrfs_free_path(path);
7524         return ret;
7525 }
7526
7527 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7528 {
7529         struct radix_tree_root *root = &inode->i_mapping->page_tree;
7530         bool found = false;
7531         void **pagep = NULL;
7532         struct page *page = NULL;
7533         unsigned long start_idx;
7534         unsigned long end_idx;
7535
7536         start_idx = start >> PAGE_SHIFT;
7537
7538         /*
7539          * end is the last byte in the last page.  end == start is legal
7540          */
7541         end_idx = end >> PAGE_SHIFT;
7542
7543         rcu_read_lock();
7544
7545         /* Most of the code in this while loop is lifted from
7546          * find_get_page.  It's been modified to begin searching from a
7547          * page and return just the first page found in that range.  If the
7548          * found idx is less than or equal to the end idx then we know that
7549          * a page exists.  If no pages are found or if those pages are
7550          * outside of the range then we're fine (yay!) */
7551         while (page == NULL &&
7552                radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7553                 page = radix_tree_deref_slot(pagep);
7554                 if (unlikely(!page))
7555                         break;
7556
7557                 if (radix_tree_exception(page)) {
7558                         if (radix_tree_deref_retry(page)) {
7559                                 page = NULL;
7560                                 continue;
7561                         }
7562                         /*
7563                          * Otherwise, shmem/tmpfs must be storing a swap entry
7564                          * here as an exceptional entry: so return it without
7565                          * attempting to raise page count.
7566                          */
7567                         page = NULL;
7568                         break; /* TODO: Is this relevant for this use case? */
7569                 }
7570
7571                 if (!page_cache_get_speculative(page)) {
7572                         page = NULL;
7573                         continue;
7574                 }
7575
7576                 /*
7577                  * Has the page moved?
7578                  * This is part of the lockless pagecache protocol. See
7579                  * include/linux/pagemap.h for details.
7580                  */
7581                 if (unlikely(page != *pagep)) {
7582                         put_page(page);
7583                         page = NULL;
7584                 }
7585         }
7586
7587         if (page) {
7588                 if (page->index <= end_idx)
7589                         found = true;
7590                 put_page(page);
7591         }
7592
7593         rcu_read_unlock();
7594         return found;
7595 }
7596
7597 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7598                               struct extent_state **cached_state, int writing)
7599 {
7600         struct btrfs_ordered_extent *ordered;
7601         int ret = 0;
7602
7603         while (1) {
7604                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7605                                  cached_state);
7606                 /*
7607                  * We're concerned with the entire range that we're going to be
7608                  * doing DIO to, so we need to make sure there's no ordered
7609                  * extents in this range.
7610                  */
7611                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7612                                                      lockend - lockstart + 1);
7613
7614                 /*
7615                  * We need to make sure there are no buffered pages in this
7616                  * range either, we could have raced between the invalidate in
7617                  * generic_file_direct_write and locking the extent.  The
7618                  * invalidate needs to happen so that reads after a write do not
7619                  * get stale data.
7620                  */
7621                 if (!ordered &&
7622                     (!writing ||
7623                      !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7624                         break;
7625
7626                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7627                                      cached_state, GFP_NOFS);
7628
7629                 if (ordered) {
7630                         /*
7631                          * If we are doing a DIO read and the ordered extent we
7632                          * found is for a buffered write, we can not wait for it
7633                          * to complete and retry, because if we do so we can
7634                          * deadlock with concurrent buffered writes on page
7635                          * locks. This happens only if our DIO read covers more
7636                          * than one extent map, if at this point has already
7637                          * created an ordered extent for a previous extent map
7638                          * and locked its range in the inode's io tree, and a
7639                          * concurrent write against that previous extent map's
7640                          * range and this range started (we unlock the ranges
7641                          * in the io tree only when the bios complete and
7642                          * buffered writes always lock pages before attempting
7643                          * to lock range in the io tree).
7644                          */
7645                         if (writing ||
7646                             test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7647                                 btrfs_start_ordered_extent(inode, ordered, 1);
7648                         else
7649                                 ret = -ENOTBLK;
7650                         btrfs_put_ordered_extent(ordered);
7651                 } else {
7652                         /*
7653                          * We could trigger writeback for this range (and wait
7654                          * for it to complete) and then invalidate the pages for
7655                          * this range (through invalidate_inode_pages2_range()),
7656                          * but that can lead us to a deadlock with a concurrent
7657                          * call to readpages() (a buffered read or a defrag call
7658                          * triggered a readahead) on a page lock due to an
7659                          * ordered dio extent we created before but did not have
7660                          * yet a corresponding bio submitted (whence it can not
7661                          * complete), which makes readpages() wait for that
7662                          * ordered extent to complete while holding a lock on
7663                          * that page.
7664                          */
7665                         ret = -ENOTBLK;
7666                 }
7667
7668                 if (ret)
7669                         break;
7670
7671                 cond_resched();
7672         }
7673
7674         return ret;
7675 }
7676
7677 /* The callers of this must take lock_extent() */
7678 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7679                                        u64 orig_start, u64 block_start,
7680                                        u64 block_len, u64 orig_block_len,
7681                                        u64 ram_bytes, int compress_type,
7682                                        int type)
7683 {
7684         struct extent_map_tree *em_tree;
7685         struct extent_map *em;
7686         struct btrfs_root *root = BTRFS_I(inode)->root;
7687         int ret;
7688
7689         ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7690                type == BTRFS_ORDERED_COMPRESSED ||
7691                type == BTRFS_ORDERED_NOCOW ||
7692                type == BTRFS_ORDERED_REGULAR);
7693
7694         em_tree = &BTRFS_I(inode)->extent_tree;
7695         em = alloc_extent_map();
7696         if (!em)
7697                 return ERR_PTR(-ENOMEM);
7698
7699         em->start = start;
7700         em->orig_start = orig_start;
7701         em->len = len;
7702         em->block_len = block_len;
7703         em->block_start = block_start;
7704         em->bdev = root->fs_info->fs_devices->latest_bdev;
7705         em->orig_block_len = orig_block_len;
7706         em->ram_bytes = ram_bytes;
7707         em->generation = -1;
7708         set_bit(EXTENT_FLAG_PINNED, &em->flags);
7709         if (type == BTRFS_ORDERED_PREALLOC) {
7710                 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7711         } else if (type == BTRFS_ORDERED_COMPRESSED) {
7712                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7713                 em->compress_type = compress_type;
7714         }
7715
7716         do {
7717                 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7718                                 em->start + em->len - 1, 0);
7719                 write_lock(&em_tree->lock);
7720                 ret = add_extent_mapping(em_tree, em, 1);
7721                 write_unlock(&em_tree->lock);
7722                 /*
7723                  * The caller has taken lock_extent(), who could race with us
7724                  * to add em?
7725                  */
7726         } while (ret == -EEXIST);
7727
7728         if (ret) {
7729                 free_extent_map(em);
7730                 return ERR_PTR(ret);
7731         }
7732
7733         /* em got 2 refs now, callers needs to do free_extent_map once. */
7734         return em;
7735 }
7736
7737 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7738                                    struct buffer_head *bh_result, int create)
7739 {
7740         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7741         struct extent_map *em;
7742         struct extent_state *cached_state = NULL;
7743         struct btrfs_dio_data *dio_data = NULL;
7744         u64 start = iblock << inode->i_blkbits;
7745         u64 lockstart, lockend;
7746         u64 len = bh_result->b_size;
7747         int unlock_bits = EXTENT_LOCKED;
7748         int ret = 0;
7749
7750         if (create)
7751                 unlock_bits |= EXTENT_DIRTY;
7752         else
7753                 len = min_t(u64, len, fs_info->sectorsize);
7754
7755         lockstart = start;
7756         lockend = start + len - 1;
7757
7758         if (current->journal_info) {
7759                 /*
7760                  * Need to pull our outstanding extents and set journal_info to NULL so
7761                  * that anything that needs to check if there's a transaction doesn't get
7762                  * confused.
7763                  */
7764                 dio_data = current->journal_info;
7765                 current->journal_info = NULL;
7766         }
7767
7768         /*
7769          * If this errors out it's because we couldn't invalidate pagecache for
7770          * this range and we need to fallback to buffered.
7771          */
7772         if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7773                                create)) {
7774                 ret = -ENOTBLK;
7775                 goto err;
7776         }
7777
7778         em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7779         if (IS_ERR(em)) {
7780                 ret = PTR_ERR(em);
7781                 goto unlock_err;
7782         }
7783
7784         /*
7785          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7786          * io.  INLINE is special, and we could probably kludge it in here, but
7787          * it's still buffered so for safety lets just fall back to the generic
7788          * buffered path.
7789          *
7790          * For COMPRESSED we _have_ to read the entire extent in so we can
7791          * decompress it, so there will be buffering required no matter what we
7792          * do, so go ahead and fallback to buffered.
7793          *
7794          * We return -ENOTBLK because that's what makes DIO go ahead and go back
7795          * to buffered IO.  Don't blame me, this is the price we pay for using
7796          * the generic code.
7797          */
7798         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7799             em->block_start == EXTENT_MAP_INLINE) {
7800                 free_extent_map(em);
7801                 ret = -ENOTBLK;
7802                 goto unlock_err;
7803         }
7804
7805         /* Just a good old fashioned hole, return */
7806         if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7807                         test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7808                 free_extent_map(em);
7809                 goto unlock_err;
7810         }
7811
7812         /*
7813          * We don't allocate a new extent in the following cases
7814          *
7815          * 1) The inode is marked as NODATACOW.  In this case we'll just use the
7816          * existing extent.
7817          * 2) The extent is marked as PREALLOC.  We're good to go here and can
7818          * just use the extent.
7819          *
7820          */
7821         if (!create) {
7822                 len = min(len, em->len - (start - em->start));
7823                 lockstart = start + len;
7824                 goto unlock;
7825         }
7826
7827         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7828             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7829              em->block_start != EXTENT_MAP_HOLE)) {
7830                 int type;
7831                 u64 block_start, orig_start, orig_block_len, ram_bytes;
7832
7833                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7834                         type = BTRFS_ORDERED_PREALLOC;
7835                 else
7836                         type = BTRFS_ORDERED_NOCOW;
7837                 len = min(len, em->len - (start - em->start));
7838                 block_start = em->block_start + (start - em->start);
7839
7840                 if (can_nocow_extent(inode, start, &len, &orig_start,
7841                                      &orig_block_len, &ram_bytes) == 1 &&
7842                     btrfs_inc_nocow_writers(fs_info, block_start)) {
7843                         struct extent_map *em2;
7844
7845                         em2 = btrfs_create_dio_extent(inode, start, len,
7846                                                       orig_start, block_start,
7847                                                       len, orig_block_len,
7848                                                       ram_bytes, type);
7849                         btrfs_dec_nocow_writers(fs_info, block_start);
7850                         if (type == BTRFS_ORDERED_PREALLOC) {
7851                                 free_extent_map(em);
7852                                 em = em2;
7853                         }
7854                         if (em2 && IS_ERR(em2)) {
7855                                 ret = PTR_ERR(em2);
7856                                 goto unlock_err;
7857                         }
7858                         /*
7859                          * For inode marked NODATACOW or extent marked PREALLOC,
7860                          * use the existing or preallocated extent, so does not
7861                          * need to adjust btrfs_space_info's bytes_may_use.
7862                          */
7863                         btrfs_free_reserved_data_space_noquota(inode,
7864                                         start, len);
7865                         goto unlock;
7866                 }
7867         }
7868
7869         /*
7870          * this will cow the extent, reset the len in case we changed
7871          * it above
7872          */
7873         len = bh_result->b_size;
7874         free_extent_map(em);
7875         em = btrfs_new_extent_direct(inode, start, len);
7876         if (IS_ERR(em)) {
7877                 ret = PTR_ERR(em);
7878                 goto unlock_err;
7879         }
7880         len = min(len, em->len - (start - em->start));
7881 unlock:
7882         bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7883                 inode->i_blkbits;
7884         bh_result->b_size = len;
7885         bh_result->b_bdev = em->bdev;
7886         set_buffer_mapped(bh_result);
7887         if (create) {
7888                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7889                         set_buffer_new(bh_result);
7890
7891                 /*
7892                  * Need to update the i_size under the extent lock so buffered
7893                  * readers will get the updated i_size when we unlock.
7894                  */
7895                 if (!dio_data->overwrite && start + len > i_size_read(inode))
7896                         i_size_write(inode, start + len);
7897
7898                 WARN_ON(dio_data->reserve < len);
7899                 dio_data->reserve -= len;
7900                 dio_data->unsubmitted_oe_range_end = start + len;
7901                 current->journal_info = dio_data;
7902         }
7903
7904         /*
7905          * In the case of write we need to clear and unlock the entire range,
7906          * in the case of read we need to unlock only the end area that we
7907          * aren't using if there is any left over space.
7908          */
7909         if (lockstart < lockend) {
7910                 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7911                                  lockend, unlock_bits, 1, 0,
7912                                  &cached_state);
7913         } else {
7914                 free_extent_state(cached_state);
7915         }
7916
7917         free_extent_map(em);
7918
7919         return 0;
7920
7921 unlock_err:
7922         clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7923                          unlock_bits, 1, 0, &cached_state);
7924 err:
7925         if (dio_data)
7926                 current->journal_info = dio_data;
7927         return ret;
7928 }
7929
7930 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7931                                                  struct bio *bio,
7932                                                  int mirror_num)
7933 {
7934         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7935         blk_status_t ret;
7936
7937         BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7938
7939         bio_get(bio);
7940
7941         ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7942         if (ret)
7943                 goto err;
7944
7945         ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7946 err:
7947         bio_put(bio);
7948         return ret;
7949 }
7950
7951 static int btrfs_check_dio_repairable(struct inode *inode,
7952                                       struct bio *failed_bio,
7953                                       struct io_failure_record *failrec,
7954                                       int failed_mirror)
7955 {
7956         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7957         int num_copies;
7958
7959         num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7960         if (num_copies == 1) {
7961                 /*
7962                  * we only have a single copy of the data, so don't bother with
7963                  * all the retry and error correction code that follows. no
7964                  * matter what the error is, it is very likely to persist.
7965                  */
7966                 btrfs_debug(fs_info,
7967                         "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7968                         num_copies, failrec->this_mirror, failed_mirror);
7969                 return 0;
7970         }
7971
7972         failrec->failed_mirror = failed_mirror;
7973         failrec->this_mirror++;
7974         if (failrec->this_mirror == failed_mirror)
7975                 failrec->this_mirror++;
7976
7977         if (failrec->this_mirror > num_copies) {
7978                 btrfs_debug(fs_info,
7979                         "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7980                         num_copies, failrec->this_mirror, failed_mirror);
7981                 return 0;
7982         }
7983
7984         return 1;
7985 }
7986
7987 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7988                                    struct page *page, unsigned int pgoff,
7989                                    u64 start, u64 end, int failed_mirror,
7990                                    bio_end_io_t *repair_endio, void *repair_arg)
7991 {
7992         struct io_failure_record *failrec;
7993         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7994         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7995         struct bio *bio;
7996         int isector;
7997         unsigned int read_mode = 0;
7998         int segs;
7999         int ret;
8000         blk_status_t status;
8001
8002         BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
8003
8004         ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
8005         if (ret)
8006                 return errno_to_blk_status(ret);
8007
8008         ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
8009                                          failed_mirror);
8010         if (!ret) {
8011                 free_io_failure(failure_tree, io_tree, failrec);
8012                 return BLK_STS_IOERR;
8013         }
8014
8015         segs = bio_segments(failed_bio);
8016         if (segs > 1 ||
8017             (failed_bio->bi_io_vec->bv_len > btrfs_inode_sectorsize(inode)))
8018                 read_mode |= REQ_FAILFAST_DEV;
8019
8020         isector = start - btrfs_io_bio(failed_bio)->logical;
8021         isector >>= inode->i_sb->s_blocksize_bits;
8022         bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
8023                                 pgoff, isector, repair_endio, repair_arg);
8024         bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
8025
8026         btrfs_debug(BTRFS_I(inode)->root->fs_info,
8027                     "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
8028                     read_mode, failrec->this_mirror, failrec->in_validation);
8029
8030         status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
8031         if (status) {
8032                 free_io_failure(failure_tree, io_tree, failrec);
8033                 bio_put(bio);
8034         }
8035
8036         return status;
8037 }
8038
8039 struct btrfs_retry_complete {
8040         struct completion done;
8041         struct inode *inode;
8042         u64 start;
8043         int uptodate;
8044 };
8045
8046 static void btrfs_retry_endio_nocsum(struct bio *bio)
8047 {
8048         struct btrfs_retry_complete *done = bio->bi_private;
8049         struct inode *inode = done->inode;
8050         struct bio_vec *bvec;
8051         struct extent_io_tree *io_tree, *failure_tree;
8052         int i;
8053
8054         if (bio->bi_status)
8055                 goto end;
8056
8057         ASSERT(bio->bi_vcnt == 1);
8058         io_tree = &BTRFS_I(inode)->io_tree;
8059         failure_tree = &BTRFS_I(inode)->io_failure_tree;
8060         ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(inode));
8061
8062         done->uptodate = 1;
8063         ASSERT(!bio_flagged(bio, BIO_CLONED));
8064         bio_for_each_segment_all(bvec, bio, i)
8065                 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
8066                                  io_tree, done->start, bvec->bv_page,
8067                                  btrfs_ino(BTRFS_I(inode)), 0);
8068 end:
8069         complete(&done->done);
8070         bio_put(bio);
8071 }
8072
8073 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
8074                                                 struct btrfs_io_bio *io_bio)
8075 {
8076         struct btrfs_fs_info *fs_info;
8077         struct bio_vec bvec;
8078         struct bvec_iter iter;
8079         struct btrfs_retry_complete done;
8080         u64 start;
8081         unsigned int pgoff;
8082         u32 sectorsize;
8083         int nr_sectors;
8084         blk_status_t ret;
8085         blk_status_t err = BLK_STS_OK;
8086
8087         fs_info = BTRFS_I(inode)->root->fs_info;
8088         sectorsize = fs_info->sectorsize;
8089
8090         start = io_bio->logical;
8091         done.inode = inode;
8092         io_bio->bio.bi_iter = io_bio->iter;
8093
8094         bio_for_each_segment(bvec, &io_bio->bio, iter) {
8095                 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8096                 pgoff = bvec.bv_offset;
8097
8098 next_block_or_try_again:
8099                 done.uptodate = 0;
8100                 done.start = start;
8101                 init_completion(&done.done);
8102
8103                 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8104                                 pgoff, start, start + sectorsize - 1,
8105                                 io_bio->mirror_num,
8106                                 btrfs_retry_endio_nocsum, &done);
8107                 if (ret) {
8108                         err = ret;
8109                         goto next;
8110                 }
8111
8112                 wait_for_completion_io(&done.done);
8113
8114                 if (!done.uptodate) {
8115                         /* We might have another mirror, so try again */
8116                         goto next_block_or_try_again;
8117                 }
8118
8119 next:
8120                 start += sectorsize;
8121
8122                 nr_sectors--;
8123                 if (nr_sectors) {
8124                         pgoff += sectorsize;
8125                         ASSERT(pgoff < PAGE_SIZE);
8126                         goto next_block_or_try_again;
8127                 }
8128         }
8129
8130         return err;
8131 }
8132
8133 static void btrfs_retry_endio(struct bio *bio)
8134 {
8135         struct btrfs_retry_complete *done = bio->bi_private;
8136         struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8137         struct extent_io_tree *io_tree, *failure_tree;
8138         struct inode *inode = done->inode;
8139         struct bio_vec *bvec;
8140         int uptodate;
8141         int ret;
8142         int i;
8143
8144         if (bio->bi_status)
8145                 goto end;
8146
8147         uptodate = 1;
8148
8149         ASSERT(bio->bi_vcnt == 1);
8150         ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(done->inode));
8151
8152         io_tree = &BTRFS_I(inode)->io_tree;
8153         failure_tree = &BTRFS_I(inode)->io_failure_tree;
8154
8155         ASSERT(!bio_flagged(bio, BIO_CLONED));
8156         bio_for_each_segment_all(bvec, bio, i) {
8157                 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8158                                              bvec->bv_offset, done->start,
8159                                              bvec->bv_len);
8160                 if (!ret)
8161                         clean_io_failure(BTRFS_I(inode)->root->fs_info,
8162                                          failure_tree, io_tree, done->start,
8163                                          bvec->bv_page,
8164                                          btrfs_ino(BTRFS_I(inode)),
8165                                          bvec->bv_offset);
8166                 else
8167                         uptodate = 0;
8168         }
8169
8170         done->uptodate = uptodate;
8171 end:
8172         complete(&done->done);
8173         bio_put(bio);
8174 }
8175
8176 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8177                 struct btrfs_io_bio *io_bio, blk_status_t err)
8178 {
8179         struct btrfs_fs_info *fs_info;
8180         struct bio_vec bvec;
8181         struct bvec_iter iter;
8182         struct btrfs_retry_complete done;
8183         u64 start;
8184         u64 offset = 0;
8185         u32 sectorsize;
8186         int nr_sectors;
8187         unsigned int pgoff;
8188         int csum_pos;
8189         bool uptodate = (err == 0);
8190         int ret;
8191         blk_status_t status;
8192
8193         fs_info = BTRFS_I(inode)->root->fs_info;
8194         sectorsize = fs_info->sectorsize;
8195
8196         err = BLK_STS_OK;
8197         start = io_bio->logical;
8198         done.inode = inode;
8199         io_bio->bio.bi_iter = io_bio->iter;
8200
8201         bio_for_each_segment(bvec, &io_bio->bio, iter) {
8202                 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8203
8204                 pgoff = bvec.bv_offset;
8205 next_block:
8206                 if (uptodate) {
8207                         csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8208                         ret = __readpage_endio_check(inode, io_bio, csum_pos,
8209                                         bvec.bv_page, pgoff, start, sectorsize);
8210                         if (likely(!ret))
8211                                 goto next;
8212                 }
8213 try_again:
8214                 done.uptodate = 0;
8215                 done.start = start;
8216                 init_completion(&done.done);
8217
8218                 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8219                                         pgoff, start, start + sectorsize - 1,
8220                                         io_bio->mirror_num, btrfs_retry_endio,
8221                                         &done);
8222                 if (status) {
8223                         err = status;
8224                         goto next;
8225                 }
8226
8227                 wait_for_completion_io(&done.done);
8228
8229                 if (!done.uptodate) {
8230                         /* We might have another mirror, so try again */
8231                         goto try_again;
8232                 }
8233 next:
8234                 offset += sectorsize;
8235                 start += sectorsize;
8236
8237                 ASSERT(nr_sectors);
8238
8239                 nr_sectors--;
8240                 if (nr_sectors) {
8241                         pgoff += sectorsize;
8242                         ASSERT(pgoff < PAGE_SIZE);
8243                         goto next_block;
8244                 }
8245         }
8246
8247         return err;
8248 }
8249
8250 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8251                 struct btrfs_io_bio *io_bio, blk_status_t err)
8252 {
8253         bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8254
8255         if (skip_csum) {
8256                 if (unlikely(err))
8257                         return __btrfs_correct_data_nocsum(inode, io_bio);
8258                 else
8259                         return BLK_STS_OK;
8260         } else {
8261                 return __btrfs_subio_endio_read(inode, io_bio, err);
8262         }
8263 }
8264
8265 static void btrfs_endio_direct_read(struct bio *bio)
8266 {
8267         struct btrfs_dio_private *dip = bio->bi_private;
8268         struct inode *inode = dip->inode;
8269         struct bio *dio_bio;
8270         struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8271         blk_status_t err = bio->bi_status;
8272
8273         if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8274                 err = btrfs_subio_endio_read(inode, io_bio, err);
8275
8276         unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8277                       dip->logical_offset + dip->bytes - 1);
8278         dio_bio = dip->dio_bio;
8279
8280         kfree(dip);
8281
8282         dio_bio->bi_status = err;
8283         dio_end_io(dio_bio);
8284
8285         if (io_bio->end_io)
8286                 io_bio->end_io(io_bio, blk_status_to_errno(err));
8287         bio_put(bio);
8288 }
8289
8290 static void __endio_write_update_ordered(struct inode *inode,
8291                                          const u64 offset, const u64 bytes,
8292                                          const bool uptodate)
8293 {
8294         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8295         struct btrfs_ordered_extent *ordered = NULL;
8296         struct btrfs_workqueue *wq;
8297         btrfs_work_func_t func;
8298         u64 ordered_offset = offset;
8299         u64 ordered_bytes = bytes;
8300         u64 last_offset;
8301         int ret;
8302
8303         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8304                 wq = fs_info->endio_freespace_worker;
8305                 func = btrfs_freespace_write_helper;
8306         } else {
8307                 wq = fs_info->endio_write_workers;
8308                 func = btrfs_endio_write_helper;
8309         }
8310
8311 again:
8312         last_offset = ordered_offset;
8313         ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8314                                                    &ordered_offset,
8315                                                    ordered_bytes,
8316                                                    uptodate);
8317         if (!ret)
8318                 goto out_test;
8319
8320         btrfs_init_work(&ordered->work, func, finish_ordered_fn, NULL, NULL);
8321         btrfs_queue_work(wq, &ordered->work);
8322 out_test:
8323         /*
8324          * If btrfs_dec_test_ordered_pending does not find any ordered extent
8325          * in the range, we can exit.
8326          */
8327         if (ordered_offset == last_offset)
8328                 return;
8329         /*
8330          * our bio might span multiple ordered extents.  If we haven't
8331          * completed the accounting for the whole dio, go back and try again
8332          */
8333         if (ordered_offset < offset + bytes) {
8334                 ordered_bytes = offset + bytes - ordered_offset;
8335                 ordered = NULL;
8336                 goto again;
8337         }
8338 }
8339
8340 static void btrfs_endio_direct_write(struct bio *bio)
8341 {
8342         struct btrfs_dio_private *dip = bio->bi_private;
8343         struct bio *dio_bio = dip->dio_bio;
8344
8345         __endio_write_update_ordered(dip->inode, dip->logical_offset,
8346                                      dip->bytes, !bio->bi_status);
8347
8348         kfree(dip);
8349
8350         dio_bio->bi_status = bio->bi_status;
8351         dio_end_io(dio_bio);
8352         bio_put(bio);
8353 }
8354
8355 static blk_status_t __btrfs_submit_bio_start_direct_io(void *private_data,
8356                                     struct bio *bio, int mirror_num,
8357                                     unsigned long bio_flags, u64 offset)
8358 {
8359         struct inode *inode = private_data;
8360         blk_status_t ret;
8361         ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8362         BUG_ON(ret); /* -ENOMEM */
8363         return 0;
8364 }
8365
8366 static void btrfs_end_dio_bio(struct bio *bio)
8367 {
8368         struct btrfs_dio_private *dip = bio->bi_private;
8369         blk_status_t err = bio->bi_status;
8370
8371         if (err)
8372                 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8373                            "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8374                            btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8375                            bio->bi_opf,
8376                            (unsigned long long)bio->bi_iter.bi_sector,
8377                            bio->bi_iter.bi_size, err);
8378
8379         if (dip->subio_endio)
8380                 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8381
8382         if (err) {
8383                 dip->errors = 1;
8384
8385                 /*
8386                  * before atomic variable goto zero, we must make sure
8387                  * dip->errors is perceived to be set.
8388                  */
8389                 smp_mb__before_atomic();
8390         }
8391
8392         /* if there are more bios still pending for this dio, just exit */
8393         if (!atomic_dec_and_test(&dip->pending_bios))
8394                 goto out;
8395
8396         if (dip->errors) {
8397                 bio_io_error(dip->orig_bio);
8398         } else {
8399                 dip->dio_bio->bi_status = BLK_STS_OK;
8400                 bio_endio(dip->orig_bio);
8401         }
8402 out:
8403         bio_put(bio);
8404 }
8405
8406 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8407                                                  struct btrfs_dio_private *dip,
8408                                                  struct bio *bio,
8409                                                  u64 file_offset)
8410 {
8411         struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8412         struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8413         blk_status_t ret;
8414
8415         /*
8416          * We load all the csum data we need when we submit
8417          * the first bio to reduce the csum tree search and
8418          * contention.
8419          */
8420         if (dip->logical_offset == file_offset) {
8421                 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8422                                                 file_offset);
8423                 if (ret)
8424                         return ret;
8425         }
8426
8427         if (bio == dip->orig_bio)
8428                 return 0;
8429
8430         file_offset -= dip->logical_offset;
8431         file_offset >>= inode->i_sb->s_blocksize_bits;
8432         io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8433
8434         return 0;
8435 }
8436
8437 static inline blk_status_t
8438 __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode, u64 file_offset,
8439                        int async_submit)
8440 {
8441         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8442         struct btrfs_dio_private *dip = bio->bi_private;
8443         bool write = bio_op(bio) == REQ_OP_WRITE;
8444         blk_status_t ret;
8445
8446         /* Check btrfs_submit_bio_hook() for rules about async submit. */
8447         if (async_submit)
8448                 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8449
8450         bio_get(bio);
8451
8452         if (!write) {
8453                 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8454                 if (ret)
8455                         goto err;
8456         }
8457
8458         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8459                 goto map;
8460
8461         if (write && async_submit) {
8462                 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8463                                           file_offset, inode,
8464                                           __btrfs_submit_bio_start_direct_io,
8465                                           __btrfs_submit_bio_done);
8466                 goto err;
8467         } else if (write) {
8468                 /*
8469                  * If we aren't doing async submit, calculate the csum of the
8470                  * bio now.
8471                  */
8472                 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8473                 if (ret)
8474                         goto err;
8475         } else {
8476                 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8477                                                      file_offset);
8478                 if (ret)
8479                         goto err;
8480         }
8481 map:
8482         ret = btrfs_map_bio(fs_info, bio, 0, 0);
8483 err:
8484         bio_put(bio);
8485         return ret;
8486 }
8487
8488 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8489 {
8490         struct inode *inode = dip->inode;
8491         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8492         struct bio *bio;
8493         struct bio *orig_bio = dip->orig_bio;
8494         u64 start_sector = orig_bio->bi_iter.bi_sector;
8495         u64 file_offset = dip->logical_offset;
8496         u64 map_length;
8497         int async_submit = 0;
8498         u64 submit_len;
8499         int clone_offset = 0;
8500         int clone_len;
8501         int ret;
8502         blk_status_t status;
8503
8504         map_length = orig_bio->bi_iter.bi_size;
8505         submit_len = map_length;
8506         ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8507                               &map_length, NULL, 0);
8508         if (ret)
8509                 return -EIO;
8510
8511         if (map_length >= submit_len) {
8512                 bio = orig_bio;
8513                 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8514                 goto submit;
8515         }
8516
8517         /* async crcs make it difficult to collect full stripe writes. */
8518         if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8519                 async_submit = 0;
8520         else
8521                 async_submit = 1;
8522
8523         /* bio split */
8524         ASSERT(map_length <= INT_MAX);
8525         atomic_inc(&dip->pending_bios);
8526         do {
8527                 clone_len = min_t(int, submit_len, map_length);
8528
8529                 /*
8530                  * This will never fail as it's passing GPF_NOFS and
8531                  * the allocation is backed by btrfs_bioset.
8532                  */
8533                 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8534                                               clone_len);
8535                 bio->bi_private = dip;
8536                 bio->bi_end_io = btrfs_end_dio_bio;
8537                 btrfs_io_bio(bio)->logical = file_offset;
8538
8539                 ASSERT(submit_len >= clone_len);
8540                 submit_len -= clone_len;
8541                 if (submit_len == 0)
8542                         break;
8543
8544                 /*
8545                  * Increase the count before we submit the bio so we know
8546                  * the end IO handler won't happen before we increase the
8547                  * count. Otherwise, the dip might get freed before we're
8548                  * done setting it up.
8549                  */
8550                 atomic_inc(&dip->pending_bios);
8551
8552                 status = __btrfs_submit_dio_bio(bio, inode, file_offset,
8553                                                 async_submit);
8554                 if (status) {
8555                         bio_put(bio);
8556                         atomic_dec(&dip->pending_bios);
8557                         goto out_err;
8558                 }
8559
8560                 clone_offset += clone_len;
8561                 start_sector += clone_len >> 9;
8562                 file_offset += clone_len;
8563
8564                 map_length = submit_len;
8565                 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8566                                       start_sector << 9, &map_length, NULL, 0);
8567                 if (ret)
8568                         goto out_err;
8569         } while (submit_len > 0);
8570
8571 submit:
8572         status = __btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8573         if (!status)
8574                 return 0;
8575
8576         bio_put(bio);
8577 out_err:
8578         dip->errors = 1;
8579         /*
8580          * before atomic variable goto zero, we must
8581          * make sure dip->errors is perceived to be set.
8582          */
8583         smp_mb__before_atomic();
8584         if (atomic_dec_and_test(&dip->pending_bios))
8585                 bio_io_error(dip->orig_bio);
8586
8587         /* bio_end_io() will handle error, so we needn't return it */
8588         return 0;
8589 }
8590
8591 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8592                                 loff_t file_offset)
8593 {
8594         struct btrfs_dio_private *dip = NULL;
8595         struct bio *bio = NULL;
8596         struct btrfs_io_bio *io_bio;
8597         bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8598         int ret = 0;
8599
8600         bio = btrfs_bio_clone(dio_bio);
8601
8602         dip = kzalloc(sizeof(*dip), GFP_NOFS);
8603         if (!dip) {
8604                 ret = -ENOMEM;
8605                 goto free_ordered;
8606         }
8607
8608         dip->private = dio_bio->bi_private;
8609         dip->inode = inode;
8610         dip->logical_offset = file_offset;
8611         dip->bytes = dio_bio->bi_iter.bi_size;
8612         dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8613         bio->bi_private = dip;
8614         dip->orig_bio = bio;
8615         dip->dio_bio = dio_bio;
8616         atomic_set(&dip->pending_bios, 0);
8617         io_bio = btrfs_io_bio(bio);
8618         io_bio->logical = file_offset;
8619
8620         if (write) {
8621                 bio->bi_end_io = btrfs_endio_direct_write;
8622         } else {
8623                 bio->bi_end_io = btrfs_endio_direct_read;
8624                 dip->subio_endio = btrfs_subio_endio_read;
8625         }
8626
8627         /*
8628          * Reset the range for unsubmitted ordered extents (to a 0 length range)
8629          * even if we fail to submit a bio, because in such case we do the
8630          * corresponding error handling below and it must not be done a second
8631          * time by btrfs_direct_IO().
8632          */
8633         if (write) {
8634                 struct btrfs_dio_data *dio_data = current->journal_info;
8635
8636                 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8637                         dip->bytes;
8638                 dio_data->unsubmitted_oe_range_start =
8639                         dio_data->unsubmitted_oe_range_end;
8640         }
8641
8642         ret = btrfs_submit_direct_hook(dip);
8643         if (!ret)
8644                 return;
8645
8646         if (io_bio->end_io)
8647                 io_bio->end_io(io_bio, ret);
8648
8649 free_ordered:
8650         /*
8651          * If we arrived here it means either we failed to submit the dip
8652          * or we either failed to clone the dio_bio or failed to allocate the
8653          * dip. If we cloned the dio_bio and allocated the dip, we can just
8654          * call bio_endio against our io_bio so that we get proper resource
8655          * cleanup if we fail to submit the dip, otherwise, we must do the
8656          * same as btrfs_endio_direct_[write|read] because we can't call these
8657          * callbacks - they require an allocated dip and a clone of dio_bio.
8658          */
8659         if (bio && dip) {
8660                 bio_io_error(bio);
8661                 /*
8662                  * The end io callbacks free our dip, do the final put on bio
8663                  * and all the cleanup and final put for dio_bio (through
8664                  * dio_end_io()).
8665                  */
8666                 dip = NULL;
8667                 bio = NULL;
8668         } else {
8669                 if (write)
8670                         __endio_write_update_ordered(inode,
8671                                                 file_offset,
8672                                                 dio_bio->bi_iter.bi_size,
8673                                                 false);
8674                 else
8675                         unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8676                               file_offset + dio_bio->bi_iter.bi_size - 1);
8677
8678                 dio_bio->bi_status = BLK_STS_IOERR;
8679                 /*
8680                  * Releases and cleans up our dio_bio, no need to bio_put()
8681                  * nor bio_endio()/bio_io_error() against dio_bio.
8682                  */
8683                 dio_end_io(dio_bio);
8684         }
8685         if (bio)
8686                 bio_put(bio);
8687         kfree(dip);
8688 }
8689
8690 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8691                                const struct iov_iter *iter, loff_t offset)
8692 {
8693         int seg;
8694         int i;
8695         unsigned int blocksize_mask = fs_info->sectorsize - 1;
8696         ssize_t retval = -EINVAL;
8697
8698         if (offset & blocksize_mask)
8699                 goto out;
8700
8701         if (iov_iter_alignment(iter) & blocksize_mask)
8702                 goto out;
8703
8704         /* If this is a write we don't need to check anymore */
8705         if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8706                 return 0;
8707         /*
8708          * Check to make sure we don't have duplicate iov_base's in this
8709          * iovec, if so return EINVAL, otherwise we'll get csum errors
8710          * when reading back.
8711          */
8712         for (seg = 0; seg < iter->nr_segs; seg++) {
8713                 for (i = seg + 1; i < iter->nr_segs; i++) {
8714                         if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8715                                 goto out;
8716                 }
8717         }
8718         retval = 0;
8719 out:
8720         return retval;
8721 }
8722
8723 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8724 {
8725         struct file *file = iocb->ki_filp;
8726         struct inode *inode = file->f_mapping->host;
8727         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8728         struct btrfs_dio_data dio_data = { 0 };
8729         struct extent_changeset *data_reserved = NULL;
8730         loff_t offset = iocb->ki_pos;
8731         size_t count = 0;
8732         int flags = 0;
8733         bool wakeup = true;
8734         bool relock = false;
8735         ssize_t ret;
8736
8737         if (check_direct_IO(fs_info, iter, offset))
8738                 return 0;
8739
8740         inode_dio_begin(inode);
8741
8742         /*
8743          * The generic stuff only does filemap_write_and_wait_range, which
8744          * isn't enough if we've written compressed pages to this area, so
8745          * we need to flush the dirty pages again to make absolutely sure
8746          * that any outstanding dirty pages are on disk.
8747          */
8748         count = iov_iter_count(iter);
8749         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8750                      &BTRFS_I(inode)->runtime_flags))
8751                 filemap_fdatawrite_range(inode->i_mapping, offset,
8752                                          offset + count - 1);
8753
8754         if (iov_iter_rw(iter) == WRITE) {
8755                 /*
8756                  * If the write DIO is beyond the EOF, we need update
8757                  * the isize, but it is protected by i_mutex. So we can
8758                  * not unlock the i_mutex at this case.
8759                  */
8760                 if (offset + count <= inode->i_size) {
8761                         dio_data.overwrite = 1;
8762                         inode_unlock(inode);
8763                         relock = true;
8764                 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8765                         ret = -EAGAIN;
8766                         goto out;
8767                 }
8768                 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8769                                                    offset, count);
8770                 if (ret)
8771                         goto out;
8772
8773                 /*
8774                  * We need to know how many extents we reserved so that we can
8775                  * do the accounting properly if we go over the number we
8776                  * originally calculated.  Abuse current->journal_info for this.
8777                  */
8778                 dio_data.reserve = round_up(count,
8779                                             fs_info->sectorsize);
8780                 dio_data.unsubmitted_oe_range_start = (u64)offset;
8781                 dio_data.unsubmitted_oe_range_end = (u64)offset;
8782                 current->journal_info = &dio_data;
8783                 down_read(&BTRFS_I(inode)->dio_sem);
8784         } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8785                                      &BTRFS_I(inode)->runtime_flags)) {
8786                 inode_dio_end(inode);
8787                 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8788                 wakeup = false;
8789         }
8790
8791         ret = __blockdev_direct_IO(iocb, inode,
8792                                    fs_info->fs_devices->latest_bdev,
8793                                    iter, btrfs_get_blocks_direct, NULL,
8794                                    btrfs_submit_direct, flags);
8795         if (iov_iter_rw(iter) == WRITE) {
8796                 up_read(&BTRFS_I(inode)->dio_sem);
8797                 current->journal_info = NULL;
8798                 if (ret < 0 && ret != -EIOCBQUEUED) {
8799                         if (dio_data.reserve)
8800                                 btrfs_delalloc_release_space(inode, data_reserved,
8801                                         offset, dio_data.reserve);
8802                         /*
8803                          * On error we might have left some ordered extents
8804                          * without submitting corresponding bios for them, so
8805                          * cleanup them up to avoid other tasks getting them
8806                          * and waiting for them to complete forever.
8807                          */
8808                         if (dio_data.unsubmitted_oe_range_start <
8809                             dio_data.unsubmitted_oe_range_end)
8810                                 __endio_write_update_ordered(inode,
8811                                         dio_data.unsubmitted_oe_range_start,
8812                                         dio_data.unsubmitted_oe_range_end -
8813                                         dio_data.unsubmitted_oe_range_start,
8814                                         false);
8815                 } else if (ret >= 0 && (size_t)ret < count)
8816                         btrfs_delalloc_release_space(inode, data_reserved,
8817                                         offset, count - (size_t)ret);
8818                 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
8819         }
8820 out:
8821         if (wakeup)
8822                 inode_dio_end(inode);
8823         if (relock)
8824                 inode_lock(inode);
8825
8826         extent_changeset_free(data_reserved);
8827         return ret;
8828 }
8829
8830 #define BTRFS_FIEMAP_FLAGS      (FIEMAP_FLAG_SYNC)
8831
8832 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8833                 __u64 start, __u64 len)
8834 {
8835         int     ret;
8836
8837         ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8838         if (ret)
8839                 return ret;
8840
8841         return extent_fiemap(inode, fieinfo, start, len);
8842 }
8843
8844 int btrfs_readpage(struct file *file, struct page *page)
8845 {
8846         struct extent_io_tree *tree;
8847         tree = &BTRFS_I(page->mapping->host)->io_tree;
8848         return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8849 }
8850
8851 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8852 {
8853         struct extent_io_tree *tree;
8854         struct inode *inode = page->mapping->host;
8855         int ret;
8856
8857         if (current->flags & PF_MEMALLOC) {
8858                 redirty_page_for_writepage(wbc, page);
8859                 unlock_page(page);
8860                 return 0;
8861         }
8862
8863         /*
8864          * If we are under memory pressure we will call this directly from the
8865          * VM, we need to make sure we have the inode referenced for the ordered
8866          * extent.  If not just return like we didn't do anything.
8867          */
8868         if (!igrab(inode)) {
8869                 redirty_page_for_writepage(wbc, page);
8870                 return AOP_WRITEPAGE_ACTIVATE;
8871         }
8872         tree = &BTRFS_I(page->mapping->host)->io_tree;
8873         ret = extent_write_full_page(tree, page, wbc);
8874         btrfs_add_delayed_iput(inode);
8875         return ret;
8876 }
8877
8878 static int btrfs_writepages(struct address_space *mapping,
8879                             struct writeback_control *wbc)
8880 {
8881         struct extent_io_tree *tree;
8882
8883         tree = &BTRFS_I(mapping->host)->io_tree;
8884         return extent_writepages(tree, mapping, wbc);
8885 }
8886
8887 static int
8888 btrfs_readpages(struct file *file, struct address_space *mapping,
8889                 struct list_head *pages, unsigned nr_pages)
8890 {
8891         struct extent_io_tree *tree;
8892         tree = &BTRFS_I(mapping->host)->io_tree;
8893         return extent_readpages(tree, mapping, pages, nr_pages);
8894 }
8895 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8896 {
8897         struct extent_io_tree *tree;
8898         struct extent_map_tree *map;
8899         int ret;
8900
8901         tree = &BTRFS_I(page->mapping->host)->io_tree;
8902         map = &BTRFS_I(page->mapping->host)->extent_tree;
8903         ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8904         if (ret == 1) {
8905                 ClearPagePrivate(page);
8906                 set_page_private(page, 0);
8907                 put_page(page);
8908         }
8909         return ret;
8910 }
8911
8912 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8913 {
8914         if (PageWriteback(page) || PageDirty(page))
8915                 return 0;
8916         return __btrfs_releasepage(page, gfp_flags);
8917 }
8918
8919 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8920                                  unsigned int length)
8921 {
8922         struct inode *inode = page->mapping->host;
8923         struct extent_io_tree *tree;
8924         struct btrfs_ordered_extent *ordered;
8925         struct extent_state *cached_state = NULL;
8926         u64 page_start = page_offset(page);
8927         u64 page_end = page_start + PAGE_SIZE - 1;
8928         u64 start;
8929         u64 end;
8930         int inode_evicting = inode->i_state & I_FREEING;
8931
8932         /*
8933          * we have the page locked, so new writeback can't start,
8934          * and the dirty bit won't be cleared while we are here.
8935          *
8936          * Wait for IO on this page so that we can safely clear
8937          * the PagePrivate2 bit and do ordered accounting
8938          */
8939         wait_on_page_writeback(page);
8940
8941         tree = &BTRFS_I(inode)->io_tree;
8942         if (offset) {
8943                 btrfs_releasepage(page, GFP_NOFS);
8944                 return;
8945         }
8946
8947         if (!inode_evicting)
8948                 lock_extent_bits(tree, page_start, page_end, &cached_state);
8949 again:
8950         start = page_start;
8951         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8952                                         page_end - start + 1);
8953         if (ordered) {
8954                 end = min(page_end, ordered->file_offset + ordered->len - 1);
8955                 /*
8956                  * IO on this page will never be started, so we need
8957                  * to account for any ordered extents now
8958                  */
8959                 if (!inode_evicting)
8960                         clear_extent_bit(tree, start, end,
8961                                          EXTENT_DIRTY | EXTENT_DELALLOC |
8962                                          EXTENT_DELALLOC_NEW |
8963                                          EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8964                                          EXTENT_DEFRAG, 1, 0, &cached_state);
8965                 /*
8966                  * whoever cleared the private bit is responsible
8967                  * for the finish_ordered_io
8968                  */
8969                 if (TestClearPagePrivate2(page)) {
8970                         struct btrfs_ordered_inode_tree *tree;
8971                         u64 new_len;
8972
8973                         tree = &BTRFS_I(inode)->ordered_tree;
8974
8975                         spin_lock_irq(&tree->lock);
8976                         set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8977                         new_len = start - ordered->file_offset;
8978                         if (new_len < ordered->truncated_len)
8979                                 ordered->truncated_len = new_len;
8980                         spin_unlock_irq(&tree->lock);
8981
8982                         if (btrfs_dec_test_ordered_pending(inode, &ordered,
8983                                                            start,
8984                                                            end - start + 1, 1))
8985                                 btrfs_finish_ordered_io(ordered);
8986                 }
8987                 btrfs_put_ordered_extent(ordered);
8988                 if (!inode_evicting) {
8989                         cached_state = NULL;
8990                         lock_extent_bits(tree, start, end,
8991                                          &cached_state);
8992                 }
8993
8994                 start = end + 1;
8995                 if (start < page_end)
8996                         goto again;
8997         }
8998
8999         /*
9000          * Qgroup reserved space handler
9001          * Page here will be either
9002          * 1) Already written to disk
9003          *    In this case, its reserved space is released from data rsv map
9004          *    and will be freed by delayed_ref handler finally.
9005          *    So even we call qgroup_free_data(), it won't decrease reserved
9006          *    space.
9007          * 2) Not written to disk
9008          *    This means the reserved space should be freed here. However,
9009          *    if a truncate invalidates the page (by clearing PageDirty)
9010          *    and the page is accounted for while allocating extent
9011          *    in btrfs_check_data_free_space() we let delayed_ref to
9012          *    free the entire extent.
9013          */
9014         if (PageDirty(page))
9015                 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
9016         if (!inode_evicting) {
9017                 clear_extent_bit(tree, page_start, page_end,
9018                                  EXTENT_LOCKED | EXTENT_DIRTY |
9019                                  EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
9020                                  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
9021                                  &cached_state);
9022
9023                 __btrfs_releasepage(page, GFP_NOFS);
9024         }
9025
9026         ClearPageChecked(page);
9027         if (PagePrivate(page)) {
9028                 ClearPagePrivate(page);
9029                 set_page_private(page, 0);
9030                 put_page(page);
9031         }
9032 }
9033
9034 /*
9035  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
9036  * called from a page fault handler when a page is first dirtied. Hence we must
9037  * be careful to check for EOF conditions here. We set the page up correctly
9038  * for a written page which means we get ENOSPC checking when writing into
9039  * holes and correct delalloc and unwritten extent mapping on filesystems that
9040  * support these features.
9041  *
9042  * We are not allowed to take the i_mutex here so we have to play games to
9043  * protect against truncate races as the page could now be beyond EOF.  Because
9044  * vmtruncate() writes the inode size before removing pages, once we have the
9045  * page lock we can determine safely if the page is beyond EOF. If it is not
9046  * beyond EOF, then the page is guaranteed safe against truncation until we
9047  * unlock the page.
9048  */
9049 int btrfs_page_mkwrite(struct vm_fault *vmf)
9050 {
9051         struct page *page = vmf->page;
9052         struct inode *inode = file_inode(vmf->vma->vm_file);
9053         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9054         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9055         struct btrfs_ordered_extent *ordered;
9056         struct extent_state *cached_state = NULL;
9057         struct extent_changeset *data_reserved = NULL;
9058         char *kaddr;
9059         unsigned long zero_start;
9060         loff_t size;
9061         int ret;
9062         int reserved = 0;
9063         u64 reserved_space;
9064         u64 page_start;
9065         u64 page_end;
9066         u64 end;
9067
9068         reserved_space = PAGE_SIZE;
9069
9070         sb_start_pagefault(inode->i_sb);
9071         page_start = page_offset(page);
9072         page_end = page_start + PAGE_SIZE - 1;
9073         end = page_end;
9074
9075         /*
9076          * Reserving delalloc space after obtaining the page lock can lead to
9077          * deadlock. For example, if a dirty page is locked by this function
9078          * and the call to btrfs_delalloc_reserve_space() ends up triggering
9079          * dirty page write out, then the btrfs_writepage() function could
9080          * end up waiting indefinitely to get a lock on the page currently
9081          * being processed by btrfs_page_mkwrite() function.
9082          */
9083         ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
9084                                            reserved_space);
9085         if (!ret) {
9086                 ret = file_update_time(vmf->vma->vm_file);
9087                 reserved = 1;
9088         }
9089         if (ret) {
9090                 if (ret == -ENOMEM)
9091                         ret = VM_FAULT_OOM;
9092                 else /* -ENOSPC, -EIO, etc */
9093                         ret = VM_FAULT_SIGBUS;
9094                 if (reserved)
9095                         goto out;
9096                 goto out_noreserve;
9097         }
9098
9099         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
9100 again:
9101         lock_page(page);
9102         size = i_size_read(inode);
9103
9104         if ((page->mapping != inode->i_mapping) ||
9105             (page_start >= size)) {
9106                 /* page got truncated out from underneath us */
9107                 goto out_unlock;
9108         }
9109         wait_on_page_writeback(page);
9110
9111         lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9112         set_page_extent_mapped(page);
9113
9114         /*
9115          * we can't set the delalloc bits if there are pending ordered
9116          * extents.  Drop our locks and wait for them to finish
9117          */
9118         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
9119                         PAGE_SIZE);
9120         if (ordered) {
9121                 unlock_extent_cached(io_tree, page_start, page_end,
9122                                      &cached_state, GFP_NOFS);
9123                 unlock_page(page);
9124                 btrfs_start_ordered_extent(inode, ordered, 1);
9125                 btrfs_put_ordered_extent(ordered);
9126                 goto again;
9127         }
9128
9129         if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9130                 reserved_space = round_up(size - page_start,
9131                                           fs_info->sectorsize);
9132                 if (reserved_space < PAGE_SIZE) {
9133                         end = page_start + reserved_space - 1;
9134                         btrfs_delalloc_release_space(inode, data_reserved,
9135                                         page_start, PAGE_SIZE - reserved_space);
9136                 }
9137         }
9138
9139         /*
9140          * page_mkwrite gets called when the page is firstly dirtied after it's
9141          * faulted in, but write(2) could also dirty a page and set delalloc
9142          * bits, thus in this case for space account reason, we still need to
9143          * clear any delalloc bits within this page range since we have to
9144          * reserve data&meta space before lock_page() (see above comments).
9145          */
9146         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9147                           EXTENT_DIRTY | EXTENT_DELALLOC |
9148                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9149                           0, 0, &cached_state);
9150
9151         ret = btrfs_set_extent_delalloc(inode, page_start, end, 0,
9152                                         &cached_state, 0);
9153         if (ret) {
9154                 unlock_extent_cached(io_tree, page_start, page_end,
9155                                      &cached_state, GFP_NOFS);
9156                 ret = VM_FAULT_SIGBUS;
9157                 goto out_unlock;
9158         }
9159         ret = 0;
9160
9161         /* page is wholly or partially inside EOF */
9162         if (page_start + PAGE_SIZE > size)
9163                 zero_start = size & ~PAGE_MASK;
9164         else
9165                 zero_start = PAGE_SIZE;
9166
9167         if (zero_start != PAGE_SIZE) {
9168                 kaddr = kmap(page);
9169                 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9170                 flush_dcache_page(page);
9171                 kunmap(page);
9172         }
9173         ClearPageChecked(page);
9174         set_page_dirty(page);
9175         SetPageUptodate(page);
9176
9177         BTRFS_I(inode)->last_trans = fs_info->generation;
9178         BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9179         BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9180
9181         unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
9182
9183 out_unlock:
9184         if (!ret) {
9185                 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9186                 sb_end_pagefault(inode->i_sb);
9187                 extent_changeset_free(data_reserved);
9188                 return VM_FAULT_LOCKED;
9189         }
9190         unlock_page(page);
9191 out:
9192         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9193         btrfs_delalloc_release_space(inode, data_reserved, page_start,
9194                                      reserved_space);
9195 out_noreserve:
9196         sb_end_pagefault(inode->i_sb);
9197         extent_changeset_free(data_reserved);
9198         return ret;
9199 }
9200
9201 static int btrfs_truncate(struct inode *inode)
9202 {
9203         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9204         struct btrfs_root *root = BTRFS_I(inode)->root;
9205         struct btrfs_block_rsv *rsv;
9206         int ret = 0;
9207         int err = 0;
9208         struct btrfs_trans_handle *trans;
9209         u64 mask = fs_info->sectorsize - 1;
9210         u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9211
9212         ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9213                                        (u64)-1);
9214         if (ret)
9215                 return ret;
9216
9217         /*
9218          * Yes ladies and gentlemen, this is indeed ugly.  The fact is we have
9219          * 3 things going on here
9220          *
9221          * 1) We need to reserve space for our orphan item and the space to
9222          * delete our orphan item.  Lord knows we don't want to have a dangling
9223          * orphan item because we didn't reserve space to remove it.
9224          *
9225          * 2) We need to reserve space to update our inode.
9226          *
9227          * 3) We need to have something to cache all the space that is going to
9228          * be free'd up by the truncate operation, but also have some slack
9229          * space reserved in case it uses space during the truncate (thank you
9230          * very much snapshotting).
9231          *
9232          * And we need these to all be separate.  The fact is we can use a lot of
9233          * space doing the truncate, and we have no earthly idea how much space
9234          * we will use, so we need the truncate reservation to be separate so it
9235          * doesn't end up using space reserved for updating the inode or
9236          * removing the orphan item.  We also need to be able to stop the
9237          * transaction and start a new one, which means we need to be able to
9238          * update the inode several times, and we have no idea of knowing how
9239          * many times that will be, so we can't just reserve 1 item for the
9240          * entirety of the operation, so that has to be done separately as well.
9241          * Then there is the orphan item, which does indeed need to be held on
9242          * to for the whole operation, and we need nobody to touch this reserved
9243          * space except the orphan code.
9244          *
9245          * So that leaves us with
9246          *
9247          * 1) root->orphan_block_rsv - for the orphan deletion.
9248          * 2) rsv - for the truncate reservation, which we will steal from the
9249          * transaction reservation.
9250          * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9251          * updating the inode.
9252          */
9253         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9254         if (!rsv)
9255                 return -ENOMEM;
9256         rsv->size = min_size;
9257         rsv->failfast = 1;
9258
9259         /*
9260          * 1 for the truncate slack space
9261          * 1 for updating the inode.
9262          */
9263         trans = btrfs_start_transaction(root, 2);
9264         if (IS_ERR(trans)) {
9265                 err = PTR_ERR(trans);
9266                 goto out;
9267         }
9268
9269         /* Migrate the slack space for the truncate to our reserve */
9270         ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9271                                       min_size, 0);
9272         BUG_ON(ret);
9273
9274         /*
9275          * So if we truncate and then write and fsync we normally would just
9276          * write the extents that changed, which is a problem if we need to
9277          * first truncate that entire inode.  So set this flag so we write out
9278          * all of the extents in the inode to the sync log so we're completely
9279          * safe.
9280          */
9281         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9282         trans->block_rsv = rsv;
9283
9284         while (1) {
9285                 ret = btrfs_truncate_inode_items(trans, root, inode,
9286                                                  inode->i_size,
9287                                                  BTRFS_EXTENT_DATA_KEY);
9288                 trans->block_rsv = &fs_info->trans_block_rsv;
9289                 if (ret != -ENOSPC && ret != -EAGAIN) {
9290                         err = ret;
9291                         break;
9292                 }
9293
9294                 ret = btrfs_update_inode(trans, root, inode);
9295                 if (ret) {
9296                         err = ret;
9297                         break;
9298                 }
9299
9300                 btrfs_end_transaction(trans);
9301                 btrfs_btree_balance_dirty(fs_info);
9302
9303                 trans = btrfs_start_transaction(root, 2);
9304                 if (IS_ERR(trans)) {
9305                         ret = err = PTR_ERR(trans);
9306                         trans = NULL;
9307                         break;
9308                 }
9309
9310                 btrfs_block_rsv_release(fs_info, rsv, -1);
9311                 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9312                                               rsv, min_size, 0);
9313                 BUG_ON(ret);    /* shouldn't happen */
9314                 trans->block_rsv = rsv;
9315         }
9316
9317         /*
9318          * We can't call btrfs_truncate_block inside a trans handle as we could
9319          * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9320          * we've truncated everything except the last little bit, and can do
9321          * btrfs_truncate_block and then update the disk_i_size.
9322          */
9323         if (ret == NEED_TRUNCATE_BLOCK) {
9324                 btrfs_end_transaction(trans);
9325                 btrfs_btree_balance_dirty(fs_info);
9326
9327                 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9328                 if (ret)
9329                         goto out;
9330                 trans = btrfs_start_transaction(root, 1);
9331                 if (IS_ERR(trans)) {
9332                         ret = PTR_ERR(trans);
9333                         goto out;
9334                 }
9335                 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9336         }
9337
9338         if (ret == 0 && inode->i_nlink > 0) {
9339                 trans->block_rsv = root->orphan_block_rsv;
9340                 ret = btrfs_orphan_del(trans, BTRFS_I(inode));
9341                 if (ret)
9342                         err = ret;
9343         }
9344
9345         if (trans) {
9346                 trans->block_rsv = &fs_info->trans_block_rsv;
9347                 ret = btrfs_update_inode(trans, root, inode);
9348                 if (ret && !err)
9349                         err = ret;
9350
9351                 ret = btrfs_end_transaction(trans);
9352                 btrfs_btree_balance_dirty(fs_info);
9353         }
9354 out:
9355         btrfs_free_block_rsv(fs_info, rsv);
9356
9357         if (ret && !err)
9358                 err = ret;
9359
9360         return err;
9361 }
9362
9363 /*
9364  * create a new subvolume directory/inode (helper for the ioctl).
9365  */
9366 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9367                              struct btrfs_root *new_root,
9368                              struct btrfs_root *parent_root,
9369                              u64 new_dirid)
9370 {
9371         struct inode *inode;
9372         int err;
9373         u64 index = 0;
9374
9375         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9376                                 new_dirid, new_dirid,
9377                                 S_IFDIR | (~current_umask() & S_IRWXUGO),
9378                                 &index);
9379         if (IS_ERR(inode))
9380                 return PTR_ERR(inode);
9381         inode->i_op = &btrfs_dir_inode_operations;
9382         inode->i_fop = &btrfs_dir_file_operations;
9383
9384         set_nlink(inode, 1);
9385         btrfs_i_size_write(BTRFS_I(inode), 0);
9386         unlock_new_inode(inode);
9387
9388         err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9389         if (err)
9390                 btrfs_err(new_root->fs_info,
9391                           "error inheriting subvolume %llu properties: %d",
9392                           new_root->root_key.objectid, err);
9393
9394         err = btrfs_update_inode(trans, new_root, inode);
9395
9396         iput(inode);
9397         return err;
9398 }
9399
9400 struct inode *btrfs_alloc_inode(struct super_block *sb)
9401 {
9402         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9403         struct btrfs_inode *ei;
9404         struct inode *inode;
9405
9406         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9407         if (!ei)
9408                 return NULL;
9409
9410         ei->root = NULL;
9411         ei->generation = 0;
9412         ei->last_trans = 0;
9413         ei->last_sub_trans = 0;
9414         ei->logged_trans = 0;
9415         ei->delalloc_bytes = 0;
9416         ei->new_delalloc_bytes = 0;
9417         ei->defrag_bytes = 0;
9418         ei->disk_i_size = 0;
9419         ei->flags = 0;
9420         ei->csum_bytes = 0;
9421         ei->index_cnt = (u64)-1;
9422         ei->dir_index = 0;
9423         ei->last_unlink_trans = 0;
9424         ei->last_log_commit = 0;
9425         ei->delayed_iput_count = 0;
9426
9427         spin_lock_init(&ei->lock);
9428         ei->outstanding_extents = 0;
9429         if (sb->s_magic != BTRFS_TEST_MAGIC)
9430                 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9431                                               BTRFS_BLOCK_RSV_DELALLOC);
9432         ei->runtime_flags = 0;
9433         ei->prop_compress = BTRFS_COMPRESS_NONE;
9434         ei->defrag_compress = BTRFS_COMPRESS_NONE;
9435
9436         ei->delayed_node = NULL;
9437
9438         ei->i_otime.tv_sec = 0;
9439         ei->i_otime.tv_nsec = 0;
9440
9441         inode = &ei->vfs_inode;
9442         extent_map_tree_init(&ei->extent_tree);
9443         extent_io_tree_init(&ei->io_tree, inode);
9444         extent_io_tree_init(&ei->io_failure_tree, inode);
9445         ei->io_tree.track_uptodate = 1;
9446         ei->io_failure_tree.track_uptodate = 1;
9447         atomic_set(&ei->sync_writers, 0);
9448         mutex_init(&ei->log_mutex);
9449         mutex_init(&ei->delalloc_mutex);
9450         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9451         INIT_LIST_HEAD(&ei->delalloc_inodes);
9452         INIT_LIST_HEAD(&ei->delayed_iput);
9453         RB_CLEAR_NODE(&ei->rb_node);
9454         init_rwsem(&ei->dio_sem);
9455
9456         return inode;
9457 }
9458
9459 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9460 void btrfs_test_destroy_inode(struct inode *inode)
9461 {
9462         btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9463         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9464 }
9465 #endif
9466
9467 static void btrfs_i_callback(struct rcu_head *head)
9468 {
9469         struct inode *inode = container_of(head, struct inode, i_rcu);
9470         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9471 }
9472
9473 void btrfs_destroy_inode(struct inode *inode)
9474 {
9475         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9476         struct btrfs_ordered_extent *ordered;
9477         struct btrfs_root *root = BTRFS_I(inode)->root;
9478
9479         WARN_ON(!hlist_empty(&inode->i_dentry));
9480         WARN_ON(inode->i_data.nrpages);
9481         WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9482         WARN_ON(BTRFS_I(inode)->block_rsv.size);
9483         WARN_ON(BTRFS_I(inode)->outstanding_extents);
9484         WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9485         WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9486         WARN_ON(BTRFS_I(inode)->csum_bytes);
9487         WARN_ON(BTRFS_I(inode)->defrag_bytes);
9488
9489         /*
9490          * This can happen where we create an inode, but somebody else also
9491          * created the same inode and we need to destroy the one we already
9492          * created.
9493          */
9494         if (!root)
9495                 goto free;
9496
9497         if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9498                      &BTRFS_I(inode)->runtime_flags)) {
9499                 btrfs_info(fs_info, "inode %llu still on the orphan list",
9500                            btrfs_ino(BTRFS_I(inode)));
9501                 atomic_dec(&root->orphan_inodes);
9502         }
9503
9504         while (1) {
9505                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9506                 if (!ordered)
9507                         break;
9508                 else {
9509                         btrfs_err(fs_info,
9510                                   "found ordered extent %llu %llu on inode cleanup",
9511                                   ordered->file_offset, ordered->len);
9512                         btrfs_remove_ordered_extent(inode, ordered);
9513                         btrfs_put_ordered_extent(ordered);
9514                         btrfs_put_ordered_extent(ordered);
9515                 }
9516         }
9517         btrfs_qgroup_check_reserved_leak(inode);
9518         inode_tree_del(inode);
9519         btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9520 free:
9521         call_rcu(&inode->i_rcu, btrfs_i_callback);
9522 }
9523
9524 int btrfs_drop_inode(struct inode *inode)
9525 {
9526         struct btrfs_root *root = BTRFS_I(inode)->root;
9527
9528         if (root == NULL)
9529                 return 1;
9530
9531         /* the snap/subvol tree is on deleting */
9532         if (btrfs_root_refs(&root->root_item) == 0)
9533                 return 1;
9534         else
9535                 return generic_drop_inode(inode);
9536 }
9537
9538 static void init_once(void *foo)
9539 {
9540         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9541
9542         inode_init_once(&ei->vfs_inode);
9543 }
9544
9545 void btrfs_destroy_cachep(void)
9546 {
9547         /*
9548          * Make sure all delayed rcu free inodes are flushed before we
9549          * destroy cache.
9550          */
9551         rcu_barrier();
9552         kmem_cache_destroy(btrfs_inode_cachep);
9553         kmem_cache_destroy(btrfs_trans_handle_cachep);
9554         kmem_cache_destroy(btrfs_path_cachep);
9555         kmem_cache_destroy(btrfs_free_space_cachep);
9556 }
9557
9558 int __init btrfs_init_cachep(void)
9559 {
9560         btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9561                         sizeof(struct btrfs_inode), 0,
9562                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9563                         init_once);
9564         if (!btrfs_inode_cachep)
9565                 goto fail;
9566
9567         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9568                         sizeof(struct btrfs_trans_handle), 0,
9569                         SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9570         if (!btrfs_trans_handle_cachep)
9571                 goto fail;
9572
9573         btrfs_path_cachep = kmem_cache_create("btrfs_path",
9574                         sizeof(struct btrfs_path), 0,
9575                         SLAB_MEM_SPREAD, NULL);
9576         if (!btrfs_path_cachep)
9577                 goto fail;
9578
9579         btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9580                         sizeof(struct btrfs_free_space), 0,
9581                         SLAB_MEM_SPREAD, NULL);
9582         if (!btrfs_free_space_cachep)
9583                 goto fail;
9584
9585         return 0;
9586 fail:
9587         btrfs_destroy_cachep();
9588         return -ENOMEM;
9589 }
9590
9591 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9592                          u32 request_mask, unsigned int flags)
9593 {
9594         u64 delalloc_bytes;
9595         struct inode *inode = d_inode(path->dentry);
9596         u32 blocksize = inode->i_sb->s_blocksize;
9597         u32 bi_flags = BTRFS_I(inode)->flags;
9598
9599         stat->result_mask |= STATX_BTIME;
9600         stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9601         stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9602         if (bi_flags & BTRFS_INODE_APPEND)
9603                 stat->attributes |= STATX_ATTR_APPEND;
9604         if (bi_flags & BTRFS_INODE_COMPRESS)
9605                 stat->attributes |= STATX_ATTR_COMPRESSED;
9606         if (bi_flags & BTRFS_INODE_IMMUTABLE)
9607                 stat->attributes |= STATX_ATTR_IMMUTABLE;
9608         if (bi_flags & BTRFS_INODE_NODUMP)
9609                 stat->attributes |= STATX_ATTR_NODUMP;
9610
9611         stat->attributes_mask |= (STATX_ATTR_APPEND |
9612                                   STATX_ATTR_COMPRESSED |
9613                                   STATX_ATTR_IMMUTABLE |
9614                                   STATX_ATTR_NODUMP);
9615
9616         generic_fillattr(inode, stat);
9617         stat->dev = BTRFS_I(inode)->root->anon_dev;
9618
9619         spin_lock(&BTRFS_I(inode)->lock);
9620         delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9621         spin_unlock(&BTRFS_I(inode)->lock);
9622         stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9623                         ALIGN(delalloc_bytes, blocksize)) >> 9;
9624         return 0;
9625 }
9626
9627 static int btrfs_rename_exchange(struct inode *old_dir,
9628                               struct dentry *old_dentry,
9629                               struct inode *new_dir,
9630                               struct dentry *new_dentry)
9631 {
9632         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9633         struct btrfs_trans_handle *trans;
9634         struct btrfs_root *root = BTRFS_I(old_dir)->root;
9635         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9636         struct inode *new_inode = new_dentry->d_inode;
9637         struct inode *old_inode = old_dentry->d_inode;
9638         struct timespec ctime = current_time(old_inode);
9639         struct dentry *parent;
9640         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9641         u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9642         u64 old_idx = 0;
9643         u64 new_idx = 0;
9644         u64 root_objectid;
9645         int ret;
9646         bool root_log_pinned = false;
9647         bool dest_log_pinned = false;
9648
9649         /* we only allow rename subvolume link between subvolumes */
9650         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9651                 return -EXDEV;
9652
9653         /* close the race window with snapshot create/destroy ioctl */
9654         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9655                 down_read(&fs_info->subvol_sem);
9656         if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9657                 down_read(&fs_info->subvol_sem);
9658
9659         /*
9660          * We want to reserve the absolute worst case amount of items.  So if
9661          * both inodes are subvols and we need to unlink them then that would
9662          * require 4 item modifications, but if they are both normal inodes it
9663          * would require 5 item modifications, so we'll assume their normal
9664          * inodes.  So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9665          * should cover the worst case number of items we'll modify.
9666          */
9667         trans = btrfs_start_transaction(root, 12);
9668         if (IS_ERR(trans)) {
9669                 ret = PTR_ERR(trans);
9670                 goto out_notrans;
9671         }
9672
9673         /*
9674          * We need to find a free sequence number both in the source and
9675          * in the destination directory for the exchange.
9676          */
9677         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9678         if (ret)
9679                 goto out_fail;
9680         ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9681         if (ret)
9682                 goto out_fail;
9683
9684         BTRFS_I(old_inode)->dir_index = 0ULL;
9685         BTRFS_I(new_inode)->dir_index = 0ULL;
9686
9687         /* Reference for the source. */
9688         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9689                 /* force full log commit if subvolume involved. */
9690                 btrfs_set_log_full_commit(fs_info, trans);
9691         } else {
9692                 btrfs_pin_log_trans(root);
9693                 root_log_pinned = true;
9694                 ret = btrfs_insert_inode_ref(trans, dest,
9695                                              new_dentry->d_name.name,
9696                                              new_dentry->d_name.len,
9697                                              old_ino,
9698                                              btrfs_ino(BTRFS_I(new_dir)),
9699                                              old_idx);
9700                 if (ret)
9701                         goto out_fail;
9702         }
9703
9704         /* And now for the dest. */
9705         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9706                 /* force full log commit if subvolume involved. */
9707                 btrfs_set_log_full_commit(fs_info, trans);
9708         } else {
9709                 btrfs_pin_log_trans(dest);
9710                 dest_log_pinned = true;
9711                 ret = btrfs_insert_inode_ref(trans, root,
9712                                              old_dentry->d_name.name,
9713                                              old_dentry->d_name.len,
9714                                              new_ino,
9715                                              btrfs_ino(BTRFS_I(old_dir)),
9716                                              new_idx);
9717                 if (ret)
9718                         goto out_fail;
9719         }
9720
9721         /* Update inode version and ctime/mtime. */
9722         inode_inc_iversion(old_dir);
9723         inode_inc_iversion(new_dir);
9724         inode_inc_iversion(old_inode);
9725         inode_inc_iversion(new_inode);
9726         old_dir->i_ctime = old_dir->i_mtime = ctime;
9727         new_dir->i_ctime = new_dir->i_mtime = ctime;
9728         old_inode->i_ctime = ctime;
9729         new_inode->i_ctime = ctime;
9730
9731         if (old_dentry->d_parent != new_dentry->d_parent) {
9732                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9733                                 BTRFS_I(old_inode), 1);
9734                 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9735                                 BTRFS_I(new_inode), 1);
9736         }
9737
9738         /* src is a subvolume */
9739         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9740                 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9741                 ret = btrfs_unlink_subvol(trans, root, old_dir,
9742                                           root_objectid,
9743                                           old_dentry->d_name.name,
9744                                           old_dentry->d_name.len);
9745         } else { /* src is an inode */
9746                 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9747                                            BTRFS_I(old_dentry->d_inode),
9748                                            old_dentry->d_name.name,
9749                                            old_dentry->d_name.len);
9750                 if (!ret)
9751                         ret = btrfs_update_inode(trans, root, old_inode);
9752         }
9753         if (ret) {
9754                 btrfs_abort_transaction(trans, ret);
9755                 goto out_fail;
9756         }
9757
9758         /* dest is a subvolume */
9759         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9760                 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9761                 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9762                                           root_objectid,
9763                                           new_dentry->d_name.name,
9764                                           new_dentry->d_name.len);
9765         } else { /* dest is an inode */
9766                 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9767                                            BTRFS_I(new_dentry->d_inode),
9768                                            new_dentry->d_name.name,
9769                                            new_dentry->d_name.len);
9770                 if (!ret)
9771                         ret = btrfs_update_inode(trans, dest, new_inode);
9772         }
9773         if (ret) {
9774                 btrfs_abort_transaction(trans, ret);
9775                 goto out_fail;
9776         }
9777
9778         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9779                              new_dentry->d_name.name,
9780                              new_dentry->d_name.len, 0, old_idx);
9781         if (ret) {
9782                 btrfs_abort_transaction(trans, ret);
9783                 goto out_fail;
9784         }
9785
9786         ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9787                              old_dentry->d_name.name,
9788                              old_dentry->d_name.len, 0, new_idx);
9789         if (ret) {
9790                 btrfs_abort_transaction(trans, ret);
9791                 goto out_fail;
9792         }
9793
9794         if (old_inode->i_nlink == 1)
9795                 BTRFS_I(old_inode)->dir_index = old_idx;
9796         if (new_inode->i_nlink == 1)
9797                 BTRFS_I(new_inode)->dir_index = new_idx;
9798
9799         if (root_log_pinned) {
9800                 parent = new_dentry->d_parent;
9801                 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9802                                 parent);
9803                 btrfs_end_log_trans(root);
9804                 root_log_pinned = false;
9805         }
9806         if (dest_log_pinned) {
9807                 parent = old_dentry->d_parent;
9808                 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9809                                 parent);
9810                 btrfs_end_log_trans(dest);
9811                 dest_log_pinned = false;
9812         }
9813 out_fail:
9814         /*
9815          * If we have pinned a log and an error happened, we unpin tasks
9816          * trying to sync the log and force them to fallback to a transaction
9817          * commit if the log currently contains any of the inodes involved in
9818          * this rename operation (to ensure we do not persist a log with an
9819          * inconsistent state for any of these inodes or leading to any
9820          * inconsistencies when replayed). If the transaction was aborted, the
9821          * abortion reason is propagated to userspace when attempting to commit
9822          * the transaction. If the log does not contain any of these inodes, we
9823          * allow the tasks to sync it.
9824          */
9825         if (ret && (root_log_pinned || dest_log_pinned)) {
9826                 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9827                     btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9828                     btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9829                     (new_inode &&
9830                      btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9831                         btrfs_set_log_full_commit(fs_info, trans);
9832
9833                 if (root_log_pinned) {
9834                         btrfs_end_log_trans(root);
9835                         root_log_pinned = false;
9836                 }
9837                 if (dest_log_pinned) {
9838                         btrfs_end_log_trans(dest);
9839                         dest_log_pinned = false;
9840                 }
9841         }
9842         ret = btrfs_end_transaction(trans);
9843 out_notrans:
9844         if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9845                 up_read(&fs_info->subvol_sem);
9846         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9847                 up_read(&fs_info->subvol_sem);
9848
9849         return ret;
9850 }
9851
9852 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9853                                      struct btrfs_root *root,
9854                                      struct inode *dir,
9855                                      struct dentry *dentry)
9856 {
9857         int ret;
9858         struct inode *inode;
9859         u64 objectid;
9860         u64 index;
9861
9862         ret = btrfs_find_free_ino(root, &objectid);
9863         if (ret)
9864                 return ret;
9865
9866         inode = btrfs_new_inode(trans, root, dir,
9867                                 dentry->d_name.name,
9868                                 dentry->d_name.len,
9869                                 btrfs_ino(BTRFS_I(dir)),
9870                                 objectid,
9871                                 S_IFCHR | WHITEOUT_MODE,
9872                                 &index);
9873
9874         if (IS_ERR(inode)) {
9875                 ret = PTR_ERR(inode);
9876                 return ret;
9877         }
9878
9879         inode->i_op = &btrfs_special_inode_operations;
9880         init_special_inode(inode, inode->i_mode,
9881                 WHITEOUT_DEV);
9882
9883         ret = btrfs_init_inode_security(trans, inode, dir,
9884                                 &dentry->d_name);
9885         if (ret)
9886                 goto out;
9887
9888         ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9889                                 BTRFS_I(inode), 0, index);
9890         if (ret)
9891                 goto out;
9892
9893         ret = btrfs_update_inode(trans, root, inode);
9894 out:
9895         unlock_new_inode(inode);
9896         if (ret)
9897                 inode_dec_link_count(inode);
9898         iput(inode);
9899
9900         return ret;
9901 }
9902
9903 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9904                            struct inode *new_dir, struct dentry *new_dentry,
9905                            unsigned int flags)
9906 {
9907         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9908         struct btrfs_trans_handle *trans;
9909         unsigned int trans_num_items;
9910         struct btrfs_root *root = BTRFS_I(old_dir)->root;
9911         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9912         struct inode *new_inode = d_inode(new_dentry);
9913         struct inode *old_inode = d_inode(old_dentry);
9914         u64 index = 0;
9915         u64 root_objectid;
9916         int ret;
9917         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9918         bool log_pinned = false;
9919
9920         if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9921                 return -EPERM;
9922
9923         /* we only allow rename subvolume link between subvolumes */
9924         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9925                 return -EXDEV;
9926
9927         if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9928             (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9929                 return -ENOTEMPTY;
9930
9931         if (S_ISDIR(old_inode->i_mode) && new_inode &&
9932             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9933                 return -ENOTEMPTY;
9934
9935
9936         /* check for collisions, even if the  name isn't there */
9937         ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9938                              new_dentry->d_name.name,
9939                              new_dentry->d_name.len);
9940
9941         if (ret) {
9942                 if (ret == -EEXIST) {
9943                         /* we shouldn't get
9944                          * eexist without a new_inode */
9945                         if (WARN_ON(!new_inode)) {
9946                                 return ret;
9947                         }
9948                 } else {
9949                         /* maybe -EOVERFLOW */
9950                         return ret;
9951                 }
9952         }
9953         ret = 0;
9954
9955         /*
9956          * we're using rename to replace one file with another.  Start IO on it
9957          * now so  we don't add too much work to the end of the transaction
9958          */
9959         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9960                 filemap_flush(old_inode->i_mapping);
9961
9962         /* close the racy window with snapshot create/destroy ioctl */
9963         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9964                 down_read(&fs_info->subvol_sem);
9965         /*
9966          * We want to reserve the absolute worst case amount of items.  So if
9967          * both inodes are subvols and we need to unlink them then that would
9968          * require 4 item modifications, but if they are both normal inodes it
9969          * would require 5 item modifications, so we'll assume they are normal
9970          * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9971          * should cover the worst case number of items we'll modify.
9972          * If our rename has the whiteout flag, we need more 5 units for the
9973          * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9974          * when selinux is enabled).
9975          */
9976         trans_num_items = 11;
9977         if (flags & RENAME_WHITEOUT)
9978                 trans_num_items += 5;
9979         trans = btrfs_start_transaction(root, trans_num_items);
9980         if (IS_ERR(trans)) {
9981                 ret = PTR_ERR(trans);
9982                 goto out_notrans;
9983         }
9984
9985         if (dest != root)
9986                 btrfs_record_root_in_trans(trans, dest);
9987
9988         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9989         if (ret)
9990                 goto out_fail;
9991
9992         BTRFS_I(old_inode)->dir_index = 0ULL;
9993         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9994                 /* force full log commit if subvolume involved. */
9995                 btrfs_set_log_full_commit(fs_info, trans);
9996         } else {
9997                 btrfs_pin_log_trans(root);
9998                 log_pinned = true;
9999                 ret = btrfs_insert_inode_ref(trans, dest,
10000                                              new_dentry->d_name.name,
10001                                              new_dentry->d_name.len,
10002                                              old_ino,
10003                                              btrfs_ino(BTRFS_I(new_dir)), index);
10004                 if (ret)
10005                         goto out_fail;
10006         }
10007
10008         inode_inc_iversion(old_dir);
10009         inode_inc_iversion(new_dir);
10010         inode_inc_iversion(old_inode);
10011         old_dir->i_ctime = old_dir->i_mtime =
10012         new_dir->i_ctime = new_dir->i_mtime =
10013         old_inode->i_ctime = current_time(old_dir);
10014
10015         if (old_dentry->d_parent != new_dentry->d_parent)
10016                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
10017                                 BTRFS_I(old_inode), 1);
10018
10019         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
10020                 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
10021                 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
10022                                         old_dentry->d_name.name,
10023                                         old_dentry->d_name.len);
10024         } else {
10025                 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
10026                                         BTRFS_I(d_inode(old_dentry)),
10027                                         old_dentry->d_name.name,
10028                                         old_dentry->d_name.len);
10029                 if (!ret)
10030                         ret = btrfs_update_inode(trans, root, old_inode);
10031         }
10032         if (ret) {
10033                 btrfs_abort_transaction(trans, ret);
10034                 goto out_fail;
10035         }
10036
10037         if (new_inode) {
10038                 inode_inc_iversion(new_inode);
10039                 new_inode->i_ctime = current_time(new_inode);
10040                 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
10041                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
10042                         root_objectid = BTRFS_I(new_inode)->location.objectid;
10043                         ret = btrfs_unlink_subvol(trans, dest, new_dir,
10044                                                 root_objectid,
10045                                                 new_dentry->d_name.name,
10046                                                 new_dentry->d_name.len);
10047                         BUG_ON(new_inode->i_nlink == 0);
10048                 } else {
10049                         ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
10050                                                  BTRFS_I(d_inode(new_dentry)),
10051                                                  new_dentry->d_name.name,
10052                                                  new_dentry->d_name.len);
10053                 }
10054                 if (!ret && new_inode->i_nlink == 0)
10055                         ret = btrfs_orphan_add(trans,
10056                                         BTRFS_I(d_inode(new_dentry)));
10057                 if (ret) {
10058                         btrfs_abort_transaction(trans, ret);
10059                         goto out_fail;
10060                 }
10061         }
10062
10063         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
10064                              new_dentry->d_name.name,
10065                              new_dentry->d_name.len, 0, index);
10066         if (ret) {
10067                 btrfs_abort_transaction(trans, ret);
10068                 goto out_fail;
10069         }
10070
10071         if (old_inode->i_nlink == 1)
10072                 BTRFS_I(old_inode)->dir_index = index;
10073
10074         if (log_pinned) {
10075                 struct dentry *parent = new_dentry->d_parent;
10076
10077                 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
10078                                 parent);
10079                 btrfs_end_log_trans(root);
10080                 log_pinned = false;
10081         }
10082
10083         if (flags & RENAME_WHITEOUT) {
10084                 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
10085                                                 old_dentry);
10086
10087                 if (ret) {
10088                         btrfs_abort_transaction(trans, ret);
10089                         goto out_fail;
10090                 }
10091         }
10092 out_fail:
10093         /*
10094          * If we have pinned the log and an error happened, we unpin tasks
10095          * trying to sync the log and force them to fallback to a transaction
10096          * commit if the log currently contains any of the inodes involved in
10097          * this rename operation (to ensure we do not persist a log with an
10098          * inconsistent state for any of these inodes or leading to any
10099          * inconsistencies when replayed). If the transaction was aborted, the
10100          * abortion reason is propagated to userspace when attempting to commit
10101          * the transaction. If the log does not contain any of these inodes, we
10102          * allow the tasks to sync it.
10103          */
10104         if (ret && log_pinned) {
10105                 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10106                     btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10107                     btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10108                     (new_inode &&
10109                      btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10110                         btrfs_set_log_full_commit(fs_info, trans);
10111
10112                 btrfs_end_log_trans(root);
10113                 log_pinned = false;
10114         }
10115         btrfs_end_transaction(trans);
10116 out_notrans:
10117         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10118                 up_read(&fs_info->subvol_sem);
10119
10120         return ret;
10121 }
10122
10123 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10124                          struct inode *new_dir, struct dentry *new_dentry,
10125                          unsigned int flags)
10126 {
10127         if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10128                 return -EINVAL;
10129
10130         if (flags & RENAME_EXCHANGE)
10131                 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10132                                           new_dentry);
10133
10134         return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10135 }
10136
10137 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10138 {
10139         struct btrfs_delalloc_work *delalloc_work;
10140         struct inode *inode;
10141
10142         delalloc_work = container_of(work, struct btrfs_delalloc_work,
10143                                      work);
10144         inode = delalloc_work->inode;
10145         filemap_flush(inode->i_mapping);
10146         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10147                                 &BTRFS_I(inode)->runtime_flags))
10148                 filemap_flush(inode->i_mapping);
10149
10150         if (delalloc_work->delay_iput)
10151                 btrfs_add_delayed_iput(inode);
10152         else
10153                 iput(inode);
10154         complete(&delalloc_work->completion);
10155 }
10156
10157 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
10158                                                     int delay_iput)
10159 {
10160         struct btrfs_delalloc_work *work;
10161
10162         work = kmalloc(sizeof(*work), GFP_NOFS);
10163         if (!work)
10164                 return NULL;
10165
10166         init_completion(&work->completion);
10167         INIT_LIST_HEAD(&work->list);
10168         work->inode = inode;
10169         work->delay_iput = delay_iput;
10170         WARN_ON_ONCE(!inode);
10171         btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10172                         btrfs_run_delalloc_work, NULL, NULL);
10173
10174         return work;
10175 }
10176
10177 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
10178 {
10179         wait_for_completion(&work->completion);
10180         kfree(work);
10181 }
10182
10183 /*
10184  * some fairly slow code that needs optimization. This walks the list
10185  * of all the inodes with pending delalloc and forces them to disk.
10186  */
10187 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
10188                                    int nr)
10189 {
10190         struct btrfs_inode *binode;
10191         struct inode *inode;
10192         struct btrfs_delalloc_work *work, *next;
10193         struct list_head works;
10194         struct list_head splice;
10195         int ret = 0;
10196
10197         INIT_LIST_HEAD(&works);
10198         INIT_LIST_HEAD(&splice);
10199
10200         mutex_lock(&root->delalloc_mutex);
10201         spin_lock(&root->delalloc_lock);
10202         list_splice_init(&root->delalloc_inodes, &splice);
10203         while (!list_empty(&splice)) {
10204                 binode = list_entry(splice.next, struct btrfs_inode,
10205                                     delalloc_inodes);
10206
10207                 list_move_tail(&binode->delalloc_inodes,
10208                                &root->delalloc_inodes);
10209                 inode = igrab(&binode->vfs_inode);
10210                 if (!inode) {
10211                         cond_resched_lock(&root->delalloc_lock);
10212                         continue;
10213                 }
10214                 spin_unlock(&root->delalloc_lock);
10215
10216                 work = btrfs_alloc_delalloc_work(inode, delay_iput);
10217                 if (!work) {
10218                         if (delay_iput)
10219                                 btrfs_add_delayed_iput(inode);
10220                         else
10221                                 iput(inode);
10222                         ret = -ENOMEM;
10223                         goto out;
10224                 }
10225                 list_add_tail(&work->list, &works);
10226                 btrfs_queue_work(root->fs_info->flush_workers,
10227                                  &work->work);
10228                 ret++;
10229                 if (nr != -1 && ret >= nr)
10230                         goto out;
10231                 cond_resched();
10232                 spin_lock(&root->delalloc_lock);
10233         }
10234         spin_unlock(&root->delalloc_lock);
10235
10236 out:
10237         list_for_each_entry_safe(work, next, &works, list) {
10238                 list_del_init(&work->list);
10239                 btrfs_wait_and_free_delalloc_work(work);
10240         }
10241
10242         if (!list_empty_careful(&splice)) {
10243                 spin_lock(&root->delalloc_lock);
10244                 list_splice_tail(&splice, &root->delalloc_inodes);
10245                 spin_unlock(&root->delalloc_lock);
10246         }
10247         mutex_unlock(&root->delalloc_mutex);
10248         return ret;
10249 }
10250
10251 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10252 {
10253         struct btrfs_fs_info *fs_info = root->fs_info;
10254         int ret;
10255
10256         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10257                 return -EROFS;
10258
10259         ret = __start_delalloc_inodes(root, delay_iput, -1);
10260         if (ret > 0)
10261                 ret = 0;
10262         return ret;
10263 }
10264
10265 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10266                                int nr)
10267 {
10268         struct btrfs_root *root;
10269         struct list_head splice;
10270         int ret;
10271
10272         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10273                 return -EROFS;
10274
10275         INIT_LIST_HEAD(&splice);
10276
10277         mutex_lock(&fs_info->delalloc_root_mutex);
10278         spin_lock(&fs_info->delalloc_root_lock);
10279         list_splice_init(&fs_info->delalloc_roots, &splice);
10280         while (!list_empty(&splice) && nr) {
10281                 root = list_first_entry(&splice, struct btrfs_root,
10282                                         delalloc_root);
10283                 root = btrfs_grab_fs_root(root);
10284                 BUG_ON(!root);
10285                 list_move_tail(&root->delalloc_root,
10286                                &fs_info->delalloc_roots);
10287                 spin_unlock(&fs_info->delalloc_root_lock);
10288
10289                 ret = __start_delalloc_inodes(root, delay_iput, nr);
10290                 btrfs_put_fs_root(root);
10291                 if (ret < 0)
10292                         goto out;
10293
10294                 if (nr != -1) {
10295                         nr -= ret;
10296                         WARN_ON(nr < 0);
10297                 }
10298                 spin_lock(&fs_info->delalloc_root_lock);
10299         }
10300         spin_unlock(&fs_info->delalloc_root_lock);
10301
10302         ret = 0;
10303 out:
10304         if (!list_empty_careful(&splice)) {
10305                 spin_lock(&fs_info->delalloc_root_lock);
10306                 list_splice_tail(&splice, &fs_info->delalloc_roots);
10307                 spin_unlock(&fs_info->delalloc_root_lock);
10308         }
10309         mutex_unlock(&fs_info->delalloc_root_mutex);
10310         return ret;
10311 }
10312
10313 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10314                          const char *symname)
10315 {
10316         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10317         struct btrfs_trans_handle *trans;
10318         struct btrfs_root *root = BTRFS_I(dir)->root;
10319         struct btrfs_path *path;
10320         struct btrfs_key key;
10321         struct inode *inode = NULL;
10322         int err;
10323         int drop_inode = 0;
10324         u64 objectid;
10325         u64 index = 0;
10326         int name_len;
10327         int datasize;
10328         unsigned long ptr;
10329         struct btrfs_file_extent_item *ei;
10330         struct extent_buffer *leaf;
10331
10332         name_len = strlen(symname);
10333         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10334                 return -ENAMETOOLONG;
10335
10336         /*
10337          * 2 items for inode item and ref
10338          * 2 items for dir items
10339          * 1 item for updating parent inode item
10340          * 1 item for the inline extent item
10341          * 1 item for xattr if selinux is on
10342          */
10343         trans = btrfs_start_transaction(root, 7);
10344         if (IS_ERR(trans))
10345                 return PTR_ERR(trans);
10346
10347         err = btrfs_find_free_ino(root, &objectid);
10348         if (err)
10349                 goto out_unlock;
10350
10351         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10352                                 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10353                                 objectid, S_IFLNK|S_IRWXUGO, &index);
10354         if (IS_ERR(inode)) {
10355                 err = PTR_ERR(inode);
10356                 goto out_unlock;
10357         }
10358
10359         /*
10360         * If the active LSM wants to access the inode during
10361         * d_instantiate it needs these. Smack checks to see
10362         * if the filesystem supports xattrs by looking at the
10363         * ops vector.
10364         */
10365         inode->i_fop = &btrfs_file_operations;
10366         inode->i_op = &btrfs_file_inode_operations;
10367         inode->i_mapping->a_ops = &btrfs_aops;
10368         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10369
10370         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10371         if (err)
10372                 goto out_unlock_inode;
10373
10374         path = btrfs_alloc_path();
10375         if (!path) {
10376                 err = -ENOMEM;
10377                 goto out_unlock_inode;
10378         }
10379         key.objectid = btrfs_ino(BTRFS_I(inode));
10380         key.offset = 0;
10381         key.type = BTRFS_EXTENT_DATA_KEY;
10382         datasize = btrfs_file_extent_calc_inline_size(name_len);
10383         err = btrfs_insert_empty_item(trans, root, path, &key,
10384                                       datasize);
10385         if (err) {
10386                 btrfs_free_path(path);
10387                 goto out_unlock_inode;
10388         }
10389         leaf = path->nodes[0];
10390         ei = btrfs_item_ptr(leaf, path->slots[0],
10391                             struct btrfs_file_extent_item);
10392         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10393         btrfs_set_file_extent_type(leaf, ei,
10394                                    BTRFS_FILE_EXTENT_INLINE);
10395         btrfs_set_file_extent_encryption(leaf, ei, 0);
10396         btrfs_set_file_extent_compression(leaf, ei, 0);
10397         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10398         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10399
10400         ptr = btrfs_file_extent_inline_start(ei);
10401         write_extent_buffer(leaf, symname, ptr, name_len);
10402         btrfs_mark_buffer_dirty(leaf);
10403         btrfs_free_path(path);
10404
10405         inode->i_op = &btrfs_symlink_inode_operations;
10406         inode_nohighmem(inode);
10407         inode->i_mapping->a_ops = &btrfs_symlink_aops;
10408         inode_set_bytes(inode, name_len);
10409         btrfs_i_size_write(BTRFS_I(inode), name_len);
10410         err = btrfs_update_inode(trans, root, inode);
10411         /*
10412          * Last step, add directory indexes for our symlink inode. This is the
10413          * last step to avoid extra cleanup of these indexes if an error happens
10414          * elsewhere above.
10415          */
10416         if (!err)
10417                 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10418                                 BTRFS_I(inode), 0, index);
10419         if (err) {
10420                 drop_inode = 1;
10421                 goto out_unlock_inode;
10422         }
10423
10424         unlock_new_inode(inode);
10425         d_instantiate(dentry, inode);
10426
10427 out_unlock:
10428         btrfs_end_transaction(trans);
10429         if (drop_inode) {
10430                 inode_dec_link_count(inode);
10431                 iput(inode);
10432         }
10433         btrfs_btree_balance_dirty(fs_info);
10434         return err;
10435
10436 out_unlock_inode:
10437         drop_inode = 1;
10438         unlock_new_inode(inode);
10439         goto out_unlock;
10440 }
10441
10442 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10443                                        u64 start, u64 num_bytes, u64 min_size,
10444                                        loff_t actual_len, u64 *alloc_hint,
10445                                        struct btrfs_trans_handle *trans)
10446 {
10447         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10448         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10449         struct extent_map *em;
10450         struct btrfs_root *root = BTRFS_I(inode)->root;
10451         struct btrfs_key ins;
10452         u64 cur_offset = start;
10453         u64 i_size;
10454         u64 cur_bytes;
10455         u64 last_alloc = (u64)-1;
10456         int ret = 0;
10457         bool own_trans = true;
10458         u64 end = start + num_bytes - 1;
10459
10460         if (trans)
10461                 own_trans = false;
10462         while (num_bytes > 0) {
10463                 if (own_trans) {
10464                         trans = btrfs_start_transaction(root, 3);
10465                         if (IS_ERR(trans)) {
10466                                 ret = PTR_ERR(trans);
10467                                 break;
10468                         }
10469                 }
10470
10471                 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10472                 cur_bytes = max(cur_bytes, min_size);
10473                 /*
10474                  * If we are severely fragmented we could end up with really
10475                  * small allocations, so if the allocator is returning small
10476                  * chunks lets make its job easier by only searching for those
10477                  * sized chunks.
10478                  */
10479                 cur_bytes = min(cur_bytes, last_alloc);
10480                 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10481                                 min_size, 0, *alloc_hint, &ins, 1, 0);
10482                 if (ret) {
10483                         if (own_trans)
10484                                 btrfs_end_transaction(trans);
10485                         break;
10486                 }
10487                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10488
10489                 last_alloc = ins.offset;
10490                 ret = insert_reserved_file_extent(trans, inode,
10491                                                   cur_offset, ins.objectid,
10492                                                   ins.offset, ins.offset,
10493                                                   ins.offset, 0, 0, 0,
10494                                                   BTRFS_FILE_EXTENT_PREALLOC);
10495                 if (ret) {
10496                         btrfs_free_reserved_extent(fs_info, ins.objectid,
10497                                                    ins.offset, 0);
10498                         btrfs_abort_transaction(trans, ret);
10499                         if (own_trans)
10500                                 btrfs_end_transaction(trans);
10501                         break;
10502                 }
10503
10504                 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10505                                         cur_offset + ins.offset -1, 0);
10506
10507                 em = alloc_extent_map();
10508                 if (!em) {
10509                         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10510                                 &BTRFS_I(inode)->runtime_flags);
10511                         goto next;
10512                 }
10513
10514                 em->start = cur_offset;
10515                 em->orig_start = cur_offset;
10516                 em->len = ins.offset;
10517                 em->block_start = ins.objectid;
10518                 em->block_len = ins.offset;
10519                 em->orig_block_len = ins.offset;
10520                 em->ram_bytes = ins.offset;
10521                 em->bdev = fs_info->fs_devices->latest_bdev;
10522                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10523                 em->generation = trans->transid;
10524
10525                 while (1) {
10526                         write_lock(&em_tree->lock);
10527                         ret = add_extent_mapping(em_tree, em, 1);
10528                         write_unlock(&em_tree->lock);
10529                         if (ret != -EEXIST)
10530                                 break;
10531                         btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10532                                                 cur_offset + ins.offset - 1,
10533                                                 0);
10534                 }
10535                 free_extent_map(em);
10536 next:
10537                 num_bytes -= ins.offset;
10538                 cur_offset += ins.offset;
10539                 *alloc_hint = ins.objectid + ins.offset;
10540
10541                 inode_inc_iversion(inode);
10542                 inode->i_ctime = current_time(inode);
10543                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10544                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10545                     (actual_len > inode->i_size) &&
10546                     (cur_offset > inode->i_size)) {
10547                         if (cur_offset > actual_len)
10548                                 i_size = actual_len;
10549                         else
10550                                 i_size = cur_offset;
10551                         i_size_write(inode, i_size);
10552                         btrfs_ordered_update_i_size(inode, i_size, NULL);
10553                 }
10554
10555                 ret = btrfs_update_inode(trans, root, inode);
10556
10557                 if (ret) {
10558                         btrfs_abort_transaction(trans, ret);
10559                         if (own_trans)
10560                                 btrfs_end_transaction(trans);
10561                         break;
10562                 }
10563
10564                 if (own_trans)
10565                         btrfs_end_transaction(trans);
10566         }
10567         if (cur_offset < end)
10568                 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10569                         end - cur_offset + 1);
10570         return ret;
10571 }
10572
10573 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10574                               u64 start, u64 num_bytes, u64 min_size,
10575                               loff_t actual_len, u64 *alloc_hint)
10576 {
10577         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10578                                            min_size, actual_len, alloc_hint,
10579                                            NULL);
10580 }
10581
10582 int btrfs_prealloc_file_range_trans(struct inode *inode,
10583                                     struct btrfs_trans_handle *trans, int mode,
10584                                     u64 start, u64 num_bytes, u64 min_size,
10585                                     loff_t actual_len, u64 *alloc_hint)
10586 {
10587         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10588                                            min_size, actual_len, alloc_hint, trans);
10589 }
10590
10591 static int btrfs_set_page_dirty(struct page *page)
10592 {
10593         return __set_page_dirty_nobuffers(page);
10594 }
10595
10596 static int btrfs_permission(struct inode *inode, int mask)
10597 {
10598         struct btrfs_root *root = BTRFS_I(inode)->root;
10599         umode_t mode = inode->i_mode;
10600
10601         if (mask & MAY_WRITE &&
10602             (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10603                 if (btrfs_root_readonly(root))
10604                         return -EROFS;
10605                 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10606                         return -EACCES;
10607         }
10608         return generic_permission(inode, mask);
10609 }
10610
10611 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10612 {
10613         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10614         struct btrfs_trans_handle *trans;
10615         struct btrfs_root *root = BTRFS_I(dir)->root;
10616         struct inode *inode = NULL;
10617         u64 objectid;
10618         u64 index;
10619         int ret = 0;
10620
10621         /*
10622          * 5 units required for adding orphan entry
10623          */
10624         trans = btrfs_start_transaction(root, 5);
10625         if (IS_ERR(trans))
10626                 return PTR_ERR(trans);
10627
10628         ret = btrfs_find_free_ino(root, &objectid);
10629         if (ret)
10630                 goto out;
10631
10632         inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10633                         btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10634         if (IS_ERR(inode)) {
10635                 ret = PTR_ERR(inode);
10636                 inode = NULL;
10637                 goto out;
10638         }
10639
10640         inode->i_fop = &btrfs_file_operations;
10641         inode->i_op = &btrfs_file_inode_operations;
10642
10643         inode->i_mapping->a_ops = &btrfs_aops;
10644         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10645
10646         ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10647         if (ret)
10648                 goto out_inode;
10649
10650         ret = btrfs_update_inode(trans, root, inode);
10651         if (ret)
10652                 goto out_inode;
10653         ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10654         if (ret)
10655                 goto out_inode;
10656
10657         /*
10658          * We set number of links to 0 in btrfs_new_inode(), and here we set
10659          * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10660          * through:
10661          *
10662          *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10663          */
10664         set_nlink(inode, 1);
10665         unlock_new_inode(inode);
10666         d_tmpfile(dentry, inode);
10667         mark_inode_dirty(inode);
10668
10669 out:
10670         btrfs_end_transaction(trans);
10671         if (ret)
10672                 iput(inode);
10673         btrfs_btree_balance_dirty(fs_info);
10674         return ret;
10675
10676 out_inode:
10677         unlock_new_inode(inode);
10678         goto out;
10679
10680 }
10681
10682 __attribute__((const))
10683 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10684 {
10685         return -EAGAIN;
10686 }
10687
10688 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10689 {
10690         struct inode *inode = private_data;
10691         return btrfs_sb(inode->i_sb);
10692 }
10693
10694 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10695                                         u64 start, u64 end)
10696 {
10697         struct inode *inode = private_data;
10698         u64 isize;
10699
10700         isize = i_size_read(inode);
10701         if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10702                 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10703                     "%s: ino %llu isize %llu odd range [%llu,%llu]",
10704                         caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10705         }
10706 }
10707
10708 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10709 {
10710         struct inode *inode = private_data;
10711         unsigned long index = start >> PAGE_SHIFT;
10712         unsigned long end_index = end >> PAGE_SHIFT;
10713         struct page *page;
10714
10715         while (index <= end_index) {
10716                 page = find_get_page(inode->i_mapping, index);
10717                 ASSERT(page); /* Pages should be in the extent_io_tree */
10718                 set_page_writeback(page);
10719                 put_page(page);
10720                 index++;
10721         }
10722 }
10723
10724 static const struct inode_operations btrfs_dir_inode_operations = {
10725         .getattr        = btrfs_getattr,
10726         .lookup         = btrfs_lookup,
10727         .create         = btrfs_create,
10728         .unlink         = btrfs_unlink,
10729         .link           = btrfs_link,
10730         .mkdir          = btrfs_mkdir,
10731         .rmdir          = btrfs_rmdir,
10732         .rename         = btrfs_rename2,
10733         .symlink        = btrfs_symlink,
10734         .setattr        = btrfs_setattr,
10735         .mknod          = btrfs_mknod,
10736         .listxattr      = btrfs_listxattr,
10737         .permission     = btrfs_permission,
10738         .get_acl        = btrfs_get_acl,
10739         .set_acl        = btrfs_set_acl,
10740         .update_time    = btrfs_update_time,
10741         .tmpfile        = btrfs_tmpfile,
10742 };
10743 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10744         .lookup         = btrfs_lookup,
10745         .permission     = btrfs_permission,
10746         .update_time    = btrfs_update_time,
10747 };
10748
10749 static const struct file_operations btrfs_dir_file_operations = {
10750         .llseek         = generic_file_llseek,
10751         .read           = generic_read_dir,
10752         .iterate_shared = btrfs_real_readdir,
10753         .open           = btrfs_opendir,
10754         .unlocked_ioctl = btrfs_ioctl,
10755 #ifdef CONFIG_COMPAT
10756         .compat_ioctl   = btrfs_compat_ioctl,
10757 #endif
10758         .release        = btrfs_release_file,
10759         .fsync          = btrfs_sync_file,
10760 };
10761
10762 static const struct extent_io_ops btrfs_extent_io_ops = {
10763         /* mandatory callbacks */
10764         .submit_bio_hook = btrfs_submit_bio_hook,
10765         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10766         .merge_bio_hook = btrfs_merge_bio_hook,
10767         .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10768         .tree_fs_info = iotree_fs_info,
10769         .set_range_writeback = btrfs_set_range_writeback,
10770
10771         /* optional callbacks */
10772         .fill_delalloc = run_delalloc_range,
10773         .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10774         .writepage_start_hook = btrfs_writepage_start_hook,
10775         .set_bit_hook = btrfs_set_bit_hook,
10776         .clear_bit_hook = btrfs_clear_bit_hook,
10777         .merge_extent_hook = btrfs_merge_extent_hook,
10778         .split_extent_hook = btrfs_split_extent_hook,
10779         .check_extent_io_range = btrfs_check_extent_io_range,
10780 };
10781
10782 /*
10783  * btrfs doesn't support the bmap operation because swapfiles
10784  * use bmap to make a mapping of extents in the file.  They assume
10785  * these extents won't change over the life of the file and they
10786  * use the bmap result to do IO directly to the drive.
10787  *
10788  * the btrfs bmap call would return logical addresses that aren't
10789  * suitable for IO and they also will change frequently as COW
10790  * operations happen.  So, swapfile + btrfs == corruption.
10791  *
10792  * For now we're avoiding this by dropping bmap.
10793  */
10794 static const struct address_space_operations btrfs_aops = {
10795         .readpage       = btrfs_readpage,
10796         .writepage      = btrfs_writepage,
10797         .writepages     = btrfs_writepages,
10798         .readpages      = btrfs_readpages,
10799         .direct_IO      = btrfs_direct_IO,
10800         .invalidatepage = btrfs_invalidatepage,
10801         .releasepage    = btrfs_releasepage,
10802         .set_page_dirty = btrfs_set_page_dirty,
10803         .error_remove_page = generic_error_remove_page,
10804 };
10805
10806 static const struct address_space_operations btrfs_symlink_aops = {
10807         .readpage       = btrfs_readpage,
10808         .writepage      = btrfs_writepage,
10809         .invalidatepage = btrfs_invalidatepage,
10810         .releasepage    = btrfs_releasepage,
10811 };
10812
10813 static const struct inode_operations btrfs_file_inode_operations = {
10814         .getattr        = btrfs_getattr,
10815         .setattr        = btrfs_setattr,
10816         .listxattr      = btrfs_listxattr,
10817         .permission     = btrfs_permission,
10818         .fiemap         = btrfs_fiemap,
10819         .get_acl        = btrfs_get_acl,
10820         .set_acl        = btrfs_set_acl,
10821         .update_time    = btrfs_update_time,
10822 };
10823 static const struct inode_operations btrfs_special_inode_operations = {
10824         .getattr        = btrfs_getattr,
10825         .setattr        = btrfs_setattr,
10826         .permission     = btrfs_permission,
10827         .listxattr      = btrfs_listxattr,
10828         .get_acl        = btrfs_get_acl,
10829         .set_acl        = btrfs_set_acl,
10830         .update_time    = btrfs_update_time,
10831 };
10832 static const struct inode_operations btrfs_symlink_inode_operations = {
10833         .get_link       = page_get_link,
10834         .getattr        = btrfs_getattr,
10835         .setattr        = btrfs_setattr,
10836         .permission     = btrfs_permission,
10837         .listxattr      = btrfs_listxattr,
10838         .update_time    = btrfs_update_time,
10839 };
10840
10841 const struct dentry_operations btrfs_dentry_operations = {
10842         .d_delete       = btrfs_dentry_delete,
10843         .d_release      = btrfs_dentry_release,
10844 };