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