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