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