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