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