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