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