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