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