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