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