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