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