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