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