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