Merge git://git.kernel.org/pub/scm/linux/kernel/git/mason/btrfs-unstable
[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      &nbs