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