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