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