]> git.karo-electronics.de Git - karo-tx-linux.git/blob - fs/btrfs/inode.c
Merge remote-tracking branch 'xfs/for-next'
[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 (WARN_ON(ret < 0))
2043                 return ret;
2044         ret = 0;
2045
2046         while (1) {
2047                 cond_resched();
2048
2049                 leaf = path->nodes[0];
2050                 slot = path->slots[0];
2051
2052                 if (slot >= btrfs_header_nritems(leaf)) {
2053                         ret = btrfs_next_leaf(root, path);
2054                         if (ret < 0) {
2055                                 goto out;
2056                         } else if (ret > 0) {
2057                                 ret = 0;
2058                                 goto out;
2059                         }
2060                         continue;
2061                 }
2062
2063                 path->slots[0]++;
2064
2065                 btrfs_item_key_to_cpu(leaf, &key, slot);
2066
2067                 if (key.objectid > inum)
2068                         goto out;
2069
2070                 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2071                         continue;
2072
2073                 extent = btrfs_item_ptr(leaf, slot,
2074                                         struct btrfs_file_extent_item);
2075
2076                 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2077                         continue;
2078
2079                 /*
2080                  * 'offset' refers to the exact key.offset,
2081                  * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2082                  * (key.offset - extent_offset).
2083                  */
2084                 if (key.offset != offset)
2085                         continue;
2086
2087                 extent_offset = btrfs_file_extent_offset(leaf, extent);
2088                 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2089
2090                 if (extent_offset >= old->extent_offset + old->offset +
2091                     old->len || extent_offset + num_bytes <=
2092                     old->extent_offset + old->offset)
2093                         continue;
2094                 break;
2095         }
2096
2097         backref = kmalloc(sizeof(*backref), GFP_NOFS);
2098         if (!backref) {
2099                 ret = -ENOENT;
2100                 goto out;
2101         }
2102
2103         backref->root_id = root_id;
2104         backref->inum = inum;
2105         backref->file_pos = offset;
2106         backref->num_bytes = num_bytes;
2107         backref->extent_offset = extent_offset;
2108         backref->generation = btrfs_file_extent_generation(leaf, extent);
2109         backref->old = old;
2110         backref_insert(&new->root, backref);
2111         old->count++;
2112 out:
2113         btrfs_release_path(path);
2114         WARN_ON(ret);
2115         return ret;
2116 }
2117
2118 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2119                                    struct new_sa_defrag_extent *new)
2120 {
2121         struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2122         struct old_sa_defrag_extent *old, *tmp;
2123         int ret;
2124
2125         new->path = path;
2126
2127         list_for_each_entry_safe(old, tmp, &new->head, list) {
2128                 ret = iterate_inodes_from_logical(old->bytenr +
2129                                                   old->extent_offset, fs_info,
2130                                                   path, record_one_backref,
2131                                                   old);
2132                 if (ret < 0 && ret != -ENOENT)
2133                         return false;
2134
2135                 /* no backref to be processed for this extent */
2136                 if (!old->count) {
2137                         list_del(&old->list);
2138                         kfree(old);
2139                 }
2140         }
2141
2142         if (list_empty(&new->head))
2143                 return false;
2144
2145         return true;
2146 }
2147
2148 static int relink_is_mergable(struct extent_buffer *leaf,
2149                               struct btrfs_file_extent_item *fi,
2150                               struct new_sa_defrag_extent *new)
2151 {
2152         if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2153                 return 0;
2154
2155         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2156                 return 0;
2157
2158         if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2159                 return 0;
2160
2161         if (btrfs_file_extent_encryption(leaf, fi) ||
2162             btrfs_file_extent_other_encoding(leaf, fi))
2163                 return 0;
2164
2165         return 1;
2166 }
2167
2168 /*
2169  * Note the backref might has changed, and in this case we just return 0.
2170  */
2171 static noinline int relink_extent_backref(struct btrfs_path *path,
2172                                  struct sa_defrag_extent_backref *prev,
2173                                  struct sa_defrag_extent_backref *backref)
2174 {
2175         struct btrfs_file_extent_item *extent;
2176         struct btrfs_file_extent_item *item;
2177         struct btrfs_ordered_extent *ordered;
2178         struct btrfs_trans_handle *trans;
2179         struct btrfs_fs_info *fs_info;
2180         struct btrfs_root *root;
2181         struct btrfs_key key;
2182         struct extent_buffer *leaf;
2183         struct old_sa_defrag_extent *old = backref->old;
2184         struct new_sa_defrag_extent *new = old->new;
2185         struct inode *src_inode = new->inode;
2186         struct inode *inode;
2187         struct extent_state *cached = NULL;
2188         int ret = 0;
2189         u64 start;
2190         u64 len;
2191         u64 lock_start;
2192         u64 lock_end;
2193         bool merge = false;
2194         int index;
2195
2196         if (prev && prev->root_id == backref->root_id &&
2197             prev->inum == backref->inum &&
2198             prev->file_pos + prev->num_bytes == backref->file_pos)
2199                 merge = true;
2200
2201         /* step 1: get root */
2202         key.objectid = backref->root_id;
2203         key.type = BTRFS_ROOT_ITEM_KEY;
2204         key.offset = (u64)-1;
2205
2206         fs_info = BTRFS_I(src_inode)->root->fs_info;
2207         index = srcu_read_lock(&fs_info->subvol_srcu);
2208
2209         root = btrfs_read_fs_root_no_name(fs_info, &key);
2210         if (IS_ERR(root)) {
2211                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2212                 if (PTR_ERR(root) == -ENOENT)
2213                         return 0;
2214                 return PTR_ERR(root);
2215         }
2216
2217         /* step 2: get inode */
2218         key.objectid = backref->inum;
2219         key.type = BTRFS_INODE_ITEM_KEY;
2220         key.offset = 0;
2221
2222         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2223         if (IS_ERR(inode)) {
2224                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2225                 return 0;
2226         }
2227
2228         srcu_read_unlock(&fs_info->subvol_srcu, index);
2229
2230         /* step 3: relink backref */
2231         lock_start = backref->file_pos;
2232         lock_end = backref->file_pos + backref->num_bytes - 1;
2233         lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2234                          0, &cached);
2235
2236         ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2237         if (ordered) {
2238                 btrfs_put_ordered_extent(ordered);
2239                 goto out_unlock;
2240         }
2241
2242         trans = btrfs_join_transaction(root);
2243         if (IS_ERR(trans)) {
2244                 ret = PTR_ERR(trans);
2245                 goto out_unlock;
2246         }
2247
2248         key.objectid = backref->inum;
2249         key.type = BTRFS_EXTENT_DATA_KEY;
2250         key.offset = backref->file_pos;
2251
2252         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2253         if (ret < 0) {
2254                 goto out_free_path;
2255         } else if (ret > 0) {
2256                 ret = 0;
2257                 goto out_free_path;
2258         }
2259
2260         extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2261                                 struct btrfs_file_extent_item);
2262
2263         if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2264             backref->generation)
2265                 goto out_free_path;
2266
2267         btrfs_release_path(path);
2268
2269         start = backref->file_pos;
2270         if (backref->extent_offset < old->extent_offset + old->offset)
2271                 start += old->extent_offset + old->offset -
2272                          backref->extent_offset;
2273
2274         len = min(backref->extent_offset + backref->num_bytes,
2275                   old->extent_offset + old->offset + old->len);
2276         len -= max(backref->extent_offset, old->extent_offset + old->offset);
2277
2278         ret = btrfs_drop_extents(trans, root, inode, start,
2279                                  start + len, 1);
2280         if (ret)
2281                 goto out_free_path;
2282 again:
2283         key.objectid = btrfs_ino(inode);
2284         key.type = BTRFS_EXTENT_DATA_KEY;
2285         key.offset = start;
2286
2287         path->leave_spinning = 1;
2288         if (merge) {
2289                 struct btrfs_file_extent_item *fi;
2290                 u64 extent_len;
2291                 struct btrfs_key found_key;
2292
2293                 ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
2294                 if (ret < 0)
2295                         goto out_free_path;
2296
2297                 path->slots[0]--;
2298                 leaf = path->nodes[0];
2299                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2300
2301                 fi = btrfs_item_ptr(leaf, path->slots[0],
2302                                     struct btrfs_file_extent_item);
2303                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2304
2305                 if (extent_len + found_key.offset == start &&
2306                     relink_is_mergable(leaf, fi, new)) {
2307                         btrfs_set_file_extent_num_bytes(leaf, fi,
2308                                                         extent_len + len);
2309                         btrfs_mark_buffer_dirty(leaf);
2310                         inode_add_bytes(inode, len);
2311
2312                         ret = 1;
2313                         goto out_free_path;
2314                 } else {
2315                         merge = false;
2316                         btrfs_release_path(path);
2317                         goto again;
2318                 }
2319         }
2320
2321         ret = btrfs_insert_empty_item(trans, root, path, &key,
2322                                         sizeof(*extent));
2323         if (ret) {
2324                 btrfs_abort_transaction(trans, root, ret);
2325                 goto out_free_path;
2326         }
2327
2328         leaf = path->nodes[0];
2329         item = btrfs_item_ptr(leaf, path->slots[0],
2330                                 struct btrfs_file_extent_item);
2331         btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2332         btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2333         btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2334         btrfs_set_file_extent_num_bytes(leaf, item, len);
2335         btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2336         btrfs_set_file_extent_generation(leaf, item, trans->transid);
2337         btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2338         btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2339         btrfs_set_file_extent_encryption(leaf, item, 0);
2340         btrfs_set_file_extent_other_encoding(leaf, item, 0);
2341
2342         btrfs_mark_buffer_dirty(leaf);
2343         inode_add_bytes(inode, len);
2344         btrfs_release_path(path);
2345
2346         ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2347                         new->disk_len, 0,
2348                         backref->root_id, backref->inum,
2349                         new->file_pos, 0);      /* start - extent_offset */
2350         if (ret) {
2351                 btrfs_abort_transaction(trans, root, ret);
2352                 goto out_free_path;
2353         }
2354
2355         ret = 1;
2356 out_free_path:
2357         btrfs_release_path(path);
2358         path->leave_spinning = 0;
2359         btrfs_end_transaction(trans, root);
2360 out_unlock:
2361         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2362                              &cached, GFP_NOFS);
2363         iput(inode);
2364         return ret;
2365 }
2366
2367 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2368 {
2369         struct old_sa_defrag_extent *old, *tmp;
2370
2371         if (!new)
2372                 return;
2373
2374         list_for_each_entry_safe(old, tmp, &new->head, list) {
2375                 list_del(&old->list);
2376                 kfree(old);
2377         }
2378         kfree(new);
2379 }
2380
2381 static void relink_file_extents(struct new_sa_defrag_extent *new)
2382 {
2383         struct btrfs_path *path;
2384         struct sa_defrag_extent_backref *backref;
2385         struct sa_defrag_extent_backref *prev = NULL;
2386         struct inode *inode;
2387         struct btrfs_root *root;
2388         struct rb_node *node;
2389         int ret;
2390
2391         inode = new->inode;
2392         root = BTRFS_I(inode)->root;
2393
2394         path = btrfs_alloc_path();
2395         if (!path)
2396                 return;
2397
2398         if (!record_extent_backrefs(path, new)) {
2399                 btrfs_free_path(path);
2400                 goto out;
2401         }
2402         btrfs_release_path(path);
2403
2404         while (1) {
2405                 node = rb_first(&new->root);
2406                 if (!node)
2407                         break;
2408                 rb_erase(node, &new->root);
2409
2410                 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2411
2412                 ret = relink_extent_backref(path, prev, backref);
2413                 WARN_ON(ret < 0);
2414
2415                 kfree(prev);
2416
2417                 if (ret == 1)
2418                         prev = backref;
2419                 else
2420                         prev = NULL;
2421                 cond_resched();
2422         }
2423         kfree(prev);
2424
2425         btrfs_free_path(path);
2426 out:
2427         free_sa_defrag_extent(new);
2428
2429         atomic_dec(&root->fs_info->defrag_running);
2430         wake_up(&root->fs_info->transaction_wait);
2431 }
2432
2433 static struct new_sa_defrag_extent *
2434 record_old_file_extents(struct inode *inode,
2435                         struct btrfs_ordered_extent *ordered)
2436 {
2437         struct btrfs_root *root = BTRFS_I(inode)->root;
2438         struct btrfs_path *path;
2439         struct btrfs_key key;
2440         struct old_sa_defrag_extent *old;
2441         struct new_sa_defrag_extent *new;
2442         int ret;
2443
2444         new = kmalloc(sizeof(*new), GFP_NOFS);
2445         if (!new)
2446                 return NULL;
2447
2448         new->inode = inode;
2449         new->file_pos = ordered->file_offset;
2450         new->len = ordered->len;
2451         new->bytenr = ordered->start;
2452         new->disk_len = ordered->disk_len;
2453         new->compress_type = ordered->compress_type;
2454         new->root = RB_ROOT;
2455         INIT_LIST_HEAD(&new->head);
2456
2457         path = btrfs_alloc_path();
2458         if (!path)
2459                 goto out_kfree;
2460
2461         key.objectid = btrfs_ino(inode);
2462         key.type = BTRFS_EXTENT_DATA_KEY;
2463         key.offset = new->file_pos;
2464
2465         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2466         if (ret < 0)
2467                 goto out_free_path;
2468         if (ret > 0 && path->slots[0] > 0)
2469                 path->slots[0]--;
2470
2471         /* find out all the old extents for the file range */
2472         while (1) {
2473                 struct btrfs_file_extent_item *extent;
2474                 struct extent_buffer *l;
2475                 int slot;
2476                 u64 num_bytes;
2477                 u64 offset;
2478                 u64 end;
2479                 u64 disk_bytenr;
2480                 u64 extent_offset;
2481
2482                 l = path->nodes[0];
2483                 slot = path->slots[0];
2484
2485                 if (slot >= btrfs_header_nritems(l)) {
2486                         ret = btrfs_next_leaf(root, path);
2487                         if (ret < 0)
2488                                 goto out_free_path;
2489                         else if (ret > 0)
2490                                 break;
2491                         continue;
2492                 }
2493
2494                 btrfs_item_key_to_cpu(l, &key, slot);
2495
2496                 if (key.objectid != btrfs_ino(inode))
2497                         break;
2498                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2499                         break;
2500                 if (key.offset >= new->file_pos + new->len)
2501                         break;
2502
2503                 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2504
2505                 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2506                 if (key.offset + num_bytes < new->file_pos)
2507                         goto next;
2508
2509                 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2510                 if (!disk_bytenr)
2511                         goto next;
2512
2513                 extent_offset = btrfs_file_extent_offset(l, extent);
2514
2515                 old = kmalloc(sizeof(*old), GFP_NOFS);
2516                 if (!old)
2517                         goto out_free_path;
2518
2519                 offset = max(new->file_pos, key.offset);
2520                 end = min(new->file_pos + new->len, key.offset + num_bytes);
2521
2522                 old->bytenr = disk_bytenr;
2523                 old->extent_offset = extent_offset;
2524                 old->offset = offset - key.offset;
2525                 old->len = end - offset;
2526                 old->new = new;
2527                 old->count = 0;
2528                 list_add_tail(&old->list, &new->head);
2529 next:
2530                 path->slots[0]++;
2531                 cond_resched();
2532         }
2533
2534         btrfs_free_path(path);
2535         atomic_inc(&root->fs_info->defrag_running);
2536
2537         return new;
2538
2539 out_free_path:
2540         btrfs_free_path(path);
2541 out_kfree:
2542         free_sa_defrag_extent(new);
2543         return NULL;
2544 }
2545
2546 /* as ordered data IO finishes, this gets called so we can finish
2547  * an ordered extent if the range of bytes in the file it covers are
2548  * fully written.
2549  */
2550 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2551 {
2552         struct inode *inode = ordered_extent->inode;
2553         struct btrfs_root *root = BTRFS_I(inode)->root;
2554         struct btrfs_trans_handle *trans = NULL;
2555         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2556         struct extent_state *cached_state = NULL;
2557         struct new_sa_defrag_extent *new = NULL;
2558         int compress_type = 0;
2559         int ret = 0;
2560         u64 logical_len = ordered_extent->len;
2561         bool nolock;
2562         bool truncated = false;
2563
2564         nolock = btrfs_is_free_space_inode(inode);
2565
2566         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2567                 ret = -EIO;
2568                 goto out;
2569         }
2570
2571         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2572                 truncated = true;
2573                 logical_len = ordered_extent->truncated_len;
2574                 /* Truncated the entire extent, don't bother adding */
2575                 if (!logical_len)
2576                         goto out;
2577         }
2578
2579         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2580                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2581                 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2582                 if (nolock)
2583                         trans = btrfs_join_transaction_nolock(root);
2584                 else
2585                         trans = btrfs_join_transaction(root);
2586                 if (IS_ERR(trans)) {
2587                         ret = PTR_ERR(trans);
2588                         trans = NULL;
2589                         goto out;
2590                 }
2591                 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2592                 ret = btrfs_update_inode_fallback(trans, root, inode);
2593                 if (ret) /* -ENOMEM or corruption */
2594                         btrfs_abort_transaction(trans, root, ret);
2595                 goto out;
2596         }
2597
2598         lock_extent_bits(io_tree, ordered_extent->file_offset,
2599                          ordered_extent->file_offset + ordered_extent->len - 1,
2600                          0, &cached_state);
2601
2602         ret = test_range_bit(io_tree, ordered_extent->file_offset,
2603                         ordered_extent->file_offset + ordered_extent->len - 1,
2604                         EXTENT_DEFRAG, 1, cached_state);
2605         if (ret) {
2606                 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2607                 if (last_snapshot >= BTRFS_I(inode)->generation)
2608                         /* the inode is shared */
2609                         new = record_old_file_extents(inode, ordered_extent);
2610
2611                 clear_extent_bit(io_tree, ordered_extent->file_offset,
2612                         ordered_extent->file_offset + ordered_extent->len - 1,
2613                         EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2614         }
2615
2616         if (nolock)
2617                 trans = btrfs_join_transaction_nolock(root);
2618         else
2619                 trans = btrfs_join_transaction(root);
2620         if (IS_ERR(trans)) {
2621                 ret = PTR_ERR(trans);
2622                 trans = NULL;
2623                 goto out_unlock;
2624         }
2625         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2626
2627         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2628                 compress_type = ordered_extent->compress_type;
2629         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2630                 BUG_ON(compress_type);
2631                 ret = btrfs_mark_extent_written(trans, inode,
2632                                                 ordered_extent->file_offset,
2633                                                 ordered_extent->file_offset +
2634                                                 logical_len);
2635         } else {
2636                 BUG_ON(root == root->fs_info->tree_root);
2637                 ret = insert_reserved_file_extent(trans, inode,
2638                                                 ordered_extent->file_offset,
2639                                                 ordered_extent->start,
2640                                                 ordered_extent->disk_len,
2641                                                 logical_len, logical_len,
2642                                                 compress_type, 0, 0,
2643                                                 BTRFS_FILE_EXTENT_REG);
2644         }
2645         unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2646                            ordered_extent->file_offset, ordered_extent->len,
2647                            trans->transid);
2648         if (ret < 0) {
2649                 btrfs_abort_transaction(trans, root, ret);
2650                 goto out_unlock;
2651         }
2652
2653         add_pending_csums(trans, inode, ordered_extent->file_offset,
2654                           &ordered_extent->list);
2655
2656         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2657         ret = btrfs_update_inode_fallback(trans, root, inode);
2658         if (ret) { /* -ENOMEM or corruption */
2659                 btrfs_abort_transaction(trans, root, ret);
2660                 goto out_unlock;
2661         }
2662         ret = 0;
2663 out_unlock:
2664         unlock_extent_cached(io_tree, ordered_extent->file_offset,
2665                              ordered_extent->file_offset +
2666                              ordered_extent->len - 1, &cached_state, GFP_NOFS);
2667 out:
2668         if (root != root->fs_info->tree_root)
2669                 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2670         if (trans)
2671                 btrfs_end_transaction(trans, root);
2672
2673         if (ret || truncated) {
2674                 u64 start, end;
2675
2676                 if (truncated)
2677                         start = ordered_extent->file_offset + logical_len;
2678                 else
2679                         start = ordered_extent->file_offset;
2680                 end = ordered_extent->file_offset + ordered_extent->len - 1;
2681                 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2682
2683                 /* Drop the cache for the part of the extent we didn't write. */
2684                 btrfs_drop_extent_cache(inode, start, end, 0);
2685
2686                 /*
2687                  * If the ordered extent had an IOERR or something else went
2688                  * wrong we need to return the space for this ordered extent
2689                  * back to the allocator.  We only free the extent in the
2690                  * truncated case if we didn't write out the extent at all.
2691                  */
2692                 if ((ret || !logical_len) &&
2693                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2694                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2695                         btrfs_free_reserved_extent(root, ordered_extent->start,
2696                                                    ordered_extent->disk_len);
2697         }
2698
2699
2700         /*
2701          * This needs to be done to make sure anybody waiting knows we are done
2702          * updating everything for this ordered extent.
2703          */
2704         btrfs_remove_ordered_extent(inode, ordered_extent);
2705
2706         /* for snapshot-aware defrag */
2707         if (new) {
2708                 if (ret) {
2709                         free_sa_defrag_extent(new);
2710                         atomic_dec(&root->fs_info->defrag_running);
2711                 } else {
2712                         relink_file_extents(new);
2713                 }
2714         }
2715
2716         /* once for us */
2717         btrfs_put_ordered_extent(ordered_extent);
2718         /* once for the tree */
2719         btrfs_put_ordered_extent(ordered_extent);
2720
2721         return ret;
2722 }
2723
2724 static void finish_ordered_fn(struct btrfs_work *work)
2725 {
2726         struct btrfs_ordered_extent *ordered_extent;
2727         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2728         btrfs_finish_ordered_io(ordered_extent);
2729 }
2730
2731 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2732                                 struct extent_state *state, int uptodate)
2733 {
2734         struct inode *inode = page->mapping->host;
2735         struct btrfs_root *root = BTRFS_I(inode)->root;
2736         struct btrfs_ordered_extent *ordered_extent = NULL;
2737         struct btrfs_workers *workers;
2738
2739         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2740
2741         ClearPagePrivate2(page);
2742         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2743                                             end - start + 1, uptodate))
2744                 return 0;
2745
2746         ordered_extent->work.func = finish_ordered_fn;
2747         ordered_extent->work.flags = 0;
2748
2749         if (btrfs_is_free_space_inode(inode))
2750                 workers = &root->fs_info->endio_freespace_worker;
2751         else
2752                 workers = &root->fs_info->endio_write_workers;
2753         btrfs_queue_worker(workers, &ordered_extent->work);
2754
2755         return 0;
2756 }
2757
2758 /*
2759  * when reads are done, we need to check csums to verify the data is correct
2760  * if there's a match, we allow the bio to finish.  If not, the code in
2761  * extent_io.c will try to find good copies for us.
2762  */
2763 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2764                                       u64 phy_offset, struct page *page,
2765                                       u64 start, u64 end, int mirror)
2766 {
2767         size_t offset = start - page_offset(page);
2768         struct inode *inode = page->mapping->host;
2769         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2770         char *kaddr;
2771         struct btrfs_root *root = BTRFS_I(inode)->root;
2772         u32 csum_expected;
2773         u32 csum = ~(u32)0;
2774         static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2775                                       DEFAULT_RATELIMIT_BURST);
2776
2777         if (PageChecked(page)) {
2778                 ClearPageChecked(page);
2779                 goto good;
2780         }
2781
2782         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2783                 goto good;
2784
2785         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2786             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2787                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2788                                   GFP_NOFS);
2789                 return 0;
2790         }
2791
2792         phy_offset >>= inode->i_sb->s_blocksize_bits;
2793         csum_expected = *(((u32 *)io_bio->csum) + phy_offset);
2794
2795         kaddr = kmap_atomic(page);
2796         csum = btrfs_csum_data(kaddr + offset, csum,  end - start + 1);
2797         btrfs_csum_final(csum, (char *)&csum);
2798         if (csum != csum_expected)
2799                 goto zeroit;
2800
2801         kunmap_atomic(kaddr);
2802 good:
2803         return 0;
2804
2805 zeroit:
2806         if (__ratelimit(&_rs))
2807                 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
2808                         btrfs_ino(page->mapping->host), start, csum, csum_expected);
2809         memset(kaddr + offset, 1, end - start + 1);
2810         flush_dcache_page(page);
2811         kunmap_atomic(kaddr);
2812         if (csum_expected == 0)
2813                 return 0;
2814         return -EIO;
2815 }
2816
2817 struct delayed_iput {
2818         struct list_head list;
2819         struct inode *inode;
2820 };
2821
2822 /* JDM: If this is fs-wide, why can't we add a pointer to
2823  * btrfs_inode instead and avoid the allocation? */
2824 void btrfs_add_delayed_iput(struct inode *inode)
2825 {
2826         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2827         struct delayed_iput *delayed;
2828
2829         if (atomic_add_unless(&inode->i_count, -1, 1))
2830                 return;
2831
2832         delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2833         delayed->inode = inode;
2834
2835         spin_lock(&fs_info->delayed_iput_lock);
2836         list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2837         spin_unlock(&fs_info->delayed_iput_lock);
2838 }
2839
2840 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2841 {
2842         LIST_HEAD(list);
2843         struct btrfs_fs_info *fs_info = root->fs_info;
2844         struct delayed_iput *delayed;
2845         int empty;
2846
2847         spin_lock(&fs_info->delayed_iput_lock);
2848         empty = list_empty(&fs_info->delayed_iputs);
2849         spin_unlock(&fs_info->delayed_iput_lock);
2850         if (empty)
2851                 return;
2852
2853         spin_lock(&fs_info->delayed_iput_lock);
2854         list_splice_init(&fs_info->delayed_iputs, &list);
2855         spin_unlock(&fs_info->delayed_iput_lock);
2856
2857         while (!list_empty(&list)) {
2858                 delayed = list_entry(list.next, struct delayed_iput, list);
2859                 list_del(&delayed->list);
2860                 iput(delayed->inode);
2861                 kfree(delayed);
2862         }
2863 }
2864
2865 /*
2866  * This is called in transaction commit time. If there are no orphan
2867  * files in the subvolume, it removes orphan item and frees block_rsv
2868  * structure.
2869  */
2870 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2871                               struct btrfs_root *root)
2872 {
2873         struct btrfs_block_rsv *block_rsv;
2874         int ret;
2875
2876         if (atomic_read(&root->orphan_inodes) ||
2877             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2878                 return;
2879
2880         spin_lock(&root->orphan_lock);
2881         if (atomic_read(&root->orphan_inodes)) {
2882                 spin_unlock(&root->orphan_lock);
2883                 return;
2884         }
2885
2886         if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2887                 spin_unlock(&root->orphan_lock);
2888                 return;
2889         }
2890
2891         block_rsv = root->orphan_block_rsv;
2892         root->orphan_block_rsv = NULL;
2893         spin_unlock(&root->orphan_lock);
2894
2895         if (root->orphan_item_inserted &&
2896             btrfs_root_refs(&root->root_item) > 0) {
2897                 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2898                                             root->root_key.objectid);
2899                 if (ret)
2900                         btrfs_abort_transaction(trans, root, ret);
2901                 else
2902                         root->orphan_item_inserted = 0;
2903         }
2904
2905         if (block_rsv) {
2906                 WARN_ON(block_rsv->size > 0);
2907                 btrfs_free_block_rsv(root, block_rsv);
2908         }
2909 }
2910
2911 /*
2912  * This creates an orphan entry for the given inode in case something goes
2913  * wrong in the middle of an unlink/truncate.
2914  *
2915  * NOTE: caller of this function should reserve 5 units of metadata for
2916  *       this function.
2917  */
2918 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2919 {
2920         struct btrfs_root *root = BTRFS_I(inode)->root;
2921         struct btrfs_block_rsv *block_rsv = NULL;
2922         int reserve = 0;
2923         int insert = 0;
2924         int ret;
2925
2926         if (!root->orphan_block_rsv) {
2927                 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2928                 if (!block_rsv)
2929                         return -ENOMEM;
2930         }
2931
2932         spin_lock(&root->orphan_lock);
2933         if (!root->orphan_block_rsv) {
2934                 root->orphan_block_rsv = block_rsv;
2935         } else if (block_rsv) {
2936                 btrfs_free_block_rsv(root, block_rsv);
2937                 block_rsv = NULL;
2938         }
2939
2940         if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2941                               &BTRFS_I(inode)->runtime_flags)) {
2942 #if 0
2943                 /*
2944                  * For proper ENOSPC handling, we should do orphan
2945                  * cleanup when mounting. But this introduces backward
2946                  * compatibility issue.
2947                  */
2948                 if (!xchg(&root->orphan_item_inserted, 1))
2949                         insert = 2;
2950                 else
2951                         insert = 1;
2952 #endif
2953                 insert = 1;
2954                 atomic_inc(&root->orphan_inodes);
2955         }
2956
2957         if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2958                               &BTRFS_I(inode)->runtime_flags))
2959                 reserve = 1;
2960         spin_unlock(&root->orphan_lock);
2961
2962         /* grab metadata reservation from transaction handle */
2963         if (reserve) {
2964                 ret = btrfs_orphan_reserve_metadata(trans, inode);
2965                 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2966         }
2967
2968         /* insert an orphan item to track this unlinked/truncated file */
2969         if (insert >= 1) {
2970                 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2971                 if (ret) {
2972                         atomic_dec(&root->orphan_inodes);
2973                         if (reserve) {
2974                                 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2975                                           &BTRFS_I(inode)->runtime_flags);
2976                                 btrfs_orphan_release_metadata(inode);
2977                         }
2978                         if (ret != -EEXIST) {
2979                                 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2980                                           &BTRFS_I(inode)->runtime_flags);
2981                                 btrfs_abort_transaction(trans, root, ret);
2982                                 return ret;
2983                         }
2984                 }
2985                 ret = 0;
2986         }
2987
2988         /* insert an orphan item to track subvolume contains orphan files */
2989         if (insert >= 2) {
2990                 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2991                                                root->root_key.objectid);
2992                 if (ret && ret != -EEXIST) {
2993                         btrfs_abort_transaction(trans, root, ret);
2994                         return ret;
2995                 }
2996         }
2997         return 0;
2998 }
2999
3000 /*
3001  * We have done the truncate/delete so we can go ahead and remove the orphan
3002  * item for this particular inode.
3003  */
3004 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3005                             struct inode *inode)
3006 {
3007         struct btrfs_root *root = BTRFS_I(inode)->root;
3008         int delete_item = 0;
3009         int release_rsv = 0;
3010         int ret = 0;
3011
3012         spin_lock(&root->orphan_lock);
3013         if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3014                                &BTRFS_I(inode)->runtime_flags))
3015                 delete_item = 1;
3016
3017         if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3018                                &BTRFS_I(inode)->runtime_flags))
3019                 release_rsv = 1;
3020         spin_unlock(&root->orphan_lock);
3021
3022         if (delete_item) {
3023                 atomic_dec(&root->orphan_inodes);
3024                 if (trans)
3025                         ret = btrfs_del_orphan_item(trans, root,
3026                                                     btrfs_ino(inode));
3027         }
3028
3029         if (release_rsv)
3030                 btrfs_orphan_release_metadata(inode);
3031
3032         return ret;
3033 }
3034
3035 /*
3036  * this cleans up any orphans that may be left on the list from the last use
3037  * of this root.
3038  */
3039 int btrfs_orphan_cleanup(struct btrfs_root *root)
3040 {
3041         struct btrfs_path *path;
3042         struct extent_buffer *leaf;
3043         struct btrfs_key key, found_key;
3044         struct btrfs_trans_handle *trans;
3045         struct inode *inode;
3046         u64 last_objectid = 0;
3047         int ret = 0, nr_unlink = 0, nr_truncate = 0;
3048
3049         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3050                 return 0;
3051
3052         path = btrfs_alloc_path();
3053         if (!path) {
3054                 ret = -ENOMEM;
3055                 goto out;
3056         }
3057         path->reada = -1;
3058
3059         key.objectid = BTRFS_ORPHAN_OBJECTID;
3060         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3061         key.offset = (u64)-1;
3062
3063         while (1) {
3064                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3065                 if (ret < 0)
3066                         goto out;
3067
3068                 /*
3069                  * if ret == 0 means we found what we were searching for, which
3070                  * is weird, but possible, so only screw with path if we didn't
3071                  * find the key and see if we have stuff that matches
3072                  */
3073                 if (ret > 0) {
3074                         ret = 0;
3075                         if (path->slots[0] == 0)
3076                                 break;
3077                         path->slots[0]--;
3078                 }
3079
3080                 /* pull out the item */
3081                 leaf = path->nodes[0];
3082                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3083
3084                 /* make sure the item matches what we want */
3085                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3086                         break;
3087                 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3088                         break;
3089
3090                 /* release the path since we're done with it */
3091                 btrfs_release_path(path);
3092
3093                 /*
3094                  * this is where we are basically btrfs_lookup, without the
3095                  * crossing root thing.  we store the inode number in the
3096                  * offset of the orphan item.
3097                  */
3098
3099                 if (found_key.offset == last_objectid) {
3100                         btrfs_err(root->fs_info,
3101                                 "Error removing orphan entry, stopping orphan cleanup");
3102                         ret = -EINVAL;
3103                         goto out;
3104                 }
3105
3106                 last_objectid = found_key.offset;
3107
3108                 found_key.objectid = found_key.offset;
3109                 found_key.type = BTRFS_INODE_ITEM_KEY;
3110                 found_key.offset = 0;
3111                 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3112                 ret = PTR_ERR_OR_ZERO(inode);
3113                 if (ret && ret != -ESTALE)
3114                         goto out;
3115
3116                 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3117                         struct btrfs_root *dead_root;
3118                         struct btrfs_fs_info *fs_info = root->fs_info;
3119                         int is_dead_root = 0;
3120
3121                         /*
3122                          * this is an orphan in the tree root. Currently these
3123                          * could come from 2 sources:
3124                          *  a) a snapshot deletion in progress
3125                          *  b) a free space cache inode
3126                          * We need to distinguish those two, as the snapshot
3127                          * orphan must not get deleted.
3128                          * find_dead_roots already ran before us, so if this
3129                          * is a snapshot deletion, we should find the root
3130                          * in the dead_roots list
3131                          */
3132                         spin_lock(&fs_info->trans_lock);
3133                         list_for_each_entry(dead_root, &fs_info->dead_roots,
3134                                             root_list) {
3135                                 if (dead_root->root_key.objectid ==
3136                                     found_key.objectid) {
3137                                         is_dead_root = 1;
3138                                         break;
3139                                 }
3140                         }
3141                         spin_unlock(&fs_info->trans_lock);
3142                         if (is_dead_root) {
3143                                 /* prevent this orphan from being found again */
3144                                 key.offset = found_key.objectid - 1;
3145                                 continue;
3146                         }
3147                 }
3148                 /*
3149                  * Inode is already gone but the orphan item is still there,
3150                  * kill the orphan item.
3151                  */
3152                 if (ret == -ESTALE) {
3153                         trans = btrfs_start_transaction(root, 1);
3154                         if (IS_ERR(trans)) {
3155                                 ret = PTR_ERR(trans);
3156                                 goto out;
3157                         }
3158                         btrfs_debug(root->fs_info, "auto deleting %Lu",
3159                                 found_key.objectid);
3160                         ret = btrfs_del_orphan_item(trans, root,
3161                                                     found_key.objectid);
3162                         btrfs_end_transaction(trans, root);
3163                         if (ret)
3164                                 goto out;
3165                         continue;
3166                 }
3167
3168                 /*
3169                  * add this inode to the orphan list so btrfs_orphan_del does
3170                  * the proper thing when we hit it
3171                  */
3172                 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3173                         &BTRFS_I(inode)->runtime_flags);
3174                 atomic_inc(&root->orphan_inodes);
3175
3176                 /* if we have links, this was a truncate, lets do that */
3177                 if (inode->i_nlink) {
3178                         if (WARN_ON(!S_ISREG(inode->i_mode))) {
3179                                 iput(inode);
3180                                 continue;
3181                         }
3182                         nr_truncate++;
3183
3184                         /* 1 for the orphan item deletion. */
3185                         trans = btrfs_start_transaction(root, 1);
3186                         if (IS_ERR(trans)) {
3187                                 iput(inode);
3188                                 ret = PTR_ERR(trans);
3189                                 goto out;
3190                         }
3191                         ret = btrfs_orphan_add(trans, inode);
3192                         btrfs_end_transaction(trans, root);
3193                         if (ret) {
3194                                 iput(inode);
3195                                 goto out;
3196                         }
3197
3198                         ret = btrfs_truncate(inode);
3199                         if (ret)
3200                                 btrfs_orphan_del(NULL, inode);
3201                 } else {
3202                         nr_unlink++;
3203                 }
3204
3205                 /* this will do delete_inode and everything for us */
3206                 iput(inode);
3207                 if (ret)
3208                         goto out;
3209         }
3210         /* release the path since we're done with it */
3211         btrfs_release_path(path);
3212
3213         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3214
3215         if (root->orphan_block_rsv)
3216                 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3217                                         (u64)-1);
3218
3219         if (root->orphan_block_rsv || root->orphan_item_inserted) {
3220                 trans = btrfs_join_transaction(root);
3221                 if (!IS_ERR(trans))
3222                         btrfs_end_transaction(trans, root);
3223         }
3224
3225         if (nr_unlink)
3226                 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3227         if (nr_truncate)
3228                 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3229
3230 out:
3231         if (ret)
3232                 btrfs_crit(root->fs_info,
3233                         "could not do orphan cleanup %d", ret);
3234         btrfs_free_path(path);
3235         return ret;
3236 }
3237
3238 /*
3239  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3240  * don't find any xattrs, we know there can't be any acls.
3241  *
3242  * slot is the slot the inode is in, objectid is the objectid of the inode
3243  */
3244 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3245                                           int slot, u64 objectid)
3246 {
3247         u32 nritems = btrfs_header_nritems(leaf);
3248         struct btrfs_key found_key;
3249         static u64 xattr_access = 0;
3250         static u64 xattr_default = 0;
3251         int scanned = 0;
3252
3253         if (!xattr_access) {
3254                 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3255                                         strlen(POSIX_ACL_XATTR_ACCESS));
3256                 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3257                                         strlen(POSIX_ACL_XATTR_DEFAULT));
3258         }
3259
3260         slot++;
3261         while (slot < nritems) {
3262                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3263
3264                 /* we found a different objectid, there must not be acls */
3265                 if (found_key.objectid != objectid)
3266                         return 0;
3267
3268                 /* we found an xattr, assume we've got an acl */
3269                 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3270                         if (found_key.offset == xattr_access ||
3271                             found_key.offset == xattr_default)
3272                                 return 1;
3273                 }
3274
3275                 /*
3276                  * we found a key greater than an xattr key, there can't
3277                  * be any acls later on
3278                  */
3279                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3280                         return 0;
3281
3282                 slot++;
3283                 scanned++;
3284
3285                 /*
3286                  * it goes inode, inode backrefs, xattrs, extents,
3287                  * so if there are a ton of hard links to an inode there can
3288                  * be a lot of backrefs.  Don't waste time searching too hard,
3289                  * this is just an optimization
3290                  */
3291                 if (scanned >= 8)
3292                         break;
3293         }
3294         /* we hit the end of the leaf before we found an xattr or
3295          * something larger than an xattr.  We have to assume the inode
3296          * has acls
3297          */
3298         return 1;
3299 }
3300
3301 /*
3302  * read an inode from the btree into the in-memory inode
3303  */
3304 static void btrfs_read_locked_inode(struct inode *inode)
3305 {
3306         struct btrfs_path *path;
3307         struct extent_buffer *leaf;
3308         struct btrfs_inode_item *inode_item;
3309         struct btrfs_timespec *tspec;
3310         struct btrfs_root *root = BTRFS_I(inode)->root;
3311         struct btrfs_key location;
3312         unsigned long ptr;
3313         int maybe_acls;
3314         u32 rdev;
3315         int ret;
3316         bool filled = false;
3317
3318         ret = btrfs_fill_inode(inode, &rdev);
3319         if (!ret)
3320                 filled = true;
3321
3322         path = btrfs_alloc_path();
3323         if (!path)
3324                 goto make_bad;
3325
3326         path->leave_spinning = 1;
3327         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3328
3329         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3330         if (ret)
3331                 goto make_bad;
3332
3333         leaf = path->nodes[0];
3334
3335         if (filled)
3336                 goto cache_index;
3337
3338         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3339                                     struct btrfs_inode_item);
3340         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3341         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3342         i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3343         i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3344         btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3345
3346         tspec = btrfs_inode_atime(inode_item);
3347         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3348         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3349
3350         tspec = btrfs_inode_mtime(inode_item);
3351         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3352         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3353
3354         tspec = btrfs_inode_ctime(inode_item);
3355         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3356         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3357
3358         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3359         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3360         BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3361
3362         /*
3363          * If we were modified in the current generation and evicted from memory
3364          * and then re-read we need to do a full sync since we don't have any
3365          * idea about which extents were modified before we were evicted from
3366          * cache.
3367          */
3368         if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3369                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3370                         &BTRFS_I(inode)->runtime_flags);
3371
3372         inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3373         inode->i_generation = BTRFS_I(inode)->generation;
3374         inode->i_rdev = 0;
3375         rdev = btrfs_inode_rdev(leaf, inode_item);
3376
3377         BTRFS_I(inode)->index_cnt = (u64)-1;
3378         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3379
3380 cache_index:
3381         path->slots[0]++;
3382         if (inode->i_nlink != 1 ||
3383             path->slots[0] >= btrfs_header_nritems(leaf))
3384                 goto cache_acl;
3385
3386         btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3387         if (location.objectid != btrfs_ino(inode))
3388                 goto cache_acl;
3389
3390         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3391         if (location.type == BTRFS_INODE_REF_KEY) {
3392                 struct btrfs_inode_ref *ref;
3393
3394                 ref = (struct btrfs_inode_ref *)ptr;
3395                 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3396         } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3397                 struct btrfs_inode_extref *extref;
3398
3399                 extref = (struct btrfs_inode_extref *)ptr;
3400                 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3401                                                                      extref);
3402         }
3403 cache_acl:
3404         /*
3405          * try to precache a NULL acl entry for files that don't have
3406          * any xattrs or acls
3407          */
3408         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3409                                            btrfs_ino(inode));
3410         if (!maybe_acls)
3411                 cache_no_acl(inode);
3412
3413         btrfs_free_path(path);
3414
3415         switch (inode->i_mode & S_IFMT) {
3416         case S_IFREG:
3417                 inode->i_mapping->a_ops = &btrfs_aops;
3418                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3419                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3420                 inode->i_fop = &btrfs_file_operations;
3421                 inode->i_op = &btrfs_file_inode_operations;
3422                 break;
3423         case S_IFDIR:
3424                 inode->i_fop = &btrfs_dir_file_operations;
3425                 if (root == root->fs_info->tree_root)
3426                         inode->i_op = &btrfs_dir_ro_inode_operations;
3427                 else
3428                         inode->i_op = &btrfs_dir_inode_operations;
3429                 break;
3430         case S_IFLNK:
3431                 inode->i_op = &btrfs_symlink_inode_operations;
3432                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3433                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3434                 break;
3435         default:
3436                 inode->i_op = &btrfs_special_inode_operations;
3437                 init_special_inode(inode, inode->i_mode, rdev);
3438                 break;
3439         }
3440
3441         btrfs_update_iflags(inode);
3442         return;
3443
3444 make_bad:
3445         btrfs_free_path(path);
3446         make_bad_inode(inode);
3447 }
3448
3449 /*
3450  * given a leaf and an inode, copy the inode fields into the leaf
3451  */
3452 static void fill_inode_item(struct btrfs_trans_handle *trans,
3453                             struct extent_buffer *leaf,
3454                             struct btrfs_inode_item *item,
3455                             struct inode *inode)
3456 {
3457         struct btrfs_map_token token;
3458
3459         btrfs_init_map_token(&token);
3460
3461         btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3462         btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3463         btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3464                                    &token);
3465         btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3466         btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3467
3468         btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3469                                      inode->i_atime.tv_sec, &token);
3470         btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3471                                       inode->i_atime.tv_nsec, &token);
3472
3473         btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3474                                      inode->i_mtime.tv_sec, &token);
3475         btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3476                                       inode->i_mtime.tv_nsec, &token);
3477
3478         btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3479                                      inode->i_ctime.tv_sec, &token);
3480         btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3481                                       inode->i_ctime.tv_nsec, &token);
3482
3483         btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3484                                      &token);
3485         btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3486                                          &token);
3487         btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3488         btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3489         btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3490         btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3491         btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3492 }
3493
3494 /*
3495  * copy everything in the in-memory inode into the btree.
3496  */
3497 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3498                                 struct btrfs_root *root, struct inode *inode)
3499 {
3500         struct btrfs_inode_item *inode_item;
3501         struct btrfs_path *path;
3502         struct extent_buffer *leaf;
3503         int ret;
3504
3505         path = btrfs_alloc_path();
3506         if (!path)
3507                 return -ENOMEM;
3508
3509         path->leave_spinning = 1;
3510         ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3511                                  1);
3512         if (ret) {
3513                 if (ret > 0)
3514                         ret = -ENOENT;
3515                 goto failed;
3516         }
3517
3518         btrfs_unlock_up_safe(path, 1);
3519         leaf = path->nodes[0];
3520         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3521                                     struct btrfs_inode_item);
3522
3523         fill_inode_item(trans, leaf, inode_item, inode);
3524         btrfs_mark_buffer_dirty(leaf);
3525         btrfs_set_inode_last_trans(trans, inode);
3526         ret = 0;
3527 failed:
3528         btrfs_free_path(path);
3529         return ret;
3530 }
3531
3532 /*
3533  * copy everything in the in-memory inode into the btree.
3534  */
3535 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3536                                 struct btrfs_root *root, struct inode *inode)
3537 {
3538         int ret;
3539
3540         /*
3541          * If the inode is a free space inode, we can deadlock during commit
3542          * if we put it into the delayed code.
3543          *
3544          * The data relocation inode should also be directly updated
3545          * without delay
3546          */
3547         if (!btrfs_is_free_space_inode(inode)
3548             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3549                 btrfs_update_root_times(trans, root);
3550
3551                 ret = btrfs_delayed_update_inode(trans, root, inode);
3552                 if (!ret)
3553                         btrfs_set_inode_last_trans(trans, inode);
3554                 return ret;
3555         }
3556
3557         return btrfs_update_inode_item(trans, root, inode);
3558 }
3559
3560 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3561                                          struct btrfs_root *root,
3562                                          struct inode *inode)
3563 {
3564         int ret;
3565
3566         ret = btrfs_update_inode(trans, root, inode);
3567         if (ret == -ENOSPC)
3568                 return btrfs_update_inode_item(trans, root, inode);
3569         return ret;
3570 }
3571
3572 /*
3573  * unlink helper that gets used here in inode.c and in the tree logging
3574  * recovery code.  It remove a link in a directory with a given name, and
3575  * also drops the back refs in the inode to the directory
3576  */
3577 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3578                                 struct btrfs_root *root,
3579                                 struct inode *dir, struct inode *inode,
3580                                 const char *name, int name_len)
3581 {
3582         struct btrfs_path *path;
3583         int ret = 0;
3584         struct extent_buffer *leaf;
3585         struct btrfs_dir_item *di;
3586         struct btrfs_key key;
3587         u64 index;
3588         u64 ino = btrfs_ino(inode);
3589         u64 dir_ino = btrfs_ino(dir);
3590
3591         path = btrfs_alloc_path();
3592         if (!path) {
3593                 ret = -ENOMEM;
3594                 goto out;
3595         }
3596
3597         path->leave_spinning = 1;
3598         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3599                                     name, name_len, -1);
3600         if (IS_ERR(di)) {
3601                 ret = PTR_ERR(di);
3602                 goto err;
3603         }
3604         if (!di) {
3605                 ret = -ENOENT;
3606                 goto err;
3607         }
3608         leaf = path->nodes[0];
3609         btrfs_dir_item_key_to_cpu(leaf, di, &key);
3610         ret = btrfs_delete_one_dir_name(trans, root, path, di);
3611         if (ret)
3612                 goto err;
3613         btrfs_release_path(path);
3614
3615         /*
3616          * If we don't have dir index, we have to get it by looking up
3617          * the inode ref, since we get the inode ref, remove it directly,
3618          * it is unnecessary to do delayed deletion.
3619          *
3620          * But if we have dir index, needn't search inode ref to get it.
3621          * Since the inode ref is close to the inode item, it is better
3622          * that we delay to delete it, and just do this deletion when
3623          * we update the inode item.
3624          */
3625         if (BTRFS_I(inode)->dir_index) {
3626                 ret = btrfs_delayed_delete_inode_ref(inode);
3627                 if (!ret) {
3628                         index = BTRFS_I(inode)->dir_index;
3629                         goto skip_backref;
3630                 }
3631         }
3632
3633         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3634                                   dir_ino, &index);
3635         if (ret) {
3636                 btrfs_info(root->fs_info,
3637                         "failed to delete reference to %.*s, inode %llu parent %llu",
3638                         name_len, name, ino, dir_ino);
3639                 btrfs_abort_transaction(trans, root, ret);
3640                 goto err;
3641         }
3642 skip_backref:
3643         ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3644         if (ret) {
3645                 btrfs_abort_transaction(trans, root, ret);
3646                 goto err;
3647         }
3648
3649         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3650                                          inode, dir_ino);
3651         if (ret != 0 && ret != -ENOENT) {
3652                 btrfs_abort_transaction(trans, root, ret);
3653                 goto err;
3654         }
3655
3656         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3657                                            dir, index);
3658         if (ret == -ENOENT)
3659                 ret = 0;
3660         else if (ret)
3661                 btrfs_abort_transaction(trans, root, ret);
3662 err:
3663         btrfs_free_path(path);
3664         if (ret)
3665                 goto out;
3666
3667         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3668         inode_inc_iversion(inode);
3669         inode_inc_iversion(dir);
3670         inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3671         ret = btrfs_update_inode(trans, root, dir);
3672 out:
3673         return ret;
3674 }
3675
3676 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3677                        struct btrfs_root *root,
3678                        struct inode *dir, struct inode *inode,
3679                        const char *name, int name_len)
3680 {
3681         int ret;
3682         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3683         if (!ret) {
3684                 drop_nlink(inode);
3685                 ret = btrfs_update_inode(trans, root, inode);
3686         }
3687         return ret;
3688 }
3689
3690 /*
3691  * helper to start transaction for unlink and rmdir.
3692  *
3693  * unlink and rmdir are special in btrfs, they do not always free space, so
3694  * if we cannot make our reservations the normal way try and see if there is
3695  * plenty of slack room in the global reserve to migrate, otherwise we cannot
3696  * allow the unlink to occur.
3697  */
3698 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3699 {
3700         struct btrfs_trans_handle *trans;
3701         struct btrfs_root *root = BTRFS_I(dir)->root;
3702         int ret;
3703
3704         /*
3705          * 1 for the possible orphan item
3706          * 1 for the dir item
3707          * 1 for the dir index
3708          * 1 for the inode ref
3709          * 1 for the inode
3710          */
3711         trans = btrfs_start_transaction(root, 5);
3712         if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3713                 return trans;
3714
3715         if (PTR_ERR(trans) == -ENOSPC) {
3716                 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3717
3718                 trans = btrfs_start_transaction(root, 0);
3719                 if (IS_ERR(trans))
3720                         return trans;
3721                 ret = btrfs_cond_migrate_bytes(root->fs_info,
3722                                                &root->fs_info->trans_block_rsv,
3723                                                num_bytes, 5);
3724                 if (ret) {
3725                         btrfs_end_transaction(trans, root);
3726                         return ERR_PTR(ret);
3727                 }
3728                 trans->block_rsv = &root->fs_info->trans_block_rsv;
3729                 trans->bytes_reserved = num_bytes;
3730         }
3731         return trans;
3732 }
3733
3734 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3735 {
3736         struct btrfs_root *root = BTRFS_I(dir)->root;
3737         struct btrfs_trans_handle *trans;
3738         struct inode *inode = dentry->d_inode;
3739         int ret;
3740
3741         trans = __unlink_start_trans(dir);
3742         if (IS_ERR(trans))
3743                 return PTR_ERR(trans);
3744
3745         btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3746
3747         ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3748                                  dentry->d_name.name, dentry->d_name.len);
3749         if (ret)
3750                 goto out;
3751
3752         if (inode->i_nlink == 0) {
3753                 ret = btrfs_orphan_add(trans, inode);
3754                 if (ret)
3755                         goto out;
3756         }
3757
3758 out:
3759         btrfs_end_transaction(trans, root);
3760         btrfs_btree_balance_dirty(root);
3761         return ret;
3762 }
3763
3764 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3765                         struct btrfs_root *root,
3766                         struct inode *dir, u64 objectid,
3767                         const char *name, int name_len)
3768 {
3769         struct btrfs_path *path;
3770         struct extent_buffer *leaf;
3771         struct btrfs_dir_item *di;
3772         struct btrfs_key key;
3773         u64 index;
3774         int ret;
3775         u64 dir_ino = btrfs_ino(dir);
3776
3777         path = btrfs_alloc_path();
3778         if (!path)
3779                 return -ENOMEM;
3780
3781         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3782                                    name, name_len, -1);
3783         if (IS_ERR_OR_NULL(di)) {
3784                 if (!di)
3785                         ret = -ENOENT;
3786                 else
3787                         ret = PTR_ERR(di);
3788                 goto out;
3789         }
3790
3791         leaf = path->nodes[0];
3792         btrfs_dir_item_key_to_cpu(leaf, di, &key);
3793         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3794         ret = btrfs_delete_one_dir_name(trans, root, path, di);
3795         if (ret) {
3796                 btrfs_abort_transaction(trans, root, ret);
3797                 goto out;
3798         }
3799         btrfs_release_path(path);
3800
3801         ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3802                                  objectid, root->root_key.objectid,
3803                                  dir_ino, &index, name, name_len);
3804         if (ret < 0) {
3805                 if (ret != -ENOENT) {
3806                         btrfs_abort_transaction(trans, root, ret);
3807                         goto out;
3808                 }
3809                 di = btrfs_search_dir_index_item(root, path, dir_ino,
3810                                                  name, name_len);
3811                 if (IS_ERR_OR_NULL(di)) {
3812                         if (!di)
3813                                 ret = -ENOENT;
3814                         else
3815                                 ret = PTR_ERR(di);
3816                         btrfs_abort_transaction(trans, root, ret);
3817                         goto out;
3818                 }
3819
3820                 leaf = path->nodes[0];
3821                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3822                 btrfs_release_path(path);
3823                 index = key.offset;
3824         }
3825         btrfs_release_path(path);
3826
3827         ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3828         if (ret) {
3829                 btrfs_abort_transaction(trans, root, ret);
3830                 goto out;
3831         }
3832
3833         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3834         inode_inc_iversion(dir);
3835         dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3836         ret = btrfs_update_inode_fallback(trans, root, dir);
3837         if (ret)
3838                 btrfs_abort_transaction(trans, root, ret);
3839 out:
3840         btrfs_free_path(path);
3841         return ret;
3842 }
3843
3844 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3845 {
3846         struct inode *inode = dentry->d_inode;
3847         int err = 0;
3848         struct btrfs_root *root = BTRFS_I(dir)->root;
3849         struct btrfs_trans_handle *trans;
3850
3851         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3852                 return -ENOTEMPTY;
3853         if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3854                 return -EPERM;
3855
3856         trans = __unlink_start_trans(dir);
3857         if (IS_ERR(trans))
3858                 return PTR_ERR(trans);
3859
3860         if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3861                 err = btrfs_unlink_subvol(trans, root, dir,
3862                                           BTRFS_I(inode)->location.objectid,
3863                                           dentry->d_name.name,
3864                                           dentry->d_name.len);
3865                 goto out;
3866         }
3867
3868         err = btrfs_orphan_add(trans, inode);
3869         if (err)
3870                 goto out;
3871
3872         /* now the directory is empty */
3873         err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3874                                  dentry->d_name.name, dentry->d_name.len);
3875         if (!err)
3876                 btrfs_i_size_write(inode, 0);
3877 out:
3878         btrfs_end_transaction(trans, root);
3879         btrfs_btree_balance_dirty(root);
3880
3881         return err;
3882 }
3883
3884 /*
3885  * this can truncate away extent items, csum items and directory items.
3886  * It starts at a high offset and removes keys until it can't find
3887  * any higher than new_size
3888  *
3889  * csum items that cross the new i_size are truncated to the new size
3890  * as well.
3891  *
3892  * min_type is the minimum key type to truncate down to.  If set to 0, this
3893  * will kill all the items on this inode, including the INODE_ITEM_KEY.
3894  */
3895 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3896                                struct btrfs_root *root,
3897                                struct inode *inode,
3898                                u64 new_size, u32 min_type)
3899 {
3900         struct btrfs_path *path;
3901         struct extent_buffer *leaf;
3902         struct btrfs_file_extent_item *fi;
3903         struct btrfs_key key;
3904         struct btrfs_key found_key;
3905         u64 extent_start = 0;
3906         u64 extent_num_bytes = 0;
3907         u64 extent_offset = 0;
3908         u64 item_end = 0;
3909         u64 last_size = (u64)-1;
3910         u32 found_type = (u8)-1;
3911         int found_extent;
3912         int del_item;
3913         int pending_del_nr = 0;
3914         int pending_del_slot = 0;
3915         int extent_type = -1;
3916         int ret;
3917         int err = 0;
3918         u64 ino = btrfs_ino(inode);
3919
3920         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3921
3922         path = btrfs_alloc_path();
3923         if (!path)
3924                 return -ENOMEM;
3925         path->reada = -1;
3926
3927         /*
3928          * We want to drop from the next block forward in case this new size is
3929          * not block aligned since we will be keeping the last block of the
3930          * extent just the way it is.
3931          */
3932         if (root->ref_cows || root == root->fs_info->tree_root)
3933                 btrfs_drop_extent_cache(inode, ALIGN(new_size,
3934                                         root->sectorsize), (u64)-1, 0);
3935
3936         /*
3937          * This function is also used to drop the items in the log tree before
3938          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3939          * it is used to drop the loged items. So we shouldn't kill the delayed
3940          * items.
3941          */
3942         if (min_type == 0 && root == BTRFS_I(inode)->root)
3943                 btrfs_kill_delayed_inode_items(inode);
3944
3945         key.objectid = ino;
3946         key.offset = (u64)-1;
3947         key.type = (u8)-1;
3948
3949 search_again:
3950         path->leave_spinning = 1;
3951         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3952         if (ret < 0) {
3953                 err = ret;
3954                 goto out;
3955         }
3956
3957         if (ret > 0) {
3958                 /* there are no items in the tree for us to truncate, we're
3959                  * done
3960                  */
3961                 if (path->slots[0] == 0)
3962                         goto out;
3963                 path->slots[0]--;
3964         }
3965
3966         while (1) {
3967                 fi = NULL;
3968                 leaf = path->nodes[0];
3969                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3970                 found_type = btrfs_key_type(&found_key);
3971
3972                 if (found_key.objectid != ino)
3973                         break;
3974
3975                 if (found_type < min_type)
3976                         break;
3977
3978                 item_end = found_key.offset;
3979                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3980                         fi = btrfs_item_ptr(leaf, path->slots[0],
3981                                             struct btrfs_file_extent_item);
3982                         extent_type = btrfs_file_extent_type(leaf, fi);
3983                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3984                                 item_end +=
3985                                     btrfs_file_extent_num_bytes(leaf, fi);
3986                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3987                                 item_end += btrfs_file_extent_inline_len(leaf,
3988                                                                          fi);
3989                         }
3990                         item_end--;
3991                 }
3992                 if (found_type > min_type) {
3993                         del_item = 1;
3994                 } else {
3995                         if (item_end < new_size)
3996                                 break;
3997                         if (found_key.offset >= new_size)
3998                                 del_item = 1;
3999                         else
4000                                 del_item = 0;
4001                 }
4002                 found_extent = 0;
4003                 /* FIXME, shrink the extent if the ref count is only 1 */
4004                 if (found_type != BTRFS_EXTENT_DATA_KEY)
4005                         goto delete;
4006
4007                 if (del_item)
4008                         last_size = found_key.offset;
4009                 else
4010                         last_size = new_size;
4011
4012                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4013                         u64 num_dec;
4014                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4015                         if (!del_item) {
4016                                 u64 orig_num_bytes =
4017                                         btrfs_file_extent_num_bytes(leaf, fi);
4018                                 extent_num_bytes = ALIGN(new_size -
4019                                                 found_key.offset,
4020                                                 root->sectorsize);
4021                                 btrfs_set_file_extent_num_bytes(leaf, fi,
4022                                                          extent_num_bytes);
4023                                 num_dec = (orig_num_bytes -
4024                                            extent_num_bytes);
4025                                 if (root->ref_cows && extent_start != 0)
4026                                         inode_sub_bytes(inode, num_dec);
4027                                 btrfs_mark_buffer_dirty(leaf);
4028                         } else {
4029                                 extent_num_bytes =
4030                                         btrfs_file_extent_disk_num_bytes(leaf,
4031                                                                          fi);
4032                                 extent_offset = found_key.offset -
4033                                         btrfs_file_extent_offset(leaf, fi);
4034
4035                                 /* FIXME blocksize != 4096 */
4036                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4037                                 if (extent_start != 0) {
4038                                         found_extent = 1;
4039                                         if (root->ref_cows)
4040                                                 inode_sub_bytes(inode, num_dec);
4041                                 }
4042                         }
4043                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4044                         /*
4045                          * we can't truncate inline items that have had
4046                          * special encodings
4047                          */
4048                         if (!del_item &&
4049                             btrfs_file_extent_compression(leaf, fi) == 0 &&
4050                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
4051                             btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4052                                 u32 size = new_size - found_key.offset;
4053
4054                                 if (root->ref_cows) {
4055                                         inode_sub_bytes(inode, item_end + 1 -
4056                                                         new_size);
4057                                 }
4058                                 size =
4059                                     btrfs_file_extent_calc_inline_size(size);
4060                                 btrfs_truncate_item(root, path, size, 1);
4061                         } else if (root->ref_cows) {
4062                                 inode_sub_bytes(inode, item_end + 1 -
4063                                                 found_key.offset);
4064                         }
4065                 }
4066 delete:
4067                 if (del_item) {
4068                         if (!pending_del_nr) {
4069                                 /* no pending yet, add ourselves */
4070                                 pending_del_slot = path->slots[0];
4071                                 pending_del_nr = 1;
4072                         } else if (pending_del_nr &&
4073                                    path->slots[0] + 1 == pending_del_slot) {
4074                                 /* hop on the pending chunk */
4075                                 pending_del_nr++;
4076                                 pending_del_slot = path->slots[0];
4077                         } else {
4078                                 BUG();
4079                         }
4080                 } else {
4081                         break;
4082                 }
4083                 if (found_extent && (root->ref_cows ||
4084                                      root == root->fs_info->tree_root)) {
4085                         btrfs_set_path_blocking(path);
4086                         ret = btrfs_free_extent(trans, root, extent_start,
4087                                                 extent_num_bytes, 0,
4088                                                 btrfs_header_owner(leaf),
4089                                                 ino, extent_offset, 0);
4090                         BUG_ON(ret);
4091                 }
4092
4093                 if (found_type == BTRFS_INODE_ITEM_KEY)
4094                         break;
4095
4096                 if (path->slots[0] == 0 ||
4097                     path->slots[0] != pending_del_slot) {
4098                         if (pending_del_nr) {
4099                                 ret = btrfs_del_items(trans, root, path,
4100                                                 pending_del_slot,
4101                                                 pending_del_nr);
4102                                 if (ret) {
4103                                         btrfs_abort_transaction(trans,
4104                                                                 root, ret);
4105                                         goto error;
4106                                 }
4107                                 pending_del_nr = 0;
4108                         }
4109                         btrfs_release_path(path);
4110                         goto search_again;
4111                 } else {
4112                         path->slots[0]--;
4113                 }
4114         }
4115 out:
4116         if (pending_del_nr) {
4117                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4118                                       pending_del_nr);
4119                 if (ret)
4120                         btrfs_abort_transaction(trans, root, ret);
4121         }
4122 error:
4123         if (last_size != (u64)-1)
4124                 btrfs_ordered_update_i_size(inode, last_size, NULL);
4125         btrfs_free_path(path);
4126         return err;
4127 }
4128
4129 /*
4130  * btrfs_truncate_page - read, zero a chunk and write a page
4131  * @inode - inode that we're zeroing
4132  * @from - the offset to start zeroing
4133  * @len - the length to zero, 0 to zero the entire range respective to the
4134  *      offset
4135  * @front - zero up to the offset instead of from the offset on
4136  *
4137  * This will find the page for the "from" offset and cow the page and zero the
4138  * part we want to zero.  This is used with truncate and hole punching.
4139  */
4140 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4141                         int front)
4142 {
4143         struct address_space *mapping = inode->i_mapping;
4144         struct btrfs_root *root = BTRFS_I(inode)->root;
4145         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4146         struct btrfs_ordered_extent *ordered;
4147         struct extent_state *cached_state = NULL;
4148         char *kaddr;
4149         u32 blocksize = root->sectorsize;
4150         pgoff_t index = from >> PAGE_CACHE_SHIFT;
4151         unsigned offset = from & (PAGE_CACHE_SIZE-1);
4152         struct page *page;
4153         gfp_t mask = btrfs_alloc_write_mask(mapping);
4154         int ret = 0;
4155         u64 page_start;
4156         u64 page_end;
4157
4158         if ((offset & (blocksize - 1)) == 0 &&
4159             (!len || ((len & (blocksize - 1)) == 0)))
4160                 goto out;
4161         ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4162         if (ret)
4163                 goto out;
4164
4165 again:
4166         page = find_or_create_page(mapping, index, mask);
4167         if (!page) {
4168                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4169                 ret = -ENOMEM;
4170                 goto out;
4171         }
4172
4173         page_start = page_offset(page);
4174         page_end = page_start + PAGE_CACHE_SIZE - 1;
4175
4176         if (!PageUptodate(page)) {
4177                 ret = btrfs_readpage(NULL, page);
4178                 lock_page(page);
4179                 if (page->mapping != mapping) {
4180                         unlock_page(page);
4181                         page_cache_release(page);
4182                         goto again;
4183                 }
4184                 if (!PageUptodate(page)) {
4185                         ret = -EIO;
4186                         goto out_unlock;
4187                 }
4188         }
4189         wait_on_page_writeback(page);
4190
4191         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4192         set_page_extent_mapped(page);
4193
4194         ordered = btrfs_lookup_ordered_extent(inode, page_start);
4195         if (ordered) {
4196                 unlock_extent_cached(io_tree, page_start, page_end,
4197                                      &cached_state, GFP_NOFS);
4198                 unlock_page(page);
4199                 page_cache_release(page);
4200                 btrfs_start_ordered_extent(inode, ordered, 1);
4201                 btrfs_put_ordered_extent(ordered);
4202                 goto again;
4203         }
4204
4205         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4206                           EXTENT_DIRTY | EXTENT_DELALLOC |
4207                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4208                           0, 0, &cached_state, GFP_NOFS);
4209
4210         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4211                                         &cached_state);
4212         if (ret) {
4213                 unlock_extent_cached(io_tree, page_start, page_end,
4214                                      &cached_state, GFP_NOFS);
4215                 goto out_unlock;
4216         }
4217
4218         if (offset != PAGE_CACHE_SIZE) {
4219                 if (!len)
4220                         len = PAGE_CACHE_SIZE - offset;
4221                 kaddr = kmap(page);
4222                 if (front)
4223                         memset(kaddr, 0, offset);
4224                 else
4225                         memset(kaddr + offset, 0, len);
4226                 flush_dcache_page(page);
4227                 kunmap(page);
4228         }
4229         ClearPageChecked(page);
4230         set_page_dirty(page);
4231         unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4232                              GFP_NOFS);
4233
4234 out_unlock:
4235         if (ret)
4236                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4237         unlock_page(page);
4238         page_cache_release(page);
4239 out:
4240         return ret;
4241 }
4242
4243 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4244                              u64 offset, u64 len)
4245 {
4246         struct btrfs_trans_handle *trans;
4247         int ret;
4248
4249         /*
4250          * Still need to make sure the inode looks like it's been updated so
4251          * that any holes get logged if we fsync.
4252          */
4253         if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4254                 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4255                 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4256                 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4257                 return 0;
4258         }
4259
4260         /*
4261          * 1 - for the one we're dropping
4262          * 1 - for the one we're adding
4263          * 1 - for updating the inode.
4264          */
4265         trans = btrfs_start_transaction(root, 3);
4266         if (IS_ERR(trans))
4267                 return PTR_ERR(trans);
4268
4269         ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4270         if (ret) {
4271                 btrfs_abort_transaction(trans, root, ret);
4272                 btrfs_end_transaction(trans, root);
4273                 return ret;
4274         }
4275
4276         ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4277                                        0, 0, len, 0, len, 0, 0, 0);
4278         if (ret)
4279                 btrfs_abort_transaction(trans, root, ret);
4280         else
4281                 btrfs_update_inode(trans, root, inode);
4282         btrfs_end_transaction(trans, root);
4283         return ret;
4284 }
4285
4286 /*
4287  * This function puts in dummy file extents for the area we're creating a hole
4288  * for.  So if we are truncating this file to a larger size we need to insert
4289  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4290  * the range between oldsize and size
4291  */
4292 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4293 {
4294         struct btrfs_root *root = BTRFS_I(inode)->root;
4295         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4296         struct extent_map *em = NULL;
4297         struct extent_state *cached_state = NULL;
4298         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4299         u64 hole_start = ALIGN(oldsize, root->sectorsize);
4300         u64 block_end = ALIGN(size, root->sectorsize);
4301         u64 last_byte;
4302         u64 cur_offset;
4303         u64 hole_size;
4304         int err = 0;
4305
4306         /*
4307          * If our size started in the middle of a page we need to zero out the
4308          * rest of the page before we expand the i_size, otherwise we could
4309          * expose stale data.
4310          */
4311         err = btrfs_truncate_page(inode, oldsize, 0, 0);
4312         if (err)
4313                 return err;
4314
4315         if (size <= hole_start)
4316                 return 0;
4317
4318         while (1) {
4319                 struct btrfs_ordered_extent *ordered;
4320
4321                 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4322                                  &cached_state);
4323                 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4324                                                      block_end - hole_start);
4325                 if (!ordered)
4326                         break;
4327                 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4328                                      &cached_state, GFP_NOFS);
4329                 btrfs_start_ordered_extent(inode, ordered, 1);
4330                 btrfs_put_ordered_extent(ordered);
4331         }
4332
4333         cur_offset = hole_start;
4334         while (1) {
4335                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4336                                 block_end - cur_offset, 0);
4337                 if (IS_ERR(em)) {
4338                         err = PTR_ERR(em);
4339                         em = NULL;
4340                         break;
4341                 }
4342                 last_byte = min(extent_map_end(em), block_end);
4343                 last_byte = ALIGN(last_byte , root->sectorsize);
4344                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4345                         struct extent_map *hole_em;
4346                         hole_size = last_byte - cur_offset;
4347
4348                         err = maybe_insert_hole(root, inode, cur_offset,
4349                                                 hole_size);
4350                         if (err)
4351                                 break;
4352                         btrfs_drop_extent_cache(inode, cur_offset,
4353                                                 cur_offset + hole_size - 1, 0);
4354                         hole_em = alloc_extent_map();
4355                         if (!hole_em) {
4356                                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4357                                         &BTRFS_I(inode)->runtime_flags);
4358                                 goto next;
4359                         }
4360                         hole_em->start = cur_offset;
4361                         hole_em->len = hole_size;
4362                         hole_em->orig_start = cur_offset;
4363
4364                         hole_em->block_start = EXTENT_MAP_HOLE;
4365                         hole_em->block_len = 0;
4366                         hole_em->orig_block_len = 0;
4367                         hole_em->ram_bytes = hole_size;
4368                         hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4369                         hole_em->compress_type = BTRFS_COMPRESS_NONE;
4370                         hole_em->generation = root->fs_info->generation;
4371
4372                         while (1) {
4373                                 write_lock(&em_tree->lock);
4374                                 err = add_extent_mapping(em_tree, hole_em, 1);
4375                                 write_unlock(&em_tree->lock);
4376                                 if (err != -EEXIST)
4377                                         break;
4378                                 btrfs_drop_extent_cache(inode, cur_offset,
4379                                                         cur_offset +
4380                                                         hole_size - 1, 0);
4381                         }
4382                         free_extent_map(hole_em);
4383                 }
4384 next:
4385                 free_extent_map(em);
4386                 em = NULL;
4387                 cur_offset = last_byte;
4388                 if (cur_offset >= block_end)
4389                         break;
4390         }
4391         free_extent_map(em);
4392         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4393                              GFP_NOFS);
4394         return err;
4395 }
4396
4397 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4398 {
4399         struct btrfs_root *root = BTRFS_I(inode)->root;
4400         struct btrfs_trans_handle *trans;
4401         loff_t oldsize = i_size_read(inode);
4402         loff_t newsize = attr->ia_size;
4403         int mask = attr->ia_valid;
4404         int ret;
4405
4406         /*
4407          * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4408          * special case where we need to update the times despite not having
4409          * these flags set.  For all other operations the VFS set these flags
4410          * explicitly if it wants a timestamp update.
4411          */
4412         if (newsize != oldsize) {
4413                 inode_inc_iversion(inode);
4414                 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4415                         inode->i_ctime = inode->i_mtime =
4416                                 current_fs_time(inode->i_sb);
4417         }
4418
4419         if (newsize > oldsize) {
4420                 truncate_pagecache(inode, newsize);
4421                 ret = btrfs_cont_expand(inode, oldsize, newsize);
4422                 if (ret)
4423                         return ret;
4424
4425                 trans = btrfs_start_transaction(root, 1);
4426                 if (IS_ERR(trans))
4427                         return PTR_ERR(trans);
4428
4429                 i_size_write(inode, newsize);
4430                 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4431                 ret = btrfs_update_inode(trans, root, inode);
4432                 btrfs_end_transaction(trans, root);
4433         } else {
4434
4435                 /*
4436                  * We're truncating a file that used to have good data down to
4437                  * zero. Make sure it gets into the ordered flush list so that
4438                  * any new writes get down to disk quickly.
4439                  */
4440                 if (newsize == 0)
4441                         set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4442                                 &BTRFS_I(inode)->runtime_flags);
4443
4444                 /*
4445                  * 1 for the orphan item we're going to add
4446                  * 1 for the orphan item deletion.
4447                  */
4448                 trans = btrfs_start_transaction(root, 2);
4449                 if (IS_ERR(trans))
4450                         return PTR_ERR(trans);
4451
4452                 /*
4453                  * We need to do this in case we fail at _any_ point during the
4454                  * actual truncate.  Once we do the truncate_setsize we could
4455                  * invalidate pages which forces any outstanding ordered io to
4456                  * be instantly completed which will give us extents that need
4457                  * to be truncated.  If we fail to get an orphan inode down we
4458                  * could have left over extents that were never meant to live,
4459                  * so we need to garuntee from this point on that everything
4460                  * will be consistent.
4461                  */
4462                 ret = btrfs_orphan_add(trans, inode);
4463                 btrfs_end_transaction(trans, root);
4464                 if (ret)
4465                         return ret;
4466
4467                 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4468                 truncate_setsize(inode, newsize);
4469
4470                 /* Disable nonlocked read DIO to avoid the end less truncate */
4471                 btrfs_inode_block_unlocked_dio(inode);
4472                 inode_dio_wait(inode);
4473                 btrfs_inode_resume_unlocked_dio(inode);
4474
4475                 ret = btrfs_truncate(inode);
4476                 if (ret && inode->i_nlink) {
4477                         int err;
4478
4479                         /*
4480                          * failed to truncate, disk_i_size is only adjusted down
4481                          * as we remove extents, so it should represent the true
4482                          * size of the inode, so reset the in memory size and
4483                          * delete our orphan entry.
4484                          */
4485                         trans = btrfs_join_transaction(root);
4486                         if (IS_ERR(trans)) {
4487                                 btrfs_orphan_del(NULL, inode);
4488                                 return ret;
4489                         }
4490                         i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4491                         err = btrfs_orphan_del(trans, inode);
4492                         if (err)
4493                                 btrfs_abort_transaction(trans, root, err);
4494                         btrfs_end_transaction(trans, root);
4495                 }
4496         }
4497
4498         return ret;
4499 }
4500
4501 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4502 {
4503         struct inode *inode = dentry->d_inode;
4504         struct btrfs_root *root = BTRFS_I(inode)->root;
4505         int err;
4506
4507         if (btrfs_root_readonly(root))
4508                 return -EROFS;
4509
4510         err = inode_change_ok(inode, attr);
4511         if (err)
4512                 return err;
4513
4514         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4515                 err = btrfs_setsize(inode, attr);
4516                 if (err)
4517                         return err;
4518         }
4519
4520         if (attr->ia_valid) {
4521                 setattr_copy(inode, attr);
4522                 inode_inc_iversion(inode);
4523                 err = btrfs_dirty_inode(inode);
4524
4525                 if (!err && attr->ia_valid & ATTR_MODE)
4526                         err = btrfs_acl_chmod(inode);
4527         }
4528
4529         return err;
4530 }
4531
4532 /*
4533  * While truncating the inode pages during eviction, we get the VFS calling
4534  * btrfs_invalidatepage() against each page of the inode. This is slow because
4535  * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4536  * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4537  * extent_state structures over and over, wasting lots of time.
4538  *
4539  * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4540  * those expensive operations on a per page basis and do only the ordered io
4541  * finishing, while we release here the extent_map and extent_state structures,
4542  * without the excessive merging and splitting.
4543  */
4544 static void evict_inode_truncate_pages(struct inode *inode)
4545 {
4546         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4547         struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4548         struct rb_node *node;
4549
4550         ASSERT(inode->i_state & I_FREEING);
4551         truncate_inode_pages(&inode->i_data, 0);
4552
4553         write_lock(&map_tree->lock);
4554         while (!RB_EMPTY_ROOT(&map_tree->map)) {
4555                 struct extent_map *em;
4556
4557                 node = rb_first(&map_tree->map);
4558                 em = rb_entry(node, struct extent_map, rb_node);
4559                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4560                 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4561                 remove_extent_mapping(map_tree, em);
4562                 free_extent_map(em);
4563         }
4564         write_unlock(&map_tree->lock);
4565
4566         spin_lock(&io_tree->lock);
4567         while (!RB_EMPTY_ROOT(&io_tree->state)) {
4568                 struct extent_state *state;
4569                 struct extent_state *cached_state = NULL;
4570
4571                 node = rb_first(&io_tree->state);
4572                 state = rb_entry(node, struct extent_state, rb_node);
4573                 atomic_inc(&state->refs);
4574                 spin_unlock(&io_tree->lock);
4575
4576                 lock_extent_bits(io_tree, state->start, state->end,
4577                                  0, &cached_state);
4578                 clear_extent_bit(io_tree, state->start, state->end,
4579                                  EXTENT_LOCKED | EXTENT_DIRTY |
4580                                  EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
4581                                  EXTENT_DEFRAG, 1, 1,
4582                                  &cached_state, GFP_NOFS);
4583                 free_extent_state(state);
4584
4585                 spin_lock(&io_tree->lock);
4586         }
4587         spin_unlock(&io_tree->lock);
4588 }
4589
4590 void btrfs_evict_inode(struct inode *inode)
4591 {
4592         struct btrfs_trans_handle *trans;
4593         struct btrfs_root *root = BTRFS_I(inode)->root;
4594         struct btrfs_block_rsv *rsv, *global_rsv;
4595         u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4596         int ret;
4597
4598         trace_btrfs_inode_evict(inode);
4599
4600         evict_inode_truncate_pages(inode);
4601
4602         if (inode->i_nlink &&
4603             ((btrfs_root_refs(&root->root_item) != 0 &&
4604               root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4605              btrfs_is_free_space_inode(inode)))
4606                 goto no_delete;
4607
4608         if (is_bad_inode(inode)) {
4609                 btrfs_orphan_del(NULL, inode);
4610                 goto no_delete;
4611         }
4612         /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4613         btrfs_wait_ordered_range(inode, 0, (u64)-1);
4614
4615         if (root->fs_info->log_root_recovering) {
4616                 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4617                                  &BTRFS_I(inode)->runtime_flags));
4618                 goto no_delete;
4619         }
4620
4621         if (inode->i_nlink > 0) {
4622                 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4623                        root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4624                 goto no_delete;
4625         }
4626
4627         ret = btrfs_commit_inode_delayed_inode(inode);
4628         if (ret) {
4629                 btrfs_orphan_del(NULL, inode);
4630                 goto no_delete;
4631         }
4632
4633         rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4634         if (!rsv) {
4635                 btrfs_orphan_del(NULL, inode);
4636                 goto no_delete;
4637         }
4638         rsv->size = min_size;
4639         rsv->failfast = 1;
4640         global_rsv = &root->fs_info->global_block_rsv;
4641
4642         btrfs_i_size_write(inode, 0);
4643
4644         /*
4645          * This is a bit simpler than btrfs_truncate since we've already
4646          * reserved our space for our orphan item in the unlink, so we just
4647          * need to reserve some slack space in case we add bytes and update
4648          * inode item when doing the truncate.
4649          */
4650         while (1) {
4651                 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4652                                              BTRFS_RESERVE_FLUSH_LIMIT);
4653
4654                 /*
4655                  * Try and steal from the global reserve since we will
4656                  * likely not use this space anyway, we want to try as
4657                  * hard as possible to get this to work.
4658                  */
4659                 if (ret)
4660                         ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4661
4662                 if (ret) {
4663                         btrfs_warn(root->fs_info,
4664                                 "Could not get space for a delete, will truncate on mount %d",
4665                                 ret);
4666                         btrfs_orphan_del(NULL, inode);
4667                         btrfs_free_block_rsv(root, rsv);
4668                         goto no_delete;
4669                 }
4670
4671                 trans = btrfs_join_transaction(root);
4672                 if (IS_ERR(trans)) {
4673                         btrfs_orphan_del(NULL, inode);
4674                         btrfs_free_block_rsv(root, rsv);
4675                         goto no_delete;
4676                 }
4677
4678                 trans->block_rsv = rsv;
4679
4680                 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4681                 if (ret != -ENOSPC)
4682                         break;
4683
4684                 trans->block_rsv = &root->fs_info->trans_block_rsv;
4685                 btrfs_end_transaction(trans, root);
4686                 trans = NULL;
4687                 btrfs_btree_balance_dirty(root);
4688         }
4689
4690         btrfs_free_block_rsv(root, rsv);
4691
4692         /*
4693          * Errors here aren't a big deal, it just means we leave orphan items
4694          * in the tree.  They will be cleaned up on the next mount.
4695          */
4696         if (ret == 0) {
4697                 trans->block_rsv = root->orphan_block_rsv;
4698                 btrfs_orphan_del(trans, inode);
4699         } else {
4700                 btrfs_orphan_del(NULL, inode);
4701         }
4702
4703         trans->block_rsv = &root->fs_info->trans_block_rsv;
4704         if (!(root == root->fs_info->tree_root ||
4705               root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4706                 btrfs_return_ino(root, btrfs_ino(inode));
4707
4708         btrfs_end_transaction(trans, root);
4709         btrfs_btree_balance_dirty(root);
4710 no_delete:
4711         btrfs_remove_delayed_node(inode);
4712         clear_inode(inode);
4713         return;
4714 }
4715
4716 /*
4717  * this returns the key found in the dir entry in the location pointer.
4718  * If no dir entries were found, location->objectid is 0.
4719  */
4720 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4721                                struct btrfs_key *location)
4722 {
4723         const char *name = dentry->d_name.name;
4724         int namelen = dentry->d_name.len;
4725         struct btrfs_dir_item *di;
4726         struct btrfs_path *path;
4727         struct btrfs_root *root = BTRFS_I(dir)->root;
4728         int ret = 0;
4729
4730         path = btrfs_alloc_path();
4731         if (!path)
4732                 return -ENOMEM;
4733
4734         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4735                                     namelen, 0);
4736         if (IS_ERR(di))
4737                 ret = PTR_ERR(di);
4738
4739         if (IS_ERR_OR_NULL(di))
4740                 goto out_err;
4741
4742         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4743 out:
4744         btrfs_free_path(path);
4745         return ret;
4746 out_err:
4747         location->objectid = 0;
4748         goto out;
4749 }
4750
4751 /*
4752  * when we hit a tree root in a directory, the btrfs part of the inode
4753  * needs to be changed to reflect the root directory of the tree root.  This
4754  * is kind of like crossing a mount point.
4755  */
4756 static int fixup_tree_root_location(struct btrfs_root *root,
4757                                     struct inode *dir,
4758                                     struct dentry *dentry,
4759                                     struct btrfs_key *location,
4760                                     struct btrfs_root **sub_root)
4761 {
4762         struct btrfs_path *path;
4763         struct btrfs_root *new_root;
4764         struct btrfs_root_ref *ref;
4765         struct extent_buffer *leaf;
4766         int ret;
4767         int err = 0;
4768
4769         path = btrfs_alloc_path();
4770         if (!path) {
4771                 err = -ENOMEM;
4772                 goto out;
4773         }
4774
4775         err = -ENOENT;
4776         ret = btrfs_find_item(root->fs_info->tree_root, path,
4777                                 BTRFS_I(dir)->root->root_key.objectid,
4778                                 location->objectid, BTRFS_ROOT_REF_KEY, NULL);
4779         if (ret) {
4780                 if (ret < 0)
4781                         err = ret;
4782                 goto out;
4783         }
4784
4785         leaf = path->nodes[0];
4786         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4787         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4788             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4789                 goto out;
4790
4791         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4792                                    (unsigned long)(ref + 1),
4793                                    dentry->d_name.len);
4794         if (ret)
4795                 goto out;
4796
4797         btrfs_release_path(path);
4798
4799         new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4800         if (IS_ERR(new_root)) {
4801                 err = PTR_ERR(new_root);
4802                 goto out;
4803         }
4804
4805         *sub_root = new_root;
4806         location->objectid = btrfs_root_dirid(&new_root->root_item);
4807         location->type = BTRFS_INODE_ITEM_KEY;
4808         location->offset = 0;
4809         err = 0;
4810 out:
4811         btrfs_free_path(path);
4812         return err;
4813 }
4814
4815 static void inode_tree_add(struct inode *inode)
4816 {
4817         struct btrfs_root *root = BTRFS_I(inode)->root;
4818         struct btrfs_inode *entry;
4819         struct rb_node **p;
4820         struct rb_node *parent;
4821         struct rb_node *new = &BTRFS_I(inode)->rb_node;
4822         u64 ino = btrfs_ino(inode);
4823
4824         if (inode_unhashed(inode))
4825                 return;
4826         parent = NULL;
4827         spin_lock(&root->inode_lock);
4828         p = &root->inode_tree.rb_node;
4829         while (*p) {
4830                 parent = *p;
4831                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4832
4833                 if (ino < btrfs_ino(&entry->vfs_inode))
4834                         p = &parent->rb_left;
4835                 else if (ino > btrfs_ino(&entry->vfs_inode))
4836                         p = &parent->rb_right;
4837                 else {
4838                         WARN_ON(!(entry->vfs_inode.i_state &
4839                                   (I_WILL_FREE | I_FREEING)));
4840                         rb_replace_node(parent, new, &root->inode_tree);
4841                         RB_CLEAR_NODE(parent);
4842                         spin_unlock(&root->inode_lock);
4843                         return;
4844                 }
4845         }
4846         rb_link_node(new, parent, p);
4847         rb_insert_color(new, &root->inode_tree);
4848         spin_unlock(&root->inode_lock);
4849 }
4850
4851 static void inode_tree_del(struct inode *inode)
4852 {
4853         struct btrfs_root *root = BTRFS_I(inode)->root;
4854         int empty = 0;
4855
4856         spin_lock(&root->inode_lock);
4857         if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4858                 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4859                 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4860                 empty = RB_EMPTY_ROOT(&root->inode_tree);
4861         }
4862         spin_unlock(&root->inode_lock);
4863
4864         if (empty && btrfs_root_refs(&root->root_item) == 0) {
4865                 synchronize_srcu(&root->fs_info->subvol_srcu);
4866                 spin_lock(&root->inode_lock);
4867                 empty = RB_EMPTY_ROOT(&root->inode_tree);
4868                 spin_unlock(&root->inode_lock);
4869                 if (empty)
4870                         btrfs_add_dead_root(root);
4871         }
4872 }
4873
4874 void btrfs_invalidate_inodes(struct btrfs_root *root)
4875 {
4876         struct rb_node *node;
4877         struct rb_node *prev;
4878         struct btrfs_inode *entry;
4879         struct inode *inode;
4880         u64 objectid = 0;
4881
4882         WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4883
4884         spin_lock(&root->inode_lock);
4885 again:
4886         node = root->inode_tree.rb_node;
4887         prev = NULL;
4888         while (node) {
4889                 prev = node;
4890                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4891
4892                 if (objectid < btrfs_ino(&entry->vfs_inode))
4893                         node = node->rb_left;
4894                 else if (objectid > btrfs_ino(&entry->vfs_inode))
4895                         node = node->rb_right;
4896                 else
4897                         break;
4898         }
4899         if (!node) {
4900                 while (prev) {
4901                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
4902                         if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4903                                 node = prev;
4904                                 break;
4905                         }
4906                         prev = rb_next(prev);
4907                 }
4908         }
4909         while (node) {
4910                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4911                 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4912                 inode = igrab(&entry->vfs_inode);
4913                 if (inode) {
4914                         spin_unlock(&root->inode_lock);
4915                         if (atomic_read(&inode->i_count) > 1)
4916                                 d_prune_aliases(inode);
4917                         /*
4918                          * btrfs_drop_inode will have it removed from
4919                          * the inode cache when its usage count
4920                          * hits zero.
4921                          */
4922                         iput(inode);
4923                         cond_resched();
4924                         spin_lock(&root->inode_lock);
4925                         goto again;
4926                 }
4927
4928                 if (cond_resched_lock(&root->inode_lock))
4929                         goto again;
4930
4931                 node = rb_next(node);
4932         }
4933         spin_unlock(&root->inode_lock);
4934 }
4935
4936 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4937 {
4938         struct btrfs_iget_args *args = p;
4939         inode->i_ino = args->ino;
4940         BTRFS_I(inode)->root = args->root;
4941         return 0;
4942 }
4943
4944 static int btrfs_find_actor(struct inode *inode, void *opaque)
4945 {
4946         struct btrfs_iget_args *args = opaque;
4947         return args->ino == btrfs_ino(inode) &&
4948                 args->root == BTRFS_I(inode)->root;
4949 }
4950
4951 static struct inode *btrfs_iget_locked(struct super_block *s,
4952                                        u64 objectid,
4953                                        struct btrfs_root *root)
4954 {
4955         struct inode *inode;
4956         struct btrfs_iget_args args;
4957         unsigned long hashval = btrfs_inode_hash(objectid, root);
4958
4959         args.ino = objectid;
4960         args.root = root;
4961
4962         inode = iget5_locked(s, hashval, btrfs_find_actor,
4963                              btrfs_init_locked_inode,
4964                              (void *)&args);
4965         return inode;
4966 }
4967
4968 /* Get an inode object given its location and corresponding root.
4969  * Returns in *is_new if the inode was read from disk
4970  */
4971 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4972                          struct btrfs_root *root, int *new)
4973 {
4974         struct inode *inode;
4975
4976         inode = btrfs_iget_locked(s, location->objectid, root);
4977         if (!inode)
4978                 return ERR_PTR(-ENOMEM);
4979
4980         if (inode->i_state & I_NEW) {
4981                 BTRFS_I(inode)->root = root;
4982                 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4983                 btrfs_read_locked_inode(inode);
4984                 if (!is_bad_inode(inode)) {
4985                         inode_tree_add(inode);
4986                         unlock_new_inode(inode);
4987                         if (new)
4988                                 *new = 1;
4989                 } else {
4990                         unlock_new_inode(inode);
4991                         iput(inode);
4992                         inode = ERR_PTR(-ESTALE);
4993                 }
4994         }
4995
4996         return inode;
4997 }
4998
4999 static struct inode *new_simple_dir(struct super_block *s,
5000                                     struct btrfs_key *key,
5001                                     struct btrfs_root *root)
5002 {
5003         struct inode *inode = new_inode(s);
5004
5005         if (!inode)
5006                 return ERR_PTR(-ENOMEM);
5007
5008         BTRFS_I(inode)->root = root;
5009         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5010         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5011
5012         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5013         inode->i_op = &btrfs_dir_ro_inode_operations;
5014         inode->i_fop = &simple_dir_operations;
5015         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5016         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5017
5018         return inode;
5019 }
5020
5021 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5022 {
5023         struct inode *inode;
5024         struct btrfs_root *root = BTRFS_I(dir)->root;
5025         struct btrfs_root *sub_root = root;
5026         struct btrfs_key location;
5027         int index;
5028         int ret = 0;
5029
5030         if (dentry->d_name.len > BTRFS_NAME_LEN)
5031                 return ERR_PTR(-ENAMETOOLONG);
5032
5033         ret = btrfs_inode_by_name(dir, dentry, &location);
5034         if (ret < 0)
5035                 return ERR_PTR(ret);
5036
5037         if (location.objectid == 0)
5038                 return ERR_PTR(-ENOENT);
5039
5040         if (location.type == BTRFS_INODE_ITEM_KEY) {
5041                 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5042                 return inode;
5043         }
5044
5045         BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5046
5047         index = srcu_read_lock(&root->fs_info->subvol_srcu);
5048         ret = fixup_tree_root_location(root, dir, dentry,
5049                                        &location, &sub_root);
5050         if (ret < 0) {
5051                 if (ret != -ENOENT)
5052                         inode = ERR_PTR(ret);
5053                 else
5054                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
5055         } else {
5056                 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5057         }
5058         srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5059
5060         if (!IS_ERR(inode) && root != sub_root) {
5061                 down_read(&root->fs_info->cleanup_work_sem);
5062                 if (!(inode->i_sb->s_flags & MS_RDONLY))
5063                         ret = btrfs_orphan_cleanup(sub_root);
5064                 up_read(&root->fs_info->cleanup_work_sem);
5065                 if (ret) {
5066                         iput(inode);
5067                         inode = ERR_PTR(ret);
5068                 }
5069         }
5070
5071         return inode;
5072 }
5073
5074 static int btrfs_dentry_delete(const struct dentry *dentry)
5075 {
5076         struct btrfs_root *root;
5077         struct inode *inode = dentry->d_inode;
5078
5079         if (!inode && !IS_ROOT(dentry))
5080                 inode = dentry->d_parent->d_inode;
5081
5082         if (inode) {
5083                 root = BTRFS_I(inode)->root;
5084                 if (btrfs_root_refs(&root->root_item) == 0)
5085                         return 1;
5086
5087                 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5088                         return 1;
5089         }
5090         return 0;
5091 }
5092
5093 static void btrfs_dentry_release(struct dentry *dentry)
5094 {
5095         if (dentry->d_fsdata)
5096                 kfree(dentry->d_fsdata);
5097 }
5098
5099 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5100                                    unsigned int flags)
5101 {
5102         struct inode *inode;
5103
5104         inode = btrfs_lookup_dentry(dir, dentry);
5105         if (IS_ERR(inode)) {
5106                 if (PTR_ERR(inode) == -ENOENT)
5107                         inode = NULL;
5108                 else
5109                         return ERR_CAST(inode);
5110         }
5111
5112         return d_splice_alias(inode, dentry);
5113 }
5114
5115 unsigned char btrfs_filetype_table[] = {
5116         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5117 };
5118
5119 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5120 {
5121         struct inode *inode = file_inode(file);
5122         struct btrfs_root *root = BTRFS_I(inode)->root;
5123         struct btrfs_item *item;
5124         struct btrfs_dir_item *di;
5125         struct btrfs_key key;
5126         struct btrfs_key found_key;
5127         struct btrfs_path *path;
5128         struct list_head ins_list;
5129         struct list_head del_list;
5130         int ret;
5131         struct extent_buffer *leaf;
5132         int slot;
5133         unsigned char d_type;
5134         int over = 0;
5135         u32 di_cur;
5136         u32 di_total;
5137         u32 di_len;
5138         int key_type = BTRFS_DIR_INDEX_KEY;
5139         char tmp_name[32];
5140         char *name_ptr;
5141         int name_len;
5142         int is_curr = 0;        /* ctx->pos points to the current index? */
5143
5144         /* FIXME, use a real flag for deciding about the key type */
5145         if (root->fs_info->tree_root == root)
5146                 key_type = BTRFS_DIR_ITEM_KEY;
5147
5148         if (!dir_emit_dots(file, ctx))
5149                 return 0;
5150
5151         path = btrfs_alloc_path();
5152         if (!path)
5153                 return -ENOMEM;
5154
5155         path->reada = 1;
5156
5157         if (key_type == BTRFS_DIR_INDEX_KEY) {
5158                 INIT_LIST_HEAD(&ins_list);
5159                 INIT_LIST_HEAD(&del_list);
5160                 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5161         }
5162
5163         btrfs_set_key_type(&key, key_type);
5164         key.offset = ctx->pos;
5165         key.objectid = btrfs_ino(inode);
5166
5167         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5168         if (ret < 0)
5169                 goto err;
5170
5171         while (1) {
5172                 leaf = path->nodes[0];
5173                 slot = path->slots[0];
5174                 if (slot >= btrfs_header_nritems(leaf)) {
5175                         ret = btrfs_next_leaf(root, path);
5176                         if (ret < 0)
5177                                 goto err;
5178                         else if (ret > 0)
5179                                 break;
5180                         continue;
5181                 }
5182
5183                 item = btrfs_item_nr(slot);
5184                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5185
5186                 if (found_key.objectid != key.objectid)
5187                         break;
5188                 if (btrfs_key_type(&found_key) != key_type)
5189                         break;
5190                 if (found_key.offset < ctx->pos)
5191                         goto next;
5192                 if (key_type == BTRFS_DIR_INDEX_KEY &&
5193                     btrfs_should_delete_dir_index(&del_list,
5194                                                   found_key.offset))
5195                         goto next;
5196
5197                 ctx->pos = found_key.offset;
5198                 is_curr = 1;
5199
5200                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5201                 di_cur = 0;
5202                 di_total = btrfs_item_size(leaf, item);
5203
5204                 while (di_cur < di_total) {
5205                         struct btrfs_key location;
5206
5207                         if (verify_dir_item(root, leaf, di))
5208                                 break;
5209
5210                         name_len = btrfs_dir_name_len(leaf, di);
5211                         if (name_len <= sizeof(tmp_name)) {
5212                                 name_ptr = tmp_name;
5213                         } else {
5214                                 name_ptr = kmalloc(name_len, GFP_NOFS);
5215                                 if (!name_ptr) {
5216                                         ret = -ENOMEM;
5217                                         goto err;
5218                                 }
5219                         }
5220                         read_extent_buffer(leaf, name_ptr,
5221                                            (unsigned long)(di + 1), name_len);
5222
5223                         d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5224                         btrfs_dir_item_key_to_cpu(leaf, di, &location);
5225
5226
5227                         /* is this a reference to our own snapshot? If so
5228                          * skip it.
5229                          *
5230                          * In contrast to old kernels, we insert the snapshot's
5231                          * dir item and dir index after it has been created, so
5232                          * we won't find a reference to our own snapshot. We
5233                          * still keep the following code for backward
5234                          * compatibility.
5235                          */
5236                         if (location.type == BTRFS_ROOT_ITEM_KEY &&
5237                             location.objectid == root->root_key.objectid) {
5238                                 over = 0;
5239                                 goto skip;
5240                         }
5241                         over = !dir_emit(ctx, name_ptr, name_len,
5242                                        location.objectid, d_type);
5243
5244 skip:
5245                         if (name_ptr != tmp_name)
5246                                 kfree(name_ptr);
5247
5248                         if (over)
5249                                 goto nopos;
5250                         di_len = btrfs_dir_name_len(leaf, di) +
5251                                  btrfs_dir_data_len(leaf, di) + sizeof(*di);
5252                         di_cur += di_len;
5253                         di = (struct btrfs_dir_item *)((char *)di + di_len);
5254                 }
5255 next:
5256                 path->slots[0]++;
5257         }
5258
5259         if (key_type == BTRFS_DIR_INDEX_KEY) {
5260                 if (is_curr)
5261                         ctx->pos++;
5262                 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5263                 if (ret)
5264                         goto nopos;
5265         }
5266
5267         /* Reached end of directory/root. Bump pos past the last item. */
5268         ctx->pos++;
5269
5270         /*
5271          * Stop new entries from being returned after we return the last
5272          * entry.
5273          *
5274          * New directory entries are assigned a strictly increasing
5275          * offset.  This means that new entries created during readdir
5276          * are *guaranteed* to be seen in the future by that readdir.
5277          * This has broken buggy programs which operate on names as
5278          * they're returned by readdir.  Until we re-use freed offsets
5279          * we have this hack to stop new entries from being returned
5280          * under the assumption that they'll never reach this huge
5281          * offset.
5282          *
5283          * This is being careful not to overflow 32bit loff_t unless the
5284          * last entry requires it because doing so has broken 32bit apps
5285          * in the past.
5286          */
5287         if (key_type == BTRFS_DIR_INDEX_KEY) {
5288                 if (ctx->pos >= INT_MAX)
5289                         ctx->pos = LLONG_MAX;
5290                 else
5291                         ctx->pos = INT_MAX;
5292         }
5293 nopos:
5294         ret = 0;
5295 err:
5296         if (key_type == BTRFS_DIR_INDEX_KEY)
5297                 btrfs_put_delayed_items(&ins_list, &del_list);
5298         btrfs_free_path(path);
5299         return ret;
5300 }
5301
5302 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5303 {
5304         struct btrfs_root *root = BTRFS_I(inode)->root;
5305         struct btrfs_trans_handle *trans;
5306         int ret = 0;
5307         bool nolock = false;
5308
5309         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5310                 return 0;
5311
5312         if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5313                 nolock = true;
5314
5315         if (wbc->sync_mode == WB_SYNC_ALL) {
5316                 if (nolock)
5317                         trans = btrfs_join_transaction_nolock(root);
5318                 else
5319                         trans = btrfs_join_transaction(root);
5320                 if (IS_ERR(trans))
5321                         return PTR_ERR(trans);
5322                 ret = btrfs_commit_transaction(trans, root);
5323         }
5324         return ret;
5325 }
5326
5327 /*
5328  * This is somewhat expensive, updating the tree every time the
5329  * inode changes.  But, it is most likely to find the inode in cache.
5330  * FIXME, needs more benchmarking...there are no reasons other than performance
5331  * to keep or drop this code.
5332  */
5333 static int btrfs_dirty_inode(struct inode *inode)
5334 {
5335         struct btrfs_root *root = BTRFS_I(inode)->root;
5336         struct btrfs_trans_handle *trans;
5337         int ret;
5338
5339         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5340                 return 0;
5341
5342         trans = btrfs_join_transaction(root);
5343         if (IS_ERR(trans))
5344                 return PTR_ERR(trans);
5345
5346         ret = btrfs_update_inode(trans, root, inode);
5347         if (ret && ret == -ENOSPC) {
5348                 /* whoops, lets try again with the full transaction */
5349                 btrfs_end_transaction(trans, root);
5350                 trans = btrfs_start_transaction(root, 1);
5351                 if (IS_ERR(trans))
5352                         return PTR_ERR(trans);
5353
5354                 ret = btrfs_update_inode(trans, root, inode);
5355         }
5356         btrfs_end_transaction(trans, root);
5357         if (BTRFS_I(inode)->delayed_node)
5358                 btrfs_balance_delayed_items(root);
5359
5360         return ret;
5361 }
5362
5363 /*
5364  * This is a copy of file_update_time.  We need this so we can return error on
5365  * ENOSPC for updating the inode in the case of file write and mmap writes.
5366  */
5367 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5368                              int flags)
5369 {
5370         struct btrfs_root *root = BTRFS_I(inode)->root;
5371
5372         if (btrfs_root_readonly(root))
5373                 return -EROFS;
5374
5375         if (flags & S_VERSION)
5376                 inode_inc_iversion(inode);
5377         if (flags & S_CTIME)
5378                 inode->i_ctime = *now;
5379         if (flags & S_MTIME)
5380                 inode->i_mtime = *now;
5381         if (flags & S_ATIME)
5382                 inode->i_atime = *now;
5383         return btrfs_dirty_inode(inode);
5384 }
5385
5386 /*
5387  * find the highest existing sequence number in a directory
5388  * and then set the in-memory index_cnt variable to reflect
5389  * free sequence numbers
5390  */
5391 static int btrfs_set_inode_index_count(struct inode *inode)
5392 {
5393         struct btrfs_root *root = BTRFS_I(inode)->root;
5394         struct btrfs_key key, found_key;
5395         struct btrfs_path *path;
5396         struct extent_buffer *leaf;
5397         int ret;
5398
5399         key.objectid = btrfs_ino(inode);
5400         btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5401         key.offset = (u64)-1;
5402
5403         path = btrfs_alloc_path();
5404         if (!path)
5405                 return -ENOMEM;
5406
5407         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5408         if (ret < 0)
5409                 goto out;
5410         /* FIXME: we should be able to handle this */
5411         if (ret == 0)
5412                 goto out;
5413         ret = 0;
5414
5415         /*
5416          * MAGIC NUMBER EXPLANATION:
5417          * since we search a directory based on f_pos we have to start at 2
5418          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5419          * else has to start at 2
5420          */
5421         if (path->slots[0] == 0) {
5422                 BTRFS_I(inode)->index_cnt = 2;
5423                 goto out;
5424         }
5425
5426         path->slots[0]--;
5427
5428         leaf = path->nodes[0];
5429         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5430
5431         if (found_key.objectid != btrfs_ino(inode) ||
5432             btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5433                 BTRFS_I(inode)->index_cnt = 2;
5434                 goto out;
5435         }
5436
5437         BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5438 out:
5439         btrfs_free_path(path);
5440         return ret;
5441 }
5442
5443 /*
5444  * helper to find a free sequence number in a given directory.  This current
5445  * code is very simple, later versions will do smarter things in the btree
5446  */
5447 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5448 {
5449         int ret = 0;
5450
5451         if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5452                 ret = btrfs_inode_delayed_dir_index_count(dir);
5453                 if (ret) {
5454                         ret = btrfs_set_inode_index_count(dir);
5455                         if (ret)
5456                                 return ret;
5457                 }
5458         }
5459
5460         *index = BTRFS_I(dir)->index_cnt;
5461         BTRFS_I(dir)->index_cnt++;
5462
5463         return ret;
5464 }
5465
5466 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5467                                      struct btrfs_root *root,
5468                                      struct inode *dir,
5469                                      const char *name, int name_len,
5470                                      u64 ref_objectid, u64 objectid,
5471                                      umode_t mode, u64 *index)
5472 {
5473         struct inode *inode;
5474         struct btrfs_inode_item *inode_item;
5475         struct btrfs_key *location;
5476         struct btrfs_path *path;
5477         struct btrfs_inode_ref *ref;
5478         struct btrfs_key key[2];
5479         u32 sizes[2];
5480         unsigned long ptr;
5481         int ret;
5482
5483         path = btrfs_alloc_path();
5484         if (!path)
5485                 return ERR_PTR(-ENOMEM);
5486
5487         inode = new_inode(root->fs_info->sb);
5488         if (!inode) {
5489                 btrfs_free_path(path);
5490                 return ERR_PTR(-ENOMEM);
5491         }
5492
5493         /*
5494          * we have to initialize this early, so we can reclaim the inode
5495          * number if we fail afterwards in this function.
5496          */
5497         inode->i_ino = objectid;
5498
5499         if (dir) {
5500                 trace_btrfs_inode_request(dir);
5501
5502                 ret = btrfs_set_inode_index(dir, index);
5503                 if (ret) {
5504                         btrfs_free_path(path);
5505                         iput(inode);
5506                         return ERR_PTR(ret);
5507                 }
5508         }
5509         /*
5510          * index_cnt is ignored for everything but a dir,
5511          * btrfs_get_inode_index_count has an explanation for the magic
5512          * number
5513          */
5514         BTRFS_I(inode)->index_cnt = 2;
5515         BTRFS_I(inode)->dir_index = *index;
5516         BTRFS_I(inode)->root = root;
5517         BTRFS_I(inode)->generation = trans->transid;
5518         inode->i_generation = BTRFS_I(inode)->generation;
5519
5520         /*
5521          * We could have gotten an inode number from somebody who was fsynced
5522          * and then removed in this same transaction, so let's just set full
5523          * sync since it will be a full sync anyway and this will blow away the
5524          * old info in the log.
5525          */
5526         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5527
5528         key[0].objectid = objectid;
5529         btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5530         key[0].offset = 0;
5531
5532         /*
5533          * Start new inodes with an inode_ref. This is slightly more
5534          * efficient for small numbers of hard links since they will
5535          * be packed into one item. Extended refs will kick in if we
5536          * add more hard links than can fit in the ref item.
5537          */
5538         key[1].objectid = objectid;
5539         btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5540         key[1].offset = ref_objectid;
5541
5542         sizes[0] = sizeof(struct btrfs_inode_item);
5543         sizes[1] = name_len + sizeof(*ref);
5544
5545         path->leave_spinning = 1;
5546         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5547         if (ret != 0)
5548                 goto fail;
5549
5550         inode_init_owner(inode, dir, mode);
5551         inode_set_bytes(inode, 0);
5552         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5553         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5554                                   struct btrfs_inode_item);
5555         memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5556                              sizeof(*inode_item));
5557         fill_inode_item(trans, path->nodes[0], inode_item, inode);
5558
5559         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5560                              struct btrfs_inode_ref);
5561         btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5562         btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5563         ptr = (unsigned long)(ref + 1);
5564         write_extent_buffer(path->nodes[0], name, ptr, name_len);
5565
5566         btrfs_mark_buffer_dirty(path->nodes[0]);
5567         btrfs_free_path(path);
5568
5569         location = &BTRFS_I(inode)->location;
5570         location->objectid = objectid;
5571         location->offset = 0;
5572         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5573
5574         btrfs_inherit_iflags(inode, dir);
5575
5576         if (S_ISREG(mode)) {
5577                 if (btrfs_test_opt(root, NODATASUM))
5578                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5579                 if (btrfs_test_opt(root, NODATACOW))
5580                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5581                                 BTRFS_INODE_NODATASUM;
5582         }
5583
5584         btrfs_insert_inode_hash(inode);
5585         inode_tree_add(inode);
5586
5587         trace_btrfs_inode_new(inode);
5588         btrfs_set_inode_last_trans(trans, inode);
5589
5590         btrfs_update_root_times(trans, root);
5591
5592         return inode;
5593 fail:
5594         if (dir)
5595                 BTRFS_I(dir)->index_cnt--;
5596         btrfs_free_path(path);
5597         iput(inode);
5598         return ERR_PTR(ret);
5599 }
5600
5601 static inline u8 btrfs_inode_type(struct inode *inode)
5602 {
5603         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5604 }
5605
5606 /*
5607  * utility function to add 'inode' into 'parent_inode' with
5608  * a give name and a given sequence number.
5609  * if 'add_backref' is true, also insert a backref from the
5610  * inode to the parent directory.
5611  */
5612 int btrfs_add_link(struct btrfs_trans_handle *trans,
5613                    struct inode *parent_inode, struct inode *inode,
5614                    const char *name, int name_len, int add_backref, u64 index)
5615 {
5616         int ret = 0;
5617         struct btrfs_key key;
5618         struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5619         u64 ino = btrfs_ino(inode);
5620         u64 parent_ino = btrfs_ino(parent_inode);
5621
5622         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5623                 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5624         } else {
5625                 key.objectid = ino;
5626                 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5627                 key.offset = 0;
5628         }
5629
5630         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5631                 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5632                                          key.objectid, root->root_key.objectid,
5633                                          parent_ino, index, name, name_len);
5634         } else if (add_backref) {
5635                 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5636                                              parent_ino, index);
5637         }
5638
5639         /* Nothing to clean up yet */
5640         if (ret)
5641                 return ret;
5642
5643         ret = btrfs_insert_dir_item(trans, root, name, name_len,
5644                                     parent_inode, &key,
5645                                     btrfs_inode_type(inode), index);
5646         if (ret == -EEXIST || ret == -EOVERFLOW)
5647                 goto fail_dir_item;
5648         else if (ret) {
5649                 btrfs_abort_transaction(trans, root, ret);
5650                 return ret;
5651         }
5652
5653         btrfs_i_size_write(parent_inode, parent_inode->i_size +
5654                            name_len * 2);
5655         inode_inc_iversion(parent_inode);
5656         parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5657         ret = btrfs_update_inode(trans, root, parent_inode);
5658         if (ret)
5659                 btrfs_abort_transaction(trans, root, ret);
5660         return ret;
5661
5662 fail_dir_item:
5663         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5664                 u64 local_index;
5665                 int err;
5666                 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5667                                  key.objectid, root->root_key.objectid,
5668                                  parent_ino, &local_index, name, name_len);
5669
5670         } else if (add_backref) {
5671                 u64 local_index;
5672                 int err;
5673
5674                 err = btrfs_del_inode_ref(trans, root, name, name_len,
5675                                           ino, parent_ino, &local_index);
5676         }
5677         return ret;
5678 }
5679
5680 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5681                             struct inode *dir, struct dentry *dentry,
5682                             struct inode *inode, int backref, u64 index)
5683 {
5684         int err = btrfs_add_link(trans, dir, inode,
5685                                  dentry->d_name.name, dentry->d_name.len,
5686                                  backref, index);
5687         if (err > 0)
5688                 err = -EEXIST;
5689         return err;
5690 }
5691
5692 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5693                         umode_t mode, dev_t rdev)
5694 {
5695         struct btrfs_trans_handle *trans;
5696         struct btrfs_root *root = BTRFS_I(dir)->root;
5697         struct inode *inode = NULL;
5698         int err;
5699         int drop_inode = 0;
5700         u64 objectid;
5701         u64 index = 0;
5702
5703         if (!new_valid_dev(rdev))
5704                 return -EINVAL;
5705
5706         /*
5707          * 2 for inode item and ref
5708          * 2 for dir items
5709          * 1 for xattr if selinux is on
5710          */
5711         trans = btrfs_start_transaction(root, 5);
5712         if (IS_ERR(trans))
5713                 return PTR_ERR(trans);
5714
5715         err = btrfs_find_free_ino(root, &objectid);
5716         if (err)
5717                 goto out_unlock;
5718
5719         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5720                                 dentry->d_name.len, btrfs_ino(dir), objectid,
5721                                 mode, &index);
5722         if (IS_ERR(inode)) {
5723                 err = PTR_ERR(inode);
5724                 goto out_unlock;
5725         }
5726
5727         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5728         if (err) {
5729                 drop_inode = 1;
5730                 goto out_unlock;
5731         }
5732
5733         /*
5734         * If the active LSM wants to access the inode during
5735         * d_instantiate it needs these. Smack checks to see
5736         * if the filesystem supports xattrs by looking at the
5737         * ops vector.
5738         */
5739
5740         inode->i_op = &btrfs_special_inode_operations;
5741         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5742         if (err)
5743                 drop_inode = 1;
5744         else {
5745                 init_special_inode(inode, inode->i_mode, rdev);
5746                 btrfs_update_inode(trans, root, inode);
5747                 d_instantiate(dentry, inode);
5748         }
5749 out_unlock:
5750         btrfs_end_transaction(trans, root);
5751         btrfs_btree_balance_dirty(root);
5752         if (drop_inode) {
5753                 inode_dec_link_count(inode);
5754                 iput(inode);
5755         }
5756         return err;
5757 }
5758
5759 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5760                         umode_t mode, bool excl)
5761 {
5762         struct btrfs_trans_handle *trans;
5763         struct btrfs_root *root = BTRFS_I(dir)->root;
5764         struct inode *inode = NULL;
5765         int drop_inode_on_err = 0;
5766         int err;
5767         u64 objectid;
5768         u64 index = 0;
5769
5770         /*
5771          * 2 for inode item and ref
5772          * 2 for dir items
5773          * 1 for xattr if selinux is on
5774          */
5775         trans = btrfs_start_transaction(root, 5);
5776         if (IS_ERR(trans))
5777                 return PTR_ERR(trans);
5778
5779         err = btrfs_find_free_ino(root, &objectid);
5780         if (err)
5781                 goto out_unlock;
5782
5783         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5784                                 dentry->d_name.len, btrfs_ino(dir), objectid,
5785                                 mode, &index);
5786         if (IS_ERR(inode)) {
5787                 err = PTR_ERR(inode);
5788                 goto out_unlock;
5789         }
5790         drop_inode_on_err = 1;
5791
5792         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5793         if (err)
5794                 goto out_unlock;
5795
5796         err = btrfs_update_inode(trans, root, inode);
5797         if (err)
5798                 goto out_unlock;
5799
5800         /*
5801         * If the active LSM wants to access the inode during
5802         * d_instantiate it needs these. Smack checks to see
5803         * if the filesystem supports xattrs by looking at the
5804         * ops vector.
5805         */
5806         inode->i_fop = &btrfs_file_operations;
5807         inode->i_op = &btrfs_file_inode_operations;
5808
5809         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5810         if (err)
5811                 goto out_unlock;
5812
5813         inode->i_mapping->a_ops = &btrfs_aops;
5814         inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5815         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5816         d_instantiate(dentry, inode);
5817
5818 out_unlock:
5819         btrfs_end_transaction(trans, root);
5820         if (err && drop_inode_on_err) {
5821                 inode_dec_link_count(inode);
5822                 iput(inode);
5823         }
5824         btrfs_btree_balance_dirty(root);
5825         return err;
5826 }
5827
5828 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5829                       struct dentry *dentry)
5830 {
5831         struct btrfs_trans_handle *trans;
5832         struct btrfs_root *root = BTRFS_I(dir)->root;
5833         struct inode *inode = old_dentry->d_inode;
5834         u64 index;
5835         int err;
5836         int drop_inode = 0;
5837
5838         /* do not allow sys_link's with other subvols of the same device */
5839         if (root->objectid != BTRFS_I(inode)->root->objectid)
5840                 return -EXDEV;
5841
5842         if (inode->i_nlink >= BTRFS_LINK_MAX)
5843                 return -EMLINK;
5844
5845         err = btrfs_set_inode_index(dir, &index);
5846         if (err)
5847                 goto fail;
5848
5849         /*
5850          * 2 items for inode and inode ref
5851          * 2 items for dir items
5852          * 1 item for parent inode
5853          */
5854         trans = btrfs_start_transaction(root, 5);
5855         if (IS_ERR(trans)) {
5856                 err = PTR_ERR(trans);
5857                 goto fail;
5858         }
5859
5860         /* There are several dir indexes for this inode, clear the cache. */
5861         BTRFS_I(inode)->dir_index = 0ULL;
5862         inc_nlink(inode);
5863         inode_inc_iversion(inode);
5864         inode->i_ctime = CURRENT_TIME;
5865         ihold(inode);
5866         set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5867
5868         err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5869
5870         if (err) {
5871                 drop_inode = 1;
5872         } else {
5873                 struct dentry *parent = dentry->d_parent;
5874                 err = btrfs_update_inode(trans, root, inode);
5875                 if (err)
5876                         goto fail;
5877                 d_instantiate(dentry, inode);
5878                 btrfs_log_new_name(trans, inode, NULL, parent);
5879         }
5880
5881         btrfs_end_transaction(trans, root);
5882 fail:
5883         if (drop_inode) {
5884                 inode_dec_link_count(inode);
5885                 iput(inode);
5886         }
5887         btrfs_btree_balance_dirty(root);
5888         return err;
5889 }
5890
5891 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5892 {
5893         struct inode *inode = NULL;
5894         struct btrfs_trans_handle *trans;
5895         struct btrfs_root *root = BTRFS_I(dir)->root;
5896         int err = 0;
5897         int drop_on_err = 0;
5898         u64 objectid = 0;
5899         u64 index = 0;
5900
5901         /*
5902          * 2 items for inode and ref
5903          * 2 items for dir items
5904          * 1 for xattr if selinux is on
5905          */
5906         trans = btrfs_start_transaction(root, 5);
5907         if (IS_ERR(trans))
5908                 return PTR_ERR(trans);
5909
5910         err = btrfs_find_free_ino(root, &objectid);
5911         if (err)
5912                 goto out_fail;
5913
5914         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5915                                 dentry->d_name.len, btrfs_ino(dir), objectid,
5916                                 S_IFDIR | mode, &index);
5917         if (IS_ERR(inode)) {
5918                 err = PTR_ERR(inode);
5919                 goto out_fail;
5920         }
5921
5922         drop_on_err = 1;
5923
5924         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5925         if (err)
5926                 goto out_fail;
5927
5928         inode->i_op = &btrfs_dir_inode_operations;
5929         inode->i_fop = &btrfs_dir_file_operations;
5930
5931         btrfs_i_size_write(inode, 0);
5932         err = btrfs_update_inode(trans, root, inode);
5933         if (err)
5934                 goto out_fail;
5935
5936         err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5937                              dentry->d_name.len, 0, index);
5938         if (err)
5939                 goto out_fail;
5940
5941         d_instantiate(dentry, inode);
5942         drop_on_err = 0;
5943
5944 out_fail:
5945         btrfs_end_transaction(trans, root);
5946         if (drop_on_err)
5947                 iput(inode);
5948         btrfs_btree_balance_dirty(root);
5949         return err;
5950 }
5951
5952 /* helper for btfs_get_extent.  Given an existing extent in the tree,
5953  * and an extent that you want to insert, deal with overlap and insert
5954  * the new extent into the tree.
5955  */
5956 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5957                                 struct extent_map *existing,
5958                                 struct extent_map *em,
5959                                 u64 map_start, u64 map_len)
5960 {
5961         u64 start_diff;
5962
5963         BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5964         start_diff = map_start - em->start;
5965         em->start = map_start;
5966         em->len = map_len;
5967         if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5968             !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5969                 em->block_start += start_diff;
5970                 em->block_len -= start_diff;
5971         }
5972         return add_extent_mapping(em_tree, em, 0);
5973 }
5974
5975 static noinline int uncompress_inline(struct btrfs_path *path,
5976                                       struct inode *inode, struct page *page,
5977                                       size_t pg_offset, u64 extent_offset,
5978                                       struct btrfs_file_extent_item *item)
5979 {
5980         int ret;
5981         struct extent_buffer *leaf = path->nodes[0];
5982         char *tmp;
5983         size_t max_size;
5984         unsigned long inline_size;
5985         unsigned long ptr;
5986         int compress_type;
5987
5988         WARN_ON(pg_offset != 0);
5989         compress_type = btrfs_file_extent_compression(leaf, item);
5990         max_size = btrfs_file_extent_ram_bytes(leaf, item);
5991         inline_size = btrfs_file_extent_inline_item_len(leaf,
5992                                         btrfs_item_nr(path->slots[0]));
5993         tmp = kmalloc(inline_size, GFP_NOFS);
5994         if (!tmp)
5995                 return -ENOMEM;
5996         ptr = btrfs_file_extent_inline_start(item);
5997
5998         read_extent_buffer(leaf, tmp, ptr, inline_size);
5999
6000         max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6001         ret = btrfs_decompress(compress_type, tmp, page,
6002                                extent_offset, inline_size, max_size);
6003         if (ret) {
6004                 char *kaddr = kmap_atomic(page);
6005                 unsigned long copy_size = min_t(u64,
6006                                   PAGE_CACHE_SIZE - pg_offset,
6007                                   max_size - extent_offset);
6008                 memset(kaddr + pg_offset, 0, copy_size);
6009                 kunmap_atomic(kaddr);
6010         }
6011         kfree(tmp);
6012         return 0;
6013 }
6014
6015 /*
6016  * a bit scary, this does extent mapping from logical file offset to the disk.
6017  * the ugly parts come from merging extents from the disk with the in-ram
6018  * representation.  This gets more complex because of the data=ordered code,
6019  * where the in-ram extents might be locked pending data=ordered completion.
6020  *
6021  * This also copies inline extents directly into the page.
6022  */
6023
6024 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6025                                     size_t pg_offset, u64 start, u64 len,
6026                                     int create)
6027 {
6028         int ret;
6029         int err = 0;
6030         u64 bytenr;
6031         u64 extent_start = 0;
6032         u64 extent_end = 0;
6033         u64 objectid = btrfs_ino(inode);
6034         u32 found_type;
6035         struct btrfs_path *path = NULL;
6036         struct btrfs_root *root = BTRFS_I(inode)->root;
6037         struct btrfs_file_extent_item *item;
6038         struct extent_buffer *leaf;
6039         struct btrfs_key found_key;
6040         struct extent_map *em = NULL;
6041         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6042         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6043         struct btrfs_trans_handle *trans = NULL;
6044         int compress_type;
6045
6046 again:
6047         read_lock(&em_tree->lock);
6048         em = lookup_extent_mapping(em_tree, start, len);
6049         if (em)
6050                 em->bdev = root->fs_info->fs_devices->latest_bdev;
6051         read_unlock(&em_tree->lock);
6052
6053         if (em) {
6054                 if (em->start > start || em->start + em->len <= start)
6055                         free_extent_map(em);
6056                 else if (em->block_start == EXTENT_MAP_INLINE && page)
6057                         free_extent_map(em);
6058                 else
6059                         goto out;
6060         }
6061         em = alloc_extent_map();
6062         if (!em) {
6063                 err = -ENOMEM;
6064                 goto out;
6065         }
6066         em->bdev = root->fs_info->fs_devices->latest_bdev;
6067         em->start = EXTENT_MAP_HOLE;
6068         em->orig_start = EXTENT_MAP_HOLE;
6069         em->len = (u64)-1;
6070         em->block_len = (u64)-1;
6071
6072         if (!path) {
6073                 path = btrfs_alloc_path();
6074                 if (!path) {
6075                         err = -ENOMEM;
6076                         goto out;
6077                 }
6078                 /*
6079                  * Chances are we'll be called again, so go ahead and do
6080                  * readahead
6081                  */
6082                 path->reada = 1;
6083         }
6084
6085         ret = btrfs_lookup_file_extent(trans, root, path,
6086                                        objectid, start, trans != NULL);
6087         if (ret < 0) {
6088                 err = ret;
6089                 goto out;
6090         }
6091
6092         if (ret != 0) {
6093                 if (path->slots[0] == 0)
6094                         goto not_found;
6095                 path->slots[0]--;
6096         }
6097
6098         leaf = path->nodes[0];
6099         item = btrfs_item_ptr(leaf, path->slots[0],
6100                               struct btrfs_file_extent_item);
6101         /* are we inside the extent that was found? */
6102         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6103         found_type = btrfs_key_type(&found_key);
6104         if (found_key.objectid != objectid ||
6105             found_type != BTRFS_EXTENT_DATA_KEY) {
6106                 /*
6107                  * If we backup past the first extent we want to move forward
6108                  * and see if there is an extent in front of us, otherwise we'll
6109                  * say there is a hole for our whole search range which can
6110                  * cause problems.
6111                  */
6112                 extent_end = start;
6113                 goto next;
6114         }
6115
6116         found_type = btrfs_file_extent_type(leaf, item);
6117         extent_start = found_key.offset;
6118         compress_type = btrfs_file_extent_compression(leaf, item);
6119         if (found_type == BTRFS_FILE_EXTENT_REG ||
6120             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6121                 extent_end = extent_start +
6122                        btrfs_file_extent_num_bytes(leaf, item);
6123         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6124                 size_t size;
6125                 size = btrfs_file_extent_inline_len(leaf, item);
6126                 extent_end = ALIGN(extent_start + size, root->sectorsize);
6127         }
6128 next:
6129         if (start >= extent_end) {
6130                 path->slots[0]++;
6131                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6132                         ret = btrfs_next_leaf(root, path);
6133                         if (ret < 0) {
6134                                 err = ret;
6135                                 goto out;
6136                         }
6137                         if (ret > 0)
6138                                 goto not_found;
6139                         leaf = path->nodes[0];
6140                 }
6141                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6142                 if (found_key.objectid != objectid ||
6143                     found_key.type != BTRFS_EXTENT_DATA_KEY)
6144                         goto not_found;
6145                 if (start + len <= found_key.offset)
6146                         goto not_found;
6147                 em->start = start;
6148                 em->orig_start = start;
6149                 em->len = found_key.offset - start;
6150                 goto not_found_em;
6151         }
6152
6153         em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6154         if (found_type == BTRFS_FILE_EXTENT_REG ||
6155             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6156                 em->start = extent_start;
6157                 em->len = extent_end - extent_start;
6158                 em->orig_start = extent_start -
6159                                  btrfs_file_extent_offset(leaf, item);
6160                 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6161                                                                       item);
6162                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6163                 if (bytenr == 0) {
6164                         em->block_start = EXTENT_MAP_HOLE;
6165                         goto insert;
6166                 }
6167                 if (compress_type != BTRFS_COMPRESS_NONE) {
6168                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6169                         em->compress_type = compress_type;
6170                         em->block_start = bytenr;
6171                         em->block_len = em->orig_block_len;
6172                 } else {
6173                         bytenr += btrfs_file_extent_offset(leaf, item);
6174                         em->block_start = bytenr;
6175                         em->block_len = em->len;
6176                         if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6177                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6178                 }
6179                 goto insert;
6180         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6181                 unsigned long ptr;
6182                 char *map;
6183                 size_t size;
6184                 size_t extent_offset;
6185                 size_t copy_size;
6186
6187                 em->block_start = EXTENT_MAP_INLINE;
6188                 if (!page || create) {
6189                         em->start = extent_start;
6190                         em->len = extent_end - extent_start;
6191                         goto out;
6192                 }
6193
6194                 size = btrfs_file_extent_inline_len(leaf, item);
6195                 extent_offset = page_offset(page) + pg_offset - extent_start;
6196                 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6197                                 size - extent_offset);
6198                 em->start = extent_start + extent_offset;
6199                 em->len = ALIGN(copy_size, root->sectorsize);
6200                 em->orig_block_len = em->len;
6201                 em->orig_start = em->start;
6202                 if (compress_type) {
6203                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6204                         em->compress_type = compress_type;
6205                 }
6206                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6207                 if (create == 0 && !PageUptodate(page)) {
6208                         if (btrfs_file_extent_compression(leaf, item) !=
6209                             BTRFS_COMPRESS_NONE) {
6210                                 ret = uncompress_inline(path, inode, page,
6211                                                         pg_offset,
6212                                                         extent_offset, item);
6213                                 BUG_ON(ret); /* -ENOMEM */
6214                         } else {
6215                                 map = kmap(page);
6216                                 read_extent_buffer(leaf, map + pg_offset, ptr,
6217                                                    copy_size);
6218                                 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6219                                         memset(map + pg_offset + copy_size, 0,
6220                                                PAGE_CACHE_SIZE - pg_offset -
6221                                                copy_size);
6222                                 }
6223                                 kunmap(page);
6224                         }
6225                         flush_dcache_page(page);
6226                 } else if (create && PageUptodate(page)) {
6227                         BUG();
6228                         if (!trans) {
6229                                 kunmap(page);
6230                                 free_extent_map(em);
6231                                 em = NULL;
6232
6233                                 btrfs_release_path(path);
6234                                 trans = btrfs_join_transaction(root);
6235
6236                                 if (IS_ERR(trans))
6237                                         return ERR_CAST(trans);
6238                                 goto again;
6239                         }
6240                         map = kmap(page);
6241                         write_extent_buffer(leaf, map + pg_offset, ptr,
6242                                             copy_size);
6243                         kunmap(page);
6244                         btrfs_mark_buffer_dirty(leaf);
6245                 }
6246                 set_extent_uptodate(io_tree, em->start,
6247                                     extent_map_end(em) - 1, NULL, GFP_NOFS);
6248                 goto insert;
6249         } else {
6250                 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6251         }
6252 not_found:
6253         em->start = start;
6254         em->orig_start = start;
6255         em->len = len;
6256 not_found_em:
6257         em->block_start = EXTENT_MAP_HOLE;
6258         set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6259 insert:
6260         btrfs_release_path(path);
6261         if (em->start > start || extent_map_end(em) <= start) {
6262                 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6263                         em->start, em->len, start, len);
6264                 err = -EIO;
6265                 goto out;
6266         }
6267
6268         err = 0;
6269         write_lock(&em_tree->lock);
6270         ret = add_extent_mapping(em_tree, em, 0);
6271         /* it is possible that someone inserted the extent into the tree
6272          * while we had the lock dropped.  It is also possible that
6273          * an overlapping map exists in the tree
6274          */
6275         if (ret == -EEXIST) {
6276                 struct extent_map *existing;
6277
6278                 ret = 0;
6279
6280                 existing = lookup_extent_mapping(em_tree, start, len);
6281                 if (existing && (existing->start > start ||
6282                     existing->start + existing->len <= start)) {
6283                         free_extent_map(existing);
6284                         existing = NULL;
6285                 }
6286                 if (!existing) {
6287                         existing = lookup_extent_mapping(em_tree, em->start,
6288                                                          em->len);
6289                         if (existing) {
6290                                 err = merge_extent_mapping(em_tree, existing,
6291                                                            em, start,
6292                                                            root->sectorsize);
6293                                 free_extent_map(existing);
6294                                 if (err) {
6295                                         free_extent_map(em);
6296                                         em = NULL;
6297                                 }
6298                         } else {
6299                                 err = -EIO;
6300                                 free_extent_map(em);
6301                                 em = NULL;
6302                         }
6303                 } else {
6304                         free_extent_map(em);
6305                         em = existing;
6306                         err = 0;
6307                 }
6308         }
6309         write_unlock(&em_tree->lock);
6310 out:
6311
6312         trace_btrfs_get_extent(root, em);
6313
6314         if (path)
6315                 btrfs_free_path(path);
6316         if (trans) {
6317                 ret = btrfs_end_transaction(trans, root);
6318                 if (!err)
6319                         err = ret;
6320         }
6321         if (err) {
6322                 free_extent_map(em);
6323                 return ERR_PTR(err);
6324         }
6325         BUG_ON(!em); /* Error is always set */
6326         return em;
6327 }
6328
6329 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6330                                            size_t pg_offset, u64 start, u64 len,
6331                                            int create)
6332 {
6333         struct extent_map *em;
6334         struct extent_map *hole_em = NULL;
6335         u64 range_start = start;
6336         u64 end;
6337         u64 found;
6338         u64 found_end;
6339         int err = 0;
6340
6341         em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6342         if (IS_ERR(em))
6343                 return em;
6344         if (em) {
6345                 /*
6346                  * if our em maps to
6347                  * -  a hole or
6348                  * -  a pre-alloc extent,
6349                  * there might actually be delalloc bytes behind it.
6350                  */
6351                 if (em->block_start != EXTENT_MAP_HOLE &&
6352                     !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6353                         return em;
6354                 else
6355                         hole_em = em;
6356         }
6357
6358         /* check to see if we've wrapped (len == -1 or similar) */
6359         end = start + len;
6360         if (end < start)
6361                 end = (u64)-1;
6362         else
6363                 end -= 1;
6364
6365         em = NULL;
6366
6367         /* ok, we didn't find anything, lets look for delalloc */
6368         found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6369                                  end, len, EXTENT_DELALLOC, 1);
6370         found_end = range_start + found;
6371         if (found_end < range_start)
6372                 found_end = (u64)-1;
6373
6374         /*
6375          * we didn't find anything useful, return
6376          * the original results from get_extent()
6377          */
6378         if (range_start > end || found_end <= start) {
6379                 em = hole_em;
6380                 hole_em = NULL;
6381                 goto out;
6382         }
6383
6384         /* adjust the range_start to make sure it doesn't
6385          * go backwards from the start they passed in
6386          */
6387         range_start = max(start, range_start);
6388         found = found_end - range_start;
6389
6390         if (found > 0) {
6391                 u64 hole_start = start;
6392                 u64 hole_len = len;
6393
6394                 em = alloc_extent_map();
6395                 if (!em) {
6396                         err = -ENOMEM;
6397                         goto out;
6398                 }
6399                 /*
6400                  * when btrfs_get_extent can't find anything it
6401                  * returns one huge hole
6402                  *
6403                  * make sure what it found really fits our range, and
6404                  * adjust to make sure it is based on the start from
6405                  * the caller
6406                  */
6407                 if (hole_em) {
6408                         u64 calc_end = extent_map_end(hole_em);
6409
6410                         if (calc_end <= start || (hole_em->start > end)) {
6411                                 free_extent_map(hole_em);
6412                                 hole_em = NULL;
6413                         } else {
6414                                 hole_start = max(hole_em->start, start);
6415                                 hole_len = calc_end - hole_start;
6416                         }
6417                 }
6418                 em->bdev = NULL;
6419                 if (hole_em && range_start > hole_start) {
6420                         /* our hole starts before our delalloc, so we
6421                          * have to return just the parts of the hole
6422                          * that go until  the delalloc starts
6423                          */
6424                         em->len = min(hole_len,
6425                                       range_start - hole_start);
6426                         em->start = hole_start;
6427                         em->orig_start = hole_start;
6428                         /*
6429                          * don't adjust block start at all,
6430                          * it is fixed at EXTENT_MAP_HOLE
6431                          */
6432                         em->block_start = hole_em->block_start;
6433                         em->block_len = hole_len;
6434                         if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6435                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6436                 } else {
6437                         em->start = range_start;
6438                         em->len = found;
6439                         em->orig_start = range_start;
6440                         em->block_start = EXTENT_MAP_DELALLOC;
6441                         em->block_len = found;
6442                 }
6443         } else if (hole_em) {
6444                 return hole_em;
6445         }
6446 out:
6447
6448         free_extent_map(hole_em);
6449         if (err) {
6450                 free_extent_map(em);
6451                 return ERR_PTR(err);
6452         }
6453         return em;
6454 }
6455
6456 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6457                                                   u64 start, u64 len)
6458 {
6459         struct btrfs_root *root = BTRFS_I(inode)->root;
6460         struct extent_map *em;
6461         struct btrfs_key ins;
6462         u64 alloc_hint;
6463         int ret;
6464
6465         alloc_hint = get_extent_allocation_hint(inode, start, len);
6466         ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6467                                    alloc_hint, &ins, 1);
6468         if (ret)
6469                 return ERR_PTR(ret);
6470
6471         em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6472                               ins.offset, ins.offset, ins.offset, 0);
6473         if (IS_ERR(em)) {
6474                 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6475                 return em;
6476         }
6477
6478         ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6479                                            ins.offset, ins.offset, 0);
6480         if (ret) {
6481                 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6482                 free_extent_map(em);
6483                 return ERR_PTR(ret);
6484         }
6485
6486         return em;
6487 }
6488
6489 /*
6490  * returns 1 when the nocow is safe, < 1 on error, 0 if the
6491  * block must be cow'd
6492  */
6493 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6494                               u64 *orig_start, u64 *orig_block_len,
6495                               u64 *ram_bytes)
6496 {
6497         struct btrfs_trans_handle *trans;
6498         struct btrfs_path *path;
6499         int ret;
6500         struct extent_buffer *leaf;
6501         struct btrfs_root *root = BTRFS_I(inode)->root;
6502         struct btrfs_file_extent_item *fi;
6503         struct btrfs_key key;
6504         u64 disk_bytenr;
6505         u64 backref_offset;
6506         u64 extent_end;
6507         u64 num_bytes;
6508         int slot;
6509         int found_type;
6510         bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6511         path = btrfs_alloc_path();
6512         if (!path)
6513                 return -ENOMEM;
6514
6515         ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6516                                        offset, 0);
6517         if (ret < 0)
6518                 goto out;
6519
6520         slot = path->slots[0];
6521         if (ret == 1) {
6522                 if (slot == 0) {
6523                         /* can't find the item, must cow */
6524                         ret = 0;
6525                         goto out;
6526                 }
6527                 slot--;
6528         }
6529         ret = 0;
6530         leaf = path->nodes[0];
6531         btrfs_item_key_to_cpu(leaf, &key, slot);
6532         if (key.objectid != btrfs_ino(inode) ||
6533             key.type != BTRFS_EXTENT_DATA_KEY) {
6534                 /* not our file or wrong item type, must cow */
6535                 goto out;
6536         }
6537
6538         if (key.offset > offset) {
6539                 /* Wrong offset, must cow */
6540                 goto out;
6541         }
6542
6543         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6544         found_type = btrfs_file_extent_type(leaf, fi);
6545         if (found_type != BTRFS_FILE_EXTENT_REG &&
6546             found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6547                 /* not a regular extent, must cow */
6548                 goto out;
6549         }
6550
6551         if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6552                 goto out;
6553
6554         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6555         if (disk_bytenr == 0)
6556                 goto out;
6557
6558         if (btrfs_file_extent_compression(leaf, fi) ||
6559             btrfs_file_extent_encryption(leaf, fi) ||
6560             btrfs_file_extent_other_encoding(leaf, fi))
6561                 goto out;
6562
6563         backref_offset = btrfs_file_extent_offset(leaf, fi);
6564
6565         if (orig_start) {
6566                 *orig_start = key.offset - backref_offset;
6567                 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6568                 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6569         }
6570
6571         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6572
6573         if (btrfs_extent_readonly(root, disk_bytenr))
6574                 goto out;
6575         btrfs_release_path(path);
6576
6577         /*
6578          * look for other files referencing this extent, if we
6579          * find any we must cow
6580          */
6581         trans = btrfs_join_transaction(root);
6582         if (IS_ERR(trans)) {
6583                 ret = 0;
6584                 goto out;
6585         }
6586
6587         ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6588                                     key.offset - backref_offset, disk_bytenr);
6589         btrfs_end_transaction(trans, root);
6590         if (ret) {
6591                 ret = 0;
6592                 goto out;
6593         }
6594
6595         /*
6596          * adjust disk_bytenr and num_bytes to cover just the bytes
6597          * in this extent we are about to write.  If there
6598          * are any csums in that range we have to cow in order
6599          * to keep the csums correct
6600          */
6601         disk_bytenr += backref_offset;
6602         disk_bytenr += offset - key.offset;
6603         num_bytes = min(offset + *len, extent_end) - offset;
6604         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6605                                 goto out;
6606         /*
6607          * all of the above have passed, it is safe to overwrite this extent
6608          * without cow
6609          */
6610         *len = num_bytes;
6611         ret = 1;
6612 out:
6613         btrfs_free_path(path);
6614         return ret;
6615 }
6616
6617 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6618                               struct extent_state **cached_state, int writing)
6619 {
6620         struct btrfs_ordered_extent *ordered;
6621         int ret = 0;
6622
6623         while (1) {
6624                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6625                                  0, cached_state);
6626                 /*
6627                  * We're concerned with the entire range that we're going to be
6628                  * doing DIO to, so we need to make sure theres no ordered
6629                  * extents in this range.
6630                  */
6631                 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6632                                                      lockend - lockstart + 1);
6633
6634                 /*
6635                  * We need to make sure there are no buffered pages in this
6636                  * range either, we could have raced between the invalidate in
6637                  * generic_file_direct_write and locking the extent.  The
6638                  * invalidate needs to happen so that reads after a write do not
6639                  * get stale data.
6640                  */
6641                 if (!ordered && (!writing ||
6642                     !test_range_bit(&BTRFS_I(inode)->io_tree,
6643                                     lockstart, lockend, EXTENT_UPTODATE, 0,
6644                                     *cached_state)))
6645                         break;
6646
6647                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6648                                      cached_state, GFP_NOFS);
6649
6650                 if (ordered) {
6651                         btrfs_start_ordered_extent(inode, ordered, 1);
6652                         btrfs_put_ordered_extent(ordered);
6653                 } else {
6654                         /* Screw you mmap */
6655                         ret = filemap_write_and_wait_range(inode->i_mapping,
6656                                                            lockstart,
6657                                                            lockend);
6658                         if (ret)
6659                                 break;
6660
6661                         /*
6662                          * If we found a page that couldn't be invalidated just
6663                          * fall back to buffered.
6664                          */
6665                         ret = invalidate_inode_pages2_range(inode->i_mapping,
6666                                         lockstart >> PAGE_CACHE_SHIFT,
6667                                         lockend >> PAGE_CACHE_SHIFT);
6668                         if (ret)
6669                                 break;
6670                 }
6671
6672                 cond_resched();
6673         }
6674
6675         return ret;
6676 }
6677
6678 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6679                                            u64 len, u64 orig_start,
6680                                            u64 block_start, u64 block_len,
6681                                            u64 orig_block_len, u64 ram_bytes,
6682                                            int type)
6683 {
6684         struct extent_map_tree *em_tree;
6685         struct extent_map *em;
6686         struct btrfs_root *root = BTRFS_I(inode)->root;
6687         int ret;
6688
6689         em_tree = &BTRFS_I(inode)->extent_tree;
6690         em = alloc_extent_map();
6691         if (!em)
6692                 return ERR_PTR(-ENOMEM);
6693
6694         em->start = start;
6695         em->orig_start = orig_start;
6696         em->mod_start = start;
6697         em->mod_len = len;
6698         em->len = len;
6699         em->block_len = block_len;
6700         em->block_start = block_start;
6701         em->bdev = root->fs_info->fs_devices->latest_bdev;
6702         em->orig_block_len = orig_block_len;
6703         em->ram_bytes = ram_bytes;
6704         em->generation = -1;
6705         set_bit(EXTENT_FLAG_PINNED, &em->flags);
6706         if (type == BTRFS_ORDERED_PREALLOC)
6707                 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6708
6709         do {
6710                 btrfs_drop_extent_cache(inode, em->start,
6711                                 em->start + em->len - 1, 0);
6712                 write_lock(&em_tree->lock);
6713                 ret = add_extent_mapping(em_tree, em, 1);
6714                 write_unlock(&em_tree->lock);
6715         } while (ret == -EEXIST);
6716
6717         if (ret) {
6718                 free_extent_map(em);
6719                 return ERR_PTR(ret);
6720         }
6721
6722         return em;
6723 }
6724
6725
6726 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6727                                    struct buffer_head *bh_result, int create)
6728 {
6729         struct extent_map *em;
6730         struct btrfs_root *root = BTRFS_I(inode)->root;
6731         struct extent_state *cached_state = NULL;
6732         u64 start = iblock << inode->i_blkbits;
6733         u64 lockstart, lockend;
6734         u64 len = bh_result->b_size;
6735         int unlock_bits = EXTENT_LOCKED;
6736         int ret = 0;
6737
6738         if (create)
6739                 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6740         else
6741                 len = min_t(u64, len, root->sectorsize);
6742
6743         lockstart = start;
6744         lockend = start + len - 1;
6745
6746         /*
6747          * If this errors out it's because we couldn't invalidate pagecache for
6748          * this range and we need to fallback to buffered.
6749          */
6750         if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6751                 return -ENOTBLK;
6752
6753         em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6754         if (IS_ERR(em)) {
6755                 ret = PTR_ERR(em);
6756                 goto unlock_err;
6757         }
6758
6759         /*
6760          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6761          * io.  INLINE is special, and we could probably kludge it in here, but
6762          * it's still buffered so for safety lets just fall back to the generic
6763          * buffered path.
6764          *
6765          * For COMPRESSED we _have_ to read the entire extent in so we can
6766          * decompress it, so there will be buffering required no matter what we
6767          * do, so go ahead and fallback to buffered.
6768          *
6769          * We return -ENOTBLK because thats what makes DIO go ahead and go back
6770          * to buffered IO.  Don't blame me, this is the price we pay for using
6771          * the generic code.
6772          */
6773         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6774             em->block_start == EXTENT_MAP_INLINE) {
6775                 free_extent_map(em);
6776                 ret = -ENOTBLK;
6777                 goto unlock_err;
6778         }
6779
6780         /* Just a good old fashioned hole, return */
6781         if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6782                         test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6783                 free_extent_map(em);
6784                 goto unlock_err;
6785         }
6786
6787         /*
6788          * We don't allocate a new extent in the following cases
6789          *
6790          * 1) The inode is marked as NODATACOW.  In this case we'll just use the
6791          * existing extent.
6792          * 2) The extent is marked as PREALLOC.  We're good to go here and can
6793          * just use the extent.
6794          *
6795          */
6796         if (!create) {
6797                 len = min(len, em->len - (start - em->start));
6798                 lockstart = start + len;
6799                 goto unlock;
6800         }
6801
6802         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6803             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6804              em->block_start != EXTENT_MAP_HOLE)) {
6805                 int type;
6806                 int ret;
6807                 u64 block_start, orig_start, orig_block_len, ram_bytes;
6808
6809                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6810                         type = BTRFS_ORDERED_PREALLOC;
6811                 else
6812                         type = BTRFS_ORDERED_NOCOW;
6813                 len = min(len, em->len - (start - em->start));
6814                 block_start = em->block_start + (start - em->start);
6815
6816                 if (can_nocow_extent(inode, start, &len, &orig_start,
6817                                      &orig_block_len, &ram_bytes) == 1) {
6818                         if (type == BTRFS_ORDERED_PREALLOC) {
6819                                 free_extent_map(em);
6820                                 em = create_pinned_em(inode, start, len,
6821                                                        orig_start,
6822                                                        block_start, len,
6823                                                        orig_block_len,
6824                                                        ram_bytes, type);
6825                                 if (IS_ERR(em))
6826                                         goto unlock_err;
6827                         }
6828
6829                         ret = btrfs_add_ordered_extent_dio(inode, start,
6830                                            block_start, len, len, type);
6831                         if (ret) {
6832                                 free_extent_map(em);
6833                                 goto unlock_err;
6834                         }
6835                         goto unlock;
6836                 }
6837         }
6838
6839         /*
6840          * this will cow the extent, reset the len in case we changed
6841          * it above
6842          */
6843         len = bh_result->b_size;
6844         free_extent_map(em);
6845         em = btrfs_new_extent_direct(inode, start, len);
6846         if (IS_ERR(em)) {
6847                 ret = PTR_ERR(em);
6848                 goto unlock_err;
6849         }
6850         len = min(len, em->len - (start - em->start));
6851 unlock:
6852         bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6853                 inode->i_blkbits;
6854         bh_result->b_size = len;
6855         bh_result->b_bdev = em->bdev;
6856         set_buffer_mapped(bh_result);
6857         if (create) {
6858                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6859                         set_buffer_new(bh_result);
6860
6861                 /*
6862                  * Need to update the i_size under the extent lock so buffered
6863                  * readers will get the updated i_size when we unlock.
6864                  */
6865                 if (start + len > i_size_read(inode))
6866                         i_size_write(inode, start + len);
6867
6868                 spin_lock(&BTRFS_I(inode)->lock);
6869                 BTRFS_I(inode)->outstanding_extents++;
6870                 spin_unlock(&BTRFS_I(inode)->lock);
6871
6872                 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6873                                      lockstart + len - 1, EXTENT_DELALLOC, NULL,
6874                                      &cached_state, GFP_NOFS);
6875                 BUG_ON(ret);
6876         }
6877
6878         /*
6879          * In the case of write we need to clear and unlock the entire range,
6880          * in the case of read we need to unlock only the end area that we
6881          * aren't using if there is any left over space.
6882          */
6883         if (lockstart < lockend) {
6884                 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6885                                  lockend, unlock_bits, 1, 0,
6886                                  &cached_state, GFP_NOFS);
6887         } else {
6888                 free_extent_state(cached_state);
6889         }
6890
6891         free_extent_map(em);
6892
6893         return 0;
6894
6895 unlock_err:
6896         clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6897                          unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6898         return ret;
6899 }
6900
6901 static void btrfs_endio_direct_read(struct bio *bio, int err)
6902 {
6903         struct btrfs_dio_private *dip = bio->bi_private;
6904         struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6905         struct bio_vec *bvec = bio->bi_io_vec;
6906         struct inode *inode = dip->inode;
6907         struct btrfs_root *root = BTRFS_I(inode)->root;
6908         struct bio *dio_bio;
6909         u32 *csums = (u32 *)dip->csum;
6910         int index = 0;
6911         u64 start;
6912
6913         start = dip->logical_offset;
6914         do {
6915                 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6916                         struct page *page = bvec->bv_page;
6917                         char *kaddr;
6918                         u32 csum = ~(u32)0;
6919                         unsigned long flags;
6920
6921                         local_irq_save(flags);
6922                         kaddr = kmap_atomic(page);
6923                         csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6924                                                csum, bvec->bv_len);
6925                         btrfs_csum_final(csum, (char *)&csum);
6926                         kunmap_atomic(kaddr);
6927                         local_irq_restore(flags);
6928
6929                         flush_dcache_page(bvec->bv_page);
6930                         if (csum != csums[index]) {
6931                                 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
6932                                           btrfs_ino(inode), start, csum,
6933                                           csums[index]);
6934                                 err = -EIO;
6935                         }
6936                 }
6937
6938                 start += bvec->bv_len;
6939                 bvec++;
6940                 index++;
6941         } while (bvec <= bvec_end);
6942
6943         unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6944                       dip->logical_offset + dip->bytes - 1);
6945         dio_bio = dip->dio_bio;
6946
6947         kfree(dip);
6948
6949         /* If we had a csum failure make sure to clear the uptodate flag */
6950         if (err)
6951                 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6952         dio_end_io(dio_bio, err);
6953         bio_put(bio);
6954 }
6955
6956 static void btrfs_endio_direct_write(struct bio *bio, int err)
6957 {
6958         struct btrfs_dio_private *dip = bio->bi_private;
6959         struct inode *inode = dip->inode;
6960         struct btrfs_root *root = BTRFS_I(inode)->root;
6961         struct btrfs_ordered_extent *ordered = NULL;
6962         u64 ordered_offset = dip->logical_offset;
6963         u64 ordered_bytes = dip->bytes;
6964         struct bio *dio_bio;
6965         int ret;
6966
6967         if (err)
6968                 goto out_done;
6969 again:
6970         ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6971                                                    &ordered_offset,
6972                                                    ordered_bytes, !err);
6973         if (!ret)
6974                 goto out_test;
6975
6976         ordered->work.func = finish_ordered_fn;
6977         ordered->work.flags = 0;
6978         btrfs_queue_worker(&root->fs_info->endio_write_workers,
6979                            &ordered->work);
6980 out_test:
6981         /*
6982          * our bio might span multiple ordered extents.  If we haven't
6983          * completed the accounting for the whole dio, go back and try again
6984          */
6985         if (ordered_offset < dip->logical_offset + dip->bytes) {
6986                 ordered_bytes = dip->logical_offset + dip->bytes -
6987                         ordered_offset;
6988                 ordered = NULL;
6989                 goto again;
6990         }
6991 out_done:
6992         dio_bio = dip->dio_bio;
6993
6994         kfree(dip);
6995
6996         /* If we had an error make sure to clear the uptodate flag */
6997         if (err)
6998                 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6999         dio_end_io(dio_bio, err);
7000         bio_put(bio);
7001 }
7002
7003 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7004                                     struct bio *bio, int mirror_num,
7005                                     unsigned long bio_flags, u64 offset)
7006 {
7007         int ret;
7008         struct btrfs_root *root = BTRFS_I(inode)->root;
7009         ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7010         BUG_ON(ret); /* -ENOMEM */
7011         return 0;
7012 }
7013
7014 static void btrfs_end_dio_bio(struct bio *bio, int err)
7015 {
7016         struct btrfs_dio_private *dip = bio->bi_private;
7017
7018         if (err) {
7019                 btrfs_err(BTRFS_I(dip->inode)->root->fs_info,
7020                           "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7021                       btrfs_ino(dip->inode), bio->bi_rw,
7022                       (unsigned long long)bio->bi_sector, bio->bi_size, err);
7023                 dip->errors = 1;
7024
7025                 /*
7026                  * before atomic variable goto zero, we must make sure
7027                  * dip->errors is perceived to be set.
7028                  */
7029                 smp_mb__before_atomic_dec();
7030         }
7031
7032         /* if there are more bios still pending for this dio, just exit */
7033         if (!atomic_dec_and_test(&dip->pending_bios))
7034                 goto out;
7035
7036         if (dip->errors) {
7037                 bio_io_error(dip->orig_bio);
7038         } else {
7039                 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7040                 bio_endio(dip->orig_bio, 0);
7041         }
7042 out:
7043         bio_put(bio);
7044 }
7045
7046 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7047                                        u64 first_sector, gfp_t gfp_flags)
7048 {
7049         int nr_vecs = bio_get_nr_vecs(bdev);
7050         return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7051 }
7052
7053 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7054                                          int rw, u64 file_offset, int skip_sum,
7055                                          int async_submit)
7056 {
7057         struct btrfs_dio_private *dip = bio->bi_private;
7058         int write = rw & REQ_WRITE;
7059         struct btrfs_root *root = BTRFS_I(inode)->root;
7060         int ret;
7061
7062         if (async_submit)
7063                 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7064
7065         bio_get(bio);
7066
7067         if (!write) {
7068                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7069                 if (ret)
7070                         goto err;
7071         }
7072
7073         if (skip_sum)
7074                 goto map;
7075
7076         if (write && async_submit) {
7077                 ret = btrfs_wq_submit_bio(root->fs_info,
7078                                    inode, rw, bio, 0, 0,
7079                                    file_offset,
7080                                    __btrfs_submit_bio_start_direct_io,
7081                                    __btrfs_submit_bio_done);
7082                 goto err;
7083         } else if (write) {
7084                 /*
7085                  * If we aren't doing async submit, calculate the csum of the
7086                  * bio now.
7087                  */
7088                 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7089                 if (ret)
7090                         goto err;
7091         } else if (!skip_sum) {
7092                 ret = btrfs_lookup_bio_sums_dio(root, inode, dip, bio,
7093                                                 file_offset);
7094                 if (ret)
7095                         goto err;
7096         }
7097
7098 map:
7099         ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7100 err:
7101         bio_put(bio);
7102         return ret;
7103 }
7104
7105 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7106                                     int skip_sum)
7107 {
7108         struct inode *inode = dip->inode;
7109         struct btrfs_root *root = BTRFS_I(inode)->root;
7110         struct bio *bio;
7111         struct bio *orig_bio = dip->orig_bio;
7112         struct bio_vec *bvec = orig_bio->bi_io_vec;
7113         u64 start_sector = orig_bio->bi_sector;
7114         u64 file_offset = dip->logical_offset;
7115         u64 submit_len = 0;
7116         u64 map_length;
7117         int nr_pages = 0;
7118         int ret = 0;
7119         int async_submit = 0;
7120
7121         map_length = orig_bio->bi_size;
7122         ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7123                               &map_length, NULL, 0);
7124         if (ret) {
7125                 bio_put(orig_bio);
7126                 return -EIO;
7127         }
7128
7129         if (map_length >= orig_bio->bi_size) {
7130                 bio = orig_bio;
7131                 goto submit;
7132         }
7133
7134         /* async crcs make it difficult to collect full stripe writes. */
7135         if (btrfs_get_alloc_profile(root, 1) &
7136             (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7137                 async_submit = 0;
7138         else
7139                 async_submit = 1;
7140
7141         bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7142         if (!bio)
7143                 return -ENOMEM;
7144         bio->bi_private = dip;
7145         bio->bi_end_io = btrfs_end_dio_bio;
7146         atomic_inc(&dip->pending_bios);
7147
7148         while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7149                 if (unlikely(map_length < submit_len + bvec->bv_len ||
7150                     bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7151                                  bvec->bv_offset) < bvec->bv_len)) {
7152                         /*
7153                          * inc the count before we submit the bio so
7154                          * we know the end IO handler won't happen before
7155                          * we inc the count. Otherwise, the dip might get freed
7156                          * before we're done setting it up
7157                          */
7158                         atomic_inc(&dip->pending_bios);
7159                         ret = __btrfs_submit_dio_bio(bio, inode, rw,
7160                                                      file_offset, skip_sum,
7161                                                      async_submit);
7162                         if (ret) {
7163                                 bio_put(bio);
7164                                 atomic_dec(&dip->pending_bios);
7165                                 goto out_err;
7166                         }
7167
7168                         start_sector += submit_len >> 9;
7169                         file_offset += submit_len;
7170
7171                         submit_len = 0;
7172                         nr_pages = 0;
7173
7174                         bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7175                                                   start_sector, GFP_NOFS);
7176                         if (!bio)
7177                                 goto out_err;
7178                         bio->bi_private = dip;
7179                         bio->bi_end_io = btrfs_end_dio_bio;
7180
7181                         map_length = orig_bio->bi_size;
7182                         ret = btrfs_map_block(root->fs_info, rw,
7183                                               start_sector << 9,
7184                                               &map_length, NULL, 0);
7185                         if (ret) {
7186                                 bio_put(bio);
7187                                 goto out_err;
7188                         }
7189                 } else {
7190                         submit_len += bvec->bv_len;
7191                         nr_pages++;
7192                         bvec++;
7193                 }
7194         }
7195
7196 submit:
7197         ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7198                                      async_submit);
7199         if (!ret)
7200                 return 0;
7201
7202         bio_put(bio);
7203 out_err:
7204         dip->errors = 1;
7205         /*
7206          * before atomic variable goto zero, we must
7207          * make sure dip->errors is perceived to be set.
7208          */
7209         smp_mb__before_atomic_dec();
7210         if (atomic_dec_and_test(&dip->pending_bios))
7211                 bio_io_error(dip->orig_bio);
7212
7213         /* bio_end_io() will handle error, so we needn't return it */
7214         return 0;
7215 }
7216
7217 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7218                                 struct inode *inode, loff_t file_offset)
7219 {
7220         struct btrfs_root *root = BTRFS_I(inode)->root;
7221         struct btrfs_dio_private *dip;
7222         struct bio *io_bio;
7223         int skip_sum;
7224         int sum_len;
7225         int write = rw & REQ_WRITE;
7226         int ret = 0;
7227         u16 csum_size;
7228
7229         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7230
7231         io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7232         if (!io_bio) {
7233                 ret = -ENOMEM;
7234                 goto free_ordered;
7235         }
7236
7237         if (!skip_sum && !write) {
7238                 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
7239                 sum_len = dio_bio->bi_size >> inode->i_sb->s_blocksize_bits;
7240                 sum_len *= csum_size;
7241         } else {
7242                 sum_len = 0;
7243         }
7244
7245         dip = kmalloc(sizeof(*dip) + sum_len, GFP_NOFS);
7246         if (!dip) {
7247                 ret = -ENOMEM;
7248                 goto free_io_bio;
7249         }
7250
7251         dip->private = dio_bio->bi_private;
7252         dip->inode = inode;
7253         dip->logical_offset = file_offset;
7254         dip->bytes = dio_bio->bi_size;
7255         dip->disk_bytenr = (u64)dio_bio->bi_sector << 9;
7256         io_bio->bi_private = dip;
7257         dip->errors = 0;
7258         dip->orig_bio = io_bio;
7259         dip->dio_bio = dio_bio;
7260         atomic_set(&dip->pending_bios, 0);
7261
7262         if (write)
7263                 io_bio->bi_end_io = btrfs_endio_direct_write;
7264         else
7265                 io_bio->bi_end_io = btrfs_endio_direct_read;
7266
7267         ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7268         if (!ret)
7269                 return;
7270
7271 free_io_bio:
7272         bio_put(io_bio);
7273
7274 free_ordered:
7275         /*
7276          * If this is a write, we need to clean up the reserved space and kill
7277          * the ordered extent.
7278          */
7279         if (write) {
7280                 struct btrfs_ordered_extent *ordered;
7281                 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7282                 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7283                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7284                         btrfs_free_reserved_extent(root, ordered->start,
7285                                                    ordered->disk_len);
7286                 btrfs_put_ordered_extent(ordered);
7287                 btrfs_put_ordered_extent(ordered);
7288         }
7289         bio_endio(dio_bio, ret);
7290 }
7291
7292 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7293                         const struct iovec *iov, loff_t offset,
7294                         unsigned long nr_segs)
7295 {
7296         int seg;
7297         int i;
7298         size_t size;
7299         unsigned long addr;
7300         unsigned blocksize_mask = root->sectorsize - 1;
7301         ssize_t retval = -EINVAL;
7302         loff_t end = offset;
7303
7304         if (offset & blocksize_mask)
7305                 goto out;
7306
7307         /* Check the memory alignment.  Blocks cannot straddle pages */
7308         for (seg = 0; seg < nr_segs; seg++) {
7309                 addr = (unsigned long)iov[seg].iov_base;
7310                 size = iov[seg].iov_len;
7311                 end += size;
7312                 if ((addr & blocksize_mask) || (size & blocksize_mask))
7313                         goto out;
7314
7315                 /* If this is a write we don't need to check anymore */
7316                 if (rw & WRITE)
7317                         continue;
7318
7319                 /*
7320                  * Check to make sure we don't have duplicate iov_base's in this
7321                  * iovec, if so return EINVAL, otherwise we'll get csum errors
7322                  * when reading back.
7323                  */
7324                 for (i = seg + 1; i < nr_segs; i++) {
7325                         if (iov[seg].iov_base == iov[i].iov_base)
7326                                 goto out;
7327                 }
7328         }
7329         retval = 0;
7330 out:
7331         return retval;
7332 }
7333
7334 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7335                         const struct iovec *iov, loff_t offset,
7336                         unsigned long nr_segs)
7337 {
7338         struct file *file = iocb->ki_filp;
7339         struct inode *inode = file->f_mapping->host;
7340         size_t count = 0;
7341         int flags = 0;
7342         bool wakeup = true;
7343         bool relock = false;
7344         ssize_t ret;
7345
7346         if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7347                             offset, nr_segs))
7348                 return 0;
7349
7350         atomic_inc(&inode->i_dio_count);
7351         smp_mb__after_atomic_inc();
7352
7353         /*
7354          * The generic stuff only does filemap_write_and_wait_range, which isn't
7355          * enough if we've written compressed pages to this area, so we need to
7356          * call btrfs_wait_ordered_range to make absolutely sure that any
7357          * outstanding dirty pages are on disk.
7358          */
7359         count = iov_length(iov, nr_segs);
7360         ret = btrfs_wait_ordered_range(inode, offset, count);
7361         if (ret)
7362                 return ret;
7363
7364         if (rw & WRITE) {
7365                 /*
7366                  * If the write DIO is beyond the EOF, we need update
7367                  * the isize, but it is protected by i_mutex. So we can
7368                  * not unlock the i_mutex at this case.
7369                  */
7370                 if (offset + count <= inode->i_size) {
7371                         mutex_unlock(&inode->i_mutex);
7372                         relock = true;
7373                 }
7374                 ret = btrfs_delalloc_reserve_space(inode, count);
7375                 if (ret)
7376                         goto out;
7377         } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7378                                      &BTRFS_I(inode)->runtime_flags))) {
7379                 inode_dio_done(inode);
7380                 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7381                 wakeup = false;
7382         }
7383
7384         ret = __blockdev_direct_IO(rw, iocb, inode,
7385                         BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7386                         iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7387                         btrfs_submit_direct, flags);
7388         if (rw & WRITE) {
7389                 if (ret < 0 && ret != -EIOCBQUEUED)
7390                         btrfs_delalloc_release_space(inode, count);
7391                 else if (ret >= 0 && (size_t)ret < count)
7392                         btrfs_delalloc_release_space(inode,
7393                                                      count - (size_t)ret);
7394                 else
7395                         btrfs_delalloc_release_metadata(inode, 0);
7396         }
7397 out:
7398         if (wakeup)
7399                 inode_dio_done(inode);
7400         if (relock)
7401                 mutex_lock(&inode->i_mutex);
7402
7403         return ret;
7404 }
7405
7406 #define BTRFS_FIEMAP_FLAGS      (FIEMAP_FLAG_SYNC)
7407
7408 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7409                 __u64 start, __u64 len)
7410 {
7411         int     ret;
7412
7413         ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7414         if (ret)
7415                 return ret;
7416
7417         return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7418 }
7419
7420 int btrfs_readpage(struct file *file, struct page *page)
7421 {
7422         struct extent_io_tree *tree;
7423         tree = &BTRFS_I(page->mapping->host)->io_tree;
7424         return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7425 }
7426
7427 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7428 {
7429         struct extent_io_tree *tree;
7430
7431
7432         if (current->flags & PF_MEMALLOC) {
7433                 redirty_page_for_writepage(wbc, page);
7434                 unlock_page(page);
7435                 return 0;
7436         }
7437         tree = &BTRFS_I(page->mapping->host)->io_tree;
7438         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7439 }
7440
7441 static int btrfs_writepages(struct address_space *mapping,
7442                             struct writeback_control *wbc)
7443 {
7444         struct extent_io_tree *tree;
7445
7446         tree = &BTRFS_I(mapping->host)->io_tree;
7447         return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7448 }
7449
7450 static int
7451 btrfs_readpages(struct file *file, struct address_space *mapping,
7452                 struct list_head *pages, unsigned nr_pages)
7453 {
7454         struct extent_io_tree *tree;
7455         tree = &BTRFS_I(mapping->host)->io_tree;
7456         return extent_readpages(tree, mapping, pages, nr_pages,
7457                                 btrfs_get_extent);
7458 }
7459 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7460 {
7461         struct extent_io_tree *tree;
7462         struct extent_map_tree *map;
7463         int ret;
7464
7465         tree = &BTRFS_I(page->mapping->host)->io_tree;
7466         map = &BTRFS_I(page->mapping->host)->extent_tree;
7467         ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7468         if (ret == 1) {
7469                 ClearPagePrivate(page);
7470                 set_page_private(page, 0);
7471                 page_cache_release(page);
7472         }
7473         return ret;
7474 }
7475
7476 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7477 {
7478         if (PageWriteback(page) || PageDirty(page))
7479                 return 0;
7480         return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7481 }
7482
7483 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7484                                  unsigned int length)
7485 {
7486         struct inode *inode = page->mapping->host;
7487         struct extent_io_tree *tree;
7488         struct btrfs_ordered_extent *ordered;
7489         struct extent_state *cached_state = NULL;
7490         u64 page_start = page_offset(page);
7491         u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7492         int inode_evicting = inode->i_state & I_FREEING;
7493
7494         /*
7495          * we have the page locked, so new writeback can't start,
7496          * and the dirty bit won't be cleared while we are here.
7497          *
7498          * Wait for IO on this page so that we can safely clear
7499          * the PagePrivate2 bit and do ordered accounting
7500          */
7501         wait_on_page_writeback(page);
7502
7503         tree = &BTRFS_I(inode)->io_tree;
7504         if (offset) {
7505                 btrfs_releasepage(page, GFP_NOFS);
7506                 return;
7507         }
7508
7509         if (!inode_evicting)
7510                 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7511         ordered = btrfs_lookup_ordered_extent(inode, page_start);
7512         if (ordered) {
7513                 /*
7514                  * IO on this page will never be started, so we need
7515                  * to account for any ordered extents now
7516                  */
7517                 if (!inode_evicting)
7518                         clear_extent_bit(tree, page_start, page_end,
7519                                          EXTENT_DIRTY | EXTENT_DELALLOC |
7520                                          EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7521                                          EXTENT_DEFRAG, 1, 0, &cached_state,
7522                                          GFP_NOFS);
7523                 /*
7524                  * whoever cleared the private bit is responsible
7525                  * for the finish_ordered_io
7526                  */
7527                 if (TestClearPagePrivate2(page)) {
7528                         struct btrfs_ordered_inode_tree *tree;
7529                         u64 new_len;
7530
7531                         tree = &BTRFS_I(inode)->ordered_tree;
7532
7533                         spin_lock_irq(&tree->lock);
7534                         set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
7535                         new_len = page_start - ordered->file_offset;
7536                         if (new_len < ordered->truncated_len)
7537                                 ordered->truncated_len = new_len;
7538                         spin_unlock_irq(&tree->lock);
7539
7540                         if (btrfs_dec_test_ordered_pending(inode, &ordered,
7541                                                            page_start,
7542                                                            PAGE_CACHE_SIZE, 1))
7543                                 btrfs_finish_ordered_io(ordered);
7544                 }
7545                 btrfs_put_ordered_extent(ordered);
7546                 if (!inode_evicting) {
7547                         cached_state = NULL;
7548                         lock_extent_bits(tree, page_start, page_end, 0,
7549                                          &cached_state);
7550                 }
7551         }
7552
7553         if (!inode_evicting) {
7554                 clear_extent_bit(tree, page_start, page_end,
7555                                  EXTENT_LOCKED | EXTENT_DIRTY |
7556                                  EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
7557                                  EXTENT_DEFRAG, 1, 1,
7558                                  &cached_state, GFP_NOFS);
7559
7560                 __btrfs_releasepage(page, GFP_NOFS);
7561         }
7562
7563         ClearPageChecked(page);
7564         if (PagePrivate(page)) {
7565                 ClearPagePrivate(page);
7566                 set_page_private(page, 0);
7567                 page_cache_release(page);
7568         }
7569 }
7570
7571 /*
7572  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7573  * called from a page fault handler when a page is first dirtied. Hence we must
7574  * be careful to check for EOF conditions here. We set the page up correctly
7575  * for a written page which means we get ENOSPC checking when writing into
7576  * holes and correct delalloc and unwritten extent mapping on filesystems that
7577  * support these features.
7578  *
7579  * We are not allowed to take the i_mutex here so we have to play games to
7580  * protect against truncate races as the page could now be beyond EOF.  Because
7581  * vmtruncate() writes the inode size before removing pages, once we have the
7582  * page lock we can determine safely if the page is beyond EOF. If it is not
7583  * beyond EOF, then the page is guaranteed safe against truncation until we
7584  * unlock the page.
7585  */
7586 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7587 {
7588         struct page *page = vmf->page;
7589         struct inode *inode = file_inode(vma->vm_file);
7590         struct btrfs_root *root = BTRFS_I(inode)->root;
7591         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7592         struct btrfs_ordered_extent *ordered;
7593         struct extent_state *cached_state = NULL;
7594         char *kaddr;
7595         unsigned long zero_start;
7596         loff_t size;
7597         int ret;
7598         int reserved = 0;
7599         u64 page_start;
7600         u64 page_end;
7601
7602         sb_start_pagefault(inode->i_sb);
7603         ret  = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7604         if (!ret) {
7605                 ret = file_update_time(vma->vm_file);
7606                 reserved = 1;
7607         }
7608         if (ret) {
7609                 if (ret == -ENOMEM)
7610                         ret = VM_FAULT_OOM;
7611                 else /* -ENOSPC, -EIO, etc */
7612                         ret = VM_FAULT_SIGBUS;
7613                 if (reserved)
7614                         goto out;
7615                 goto out_noreserve;
7616         }
7617
7618         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7619 again:
7620         lock_page(page);
7621         size = i_size_read(inode);
7622         page_start = page_offset(page);
7623         page_end = page_start + PAGE_CACHE_SIZE - 1;
7624
7625         if ((page->mapping != inode->i_mapping) ||
7626             (page_start >= size)) {
7627                 /* page got truncated out from underneath us */
7628                 goto out_unlock;
7629         }
7630         wait_on_page_writeback(page);
7631
7632         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7633         set_page_extent_mapped(page);
7634
7635         /*
7636          * we can't set the delalloc bits if there are pending ordered
7637          * extents.  Drop our locks and wait for them to finish
7638          */
7639         ordered = btrfs_lookup_ordered_extent(inode, page_start);
7640         if (ordered) {
7641                 unlock_extent_cached(io_tree, page_start, page_end,
7642                                      &cached_state, GFP_NOFS);
7643                 unlock_page(page);
7644                 btrfs_start_ordered_extent(inode, ordered, 1);
7645                 btrfs_put_ordered_extent(ordered);
7646                 goto again;
7647         }
7648
7649         /*
7650          * XXX - page_mkwrite gets called every time the page is dirtied, even
7651          * if it was already dirty, so for space accounting reasons we need to
7652          * clear any delalloc bits for the range we are fixing to save.  There
7653          * is probably a better way to do this, but for now keep consistent with
7654          * prepare_pages in the normal write path.
7655          */
7656         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7657                           EXTENT_DIRTY | EXTENT_DELALLOC |
7658                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7659                           0, 0, &cached_state, GFP_NOFS);
7660
7661         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7662                                         &cached_state);
7663         if (ret) {
7664                 unlock_extent_cached(io_tree, page_start, page_end,
7665                                      &cached_state, GFP_NOFS);
7666                 ret = VM_FAULT_SIGBUS;
7667                 goto out_unlock;
7668         }
7669         ret = 0;
7670
7671         /* page is wholly or partially inside EOF */
7672         if (page_start + PAGE_CACHE_SIZE > size)
7673                 zero_start = size & ~PAGE_CACHE_MASK;
7674         else
7675                 zero_start = PAGE_CACHE_SIZE;
7676
7677         if (zero_start != PAGE_CACHE_SIZE) {
7678                 kaddr = kmap(page);
7679                 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7680                 flush_dcache_page(page);
7681                 kunmap(page);
7682         }
7683         ClearPageChecked(page);
7684         set_page_dirty(page);
7685         SetPageUptodate(page);
7686
7687         BTRFS_I(inode)->last_trans = root->fs_info->generation;
7688         BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7689         BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7690
7691         unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7692
7693 out_unlock:
7694         if (!ret) {
7695                 sb_end_pagefault(inode->i_sb);
7696                 return VM_FAULT_LOCKED;
7697         }
7698         unlock_page(page);
7699 out:
7700         btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7701 out_noreserve:
7702         sb_end_pagefault(inode->i_sb);
7703         return ret;
7704 }
7705
7706 static int btrfs_truncate(struct inode *inode)
7707 {
7708         struct btrfs_root *root = BTRFS_I(inode)->root;
7709         struct btrfs_block_rsv *rsv;
7710         int ret = 0;
7711         int err = 0;
7712         struct btrfs_trans_handle *trans;
7713         u64 mask = root->sectorsize - 1;
7714         u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7715
7716         ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
7717                                        (u64)-1);
7718         if (ret)
7719                 return ret;
7720
7721         /*
7722          * Yes ladies and gentelment, this is indeed ugly.  The fact is we have
7723          * 3 things going on here
7724          *
7725          * 1) We need to reserve space for our orphan item and the space to
7726          * delete our orphan item.  Lord knows we don't want to have a dangling
7727          * orphan item because we didn't reserve space to remove it.
7728          *
7729          * 2) We need to reserve space to update our inode.
7730          *
7731          * 3) We need to have something to cache all the space that is going to
7732          * be free'd up by the truncate operation, but also have some slack
7733          * space reserved in case it uses space during the truncate (thank you
7734          * very much snapshotting).
7735          *
7736          * And we need these to all be seperate.  The fact is we can use alot of
7737          * space doing the truncate, and we have no earthly idea how much space
7738          * we will use, so we need the truncate reservation to be seperate so it
7739          * doesn't end up using space reserved for updating the inode or
7740          * removing the orphan item.  We also need to be able to stop the
7741          * transaction and start a new one, which means we need to be able to
7742          * update the inode several times, and we have no idea of knowing how
7743          * many times that will be, so we can't just reserve 1 item for the
7744          * entirety of the opration, so that has to be done seperately as well.
7745          * Then there is the orphan item, which does indeed need to be held on
7746          * to for the whole operation, and we need nobody to touch this reserved
7747          * space except the orphan code.
7748          *
7749          * So that leaves us with
7750          *
7751          * 1) root->orphan_block_rsv - for the orphan deletion.
7752          * 2) rsv - for the truncate reservation, which we will steal from the
7753          * transaction reservation.
7754          * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7755          * updating the inode.
7756          */
7757         rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7758         if (!rsv)
7759                 return -ENOMEM;
7760         rsv->size = min_size;
7761         rsv->failfast = 1;
7762
7763         /*
7764          * 1 for the truncate slack space
7765          * 1 for updating the inode.
7766          */
7767         trans = btrfs_start_transaction(root, 2);
7768         if (IS_ERR(trans)) {
7769                 err = PTR_ERR(trans);
7770                 goto out;
7771         }
7772
7773         /* Migrate the slack space for the truncate to our reserve */
7774         ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7775                                       min_size);
7776         BUG_ON(ret);
7777
7778         /*
7779          * setattr is responsible for setting the ordered_data_close flag,
7780          * but that is only tested during the last file release.  That
7781          * could happen well after the next commit, leaving a great big
7782          * window where new writes may get lost if someone chooses to write
7783          * to this file after truncating to zero
7784          *
7785          * The inode doesn't have any dirty data here, and so if we commit
7786          * this is a noop.  If someone immediately starts writing to the inode
7787          * it is very likely we'll catch some of their writes in this
7788          * transaction, and the commit will find this file on the ordered
7789          * data list with good things to send down.
7790          *
7791          * This is a best effort solution, there is still a window where
7792          * using truncate to replace the contents of the file will
7793          * end up with a zero length file after a crash.
7794          */
7795         if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7796                                            &BTRFS_I(inode)->runtime_flags))
7797                 btrfs_add_ordered_operation(trans, root, inode);
7798
7799         /*
7800          * So if we truncate and then write and fsync we normally would just
7801          * write the extents that changed, which is a problem if we need to
7802          * first truncate that entire inode.  So set this flag so we write out
7803          * all of the extents in the inode to the sync log so we're completely
7804          * safe.
7805          */
7806         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7807         trans->block_rsv = rsv;
7808
7809         while (1) {
7810                 ret = btrfs_truncate_inode_items(trans, root, inode,
7811                                                  inode->i_size,
7812                                                  BTRFS_EXTENT_DATA_KEY);
7813                 if (ret != -ENOSPC) {
7814                         err = ret;
7815                         break;
7816                 }
7817
7818                 trans->block_rsv = &root->fs_info->trans_block_rsv;
7819                 ret = btrfs_update_inode(trans, root, inode);
7820                 if (ret) {
7821                         err = ret;
7822                         break;
7823                 }
7824
7825                 btrfs_end_transaction(trans, root);
7826                 btrfs_btree_balance_dirty(root);
7827
7828                 trans = btrfs_start_transaction(root, 2);
7829                 if (IS_ERR(trans)) {
7830                         ret = err = PTR_ERR(trans);
7831                         trans = NULL;
7832                         break;
7833                 }
7834
7835                 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7836                                               rsv, min_size);
7837                 BUG_ON(ret);    /* shouldn't happen */
7838                 trans->block_rsv = rsv;
7839         }
7840
7841         if (ret == 0 && inode->i_nlink > 0) {
7842                 trans->block_rsv = root->orphan_block_rsv;
7843                 ret = btrfs_orphan_del(trans, inode);
7844                 if (ret)
7845                         err = ret;
7846         }
7847
7848         if (trans) {
7849                 trans->block_rsv = &root->fs_info->trans_block_rsv;
7850                 ret = btrfs_update_inode(trans, root, inode);
7851                 if (ret && !err)
7852                         err = ret;
7853
7854                 ret = btrfs_end_transaction(trans, root);
7855                 btrfs_btree_balance_dirty(root);
7856         }
7857
7858 out:
7859         btrfs_free_block_rsv(root, rsv);
7860
7861         if (ret && !err)
7862                 err = ret;
7863
7864         return err;
7865 }
7866
7867 /*
7868  * create a new subvolume directory/inode (helper for the ioctl).
7869  */
7870 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7871                              struct btrfs_root *new_root, u64 new_dirid)
7872 {
7873         struct inode *inode;
7874         int err;
7875         u64 index = 0;
7876
7877         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7878                                 new_dirid, new_dirid,
7879                                 S_IFDIR | (~current_umask() & S_IRWXUGO),
7880                                 &index);
7881         if (IS_ERR(inode))
7882                 return PTR_ERR(inode);
7883         inode->i_op = &btrfs_dir_inode_operations;
7884         inode->i_fop = &btrfs_dir_file_operations;
7885
7886         set_nlink(inode, 1);
7887         btrfs_i_size_write(inode, 0);
7888
7889         err = btrfs_update_inode(trans, new_root, inode);
7890
7891         iput(inode);
7892         return err;
7893 }
7894
7895 struct inode *btrfs_alloc_inode(struct super_block *sb)
7896 {
7897         struct btrfs_inode *ei;
7898         struct inode *inode;
7899
7900         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7901         if (!ei)
7902                 return NULL;
7903
7904         ei->root = NULL;
7905         ei->generation = 0;
7906         ei->last_trans = 0;
7907         ei->last_sub_trans = 0;
7908         ei->logged_trans = 0;
7909         ei->delalloc_bytes = 0;
7910         ei->disk_i_size = 0;
7911         ei->flags = 0;
7912         ei->csum_bytes = 0;
7913         ei->index_cnt = (u64)-1;
7914         ei->dir_index = 0;
7915         ei->last_unlink_trans = 0;
7916         ei->last_log_commit = 0;
7917
7918         spin_lock_init(&ei->lock);
7919         ei->outstanding_extents = 0;
7920         ei->reserved_extents = 0;
7921
7922         ei->runtime_flags = 0;
7923         ei->force_compress = BTRFS_COMPRESS_NONE;
7924
7925         ei->delayed_node = NULL;
7926
7927         inode = &ei->vfs_inode;
7928         extent_map_tree_init(&ei->extent_tree);
7929         extent_io_tree_init(&ei->io_tree, &inode->i_data);
7930         extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7931         ei->io_tree.track_uptodate = 1;
7932         ei->io_failure_tree.track_uptodate = 1;
7933         atomic_set(&ei->sync_writers, 0);
7934         mutex_init(&ei->log_mutex);
7935         mutex_init(&ei->delalloc_mutex);
7936         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7937         INIT_LIST_HEAD(&ei->delalloc_inodes);
7938         INIT_LIST_HEAD(&ei->ordered_operations);
7939         RB_CLEAR_NODE(&ei->rb_node);
7940
7941         return inode;
7942 }
7943
7944 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
7945 void btrfs_test_destroy_inode(struct inode *inode)
7946 {
7947         btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7948         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7949 }
7950 #endif
7951
7952 static void btrfs_i_callback(struct rcu_head *head)
7953 {
7954         struct inode *inode = container_of(head, struct inode, i_rcu);
7955         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7956 }
7957
7958 void btrfs_destroy_inode(struct inode *inode)
7959 {
7960         struct btrfs_ordered_extent *ordered;
7961         struct btrfs_root *root = BTRFS_I(inode)->root;
7962
7963         WARN_ON(!hlist_empty(&inode->i_dentry));
7964         WARN_ON(inode->i_data.nrpages);
7965         WARN_ON(BTRFS_I(inode)->outstanding_extents);
7966         WARN_ON(BTRFS_I(inode)->reserved_extents);
7967         WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7968         WARN_ON(BTRFS_I(inode)->csum_bytes);
7969
7970         /*
7971          * This can happen where we create an inode, but somebody else also
7972          * created the same inode and we need to destroy the one we already
7973          * created.
7974          */
7975         if (!root)
7976                 goto free;
7977
7978         /*
7979          * Make sure we're properly removed from the ordered operation
7980          * lists.
7981          */
7982         smp_mb();
7983         if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7984                 spin_lock(&root->fs_info->ordered_root_lock);
7985                 list_del_init(&BTRFS_I(inode)->ordered_operations);
7986                 spin_unlock(&root->fs_info->ordered_root_lock);
7987         }
7988
7989         if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7990                      &BTRFS_I(inode)->runtime_flags)) {
7991                 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
7992                         btrfs_ino(inode));
7993                 atomic_dec(&root->orphan_inodes);
7994         }
7995
7996         while (1) {
7997                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7998                 if (!ordered)
7999                         break;
8000                 else {
8001                         btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8002                                 ordered->file_offset, ordered->len);
8003                         btrfs_remove_ordered_extent(inode, ordered);
8004                         btrfs_put_ordered_extent(ordered);
8005                         btrfs_put_ordered_extent(ordered);
8006                 }
8007         }
8008         inode_tree_del(inode);
8009         btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8010 free:
8011         call_rcu(&inode->i_rcu, btrfs_i_callback);
8012 }
8013
8014 int btrfs_drop_inode(struct inode *inode)
8015 {
8016         struct btrfs_root *root = BTRFS_I(inode)->root;
8017
8018         if (root == NULL)
8019                 return 1;
8020
8021         /* the snap/subvol tree is on deleting */
8022         if (btrfs_root_refs(&root->root_item) == 0)
8023                 return 1;
8024         else
8025                 return generic_drop_inode(inode);
8026 }
8027
8028 static void init_once(void *foo)
8029 {
8030         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8031
8032         inode_init_once(&ei->vfs_inode);
8033 }
8034
8035 void btrfs_destroy_cachep(void)
8036 {
8037         /*
8038          * Make sure all delayed rcu free inodes are flushed before we
8039          * destroy cache.
8040          */
8041         rcu_barrier();
8042         if (btrfs_inode_cachep)
8043                 kmem_cache_destroy(btrfs_inode_cachep);
8044         if (btrfs_trans_handle_cachep)
8045                 kmem_cache_destroy(btrfs_trans_handle_cachep);
8046         if (btrfs_transaction_cachep)
8047                 kmem_cache_destroy(btrfs_transaction_cachep);
8048         if (btrfs_path_cachep)
8049                 kmem_cache_destroy(btrfs_path_cachep);
8050         if (btrfs_free_space_cachep)
8051                 kmem_cache_destroy(btrfs_free_space_cachep);
8052         if (btrfs_delalloc_work_cachep)
8053                 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8054 }
8055
8056 int btrfs_init_cachep(void)
8057 {
8058         btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8059                         sizeof(struct btrfs_inode), 0,
8060                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8061         if (!btrfs_inode_cachep)
8062                 goto fail;
8063
8064         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8065                         sizeof(struct btrfs_trans_handle), 0,
8066                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8067         if (!btrfs_trans_handle_cachep)
8068                 goto fail;
8069
8070         btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8071                         sizeof(struct btrfs_transaction), 0,
8072                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8073         if (!btrfs_transaction_cachep)
8074                 goto fail;
8075
8076         btrfs_path_cachep = kmem_cache_create("btrfs_path",
8077                         sizeof(struct btrfs_path), 0,
8078                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8079         if (!btrfs_path_cachep)
8080                 goto fail;
8081
8082         btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8083                         sizeof(struct btrfs_free_space), 0,
8084                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8085         if (!btrfs_free_space_cachep)
8086                 goto fail;
8087
8088         btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8089                         sizeof(struct btrfs_delalloc_work), 0,
8090                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8091                         NULL);
8092         if (!btrfs_delalloc_work_cachep)
8093                 goto fail;
8094
8095         return 0;
8096 fail:
8097         btrfs_destroy_cachep();
8098         return -ENOMEM;
8099 }
8100
8101 static int btrfs_getattr(struct vfsmount *mnt,
8102                          struct dentry *dentry, struct kstat *stat)
8103 {
8104         u64 delalloc_bytes;
8105         struct inode *inode = dentry->d_inode;
8106         u32 blocksize = inode->i_sb->s_blocksize;
8107
8108         generic_fillattr(inode, stat);
8109         stat->dev = BTRFS_I(inode)->root->anon_dev;
8110         stat->blksize = PAGE_CACHE_SIZE;
8111
8112         spin_lock(&BTRFS_I(inode)->lock);
8113         delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8114         spin_unlock(&BTRFS_I(inode)->lock);
8115         stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8116                         ALIGN(delalloc_bytes, blocksize)) >> 9;
8117         return 0;
8118 }
8119
8120 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8121                            struct inode *new_dir, struct dentry *new_dentry)
8122 {
8123         struct btrfs_trans_handle *trans;
8124         struct btrfs_root *root = BTRFS_I(old_dir)->root;
8125         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8126         struct inode *new_inode = new_dentry->d_inode;
8127         struct inode *old_inode = old_dentry->d_inode;
8128         struct timespec ctime = CURRENT_TIME;
8129         u64 index = 0;
8130         u64 root_objectid;
8131         int ret;
8132         u64 old_ino = btrfs_ino(old_inode);
8133
8134         if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8135                 return -EPERM;
8136
8137         /* we only allow rename subvolume link between subvolumes */
8138         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8139                 return -EXDEV;
8140
8141         if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8142             (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8143                 return -ENOTEMPTY;
8144
8145         if (S_ISDIR(old_inode->i_mode) && new_inode &&
8146             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8147                 return -ENOTEMPTY;
8148
8149
8150         /* check for collisions, even if the  name isn't there */
8151         ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8152                              new_dentry->d_name.name,
8153                              new_dentry->d_name.len);
8154
8155         if (ret) {
8156                 if (ret == -EEXIST) {
8157                         /* we shouldn't get
8158                          * eexist without a new_inode */
8159                         if (WARN_ON(!new_inode)) {
8160                                 return ret;
8161                         }
8162                 } else {
8163                         /* maybe -EOVERFLOW */
8164                         return ret;
8165                 }
8166         }
8167         ret = 0;
8168
8169         /*
8170          * we're using rename to replace one file with another.
8171          * and the replacement file is large.  Start IO on it now so
8172          * we don't add too much work to the end of the transaction
8173          */
8174         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8175             old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8176                 filemap_flush(old_inode->i_mapping);
8177
8178         /* close the racy window with snapshot create/destroy ioctl */
8179         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8180                 down_read(&root->fs_info->subvol_sem);
8181         /*
8182          * We want to reserve the absolute worst case amount of items.  So if
8183          * both inodes are subvols and we need to unlink them then that would
8184          * require 4 item modifications, but if they are both normal inodes it
8185          * would require 5 item modifications, so we'll assume their normal
8186          * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8187          * should cover the worst case number of items we'll modify.
8188          */
8189         trans = btrfs_start_transaction(root, 11);
8190         if (IS_ERR(trans)) {
8191                 ret = PTR_ERR(trans);
8192                 goto out_notrans;
8193         }
8194
8195         if (dest != root)
8196                 btrfs_record_root_in_trans(trans, dest);
8197
8198         ret = btrfs_set_inode_index(new_dir, &index);
8199         if (ret)
8200                 goto out_fail;
8201
8202         BTRFS_I(old_inode)->dir_index = 0ULL;
8203         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8204                 /* force full log commit if subvolume involved. */
8205                 root->fs_info->last_trans_log_full_commit = trans->transid;
8206         } else {
8207                 ret = btrfs_insert_inode_ref(trans, dest,
8208                                              new_dentry->d_name.name,
8209                                              new_dentry->d_name.len,
8210                                              old_ino,
8211                                              btrfs_ino(new_dir), index);
8212                 if (ret)
8213                         goto out_fail;
8214                 /*
8215                  * this is an ugly little race, but the rename is required
8216                  * to make sure that if we crash, the inode is either at the
8217                  * old name or the new one.  pinning the log transaction lets
8218                  * us make sure we don't allow a log commit to come in after
8219                  * we unlink the name but before we add the new name back in.
8220                  */
8221                 btrfs_pin_log_trans(root);
8222         }
8223         /*
8224          * make sure the inode gets flushed if it is replacing
8225          * something.
8226          */
8227         if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8228                 btrfs_add_ordered_operation(trans, root, old_inode);
8229
8230         inode_inc_iversion(old_dir);
8231         inode_inc_iversion(new_dir);
8232         inode_inc_iversion(old_inode);
8233         old_dir->i_ctime = old_dir->i_mtime = ctime;
8234         new_dir->i_ctime = new_dir->i_mtime = ctime;
8235         old_inode->i_ctime = ctime;
8236
8237         if (old_dentry->d_parent != new_dentry->d_parent)
8238                 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8239
8240         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8241                 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8242                 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8243                                         old_dentry->d_name.name,
8244                                         old_dentry->d_name.len);
8245         } else {
8246                 ret = __btrfs_unlink_inode(trans, root, old_dir,
8247                                         old_dentry->d_inode,
8248                                         old_dentry->d_name.name,
8249                                         old_dentry->d_name.len);
8250                 if (!ret)
8251                         ret = btrfs_update_inode(trans, root, old_inode);
8252         }
8253         if (ret) {
8254                 btrfs_abort_transaction(trans, root, ret);
8255                 goto out_fail;
8256         }
8257
8258         if (new_inode) {
8259                 inode_inc_iversion(new_inode);
8260                 new_inode->i_ctime = CURRENT_TIME;
8261                 if (unlikely(btrfs_ino(new_inode) ==
8262                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8263                         root_objectid = BTRFS_I(new_inode)->location.objectid;
8264                         ret = btrfs_unlink_subvol(trans, dest, new_dir,
8265                                                 root_objectid,
8266                                                 new_dentry->d_name.name,
8267                                                 new_dentry->d_name.len);
8268                         BUG_ON(new_inode->i_nlink == 0);
8269                 } else {
8270                         ret = btrfs_unlink_inode(trans, dest, new_dir,
8271                                                  new_dentry->d_inode,
8272                                                  new_dentry->d_name.name,
8273                                                  new_dentry->d_name.len);
8274                 }
8275                 if (!ret && new_inode->i_nlink == 0)
8276                         ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8277                 if (ret) {
8278                         btrfs_abort_transaction(trans, root, ret);
8279                         goto out_fail;
8280                 }
8281         }
8282
8283         ret = btrfs_add_link(trans, new_dir, old_inode,
8284                              new_dentry->d_name.name,
8285                              new_dentry->d_name.len, 0, index);
8286         if (ret) {
8287                 btrfs_abort_transaction(trans, root, ret);
8288                 goto out_fail;
8289         }
8290
8291         if (old_inode->i_nlink == 1)
8292                 BTRFS_I(old_inode)->dir_index = index;
8293
8294         if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8295                 struct dentry *parent = new_dentry->d_parent;
8296                 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8297                 btrfs_end_log_trans(root);
8298         }
8299 out_fail:
8300         btrfs_end_transaction(trans, root);
8301 out_notrans:
8302         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8303                 up_read(&root->fs_info->subvol_sem);
8304
8305         return ret;
8306 }
8307
8308 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8309 {
8310         struct btrfs_delalloc_work *delalloc_work;
8311         struct inode *inode;
8312
8313         delalloc_work = container_of(work, struct btrfs_delalloc_work,
8314                                      work);
8315         inode = delalloc_work->inode;
8316         if (delalloc_work->wait) {
8317                 btrfs_wait_ordered_range(inode, 0, (u64)-1);
8318         } else {
8319                 filemap_flush(inode->i_mapping);
8320                 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8321                              &BTRFS_I(inode)->runtime_flags))
8322                         filemap_flush(inode->i_mapping);
8323         }
8324
8325         if (delalloc_work->delay_iput)
8326                 btrfs_add_delayed_iput(inode);
8327         else
8328                 iput(inode);
8329         complete(&delalloc_work->completion);
8330 }
8331
8332 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8333                                                     int wait, int delay_iput)
8334 {
8335         struct btrfs_delalloc_work *work;
8336
8337         work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8338         if (!work)
8339                 return NULL;
8340
8341         init_completion(&work->completion);
8342         INIT_LIST_HEAD(&work->list);
8343         work->inode = inode;
8344         work->wait = wait;
8345         work->delay_iput = delay_iput;
8346         work->work.func = btrfs_run_delalloc_work;
8347
8348         return work;
8349 }
8350
8351 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8352 {
8353         wait_for_completion(&work->completion);
8354         kmem_cache_free(btrfs_delalloc_work_cachep, work);
8355 }
8356
8357 /*
8358  * some fairly slow code that needs optimization. This walks the list
8359  * of all the inodes with pending delalloc and forces them to disk.
8360  */
8361 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8362 {
8363         struct btrfs_inode *binode;
8364         struct inode *inode;
8365         struct btrfs_delalloc_work *work, *next;
8366         struct list_head works;
8367         struct list_head splice;
8368         int ret = 0;
8369
8370         INIT_LIST_HEAD(&works);
8371         INIT_LIST_HEAD(&splice);
8372
8373         spin_lock(&root->delalloc_lock);
8374         list_splice_init(&root->delalloc_inodes, &splice);
8375         while (!list_empty(&splice)) {
8376                 binode = list_entry(splice.next, struct btrfs_inode,
8377                                     delalloc_inodes);
8378
8379                 list_move_tail(&binode->delalloc_inodes,
8380                                &root->delalloc_inodes);
8381                 inode = igrab(&binode->vfs_inode);
8382                 if (!inode) {
8383                         cond_resched_lock(&root->delalloc_lock);
8384                         continue;
8385                 }
8386                 spin_unlock(&root->delalloc_lock);
8387
8388                 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8389                 if (unlikely(!work)) {
8390                         if (delay_iput)
8391                                 btrfs_add_delayed_iput(inode);
8392                         else
8393                                 iput(inode);
8394                         ret = -ENOMEM;
8395                         goto out;
8396                 }
8397                 list_add_tail(&work->list, &works);
8398                 btrfs_queue_worker(&root->fs_info->flush_workers,
8399                                    &work->work);
8400
8401                 cond_resched();
8402                 spin_lock(&root->delalloc_lock);
8403         }
8404         spin_unlock(&root->delalloc_lock);
8405
8406         list_for_each_entry_safe(work, next, &works, list) {
8407                 list_del_init(&work->list);
8408                 btrfs_wait_and_free_delalloc_work(work);
8409         }
8410         return 0;
8411 out:
8412         list_for_each_entry_safe(work, next, &works, list) {
8413                 list_del_init(&work->list);
8414                 btrfs_wait_and_free_delalloc_work(work);
8415         }
8416
8417         if (!list_empty_careful(&splice)) {
8418                 spin_lock(&root->delalloc_lock);
8419                 list_splice_tail(&splice, &root->delalloc_inodes);
8420                 spin_unlock(&root->delalloc_lock);
8421         }
8422         return ret;
8423 }
8424
8425 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8426 {
8427         int ret;
8428
8429         if (root->fs_info->sb->s_flags & MS_RDONLY)
8430                 return -EROFS;
8431
8432         ret = __start_delalloc_inodes(root, delay_iput);
8433         /*
8434          * the filemap_flush will queue IO into the worker threads, but
8435          * we have to make sure the IO is actually started and that
8436          * ordered extents get created before we return
8437          */
8438         atomic_inc(&root->fs_info->async_submit_draining);
8439         while (atomic_read(&root->fs_info->nr_async_submits) ||
8440               atomic_read(&root->fs_info->async_delalloc_pages)) {
8441                 wait_event(root->fs_info->async_submit_wait,
8442                    (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8443                     atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8444         }
8445         atomic_dec(&root->fs_info->async_submit_draining);
8446         return ret;
8447 }
8448
8449 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput)
8450 {
8451         struct btrfs_root *root;
8452         struct list_head splice;
8453         int ret;
8454
8455         if (fs_info->sb->s_flags & MS_RDONLY)
8456                 return -EROFS;
8457
8458         INIT_LIST_HEAD(&splice);
8459
8460         spin_lock(&fs_info->delalloc_root_lock);
8461         list_splice_init(&fs_info->delalloc_roots, &splice);
8462         while (!list_empty(&splice)) {
8463                 root = list_first_entry(&splice, struct btrfs_root,
8464                                         delalloc_root);
8465                 root = btrfs_grab_fs_root(root);
8466                 BUG_ON(!root);
8467                 list_move_tail(&root->delalloc_root,
8468                                &fs_info->delalloc_roots);
8469                 spin_unlock(&fs_info->delalloc_root_lock);
8470
8471                 ret = __start_delalloc_inodes(root, delay_iput);
8472                 btrfs_put_fs_root(root);
8473                 if (ret)
8474                         goto out;
8475
8476                 spin_lock(&fs_info->delalloc_root_lock);
8477         }
8478         spin_unlock(&fs_info->delalloc_root_lock);
8479
8480         atomic_inc(&fs_info->async_submit_draining);
8481         while (atomic_read(&fs_info->nr_async_submits) ||
8482               atomic_read(&fs_info->async_delalloc_pages)) {
8483                 wait_event(fs_info->async_submit_wait,
8484                    (atomic_read(&fs_info->nr_async_submits) == 0 &&
8485                     atomic_read(&fs_info->async_delalloc_pages) == 0));
8486         }
8487         atomic_dec(&fs_info->async_submit_draining);
8488         return 0;
8489 out:
8490         if (!list_empty_careful(&splice)) {
8491                 spin_lock(&fs_info->delalloc_root_lock);
8492                 list_splice_tail(&splice, &fs_info->delalloc_roots);
8493                 spin_unlock(&fs_info->delalloc_root_lock);
8494         }
8495         return ret;
8496 }
8497
8498 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8499                          const char *symname)
8500 {
8501         struct btrfs_trans_handle *trans;
8502         struct btrfs_root *root = BTRFS_I(dir)->root;
8503         struct btrfs_path *path;
8504         struct btrfs_key key;
8505         struct inode *inode = NULL;
8506         int err;
8507         int drop_inode = 0;
8508         u64 objectid;
8509         u64 index = 0;
8510         int name_len;
8511         int datasize;
8512         unsigned long ptr;
8513         struct btrfs_file_extent_item *ei;
8514         struct extent_buffer *leaf;
8515
8516         name_len = strlen(symname);
8517         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8518                 return -ENAMETOOLONG;
8519
8520         /*
8521          * 2 items for inode item and ref
8522          * 2 items for dir items
8523          * 1 item for xattr if selinux is on
8524          */
8525         trans = btrfs_start_transaction(root, 5);
8526         if (IS_ERR(trans))
8527                 return PTR_ERR(trans);
8528
8529         err = btrfs_find_free_ino(root, &objectid);
8530         if (err)
8531                 goto out_unlock;
8532
8533         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8534                                 dentry->d_name.len, btrfs_ino(dir), objectid,
8535                                 S_IFLNK|S_IRWXUGO, &index);
8536         if (IS_ERR(inode)) {
8537                 err = PTR_ERR(inode);
8538                 goto out_unlock;
8539         }
8540
8541         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8542         if (err) {
8543                 drop_inode = 1;
8544                 goto out_unlock;
8545         }
8546
8547         /*
8548         * If the active LSM wants to access the inode during
8549         * d_instantiate it needs these. Smack checks to see
8550         * if the filesystem supports xattrs by looking at the
8551         * ops vector.
8552         */
8553         inode->i_fop = &btrfs_file_operations;
8554         inode->i_op = &btrfs_file_inode_operations;
8555
8556         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8557         if (err)
8558                 drop_inode = 1;
8559         else {
8560                 inode->i_mapping->a_ops = &btrfs_aops;
8561                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8562                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8563         }
8564         if (drop_inode)
8565                 goto out_unlock;
8566
8567         path = btrfs_alloc_path();
8568         if (!path) {
8569                 err = -ENOMEM;
8570                 drop_inode = 1;
8571                 goto out_unlock;
8572         }
8573         key.objectid = btrfs_ino(inode);
8574         key.offset = 0;
8575         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8576         datasize = btrfs_file_extent_calc_inline_size(name_len);
8577         err = btrfs_insert_empty_item(trans, root, path, &key,
8578                                       datasize);
8579         if (err) {
8580                 drop_inode = 1;
8581                 btrfs_free_path(path);
8582                 goto out_unlock;
8583         }
8584         leaf = path->nodes[0];
8585         ei = btrfs_item_ptr(leaf, path->slots[0],
8586                             struct btrfs_file_extent_item);
8587         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8588         btrfs_set_file_extent_type(leaf, ei,
8589                                    BTRFS_FILE_EXTENT_INLINE);
8590         btrfs_set_file_extent_encryption(leaf, ei, 0);
8591         btrfs_set_file_extent_compression(leaf, ei, 0);
8592         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8593         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8594
8595         ptr = btrfs_file_extent_inline_start(ei);
8596         write_extent_buffer(leaf, symname, ptr, name_len);
8597         btrfs_mark_buffer_dirty(leaf);
8598         btrfs_free_path(path);
8599
8600         inode->i_op = &btrfs_symlink_inode_operations;
8601         inode->i_mapping->a_ops = &btrfs_symlink_aops;
8602         inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8603         inode_set_bytes(inode, name_len);
8604         btrfs_i_size_write(inode, name_len);
8605         err = btrfs_update_inode(trans, root, inode);
8606         if (err)
8607                 drop_inode = 1;
8608
8609 out_unlock:
8610         if (!err)
8611                 d_instantiate(dentry, inode);
8612         btrfs_end_transaction(trans, root);
8613         if (drop_inode) {
8614                 inode_dec_link_count(inode);
8615                 iput(inode);
8616         }
8617         btrfs_btree_balance_dirty(root);
8618         return err;
8619 }
8620
8621 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8622                                        u64 start, u64 num_bytes, u64 min_size,
8623                                        loff_t actual_len, u64 *alloc_hint,
8624                                        struct btrfs_trans_handle *trans)
8625 {
8626         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8627         struct extent_map *em;
8628         struct btrfs_root *root = BTRFS_I(inode)->root;
8629         struct btrfs_key ins;
8630         u64 cur_offset = start;
8631         u64 i_size;
8632         u64 cur_bytes;
8633         int ret = 0;
8634         bool own_trans = true;
8635
8636         if (trans)
8637                 own_trans = false;
8638         while (num_bytes > 0) {
8639                 if (own_trans) {
8640                         trans = btrfs_start_transaction(root, 3);
8641                         if (IS_ERR(trans)) {
8642                                 ret = PTR_ERR(trans);
8643                                 break;
8644                         }
8645                 }
8646
8647                 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8648                 cur_bytes = max(cur_bytes, min_size);
8649                 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
8650                                            *alloc_hint, &ins, 1);
8651                 if (ret) {
8652                         if (own_trans)
8653                                 btrfs_end_transaction(trans, root);
8654                         break;
8655                 }
8656
8657                 ret = insert_reserved_file_extent(trans, inode,
8658                                                   cur_offset, ins.objectid,
8659                                                   ins.offset, ins.offset,
8660                                                   ins.offset, 0, 0, 0,
8661                                                   BTRFS_FILE_EXTENT_PREALLOC);
8662                 if (ret) {
8663                         btrfs_free_reserved_extent(root, ins.objectid,
8664                                                    ins.offset);
8665                         btrfs_abort_transaction(trans, root, ret);
8666                         if (own_trans)
8667                                 btrfs_end_transaction(trans, root);
8668                         break;
8669                 }
8670                 btrfs_drop_extent_cache(inode, cur_offset,
8671                                         cur_offset + ins.offset -1, 0);
8672
8673                 em = alloc_extent_map();
8674                 if (!em) {
8675                         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8676                                 &BTRFS_I(inode)->runtime_flags);
8677                         goto next;
8678                 }
8679
8680                 em->start = cur_offset;
8681                 em->orig_start = cur_offset;
8682                 em->len = ins.offset;
8683                 em->block_start = ins.objectid;
8684                 em->block_len = ins.offset;
8685                 em->orig_block_len = ins.offset;
8686                 em->ram_bytes = ins.offset;
8687                 em->bdev = root->fs_info->fs_devices->latest_bdev;
8688                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8689                 em->generation = trans->transid;
8690
8691                 while (1) {
8692                         write_lock(&em_tree->lock);
8693                         ret = add_extent_mapping(em_tree, em, 1);
8694                         write_unlock(&em_tree->lock);
8695                         if (ret != -EEXIST)
8696                                 break;
8697                         btrfs_drop_extent_cache(inode, cur_offset,
8698                                                 cur_offset + ins.offset - 1,
8699                                                 0);
8700                 }
8701                 free_extent_map(em);
8702 next:
8703                 num_bytes -= ins.offset;
8704                 cur_offset += ins.offset;
8705                 *alloc_hint = ins.objectid + ins.offset;
8706
8707                 inode_inc_iversion(inode);
8708                 inode->i_ctime = CURRENT_TIME;
8709                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8710                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8711                     (actual_len > inode->i_size) &&
8712                     (cur_offset > inode->i_size)) {
8713                         if (cur_offset > actual_len)
8714                                 i_size = actual_len;
8715                         else
8716                                 i_size = cur_offset;
8717                         i_size_write(inode, i_size);
8718                         btrfs_ordered_update_i_size(inode, i_size, NULL);
8719                 }
8720
8721                 ret = btrfs_update_inode(trans, root, inode);
8722
8723                 if (ret) {
8724                         btrfs_abort_transaction(trans, root, ret);
8725                         if (own_trans)
8726                                 btrfs_end_transaction(trans, root);
8727                         break;
8728                 }
8729
8730                 if (own_trans)
8731                         btrfs_end_transaction(trans, root);
8732         }
8733         return ret;
8734 }
8735
8736 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8737                               u64 start, u64 num_bytes, u64 min_size,
8738                               loff_t actual_len, u64 *alloc_hint)
8739 {
8740         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8741                                            min_size, actual_len, alloc_hint,
8742                                            NULL);
8743 }
8744
8745 int btrfs_prealloc_file_range_trans(struct inode *inode,
8746                                     struct btrfs_trans_handle *trans, int mode,
8747                                     u64 start, u64 num_bytes, u64 min_size,
8748                                     loff_t actual_len, u64 *alloc_hint)
8749 {
8750         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8751                                            min_size, actual_len, alloc_hint, trans);
8752 }
8753
8754 static int btrfs_set_page_dirty(struct page *page)
8755 {
8756         return __set_page_dirty_nobuffers(page);
8757 }
8758
8759 static int btrfs_permission(struct inode *inode, int mask)
8760 {
8761         struct btrfs_root *root = BTRFS_I(inode)->root;
8762         umode_t mode = inode->i_mode;
8763
8764         if (mask & MAY_WRITE &&
8765             (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8766                 if (btrfs_root_readonly(root))
8767                         return -EROFS;
8768                 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8769                         return -EACCES;
8770         }
8771         return generic_permission(inode, mask);
8772 }
8773
8774 static const struct inode_operations btrfs_dir_inode_operations = {
8775         .getattr        = btrfs_getattr,
8776         .lookup         = btrfs_lookup,
8777         .create         = btrfs_create,
8778         .unlink         = btrfs_unlink,
8779         .link           = btrfs_link,
8780         .mkdir          = btrfs_mkdir,
8781         .rmdir          = btrfs_rmdir,
8782         .rename         = btrfs_rename,
8783         .symlink        = btrfs_symlink,
8784         .setattr        = btrfs_setattr,
8785         .mknod          = btrfs_mknod,
8786         .setxattr       = btrfs_setxattr,
8787         .getxattr       = btrfs_getxattr,
8788         .listxattr      = btrfs_listxattr,
8789         .removexattr    = btrfs_removexattr,
8790         .permission     = btrfs_permission,
8791         .get_acl        = btrfs_get_acl,
8792         .update_time    = btrfs_update_time,
8793 };
8794 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8795         .lookup         = btrfs_lookup,
8796         .permission     = btrfs_permission,
8797         .get_acl        = btrfs_get_acl,
8798         .update_time    = btrfs_update_time,
8799 };
8800
8801 static const struct file_operations btrfs_dir_file_operations = {
8802         .llseek         = generic_file_llseek,
8803         .read           = generic_read_dir,
8804         .iterate        = btrfs_real_readdir,
8805         .unlocked_ioctl = btrfs_ioctl,
8806 #ifdef CONFIG_COMPAT
8807         .compat_ioctl   = btrfs_ioctl,
8808 #endif
8809         .release        = btrfs_release_file,
8810         .fsync          = btrfs_sync_file,
8811 };
8812
8813 static struct extent_io_ops btrfs_extent_io_ops = {
8814         .fill_delalloc = run_delalloc_range,
8815         .submit_bio_hook = btrfs_submit_bio_hook,
8816         .merge_bio_hook = btrfs_merge_bio_hook,
8817         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8818         .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8819         .writepage_start_hook = btrfs_writepage_start_hook,
8820         .set_bit_hook = btrfs_set_bit_hook,
8821         .clear_bit_hook = btrfs_clear_bit_hook,
8822         .merge_extent_hook = btrfs_merge_extent_hook,
8823         .split_extent_hook = btrfs_split_extent_hook,
8824 };
8825
8826 /*
8827  * btrfs doesn't support the bmap operation because swapfiles
8828  * use bmap to make a mapping of extents in the file.  They assume
8829  * these extents won't change over the life of the file and they
8830  * use the bmap result to do IO directly to the drive.
8831  *
8832  * the btrfs bmap call would return logical addresses that aren't
8833  * suitable for IO and they also will change frequently as COW
8834  * operations happen.  So, swapfile + btrfs == corruption.
8835  *
8836  * For now we're avoiding this by dropping bmap.
8837  */
8838 static const struct address_space_operations btrfs_aops = {
8839         .readpage       = btrfs_readpage,
8840         .writepage      = btrfs_writepage,
8841         .writepages     = btrfs_writepages,
8842         .readpages      = btrfs_readpages,
8843         .direct_IO      = btrfs_direct_IO,
8844         .invalidatepage = btrfs_invalidatepage,
8845         .releasepage    = btrfs_releasepage,
8846         .set_page_dirty = btrfs_set_page_dirty,
8847         .error_remove_page = generic_error_remove_page,
8848 };
8849
8850 static const struct address_space_operations btrfs_symlink_aops = {
8851         .readpage       = btrfs_readpage,
8852         .writepage      = btrfs_writepage,
8853         .invalidatepage = btrfs_invalidatepage,
8854         .releasepage    = btrfs_releasepage,
8855 };
8856
8857 static const struct inode_operations btrfs_file_inode_operations = {
8858         .getattr        = btrfs_getattr,
8859         .setattr        = btrfs_setattr,
8860         .setxattr       = btrfs_setxattr,
8861         .getxattr       = btrfs_getxattr,
8862         .listxattr      = btrfs_listxattr,
8863         .removexattr    = btrfs_removexattr,
8864         .permission     = btrfs_permission,
8865         .fiemap         = btrfs_fiemap,
8866         .get_acl        = btrfs_get_acl,
8867         .update_time    = btrfs_update_time,
8868 };
8869 static const struct inode_operations btrfs_special_inode_operations = {
8870         .getattr        = btrfs_getattr,
8871         .setattr        = btrfs_setattr,
8872         .permission     = btrfs_permission,
8873         .setxattr       = btrfs_setxattr,
8874         .getxattr       = btrfs_getxattr,
8875         .listxattr      = btrfs_listxattr,
8876         .removexattr    = btrfs_removexattr,
8877         .get_acl        = btrfs_get_acl,
8878         .update_time    = btrfs_update_time,
8879 };
8880 static const struct inode_operations btrfs_symlink_inode_operations = {
8881         .readlink       = generic_readlink,
8882         .follow_link    = page_follow_link_light,
8883         .put_link       = page_put_link,
8884         .getattr        = btrfs_getattr,
8885         .setattr        = btrfs_setattr,
8886         .permission     = btrfs_permission,
8887         .setxattr       = btrfs_setxattr,
8888         .getxattr       = btrfs_getxattr,
8889         .listxattr      = btrfs_listxattr,
8890         .removexattr    = btrfs_removexattr,
8891         .get_acl        = btrfs_get_acl,
8892         .update_time    = btrfs_update_time,
8893 };
8894
8895 const struct dentry_operations btrfs_dentry_operations = {
8896         .d_delete       = btrfs_dentry_delete,
8897         .d_release      = btrfs_dentry_release,
8898 };