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