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