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