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