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