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