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