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