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