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