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