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