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