Btrfs: fix wrong mtime and ctime when creating snapshots
[linux-3.10.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/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include <linux/mount.h>
42 #include "compat.h"
43 #include "ctree.h"
44 #include "disk-io.h"
45 #include "transaction.h"
46 #include "btrfs_inode.h"
47 #include "ioctl.h"
48 #include "print-tree.h"
49 #include "ordered-data.h"
50 #include "xattr.h"
51 #include "tree-log.h"
52 #include "volumes.h"
53 #include "compression.h"
54 #include "locking.h"
55 #include "free-space-cache.h"
56 #include "inode-map.h"
57
58 struct btrfs_iget_args {
59         u64 ino;
60         struct btrfs_root *root;
61 };
62
63 static const struct inode_operations btrfs_dir_inode_operations;
64 static const struct inode_operations btrfs_symlink_inode_operations;
65 static const struct inode_operations btrfs_dir_ro_inode_operations;
66 static const struct inode_operations btrfs_special_inode_operations;
67 static const struct inode_operations btrfs_file_inode_operations;
68 static const struct address_space_operations btrfs_aops;
69 static const struct address_space_operations btrfs_symlink_aops;
70 static const struct file_operations btrfs_dir_file_operations;
71 static struct extent_io_ops btrfs_extent_io_ops;
72
73 static struct kmem_cache *btrfs_inode_cachep;
74 struct kmem_cache *btrfs_trans_handle_cachep;
75 struct kmem_cache *btrfs_transaction_cachep;
76 struct kmem_cache *btrfs_path_cachep;
77 struct kmem_cache *btrfs_free_space_cachep;
78
79 #define S_SHIFT 12
80 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
81         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
82         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
83         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
84         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
85         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
86         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
87         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
88 };
89
90 static int btrfs_setsize(struct inode *inode, loff_t newsize);
91 static int btrfs_truncate(struct inode *inode);
92 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
93 static noinline int cow_file_range(struct inode *inode,
94                                    struct page *locked_page,
95                                    u64 start, u64 end, int *page_started,
96                                    unsigned long *nr_written, int unlock);
97 static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
98                                 struct btrfs_root *root, struct inode *inode);
99
100 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
101                                      struct inode *inode,  struct inode *dir,
102                                      const struct qstr *qstr)
103 {
104         int err;
105
106         err = btrfs_init_acl(trans, inode, dir);
107         if (!err)
108                 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
109         return err;
110 }
111
112 /*
113  * this does all the hard work for inserting an inline extent into
114  * the btree.  The caller should have done a btrfs_drop_extents so that
115  * no overlapping inline items exist in the btree
116  */
117 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
118                                 struct btrfs_root *root, struct inode *inode,
119                                 u64 start, size_t size, size_t compressed_size,
120                                 int compress_type,
121                                 struct page **compressed_pages)
122 {
123         struct btrfs_key key;
124         struct btrfs_path *path;
125         struct extent_buffer *leaf;
126         struct page *page = NULL;
127         char *kaddr;
128         unsigned long ptr;
129         struct btrfs_file_extent_item *ei;
130         int err = 0;
131         int ret;
132         size_t cur_size = size;
133         size_t datasize;
134         unsigned long offset;
135
136         if (compressed_size && compressed_pages)
137                 cur_size = compressed_size;
138
139         path = btrfs_alloc_path();
140         if (!path)
141                 return -ENOMEM;
142
143         path->leave_spinning = 1;
144
145         key.objectid = btrfs_ino(inode);
146         key.offset = start;
147         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
148         datasize = btrfs_file_extent_calc_inline_size(cur_size);
149
150         inode_add_bytes(inode, size);
151         ret = btrfs_insert_empty_item(trans, root, path, &key,
152                                       datasize);
153         if (ret) {
154                 err = ret;
155                 goto fail;
156         }
157         leaf = path->nodes[0];
158         ei = btrfs_item_ptr(leaf, path->slots[0],
159                             struct btrfs_file_extent_item);
160         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
161         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
162         btrfs_set_file_extent_encryption(leaf, ei, 0);
163         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
164         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
165         ptr = btrfs_file_extent_inline_start(ei);
166
167         if (compress_type != BTRFS_COMPRESS_NONE) {
168                 struct page *cpage;
169                 int i = 0;
170                 while (compressed_size > 0) {
171                         cpage = compressed_pages[i];
172                         cur_size = min_t(unsigned long, compressed_size,
173                                        PAGE_CACHE_SIZE);
174
175                         kaddr = kmap_atomic(cpage);
176                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
177                         kunmap_atomic(kaddr);
178
179                         i++;
180                         ptr += cur_size;
181                         compressed_size -= cur_size;
182                 }
183                 btrfs_set_file_extent_compression(leaf, ei,
184                                                   compress_type);
185         } else {
186                 page = find_get_page(inode->i_mapping,
187                                      start >> PAGE_CACHE_SHIFT);
188                 btrfs_set_file_extent_compression(leaf, ei, 0);
189                 kaddr = kmap_atomic(page);
190                 offset = start & (PAGE_CACHE_SIZE - 1);
191                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
192                 kunmap_atomic(kaddr);
193                 page_cache_release(page);
194         }
195         btrfs_mark_buffer_dirty(leaf);
196         btrfs_free_path(path);
197
198         /*
199          * we're an inline extent, so nobody can
200          * extend the file past i_size without locking
201          * a page we already have locked.
202          *
203          * We must do any isize and inode updates
204          * before we unlock the pages.  Otherwise we
205          * could end up racing with unlink.
206          */
207         BTRFS_I(inode)->disk_i_size = inode->i_size;
208         ret = btrfs_update_inode(trans, root, inode);
209
210         return ret;
211 fail:
212         btrfs_free_path(path);
213         return err;
214 }
215
216
217 /*
218  * conditionally insert an inline extent into the file.  This
219  * does the checks required to make sure the data is small enough
220  * to fit as an inline extent.
221  */
222 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
223                                  struct btrfs_root *root,
224                                  struct inode *inode, u64 start, u64 end,
225                                  size_t compressed_size, int compress_type,
226                                  struct page **compressed_pages)
227 {
228         u64 isize = i_size_read(inode);
229         u64 actual_end = min(end + 1, isize);
230         u64 inline_len = actual_end - start;
231         u64 aligned_end = (end + root->sectorsize - 1) &
232                         ~((u64)root->sectorsize - 1);
233         u64 hint_byte;
234         u64 data_len = inline_len;
235         int ret;
236
237         if (compressed_size)
238                 data_len = compressed_size;
239
240         if (start > 0 ||
241             actual_end >= PAGE_CACHE_SIZE ||
242             data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
243             (!compressed_size &&
244             (actual_end & (root->sectorsize - 1)) == 0) ||
245             end + 1 < isize ||
246             data_len > root->fs_info->max_inline) {
247                 return 1;
248         }
249
250         ret = btrfs_drop_extents(trans, inode, start, aligned_end,
251                                  &hint_byte, 1);
252         if (ret)
253                 return ret;
254
255         if (isize > actual_end)
256                 inline_len = min_t(u64, isize, actual_end);
257         ret = insert_inline_extent(trans, root, inode, start,
258                                    inline_len, compressed_size,
259                                    compress_type, compressed_pages);
260         if (ret && ret != -ENOSPC) {
261                 btrfs_abort_transaction(trans, root, ret);
262                 return ret;
263         } else if (ret == -ENOSPC) {
264                 return 1;
265         }
266
267         btrfs_delalloc_release_metadata(inode, end + 1 - start);
268         btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
269         return 0;
270 }
271
272 struct async_extent {
273         u64 start;
274         u64 ram_size;
275         u64 compressed_size;
276         struct page **pages;
277         unsigned long nr_pages;
278         int compress_type;
279         struct list_head list;
280 };
281
282 struct async_cow {
283         struct inode *inode;
284         struct btrfs_root *root;
285         struct page *locked_page;
286         u64 start;
287         u64 end;
288         struct list_head extents;
289         struct btrfs_work work;
290 };
291
292 static noinline int add_async_extent(struct async_cow *cow,
293                                      u64 start, u64 ram_size,
294                                      u64 compressed_size,
295                                      struct page **pages,
296                                      unsigned long nr_pages,
297                                      int compress_type)
298 {
299         struct async_extent *async_extent;
300
301         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
302         BUG_ON(!async_extent); /* -ENOMEM */
303         async_extent->start = start;
304         async_extent->ram_size = ram_size;
305         async_extent->compressed_size = compressed_size;
306         async_extent->pages = pages;
307         async_extent->nr_pages = nr_pages;
308         async_extent->compress_type = compress_type;
309         list_add_tail(&async_extent->list, &cow->extents);
310         return 0;
311 }
312
313 /*
314  * we create compressed extents in two phases.  The first
315  * phase compresses a range of pages that have already been
316  * locked (both pages and state bits are locked).
317  *
318  * This is done inside an ordered work queue, and the compression
319  * is spread across many cpus.  The actual IO submission is step
320  * two, and the ordered work queue takes care of making sure that
321  * happens in the same order things were put onto the queue by
322  * writepages and friends.
323  *
324  * If this code finds it can't get good compression, it puts an
325  * entry onto the work queue to write the uncompressed bytes.  This
326  * makes sure that both compressed inodes and uncompressed inodes
327  * are written in the same order that pdflush sent them down.
328  */
329 static noinline int compress_file_range(struct inode *inode,
330                                         struct page *locked_page,
331                                         u64 start, u64 end,
332                                         struct async_cow *async_cow,
333                                         int *num_added)
334 {
335         struct btrfs_root *root = BTRFS_I(inode)->root;
336         struct btrfs_trans_handle *trans;
337         u64 num_bytes;
338         u64 blocksize = root->sectorsize;
339         u64 actual_end;
340         u64 isize = i_size_read(inode);
341         int ret = 0;
342         struct page **pages = NULL;
343         unsigned long nr_pages;
344         unsigned long nr_pages_ret = 0;
345         unsigned long total_compressed = 0;
346         unsigned long total_in = 0;
347         unsigned long max_compressed = 128 * 1024;
348         unsigned long max_uncompressed = 128 * 1024;
349         int i;
350         int will_compress;
351         int compress_type = root->fs_info->compress_type;
352
353         /* if this is a small write inside eof, kick off a defrag */
354         if ((end - start + 1) < 16 * 1024 &&
355             (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
356                 btrfs_add_inode_defrag(NULL, inode);
357
358         actual_end = min_t(u64, isize, end + 1);
359 again:
360         will_compress = 0;
361         nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
362         nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
363
364         /*
365          * we don't want to send crud past the end of i_size through
366          * compression, that's just a waste of CPU time.  So, if the
367          * end of the file is before the start of our current
368          * requested range of bytes, we bail out to the uncompressed
369          * cleanup code that can deal with all of this.
370          *
371          * It isn't really the fastest way to fix things, but this is a
372          * very uncommon corner.
373          */
374         if (actual_end <= start)
375                 goto cleanup_and_bail_uncompressed;
376
377         total_compressed = actual_end - start;
378
379         /* we want to make sure that amount of ram required to uncompress
380          * an extent is reasonable, so we limit the total size in ram
381          * of a compressed extent to 128k.  This is a crucial number
382          * because it also controls how easily we can spread reads across
383          * cpus for decompression.
384          *
385          * We also want to make sure the amount of IO required to do
386          * a random read is reasonably small, so we limit the size of
387          * a compressed extent to 128k.
388          */
389         total_compressed = min(total_compressed, max_uncompressed);
390         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
391         num_bytes = max(blocksize,  num_bytes);
392         total_in = 0;
393         ret = 0;
394
395         /*
396          * we do compression for mount -o compress and when the
397          * inode has not been flagged as nocompress.  This flag can
398          * change at any time if we discover bad compression ratios.
399          */
400         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
401             (btrfs_test_opt(root, COMPRESS) ||
402              (BTRFS_I(inode)->force_compress) ||
403              (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
404                 WARN_ON(pages);
405                 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
406                 if (!pages) {
407                         /* just bail out to the uncompressed code */
408                         goto cont;
409                 }
410
411                 if (BTRFS_I(inode)->force_compress)
412                         compress_type = BTRFS_I(inode)->force_compress;
413
414                 ret = btrfs_compress_pages(compress_type,
415                                            inode->i_mapping, start,
416                                            total_compressed, pages,
417                                            nr_pages, &nr_pages_ret,
418                                            &total_in,
419                                            &total_compressed,
420                                            max_compressed);
421
422                 if (!ret) {
423                         unsigned long offset = total_compressed &
424                                 (PAGE_CACHE_SIZE - 1);
425                         struct page *page = pages[nr_pages_ret - 1];
426                         char *kaddr;
427
428                         /* zero the tail end of the last page, we might be
429                          * sending it down to disk
430                          */
431                         if (offset) {
432                                 kaddr = kmap_atomic(page);
433                                 memset(kaddr + offset, 0,
434                                        PAGE_CACHE_SIZE - offset);
435                                 kunmap_atomic(kaddr);
436                         }
437                         will_compress = 1;
438                 }
439         }
440 cont:
441         if (start == 0) {
442                 trans = btrfs_join_transaction(root);
443                 if (IS_ERR(trans)) {
444                         ret = PTR_ERR(trans);
445                         trans = NULL;
446                         goto cleanup_and_out;
447                 }
448                 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
449
450                 /* lets try to make an inline extent */
451                 if (ret || total_in < (actual_end - start)) {
452                         /* we didn't compress the entire range, try
453                          * to make an uncompressed inline extent.
454                          */
455                         ret = cow_file_range_inline(trans, root, inode,
456                                                     start, end, 0, 0, NULL);
457                 } else {
458                         /* try making a compressed inline extent */
459                         ret = cow_file_range_inline(trans, root, inode,
460                                                     start, end,
461                                                     total_compressed,
462                                                     compress_type, pages);
463                 }
464                 if (ret <= 0) {
465                         /*
466                          * inline extent creation worked or returned error,
467                          * we don't need to create any more async work items.
468                          * Unlock and free up our temp pages.
469                          */
470                         extent_clear_unlock_delalloc(inode,
471                              &BTRFS_I(inode)->io_tree,
472                              start, end, NULL,
473                              EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
474                              EXTENT_CLEAR_DELALLOC |
475                              EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
476
477                         btrfs_end_transaction(trans, root);
478                         goto free_pages_out;
479                 }
480                 btrfs_end_transaction(trans, root);
481         }
482
483         if (will_compress) {
484                 /*
485                  * we aren't doing an inline extent round the compressed size
486                  * up to a block size boundary so the allocator does sane
487                  * things
488                  */
489                 total_compressed = (total_compressed + blocksize - 1) &
490                         ~(blocksize - 1);
491
492                 /*
493                  * one last check to make sure the compression is really a
494                  * win, compare the page count read with the blocks on disk
495                  */
496                 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
497                         ~(PAGE_CACHE_SIZE - 1);
498                 if (total_compressed >= total_in) {
499                         will_compress = 0;
500                 } else {
501                         num_bytes = total_in;
502                 }
503         }
504         if (!will_compress && pages) {
505                 /*
506                  * the compression code ran but failed to make things smaller,
507                  * free any pages it allocated and our page pointer array
508                  */
509                 for (i = 0; i < nr_pages_ret; i++) {
510                         WARN_ON(pages[i]->mapping);
511                         page_cache_release(pages[i]);
512                 }
513                 kfree(pages);
514                 pages = NULL;
515                 total_compressed = 0;
516                 nr_pages_ret = 0;
517
518                 /* flag the file so we don't compress in the future */
519                 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
520                     !(BTRFS_I(inode)->force_compress)) {
521                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
522                 }
523         }
524         if (will_compress) {
525                 *num_added += 1;
526
527                 /* the async work queues will take care of doing actual
528                  * allocation on disk for these compressed pages,
529                  * and will submit them to the elevator.
530                  */
531                 add_async_extent(async_cow, start, num_bytes,
532                                  total_compressed, pages, nr_pages_ret,
533                                  compress_type);
534
535                 if (start + num_bytes < end) {
536                         start += num_bytes;
537                         pages = NULL;
538                         cond_resched();
539                         goto again;
540                 }
541         } else {
542 cleanup_and_bail_uncompressed:
543                 /*
544                  * No compression, but we still need to write the pages in
545                  * the file we've been given so far.  redirty the locked
546                  * page if it corresponds to our extent and set things up
547                  * for the async work queue to run cow_file_range to do
548                  * the normal delalloc dance
549                  */
550                 if (page_offset(locked_page) >= start &&
551                     page_offset(locked_page) <= end) {
552                         __set_page_dirty_nobuffers(locked_page);
553                         /* unlocked later on in the async handlers */
554                 }
555                 add_async_extent(async_cow, start, end - start + 1,
556                                  0, NULL, 0, BTRFS_COMPRESS_NONE);
557                 *num_added += 1;
558         }
559
560 out:
561         return ret;
562
563 free_pages_out:
564         for (i = 0; i < nr_pages_ret; i++) {
565                 WARN_ON(pages[i]->mapping);
566                 page_cache_release(pages[i]);
567         }
568         kfree(pages);
569
570         goto out;
571
572 cleanup_and_out:
573         extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
574                                      start, end, NULL,
575                                      EXTENT_CLEAR_UNLOCK_PAGE |
576                                      EXTENT_CLEAR_DIRTY |
577                                      EXTENT_CLEAR_DELALLOC |
578                                      EXTENT_SET_WRITEBACK |
579                                      EXTENT_END_WRITEBACK);
580         if (!trans || IS_ERR(trans))
581                 btrfs_error(root->fs_info, ret, "Failed to join transaction");
582         else
583                 btrfs_abort_transaction(trans, root, ret);
584         goto free_pages_out;
585 }
586
587 /*
588  * phase two of compressed writeback.  This is the ordered portion
589  * of the code, which only gets called in the order the work was
590  * queued.  We walk all the async extents created by compress_file_range
591  * and send them down to the disk.
592  */
593 static noinline int submit_compressed_extents(struct inode *inode,
594                                               struct async_cow *async_cow)
595 {
596         struct async_extent *async_extent;
597         u64 alloc_hint = 0;
598         struct btrfs_trans_handle *trans;
599         struct btrfs_key ins;
600         struct extent_map *em;
601         struct btrfs_root *root = BTRFS_I(inode)->root;
602         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
603         struct extent_io_tree *io_tree;
604         int ret = 0;
605
606         if (list_empty(&async_cow->extents))
607                 return 0;
608
609
610         while (!list_empty(&async_cow->extents)) {
611                 async_extent = list_entry(async_cow->extents.next,
612                                           struct async_extent, list);
613                 list_del(&async_extent->list);
614
615                 io_tree = &BTRFS_I(inode)->io_tree;
616
617 retry:
618                 /* did the compression code fall back to uncompressed IO? */
619                 if (!async_extent->pages) {
620                         int page_started = 0;
621                         unsigned long nr_written = 0;
622
623                         lock_extent(io_tree, async_extent->start,
624                                          async_extent->start +
625                                          async_extent->ram_size - 1);
626
627                         /* allocate blocks */
628                         ret = cow_file_range(inode, async_cow->locked_page,
629                                              async_extent->start,
630                                              async_extent->start +
631                                              async_extent->ram_size - 1,
632                                              &page_started, &nr_written, 0);
633
634                         /* JDM XXX */
635
636                         /*
637                          * if page_started, cow_file_range inserted an
638                          * inline extent and took care of all the unlocking
639                          * and IO for us.  Otherwise, we need to submit
640                          * all those pages down to the drive.
641                          */
642                         if (!page_started && !ret)
643                                 extent_write_locked_range(io_tree,
644                                                   inode, async_extent->start,
645                                                   async_extent->start +
646                                                   async_extent->ram_size - 1,
647                                                   btrfs_get_extent,
648                                                   WB_SYNC_ALL);
649                         kfree(async_extent);
650                         cond_resched();
651                         continue;
652                 }
653
654                 lock_extent(io_tree, async_extent->start,
655                             async_extent->start + async_extent->ram_size - 1);
656
657                 trans = btrfs_join_transaction(root);
658                 if (IS_ERR(trans)) {
659                         ret = PTR_ERR(trans);
660                 } else {
661                         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
662                         ret = btrfs_reserve_extent(trans, root,
663                                            async_extent->compressed_size,
664                                            async_extent->compressed_size,
665                                            0, alloc_hint, &ins, 1);
666                         if (ret)
667                                 btrfs_abort_transaction(trans, root, ret);
668                         btrfs_end_transaction(trans, root);
669                 }
670
671                 if (ret) {
672                         int i;
673                         for (i = 0; i < async_extent->nr_pages; i++) {
674                                 WARN_ON(async_extent->pages[i]->mapping);
675                                 page_cache_release(async_extent->pages[i]);
676                         }
677                         kfree(async_extent->pages);
678                         async_extent->nr_pages = 0;
679                         async_extent->pages = NULL;
680                         unlock_extent(io_tree, async_extent->start,
681                                       async_extent->start +
682                                       async_extent->ram_size - 1);
683                         if (ret == -ENOSPC)
684                                 goto retry;
685                         goto out_free; /* JDM: Requeue? */
686                 }
687
688                 /*
689                  * here we're doing allocation and writeback of the
690                  * compressed pages
691                  */
692                 btrfs_drop_extent_cache(inode, async_extent->start,
693                                         async_extent->start +
694                                         async_extent->ram_size - 1, 0);
695
696                 em = alloc_extent_map();
697                 BUG_ON(!em); /* -ENOMEM */
698                 em->start = async_extent->start;
699                 em->len = async_extent->ram_size;
700                 em->orig_start = em->start;
701
702                 em->block_start = ins.objectid;
703                 em->block_len = ins.offset;
704                 em->bdev = root->fs_info->fs_devices->latest_bdev;
705                 em->compress_type = async_extent->compress_type;
706                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
707                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
708
709                 while (1) {
710                         write_lock(&em_tree->lock);
711                         ret = add_extent_mapping(em_tree, em);
712                         write_unlock(&em_tree->lock);
713                         if (ret != -EEXIST) {
714                                 free_extent_map(em);
715                                 break;
716                         }
717                         btrfs_drop_extent_cache(inode, async_extent->start,
718                                                 async_extent->start +
719                                                 async_extent->ram_size - 1, 0);
720                 }
721
722                 ret = btrfs_add_ordered_extent_compress(inode,
723                                                 async_extent->start,
724                                                 ins.objectid,
725                                                 async_extent->ram_size,
726                                                 ins.offset,
727                                                 BTRFS_ORDERED_COMPRESSED,
728                                                 async_extent->compress_type);
729                 BUG_ON(ret); /* -ENOMEM */
730
731                 /*
732                  * clear dirty, set writeback and unlock the pages.
733                  */
734                 extent_clear_unlock_delalloc(inode,
735                                 &BTRFS_I(inode)->io_tree,
736                                 async_extent->start,
737                                 async_extent->start +
738                                 async_extent->ram_size - 1,
739                                 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
740                                 EXTENT_CLEAR_UNLOCK |
741                                 EXTENT_CLEAR_DELALLOC |
742                                 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
743
744                 ret = btrfs_submit_compressed_write(inode,
745                                     async_extent->start,
746                                     async_extent->ram_size,
747                                     ins.objectid,
748                                     ins.offset, async_extent->pages,
749                                     async_extent->nr_pages);
750
751                 BUG_ON(ret); /* -ENOMEM */
752                 alloc_hint = ins.objectid + ins.offset;
753                 kfree(async_extent);
754                 cond_resched();
755         }
756         ret = 0;
757 out:
758         return ret;
759 out_free:
760         kfree(async_extent);
761         goto out;
762 }
763
764 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
765                                       u64 num_bytes)
766 {
767         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
768         struct extent_map *em;
769         u64 alloc_hint = 0;
770
771         read_lock(&em_tree->lock);
772         em = search_extent_mapping(em_tree, start, num_bytes);
773         if (em) {
774                 /*
775                  * if block start isn't an actual block number then find the
776                  * first block in this inode and use that as a hint.  If that
777                  * block is also bogus then just don't worry about it.
778                  */
779                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
780                         free_extent_map(em);
781                         em = search_extent_mapping(em_tree, 0, 0);
782                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
783                                 alloc_hint = em->block_start;
784                         if (em)
785                                 free_extent_map(em);
786                 } else {
787                         alloc_hint = em->block_start;
788                         free_extent_map(em);
789                 }
790         }
791         read_unlock(&em_tree->lock);
792
793         return alloc_hint;
794 }
795
796 /*
797  * when extent_io.c finds a delayed allocation range in the file,
798  * the call backs end up in this code.  The basic idea is to
799  * allocate extents on disk for the range, and create ordered data structs
800  * in ram to track those extents.
801  *
802  * locked_page is the page that writepage had locked already.  We use
803  * it to make sure we don't do extra locks or unlocks.
804  *
805  * *page_started is set to one if we unlock locked_page and do everything
806  * required to start IO on it.  It may be clean and already done with
807  * IO when we return.
808  */
809 static noinline int cow_file_range(struct inode *inode,
810                                    struct page *locked_page,
811                                    u64 start, u64 end, int *page_started,
812                                    unsigned long *nr_written,
813                                    int unlock)
814 {
815         struct btrfs_root *root = BTRFS_I(inode)->root;
816         struct btrfs_trans_handle *trans;
817         u64 alloc_hint = 0;
818         u64 num_bytes;
819         unsigned long ram_size;
820         u64 disk_num_bytes;
821         u64 cur_alloc_size;
822         u64 blocksize = root->sectorsize;
823         struct btrfs_key ins;
824         struct extent_map *em;
825         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
826         int ret = 0;
827
828         BUG_ON(btrfs_is_free_space_inode(inode));
829         trans = btrfs_join_transaction(root);
830         if (IS_ERR(trans)) {
831                 extent_clear_unlock_delalloc(inode,
832                              &BTRFS_I(inode)->io_tree,
833                              start, end, locked_page,
834                              EXTENT_CLEAR_UNLOCK_PAGE |
835                              EXTENT_CLEAR_UNLOCK |
836                              EXTENT_CLEAR_DELALLOC |
837                              EXTENT_CLEAR_DIRTY |
838                              EXTENT_SET_WRITEBACK |
839                              EXTENT_END_WRITEBACK);
840                 return PTR_ERR(trans);
841         }
842         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
843
844         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
845         num_bytes = max(blocksize,  num_bytes);
846         disk_num_bytes = num_bytes;
847         ret = 0;
848
849         /* if this is a small write inside eof, kick off defrag */
850         if (num_bytes < 64 * 1024 &&
851             (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
852                 btrfs_add_inode_defrag(trans, inode);
853
854         if (start == 0) {
855                 /* lets try to make an inline extent */
856                 ret = cow_file_range_inline(trans, root, inode,
857                                             start, end, 0, 0, NULL);
858                 if (ret == 0) {
859                         extent_clear_unlock_delalloc(inode,
860                                      &BTRFS_I(inode)->io_tree,
861                                      start, end, NULL,
862                                      EXTENT_CLEAR_UNLOCK_PAGE |
863                                      EXTENT_CLEAR_UNLOCK |
864                                      EXTENT_CLEAR_DELALLOC |
865                                      EXTENT_CLEAR_DIRTY |
866                                      EXTENT_SET_WRITEBACK |
867                                      EXTENT_END_WRITEBACK);
868
869                         *nr_written = *nr_written +
870                              (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
871                         *page_started = 1;
872                         goto out;
873                 } else if (ret < 0) {
874                         btrfs_abort_transaction(trans, root, ret);
875                         goto out_unlock;
876                 }
877         }
878
879         BUG_ON(disk_num_bytes >
880                btrfs_super_total_bytes(root->fs_info->super_copy));
881
882         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
883         btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
884
885         while (disk_num_bytes > 0) {
886                 unsigned long op;
887
888                 cur_alloc_size = disk_num_bytes;
889                 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
890                                            root->sectorsize, 0, alloc_hint,
891                                            &ins, 1);
892                 if (ret < 0) {
893                         btrfs_abort_transaction(trans, root, ret);
894                         goto out_unlock;
895                 }
896
897                 em = alloc_extent_map();
898                 BUG_ON(!em); /* -ENOMEM */
899                 em->start = start;
900                 em->orig_start = em->start;
901                 ram_size = ins.offset;
902                 em->len = ins.offset;
903
904                 em->block_start = ins.objectid;
905                 em->block_len = ins.offset;
906                 em->bdev = root->fs_info->fs_devices->latest_bdev;
907                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
908
909                 while (1) {
910                         write_lock(&em_tree->lock);
911                         ret = add_extent_mapping(em_tree, em);
912                         write_unlock(&em_tree->lock);
913                         if (ret != -EEXIST) {
914                                 free_extent_map(em);
915                                 break;
916                         }
917                         btrfs_drop_extent_cache(inode, start,
918                                                 start + ram_size - 1, 0);
919                 }
920
921                 cur_alloc_size = ins.offset;
922                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
923                                                ram_size, cur_alloc_size, 0);
924                 BUG_ON(ret); /* -ENOMEM */
925
926                 if (root->root_key.objectid ==
927                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
928                         ret = btrfs_reloc_clone_csums(inode, start,
929                                                       cur_alloc_size);
930                         if (ret) {
931                                 btrfs_abort_transaction(trans, root, ret);
932                                 goto out_unlock;
933                         }
934                 }
935
936                 if (disk_num_bytes < cur_alloc_size)
937                         break;
938
939                 /* we're not doing compressed IO, don't unlock the first
940                  * page (which the caller expects to stay locked), don't
941                  * clear any dirty bits and don't set any writeback bits
942                  *
943                  * Do set the Private2 bit so we know this page was properly
944                  * setup for writepage
945                  */
946                 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
947                 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
948                         EXTENT_SET_PRIVATE2;
949
950                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
951                                              start, start + ram_size - 1,
952                                              locked_page, op);
953                 disk_num_bytes -= cur_alloc_size;
954                 num_bytes -= cur_alloc_size;
955                 alloc_hint = ins.objectid + ins.offset;
956                 start += cur_alloc_size;
957         }
958         ret = 0;
959 out:
960         btrfs_end_transaction(trans, root);
961
962         return ret;
963 out_unlock:
964         extent_clear_unlock_delalloc(inode,
965                      &BTRFS_I(inode)->io_tree,
966                      start, end, locked_page,
967                      EXTENT_CLEAR_UNLOCK_PAGE |
968                      EXTENT_CLEAR_UNLOCK |
969                      EXTENT_CLEAR_DELALLOC |
970                      EXTENT_CLEAR_DIRTY |
971                      EXTENT_SET_WRITEBACK |
972                      EXTENT_END_WRITEBACK);
973
974         goto out;
975 }
976
977 /*
978  * work queue call back to started compression on a file and pages
979  */
980 static noinline void async_cow_start(struct btrfs_work *work)
981 {
982         struct async_cow *async_cow;
983         int num_added = 0;
984         async_cow = container_of(work, struct async_cow, work);
985
986         compress_file_range(async_cow->inode, async_cow->locked_page,
987                             async_cow->start, async_cow->end, async_cow,
988                             &num_added);
989         if (num_added == 0) {
990                 btrfs_add_delayed_iput(async_cow->inode);
991                 async_cow->inode = NULL;
992         }
993 }
994
995 /*
996  * work queue call back to submit previously compressed pages
997  */
998 static noinline void async_cow_submit(struct btrfs_work *work)
999 {
1000         struct async_cow *async_cow;
1001         struct btrfs_root *root;
1002         unsigned long nr_pages;
1003
1004         async_cow = container_of(work, struct async_cow, work);
1005
1006         root = async_cow->root;
1007         nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1008                 PAGE_CACHE_SHIFT;
1009
1010         if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1011             5 * 1024 * 1024 &&
1012             waitqueue_active(&root->fs_info->async_submit_wait))
1013                 wake_up(&root->fs_info->async_submit_wait);
1014
1015         if (async_cow->inode)
1016                 submit_compressed_extents(async_cow->inode, async_cow);
1017 }
1018
1019 static noinline void async_cow_free(struct btrfs_work *work)
1020 {
1021         struct async_cow *async_cow;
1022         async_cow = container_of(work, struct async_cow, work);
1023         if (async_cow->inode)
1024                 btrfs_add_delayed_iput(async_cow->inode);
1025         kfree(async_cow);
1026 }
1027
1028 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1029                                 u64 start, u64 end, int *page_started,
1030                                 unsigned long *nr_written)
1031 {
1032         struct async_cow *async_cow;
1033         struct btrfs_root *root = BTRFS_I(inode)->root;
1034         unsigned long nr_pages;
1035         u64 cur_end;
1036         int limit = 10 * 1024 * 1024;
1037
1038         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1039                          1, 0, NULL, GFP_NOFS);
1040         while (start < end) {
1041                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1042                 BUG_ON(!async_cow); /* -ENOMEM */
1043                 async_cow->inode = igrab(inode);
1044                 async_cow->root = root;
1045                 async_cow->locked_page = locked_page;
1046                 async_cow->start = start;
1047
1048                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1049                         cur_end = end;
1050                 else
1051                         cur_end = min(end, start + 512 * 1024 - 1);
1052
1053                 async_cow->end = cur_end;
1054                 INIT_LIST_HEAD(&async_cow->extents);
1055
1056                 async_cow->work.func = async_cow_start;
1057                 async_cow->work.ordered_func = async_cow_submit;
1058                 async_cow->work.ordered_free = async_cow_free;
1059                 async_cow->work.flags = 0;
1060
1061                 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1062                         PAGE_CACHE_SHIFT;
1063                 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1064
1065                 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1066                                    &async_cow->work);
1067
1068                 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1069                         wait_event(root->fs_info->async_submit_wait,
1070                            (atomic_read(&root->fs_info->async_delalloc_pages) <
1071                             limit));
1072                 }
1073
1074                 while (atomic_read(&root->fs_info->async_submit_draining) &&
1075                       atomic_read(&root->fs_info->async_delalloc_pages)) {
1076                         wait_event(root->fs_info->async_submit_wait,
1077                           (atomic_read(&root->fs_info->async_delalloc_pages) ==
1078                            0));
1079                 }
1080
1081                 *nr_written += nr_pages;
1082                 start = cur_end + 1;
1083         }
1084         *page_started = 1;
1085         return 0;
1086 }
1087
1088 static noinline int csum_exist_in_range(struct btrfs_root *root,
1089                                         u64 bytenr, u64 num_bytes)
1090 {
1091         int ret;
1092         struct btrfs_ordered_sum *sums;
1093         LIST_HEAD(list);
1094
1095         ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1096                                        bytenr + num_bytes - 1, &list, 0);
1097         if (ret == 0 && list_empty(&list))
1098                 return 0;
1099
1100         while (!list_empty(&list)) {
1101                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1102                 list_del(&sums->list);
1103                 kfree(sums);
1104         }
1105         return 1;
1106 }
1107
1108 /*
1109  * when nowcow writeback call back.  This checks for snapshots or COW copies
1110  * of the extents that exist in the file, and COWs the file as required.
1111  *
1112  * If no cow copies or snapshots exist, we write directly to the existing
1113  * blocks on disk
1114  */
1115 static noinline int run_delalloc_nocow(struct inode *inode,
1116                                        struct page *locked_page,
1117                               u64 start, u64 end, int *page_started, int force,
1118                               unsigned long *nr_written)
1119 {
1120         struct btrfs_root *root = BTRFS_I(inode)->root;
1121         struct btrfs_trans_handle *trans;
1122         struct extent_buffer *leaf;
1123         struct btrfs_path *path;
1124         struct btrfs_file_extent_item *fi;
1125         struct btrfs_key found_key;
1126         u64 cow_start;
1127         u64 cur_offset;
1128         u64 extent_end;
1129         u64 extent_offset;
1130         u64 disk_bytenr;
1131         u64 num_bytes;
1132         int extent_type;
1133         int ret, err;
1134         int type;
1135         int nocow;
1136         int check_prev = 1;
1137         bool nolock;
1138         u64 ino = btrfs_ino(inode);
1139
1140         path = btrfs_alloc_path();
1141         if (!path) {
1142                 extent_clear_unlock_delalloc(inode,
1143                              &BTRFS_I(inode)->io_tree,
1144                              start, end, locked_page,
1145                              EXTENT_CLEAR_UNLOCK_PAGE |
1146                              EXTENT_CLEAR_UNLOCK |
1147                              EXTENT_CLEAR_DELALLOC |
1148                              EXTENT_CLEAR_DIRTY |
1149                              EXTENT_SET_WRITEBACK |
1150                              EXTENT_END_WRITEBACK);
1151                 return -ENOMEM;
1152         }
1153
1154         nolock = btrfs_is_free_space_inode(inode);
1155
1156         if (nolock)
1157                 trans = btrfs_join_transaction_nolock(root);
1158         else
1159                 trans = btrfs_join_transaction(root);
1160
1161         if (IS_ERR(trans)) {
1162                 extent_clear_unlock_delalloc(inode,
1163                              &BTRFS_I(inode)->io_tree,
1164                              start, end, locked_page,
1165                              EXTENT_CLEAR_UNLOCK_PAGE |
1166                              EXTENT_CLEAR_UNLOCK |
1167                              EXTENT_CLEAR_DELALLOC |
1168                              EXTENT_CLEAR_DIRTY |
1169                              EXTENT_SET_WRITEBACK |
1170                              EXTENT_END_WRITEBACK);
1171                 btrfs_free_path(path);
1172                 return PTR_ERR(trans);
1173         }
1174
1175         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1176
1177         cow_start = (u64)-1;
1178         cur_offset = start;
1179         while (1) {
1180                 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1181                                                cur_offset, 0);
1182                 if (ret < 0) {
1183                         btrfs_abort_transaction(trans, root, ret);
1184                         goto error;
1185                 }
1186                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1187                         leaf = path->nodes[0];
1188                         btrfs_item_key_to_cpu(leaf, &found_key,
1189                                               path->slots[0] - 1);
1190                         if (found_key.objectid == ino &&
1191                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1192                                 path->slots[0]--;
1193                 }
1194                 check_prev = 0;
1195 next_slot:
1196                 leaf = path->nodes[0];
1197                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1198                         ret = btrfs_next_leaf(root, path);
1199                         if (ret < 0) {
1200                                 btrfs_abort_transaction(trans, root, ret);
1201                                 goto error;
1202                         }
1203                         if (ret > 0)
1204                                 break;
1205                         leaf = path->nodes[0];
1206                 }
1207
1208                 nocow = 0;
1209                 disk_bytenr = 0;
1210                 num_bytes = 0;
1211                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1212
1213                 if (found_key.objectid > ino ||
1214                     found_key.type > BTRFS_EXTENT_DATA_KEY ||
1215                     found_key.offset > end)
1216                         break;
1217
1218                 if (found_key.offset > cur_offset) {
1219                         extent_end = found_key.offset;
1220                         extent_type = 0;
1221                         goto out_check;
1222                 }
1223
1224                 fi = btrfs_item_ptr(leaf, path->slots[0],
1225                                     struct btrfs_file_extent_item);
1226                 extent_type = btrfs_file_extent_type(leaf, fi);
1227
1228                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1229                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1230                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1231                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1232                         extent_end = found_key.offset +
1233                                 btrfs_file_extent_num_bytes(leaf, fi);
1234                         if (extent_end <= start) {
1235                                 path->slots[0]++;
1236                                 goto next_slot;
1237                         }
1238                         if (disk_bytenr == 0)
1239                                 goto out_check;
1240                         if (btrfs_file_extent_compression(leaf, fi) ||
1241                             btrfs_file_extent_encryption(leaf, fi) ||
1242                             btrfs_file_extent_other_encoding(leaf, fi))
1243                                 goto out_check;
1244                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1245                                 goto out_check;
1246                         if (btrfs_extent_readonly(root, disk_bytenr))
1247                                 goto out_check;
1248                         if (btrfs_cross_ref_exist(trans, root, ino,
1249                                                   found_key.offset -
1250                                                   extent_offset, disk_bytenr))
1251                                 goto out_check;
1252                         disk_bytenr += extent_offset;
1253                         disk_bytenr += cur_offset - found_key.offset;
1254                         num_bytes = min(end + 1, extent_end) - cur_offset;
1255                         /*
1256                          * force cow if csum exists in the range.
1257                          * this ensure that csum for a given extent are
1258                          * either valid or do not exist.
1259                          */
1260                         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1261                                 goto out_check;
1262                         nocow = 1;
1263                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1264                         extent_end = found_key.offset +
1265                                 btrfs_file_extent_inline_len(leaf, fi);
1266                         extent_end = ALIGN(extent_end, root->sectorsize);
1267                 } else {
1268                         BUG_ON(1);
1269                 }
1270 out_check:
1271                 if (extent_end <= start) {
1272                         path->slots[0]++;
1273                         goto next_slot;
1274                 }
1275                 if (!nocow) {
1276                         if (cow_start == (u64)-1)
1277                                 cow_start = cur_offset;
1278                         cur_offset = extent_end;
1279                         if (cur_offset > end)
1280                                 break;
1281                         path->slots[0]++;
1282                         goto next_slot;
1283                 }
1284
1285                 btrfs_release_path(path);
1286                 if (cow_start != (u64)-1) {
1287                         ret = cow_file_range(inode, locked_page, cow_start,
1288                                         found_key.offset - 1, page_started,
1289                                         nr_written, 1);
1290                         if (ret) {
1291                                 btrfs_abort_transaction(trans, root, ret);
1292                                 goto error;
1293                         }
1294                         cow_start = (u64)-1;
1295                 }
1296
1297                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1298                         struct extent_map *em;
1299                         struct extent_map_tree *em_tree;
1300                         em_tree = &BTRFS_I(inode)->extent_tree;
1301                         em = alloc_extent_map();
1302                         BUG_ON(!em); /* -ENOMEM */
1303                         em->start = cur_offset;
1304                         em->orig_start = em->start;
1305                         em->len = num_bytes;
1306                         em->block_len = num_bytes;
1307                         em->block_start = disk_bytenr;
1308                         em->bdev = root->fs_info->fs_devices->latest_bdev;
1309                         set_bit(EXTENT_FLAG_PINNED, &em->flags);
1310                         while (1) {
1311                                 write_lock(&em_tree->lock);
1312                                 ret = add_extent_mapping(em_tree, em);
1313                                 write_unlock(&em_tree->lock);
1314                                 if (ret != -EEXIST) {
1315                                         free_extent_map(em);
1316                                         break;
1317                                 }
1318                                 btrfs_drop_extent_cache(inode, em->start,
1319                                                 em->start + em->len - 1, 0);
1320                         }
1321                         type = BTRFS_ORDERED_PREALLOC;
1322                 } else {
1323                         type = BTRFS_ORDERED_NOCOW;
1324                 }
1325
1326                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1327                                                num_bytes, num_bytes, type);
1328                 BUG_ON(ret); /* -ENOMEM */
1329
1330                 if (root->root_key.objectid ==
1331                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1332                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1333                                                       num_bytes);
1334                         if (ret) {
1335                                 btrfs_abort_transaction(trans, root, ret);
1336                                 goto error;
1337                         }
1338                 }
1339
1340                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1341                                 cur_offset, cur_offset + num_bytes - 1,
1342                                 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1343                                 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1344                                 EXTENT_SET_PRIVATE2);
1345                 cur_offset = extent_end;
1346                 if (cur_offset > end)
1347                         break;
1348         }
1349         btrfs_release_path(path);
1350
1351         if (cur_offset <= end && cow_start == (u64)-1) {
1352                 cow_start = cur_offset;
1353                 cur_offset = end;
1354         }
1355
1356         if (cow_start != (u64)-1) {
1357                 ret = cow_file_range(inode, locked_page, cow_start, end,
1358                                      page_started, nr_written, 1);
1359                 if (ret) {
1360                         btrfs_abort_transaction(trans, root, ret);
1361                         goto error;
1362                 }
1363         }
1364
1365 error:
1366         if (nolock) {
1367                 err = btrfs_end_transaction_nolock(trans, root);
1368         } else {
1369                 err = btrfs_end_transaction(trans, root);
1370         }
1371         if (!ret)
1372                 ret = err;
1373
1374         if (ret && cur_offset < end)
1375                 extent_clear_unlock_delalloc(inode,
1376                              &BTRFS_I(inode)->io_tree,
1377                              cur_offset, end, locked_page,
1378                              EXTENT_CLEAR_UNLOCK_PAGE |
1379                              EXTENT_CLEAR_UNLOCK |
1380                              EXTENT_CLEAR_DELALLOC |
1381                              EXTENT_CLEAR_DIRTY |
1382                              EXTENT_SET_WRITEBACK |
1383                              EXTENT_END_WRITEBACK);
1384
1385         btrfs_free_path(path);
1386         return ret;
1387 }
1388
1389 /*
1390  * extent_io.c call back to do delayed allocation processing
1391  */
1392 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1393                               u64 start, u64 end, int *page_started,
1394                               unsigned long *nr_written)
1395 {
1396         int ret;
1397         struct btrfs_root *root = BTRFS_I(inode)->root;
1398
1399         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1400                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1401                                          page_started, 1, nr_written);
1402         } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1403                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1404                                          page_started, 0, nr_written);
1405         } else if (!btrfs_test_opt(root, COMPRESS) &&
1406                    !(BTRFS_I(inode)->force_compress) &&
1407                    !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1408                 ret = cow_file_range(inode, locked_page, start, end,
1409                                       page_started, nr_written, 1);
1410         } else {
1411                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1412                         &BTRFS_I(inode)->runtime_flags);
1413                 ret = cow_file_range_async(inode, locked_page, start, end,
1414                                            page_started, nr_written);
1415         }
1416         return ret;
1417 }
1418
1419 static void btrfs_split_extent_hook(struct inode *inode,
1420                                     struct extent_state *orig, u64 split)
1421 {
1422         /* not delalloc, ignore it */
1423         if (!(orig->state & EXTENT_DELALLOC))
1424                 return;
1425
1426         spin_lock(&BTRFS_I(inode)->lock);
1427         BTRFS_I(inode)->outstanding_extents++;
1428         spin_unlock(&BTRFS_I(inode)->lock);
1429 }
1430
1431 /*
1432  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1433  * extents so we can keep track of new extents that are just merged onto old
1434  * extents, such as when we are doing sequential writes, so we can properly
1435  * account for the metadata space we'll need.
1436  */
1437 static void btrfs_merge_extent_hook(struct inode *inode,
1438                                     struct extent_state *new,
1439                                     struct extent_state *other)
1440 {
1441         /* not delalloc, ignore it */
1442         if (!(other->state & EXTENT_DELALLOC))
1443                 return;
1444
1445         spin_lock(&BTRFS_I(inode)->lock);
1446         BTRFS_I(inode)->outstanding_extents--;
1447         spin_unlock(&BTRFS_I(inode)->lock);
1448 }
1449
1450 /*
1451  * extent_io.c set_bit_hook, used to track delayed allocation
1452  * bytes in this file, and to maintain the list of inodes that
1453  * have pending delalloc work to be done.
1454  */
1455 static void btrfs_set_bit_hook(struct inode *inode,
1456                                struct extent_state *state, int *bits)
1457 {
1458
1459         /*
1460          * set_bit and clear bit hooks normally require _irqsave/restore
1461          * but in this case, we are only testing for the DELALLOC
1462          * bit, which is only set or cleared with irqs on
1463          */
1464         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1465                 struct btrfs_root *root = BTRFS_I(inode)->root;
1466                 u64 len = state->end + 1 - state->start;
1467                 bool do_list = !btrfs_is_free_space_inode(inode);
1468
1469                 if (*bits & EXTENT_FIRST_DELALLOC) {
1470                         *bits &= ~EXTENT_FIRST_DELALLOC;
1471                 } else {
1472                         spin_lock(&BTRFS_I(inode)->lock);
1473                         BTRFS_I(inode)->outstanding_extents++;
1474                         spin_unlock(&BTRFS_I(inode)->lock);
1475                 }
1476
1477                 spin_lock(&root->fs_info->delalloc_lock);
1478                 BTRFS_I(inode)->delalloc_bytes += len;
1479                 root->fs_info->delalloc_bytes += len;
1480                 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1481                         list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1482                                       &root->fs_info->delalloc_inodes);
1483                 }
1484                 spin_unlock(&root->fs_info->delalloc_lock);
1485         }
1486 }
1487
1488 /*
1489  * extent_io.c clear_bit_hook, see set_bit_hook for why
1490  */
1491 static void btrfs_clear_bit_hook(struct inode *inode,
1492                                  struct extent_state *state, int *bits)
1493 {
1494         /*
1495          * set_bit and clear bit hooks normally require _irqsave/restore
1496          * but in this case, we are only testing for the DELALLOC
1497          * bit, which is only set or cleared with irqs on
1498          */
1499         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1500                 struct btrfs_root *root = BTRFS_I(inode)->root;
1501                 u64 len = state->end + 1 - state->start;
1502                 bool do_list = !btrfs_is_free_space_inode(inode);
1503
1504                 if (*bits & EXTENT_FIRST_DELALLOC) {
1505                         *bits &= ~EXTENT_FIRST_DELALLOC;
1506                 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1507                         spin_lock(&BTRFS_I(inode)->lock);
1508                         BTRFS_I(inode)->outstanding_extents--;
1509                         spin_unlock(&BTRFS_I(inode)->lock);
1510                 }
1511
1512                 if (*bits & EXTENT_DO_ACCOUNTING)
1513                         btrfs_delalloc_release_metadata(inode, len);
1514
1515                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1516                     && do_list)
1517                         btrfs_free_reserved_data_space(inode, len);
1518
1519                 spin_lock(&root->fs_info->delalloc_lock);
1520                 root->fs_info->delalloc_bytes -= len;
1521                 BTRFS_I(inode)->delalloc_bytes -= len;
1522
1523                 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1524                     !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1525                         list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1526                 }
1527                 spin_unlock(&root->fs_info->delalloc_lock);
1528         }
1529 }
1530
1531 /*
1532  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1533  * we don't create bios that span stripes or chunks
1534  */
1535 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1536                          size_t size, struct bio *bio,
1537                          unsigned long bio_flags)
1538 {
1539         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1540         struct btrfs_mapping_tree *map_tree;
1541         u64 logical = (u64)bio->bi_sector << 9;
1542         u64 length = 0;
1543         u64 map_length;
1544         int ret;
1545
1546         if (bio_flags & EXTENT_BIO_COMPRESSED)
1547                 return 0;
1548
1549         length = bio->bi_size;
1550         map_tree = &root->fs_info->mapping_tree;
1551         map_length = length;
1552         ret = btrfs_map_block(map_tree, READ, logical,
1553                               &map_length, NULL, 0);
1554         /* Will always return 0 or 1 with map_multi == NULL */
1555         BUG_ON(ret < 0);
1556         if (map_length < length + size)
1557                 return 1;
1558         return 0;
1559 }
1560
1561 /*
1562  * in order to insert checksums into the metadata in large chunks,
1563  * we wait until bio submission time.   All the pages in the bio are
1564  * checksummed and sums are attached onto the ordered extent record.
1565  *
1566  * At IO completion time the cums attached on the ordered extent record
1567  * are inserted into the btree
1568  */
1569 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1570                                     struct bio *bio, int mirror_num,
1571                                     unsigned long bio_flags,
1572                                     u64 bio_offset)
1573 {
1574         struct btrfs_root *root = BTRFS_I(inode)->root;
1575         int ret = 0;
1576
1577         ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1578         BUG_ON(ret); /* -ENOMEM */
1579         return 0;
1580 }
1581
1582 /*
1583  * in order to insert checksums into the metadata in large chunks,
1584  * we wait until bio submission time.   All the pages in the bio are
1585  * checksummed and sums are attached onto the ordered extent record.
1586  *
1587  * At IO completion time the cums attached on the ordered extent record
1588  * are inserted into the btree
1589  */
1590 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1591                           int mirror_num, unsigned long bio_flags,
1592                           u64 bio_offset)
1593 {
1594         struct btrfs_root *root = BTRFS_I(inode)->root;
1595         return btrfs_map_bio(root, rw, bio, mirror_num, 1);
1596 }
1597
1598 /*
1599  * extent_io.c submission hook. This does the right thing for csum calculation
1600  * on write, or reading the csums from the tree before a read
1601  */
1602 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1603                           int mirror_num, unsigned long bio_flags,
1604                           u64 bio_offset)
1605 {
1606         struct btrfs_root *root = BTRFS_I(inode)->root;
1607         int ret = 0;
1608         int skip_sum;
1609         int metadata = 0;
1610
1611         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1612
1613         if (btrfs_is_free_space_inode(inode))
1614                 metadata = 2;
1615
1616         if (!(rw & REQ_WRITE)) {
1617                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1618                 if (ret)
1619                         return ret;
1620
1621                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1622                         return btrfs_submit_compressed_read(inode, bio,
1623                                                     mirror_num, bio_flags);
1624                 } else if (!skip_sum) {
1625                         ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1626                         if (ret)
1627                                 return ret;
1628                 }
1629                 goto mapit;
1630         } else if (!skip_sum) {
1631                 /* csum items have already been cloned */
1632                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1633                         goto mapit;
1634                 /* we're doing a write, do the async checksumming */
1635                 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1636                                    inode, rw, bio, mirror_num,
1637                                    bio_flags, bio_offset,
1638                                    __btrfs_submit_bio_start,
1639                                    __btrfs_submit_bio_done);
1640         }
1641
1642 mapit:
1643         return btrfs_map_bio(root, rw, bio, mirror_num, 0);
1644 }
1645
1646 /*
1647  * given a list of ordered sums record them in the inode.  This happens
1648  * at IO completion time based on sums calculated at bio submission time.
1649  */
1650 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1651                              struct inode *inode, u64 file_offset,
1652                              struct list_head *list)
1653 {
1654         struct btrfs_ordered_sum *sum;
1655
1656         list_for_each_entry(sum, list, list) {
1657                 btrfs_csum_file_blocks(trans,
1658                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
1659         }
1660         return 0;
1661 }
1662
1663 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1664                               struct extent_state **cached_state)
1665 {
1666         if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
1667                 WARN_ON(1);
1668         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1669                                    cached_state, GFP_NOFS);
1670 }
1671
1672 /* see btrfs_writepage_start_hook for details on why this is required */
1673 struct btrfs_writepage_fixup {
1674         struct page *page;
1675         struct btrfs_work work;
1676 };
1677
1678 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1679 {
1680         struct btrfs_writepage_fixup *fixup;
1681         struct btrfs_ordered_extent *ordered;
1682         struct extent_state *cached_state = NULL;
1683         struct page *page;
1684         struct inode *inode;
1685         u64 page_start;
1686         u64 page_end;
1687         int ret;
1688
1689         fixup = container_of(work, struct btrfs_writepage_fixup, work);
1690         page = fixup->page;
1691 again:
1692         lock_page(page);
1693         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1694                 ClearPageChecked(page);
1695                 goto out_page;
1696         }
1697
1698         inode = page->mapping->host;
1699         page_start = page_offset(page);
1700         page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1701
1702         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1703                          &cached_state);
1704
1705         /* already ordered? We're done */
1706         if (PagePrivate2(page))
1707                 goto out;
1708
1709         ordered = btrfs_lookup_ordered_extent(inode, page_start);
1710         if (ordered) {
1711                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1712                                      page_end, &cached_state, GFP_NOFS);
1713                 unlock_page(page);
1714                 btrfs_start_ordered_extent(inode, ordered, 1);
1715                 btrfs_put_ordered_extent(ordered);
1716                 goto again;
1717         }
1718
1719         ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1720         if (ret) {
1721                 mapping_set_error(page->mapping, ret);
1722                 end_extent_writepage(page, ret, page_start, page_end);
1723                 ClearPageChecked(page);
1724                 goto out;
1725          }
1726
1727         btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1728         ClearPageChecked(page);
1729         set_page_dirty(page);
1730 out:
1731         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1732                              &cached_state, GFP_NOFS);
1733 out_page:
1734         unlock_page(page);
1735         page_cache_release(page);
1736         kfree(fixup);
1737 }
1738
1739 /*
1740  * There are a few paths in the higher layers of the kernel that directly
1741  * set the page dirty bit without asking the filesystem if it is a
1742  * good idea.  This causes problems because we want to make sure COW
1743  * properly happens and the data=ordered rules are followed.
1744  *
1745  * In our case any range that doesn't have the ORDERED bit set
1746  * hasn't been properly setup for IO.  We kick off an async process
1747  * to fix it up.  The async helper will wait for ordered extents, set
1748  * the delalloc bit and make it safe to write the page.
1749  */
1750 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1751 {
1752         struct inode *inode = page->mapping->host;
1753         struct btrfs_writepage_fixup *fixup;
1754         struct btrfs_root *root = BTRFS_I(inode)->root;
1755
1756         /* this page is properly in the ordered list */
1757         if (TestClearPagePrivate2(page))
1758                 return 0;
1759
1760         if (PageChecked(page))
1761                 return -EAGAIN;
1762
1763         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1764         if (!fixup)
1765                 return -EAGAIN;
1766
1767         SetPageChecked(page);
1768         page_cache_get(page);
1769         fixup->work.func = btrfs_writepage_fixup_worker;
1770         fixup->page = page;
1771         btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1772         return -EBUSY;
1773 }
1774
1775 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1776                                        struct inode *inode, u64 file_pos,
1777                                        u64 disk_bytenr, u64 disk_num_bytes,
1778                                        u64 num_bytes, u64 ram_bytes,
1779                                        u8 compression, u8 encryption,
1780                                        u16 other_encoding, int extent_type)
1781 {
1782         struct btrfs_root *root = BTRFS_I(inode)->root;
1783         struct btrfs_file_extent_item *fi;
1784         struct btrfs_path *path;
1785         struct extent_buffer *leaf;
1786         struct btrfs_key ins;
1787         u64 hint;
1788         int ret;
1789
1790         path = btrfs_alloc_path();
1791         if (!path)
1792                 return -ENOMEM;
1793
1794         path->leave_spinning = 1;
1795
1796         /*
1797          * we may be replacing one extent in the tree with another.
1798          * The new extent is pinned in the extent map, and we don't want
1799          * to drop it from the cache until it is completely in the btree.
1800          *
1801          * So, tell btrfs_drop_extents to leave this extent in the cache.
1802          * the caller is expected to unpin it and allow it to be merged
1803          * with the others.
1804          */
1805         ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1806                                  &hint, 0);
1807         if (ret)
1808                 goto out;
1809
1810         ins.objectid = btrfs_ino(inode);
1811         ins.offset = file_pos;
1812         ins.type = BTRFS_EXTENT_DATA_KEY;
1813         ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1814         if (ret)
1815                 goto out;
1816         leaf = path->nodes[0];
1817         fi = btrfs_item_ptr(leaf, path->slots[0],
1818                             struct btrfs_file_extent_item);
1819         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1820         btrfs_set_file_extent_type(leaf, fi, extent_type);
1821         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1822         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1823         btrfs_set_file_extent_offset(leaf, fi, 0);
1824         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1825         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1826         btrfs_set_file_extent_compression(leaf, fi, compression);
1827         btrfs_set_file_extent_encryption(leaf, fi, encryption);
1828         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1829
1830         btrfs_unlock_up_safe(path, 1);
1831         btrfs_set_lock_blocking(leaf);
1832
1833         btrfs_mark_buffer_dirty(leaf);
1834
1835         inode_add_bytes(inode, num_bytes);
1836
1837         ins.objectid = disk_bytenr;
1838         ins.offset = disk_num_bytes;
1839         ins.type = BTRFS_EXTENT_ITEM_KEY;
1840         ret = btrfs_alloc_reserved_file_extent(trans, root,
1841                                         root->root_key.objectid,
1842                                         btrfs_ino(inode), file_pos, &ins);
1843 out:
1844         btrfs_free_path(path);
1845
1846         return ret;
1847 }
1848
1849 /*
1850  * helper function for btrfs_finish_ordered_io, this
1851  * just reads in some of the csum leaves to prime them into ram
1852  * before we start the transaction.  It limits the amount of btree
1853  * reads required while inside the transaction.
1854  */
1855 /* as ordered data IO finishes, this gets called so we can finish
1856  * an ordered extent if the range of bytes in the file it covers are
1857  * fully written.
1858  */
1859 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
1860 {
1861         struct inode *inode = ordered_extent->inode;
1862         struct btrfs_root *root = BTRFS_I(inode)->root;
1863         struct btrfs_trans_handle *trans = NULL;
1864         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1865         struct extent_state *cached_state = NULL;
1866         int compress_type = 0;
1867         int ret;
1868         bool nolock;
1869
1870         nolock = btrfs_is_free_space_inode(inode);
1871
1872         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
1873                 ret = -EIO;
1874                 goto out;
1875         }
1876
1877         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1878                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
1879                 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1880                 if (!ret) {
1881                         if (nolock)
1882                                 trans = btrfs_join_transaction_nolock(root);
1883                         else
1884                                 trans = btrfs_join_transaction(root);
1885                         if (IS_ERR(trans))
1886                                 return PTR_ERR(trans);
1887                         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1888                         ret = btrfs_update_inode_fallback(trans, root, inode);
1889                         if (ret) /* -ENOMEM or corruption */
1890                                 btrfs_abort_transaction(trans, root, ret);
1891                 }
1892                 goto out;
1893         }
1894
1895         lock_extent_bits(io_tree, ordered_extent->file_offset,
1896                          ordered_extent->file_offset + ordered_extent->len - 1,
1897                          0, &cached_state);
1898
1899         if (nolock)
1900                 trans = btrfs_join_transaction_nolock(root);
1901         else
1902                 trans = btrfs_join_transaction(root);
1903         if (IS_ERR(trans)) {
1904                 ret = PTR_ERR(trans);
1905                 trans = NULL;
1906                 goto out_unlock;
1907         }
1908         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1909
1910         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1911                 compress_type = ordered_extent->compress_type;
1912         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1913                 BUG_ON(compress_type);
1914                 ret = btrfs_mark_extent_written(trans, inode,
1915                                                 ordered_extent->file_offset,
1916                                                 ordered_extent->file_offset +
1917                                                 ordered_extent->len);
1918         } else {
1919                 BUG_ON(root == root->fs_info->tree_root);
1920                 ret = insert_reserved_file_extent(trans, inode,
1921                                                 ordered_extent->file_offset,
1922                                                 ordered_extent->start,
1923                                                 ordered_extent->disk_len,
1924                                                 ordered_extent->len,
1925                                                 ordered_extent->len,
1926                                                 compress_type, 0, 0,
1927                                                 BTRFS_FILE_EXTENT_REG);
1928                 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1929                                    ordered_extent->file_offset,
1930                                    ordered_extent->len);
1931         }
1932
1933         if (ret < 0) {
1934                 btrfs_abort_transaction(trans, root, ret);
1935                 goto out_unlock;
1936         }
1937
1938         add_pending_csums(trans, inode, ordered_extent->file_offset,
1939                           &ordered_extent->list);
1940
1941         ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1942         if (!ret || !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1943                 ret = btrfs_update_inode_fallback(trans, root, inode);
1944                 if (ret) { /* -ENOMEM or corruption */
1945                         btrfs_abort_transaction(trans, root, ret);
1946                         goto out_unlock;
1947                 }
1948         }
1949         ret = 0;
1950 out_unlock:
1951         unlock_extent_cached(io_tree, ordered_extent->file_offset,
1952                              ordered_extent->file_offset +
1953                              ordered_extent->len - 1, &cached_state, GFP_NOFS);
1954 out:
1955         if (root != root->fs_info->tree_root)
1956                 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1957         if (trans) {
1958                 if (nolock)
1959                         btrfs_end_transaction_nolock(trans, root);
1960                 else
1961                         btrfs_end_transaction(trans, root);
1962         }
1963
1964         if (ret)
1965                 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
1966                                       ordered_extent->file_offset +
1967                                       ordered_extent->len - 1, NULL, GFP_NOFS);
1968
1969         /*
1970          * This needs to be dont to make sure anybody waiting knows we are done
1971          * upating everything for this ordered extent.
1972          */
1973         btrfs_remove_ordered_extent(inode, ordered_extent);
1974
1975         /* once for us */
1976         btrfs_put_ordered_extent(ordered_extent);
1977         /* once for the tree */
1978         btrfs_put_ordered_extent(ordered_extent);
1979
1980         return ret;
1981 }
1982
1983 static void finish_ordered_fn(struct btrfs_work *work)
1984 {
1985         struct btrfs_ordered_extent *ordered_extent;
1986         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
1987         btrfs_finish_ordered_io(ordered_extent);
1988 }
1989
1990 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1991                                 struct extent_state *state, int uptodate)
1992 {
1993         struct inode *inode = page->mapping->host;
1994         struct btrfs_root *root = BTRFS_I(inode)->root;
1995         struct btrfs_ordered_extent *ordered_extent = NULL;
1996         struct btrfs_workers *workers;
1997
1998         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
1999
2000         ClearPagePrivate2(page);
2001         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2002                                             end - start + 1, uptodate))
2003                 return 0;
2004
2005         ordered_extent->work.func = finish_ordered_fn;
2006         ordered_extent->work.flags = 0;
2007
2008         if (btrfs_is_free_space_inode(inode))
2009                 workers = &root->fs_info->endio_freespace_worker;
2010         else
2011                 workers = &root->fs_info->endio_write_workers;
2012         btrfs_queue_worker(workers, &ordered_extent->work);
2013
2014         return 0;
2015 }
2016
2017 /*
2018  * when reads are done, we need to check csums to verify the data is correct
2019  * if there's a match, we allow the bio to finish.  If not, the code in
2020  * extent_io.c will try to find good copies for us.
2021  */
2022 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2023                                struct extent_state *state, int mirror)
2024 {
2025         size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
2026         struct inode *inode = page->mapping->host;
2027         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2028         char *kaddr;
2029         u64 private = ~(u32)0;
2030         int ret;
2031         struct btrfs_root *root = BTRFS_I(inode)->root;
2032         u32 csum = ~(u32)0;
2033
2034         if (PageChecked(page)) {
2035                 ClearPageChecked(page);
2036                 goto good;
2037         }
2038
2039         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2040                 goto good;
2041
2042         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2043             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2044                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2045                                   GFP_NOFS);
2046                 return 0;
2047         }
2048
2049         if (state && state->start == start) {
2050                 private = state->private;
2051                 ret = 0;
2052         } else {
2053                 ret = get_state_private(io_tree, start, &private);
2054         }
2055         kaddr = kmap_atomic(page);
2056         if (ret)
2057                 goto zeroit;
2058
2059         csum = btrfs_csum_data(root, kaddr + offset, csum,  end - start + 1);
2060         btrfs_csum_final(csum, (char *)&csum);
2061         if (csum != private)
2062                 goto zeroit;
2063
2064         kunmap_atomic(kaddr);
2065 good:
2066         return 0;
2067
2068 zeroit:
2069         printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
2070                        "private %llu\n",
2071                        (unsigned long long)btrfs_ino(page->mapping->host),
2072                        (unsigned long long)start, csum,
2073                        (unsigned long long)private);
2074         memset(kaddr + offset, 1, end - start + 1);
2075         flush_dcache_page(page);
2076         kunmap_atomic(kaddr);
2077         if (private == 0)
2078                 return 0;
2079         return -EIO;
2080 }
2081
2082 struct delayed_iput {
2083         struct list_head list;
2084         struct inode *inode;
2085 };
2086
2087 /* JDM: If this is fs-wide, why can't we add a pointer to
2088  * btrfs_inode instead and avoid the allocation? */
2089 void btrfs_add_delayed_iput(struct inode *inode)
2090 {
2091         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2092         struct delayed_iput *delayed;
2093
2094         if (atomic_add_unless(&inode->i_count, -1, 1))
2095                 return;
2096
2097         delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2098         delayed->inode = inode;
2099
2100         spin_lock(&fs_info->delayed_iput_lock);
2101         list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2102         spin_unlock(&fs_info->delayed_iput_lock);
2103 }
2104
2105 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2106 {
2107         LIST_HEAD(list);
2108         struct btrfs_fs_info *fs_info = root->fs_info;
2109         struct delayed_iput *delayed;
2110         int empty;
2111
2112         spin_lock(&fs_info->delayed_iput_lock);
2113         empty = list_empty(&fs_info->delayed_iputs);
2114         spin_unlock(&fs_info->delayed_iput_lock);
2115         if (empty)
2116                 return;
2117
2118         down_read(&root->fs_info->cleanup_work_sem);
2119         spin_lock(&fs_info->delayed_iput_lock);
2120         list_splice_init(&fs_info->delayed_iputs, &list);
2121         spin_unlock(&fs_info->delayed_iput_lock);
2122
2123         while (!list_empty(&list)) {
2124                 delayed = list_entry(list.next, struct delayed_iput, list);
2125                 list_del(&delayed->list);
2126                 iput(delayed->inode);
2127                 kfree(delayed);
2128         }
2129         up_read(&root->fs_info->cleanup_work_sem);
2130 }
2131
2132 enum btrfs_orphan_cleanup_state {
2133         ORPHAN_CLEANUP_STARTED  = 1,
2134         ORPHAN_CLEANUP_DONE     = 2,
2135 };
2136
2137 /*
2138  * This is called in transaction commit time. If there are no orphan
2139  * files in the subvolume, it removes orphan item and frees block_rsv
2140  * structure.
2141  */
2142 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2143                               struct btrfs_root *root)
2144 {
2145         struct btrfs_block_rsv *block_rsv;
2146         int ret;
2147
2148         if (atomic_read(&root->orphan_inodes) ||
2149             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2150                 return;
2151
2152         spin_lock(&root->orphan_lock);
2153         if (atomic_read(&root->orphan_inodes)) {
2154                 spin_unlock(&root->orphan_lock);
2155                 return;
2156         }
2157
2158         if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2159                 spin_unlock(&root->orphan_lock);
2160                 return;
2161         }
2162
2163         block_rsv = root->orphan_block_rsv;
2164         root->orphan_block_rsv = NULL;
2165         spin_unlock(&root->orphan_lock);
2166
2167         if (root->orphan_item_inserted &&
2168             btrfs_root_refs(&root->root_item) > 0) {
2169                 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2170                                             root->root_key.objectid);
2171                 BUG_ON(ret);
2172                 root->orphan_item_inserted = 0;
2173         }
2174
2175         if (block_rsv) {
2176                 WARN_ON(block_rsv->size > 0);
2177                 btrfs_free_block_rsv(root, block_rsv);
2178         }
2179 }
2180
2181 /*
2182  * This creates an orphan entry for the given inode in case something goes
2183  * wrong in the middle of an unlink/truncate.
2184  *
2185  * NOTE: caller of this function should reserve 5 units of metadata for
2186  *       this function.
2187  */
2188 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2189 {
2190         struct btrfs_root *root = BTRFS_I(inode)->root;
2191         struct btrfs_block_rsv *block_rsv = NULL;
2192         int reserve = 0;
2193         int insert = 0;
2194         int ret;
2195
2196         if (!root->orphan_block_rsv) {
2197                 block_rsv = btrfs_alloc_block_rsv(root);
2198                 if (!block_rsv)
2199                         return -ENOMEM;
2200         }
2201
2202         spin_lock(&root->orphan_lock);
2203         if (!root->orphan_block_rsv) {
2204                 root->orphan_block_rsv = block_rsv;
2205         } else if (block_rsv) {
2206                 btrfs_free_block_rsv(root, block_rsv);
2207                 block_rsv = NULL;
2208         }
2209
2210         if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2211                               &BTRFS_I(inode)->runtime_flags)) {
2212 #if 0
2213                 /*
2214                  * For proper ENOSPC handling, we should do orphan
2215                  * cleanup when mounting. But this introduces backward
2216                  * compatibility issue.
2217                  */
2218                 if (!xchg(&root->orphan_item_inserted, 1))
2219                         insert = 2;
2220                 else
2221                         insert = 1;
2222 #endif
2223                 insert = 1;
2224                 atomic_dec(&root->orphan_inodes);
2225         }
2226
2227         if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2228                               &BTRFS_I(inode)->runtime_flags))
2229                 reserve = 1;
2230         spin_unlock(&root->orphan_lock);
2231
2232         /* grab metadata reservation from transaction handle */
2233         if (reserve) {
2234                 ret = btrfs_orphan_reserve_metadata(trans, inode);
2235                 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2236         }
2237
2238         /* insert an orphan item to track this unlinked/truncated file */
2239         if (insert >= 1) {
2240                 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2241                 if (ret && ret != -EEXIST) {
2242                         clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2243                                   &BTRFS_I(inode)->runtime_flags);
2244                         btrfs_abort_transaction(trans, root, ret);
2245                         return ret;
2246                 }
2247                 ret = 0;
2248         }
2249
2250         /* insert an orphan item to track subvolume contains orphan files */
2251         if (insert >= 2) {
2252                 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2253                                                root->root_key.objectid);
2254                 if (ret && ret != -EEXIST) {
2255                         btrfs_abort_transaction(trans, root, ret);
2256                         return ret;
2257                 }
2258         }
2259         return 0;
2260 }
2261
2262 /*
2263  * We have done the truncate/delete so we can go ahead and remove the orphan
2264  * item for this particular inode.
2265  */
2266 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2267 {
2268         struct btrfs_root *root = BTRFS_I(inode)->root;
2269         int delete_item = 0;
2270         int release_rsv = 0;
2271         int ret = 0;
2272
2273         spin_lock(&root->orphan_lock);
2274         if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2275                                &BTRFS_I(inode)->runtime_flags))
2276                 delete_item = 1;
2277
2278         if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2279                                &BTRFS_I(inode)->runtime_flags))
2280                 release_rsv = 1;
2281         spin_unlock(&root->orphan_lock);
2282
2283         if (trans && delete_item) {
2284                 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
2285                 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2286         }
2287
2288         if (release_rsv) {
2289                 btrfs_orphan_release_metadata(inode);
2290                 atomic_dec(&root->orphan_inodes);
2291         }
2292
2293         return 0;
2294 }
2295
2296 /*
2297  * this cleans up any orphans that may be left on the list from the last use
2298  * of this root.
2299  */
2300 int btrfs_orphan_cleanup(struct btrfs_root *root)
2301 {
2302         struct btrfs_path *path;
2303         struct extent_buffer *leaf;
2304         struct btrfs_key key, found_key;
2305         struct btrfs_trans_handle *trans;
2306         struct inode *inode;
2307         u64 last_objectid = 0;
2308         int ret = 0, nr_unlink = 0, nr_truncate = 0;
2309
2310         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2311                 return 0;
2312
2313         path = btrfs_alloc_path();
2314         if (!path) {
2315                 ret = -ENOMEM;
2316                 goto out;
2317         }
2318         path->reada = -1;
2319
2320         key.objectid = BTRFS_ORPHAN_OBJECTID;
2321         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2322         key.offset = (u64)-1;
2323
2324         while (1) {
2325                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2326                 if (ret < 0)
2327                         goto out;
2328
2329                 /*
2330                  * if ret == 0 means we found what we were searching for, which
2331                  * is weird, but possible, so only screw with path if we didn't
2332                  * find the key and see if we have stuff that matches
2333                  */
2334                 if (ret > 0) {
2335                         ret = 0;
2336                         if (path->slots[0] == 0)
2337                                 break;
2338                         path->slots[0]--;
2339                 }
2340
2341                 /* pull out the item */
2342                 leaf = path->nodes[0];
2343                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2344
2345                 /* make sure the item matches what we want */
2346                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2347                         break;
2348                 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2349                         break;
2350
2351                 /* release the path since we're done with it */
2352                 btrfs_release_path(path);
2353
2354                 /*
2355                  * this is where we are basically btrfs_lookup, without the
2356                  * crossing root thing.  we store the inode number in the
2357                  * offset of the orphan item.
2358                  */
2359
2360                 if (found_key.offset == last_objectid) {
2361                         printk(KERN_ERR "btrfs: Error removing orphan entry, "
2362                                "stopping orphan cleanup\n");
2363                         ret = -EINVAL;
2364                         goto out;
2365                 }
2366
2367                 last_objectid = found_key.offset;
2368
2369                 found_key.objectid = found_key.offset;
2370                 found_key.type = BTRFS_INODE_ITEM_KEY;
2371                 found_key.offset = 0;
2372                 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2373                 ret = PTR_RET(inode);
2374                 if (ret && ret != -ESTALE)
2375                         goto out;
2376
2377                 if (ret == -ESTALE && root == root->fs_info->tree_root) {
2378                         struct btrfs_root *dead_root;
2379                         struct btrfs_fs_info *fs_info = root->fs_info;
2380                         int is_dead_root = 0;
2381
2382                         /*
2383                          * this is an orphan in the tree root. Currently these
2384                          * could come from 2 sources:
2385                          *  a) a snapshot deletion in progress
2386                          *  b) a free space cache inode
2387                          * We need to distinguish those two, as the snapshot
2388                          * orphan must not get deleted.
2389                          * find_dead_roots already ran before us, so if this
2390                          * is a snapshot deletion, we should find the root
2391                          * in the dead_roots list
2392                          */
2393                         spin_lock(&fs_info->trans_lock);
2394                         list_for_each_entry(dead_root, &fs_info->dead_roots,
2395                                             root_list) {
2396                                 if (dead_root->root_key.objectid ==
2397                                     found_key.objectid) {
2398                                         is_dead_root = 1;
2399                                         break;
2400                                 }
2401                         }
2402                         spin_unlock(&fs_info->trans_lock);
2403                         if (is_dead_root) {
2404                                 /* prevent this orphan from being found again */
2405                                 key.offset = found_key.objectid - 1;
2406                                 continue;
2407                         }
2408                 }
2409                 /*
2410                  * Inode is already gone but the orphan item is still there,
2411                  * kill the orphan item.
2412                  */
2413                 if (ret == -ESTALE) {
2414                         trans = btrfs_start_transaction(root, 1);
2415                         if (IS_ERR(trans)) {
2416                                 ret = PTR_ERR(trans);
2417                                 goto out;
2418                         }
2419                         printk(KERN_ERR "auto deleting %Lu\n",
2420                                found_key.objectid);
2421                         ret = btrfs_del_orphan_item(trans, root,
2422                                                     found_key.objectid);
2423                         BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2424                         btrfs_end_transaction(trans, root);
2425                         continue;
2426                 }
2427
2428                 /*
2429                  * add this inode to the orphan list so btrfs_orphan_del does
2430                  * the proper thing when we hit it
2431                  */
2432                 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2433                         &BTRFS_I(inode)->runtime_flags);
2434
2435                 /* if we have links, this was a truncate, lets do that */
2436                 if (inode->i_nlink) {
2437                         if (!S_ISREG(inode->i_mode)) {
2438                                 WARN_ON(1);
2439                                 iput(inode);
2440                                 continue;
2441                         }
2442                         nr_truncate++;
2443                         ret = btrfs_truncate(inode);
2444                 } else {
2445                         nr_unlink++;
2446                 }
2447
2448                 /* this will do delete_inode and everything for us */
2449                 iput(inode);
2450                 if (ret)
2451                         goto out;
2452         }
2453         /* release the path since we're done with it */
2454         btrfs_release_path(path);
2455
2456         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2457
2458         if (root->orphan_block_rsv)
2459                 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2460                                         (u64)-1);
2461
2462         if (root->orphan_block_rsv || root->orphan_item_inserted) {
2463                 trans = btrfs_join_transaction(root);
2464                 if (!IS_ERR(trans))
2465                         btrfs_end_transaction(trans, root);
2466         }
2467
2468         if (nr_unlink)
2469                 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2470         if (nr_truncate)
2471                 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2472
2473 out:
2474         if (ret)
2475                 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2476         btrfs_free_path(path);
2477         return ret;
2478 }
2479
2480 /*
2481  * very simple check to peek ahead in the leaf looking for xattrs.  If we
2482  * don't find any xattrs, we know there can't be any acls.
2483  *
2484  * slot is the slot the inode is in, objectid is the objectid of the inode
2485  */
2486 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2487                                           int slot, u64 objectid)
2488 {
2489         u32 nritems = btrfs_header_nritems(leaf);
2490         struct btrfs_key found_key;
2491         int scanned = 0;
2492
2493         slot++;
2494         while (slot < nritems) {
2495                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2496
2497                 /* we found a different objectid, there must not be acls */
2498                 if (found_key.objectid != objectid)
2499                         return 0;
2500
2501                 /* we found an xattr, assume we've got an acl */
2502                 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2503                         return 1;
2504
2505                 /*
2506                  * we found a key greater than an xattr key, there can't
2507                  * be any acls later on
2508                  */
2509                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2510                         return 0;
2511
2512                 slot++;
2513                 scanned++;
2514
2515                 /*
2516                  * it goes inode, inode backrefs, xattrs, extents,
2517                  * so if there are a ton of hard links to an inode there can
2518                  * be a lot of backrefs.  Don't waste time searching too hard,
2519                  * this is just an optimization
2520                  */
2521                 if (scanned >= 8)
2522                         break;
2523         }
2524         /* we hit the end of the leaf before we found an xattr or
2525          * something larger than an xattr.  We have to assume the inode
2526          * has acls
2527          */
2528         return 1;
2529 }
2530
2531 /*
2532  * read an inode from the btree into the in-memory inode
2533  */
2534 static void btrfs_read_locked_inode(struct inode *inode)
2535 {
2536         struct btrfs_path *path;
2537         struct extent_buffer *leaf;
2538         struct btrfs_inode_item *inode_item;
2539         struct btrfs_timespec *tspec;
2540         struct btrfs_root *root = BTRFS_I(inode)->root;
2541         struct btrfs_key location;
2542         int maybe_acls;
2543         u32 rdev;
2544         int ret;
2545         bool filled = false;
2546
2547         ret = btrfs_fill_inode(inode, &rdev);
2548         if (!ret)
2549                 filled = true;
2550
2551         path = btrfs_alloc_path();
2552         if (!path)
2553                 goto make_bad;
2554
2555         path->leave_spinning = 1;
2556         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2557
2558         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2559         if (ret)
2560                 goto make_bad;
2561
2562         leaf = path->nodes[0];
2563
2564         if (filled)
2565                 goto cache_acl;
2566
2567         inode_item = btrfs_item_ptr(leaf, path->slots[0],
2568                                     struct btrfs_inode_item);
2569         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2570         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
2571         inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2572         inode->i_gid = btrfs_inode_gid(leaf, inode_item);
2573         btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2574
2575         tspec = btrfs_inode_atime(inode_item);
2576         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2577         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2578
2579         tspec = btrfs_inode_mtime(inode_item);
2580         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2581         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2582
2583         tspec = btrfs_inode_ctime(inode_item);
2584         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2585         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2586
2587         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2588         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2589         inode->i_version = btrfs_inode_sequence(leaf, inode_item);
2590         inode->i_generation = BTRFS_I(inode)->generation;
2591         inode->i_rdev = 0;
2592         rdev = btrfs_inode_rdev(leaf, inode_item);
2593
2594         BTRFS_I(inode)->index_cnt = (u64)-1;
2595         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2596 cache_acl:
2597         /*
2598          * try to precache a NULL acl entry for files that don't have
2599          * any xattrs or acls
2600          */
2601         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
2602                                            btrfs_ino(inode));
2603         if (!maybe_acls)
2604                 cache_no_acl(inode);
2605
2606         btrfs_free_path(path);
2607
2608         switch (inode->i_mode & S_IFMT) {
2609         case S_IFREG:
2610                 inode->i_mapping->a_ops = &btrfs_aops;
2611                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2612                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2613                 inode->i_fop = &btrfs_file_operations;
2614                 inode->i_op = &btrfs_file_inode_operations;
2615                 break;
2616         case S_IFDIR:
2617                 inode->i_fop = &btrfs_dir_file_operations;
2618                 if (root == root->fs_info->tree_root)
2619                         inode->i_op = &btrfs_dir_ro_inode_operations;
2620                 else
2621                         inode->i_op = &btrfs_dir_inode_operations;
2622                 break;
2623         case S_IFLNK:
2624                 inode->i_op = &btrfs_symlink_inode_operations;
2625                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2626                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2627                 break;
2628         default:
2629                 inode->i_op = &btrfs_special_inode_operations;
2630                 init_special_inode(inode, inode->i_mode, rdev);
2631                 break;
2632         }
2633
2634         btrfs_update_iflags(inode);
2635         return;
2636
2637 make_bad:
2638         btrfs_free_path(path);
2639         make_bad_inode(inode);
2640 }
2641
2642 /*
2643  * given a leaf and an inode, copy the inode fields into the leaf
2644  */
2645 static void fill_inode_item(struct btrfs_trans_handle *trans,
2646                             struct extent_buffer *leaf,
2647                             struct btrfs_inode_item *item,
2648                             struct inode *inode)
2649 {
2650         btrfs_set_inode_uid(leaf, item, inode->i_uid);
2651         btrfs_set_inode_gid(leaf, item, inode->i_gid);
2652         btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2653         btrfs_set_inode_mode(leaf, item, inode->i_mode);
2654         btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2655
2656         btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2657                                inode->i_atime.tv_sec);
2658         btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2659                                 inode->i_atime.tv_nsec);
2660
2661         btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2662                                inode->i_mtime.tv_sec);
2663         btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2664                                 inode->i_mtime.tv_nsec);
2665
2666         btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2667                                inode->i_ctime.tv_sec);
2668         btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2669                                 inode->i_ctime.tv_nsec);
2670
2671         btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2672         btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2673         btrfs_set_inode_sequence(leaf, item, inode->i_version);
2674         btrfs_set_inode_transid(leaf, item, trans->transid);
2675         btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2676         btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2677         btrfs_set_inode_block_group(leaf, item, 0);
2678 }
2679
2680 /*
2681  * copy everything in the in-memory inode into the btree.
2682  */
2683 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
2684                                 struct btrfs_root *root, struct inode *inode)
2685 {
2686         struct btrfs_inode_item *inode_item;
2687         struct btrfs_path *path;
2688         struct extent_buffer *leaf;
2689         int ret;
2690
2691         path = btrfs_alloc_path();
2692         if (!path)
2693                 return -ENOMEM;
2694
2695         path->leave_spinning = 1;
2696         ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
2697                                  1);
2698         if (ret) {
2699                 if (ret > 0)
2700                         ret = -ENOENT;
2701                 goto failed;
2702         }
2703
2704         btrfs_unlock_up_safe(path, 1);
2705         leaf = path->nodes[0];
2706         inode_item = btrfs_item_ptr(leaf, path->slots[0],
2707                                     struct btrfs_inode_item);
2708
2709         fill_inode_item(trans, leaf, inode_item, inode);
2710         btrfs_mark_buffer_dirty(leaf);
2711         btrfs_set_inode_last_trans(trans, inode);
2712         ret = 0;
2713 failed:
2714         btrfs_free_path(path);
2715         return ret;
2716 }
2717
2718 /*
2719  * copy everything in the in-memory inode into the btree.
2720  */
2721 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2722                                 struct btrfs_root *root, struct inode *inode)
2723 {
2724         int ret;
2725
2726         /*
2727          * If the inode is a free space inode, we can deadlock during commit
2728          * if we put it into the delayed code.
2729          *
2730          * The data relocation inode should also be directly updated
2731          * without delay
2732          */
2733         if (!btrfs_is_free_space_inode(inode)
2734             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
2735                 btrfs_update_root_times(trans, root);
2736
2737                 ret = btrfs_delayed_update_inode(trans, root, inode);
2738                 if (!ret)
2739                         btrfs_set_inode_last_trans(trans, inode);
2740                 return ret;
2741         }
2742
2743         return btrfs_update_inode_item(trans, root, inode);
2744 }
2745
2746 static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
2747                                 struct btrfs_root *root, struct inode *inode)
2748 {
2749         int ret;
2750
2751         ret = btrfs_update_inode(trans, root, inode);
2752         if (ret == -ENOSPC)
2753                 return btrfs_update_inode_item(trans, root, inode);
2754         return ret;
2755 }
2756
2757 /*
2758  * unlink helper that gets used here in inode.c and in the tree logging
2759  * recovery code.  It remove a link in a directory with a given name, and
2760  * also drops the back refs in the inode to the directory
2761  */
2762 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2763                                 struct btrfs_root *root,
2764                                 struct inode *dir, struct inode *inode,
2765                                 const char *name, int name_len)
2766 {
2767         struct btrfs_path *path;
2768         int ret = 0;
2769         struct extent_buffer *leaf;
2770         struct btrfs_dir_item *di;
2771         struct btrfs_key key;
2772         u64 index;
2773         u64 ino = btrfs_ino(inode);
2774         u64 dir_ino = btrfs_ino(dir);
2775
2776         path = btrfs_alloc_path();
2777         if (!path) {
2778                 ret = -ENOMEM;
2779                 goto out;
2780         }
2781
2782         path->leave_spinning = 1;
2783         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2784                                     name, name_len, -1);
2785         if (IS_ERR(di)) {
2786                 ret = PTR_ERR(di);
2787                 goto err;
2788         }
2789         if (!di) {
2790                 ret = -ENOENT;
2791                 goto err;
2792         }
2793         leaf = path->nodes[0];
2794         btrfs_dir_item_key_to_cpu(leaf, di, &key);
2795         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2796         if (ret)
2797                 goto err;
2798         btrfs_release_path(path);
2799
2800         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
2801                                   dir_ino, &index);
2802         if (ret) {
2803                 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2804                        "inode %llu parent %llu\n", name_len, name,
2805                        (unsigned long long)ino, (unsigned long long)dir_ino);
2806                 btrfs_abort_transaction(trans, root, ret);
2807                 goto err;
2808         }
2809
2810         ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2811         if (ret) {
2812                 btrfs_abort_transaction(trans, root, ret);
2813                 goto err;
2814         }
2815
2816         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2817                                          inode, dir_ino);
2818         if (ret != 0 && ret != -ENOENT) {
2819                 btrfs_abort_transaction(trans, root, ret);
2820                 goto err;
2821         }
2822
2823         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2824                                            dir, index);
2825         if (ret == -ENOENT)
2826                 ret = 0;
2827 err:
2828         btrfs_free_path(path);
2829         if (ret)
2830                 goto out;
2831
2832         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2833         inode_inc_iversion(inode);
2834         inode_inc_iversion(dir);
2835         inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2836         ret = btrfs_update_inode(trans, root, dir);
2837 out:
2838         return ret;
2839 }
2840
2841 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2842                        struct btrfs_root *root,
2843                        struct inode *dir, struct inode *inode,
2844                        const char *name, int name_len)
2845 {
2846         int ret;
2847         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
2848         if (!ret) {
2849                 btrfs_drop_nlink(inode);
2850                 ret = btrfs_update_inode(trans, root, inode);
2851         }
2852         return ret;
2853 }
2854                 
2855
2856 /* helper to check if there is any shared block in the path */
2857 static int check_path_shared(struct btrfs_root *root,
2858                              struct btrfs_path *path)
2859 {
2860         struct extent_buffer *eb;
2861         int level;
2862         u64 refs = 1;
2863
2864         for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2865                 int ret;
2866
2867                 if (!path->nodes[level])
2868                         break;
2869                 eb = path->nodes[level];
2870                 if (!btrfs_block_can_be_shared(root, eb))
2871                         continue;
2872                 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2873                                                &refs, NULL);
2874                 if (refs > 1)
2875                         return 1;
2876         }
2877         return 0;
2878 }
2879
2880 /*
2881  * helper to start transaction for unlink and rmdir.
2882  *
2883  * unlink and rmdir are special in btrfs, they do not always free space.
2884  * so in enospc case, we should make sure they will free space before
2885  * allowing them to use the global metadata reservation.
2886  */
2887 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2888                                                        struct dentry *dentry)
2889 {
2890         struct btrfs_trans_handle *trans;
2891         struct btrfs_root *root = BTRFS_I(dir)->root;
2892         struct btrfs_path *path;
2893         struct btrfs_inode_ref *ref;
2894         struct btrfs_dir_item *di;
2895         struct inode *inode = dentry->d_inode;
2896         u64 index;
2897         int check_link = 1;
2898         int err = -ENOSPC;
2899         int ret;
2900         u64 ino = btrfs_ino(inode);
2901         u64 dir_ino = btrfs_ino(dir);
2902
2903         /*
2904          * 1 for the possible orphan item
2905          * 1 for the dir item
2906          * 1 for the dir index
2907          * 1 for the inode ref
2908          * 1 for the inode ref in the tree log
2909          * 2 for the dir entries in the log
2910          * 1 for the inode
2911          */
2912         trans = btrfs_start_transaction(root, 8);
2913         if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2914                 return trans;
2915
2916         if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2917                 return ERR_PTR(-ENOSPC);
2918
2919         /* check if there is someone else holds reference */
2920         if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2921                 return ERR_PTR(-ENOSPC);
2922
2923         if (atomic_read(&inode->i_count) > 2)
2924                 return ERR_PTR(-ENOSPC);
2925
2926         if (xchg(&root->fs_info->enospc_unlink, 1))
2927                 return ERR_PTR(-ENOSPC);
2928
2929         path = btrfs_alloc_path();
2930         if (!path) {
2931                 root->fs_info->enospc_unlink = 0;
2932                 return ERR_PTR(-ENOMEM);
2933         }
2934
2935         /* 1 for the orphan item */
2936         trans = btrfs_start_transaction(root, 1);
2937         if (IS_ERR(trans)) {
2938                 btrfs_free_path(path);
2939                 root->fs_info->enospc_unlink = 0;
2940                 return trans;
2941         }
2942
2943         path->skip_locking = 1;
2944         path->search_commit_root = 1;
2945
2946         ret = btrfs_lookup_inode(trans, root, path,
2947                                 &BTRFS_I(dir)->location, 0);
2948         if (ret < 0) {
2949                 err = ret;
2950                 goto out;
2951         }
2952         if (ret == 0) {
2953                 if (check_path_shared(root, path))
2954                         goto out;
2955         } else {
2956                 check_link = 0;
2957         }
2958         btrfs_release_path(path);
2959
2960         ret = btrfs_lookup_inode(trans, root, path,
2961                                 &BTRFS_I(inode)->location, 0);
2962         if (ret < 0) {
2963                 err = ret;
2964                 goto out;
2965         }
2966         if (ret == 0) {
2967                 if (check_path_shared(root, path))
2968                         goto out;
2969         } else {
2970                 check_link = 0;
2971         }
2972         btrfs_release_path(path);
2973
2974         if (ret == 0 && S_ISREG(inode->i_mode)) {
2975                 ret = btrfs_lookup_file_extent(trans, root, path,
2976                                                ino, (u64)-1, 0);
2977                 if (ret < 0) {
2978                         err = ret;
2979                         goto out;
2980                 }
2981                 BUG_ON(ret == 0); /* Corruption */
2982                 if (check_path_shared(root, path))
2983                         goto out;
2984                 btrfs_release_path(path);
2985         }
2986
2987         if (!check_link) {
2988                 err = 0;
2989                 goto out;
2990         }
2991
2992         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2993                                 dentry->d_name.name, dentry->d_name.len, 0);
2994         if (IS_ERR(di)) {
2995                 err = PTR_ERR(di);
2996                 goto out;
2997         }
2998         if (di) {
2999                 if (check_path_shared(root, path))
3000                         goto out;
3001         } else {
3002                 err = 0;
3003                 goto out;
3004         }
3005         btrfs_release_path(path);
3006
3007         ref = btrfs_lookup_inode_ref(trans, root, path,
3008                                 dentry->d_name.name, dentry->d_name.len,
3009                                 ino, dir_ino, 0);
3010         if (IS_ERR(ref)) {
3011                 err = PTR_ERR(ref);
3012                 goto out;
3013         }
3014         BUG_ON(!ref); /* Logic error */
3015         if (check_path_shared(root, path))
3016                 goto out;
3017         index = btrfs_inode_ref_index(path->nodes[0], ref);
3018         btrfs_release_path(path);
3019
3020         /*
3021          * This is a commit root search, if we can lookup inode item and other
3022          * relative items in the commit root, it means the transaction of
3023          * dir/file creation has been committed, and the dir index item that we
3024          * delay to insert has also been inserted into the commit root. So
3025          * we needn't worry about the delayed insertion of the dir index item
3026          * here.
3027          */
3028         di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
3029                                 dentry->d_name.name, dentry->d_name.len, 0);
3030         if (IS_ERR(di)) {
3031                 err = PTR_ERR(di);
3032                 goto out;
3033         }
3034         BUG_ON(ret == -ENOENT);
3035         if (check_path_shared(root, path))
3036                 goto out;
3037
3038         err = 0;
3039 out:
3040         btrfs_free_path(path);
3041         /* Migrate the orphan reservation over */
3042         if (!err)
3043                 err = btrfs_block_rsv_migrate(trans->block_rsv,
3044                                 &root->fs_info->global_block_rsv,
3045                                 trans->bytes_reserved);
3046
3047         if (err) {
3048                 btrfs_end_transaction(trans, root);
3049                 root->fs_info->enospc_unlink = 0;
3050                 return ERR_PTR(err);
3051         }
3052
3053         trans->block_rsv = &root->fs_info->global_block_rsv;
3054         return trans;
3055 }
3056
3057 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
3058                                struct btrfs_root *root)
3059 {
3060         if (trans->block_rsv == &root->fs_info->global_block_rsv) {
3061                 btrfs_block_rsv_release(root, trans->block_rsv,
3062                                         trans->bytes_reserved);
3063                 trans->block_rsv = &root->fs_info->trans_block_rsv;
3064                 BUG_ON(!root->fs_info->enospc_unlink);
3065                 root->fs_info->enospc_unlink = 0;
3066         }
3067         btrfs_end_transaction(trans, root);
3068 }
3069
3070 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3071 {
3072         struct btrfs_root *root = BTRFS_I(dir)->root;
3073         struct btrfs_trans_handle *trans;
3074         struct inode *inode = dentry->d_inode;
3075         int ret;
3076         unsigned long nr = 0;
3077
3078         trans = __unlink_start_trans(dir, dentry);
3079         if (IS_ERR(trans))
3080                 return PTR_ERR(trans);
3081
3082         btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3083
3084         ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3085                                  dentry->d_name.name, dentry->d_name.len);
3086         if (ret)
3087                 goto out;
3088
3089         if (inode->i_nlink == 0) {
3090                 ret = btrfs_orphan_add(trans, inode);
3091                 if (ret)
3092                         goto out;
3093         }
3094
3095 out:
3096         nr = trans->blocks_used;
3097         __unlink_end_trans(trans, root);
3098         btrfs_btree_balance_dirty(root, nr);
3099         return ret;
3100 }
3101
3102 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3103                         struct btrfs_root *root,
3104                         struct inode *dir, u64 objectid,
3105                         const char *name, int name_len)
3106 {
3107         struct btrfs_path *path;
3108         struct extent_buffer *leaf;
3109         struct btrfs_dir_item *di;
3110         struct btrfs_key key;
3111         u64 index;
3112         int ret;
3113         u64 dir_ino = btrfs_ino(dir);
3114
3115         path = btrfs_alloc_path();
3116         if (!path)
3117                 return -ENOMEM;
3118
3119         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3120                                    name, name_len, -1);
3121         if (IS_ERR_OR_NULL(di)) {
3122                 if (!di)
3123                         ret = -ENOENT;
3124                 else
3125                         ret = PTR_ERR(di);
3126                 goto out;
3127         }
3128
3129         leaf = path->nodes[0];
3130         btrfs_dir_item_key_to_cpu(leaf, di, &key);
3131         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3132         ret = btrfs_delete_one_dir_name(trans, root, path, di);
3133         if (ret) {
3134                 btrfs_abort_transaction(trans, root, ret);
3135                 goto out;
3136         }
3137         btrfs_release_path(path);
3138
3139         ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3140                                  objectid, root->root_key.objectid,
3141                                  dir_ino, &index, name, name_len);
3142         if (ret < 0) {
3143                 if (ret != -ENOENT) {
3144                         btrfs_abort_transaction(trans, root, ret);
3145                         goto out;
3146                 }
3147                 di = btrfs_search_dir_index_item(root, path, dir_ino,
3148                                                  name, name_len);
3149                 if (IS_ERR_OR_NULL(di)) {
3150                         if (!di)
3151                                 ret = -ENOENT;
3152                         else
3153                                 ret = PTR_ERR(di);
3154                         btrfs_abort_transaction(trans, root, ret);
3155                         goto out;
3156                 }
3157
3158                 leaf = path->nodes[0];
3159                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3160                 btrfs_release_path(path);
3161                 index = key.offset;
3162         }
3163         btrfs_release_path(path);
3164
3165         ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3166         if (ret) {
3167                 btrfs_abort_transaction(trans, root, ret);
3168                 goto out;
3169         }
3170
3171         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3172         inode_inc_iversion(dir);
3173         dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3174         ret = btrfs_update_inode(trans, root, dir);
3175         if (ret)
3176                 btrfs_abort_transaction(trans, root, ret);
3177 out:
3178         btrfs_free_path(path);
3179         return ret;
3180 }
3181
3182 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3183 {
3184         struct inode *inode = dentry->d_inode;
3185         int err = 0;
3186         struct btrfs_root *root = BTRFS_I(dir)->root;
3187         struct btrfs_trans_handle *trans;
3188         unsigned long nr = 0;
3189
3190         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
3191             btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3192                 return -ENOTEMPTY;
3193
3194         trans = __unlink_start_trans(dir, dentry);
3195         if (IS_ERR(trans))
3196                 return PTR_ERR(trans);
3197
3198         if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3199                 err = btrfs_unlink_subvol(trans, root, dir,
3200                                           BTRFS_I(inode)->location.objectid,
3201                                           dentry->d_name.name,
3202                                           dentry->d_name.len);
3203                 goto out;
3204         }
3205
3206         err = btrfs_orphan_add(trans, inode);
3207         if (err)
3208                 goto out;
3209
3210         /* now the directory is empty */
3211         err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3212                                  dentry->d_name.name, dentry->d_name.len);
3213         if (!err)
3214                 btrfs_i_size_write(inode, 0);
3215 out:
3216         nr = trans->blocks_used;
3217         __unlink_end_trans(trans, root);
3218         btrfs_btree_balance_dirty(root, nr);
3219
3220         return err;
3221 }
3222
3223 /*
3224  * this can truncate away extent items, csum items and directory items.
3225  * It starts at a high offset and removes keys until it can't find
3226  * any higher than new_size
3227  *
3228  * csum items that cross the new i_size are truncated to the new size
3229  * as well.
3230  *
3231  * min_type is the minimum key type to truncate down to.  If set to 0, this
3232  * will kill all the items on this inode, including the INODE_ITEM_KEY.
3233  */
3234 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3235                                struct btrfs_root *root,
3236                                struct inode *inode,
3237                                u64 new_size, u32 min_type)
3238 {
3239         struct btrfs_path *path;
3240         struct extent_buffer *leaf;
3241         struct btrfs_file_extent_item *fi;
3242         struct btrfs_key key;
3243         struct btrfs_key found_key;
3244         u64 extent_start = 0;
3245         u64 extent_num_bytes = 0;
3246         u64 extent_offset = 0;
3247         u64 item_end = 0;
3248         u64 mask = root->sectorsize - 1;
3249         u32 found_type = (u8)-1;
3250         int found_extent;
3251         int del_item;
3252         int pending_del_nr = 0;
3253         int pending_del_slot = 0;
3254         int extent_type = -1;
3255         int ret;
3256         int err = 0;
3257         u64 ino = btrfs_ino(inode);
3258
3259         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3260
3261         path = btrfs_alloc_path();
3262         if (!path)
3263                 return -ENOMEM;
3264         path->reada = -1;
3265
3266         if (root->ref_cows || root == root->fs_info->tree_root)
3267                 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
3268
3269         /*
3270          * This function is also used to drop the items in the log tree before
3271          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3272          * it is used to drop the loged items. So we shouldn't kill the delayed
3273          * items.
3274          */
3275         if (min_type == 0 && root == BTRFS_I(inode)->root)
3276                 btrfs_kill_delayed_inode_items(inode);
3277
3278         key.objectid = ino;
3279         key.offset = (u64)-1;
3280         key.type = (u8)-1;
3281
3282 search_again:
3283         path->leave_spinning = 1;
3284         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3285         if (ret < 0) {
3286                 err = ret;
3287                 goto out;
3288         }
3289
3290         if (ret > 0) {
3291                 /* there are no items in the tree for us to truncate, we're
3292                  * done
3293                  */
3294                 if (path->slots[0] == 0)
3295                         goto out;
3296                 path->slots[0]--;
3297         }
3298
3299         while (1) {
3300                 fi = NULL;
3301                 leaf = path->nodes[0];
3302                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3303                 found_type = btrfs_key_type(&found_key);
3304
3305                 if (found_key.objectid != ino)
3306                         break;
3307
3308                 if (found_type < min_type)
3309                         break;
3310
3311                 item_end = found_key.offset;
3312                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3313                         fi = btrfs_item_ptr(leaf, path->slots[0],
3314                                             struct btrfs_file_extent_item);
3315                         extent_type = btrfs_file_extent_type(leaf, fi);
3316                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3317                                 item_end +=
3318                                     btrfs_file_extent_num_bytes(leaf, fi);
3319                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3320                                 item_end += btrfs_file_extent_inline_len(leaf,
3321                                                                          fi);
3322                         }
3323                         item_end--;
3324                 }
3325                 if (found_type > min_type) {
3326                         del_item = 1;
3327                 } else {
3328                         if (item_end < new_size)
3329                                 break;
3330                         if (found_key.offset >= new_size)
3331                                 del_item = 1;
3332                         else
3333                                 del_item = 0;
3334                 }
3335                 found_extent = 0;
3336                 /* FIXME, shrink the extent if the ref count is only 1 */
3337                 if (found_type != BTRFS_EXTENT_DATA_KEY)
3338                         goto delete;
3339
3340                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3341                         u64 num_dec;
3342                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3343                         if (!del_item) {
3344                                 u64 orig_num_bytes =
3345                                         btrfs_file_extent_num_bytes(leaf, fi);
3346                                 extent_num_bytes = new_size -
3347                                         found_key.offset + root->sectorsize - 1;
3348                                 extent_num_bytes = extent_num_bytes &
3349                                         ~((u64)root->sectorsize - 1);
3350                                 btrfs_set_file_extent_num_bytes(leaf, fi,
3351                                                          extent_num_bytes);
3352                                 num_dec = (orig_num_bytes -
3353                                            extent_num_bytes);
3354                                 if (root->ref_cows && extent_start != 0)
3355                                         inode_sub_bytes(inode, num_dec);
3356                                 btrfs_mark_buffer_dirty(leaf);
3357                         } else {
3358                                 extent_num_bytes =
3359                                         btrfs_file_extent_disk_num_bytes(leaf,
3360                                                                          fi);
3361                                 extent_offset = found_key.offset -
3362                                         btrfs_file_extent_offset(leaf, fi);
3363
3364                                 /* FIXME blocksize != 4096 */
3365                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3366                                 if (extent_start != 0) {
3367                                         found_extent = 1;
3368                                         if (root->ref_cows)
3369                                                 inode_sub_bytes(inode, num_dec);
3370                                 }
3371                         }
3372                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3373                         /*
3374                          * we can't truncate inline items that have had
3375                          * special encodings
3376                          */
3377                         if (!del_item &&
3378                             btrfs_file_extent_compression(leaf, fi) == 0 &&
3379                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
3380                             btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3381                                 u32 size = new_size - found_key.offset;
3382
3383                                 if (root->ref_cows) {
3384                                         inode_sub_bytes(inode, item_end + 1 -
3385                                                         new_size);
3386                                 }
3387                                 size =
3388                                     btrfs_file_extent_calc_inline_size(size);
3389                                 btrfs_truncate_item(trans, root, path,
3390                                                     size, 1);
3391                         } else if (root->ref_cows) {
3392                                 inode_sub_bytes(inode, item_end + 1 -
3393                                                 found_key.offset);
3394                         }
3395                 }
3396 delete:
3397                 if (del_item) {
3398                         if (!pending_del_nr) {
3399                                 /* no pending yet, add ourselves */
3400                                 pending_del_slot = path->slots[0];
3401                                 pending_del_nr = 1;
3402                         } else if (pending_del_nr &&
3403                                    path->slots[0] + 1 == pending_del_slot) {
3404                                 /* hop on the pending chunk */
3405                                 pending_del_nr++;
3406                                 pending_del_slot = path->slots[0];
3407                         } else {
3408                                 BUG();
3409                         }
3410                 } else {
3411                         break;
3412                 }
3413                 if (found_extent && (root->ref_cows ||
3414                                      root == root->fs_info->tree_root)) {
3415                         btrfs_set_path_blocking(path);
3416                         ret = btrfs_free_extent(trans, root, extent_start,
3417                                                 extent_num_bytes, 0,
3418                                                 btrfs_header_owner(leaf),
3419                                                 ino, extent_offset, 0);
3420                         BUG_ON(ret);
3421                 }
3422
3423                 if (found_type == BTRFS_INODE_ITEM_KEY)
3424                         break;
3425
3426                 if (path->slots[0] == 0 ||
3427                     path->slots[0] != pending_del_slot) {
3428                         if (root->ref_cows &&
3429                             BTRFS_I(inode)->location.objectid !=
3430                                                 BTRFS_FREE_INO_OBJECTID) {
3431                                 err = -EAGAIN;
3432                                 goto out;
3433                         }
3434                         if (pending_del_nr) {
3435                                 ret = btrfs_del_items(trans, root, path,
3436                                                 pending_del_slot,
3437                                                 pending_del_nr);
3438                                 if (ret) {
3439                                         btrfs_abort_transaction(trans,
3440                                                                 root, ret);
3441                                         goto error;
3442                                 }
3443                                 pending_del_nr = 0;
3444                         }
3445                         btrfs_release_path(path);
3446                         goto search_again;
3447                 } else {
3448                         path->slots[0]--;
3449                 }
3450         }
3451 out:
3452         if (pending_del_nr) {
3453                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3454                                       pending_del_nr);
3455                 if (ret)
3456                         btrfs_abort_transaction(trans, root, ret);
3457         }
3458 error:
3459         btrfs_free_path(path);
3460         return err;
3461 }
3462
3463 /*
3464  * taken from block_truncate_page, but does cow as it zeros out
3465  * any bytes left in the last page in the file.
3466  */
3467 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3468 {
3469         struct inode *inode = mapping->host;
3470         struct btrfs_root *root = BTRFS_I(inode)->root;
3471         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3472         struct btrfs_ordered_extent *ordered;
3473         struct extent_state *cached_state = NULL;
3474         char *kaddr;
3475         u32 blocksize = root->sectorsize;
3476         pgoff_t index = from >> PAGE_CACHE_SHIFT;
3477         unsigned offset = from & (PAGE_CACHE_SIZE-1);
3478         struct page *page;
3479         gfp_t mask = btrfs_alloc_write_mask(mapping);
3480         int ret = 0;
3481         u64 page_start;
3482         u64 page_end;
3483
3484         if ((offset & (blocksize - 1)) == 0)
3485                 goto out;
3486         ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3487         if (ret)
3488                 goto out;
3489
3490         ret = -ENOMEM;
3491 again:
3492         page = find_or_create_page(mapping, index, mask);
3493         if (!page) {
3494                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3495                 goto out;
3496         }
3497
3498         page_start = page_offset(page);
3499         page_end = page_start + PAGE_CACHE_SIZE - 1;
3500
3501         if (!PageUptodate(page)) {
3502                 ret = btrfs_readpage(NULL, page);
3503                 lock_page(page);
3504                 if (page->mapping != mapping) {
3505                         unlock_page(page);
3506                         page_cache_release(page);
3507                         goto again;
3508                 }
3509                 if (!PageUptodate(page)) {
3510                         ret = -EIO;
3511                         goto out_unlock;
3512                 }
3513         }
3514         wait_on_page_writeback(page);
3515
3516         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
3517         set_page_extent_mapped(page);
3518
3519         ordered = btrfs_lookup_ordered_extent(inode, page_start);
3520         if (ordered) {
3521                 unlock_extent_cached(io_tree, page_start, page_end,
3522                                      &cached_state, GFP_NOFS);
3523                 unlock_page(page);
3524                 page_cache_release(page);
3525                 btrfs_start_ordered_extent(inode, ordered, 1);
3526                 btrfs_put_ordered_extent(ordered);
3527                 goto again;
3528         }
3529
3530         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3531                           EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
3532                           0, 0, &cached_state, GFP_NOFS);
3533
3534         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3535                                         &cached_state);
3536         if (ret) {
3537                 unlock_extent_cached(io_tree, page_start, page_end,
3538                                      &cached_state, GFP_NOFS);
3539                 goto out_unlock;
3540         }
3541
3542         ret = 0;
3543         if (offset != PAGE_CACHE_SIZE) {
3544                 kaddr = kmap(page);
3545                 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3546                 flush_dcache_page(page);
3547                 kunmap(page);
3548         }
3549         ClearPageChecked(page);
3550         set_page_dirty(page);
3551         unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3552                              GFP_NOFS);
3553
3554 out_unlock:
3555         if (ret)
3556                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3557         unlock_page(page);
3558         page_cache_release(page);
3559 out:
3560         return ret;
3561 }
3562
3563 /*
3564  * This function puts in dummy file extents for the area we're creating a hole
3565  * for.  So if we are truncating this file to a larger size we need to insert
3566  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3567  * the range between oldsize and size
3568  */
3569 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
3570 {
3571         struct btrfs_trans_handle *trans;
3572         struct btrfs_root *root = BTRFS_I(inode)->root;
3573         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3574         struct extent_map *em = NULL;
3575         struct extent_state *cached_state = NULL;
3576         u64 mask = root->sectorsize - 1;
3577         u64 hole_start = (oldsize + mask) & ~mask;
3578         u64 block_end = (size + mask) & ~mask;
3579         u64 last_byte;
3580         u64 cur_offset;
3581         u64 hole_size;
3582         int err = 0;
3583
3584         if (size <= hole_start)
3585                 return 0;
3586
3587         while (1) {
3588                 struct btrfs_ordered_extent *ordered;
3589                 btrfs_wait_ordered_range(inode, hole_start,
3590                                          block_end - hole_start);
3591                 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3592                                  &cached_state);
3593                 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3594                 if (!ordered)
3595                         break;
3596                 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3597                                      &cached_state, GFP_NOFS);
3598                 btrfs_put_ordered_extent(ordered);
3599         }
3600
3601         cur_offset = hole_start;
3602         while (1) {
3603                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3604                                 block_end - cur_offset, 0);
3605                 if (IS_ERR(em)) {
3606                         err = PTR_ERR(em);
3607                         break;
3608                 }
3609                 last_byte = min(extent_map_end(em), block_end);
3610                 last_byte = (last_byte + mask) & ~mask;
3611                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3612                         u64 hint_byte = 0;
3613                         hole_size = last_byte - cur_offset;
3614
3615                         trans = btrfs_start_transaction(root, 3);
3616                         if (IS_ERR(trans)) {
3617                                 err = PTR_ERR(trans);
3618                                 break;
3619                         }
3620
3621                         err = btrfs_drop_extents(trans, inode, cur_offset,
3622                                                  cur_offset + hole_size,
3623                                                  &hint_byte, 1);
3624                         if (err) {
3625                                 btrfs_abort_transaction(trans, root, err);
3626                                 btrfs_end_transaction(trans, root);
3627                                 break;
3628                         }
3629
3630                         err = btrfs_insert_file_extent(trans, root,
3631                                         btrfs_ino(inode), cur_offset, 0,
3632                                         0, hole_size, 0, hole_size,
3633                                         0, 0, 0);
3634                         if (err) {
3635                                 btrfs_abort_transaction(trans, root, err);
3636                                 btrfs_end_transaction(trans, root);
3637                                 break;
3638                         }
3639
3640                         btrfs_drop_extent_cache(inode, hole_start,
3641                                         last_byte - 1, 0);
3642
3643                         btrfs_update_inode(trans, root, inode);
3644                         btrfs_end_transaction(trans, root);
3645                 }
3646                 free_extent_map(em);
3647                 em = NULL;
3648                 cur_offset = last_byte;
3649                 if (cur_offset >= block_end)
3650                         break;
3651         }
3652
3653         free_extent_map(em);
3654         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3655                              GFP_NOFS);
3656         return err;
3657 }
3658
3659 static int btrfs_setsize(struct inode *inode, loff_t newsize)
3660 {
3661         struct btrfs_root *root = BTRFS_I(inode)->root;
3662         struct btrfs_trans_handle *trans;
3663         loff_t oldsize = i_size_read(inode);
3664         int ret;
3665
3666         if (newsize == oldsize)
3667                 return 0;
3668
3669         if (newsize > oldsize) {
3670                 truncate_pagecache(inode, oldsize, newsize);
3671                 ret = btrfs_cont_expand(inode, oldsize, newsize);
3672                 if (ret)
3673                         return ret;
3674
3675                 trans = btrfs_start_transaction(root, 1);
3676                 if (IS_ERR(trans))
3677                         return PTR_ERR(trans);
3678
3679                 i_size_write(inode, newsize);
3680                 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3681                 ret = btrfs_update_inode(trans, root, inode);
3682                 btrfs_end_transaction(trans, root);
3683         } else {
3684
3685                 /*
3686                  * We're truncating a file that used to have good data down to
3687                  * zero. Make sure it gets into the ordered flush list so that
3688                  * any new writes get down to disk quickly.
3689                  */
3690                 if (newsize == 0)
3691                         set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
3692                                 &BTRFS_I(inode)->runtime_flags);
3693
3694                 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3695                 truncate_setsize(inode, newsize);
3696                 ret = btrfs_truncate(inode);
3697         }
3698
3699         return ret;
3700 }
3701
3702 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3703 {
3704         struct inode *inode = dentry->d_inode;
3705         struct btrfs_root *root = BTRFS_I(inode)->root;
3706         int err;
3707
3708         if (btrfs_root_readonly(root))
3709                 return -EROFS;
3710
3711         err = inode_change_ok(inode, attr);
3712         if (err)
3713                 return err;
3714
3715         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3716                 err = btrfs_setsize(inode, attr->ia_size);
3717                 if (err)
3718                         return err;
3719         }
3720
3721         if (attr->ia_valid) {
3722                 setattr_copy(inode, attr);
3723                 inode_inc_iversion(inode);
3724                 err = btrfs_dirty_inode(inode);
3725
3726                 if (!err && attr->ia_valid & ATTR_MODE)
3727                         err = btrfs_acl_chmod(inode);
3728         }
3729
3730         return err;
3731 }
3732
3733 void btrfs_evict_inode(struct inode *inode)
3734 {
3735         struct btrfs_trans_handle *trans;
3736         struct btrfs_root *root = BTRFS_I(inode)->root;
3737         struct btrfs_block_rsv *rsv, *global_rsv;
3738         u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
3739         unsigned long nr;
3740         int ret;
3741
3742         trace_btrfs_inode_evict(inode);
3743
3744         truncate_inode_pages(&inode->i_data, 0);
3745         if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3746                                btrfs_is_free_space_inode(inode)))
3747                 goto no_delete;
3748
3749         if (is_bad_inode(inode)) {
3750                 btrfs_orphan_del(NULL, inode);
3751                 goto no_delete;
3752         }
3753         /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3754         btrfs_wait_ordered_range(inode, 0, (u64)-1);
3755
3756         if (root->fs_info->log_root_recovering) {
3757                 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3758                                  &BTRFS_I(inode)->runtime_flags));
3759                 goto no_delete;
3760         }
3761
3762         if (inode->i_nlink > 0) {
3763                 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3764                 goto no_delete;
3765         }
3766
3767         rsv = btrfs_alloc_block_rsv(root);
3768         if (!rsv) {
3769                 btrfs_orphan_del(NULL, inode);
3770                 goto no_delete;
3771         }
3772         rsv->size = min_size;
3773         global_rsv = &root->fs_info->global_block_rsv;
3774
3775         btrfs_i_size_write(inode, 0);
3776
3777         /*
3778          * This is a bit simpler than btrfs_truncate since
3779          *
3780          * 1) We've already reserved our space for our orphan item in the
3781          *    unlink.
3782          * 2) We're going to delete the inode item, so we don't need to update
3783          *    it at all.
3784          *
3785          * So we just need to reserve some slack space in case we add bytes when
3786          * doing the truncate.
3787          */
3788         while (1) {
3789                 ret = btrfs_block_rsv_refill_noflush(root, rsv, min_size);
3790
3791                 /*
3792                  * Try and steal from the global reserve since we will
3793                  * likely not use this space anyway, we want to try as
3794                  * hard as possible to get this to work.
3795                  */
3796                 if (ret)
3797                         ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
3798
3799                 if (ret) {
3800                         printk(KERN_WARNING "Could not get space for a "
3801                                "delete, will truncate on mount %d\n", ret);
3802                         btrfs_orphan_del(NULL, inode);
3803                         btrfs_free_block_rsv(root, rsv);
3804                         goto no_delete;
3805                 }
3806
3807                 trans = btrfs_start_transaction(root, 0);
3808                 if (IS_ERR(trans)) {
3809                         btrfs_orphan_del(NULL, inode);
3810                         btrfs_free_block_rsv(root, rsv);
3811                         goto no_delete;
3812                 }
3813
3814                 trans->block_rsv = rsv;
3815
3816                 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3817                 if (ret != -EAGAIN)
3818                         break;
3819
3820                 nr = trans->blocks_used;
3821                 btrfs_end_transaction(trans, root);
3822                 trans = NULL;
3823                 btrfs_btree_balance_dirty(root, nr);
3824         }
3825
3826         btrfs_free_block_rsv(root, rsv);
3827
3828         if (ret == 0) {
3829                 trans->block_rsv = root->orphan_block_rsv;
3830                 ret = btrfs_orphan_del(trans, inode);
3831                 BUG_ON(ret);
3832         }
3833
3834         trans->block_rsv = &root->fs_info->trans_block_rsv;
3835         if (!(root == root->fs_info->tree_root ||
3836               root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
3837                 btrfs_return_ino(root, btrfs_ino(inode));
3838
3839         nr = trans->blocks_used;
3840         btrfs_end_transaction(trans, root);
3841         btrfs_btree_balance_dirty(root, nr);
3842 no_delete:
3843         clear_inode(inode);
3844         return;
3845 }
3846
3847 /*
3848  * this returns the key found in the dir entry in the location pointer.
3849  * If no dir entries were found, location->objectid is 0.
3850  */
3851 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3852                                struct btrfs_key *location)
3853 {
3854         const char *name = dentry->d_name.name;
3855         int namelen = dentry->d_name.len;
3856         struct btrfs_dir_item *di;
3857         struct btrfs_path *path;
3858         struct btrfs_root *root = BTRFS_I(dir)->root;
3859         int ret = 0;
3860
3861         path = btrfs_alloc_path();
3862         if (!path)
3863                 return -ENOMEM;
3864
3865         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
3866                                     namelen, 0);
3867         if (IS_ERR(di))
3868                 ret = PTR_ERR(di);
3869
3870         if (IS_ERR_OR_NULL(di))
3871                 goto out_err;
3872
3873         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
3874 out:
3875         btrfs_free_path(path);
3876         return ret;
3877 out_err:
3878         location->objectid = 0;
3879         goto out;
3880 }
3881
3882 /*
3883  * when we hit a tree root in a directory, the btrfs part of the inode
3884  * needs to be changed to reflect the root directory of the tree root.  This
3885  * is kind of like crossing a mount point.
3886  */
3887 static int fixup_tree_root_location(struct btrfs_root *root,
3888                                     struct inode *dir,
3889                                     struct dentry *dentry,
3890                                     struct btrfs_key *location,
3891                                     struct btrfs_root **sub_root)
3892 {
3893         struct btrfs_path *path;
3894         struct btrfs_root *new_root;
3895         struct btrfs_root_ref *ref;
3896         struct extent_buffer *leaf;
3897         int ret;
3898         int err = 0;
3899
3900         path = btrfs_alloc_path();
3901         if (!path) {
3902                 err = -ENOMEM;
3903                 goto out;
3904         }
3905
3906         err = -ENOENT;
3907         ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3908                                   BTRFS_I(dir)->root->root_key.objectid,
3909                                   location->objectid);
3910         if (ret) {
3911                 if (ret < 0)
3912                         err = ret;
3913                 goto out;
3914         }
3915
3916         leaf = path->nodes[0];
3917         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3918         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
3919             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3920                 goto out;
3921
3922         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3923                                    (unsigned long)(ref + 1),
3924                                    dentry->d_name.len);
3925         if (ret)
3926                 goto out;
3927
3928         btrfs_release_path(path);
3929
3930         new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3931         if (IS_ERR(new_root)) {
3932                 err = PTR_ERR(new_root);
3933                 goto out;
3934         }
3935
3936         if (btrfs_root_refs(&new_root->root_item) == 0) {
3937                 err = -ENOENT;
3938                 goto out;
3939         }
3940
3941         *sub_root = new_root;
3942         location->objectid = btrfs_root_dirid(&new_root->root_item);
3943         location->type = BTRFS_INODE_ITEM_KEY;
3944         location->offset = 0;
3945         err = 0;
3946 out:
3947         btrfs_free_path(path);
3948         return err;
3949 }
3950
3951 static void inode_tree_add(struct inode *inode)
3952 {
3953         struct btrfs_root *root = BTRFS_I(inode)->root;
3954         struct btrfs_inode *entry;
3955         struct rb_node **p;
3956         struct rb_node *parent;
3957         u64 ino = btrfs_ino(inode);
3958 again:
3959         p = &root->inode_tree.rb_node;
3960         parent = NULL;
3961
3962         if (inode_unhashed(inode))
3963                 return;
3964
3965         spin_lock(&root->inode_lock);
3966         while (*p) {
3967                 parent = *p;
3968                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3969
3970                 if (ino < btrfs_ino(&entry->vfs_inode))
3971                         p = &parent->rb_left;
3972                 else if (ino > btrfs_ino(&entry->vfs_inode))
3973                         p = &parent->rb_right;
3974                 else {
3975                         WARN_ON(!(entry->vfs_inode.i_state &
3976                                   (I_WILL_FREE | I_FREEING)));
3977                         rb_erase(parent, &root->inode_tree);
3978                         RB_CLEAR_NODE(parent);
3979                         spin_unlock(&root->inode_lock);
3980                         goto again;
3981                 }
3982         }
3983         rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3984         rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3985         spin_unlock(&root->inode_lock);
3986 }
3987
3988 static void inode_tree_del(struct inode *inode)
3989 {
3990         struct btrfs_root *root = BTRFS_I(inode)->root;
3991         int empty = 0;
3992
3993         spin_lock(&root->inode_lock);
3994         if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
3995                 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3996                 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
3997                 empty = RB_EMPTY_ROOT(&root->inode_tree);
3998         }
3999         spin_unlock(&root->inode_lock);
4000
4001         /*
4002          * Free space cache has inodes in the tree root, but the tree root has a
4003          * root_refs of 0, so this could end up dropping the tree root as a
4004          * snapshot, so we need the extra !root->fs_info->tree_root check to
4005          * make sure we don't drop it.
4006          */
4007         if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4008             root != root->fs_info->tree_root) {
4009                 synchronize_srcu(&root->fs_info->subvol_srcu);
4010                 spin_lock(&root->inode_lock);
4011                 empty = RB_EMPTY_ROOT(&root->inode_tree);
4012                 spin_unlock(&root->inode_lock);
4013                 if (empty)
4014                         btrfs_add_dead_root(root);
4015         }
4016 }
4017
4018 void btrfs_invalidate_inodes(struct btrfs_root *root)
4019 {
4020         struct rb_node *node;
4021         struct rb_node *prev;
4022         struct btrfs_inode *entry;
4023         struct inode *inode;
4024         u64 objectid = 0;
4025
4026         WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4027
4028         spin_lock(&root->inode_lock);
4029 again:
4030         node = root->inode_tree.rb_node;
4031         prev = NULL;
4032         while (node) {
4033                 prev = node;
4034                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4035
4036                 if (objectid < btrfs_ino(&entry->vfs_inode))
4037                         node = node->rb_left;
4038                 else if (objectid > btrfs_ino(&entry->vfs_inode))
4039                         node = node->rb_right;
4040                 else
4041                         break;
4042         }
4043         if (!node) {
4044                 while (prev) {
4045                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
4046                         if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4047                                 node = prev;
4048                                 break;
4049                         }
4050                         prev = rb_next(prev);
4051                 }
4052         }
4053         while (node) {
4054                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4055                 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4056                 inode = igrab(&entry->vfs_inode);
4057                 if (inode) {
4058                         spin_unlock(&root->inode_lock);
4059                         if (atomic_read(&inode->i_count) > 1)
4060                                 d_prune_aliases(inode);
4061                         /*
4062                          * btrfs_drop_inode will have it removed from
4063                          * the inode cache when its usage count
4064                          * hits zero.
4065                          */
4066                         iput(inode);
4067                         cond_resched();
4068                         spin_lock(&root->inode_lock);
4069                         goto again;
4070                 }
4071
4072                 if (cond_resched_lock(&root->inode_lock))
4073                         goto again;
4074
4075                 node = rb_next(node);
4076         }
4077         spin_unlock(&root->inode_lock);
4078 }
4079
4080 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4081 {
4082         struct btrfs_iget_args *args = p;
4083         inode->i_ino = args->ino;
4084         BTRFS_I(inode)->root = args->root;
4085         return 0;
4086 }
4087
4088 static int btrfs_find_actor(struct inode *inode, void *opaque)
4089 {
4090         struct btrfs_iget_args *args = opaque;
4091         return args->ino == btrfs_ino(inode) &&
4092                 args->root == BTRFS_I(inode)->root;
4093 }
4094
4095 static struct inode *btrfs_iget_locked(struct super_block *s,
4096                                        u64 objectid,
4097                                        struct btrfs_root *root)
4098 {
4099         struct inode *inode;
4100         struct btrfs_iget_args args;
4101         args.ino = objectid;
4102         args.root = root;
4103
4104         inode = iget5_locked(s, objectid, btrfs_find_actor,
4105                              btrfs_init_locked_inode,
4106                              (void *)&args);
4107         return inode;
4108 }
4109
4110 /* Get an inode object given its location and corresponding root.
4111  * Returns in *is_new if the inode was read from disk
4112  */
4113 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4114                          struct btrfs_root *root, int *new)
4115 {
4116         struct inode *inode;
4117
4118         inode = btrfs_iget_locked(s, location->objectid, root);
4119         if (!inode)
4120                 return ERR_PTR(-ENOMEM);
4121
4122         if (inode->i_state & I_NEW) {
4123                 BTRFS_I(inode)->root = root;
4124                 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4125                 btrfs_read_locked_inode(inode);
4126                 if (!is_bad_inode(inode)) {
4127                         inode_tree_add(inode);
4128                         unlock_new_inode(inode);
4129                         if (new)
4130                                 *new = 1;
4131                 } else {
4132                         unlock_new_inode(inode);
4133                         iput(inode);
4134                         inode = ERR_PTR(-ESTALE);
4135                 }
4136         }
4137
4138         return inode;
4139 }
4140
4141 static struct inode *new_simple_dir(struct super_block *s,
4142                                     struct btrfs_key *key,
4143                                     struct btrfs_root *root)
4144 {
4145         struct inode *inode = new_inode(s);
4146
4147         if (!inode)
4148                 return ERR_PTR(-ENOMEM);
4149
4150         BTRFS_I(inode)->root = root;
4151         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4152         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4153
4154         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4155         inode->i_op = &btrfs_dir_ro_inode_operations;
4156         inode->i_fop = &simple_dir_operations;
4157         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4158         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4159
4160         return inode;
4161 }
4162
4163 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4164 {
4165         struct inode *inode;
4166         struct btrfs_root *root = BTRFS_I(dir)->root;
4167         struct btrfs_root *sub_root = root;
4168         struct btrfs_key location;
4169         int index;
4170         int ret = 0;
4171
4172         if (dentry->d_name.len > BTRFS_NAME_LEN)
4173                 return ERR_PTR(-ENAMETOOLONG);
4174
4175         if (unlikely(d_need_lookup(dentry))) {
4176                 memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key));
4177                 kfree(dentry->d_fsdata);
4178                 dentry->d_fsdata = NULL;
4179                 /* This thing is hashed, drop it for now */
4180                 d_drop(dentry);
4181         } else {
4182                 ret = btrfs_inode_by_name(dir, dentry, &location);
4183         }
4184
4185         if (ret < 0)
4186                 return ERR_PTR(ret);
4187
4188         if (location.objectid == 0)
4189                 return NULL;
4190
4191         if (location.type == BTRFS_INODE_ITEM_KEY) {
4192                 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4193                 return inode;
4194         }
4195
4196         BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4197
4198         index = srcu_read_lock(&root->fs_info->subvol_srcu);
4199         ret = fixup_tree_root_location(root, dir, dentry,
4200                                        &location, &sub_root);
4201         if (ret < 0) {
4202                 if (ret != -ENOENT)
4203                         inode = ERR_PTR(ret);
4204                 else
4205                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
4206         } else {
4207                 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4208         }
4209         srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4210
4211         if (!IS_ERR(inode) && root != sub_root) {
4212                 down_read(&root->fs_info->cleanup_work_sem);
4213                 if (!(inode->i_sb->s_flags & MS_RDONLY))
4214                         ret = btrfs_orphan_cleanup(sub_root);
4215                 up_read(&root->fs_info->cleanup_work_sem);
4216                 if (ret)
4217                         inode = ERR_PTR(ret);
4218         }
4219
4220         return inode;
4221 }
4222
4223 static int btrfs_dentry_delete(const struct dentry *dentry)
4224 {
4225         struct btrfs_root *root;
4226         struct inode *inode = dentry->d_inode;
4227
4228         if (!inode && !IS_ROOT(dentry))
4229                 inode = dentry->d_parent->d_inode;
4230
4231         if (inode) {
4232                 root = BTRFS_I(inode)->root;
4233                 if (btrfs_root_refs(&root->root_item) == 0)
4234                         return 1;
4235
4236                 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
4237                         return 1;
4238         }
4239         return 0;
4240 }
4241
4242 static void btrfs_dentry_release(struct dentry *dentry)
4243 {
4244         if (dentry->d_fsdata)
4245                 kfree(dentry->d_fsdata);
4246 }
4247
4248 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4249                                    struct nameidata *nd)
4250 {
4251         struct dentry *ret;
4252
4253         ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
4254         if (unlikely(d_need_lookup(dentry))) {
4255                 spin_lock(&dentry->d_lock);
4256                 dentry->d_flags &= ~DCACHE_NEED_LOOKUP;
4257                 spin_unlock(&dentry->d_lock);
4258         }
4259         return ret;
4260 }
4261
4262 unsigned char btrfs_filetype_table[] = {
4263         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4264 };
4265
4266 static int btrfs_real_readdir(struct file *filp, void *dirent,
4267                               filldir_t filldir)
4268 {
4269         struct inode *inode = filp->f_dentry->d_inode;
4270         struct btrfs_root *root = BTRFS_I(inode)->root;
4271         struct btrfs_item *item;
4272         struct btrfs_dir_item *di;
4273         struct btrfs_key key;
4274         struct btrfs_key found_key;
4275         struct btrfs_path *path;
4276         struct list_head ins_list;
4277         struct list_head del_list;
4278         int ret;
4279         struct extent_buffer *leaf;
4280         int slot;
4281         unsigned char d_type;
4282         int over = 0;
4283         u32 di_cur;
4284         u32 di_total;
4285         u32 di_len;
4286         int key_type = BTRFS_DIR_INDEX_KEY;
4287         char tmp_name[32];
4288         char *name_ptr;
4289         int name_len;
4290         int is_curr = 0;        /* filp->f_pos points to the current index? */
4291
4292         /* FIXME, use a real flag for deciding about the key type */
4293         if (root->fs_info->tree_root == root)
4294                 key_type = BTRFS_DIR_ITEM_KEY;
4295
4296         /* special case for "." */
4297         if (filp->f_pos == 0) {
4298                 over = filldir(dirent, ".", 1,
4299                                filp->f_pos, btrfs_ino(inode), DT_DIR);
4300                 if (over)
4301                         return 0;
4302                 filp->f_pos = 1;
4303         }
4304         /* special case for .., just use the back ref */
4305         if (filp->f_pos == 1) {
4306                 u64 pino = parent_ino(filp->f_path.dentry);
4307                 over = filldir(dirent, "..", 2,
4308                                filp->f_pos, pino, DT_DIR);
4309                 if (over)
4310                         return 0;
4311                 filp->f_pos = 2;
4312         }
4313         path = btrfs_alloc_path();
4314         if (!path)
4315                 return -ENOMEM;
4316
4317         path->reada = 1;
4318
4319         if (key_type == BTRFS_DIR_INDEX_KEY) {
4320                 INIT_LIST_HEAD(&ins_list);
4321                 INIT_LIST_HEAD(&del_list);
4322                 btrfs_get_delayed_items(inode, &ins_list, &del_list);
4323         }
4324
4325         btrfs_set_key_type(&key, key_type);
4326         key.offset = filp->f_pos;
4327         key.objectid = btrfs_ino(inode);
4328
4329         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4330         if (ret < 0)
4331                 goto err;
4332
4333         while (1) {
4334                 leaf = path->nodes[0];
4335                 slot = path->slots[0];
4336                 if (slot >= btrfs_header_nritems(leaf)) {
4337                         ret = btrfs_next_leaf(root, path);
4338                         if (ret < 0)
4339                                 goto err;
4340                         else if (ret > 0)
4341                                 break;
4342                         continue;
4343                 }
4344
4345                 item = btrfs_item_nr(leaf, slot);
4346                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4347
4348                 if (found_key.objectid != key.objectid)
4349                         break;
4350                 if (btrfs_key_type(&found_key) != key_type)
4351                         break;
4352                 if (found_key.offset < filp->f_pos)
4353                         goto next;
4354                 if (key_type == BTRFS_DIR_INDEX_KEY &&
4355                     btrfs_should_delete_dir_index(&del_list,
4356                                                   found_key.offset))
4357                         goto next;
4358
4359                 filp->f_pos = found_key.offset;
4360                 is_curr = 1;
4361
4362                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4363                 di_cur = 0;
4364                 di_total = btrfs_item_size(leaf, item);
4365
4366                 while (di_cur < di_total) {
4367                         struct btrfs_key location;
4368
4369                         if (verify_dir_item(root, leaf, di))
4370                                 break;
4371
4372                         name_len = btrfs_dir_name_len(leaf, di);
4373                         if (name_len <= sizeof(tmp_name)) {
4374                                 name_ptr = tmp_name;
4375                         } else {
4376                                 name_ptr = kmalloc(name_len, GFP_NOFS);
4377                                 if (!name_ptr) {
4378                                         ret = -ENOMEM;
4379                                         goto err;
4380                                 }
4381                         }
4382                         read_extent_buffer(leaf, name_ptr,
4383                                            (unsigned long)(di + 1), name_len);
4384
4385                         d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4386                         btrfs_dir_item_key_to_cpu(leaf, di, &location);
4387
4388
4389                         /* is this a reference to our own snapshot? If so
4390                          * skip it.
4391                          *
4392                          * In contrast to old kernels, we insert the snapshot's
4393                          * dir item and dir index after it has been created, so
4394                          * we won't find a reference to our own snapshot. We
4395                          * still keep the following code for backward
4396                          * compatibility.
4397                          */
4398                         if (location.type == BTRFS_ROOT_ITEM_KEY &&
4399                             location.objectid == root->root_key.objectid) {
4400                                 over = 0;
4401                                 goto skip;
4402                         }
4403                         over = filldir(dirent, name_ptr, name_len,
4404                                        found_key.offset, location.objectid,
4405                                        d_type);
4406
4407 skip:
4408                         if (name_ptr != tmp_name)
4409                                 kfree(name_ptr);
4410
4411                         if (over)
4412                                 goto nopos;
4413                         di_len = btrfs_dir_name_len(leaf, di) +
4414                                  btrfs_dir_data_len(leaf, di) + sizeof(*di);
4415                         di_cur += di_len;
4416                         di = (struct btrfs_dir_item *)((char *)di + di_len);
4417                 }
4418 next:
4419                 path->slots[0]++;
4420         }
4421
4422         if (key_type == BTRFS_DIR_INDEX_KEY) {
4423                 if (is_curr)
4424                         filp->f_pos++;
4425                 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
4426                                                       &ins_list);
4427                 if (ret)
4428                         goto nopos;
4429         }
4430
4431         /* Reached end of directory/root. Bump pos past the last item. */
4432         if (key_type == BTRFS_DIR_INDEX_KEY)
4433                 /*
4434                  * 32-bit glibc will use getdents64, but then strtol -
4435                  * so the last number we can serve is this.
4436                  */
4437                 filp->f_pos = 0x7fffffff;
4438         else
4439                 filp->f_pos++;
4440 nopos:
4441         ret = 0;
4442 err:
4443         if (key_type == BTRFS_DIR_INDEX_KEY)
4444                 btrfs_put_delayed_items(&ins_list, &del_list);
4445         btrfs_free_path(path);
4446         return ret;
4447 }
4448
4449 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4450 {
4451         struct btrfs_root *root = BTRFS_I(inode)->root;
4452         struct btrfs_trans_handle *trans;
4453         int ret = 0;
4454         bool nolock = false;
4455
4456         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4457                 return 0;
4458
4459         if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
4460                 nolock = true;
4461
4462         if (wbc->sync_mode == WB_SYNC_ALL) {
4463                 if (nolock)
4464                         trans = btrfs_join_transaction_nolock(root);
4465                 else
4466                         trans = btrfs_join_transaction(root);
4467                 if (IS_ERR(trans))
4468                         return PTR_ERR(trans);
4469                 if (nolock)
4470                         ret = btrfs_end_transaction_nolock(trans, root);
4471                 else
4472                         ret = btrfs_commit_transaction(trans, root);
4473         }
4474         return ret;
4475 }
4476
4477 /*
4478  * This is somewhat expensive, updating the tree every time the
4479  * inode changes.  But, it is most likely to find the inode in cache.
4480  * FIXME, needs more benchmarking...there are no reasons other than performance
4481  * to keep or drop this code.
4482  */
4483 int btrfs_dirty_inode(struct inode *inode)
4484 {
4485         struct btrfs_root *root = BTRFS_I(inode)->root;
4486         struct btrfs_trans_handle *trans;
4487         int ret;
4488
4489         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4490                 return 0;
4491
4492         trans = btrfs_join_transaction(root);
4493         if (IS_ERR(trans))
4494                 return PTR_ERR(trans);
4495
4496         ret = btrfs_update_inode(trans, root, inode);
4497         if (ret && ret == -ENOSPC) {
4498                 /* whoops, lets try again with the full transaction */
4499                 btrfs_end_transaction(trans, root);
4500                 trans = btrfs_start_transaction(root, 1);
4501                 if (IS_ERR(trans))
4502                         return PTR_ERR(trans);
4503
4504                 ret = btrfs_update_inode(trans, root, inode);
4505         }
4506         btrfs_end_transaction(trans, root);
4507         if (BTRFS_I(inode)->delayed_node)
4508                 btrfs_balance_delayed_items(root);
4509
4510         return ret;
4511 }
4512
4513 /*
4514  * This is a copy of file_update_time.  We need this so we can return error on
4515  * ENOSPC for updating the inode in the case of file write and mmap writes.
4516  */
4517 static int btrfs_update_time(struct inode *inode, struct timespec *now,
4518                              int flags)
4519 {
4520         struct btrfs_root *root = BTRFS_I(inode)->root;
4521
4522         if (btrfs_root_readonly(root))
4523                 return -EROFS;
4524
4525         if (flags & S_VERSION)
4526                 inode_inc_iversion(inode);
4527         if (flags & S_CTIME)
4528                 inode->i_ctime = *now;
4529         if (flags & S_MTIME)
4530                 inode->i_mtime = *now;
4531         if (flags & S_ATIME)
4532                 inode->i_atime = *now;
4533         return btrfs_dirty_inode(inode);
4534 }
4535
4536 /*
4537  * find the highest existing sequence number in a directory
4538  * and then set the in-memory index_cnt variable to reflect
4539  * free sequence numbers
4540  */
4541 static int btrfs_set_inode_index_count(struct inode *inode)
4542 {
4543         struct btrfs_root *root = BTRFS_I(inode)->root;
4544         struct btrfs_key key, found_key;
4545         struct btrfs_path *path;
4546         struct extent_buffer *leaf;
4547         int ret;
4548
4549         key.objectid = btrfs_ino(inode);
4550         btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4551         key.offset = (u64)-1;
4552
4553         path = btrfs_alloc_path();
4554         if (!path)
4555                 return -ENOMEM;
4556
4557         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4558         if (ret < 0)
4559                 goto out;
4560         /* FIXME: we should be able to handle this */
4561         if (ret == 0)
4562                 goto out;
4563         ret = 0;
4564
4565         /*
4566          * MAGIC NUMBER EXPLANATION:
4567          * since we search a directory based on f_pos we have to start at 2
4568          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4569          * else has to start at 2
4570          */
4571         if (path->slots[0] == 0) {
4572                 BTRFS_I(inode)->index_cnt = 2;
4573                 goto out;
4574         }
4575
4576         path->slots[0]--;
4577
4578         leaf = path->nodes[0];
4579         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4580
4581         if (found_key.objectid != btrfs_ino(inode) ||
4582             btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4583                 BTRFS_I(inode)->index_cnt = 2;
4584                 goto out;
4585         }
4586
4587         BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4588 out:
4589         btrfs_free_path(path);
4590         return ret;
4591 }
4592
4593 /*
4594  * helper to find a free sequence number in a given directory.  This current
4595  * code is very simple, later versions will do smarter things in the btree
4596  */
4597 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4598 {
4599         int ret = 0;
4600
4601         if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4602                 ret = btrfs_inode_delayed_dir_index_count(dir);
4603                 if (ret) {
4604                         ret = btrfs_set_inode_index_count(dir);
4605                         if (ret)
4606                                 return ret;
4607                 }
4608         }
4609
4610         *index = BTRFS_I(dir)->index_cnt;
4611         BTRFS_I(dir)->index_cnt++;
4612
4613         return ret;
4614 }
4615
4616 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4617                                      struct btrfs_root *root,
4618                                      struct inode *dir,
4619                                      const char *name, int name_len,
4620                                      u64 ref_objectid, u64 objectid,
4621                                      umode_t mode, u64 *index)
4622 {
4623         struct inode *inode;
4624         struct btrfs_inode_item *inode_item;
4625         struct btrfs_key *location;
4626         struct btrfs_path *path;
4627         struct btrfs_inode_ref *ref;
4628         struct btrfs_key key[2];
4629         u32 sizes[2];
4630         unsigned long ptr;
4631         int ret;
4632         int owner;
4633
4634         path = btrfs_alloc_path();
4635         if (!path)
4636                 return ERR_PTR(-ENOMEM);
4637
4638         inode = new_inode(root->fs_info->sb);
4639         if (!inode) {
4640                 btrfs_free_path(path);
4641                 return ERR_PTR(-ENOMEM);
4642         }
4643
4644         /*
4645          * we have to initialize this early, so we can reclaim the inode
4646          * number if we fail afterwards in this function.
4647          */
4648         inode->i_ino = objectid;
4649
4650         if (dir) {
4651                 trace_btrfs_inode_request(dir);
4652
4653                 ret = btrfs_set_inode_index(dir, index);
4654                 if (ret) {
4655                         btrfs_free_path(path);
4656                         iput(inode);
4657                         return ERR_PTR(ret);
4658                 }
4659         }
4660         /*
4661          * index_cnt is ignored for everything but a dir,
4662          * btrfs_get_inode_index_count has an explanation for the magic
4663          * number
4664          */
4665         BTRFS_I(inode)->index_cnt = 2;
4666         BTRFS_I(inode)->root = root;
4667         BTRFS_I(inode)->generation = trans->transid;
4668         inode->i_generation = BTRFS_I(inode)->generation;
4669
4670         if (S_ISDIR(mode))
4671                 owner = 0;
4672         else
4673                 owner = 1;
4674
4675         key[0].objectid = objectid;
4676         btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4677         key[0].offset = 0;
4678
4679         key[1].objectid = objectid;
4680         btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4681         key[1].offset = ref_objectid;
4682
4683         sizes[0] = sizeof(struct btrfs_inode_item);
4684         sizes[1] = name_len + sizeof(*ref);
4685
4686         path->leave_spinning = 1;
4687         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4688         if (ret != 0)
4689                 goto fail;
4690
4691         inode_init_owner(inode, dir, mode);
4692         inode_set_bytes(inode, 0);
4693         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4694         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4695                                   struct btrfs_inode_item);
4696         memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
4697                              sizeof(*inode_item));
4698         fill_inode_item(trans, path->nodes[0], inode_item, inode);
4699
4700         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4701                              struct btrfs_inode_ref);
4702         btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4703         btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4704         ptr = (unsigned long)(ref + 1);
4705         write_extent_buffer(path->nodes[0], name, ptr, name_len);
4706
4707         btrfs_mark_buffer_dirty(path->nodes[0]);
4708         btrfs_free_path(path);
4709
4710         location = &BTRFS_I(inode)->location;
4711         location->objectid = objectid;
4712         location->offset = 0;
4713         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4714
4715         btrfs_inherit_iflags(inode, dir);
4716
4717         if (S_ISREG(mode)) {
4718                 if (btrfs_test_opt(root, NODATASUM))
4719                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4720                 if (btrfs_test_opt(root, NODATACOW) ||
4721                     (BTRFS_I(dir)->flags & BTRFS_INODE_NODATACOW))
4722                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4723         }
4724
4725         insert_inode_hash(inode);
4726         inode_tree_add(inode);
4727
4728         trace_btrfs_inode_new(inode);
4729         btrfs_set_inode_last_trans(trans, inode);
4730
4731         btrfs_update_root_times(trans, root);
4732
4733         return inode;
4734 fail:
4735         if (dir)
4736                 BTRFS_I(dir)->index_cnt--;
4737         btrfs_free_path(path);
4738         iput(inode);
4739         return ERR_PTR(ret);
4740 }
4741
4742 static inline u8 btrfs_inode_type(struct inode *inode)
4743 {
4744         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4745 }
4746
4747 /*
4748  * utility function to add 'inode' into 'parent_inode' with
4749  * a give name and a given sequence number.
4750  * if 'add_backref' is true, also insert a backref from the
4751  * inode to the parent directory.
4752  */
4753 int btrfs_add_link(struct btrfs_trans_handle *trans,
4754                    struct inode *parent_inode, struct inode *inode,
4755                    const char *name, int name_len, int add_backref, u64 index)
4756 {
4757         int ret = 0;
4758         struct btrfs_key key;
4759         struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4760         u64 ino = btrfs_ino(inode);
4761         u64 parent_ino = btrfs_ino(parent_inode);
4762
4763         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4764                 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4765         } else {
4766                 key.objectid = ino;
4767                 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4768                 key.offset = 0;
4769         }
4770
4771         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4772                 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4773                                          key.objectid, root->root_key.objectid,
4774                                          parent_ino, index, name, name_len);
4775         } else if (add_backref) {
4776                 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
4777                                              parent_ino, index);
4778         }
4779
4780         /* Nothing to clean up yet */
4781         if (ret)
4782                 return ret;
4783
4784         ret = btrfs_insert_dir_item(trans, root, name, name_len,
4785                                     parent_inode, &key,
4786                                     btrfs_inode_type(inode), index);
4787         if (ret == -EEXIST)
4788                 goto fail_dir_item;
4789         else if (ret) {
4790                 btrfs_abort_transaction(trans, root, ret);
4791                 return ret;
4792         }
4793
4794         btrfs_i_size_write(parent_inode, parent_inode->i_size +
4795                            name_len * 2);
4796         inode_inc_iversion(parent_inode);
4797         parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4798         ret = btrfs_update_inode(trans, root, parent_inode);
4799         if (ret)
4800                 btrfs_abort_transaction(trans, root, ret);
4801         return ret;
4802
4803 fail_dir_item:
4804         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4805                 u64 local_index;
4806                 int err;
4807                 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4808                                  key.objectid, root->root_key.objectid,
4809                                  parent_ino, &local_index, name, name_len);
4810
4811         } else if (add_backref) {
4812                 u64 local_index;
4813                 int err;
4814
4815                 err = btrfs_del_inode_ref(trans, root, name, name_len,
4816                                           ino, parent_ino, &local_index);
4817         }
4818         return ret;
4819 }
4820
4821 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4822                             struct inode *dir, struct dentry *dentry,
4823                             struct inode *inode, int backref, u64 index)
4824 {
4825         int err = btrfs_add_link(trans, dir, inode,
4826                                  dentry->d_name.name, dentry->d_name.len,
4827                                  backref, index);
4828         if (err > 0)
4829                 err = -EEXIST;
4830         return err;
4831 }
4832
4833 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4834                         umode_t mode, dev_t rdev)
4835 {
4836         struct btrfs_trans_handle *trans;
4837         struct btrfs_root *root = BTRFS_I(dir)->root;
4838         struct inode *inode = NULL;
4839         int err;
4840         int drop_inode = 0;
4841         u64 objectid;
4842         unsigned long nr = 0;
4843         u64 index = 0;
4844
4845         if (!new_valid_dev(rdev))
4846                 return -EINVAL;
4847
4848         /*
4849          * 2 for inode item and ref
4850          * 2 for dir items
4851          * 1 for xattr if selinux is on
4852          */
4853         trans = btrfs_start_transaction(root, 5);
4854         if (IS_ERR(trans))
4855                 return PTR_ERR(trans);
4856
4857         err = btrfs_find_free_ino(root, &objectid);
4858         if (err)
4859                 goto out_unlock;
4860
4861         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4862                                 dentry->d_name.len, btrfs_ino(dir), objectid,
4863                                 mode, &index);
4864         if (IS_ERR(inode)) {
4865                 err = PTR_ERR(inode);
4866                 goto out_unlock;
4867         }
4868
4869         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4870         if (err) {
4871                 drop_inode = 1;
4872                 goto out_unlock;
4873         }
4874
4875         /*
4876         * If the active LSM wants to access the inode during
4877         * d_instantiate it needs these. Smack checks to see
4878         * if the filesystem supports xattrs by looking at the
4879         * ops vector.
4880         */
4881
4882         inode->i_op = &btrfs_special_inode_operations;
4883         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4884         if (err)
4885                 drop_inode = 1;
4886         else {
4887                 init_special_inode(inode, inode->i_mode, rdev);
4888                 btrfs_update_inode(trans, root, inode);
4889                 d_instantiate(dentry, inode);
4890         }
4891 out_unlock:
4892         nr = trans->blocks_used;
4893         btrfs_end_transaction(trans, root);
4894         btrfs_btree_balance_dirty(root, nr);
4895         if (drop_inode) {
4896                 inode_dec_link_count(inode);
4897                 iput(inode);
4898         }
4899         return err;
4900 }
4901
4902 static int btrfs_create(struct inode *dir, struct dentry *dentry,
4903                         umode_t mode, struct nameidata *nd)
4904 {
4905         struct btrfs_trans_handle *trans;
4906         struct btrfs_root *root = BTRFS_I(dir)->root;
4907         struct inode *inode = NULL;
4908         int drop_inode = 0;
4909         int err;
4910         unsigned long nr = 0;
4911         u64 objectid;
4912         u64 index = 0;
4913
4914         /*
4915          * 2 for inode item and ref
4916          * 2 for dir items
4917          * 1 for xattr if selinux is on
4918          */
4919         trans = btrfs_start_transaction(root, 5);
4920         if (IS_ERR(trans))
4921                 return PTR_ERR(trans);
4922
4923         err = btrfs_find_free_ino(root, &objectid);
4924         if (err)
4925                 goto out_unlock;
4926
4927         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4928                                 dentry->d_name.len, btrfs_ino(dir), objectid,
4929                                 mode, &index);
4930         if (IS_ERR(inode)) {
4931                 err = PTR_ERR(inode);
4932                 goto out_unlock;
4933         }
4934
4935         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4936         if (err) {
4937                 drop_inode = 1;
4938                 goto out_unlock;
4939         }
4940
4941         /*
4942         * If the active LSM wants to access the inode during
4943         * d_instantiate it needs these. Smack checks to see
4944         * if the filesystem supports xattrs by looking at the
4945         * ops vector.
4946         */
4947         inode->i_fop = &btrfs_file_operations;
4948         inode->i_op = &btrfs_file_inode_operations;
4949
4950         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4951         if (err)
4952                 drop_inode = 1;
4953         else {
4954                 inode->i_mapping->a_ops = &btrfs_aops;
4955                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4956                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4957                 d_instantiate(dentry, inode);
4958         }
4959 out_unlock:
4960         nr = trans->blocks_used;
4961         btrfs_end_transaction(trans, root);
4962         if (drop_inode) {
4963                 inode_dec_link_count(inode);
4964                 iput(inode);
4965         }
4966         btrfs_btree_balance_dirty(root, nr);
4967         return err;
4968 }
4969
4970 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4971                       struct dentry *dentry)
4972 {
4973         struct btrfs_trans_handle *trans;
4974         struct btrfs_root *root = BTRFS_I(dir)->root;
4975         struct inode *inode = old_dentry->d_inode;
4976         u64 index;
4977         unsigned long nr = 0;
4978         int err;
4979         int drop_inode = 0;
4980
4981         /* do not allow sys_link's with other subvols of the same device */
4982         if (root->objectid != BTRFS_I(inode)->root->objectid)
4983                 return -EXDEV;
4984
4985         if (inode->i_nlink == ~0U)
4986                 return -EMLINK;
4987
4988         err = btrfs_set_inode_index(dir, &index);
4989         if (err)
4990                 goto fail;
4991
4992         /*
4993          * 2 items for inode and inode ref
4994          * 2 items for dir items
4995          * 1 item for parent inode
4996          */
4997         trans = btrfs_start_transaction(root, 5);
4998         if (IS_ERR(trans)) {
4999                 err = PTR_ERR(trans);
5000                 goto fail;
5001         }
5002
5003         btrfs_inc_nlink(inode);
5004         inode_inc_iversion(inode);
5005         inode->i_ctime = CURRENT_TIME;
5006         ihold(inode);
5007
5008         err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5009
5010         if (err) {
5011                 drop_inode = 1;
5012         } else {
5013                 struct dentry *parent = dentry->d_parent;
5014                 err = btrfs_update_inode(trans, root, inode);
5015                 if (err)
5016                         goto fail;
5017                 d_instantiate(dentry, inode);
5018                 btrfs_log_new_name(trans, inode, NULL, parent);
5019         }
5020
5021         nr = trans->blocks_used;
5022         btrfs_end_transaction(trans, root);
5023 fail:
5024         if (drop_inode) {
5025                 inode_dec_link_count(inode);
5026                 iput(inode);
5027         }
5028         btrfs_btree_balance_dirty(root, nr);
5029         return err;
5030 }
5031
5032 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5033 {
5034         struct inode *inode = NULL;
5035         struct btrfs_trans_handle *trans;
5036         struct btrfs_root *root = BTRFS_I(dir)->root;
5037         int err = 0;
5038         int drop_on_err = 0;
5039         u64 objectid = 0;
5040         u64 index = 0;
5041         unsigned long nr = 1;
5042
5043         /*
5044          * 2 items for inode and ref
5045          * 2 items for dir items
5046          * 1 for xattr if selinux is on
5047          */
5048         trans = btrfs_start_transaction(root, 5);
5049         if (IS_ERR(trans))
5050                 return PTR_ERR(trans);
5051
5052         err = btrfs_find_free_ino(root, &objectid);
5053         if (err)
5054                 goto out_fail;
5055
5056         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5057                                 dentry->d_name.len, btrfs_ino(dir), objectid,
5058                                 S_IFDIR | mode, &index);
5059         if (IS_ERR(inode)) {
5060                 err = PTR_ERR(inode);
5061                 goto out_fail;
5062         }
5063
5064         drop_on_err = 1;
5065
5066         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5067         if (err)
5068                 goto out_fail;
5069
5070         inode->i_op = &btrfs_dir_inode_operations;
5071         inode->i_fop = &btrfs_dir_file_operations;
5072
5073         btrfs_i_size_write(inode, 0);
5074         err = btrfs_update_inode(trans, root, inode);
5075         if (err)
5076                 goto out_fail;
5077
5078         err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5079                              dentry->d_name.len, 0, index);
5080         if (err)
5081                 goto out_fail;
5082
5083         d_instantiate(dentry, inode);
5084         drop_on_err = 0;
5085
5086 out_fail:
5087         nr = trans->blocks_used;
5088         btrfs_end_transaction(trans, root);
5089         if (drop_on_err)
5090                 iput(inode);
5091         btrfs_btree_balance_dirty(root, nr);
5092         return err;
5093 }
5094
5095 /* helper for btfs_get_extent.  Given an existing extent in the tree,
5096  * and an extent that you want to insert, deal with overlap and insert
5097  * the new extent into the tree.
5098  */
5099 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5100                                 struct extent_map *existing,
5101                                 struct extent_map *em,
5102                                 u64 map_start, u64 map_len)
5103 {
5104         u64 start_diff;
5105
5106         BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5107         start_diff = map_start - em->start;
5108         em->start = map_start;
5109         em->len = map_len;
5110         if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5111             !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5112                 em->block_start += start_diff;
5113                 em->block_len -= start_diff;
5114         }
5115         return add_extent_mapping(em_tree, em);
5116 }
5117
5118 static noinline int uncompress_inline(struct btrfs_path *path,
5119                                       struct inode *inode, struct page *page,
5120                                       size_t pg_offset, u64 extent_offset,
5121                                       struct btrfs_file_extent_item *item)
5122 {
5123         int ret;
5124         struct extent_buffer *leaf = path->nodes[0];
5125         char *tmp;
5126         size_t max_size;
5127         unsigned long inline_size;
5128         unsigned long ptr;
5129         int compress_type;
5130
5131         WARN_ON(pg_offset != 0);
5132         compress_type = btrfs_file_extent_compression(leaf, item);
5133         max_size = btrfs_file_extent_ram_bytes(leaf, item);
5134         inline_size = btrfs_file_extent_inline_item_len(leaf,
5135                                         btrfs_item_nr(leaf, path->slots[0]));
5136         tmp = kmalloc(inline_size, GFP_NOFS);
5137         if (!tmp)
5138                 return -ENOMEM;
5139         ptr = btrfs_file_extent_inline_start(item);
5140
5141         read_extent_buffer(leaf, tmp, ptr, inline_size);
5142
5143         max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
5144         ret = btrfs_decompress(compress_type, tmp, page,
5145                                extent_offset, inline_size, max_size);
5146         if (ret) {
5147                 char *kaddr = kmap_atomic(page);
5148                 unsigned long copy_size = min_t(u64,
5149                                   PAGE_CACHE_SIZE - pg_offset,
5150                                   max_size - extent_offset);
5151                 memset(kaddr + pg_offset, 0, copy_size);
5152                 kunmap_atomic(kaddr);
5153         }
5154         kfree(tmp);
5155         return 0;
5156 }
5157
5158 /*
5159  * a bit scary, this does extent mapping from logical file offset to the disk.
5160  * the ugly parts come from merging extents from the disk with the in-ram
5161  * representation.  This gets more complex because of the data=ordered code,
5162  * where the in-ram extents might be locked pending data=ordered completion.
5163  *
5164  * This also copies inline extents directly into the page.
5165  */
5166
5167 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5168                                     size_t pg_offset, u64 start, u64 len,
5169                                     int create)
5170 {
5171         int ret;
5172         int err = 0;
5173         u64 bytenr;
5174         u64 extent_start = 0;
5175         u64 extent_end = 0;
5176         u64 objectid = btrfs_ino(inode);
5177         u32 found_type;
5178         struct btrfs_path *path = NULL;
5179         struct btrfs_root *root = BTRFS_I(inode)->root;
5180         struct btrfs_file_extent_item *item;
5181         struct extent_buffer *leaf;
5182         struct btrfs_key found_key;
5183         struct extent_map *em = NULL;
5184         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5185         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5186         struct btrfs_trans_handle *trans = NULL;
5187         int compress_type;
5188
5189 again:
5190         read_lock(&em_tree->lock);
5191         em = lookup_extent_mapping(em_tree, start, len);
5192         if (em)
5193                 em->bdev = root->fs_info->fs_devices->latest_bdev;
5194         read_unlock(&em_tree->lock);
5195
5196         if (em) {
5197                 if (em->start > start || em->start + em->len <= start)
5198                         free_extent_map(em);
5199                 else if (em->block_start == EXTENT_MAP_INLINE && page)
5200                         free_extent_map(em);
5201                 else
5202                         goto out;
5203         }
5204         em = alloc_extent_map();
5205         if (!em) {
5206                 err = -ENOMEM;
5207                 goto out;
5208         }
5209         em->bdev = root->fs_info->fs_devices->latest_bdev;
5210         em->start = EXTENT_MAP_HOLE;
5211         em->orig_start = EXTENT_MAP_HOLE;
5212         em->len = (u64)-1;
5213         em->block_len = (u64)-1;
5214
5215         if (!path) {
5216                 path = btrfs_alloc_path();
5217                 if (!path) {
5218                         err = -ENOMEM;
5219                         goto out;
5220                 }
5221                 /*
5222                  * Chances are we'll be called again, so go ahead and do
5223                  * readahead
5224                  */
5225                 path->reada = 1;
5226         }
5227
5228         ret = btrfs_lookup_file_extent(trans, root, path,
5229                                        objectid, start, trans != NULL);
5230         if (ret < 0) {
5231                 err = ret;
5232                 goto out;
5233         }
5234
5235         if (ret != 0) {
5236                 if (path->slots[0] == 0)
5237                         goto not_found;
5238                 path->slots[0]--;
5239         }
5240
5241         leaf = path->nodes[0];
5242         item = btrfs_item_ptr(leaf, path->slots[0],
5243                               struct btrfs_file_extent_item);
5244         /* are we inside the extent that was found? */
5245         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5246         found_type = btrfs_key_type(&found_key);
5247         if (found_key.objectid != objectid ||
5248             found_type != BTRFS_EXTENT_DATA_KEY) {
5249                 goto not_found;
5250         }
5251
5252         found_type = btrfs_file_extent_type(leaf, item);
5253         extent_start = found_key.offset;
5254         compress_type = btrfs_file_extent_compression(leaf, item);
5255         if (found_type == BTRFS_FILE_EXTENT_REG ||
5256             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5257                 extent_end = extent_start +
5258                        btrfs_file_extent_num_bytes(leaf, item);
5259         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5260                 size_t size;
5261                 size = btrfs_file_extent_inline_len(leaf, item);
5262                 extent_end = (extent_start + size + root->sectorsize - 1) &
5263                         ~((u64)root->sectorsize - 1);
5264         }
5265
5266         if (start >= extent_end) {
5267                 path->slots[0]++;
5268                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5269                         ret = btrfs_next_leaf(root, path);
5270                         if (ret < 0) {
5271                                 err = ret;
5272                                 goto out;
5273                         }
5274                         if (ret > 0)
5275                                 goto not_found;
5276                         leaf = path->nodes[0];
5277                 }
5278                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5279                 if (found_key.objectid != objectid ||
5280                     found_key.type != BTRFS_EXTENT_DATA_KEY)
5281                         goto not_found;
5282                 if (start + len <= found_key.offset)
5283                         goto not_found;
5284                 em->start = start;
5285                 em->len = found_key.offset - start;
5286                 goto not_found_em;
5287         }
5288
5289         if (found_type == BTRFS_FILE_EXTENT_REG ||
5290             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5291                 em->start = extent_start;
5292                 em->len = extent_end - extent_start;
5293                 em->orig_start = extent_start -
5294                                  btrfs_file_extent_offset(leaf, item);
5295                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5296                 if (bytenr == 0) {
5297                         em->block_start = EXTENT_MAP_HOLE;
5298                         goto insert;
5299                 }
5300                 if (compress_type != BTRFS_COMPRESS_NONE) {
5301                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5302                         em->compress_type = compress_type;
5303                         em->block_start = bytenr;
5304                         em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
5305                                                                          item);
5306                 } else {
5307                         bytenr += btrfs_file_extent_offset(leaf, item);
5308                         em->block_start = bytenr;
5309                         em->block_len = em->len;
5310                         if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5311                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5312                 }
5313                 goto insert;
5314         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5315                 unsigned long ptr;
5316                 char *map;
5317                 size_t size;
5318                 size_t extent_offset;
5319                 size_t copy_size;
5320
5321                 em->block_start = EXTENT_MAP_INLINE;
5322                 if (!page || create) {
5323                         em->start = extent_start;
5324                         em->len = extent_end - extent_start;
5325                         goto out;
5326                 }
5327
5328                 size = btrfs_file_extent_inline_len(leaf, item);
5329                 extent_offset = page_offset(page) + pg_offset - extent_start;
5330                 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5331                                 size - extent_offset);
5332                 em->start = extent_start + extent_offset;
5333                 em->len = (copy_size + root->sectorsize - 1) &
5334                         ~((u64)root->sectorsize - 1);
5335                 em->orig_start = EXTENT_MAP_INLINE;
5336                 if (compress_type) {
5337                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5338                         em->compress_type = compress_type;
5339                 }
5340                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5341                 if (create == 0 && !PageUptodate(page)) {
5342                         if (btrfs_file_extent_compression(leaf, item) !=
5343                             BTRFS_COMPRESS_NONE) {
5344                                 ret = uncompress_inline(path, inode, page,
5345                                                         pg_offset,
5346                                                         extent_offset, item);
5347                                 BUG_ON(ret); /* -ENOMEM */
5348                         } else {
5349                                 map = kmap(page);
5350                                 read_extent_buffer(leaf, map + pg_offset, ptr,
5351                                                    copy_size);
5352                                 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5353                                         memset(map + pg_offset + copy_size, 0,
5354                                                PAGE_CACHE_SIZE - pg_offset -
5355                                                copy_size);
5356                                 }
5357                                 kunmap(page);
5358                         }
5359                         flush_dcache_page(page);
5360                 } else if (create && PageUptodate(page)) {
5361                         BUG();
5362                         if (!trans) {
5363                                 kunmap(page);
5364                                 free_extent_map(em);
5365                                 em = NULL;
5366
5367                                 btrfs_release_path(path);
5368                                 trans = btrfs_join_transaction(root);
5369
5370                                 if (IS_ERR(trans))
5371                                         return ERR_CAST(trans);
5372                                 goto again;
5373                         }
5374                         map = kmap(page);
5375                         write_extent_buffer(leaf, map + pg_offset, ptr,
5376                                             copy_size);
5377                         kunmap(page);
5378                         btrfs_mark_buffer_dirty(leaf);
5379                 }
5380                 set_extent_uptodate(io_tree, em->start,
5381                                     extent_map_end(em) - 1, NULL, GFP_NOFS);
5382                 goto insert;
5383         } else {
5384                 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
5385                 WARN_ON(1);
5386         }
5387 not_found:
5388         em->start = start;
5389         em->len = len;
5390 not_found_em:
5391         em->block_start = EXTENT_MAP_HOLE;
5392         set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5393 insert:
5394         btrfs_release_path(path);
5395         if (em->start > start || extent_map_end(em) <= start) {
5396                 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5397                        "[%llu %llu]\n", (unsigned long long)em->start,
5398                        (unsigned long long)em->len,
5399                        (unsigned long long)start,
5400                        (unsigned long long)len);
5401                 err = -EIO;
5402                 goto out;
5403         }
5404
5405         err = 0;
5406         write_lock(&em_tree->lock);
5407         ret = add_extent_mapping(em_tree, em);
5408         /* it is possible that someone inserted the extent into the tree
5409          * while we had the lock dropped.  It is also possible that
5410          * an overlapping map exists in the tree
5411          */
5412         if (ret == -EEXIST) {
5413                 struct extent_map *existing;
5414
5415                 ret = 0;
5416
5417                 existing = lookup_extent_mapping(em_tree, start, len);
5418                 if (existing && (existing->start > start ||
5419                     existing->start + existing->len <= start)) {
5420                         free_extent_map(existing);
5421                         existing = NULL;
5422                 }
5423                 if (!existing) {
5424                         existing = lookup_extent_mapping(em_tree, em->start,
5425                                                          em->len);
5426                         if (existing) {
5427                                 err = merge_extent_mapping(em_tree, existing,
5428                                                            em, start,
5429                                                            root->sectorsize);
5430                                 free_extent_map(existing);
5431                                 if (err) {
5432                                         free_extent_map(em);
5433                                         em = NULL;
5434                                 }
5435                         } else {
5436                                 err = -EIO;
5437                                 free_extent_map(em);
5438                                 em = NULL;
5439                         }
5440                 } else {
5441                         free_extent_map(em);
5442                         em = existing;
5443                         err = 0;
5444                 }
5445         }
5446         write_unlock(&em_tree->lock);
5447 out:
5448
5449         trace_btrfs_get_extent(root, em);
5450
5451         if (path)
5452                 btrfs_free_path(path);
5453         if (trans) {
5454                 ret = btrfs_end_transaction(trans, root);
5455                 if (!err)
5456                         err = ret;
5457         }
5458         if (err) {
5459                 free_extent_map(em);
5460                 return ERR_PTR(err);
5461         }
5462         BUG_ON(!em); /* Error is always set */
5463         return em;
5464 }
5465
5466 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5467                                            size_t pg_offset, u64 start, u64 len,
5468                                            int create)
5469 {
5470         struct extent_map *em;
5471         struct extent_map *hole_em = NULL;
5472         u64 range_start = start;
5473         u64 end;
5474         u64 found;
5475         u64 found_end;
5476         int err = 0;
5477
5478         em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5479         if (IS_ERR(em))
5480                 return em;
5481         if (em) {
5482                 /*
5483                  * if our em maps to a hole, there might
5484                  * actually be delalloc bytes behind it
5485                  */
5486                 if (em->block_start != EXTENT_MAP_HOLE)
5487                         return em;
5488                 else
5489                         hole_em = em;
5490         }
5491
5492         /* check to see if we've wrapped (len == -1 or similar) */
5493         end = start + len;
5494         if (end < start)
5495                 end = (u64)-1;
5496         else
5497                 end -= 1;
5498
5499         em = NULL;
5500
5501         /* ok, we didn't find anything, lets look for delalloc */
5502         found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5503                                  end, len, EXTENT_DELALLOC, 1);
5504         found_end = range_start + found;
5505         if (found_end < range_start)
5506                 found_end = (u64)-1;
5507
5508         /*
5509          * we didn't find anything useful, return
5510          * the original results from get_extent()
5511          */
5512         if (range_start > end || found_end <= start) {
5513                 em = hole_em;
5514                 hole_em = NULL;
5515                 goto out;
5516         }
5517
5518         /* adjust the range_start to make sure it doesn't
5519          * go backwards from the start they passed in
5520          */
5521         range_start = max(start,range_start);
5522         found = found_end - range_start;
5523
5524         if (found > 0) {
5525                 u64 hole_start = start;
5526                 u64 hole_len = len;
5527
5528                 em = alloc_extent_map();
5529                 if (!em) {
5530                         err = -ENOMEM;
5531                         goto out;
5532                 }
5533                 /*
5534                  * when btrfs_get_extent can't find anything it
5535                  * returns one huge hole
5536                  *
5537                  * make sure what it found really fits our range, and
5538                  * adjust to make sure it is based on the start from
5539                  * the caller
5540                  */
5541                 if (hole_em) {
5542                         u64 calc_end = extent_map_end(hole_em);
5543
5544                         if (calc_end <= start || (hole_em->start > end)) {
5545                                 free_extent_map(hole_em);
5546                                 hole_em = NULL;
5547                         } else {
5548                                 hole_start = max(hole_em->start, start);
5549                                 hole_len = calc_end - hole_start;
5550                         }
5551                 }
5552                 em->bdev = NULL;
5553                 if (hole_em && range_start > hole_start) {
5554                         /* our hole starts before our delalloc, so we
5555                          * have to return just the parts of the hole
5556                          * that go until  the delalloc starts
5557                          */
5558                         em->len = min(hole_len,
5559                                       range_start - hole_start);
5560                         em->start = hole_start;
5561                         em->orig_start = hole_start;
5562                         /*
5563                          * don't adjust block start at all,
5564                          * it is fixed at EXTENT_MAP_HOLE
5565                          */
5566                         em->block_start = hole_em->block_start;
5567                         em->block_len = hole_len;
5568                 } else {
5569                         em->start = range_start;
5570                         em->len = found;
5571                         em->orig_start = range_start;
5572                         em->block_start = EXTENT_MAP_DELALLOC;
5573                         em->block_len = found;
5574                 }
5575         } else if (hole_em) {
5576                 return hole_em;
5577         }
5578 out:
5579
5580         free_extent_map(hole_em);
5581         if (err) {
5582                 free_extent_map(em);
5583                 return ERR_PTR(err);
5584         }
5585         return em;
5586 }
5587
5588 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5589                                                   struct extent_map *em,
5590