Btrfs: Add fallocate support v2
[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/smp_lock.h>
30 #include <linux/backing-dev.h>
31 #include <linux/mpage.h>
32 #include <linux/swap.h>
33 #include <linux/writeback.h>
34 #include <linux/statfs.h>
35 #include <linux/compat.h>
36 #include <linux/bit_spinlock.h>
37 #include <linux/version.h>
38 #include <linux/xattr.h>
39 #include <linux/posix_acl.h>
40 #include <linux/falloc.h>
41 #include "ctree.h"
42 #include "disk-io.h"
43 #include "transaction.h"
44 #include "btrfs_inode.h"
45 #include "ioctl.h"
46 #include "print-tree.h"
47 #include "volumes.h"
48 #include "ordered-data.h"
49 #include "xattr.h"
50 #include "compat.h"
51 #include "tree-log.h"
52 #include "ref-cache.h"
53 #include "compression.h"
54
55 struct btrfs_iget_args {
56         u64 ino;
57         struct btrfs_root *root;
58 };
59
60 static struct inode_operations btrfs_dir_inode_operations;
61 static struct inode_operations btrfs_symlink_inode_operations;
62 static struct inode_operations btrfs_dir_ro_inode_operations;
63 static struct inode_operations btrfs_special_inode_operations;
64 static struct inode_operations btrfs_file_inode_operations;
65 static struct address_space_operations btrfs_aops;
66 static struct address_space_operations btrfs_symlink_aops;
67 static struct file_operations btrfs_dir_file_operations;
68 static struct extent_io_ops btrfs_extent_io_ops;
69
70 static struct kmem_cache *btrfs_inode_cachep;
71 struct kmem_cache *btrfs_trans_handle_cachep;
72 struct kmem_cache *btrfs_transaction_cachep;
73 struct kmem_cache *btrfs_bit_radix_cachep;
74 struct kmem_cache *btrfs_path_cachep;
75
76 #define S_SHIFT 12
77 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
78         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
79         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
80         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
81         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
82         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
83         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
84         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
85 };
86
87 static void btrfs_truncate(struct inode *inode);
88 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
89
90 /*
91  * a very lame attempt at stopping writes when the FS is 85% full.  There
92  * are countless ways this is incorrect, but it is better than nothing.
93  */
94 int btrfs_check_free_space(struct btrfs_root *root, u64 num_required,
95                            int for_del)
96 {
97         u64 total;
98         u64 used;
99         u64 thresh;
100         unsigned long flags;
101         int ret = 0;
102
103         spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
104         total = btrfs_super_total_bytes(&root->fs_info->super_copy);
105         used = btrfs_super_bytes_used(&root->fs_info->super_copy);
106         if (for_del)
107                 thresh = total * 90;
108         else
109                 thresh = total * 85;
110
111         do_div(thresh, 100);
112
113         if (used + root->fs_info->delalloc_bytes + num_required > thresh)
114                 ret = -ENOSPC;
115         spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
116         return ret;
117 }
118
119 /*
120  * this does all the hard work for inserting an inline extent into
121  * the btree.  The caller should have done a btrfs_drop_extents so that
122  * no overlapping inline items exist in the btree
123  */
124 static int noinline insert_inline_extent(struct btrfs_trans_handle *trans,
125                                 struct btrfs_root *root, struct inode *inode,
126                                 u64 start, size_t size, size_t compressed_size,
127                                 struct page **compressed_pages)
128 {
129         struct btrfs_key key;
130         struct btrfs_path *path;
131         struct extent_buffer *leaf;
132         struct page *page = NULL;
133         char *kaddr;
134         unsigned long ptr;
135         struct btrfs_file_extent_item *ei;
136         int err = 0;
137         int ret;
138         size_t cur_size = size;
139         size_t datasize;
140         unsigned long offset;
141         int use_compress = 0;
142
143         if (compressed_size && compressed_pages) {
144                 use_compress = 1;
145                 cur_size = compressed_size;
146         }
147
148         path = btrfs_alloc_path(); if (!path)
149                 return -ENOMEM;
150
151         btrfs_set_trans_block_group(trans, inode);
152
153         key.objectid = inode->i_ino;
154         key.offset = start;
155         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
156         inode_add_bytes(inode, size);
157         datasize = btrfs_file_extent_calc_inline_size(cur_size);
158
159         inode_add_bytes(inode, size);
160         ret = btrfs_insert_empty_item(trans, root, path, &key,
161                                       datasize);
162         BUG_ON(ret);
163         if (ret) {
164                 err = ret;
165                 printk("got bad ret %d\n", ret);
166                 goto fail;
167         }
168         leaf = path->nodes[0];
169         ei = btrfs_item_ptr(leaf, path->slots[0],
170                             struct btrfs_file_extent_item);
171         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
172         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
173         btrfs_set_file_extent_encryption(leaf, ei, 0);
174         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
175         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
176         ptr = btrfs_file_extent_inline_start(ei);
177
178         if (use_compress) {
179                 struct page *cpage;
180                 int i = 0;
181                 while(compressed_size > 0) {
182                         cpage = compressed_pages[i];
183                         cur_size = min(compressed_size,
184                                        PAGE_CACHE_SIZE);
185
186                         kaddr = kmap(cpage);
187                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
188                         kunmap(cpage);
189
190                         i++;
191                         ptr += cur_size;
192                         compressed_size -= cur_size;
193                 }
194                 btrfs_set_file_extent_compression(leaf, ei,
195                                                   BTRFS_COMPRESS_ZLIB);
196         } else {
197                 page = find_get_page(inode->i_mapping,
198                                      start >> PAGE_CACHE_SHIFT);
199                 btrfs_set_file_extent_compression(leaf, ei, 0);
200                 kaddr = kmap_atomic(page, KM_USER0);
201                 offset = start & (PAGE_CACHE_SIZE - 1);
202                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
203                 kunmap_atomic(kaddr, KM_USER0);
204                 page_cache_release(page);
205         }
206         btrfs_mark_buffer_dirty(leaf);
207         btrfs_free_path(path);
208
209         BTRFS_I(inode)->disk_i_size = inode->i_size;
210         btrfs_update_inode(trans, root, inode);
211         return 0;
212 fail:
213         btrfs_free_path(path);
214         return err;
215 }
216
217
218 /*
219  * conditionally insert an inline extent into the file.  This
220  * does the checks required to make sure the data is small enough
221  * to fit as an inline extent.
222  */
223 static int cow_file_range_inline(struct btrfs_trans_handle *trans,
224                                  struct btrfs_root *root,
225                                  struct inode *inode, u64 start, u64 end,
226                                  size_t compressed_size,
227                                  struct page **compressed_pages)
228 {
229         u64 isize = i_size_read(inode);
230         u64 actual_end = min(end + 1, isize);
231         u64 inline_len = actual_end - start;
232         u64 aligned_end = (end + root->sectorsize - 1) &
233                         ~((u64)root->sectorsize - 1);
234         u64 hint_byte;
235         u64 data_len = inline_len;
236         int ret;
237
238         if (compressed_size)
239                 data_len = compressed_size;
240
241         if (start > 0 ||
242             data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
243             (!compressed_size &&
244             (actual_end & (root->sectorsize - 1)) == 0) ||
245             end + 1 < isize ||
246             data_len > root->fs_info->max_inline) {
247                 return 1;
248         }
249
250         ret = btrfs_drop_extents(trans, root, inode, start,
251                                  aligned_end, aligned_end, &hint_byte);
252         BUG_ON(ret);
253
254         if (isize > actual_end)
255                 inline_len = min_t(u64, isize, actual_end);
256         ret = insert_inline_extent(trans, root, inode, start,
257                                    inline_len, compressed_size,
258                                    compressed_pages);
259         BUG_ON(ret);
260         btrfs_drop_extent_cache(inode, start, aligned_end, 0);
261         return 0;
262 }
263
264 /*
265  * when extent_io.c finds a delayed allocation range in the file,
266  * the call backs end up in this code.  The basic idea is to
267  * allocate extents on disk for the range, and create ordered data structs
268  * in ram to track those extents.
269  *
270  * locked_page is the page that writepage had locked already.  We use
271  * it to make sure we don't do extra locks or unlocks.
272  *
273  * *page_started is set to one if we unlock locked_page and do everything
274  * required to start IO on it.  It may be clean and already done with
275  * IO when we return.
276  */
277 static int cow_file_range(struct inode *inode, struct page *locked_page,
278                           u64 start, u64 end, int *page_started)
279 {
280         struct btrfs_root *root = BTRFS_I(inode)->root;
281         struct btrfs_trans_handle *trans;
282         u64 alloc_hint = 0;
283         u64 num_bytes;
284         unsigned long ram_size;
285         u64 orig_start;
286         u64 disk_num_bytes;
287         u64 cur_alloc_size;
288         u64 blocksize = root->sectorsize;
289         u64 actual_end;
290         struct btrfs_key ins;
291         struct extent_map *em;
292         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
293         int ret = 0;
294         struct page **pages = NULL;
295         unsigned long nr_pages;
296         unsigned long nr_pages_ret = 0;
297         unsigned long total_compressed = 0;
298         unsigned long total_in = 0;
299         unsigned long max_compressed = 128 * 1024;
300         unsigned long max_uncompressed = 256 * 1024;
301         int i;
302         int ordered_type;
303         int will_compress;
304
305         trans = btrfs_join_transaction(root, 1);
306         BUG_ON(!trans);
307         btrfs_set_trans_block_group(trans, inode);
308         orig_start = start;
309
310         /*
311          * compression made this loop a bit ugly, but the basic idea is to
312          * compress some pages but keep the total size of the compressed
313          * extent relatively small.  If compression is off, this goto target
314          * is never used.
315          */
316 again:
317         will_compress = 0;
318         nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
319         nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
320
321         actual_end = min_t(u64, i_size_read(inode), end + 1);
322         total_compressed = actual_end - start;
323
324         /* we want to make sure that amount of ram required to uncompress
325          * an extent is reasonable, so we limit the total size in ram
326          * of a compressed extent to 256k
327          */
328         total_compressed = min(total_compressed, max_uncompressed);
329         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
330         num_bytes = max(blocksize,  num_bytes);
331         disk_num_bytes = num_bytes;
332         total_in = 0;
333         ret = 0;
334
335         /* we do compression for mount -o compress and when the
336          * inode has not been flagged as nocompress
337          */
338         if (!btrfs_test_flag(inode, NOCOMPRESS) &&
339             btrfs_test_opt(root, COMPRESS)) {
340                 WARN_ON(pages);
341                 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
342
343                 /* we want to make sure the amount of IO required to satisfy
344                  * a random read is reasonably small, so we limit the size
345                  * of a compressed extent to 128k
346                  */
347                 ret = btrfs_zlib_compress_pages(inode->i_mapping, start,
348                                                 total_compressed, pages,
349                                                 nr_pages, &nr_pages_ret,
350                                                 &total_in,
351                                                 &total_compressed,
352                                                 max_compressed);
353
354                 if (!ret) {
355                         unsigned long offset = total_compressed &
356                                 (PAGE_CACHE_SIZE - 1);
357                         struct page *page = pages[nr_pages_ret - 1];
358                         char *kaddr;
359
360                         /* zero the tail end of the last page, we might be
361                          * sending it down to disk
362                          */
363                         if (offset) {
364                                 kaddr = kmap_atomic(page, KM_USER0);
365                                 memset(kaddr + offset, 0,
366                                        PAGE_CACHE_SIZE - offset);
367                                 kunmap_atomic(kaddr, KM_USER0);
368                         }
369                         will_compress = 1;
370                 }
371         }
372         if (start == 0) {
373                 /* lets try to make an inline extent */
374                 if (ret || total_in < (end - start + 1)) {
375                         /* we didn't compress the entire range, try
376                          * to make an uncompressed inline extent.  This
377                          * is almost sure to fail, but maybe inline sizes
378                          * will get bigger later
379                          */
380                         ret = cow_file_range_inline(trans, root, inode,
381                                                     start, end, 0, NULL);
382                 } else {
383                         ret = cow_file_range_inline(trans, root, inode,
384                                                     start, end,
385                                                     total_compressed, pages);
386                 }
387                 if (ret == 0) {
388                         extent_clear_unlock_delalloc(inode,
389                                                      &BTRFS_I(inode)->io_tree,
390                                                      start, end, NULL,
391                                                      1, 1, 1);
392                         *page_started = 1;
393                         ret = 0;
394                         goto free_pages_out;
395                 }
396         }
397
398         if (will_compress) {
399                 /*
400                  * we aren't doing an inline extent round the compressed size
401                  * up to a block size boundary so the allocator does sane
402                  * things
403                  */
404                 total_compressed = (total_compressed + blocksize - 1) &
405                         ~(blocksize - 1);
406
407                 /*
408                  * one last check to make sure the compression is really a
409                  * win, compare the page count read with the blocks on disk
410                  */
411                 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
412                         ~(PAGE_CACHE_SIZE - 1);
413                 if (total_compressed >= total_in) {
414                         will_compress = 0;
415                 } else {
416                         disk_num_bytes = total_compressed;
417                         num_bytes = total_in;
418                 }
419         }
420         if (!will_compress && pages) {
421                 /*
422                  * the compression code ran but failed to make things smaller,
423                  * free any pages it allocated and our page pointer array
424                  */
425                 for (i = 0; i < nr_pages_ret; i++) {
426                         page_cache_release(pages[i]);
427                 }
428                 kfree(pages);
429                 pages = NULL;
430                 total_compressed = 0;
431                 nr_pages_ret = 0;
432
433                 /* flag the file so we don't compress in the future */
434                 btrfs_set_flag(inode, NOCOMPRESS);
435         }
436
437         BUG_ON(disk_num_bytes >
438                btrfs_super_total_bytes(&root->fs_info->super_copy));
439
440         btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
441
442         while(disk_num_bytes > 0) {
443                 unsigned long min_bytes;
444
445                 /*
446                  * the max size of a compressed extent is pretty small,
447                  * make the code a little less complex by forcing
448                  * the allocator to find a whole compressed extent at once
449                  */
450                 if (will_compress)
451                         min_bytes = disk_num_bytes;
452                 else
453                         min_bytes = root->sectorsize;
454
455                 cur_alloc_size = min(disk_num_bytes, root->fs_info->max_extent);
456                 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
457                                            min_bytes, 0, alloc_hint,
458                                            (u64)-1, &ins, 1);
459                 if (ret) {
460                         WARN_ON(1);
461                         goto free_pages_out_fail;
462                 }
463                 em = alloc_extent_map(GFP_NOFS);
464                 em->start = start;
465
466                 if (will_compress) {
467                         ram_size = num_bytes;
468                         em->len = num_bytes;
469                 } else {
470                         /* ramsize == disk size */
471                         ram_size = ins.offset;
472                         em->len = ins.offset;
473                 }
474
475                 em->block_start = ins.objectid;
476                 em->block_len = ins.offset;
477                 em->bdev = root->fs_info->fs_devices->latest_bdev;
478                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
479
480                 if (will_compress)
481                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
482
483                 while(1) {
484                         spin_lock(&em_tree->lock);
485                         ret = add_extent_mapping(em_tree, em);
486                         spin_unlock(&em_tree->lock);
487                         if (ret != -EEXIST) {
488                                 free_extent_map(em);
489                                 break;
490                         }
491                         btrfs_drop_extent_cache(inode, start,
492                                                 start + ram_size - 1, 0);
493                 }
494
495                 cur_alloc_size = ins.offset;
496                 ordered_type = will_compress ? BTRFS_ORDERED_COMPRESSED : 0;
497                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
498                                                ram_size, cur_alloc_size,
499                                                ordered_type);
500                 BUG_ON(ret);
501
502                 if (disk_num_bytes < cur_alloc_size) {
503                         printk("num_bytes %Lu cur_alloc %Lu\n", disk_num_bytes,
504                                cur_alloc_size);
505                         break;
506                 }
507
508                 if (will_compress) {
509                         /*
510                          * we're doing compression, we and we need to
511                          * submit the compressed extents down to the device.
512                          *
513                          * We lock down all the file pages, clearing their
514                          * dirty bits and setting them writeback.  Everyone
515                          * that wants to modify the page will wait on the
516                          * ordered extent above.
517                          *
518                          * The writeback bits on the file pages are
519                          * cleared when the compressed pages are on disk
520                          */
521                         btrfs_end_transaction(trans, root);
522
523                         if (start <= page_offset(locked_page) &&
524                             page_offset(locked_page) < start + ram_size) {
525                                 *page_started = 1;
526                         }
527
528                         extent_clear_unlock_delalloc(inode,
529                                                      &BTRFS_I(inode)->io_tree,
530                                                      start,
531                                                      start + ram_size - 1,
532                                                      NULL, 1, 1, 0);
533
534                         ret = btrfs_submit_compressed_write(inode, start,
535                                                  ram_size, ins.objectid,
536                                                  cur_alloc_size, pages,
537                                                  nr_pages_ret);
538
539                         BUG_ON(ret);
540                         trans = btrfs_join_transaction(root, 1);
541                         if (start + ram_size < end) {
542                                 start += ram_size;
543                                 alloc_hint = ins.objectid + ins.offset;
544                                 /* pages will be freed at end_bio time */
545                                 pages = NULL;
546                                 goto again;
547                         } else {
548                                 /* we've written everything, time to go */
549                                 break;
550                         }
551                 }
552                 /* we're not doing compressed IO, don't unlock the first
553                  * page (which the caller expects to stay locked), don't
554                  * clear any dirty bits and don't set any writeback bits
555                  */
556                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
557                                              start, start + ram_size - 1,
558                                              locked_page, 0, 0, 0);
559                 disk_num_bytes -= cur_alloc_size;
560                 num_bytes -= cur_alloc_size;
561                 alloc_hint = ins.objectid + ins.offset;
562                 start += cur_alloc_size;
563         }
564
565         ret = 0;
566 out:
567         btrfs_end_transaction(trans, root);
568
569         return ret;
570
571 free_pages_out_fail:
572         extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
573                                      start, end, locked_page, 0, 0, 0);
574 free_pages_out:
575         for (i = 0; i < nr_pages_ret; i++)
576                 page_cache_release(pages[i]);
577         if (pages)
578                 kfree(pages);
579
580         goto out;
581 }
582
583 /*
584  * when nowcow writeback call back.  This checks for snapshots or COW copies
585  * of the extents that exist in the file, and COWs the file as required.
586  *
587  * If no cow copies or snapshots exist, we write directly to the existing
588  * blocks on disk
589  */
590 static int run_delalloc_nocow(struct inode *inode, struct page *locked_page,
591                               u64 start, u64 end, int *page_started, int force)
592 {
593         struct btrfs_root *root = BTRFS_I(inode)->root;
594         struct btrfs_trans_handle *trans;
595         struct extent_buffer *leaf;
596         struct btrfs_path *path;
597         struct btrfs_file_extent_item *fi;
598         struct btrfs_key found_key;
599         u64 cow_start;
600         u64 cur_offset;
601         u64 extent_end;
602         u64 disk_bytenr;
603         u64 num_bytes;
604         int extent_type;
605         int ret;
606         int type;
607         int nocow;
608         int check_prev = 1;
609
610         path = btrfs_alloc_path();
611         BUG_ON(!path);
612         trans = btrfs_join_transaction(root, 1);
613         BUG_ON(!trans);
614
615         cow_start = (u64)-1;
616         cur_offset = start;
617         while (1) {
618                 ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
619                                                cur_offset, 0);
620                 BUG_ON(ret < 0);
621                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
622                         leaf = path->nodes[0];
623                         btrfs_item_key_to_cpu(leaf, &found_key,
624                                               path->slots[0] - 1);
625                         if (found_key.objectid == inode->i_ino &&
626                             found_key.type == BTRFS_EXTENT_DATA_KEY)
627                                 path->slots[0]--;
628                 }
629                 check_prev = 0;
630 next_slot:
631                 leaf = path->nodes[0];
632                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
633                         ret = btrfs_next_leaf(root, path);
634                         if (ret < 0)
635                                 BUG_ON(1);
636                         if (ret > 0)
637                                 break;
638                         leaf = path->nodes[0];
639                 }
640
641                 nocow = 0;
642                 disk_bytenr = 0;
643                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
644
645                 if (found_key.objectid > inode->i_ino ||
646                     found_key.type > BTRFS_EXTENT_DATA_KEY ||
647                     found_key.offset > end)
648                         break;
649
650                 if (found_key.offset > cur_offset) {
651                         extent_end = found_key.offset;
652                         goto out_check;
653                 }
654
655                 fi = btrfs_item_ptr(leaf, path->slots[0],
656                                     struct btrfs_file_extent_item);
657                 extent_type = btrfs_file_extent_type(leaf, fi);
658
659                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
660                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
661                         struct btrfs_block_group_cache *block_group;
662                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
663                         extent_end = found_key.offset +
664                                 btrfs_file_extent_num_bytes(leaf, fi);
665                         if (extent_end <= start) {
666                                 path->slots[0]++;
667                                 goto next_slot;
668                         }
669                         if (btrfs_file_extent_compression(leaf, fi) ||
670                             btrfs_file_extent_encryption(leaf, fi) ||
671                             btrfs_file_extent_other_encoding(leaf, fi))
672                                 goto out_check;
673                         if (disk_bytenr == 0)
674                                 goto out_check;
675                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
676                                 goto out_check;
677                         if (btrfs_cross_ref_exist(trans, root, disk_bytenr))
678                                 goto out_check;
679                         block_group = btrfs_lookup_block_group(root->fs_info,
680                                                                disk_bytenr);
681                         if (!block_group || block_group->ro)
682                                 goto out_check;
683                         disk_bytenr += btrfs_file_extent_offset(leaf, fi);
684                         nocow = 1;
685                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
686                         extent_end = found_key.offset +
687                                 btrfs_file_extent_inline_len(leaf, fi);
688                         extent_end = ALIGN(extent_end, root->sectorsize);
689                 } else {
690                         BUG_ON(1);
691                 }
692 out_check:
693                 if (extent_end <= start) {
694                         path->slots[0]++;
695                         goto next_slot;
696                 }
697                 if (!nocow) {
698                         if (cow_start == (u64)-1)
699                                 cow_start = cur_offset;
700                         cur_offset = extent_end;
701                         if (cur_offset > end)
702                                 break;
703                         path->slots[0]++;
704                         goto next_slot;
705                 }
706
707                 btrfs_release_path(root, path);
708                 if (cow_start != (u64)-1) {
709                         ret = cow_file_range(inode, locked_page, cow_start,
710                                         found_key.offset - 1, page_started);
711                         BUG_ON(ret);
712                         cow_start = (u64)-1;
713                 }
714
715                 disk_bytenr += cur_offset - found_key.offset;
716                 num_bytes = min(end + 1, extent_end) - cur_offset;
717                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
718                         struct extent_map *em;
719                         struct extent_map_tree *em_tree;
720                         em_tree = &BTRFS_I(inode)->extent_tree;
721                         em = alloc_extent_map(GFP_NOFS);
722                         em->start = cur_offset;
723                         em->len = num_bytes;
724                         em->block_len = num_bytes;
725                         em->block_start = disk_bytenr;
726                         em->bdev = root->fs_info->fs_devices->latest_bdev;
727                         set_bit(EXTENT_FLAG_PINNED, &em->flags);
728                         while (1) {
729                                 spin_lock(&em_tree->lock);
730                                 ret = add_extent_mapping(em_tree, em);
731                                 spin_unlock(&em_tree->lock);
732                                 if (ret != -EEXIST) {
733                                         free_extent_map(em);
734                                         break;
735                                 }
736                                 btrfs_drop_extent_cache(inode, em->start,
737                                                 em->start + em->len - 1, 0);
738                         }
739                         type = BTRFS_ORDERED_PREALLOC;
740                 } else {
741                         type = BTRFS_ORDERED_NOCOW;
742                 }
743
744                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
745                                                num_bytes, num_bytes, type);
746                 BUG_ON(ret);
747                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
748                                         cur_offset, cur_offset + num_bytes - 1,
749                                         locked_page, 0, 0, 0);
750                 cur_offset = extent_end;
751                 if (cur_offset > end)
752                         break;
753         }
754         btrfs_release_path(root, path);
755
756         if (cur_offset <= end && cow_start == (u64)-1)
757                 cow_start = cur_offset;
758         if (cow_start != (u64)-1) {
759                 ret = cow_file_range(inode, locked_page, cow_start, end,
760                                      page_started);
761                 BUG_ON(ret);
762         }
763
764         ret = btrfs_end_transaction(trans, root);
765         BUG_ON(ret);
766         btrfs_free_path(path);
767         return 0;
768 }
769
770 /*
771  * extent_io.c call back to do delayed allocation processing
772  */
773 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
774                               u64 start, u64 end, int *page_started)
775 {
776         struct btrfs_root *root = BTRFS_I(inode)->root;
777         int ret;
778
779         if (btrfs_test_opt(root, NODATACOW) ||
780             btrfs_test_flag(inode, NODATACOW))
781                 ret = run_delalloc_nocow(inode, locked_page, start, end,
782                                          page_started, 0);
783         else if (btrfs_test_flag(inode, PREALLOC))
784                 ret = run_delalloc_nocow(inode, locked_page, start, end,
785                                          page_started, 1);
786         else
787                 ret = cow_file_range(inode, locked_page, start, end,
788                                      page_started);
789
790         return ret;
791 }
792
793 /*
794  * extent_io.c set_bit_hook, used to track delayed allocation
795  * bytes in this file, and to maintain the list of inodes that
796  * have pending delalloc work to be done.
797  */
798 int btrfs_set_bit_hook(struct inode *inode, u64 start, u64 end,
799                        unsigned long old, unsigned long bits)
800 {
801         unsigned long flags;
802         if (!(old & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
803                 struct btrfs_root *root = BTRFS_I(inode)->root;
804                 spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
805                 BTRFS_I(inode)->delalloc_bytes += end - start + 1;
806                 root->fs_info->delalloc_bytes += end - start + 1;
807                 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
808                         list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
809                                       &root->fs_info->delalloc_inodes);
810                 }
811                 spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
812         }
813         return 0;
814 }
815
816 /*
817  * extent_io.c clear_bit_hook, see set_bit_hook for why
818  */
819 int btrfs_clear_bit_hook(struct inode *inode, u64 start, u64 end,
820                          unsigned long old, unsigned long bits)
821 {
822         if ((old & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
823                 struct btrfs_root *root = BTRFS_I(inode)->root;
824                 unsigned long flags;
825
826                 spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
827                 if (end - start + 1 > root->fs_info->delalloc_bytes) {
828                         printk("warning: delalloc account %Lu %Lu\n",
829                                end - start + 1, root->fs_info->delalloc_bytes);
830                         root->fs_info->delalloc_bytes = 0;
831                         BTRFS_I(inode)->delalloc_bytes = 0;
832                 } else {
833                         root->fs_info->delalloc_bytes -= end - start + 1;
834                         BTRFS_I(inode)->delalloc_bytes -= end - start + 1;
835                 }
836                 if (BTRFS_I(inode)->delalloc_bytes == 0 &&
837                     !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
838                         list_del_init(&BTRFS_I(inode)->delalloc_inodes);
839                 }
840                 spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
841         }
842         return 0;
843 }
844
845 /*
846  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
847  * we don't create bios that span stripes or chunks
848  */
849 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
850                          size_t size, struct bio *bio,
851                          unsigned long bio_flags)
852 {
853         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
854         struct btrfs_mapping_tree *map_tree;
855         u64 logical = (u64)bio->bi_sector << 9;
856         u64 length = 0;
857         u64 map_length;
858         int ret;
859
860         length = bio->bi_size;
861         map_tree = &root->fs_info->mapping_tree;
862         map_length = length;
863         ret = btrfs_map_block(map_tree, READ, logical,
864                               &map_length, NULL, 0);
865
866         if (map_length < length + size) {
867                 return 1;
868         }
869         return 0;
870 }
871
872 /*
873  * in order to insert checksums into the metadata in large chunks,
874  * we wait until bio submission time.   All the pages in the bio are
875  * checksummed and sums are attached onto the ordered extent record.
876  *
877  * At IO completion time the cums attached on the ordered extent record
878  * are inserted into the btree
879  */
880 int __btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
881                           int mirror_num, unsigned long bio_flags)
882 {
883         struct btrfs_root *root = BTRFS_I(inode)->root;
884         int ret = 0;
885
886         ret = btrfs_csum_one_bio(root, inode, bio);
887         BUG_ON(ret);
888
889         return btrfs_map_bio(root, rw, bio, mirror_num, 1);
890 }
891
892 /*
893  * extent_io.c submission hook. This does the right thing for csum calculation on write,
894  * or reading the csums from the tree before a read
895  */
896 int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
897                           int mirror_num, unsigned long bio_flags)
898 {
899         struct btrfs_root *root = BTRFS_I(inode)->root;
900         int ret = 0;
901         int skip_sum;
902
903         ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
904         BUG_ON(ret);
905
906         skip_sum = btrfs_test_opt(root, NODATASUM) ||
907                 btrfs_test_flag(inode, NODATASUM);
908
909         if (!(rw & (1 << BIO_RW))) {
910                 if (!skip_sum)
911                         btrfs_lookup_bio_sums(root, inode, bio);
912
913                 if (bio_flags & EXTENT_BIO_COMPRESSED)
914                         return btrfs_submit_compressed_read(inode, bio,
915                                                     mirror_num, bio_flags);
916                 goto mapit;
917         } else if (!skip_sum) {
918                 /* we're doing a write, do the async checksumming */
919                 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
920                                    inode, rw, bio, mirror_num,
921                                    bio_flags, __btrfs_submit_bio_hook);
922         }
923
924 mapit:
925         return btrfs_map_bio(root, rw, bio, mirror_num, 0);
926 }
927
928 /*
929  * given a list of ordered sums record them in the inode.  This happens
930  * at IO completion time based on sums calculated at bio submission time.
931  */
932 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
933                              struct inode *inode, u64 file_offset,
934                              struct list_head *list)
935 {
936         struct list_head *cur;
937         struct btrfs_ordered_sum *sum;
938
939         btrfs_set_trans_block_group(trans, inode);
940         list_for_each(cur, list) {
941                 sum = list_entry(cur, struct btrfs_ordered_sum, list);
942                 btrfs_csum_file_blocks(trans, BTRFS_I(inode)->root,
943                                        inode, sum);
944         }
945         return 0;
946 }
947
948 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end)
949 {
950         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
951                                    GFP_NOFS);
952 }
953
954 /* see btrfs_writepage_start_hook for details on why this is required */
955 struct btrfs_writepage_fixup {
956         struct page *page;
957         struct btrfs_work work;
958 };
959
960 void btrfs_writepage_fixup_worker(struct btrfs_work *work)
961 {
962         struct btrfs_writepage_fixup *fixup;
963         struct btrfs_ordered_extent *ordered;
964         struct page *page;
965         struct inode *inode;
966         u64 page_start;
967         u64 page_end;
968
969         fixup = container_of(work, struct btrfs_writepage_fixup, work);
970         page = fixup->page;
971 again:
972         lock_page(page);
973         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
974                 ClearPageChecked(page);
975                 goto out_page;
976         }
977
978         inode = page->mapping->host;
979         page_start = page_offset(page);
980         page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
981
982         lock_extent(&BTRFS_I(inode)->io_tree, page_start, page_end, GFP_NOFS);
983
984         /* already ordered? We're done */
985         if (test_range_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
986                              EXTENT_ORDERED, 0)) {
987                 goto out;
988         }
989
990         ordered = btrfs_lookup_ordered_extent(inode, page_start);
991         if (ordered) {
992                 unlock_extent(&BTRFS_I(inode)->io_tree, page_start,
993                               page_end, GFP_NOFS);
994                 unlock_page(page);
995                 btrfs_start_ordered_extent(inode, ordered, 1);
996                 goto again;
997         }
998
999         btrfs_set_extent_delalloc(inode, page_start, page_end);
1000         ClearPageChecked(page);
1001 out:
1002         unlock_extent(&BTRFS_I(inode)->io_tree, page_start, page_end, GFP_NOFS);
1003 out_page:
1004         unlock_page(page);
1005         page_cache_release(page);
1006 }
1007
1008 /*
1009  * There are a few paths in the higher layers of the kernel that directly
1010  * set the page dirty bit without asking the filesystem if it is a
1011  * good idea.  This causes problems because we want to make sure COW
1012  * properly happens and the data=ordered rules are followed.
1013  *
1014  * In our case any range that doesn't have the ORDERED bit set
1015  * hasn't been properly setup for IO.  We kick off an async process
1016  * to fix it up.  The async helper will wait for ordered extents, set
1017  * the delalloc bit and make it safe to write the page.
1018  */
1019 int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1020 {
1021         struct inode *inode = page->mapping->host;
1022         struct btrfs_writepage_fixup *fixup;
1023         struct btrfs_root *root = BTRFS_I(inode)->root;
1024         int ret;
1025
1026         ret = test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1027                              EXTENT_ORDERED, 0);
1028         if (ret)
1029                 return 0;
1030
1031         if (PageChecked(page))
1032                 return -EAGAIN;
1033
1034         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1035         if (!fixup)
1036                 return -EAGAIN;
1037
1038         SetPageChecked(page);
1039         page_cache_get(page);
1040         fixup->work.func = btrfs_writepage_fixup_worker;
1041         fixup->page = page;
1042         btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1043         return -EAGAIN;
1044 }
1045
1046 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1047                                        struct inode *inode, u64 file_pos,
1048                                        u64 disk_bytenr, u64 disk_num_bytes,
1049                                        u64 num_bytes, u64 ram_bytes,
1050                                        u8 compression, u8 encryption,
1051                                        u16 other_encoding, int extent_type)
1052 {
1053         struct btrfs_root *root = BTRFS_I(inode)->root;
1054         struct btrfs_file_extent_item *fi;
1055         struct btrfs_path *path;
1056         struct extent_buffer *leaf;
1057         struct btrfs_key ins;
1058         u64 hint;
1059         int ret;
1060
1061         path = btrfs_alloc_path();
1062         BUG_ON(!path);
1063
1064         ret = btrfs_drop_extents(trans, root, inode, file_pos,
1065                                  file_pos + num_bytes, file_pos, &hint);
1066         BUG_ON(ret);
1067
1068         ins.objectid = inode->i_ino;
1069         ins.offset = file_pos;
1070         ins.type = BTRFS_EXTENT_DATA_KEY;
1071         ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1072         BUG_ON(ret);
1073         leaf = path->nodes[0];
1074         fi = btrfs_item_ptr(leaf, path->slots[0],
1075                             struct btrfs_file_extent_item);
1076         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1077         btrfs_set_file_extent_type(leaf, fi, extent_type);
1078         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1079         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1080         btrfs_set_file_extent_offset(leaf, fi, 0);
1081         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1082         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1083         btrfs_set_file_extent_compression(leaf, fi, compression);
1084         btrfs_set_file_extent_encryption(leaf, fi, encryption);
1085         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1086         btrfs_mark_buffer_dirty(leaf);
1087
1088         inode_add_bytes(inode, num_bytes);
1089         btrfs_drop_extent_cache(inode, file_pos, file_pos + num_bytes - 1, 0);
1090
1091         ins.objectid = disk_bytenr;
1092         ins.offset = disk_num_bytes;
1093         ins.type = BTRFS_EXTENT_ITEM_KEY;
1094         ret = btrfs_alloc_reserved_extent(trans, root, leaf->start,
1095                                           root->root_key.objectid,
1096                                           trans->transid, inode->i_ino, &ins);
1097         BUG_ON(ret);
1098
1099         btrfs_free_path(path);
1100         return 0;
1101 }
1102
1103 /* as ordered data IO finishes, this gets called so we can finish
1104  * an ordered extent if the range of bytes in the file it covers are
1105  * fully written.
1106  */
1107 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
1108 {
1109         struct btrfs_root *root = BTRFS_I(inode)->root;
1110         struct btrfs_trans_handle *trans;
1111         struct btrfs_ordered_extent *ordered_extent;
1112         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1113         int compressed = 0;
1114         int ret;
1115
1116         ret = btrfs_dec_test_ordered_pending(inode, start, end - start + 1);
1117         if (!ret)
1118                 return 0;
1119
1120         trans = btrfs_join_transaction(root, 1);
1121
1122         ordered_extent = btrfs_lookup_ordered_extent(inode, start);
1123         BUG_ON(!ordered_extent);
1124         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags))
1125                 goto nocow;
1126
1127         lock_extent(io_tree, ordered_extent->file_offset,
1128                     ordered_extent->file_offset + ordered_extent->len - 1,
1129                     GFP_NOFS);
1130
1131         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1132                 compressed = 1;
1133         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1134                 BUG_ON(compressed);
1135                 ret = btrfs_mark_extent_written(trans, root, inode,
1136                                                 ordered_extent->file_offset,
1137                                                 ordered_extent->file_offset +
1138                                                 ordered_extent->len);
1139                 BUG_ON(ret);
1140         } else {
1141                 ret = insert_reserved_file_extent(trans, inode,
1142                                                 ordered_extent->file_offset,
1143                                                 ordered_extent->start,
1144                                                 ordered_extent->disk_len,
1145                                                 ordered_extent->len,
1146                                                 ordered_extent->len,
1147                                                 compressed, 0, 0,
1148                                                 BTRFS_FILE_EXTENT_REG);
1149                 BUG_ON(ret);
1150         }
1151         unlock_extent(io_tree, ordered_extent->file_offset,
1152                     ordered_extent->file_offset + ordered_extent->len - 1,
1153                     GFP_NOFS);
1154 nocow:
1155         add_pending_csums(trans, inode, ordered_extent->file_offset,
1156                           &ordered_extent->list);
1157
1158         mutex_lock(&BTRFS_I(inode)->extent_mutex);
1159         btrfs_ordered_update_i_size(inode, ordered_extent);
1160         btrfs_update_inode(trans, root, inode);
1161         btrfs_remove_ordered_extent(inode, ordered_extent);
1162         mutex_unlock(&BTRFS_I(inode)->extent_mutex);
1163
1164         /* once for us */
1165         btrfs_put_ordered_extent(ordered_extent);
1166         /* once for the tree */
1167         btrfs_put_ordered_extent(ordered_extent);
1168
1169         btrfs_end_transaction(trans, root);
1170         return 0;
1171 }
1172
1173 int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1174                                 struct extent_state *state, int uptodate)
1175 {
1176         return btrfs_finish_ordered_io(page->mapping->host, start, end);
1177 }
1178
1179 /*
1180  * When IO fails, either with EIO or csum verification fails, we
1181  * try other mirrors that might have a good copy of the data.  This
1182  * io_failure_record is used to record state as we go through all the
1183  * mirrors.  If another mirror has good data, the page is set up to date
1184  * and things continue.  If a good mirror can't be found, the original
1185  * bio end_io callback is called to indicate things have failed.
1186  */
1187 struct io_failure_record {
1188         struct page *page;
1189         u64 start;
1190         u64 len;
1191         u64 logical;
1192         int last_mirror;
1193 };
1194
1195 int btrfs_io_failed_hook(struct bio *failed_bio,
1196                          struct page *page, u64 start, u64 end,
1197                          struct extent_state *state)
1198 {
1199         struct io_failure_record *failrec = NULL;
1200         u64 private;
1201         struct extent_map *em;
1202         struct inode *inode = page->mapping->host;
1203         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
1204         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1205         struct bio *bio;
1206         int num_copies;
1207         int ret;
1208         int rw;
1209         u64 logical;
1210         unsigned long bio_flags = 0;
1211
1212         ret = get_state_private(failure_tree, start, &private);
1213         if (ret) {
1214                 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
1215                 if (!failrec)
1216                         return -ENOMEM;
1217                 failrec->start = start;
1218                 failrec->len = end - start + 1;
1219                 failrec->last_mirror = 0;
1220
1221                 spin_lock(&em_tree->lock);
1222                 em = lookup_extent_mapping(em_tree, start, failrec->len);
1223                 if (em->start > start || em->start + em->len < start) {
1224                         free_extent_map(em);
1225                         em = NULL;
1226                 }
1227                 spin_unlock(&em_tree->lock);
1228
1229                 if (!em || IS_ERR(em)) {
1230                         kfree(failrec);
1231                         return -EIO;
1232                 }
1233                 logical = start - em->start;
1234                 logical = em->block_start + logical;
1235                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
1236                         bio_flags = EXTENT_BIO_COMPRESSED;
1237                 failrec->logical = logical;
1238                 free_extent_map(em);
1239                 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
1240                                 EXTENT_DIRTY, GFP_NOFS);
1241                 set_state_private(failure_tree, start,
1242                                  (u64)(unsigned long)failrec);
1243         } else {
1244                 failrec = (struct io_failure_record *)(unsigned long)private;
1245         }
1246         num_copies = btrfs_num_copies(
1247                               &BTRFS_I(inode)->root->fs_info->mapping_tree,
1248                               failrec->logical, failrec->len);
1249         failrec->last_mirror++;
1250         if (!state) {
1251                 spin_lock_irq(&BTRFS_I(inode)->io_tree.lock);
1252                 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
1253                                                     failrec->start,
1254                                                     EXTENT_LOCKED);
1255                 if (state && state->start != failrec->start)
1256                         state = NULL;
1257                 spin_unlock_irq(&BTRFS_I(inode)->io_tree.lock);
1258         }
1259         if (!state || failrec->last_mirror > num_copies) {
1260                 set_state_private(failure_tree, failrec->start, 0);
1261                 clear_extent_bits(failure_tree, failrec->start,
1262                                   failrec->start + failrec->len - 1,
1263                                   EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1264                 kfree(failrec);
1265                 return -EIO;
1266         }
1267         bio = bio_alloc(GFP_NOFS, 1);
1268         bio->bi_private = state;
1269         bio->bi_end_io = failed_bio->bi_end_io;
1270         bio->bi_sector = failrec->logical >> 9;
1271         bio->bi_bdev = failed_bio->bi_bdev;
1272         bio->bi_size = 0;
1273         bio_add_page(bio, page, failrec->len, start - page_offset(page));
1274         if (failed_bio->bi_rw & (1 << BIO_RW))
1275                 rw = WRITE;
1276         else
1277                 rw = READ;
1278
1279         BTRFS_I(inode)->io_tree.ops->submit_bio_hook(inode, rw, bio,
1280                                                       failrec->last_mirror,
1281                                                       bio_flags);
1282         return 0;
1283 }
1284
1285 /*
1286  * each time an IO finishes, we do a fast check in the IO failure tree
1287  * to see if we need to process or clean up an io_failure_record
1288  */
1289 int btrfs_clean_io_failures(struct inode *inode, u64 start)
1290 {
1291         u64 private;
1292         u64 private_failure;
1293         struct io_failure_record *failure;
1294         int ret;
1295
1296         private = 0;
1297         if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
1298                              (u64)-1, 1, EXTENT_DIRTY)) {
1299                 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
1300                                         start, &private_failure);
1301                 if (ret == 0) {
1302                         failure = (struct io_failure_record *)(unsigned long)
1303                                    private_failure;
1304                         set_state_private(&BTRFS_I(inode)->io_failure_tree,
1305                                           failure->start, 0);
1306                         clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
1307                                           failure->start,
1308                                           failure->start + failure->len - 1,
1309                                           EXTENT_DIRTY | EXTENT_LOCKED,
1310                                           GFP_NOFS);
1311                         kfree(failure);
1312                 }
1313         }
1314         return 0;
1315 }
1316
1317 /*
1318  * when reads are done, we need to check csums to verify the data is correct
1319  * if there's a match, we allow the bio to finish.  If not, we go through
1320  * the io_failure_record routines to find good copies
1321  */
1322 int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
1323                                struct extent_state *state)
1324 {
1325         size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
1326         struct inode *inode = page->mapping->host;
1327         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1328         char *kaddr;
1329         u64 private = ~(u32)0;
1330         int ret;
1331         struct btrfs_root *root = BTRFS_I(inode)->root;
1332         u32 csum = ~(u32)0;
1333         unsigned long flags;
1334
1335         if (btrfs_test_opt(root, NODATASUM) ||
1336             btrfs_test_flag(inode, NODATASUM))
1337                 return 0;
1338         if (state && state->start == start) {
1339                 private = state->private;
1340                 ret = 0;
1341         } else {
1342                 ret = get_state_private(io_tree, start, &private);
1343         }
1344         local_irq_save(flags);
1345         kaddr = kmap_atomic(page, KM_IRQ0);
1346         if (ret) {
1347                 goto zeroit;
1348         }
1349         csum = btrfs_csum_data(root, kaddr + offset, csum,  end - start + 1);
1350         btrfs_csum_final(csum, (char *)&csum);
1351         if (csum != private) {
1352                 goto zeroit;
1353         }
1354         kunmap_atomic(kaddr, KM_IRQ0);
1355         local_irq_restore(flags);
1356
1357         /* if the io failure tree for this inode is non-empty,
1358          * check to see if we've recovered from a failed IO
1359          */
1360         btrfs_clean_io_failures(inode, start);
1361         return 0;
1362
1363 zeroit:
1364         printk("btrfs csum failed ino %lu off %llu csum %u private %Lu\n",
1365                page->mapping->host->i_ino, (unsigned long long)start, csum,
1366                private);
1367         memset(kaddr + offset, 1, end - start + 1);
1368         flush_dcache_page(page);
1369         kunmap_atomic(kaddr, KM_IRQ0);
1370         local_irq_restore(flags);
1371         if (private == 0)
1372                 return 0;
1373         return -EIO;
1374 }
1375
1376 /*
1377  * This creates an orphan entry for the given inode in case something goes
1378  * wrong in the middle of an unlink/truncate.
1379  */
1380 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
1381 {
1382         struct btrfs_root *root = BTRFS_I(inode)->root;
1383         int ret = 0;
1384
1385         spin_lock(&root->list_lock);
1386
1387         /* already on the orphan list, we're good */
1388         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
1389                 spin_unlock(&root->list_lock);
1390                 return 0;
1391         }
1392
1393         list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
1394
1395         spin_unlock(&root->list_lock);
1396
1397         /*
1398          * insert an orphan item to track this unlinked/truncated file
1399          */
1400         ret = btrfs_insert_orphan_item(trans, root, inode->i_ino);
1401
1402         return ret;
1403 }
1404
1405 /*
1406  * We have done the truncate/delete so we can go ahead and remove the orphan
1407  * item for this particular inode.
1408  */
1409 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
1410 {
1411         struct btrfs_root *root = BTRFS_I(inode)->root;
1412         int ret = 0;
1413
1414         spin_lock(&root->list_lock);
1415
1416         if (list_empty(&BTRFS_I(inode)->i_orphan)) {
1417                 spin_unlock(&root->list_lock);
1418                 return 0;
1419         }
1420
1421         list_del_init(&BTRFS_I(inode)->i_orphan);
1422         if (!trans) {
1423                 spin_unlock(&root->list_lock);
1424                 return 0;
1425         }
1426
1427         spin_unlock(&root->list_lock);
1428
1429         ret = btrfs_del_orphan_item(trans, root, inode->i_ino);
1430
1431         return ret;
1432 }
1433
1434 /*
1435  * this cleans up any orphans that may be left on the list from the last use
1436  * of this root.
1437  */
1438 void btrfs_orphan_cleanup(struct btrfs_root *root)
1439 {
1440         struct btrfs_path *path;
1441         struct extent_buffer *leaf;
1442         struct btrfs_item *item;
1443         struct btrfs_key key, found_key;
1444         struct btrfs_trans_handle *trans;
1445         struct inode *inode;
1446         int ret = 0, nr_unlink = 0, nr_truncate = 0;
1447
1448         /* don't do orphan cleanup if the fs is readonly. */
1449         if (root->fs_info->sb->s_flags & MS_RDONLY)
1450                 return;
1451
1452         path = btrfs_alloc_path();
1453         if (!path)
1454                 return;
1455         path->reada = -1;
1456
1457         key.objectid = BTRFS_ORPHAN_OBJECTID;
1458         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
1459         key.offset = (u64)-1;
1460
1461
1462         while (1) {
1463                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1464                 if (ret < 0) {
1465                         printk(KERN_ERR "Error searching slot for orphan: %d"
1466                                "\n", ret);
1467                         break;
1468                 }
1469
1470                 /*
1471                  * if ret == 0 means we found what we were searching for, which
1472                  * is weird, but possible, so only screw with path if we didnt
1473                  * find the key and see if we have stuff that matches
1474                  */
1475                 if (ret > 0) {
1476                         if (path->slots[0] == 0)
1477                                 break;
1478                         path->slots[0]--;
1479                 }
1480
1481                 /* pull out the item */
1482                 leaf = path->nodes[0];
1483                 item = btrfs_item_nr(leaf, path->slots[0]);
1484                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1485
1486                 /* make sure the item matches what we want */
1487                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
1488                         break;
1489                 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
1490                         break;
1491
1492                 /* release the path since we're done with it */
1493                 btrfs_release_path(root, path);
1494
1495                 /*
1496                  * this is where we are basically btrfs_lookup, without the
1497                  * crossing root thing.  we store the inode number in the
1498                  * offset of the orphan item.
1499                  */
1500                 inode = btrfs_iget_locked(root->fs_info->sb,
1501                                           found_key.offset, root);
1502                 if (!inode)
1503                         break;
1504
1505                 if (inode->i_state & I_NEW) {
1506                         BTRFS_I(inode)->root = root;
1507
1508                         /* have to set the location manually */
1509                         BTRFS_I(inode)->location.objectid = inode->i_ino;
1510                         BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
1511                         BTRFS_I(inode)->location.offset = 0;
1512
1513                         btrfs_read_locked_inode(inode);
1514                         unlock_new_inode(inode);
1515                 }
1516
1517                 /*
1518                  * add this inode to the orphan list so btrfs_orphan_del does
1519                  * the proper thing when we hit it
1520                  */
1521                 spin_lock(&root->list_lock);
1522                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
1523                 spin_unlock(&root->list_lock);
1524
1525                 /*
1526                  * if this is a bad inode, means we actually succeeded in
1527                  * removing the inode, but not the orphan record, which means
1528                  * we need to manually delete the orphan since iput will just
1529                  * do a destroy_inode
1530                  */
1531                 if (is_bad_inode(inode)) {
1532                         trans = btrfs_start_transaction(root, 1);
1533                         btrfs_orphan_del(trans, inode);
1534                         btrfs_end_transaction(trans, root);
1535                         iput(inode);
1536                         continue;
1537                 }
1538
1539                 /* if we have links, this was a truncate, lets do that */
1540                 if (inode->i_nlink) {
1541                         nr_truncate++;
1542                         btrfs_truncate(inode);
1543                 } else {
1544                         nr_unlink++;
1545                 }
1546
1547                 /* this will do delete_inode and everything for us */
1548                 iput(inode);
1549         }
1550
1551         if (nr_unlink)
1552                 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
1553         if (nr_truncate)
1554                 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
1555
1556         btrfs_free_path(path);
1557 }
1558
1559 /*
1560  * read an inode from the btree into the in-memory inode
1561  */
1562 void btrfs_read_locked_inode(struct inode *inode)
1563 {
1564         struct btrfs_path *path;
1565         struct extent_buffer *leaf;
1566         struct btrfs_inode_item *inode_item;
1567         struct btrfs_timespec *tspec;
1568         struct btrfs_root *root = BTRFS_I(inode)->root;
1569         struct btrfs_key location;
1570         u64 alloc_group_block;
1571         u32 rdev;
1572         int ret;
1573
1574         path = btrfs_alloc_path();
1575         BUG_ON(!path);
1576         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
1577
1578         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
1579         if (ret)
1580                 goto make_bad;
1581
1582         leaf = path->nodes[0];
1583         inode_item = btrfs_item_ptr(leaf, path->slots[0],
1584                                     struct btrfs_inode_item);
1585
1586         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
1587         inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
1588         inode->i_uid = btrfs_inode_uid(leaf, inode_item);
1589         inode->i_gid = btrfs_inode_gid(leaf, inode_item);
1590         btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
1591
1592         tspec = btrfs_inode_atime(inode_item);
1593         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
1594         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
1595
1596         tspec = btrfs_inode_mtime(inode_item);
1597         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
1598         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
1599
1600         tspec = btrfs_inode_ctime(inode_item);
1601         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
1602         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
1603
1604         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
1605         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
1606         inode->i_generation = BTRFS_I(inode)->generation;
1607         inode->i_rdev = 0;
1608         rdev = btrfs_inode_rdev(leaf, inode_item);
1609
1610         BTRFS_I(inode)->index_cnt = (u64)-1;
1611
1612         alloc_group_block = btrfs_inode_block_group(leaf, inode_item);
1613         BTRFS_I(inode)->block_group = btrfs_lookup_block_group(root->fs_info,
1614                                                        alloc_group_block);
1615         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
1616         if (!BTRFS_I(inode)->block_group) {
1617                 BTRFS_I(inode)->block_group = btrfs_find_block_group(root,
1618                                                  NULL, 0,
1619                                                  BTRFS_BLOCK_GROUP_METADATA, 0);
1620         }
1621         btrfs_free_path(path);
1622         inode_item = NULL;
1623
1624         switch (inode->i_mode & S_IFMT) {
1625         case S_IFREG:
1626                 inode->i_mapping->a_ops = &btrfs_aops;
1627                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
1628                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
1629                 inode->i_fop = &btrfs_file_operations;
1630                 inode->i_op = &btrfs_file_inode_operations;
1631                 break;
1632         case S_IFDIR:
1633                 inode->i_fop = &btrfs_dir_file_operations;
1634                 if (root == root->fs_info->tree_root)
1635                         inode->i_op = &btrfs_dir_ro_inode_operations;
1636                 else
1637                         inode->i_op = &btrfs_dir_inode_operations;
1638                 break;
1639         case S_IFLNK:
1640                 inode->i_op = &btrfs_symlink_inode_operations;
1641                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
1642                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
1643                 break;
1644         default:
1645                 init_special_inode(inode, inode->i_mode, rdev);
1646                 break;
1647         }
1648         return;
1649
1650 make_bad:
1651         btrfs_free_path(path);
1652         make_bad_inode(inode);
1653 }
1654
1655 /*
1656  * given a leaf and an inode, copy the inode fields into the leaf
1657  */
1658 static void fill_inode_item(struct btrfs_trans_handle *trans,
1659                             struct extent_buffer *leaf,
1660                             struct btrfs_inode_item *item,
1661                             struct inode *inode)
1662 {
1663         btrfs_set_inode_uid(leaf, item, inode->i_uid);
1664         btrfs_set_inode_gid(leaf, item, inode->i_gid);
1665         btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
1666         btrfs_set_inode_mode(leaf, item, inode->i_mode);
1667         btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
1668
1669         btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
1670                                inode->i_atime.tv_sec);
1671         btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
1672                                 inode->i_atime.tv_nsec);
1673
1674         btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
1675                                inode->i_mtime.tv_sec);
1676         btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
1677                                 inode->i_mtime.tv_nsec);
1678
1679         btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
1680                                inode->i_ctime.tv_sec);
1681         btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
1682                                 inode->i_ctime.tv_nsec);
1683
1684         btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
1685         btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
1686         btrfs_set_inode_transid(leaf, item, trans->transid);
1687         btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
1688         btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
1689         btrfs_set_inode_block_group(leaf, item,
1690                                     BTRFS_I(inode)->block_group->key.objectid);
1691 }
1692
1693 /*
1694  * copy everything in the in-memory inode into the btree.
1695  */
1696 int noinline btrfs_update_inode(struct btrfs_trans_handle *trans,
1697                               struct btrfs_root *root,
1698                               struct inode *inode)
1699 {
1700         struct btrfs_inode_item *inode_item;
1701         struct btrfs_path *path;
1702         struct extent_buffer *leaf;
1703         int ret;
1704
1705         path = btrfs_alloc_path();
1706         BUG_ON(!path);
1707         ret = btrfs_lookup_inode(trans, root, path,
1708                                  &BTRFS_I(inode)->location, 1);
1709         if (ret) {
1710                 if (ret > 0)
1711                         ret = -ENOENT;
1712                 goto failed;
1713         }
1714
1715         leaf = path->nodes[0];
1716         inode_item = btrfs_item_ptr(leaf, path->slots[0],
1717                                   struct btrfs_inode_item);
1718
1719         fill_inode_item(trans, leaf, inode_item, inode);
1720         btrfs_mark_buffer_dirty(leaf);
1721         btrfs_set_inode_last_trans(trans, inode);
1722         ret = 0;
1723 failed:
1724         btrfs_free_path(path);
1725         return ret;
1726 }
1727
1728
1729 /*
1730  * unlink helper that gets used here in inode.c and in the tree logging
1731  * recovery code.  It remove a link in a directory with a given name, and
1732  * also drops the back refs in the inode to the directory
1733  */
1734 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
1735                        struct btrfs_root *root,
1736                        struct inode *dir, struct inode *inode,
1737                        const char *name, int name_len)
1738 {
1739         struct btrfs_path *path;
1740         int ret = 0;
1741         struct extent_buffer *leaf;
1742         struct btrfs_dir_item *di;
1743         struct btrfs_key key;
1744         u64 index;
1745
1746         path = btrfs_alloc_path();
1747         if (!path) {
1748                 ret = -ENOMEM;
1749                 goto err;
1750         }
1751
1752         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
1753                                     name, name_len, -1);
1754         if (IS_ERR(di)) {
1755                 ret = PTR_ERR(di);
1756                 goto err;
1757         }
1758         if (!di) {
1759                 ret = -ENOENT;
1760                 goto err;
1761         }
1762         leaf = path->nodes[0];
1763         btrfs_dir_item_key_to_cpu(leaf, di, &key);
1764         ret = btrfs_delete_one_dir_name(trans, root, path, di);
1765         if (ret)
1766                 goto err;
1767         btrfs_release_path(root, path);
1768
1769         ret = btrfs_del_inode_ref(trans, root, name, name_len,
1770                                   inode->i_ino,
1771                                   dir->i_ino, &index);
1772         if (ret) {
1773                 printk("failed to delete reference to %.*s, "
1774                        "inode %lu parent %lu\n", name_len, name,
1775                        inode->i_ino, dir->i_ino);
1776                 goto err;
1777         }
1778
1779         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
1780                                          index, name, name_len, -1);
1781         if (IS_ERR(di)) {
1782                 ret = PTR_ERR(di);
1783                 goto err;
1784         }
1785         if (!di) {
1786                 ret = -ENOENT;
1787                 goto err;
1788         }
1789         ret = btrfs_delete_one_dir_name(trans, root, path, di);
1790         btrfs_release_path(root, path);
1791
1792         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
1793                                          inode, dir->i_ino);
1794         BUG_ON(ret != 0 && ret != -ENOENT);
1795         if (ret != -ENOENT)
1796                 BTRFS_I(dir)->log_dirty_trans = trans->transid;
1797
1798         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
1799                                            dir, index);
1800         BUG_ON(ret);
1801 err:
1802         btrfs_free_path(path);
1803         if (ret)
1804                 goto out;
1805
1806         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
1807         inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
1808         btrfs_update_inode(trans, root, dir);
1809         btrfs_drop_nlink(inode);
1810         ret = btrfs_update_inode(trans, root, inode);
1811         dir->i_sb->s_dirt = 1;
1812 out:
1813         return ret;
1814 }
1815
1816 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
1817 {
1818         struct btrfs_root *root;
1819         struct btrfs_trans_handle *trans;
1820         struct inode *inode = dentry->d_inode;
1821         int ret;
1822         unsigned long nr = 0;
1823
1824         root = BTRFS_I(dir)->root;
1825
1826         ret = btrfs_check_free_space(root, 1, 1);
1827         if (ret)
1828                 goto fail;
1829
1830         trans = btrfs_start_transaction(root, 1);
1831
1832         btrfs_set_trans_block_group(trans, dir);
1833         ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
1834                                  dentry->d_name.name, dentry->d_name.len);
1835
1836         if (inode->i_nlink == 0)
1837                 ret = btrfs_orphan_add(trans, inode);
1838
1839         nr = trans->blocks_used;
1840
1841         btrfs_end_transaction_throttle(trans, root);
1842 fail:
1843         btrfs_btree_balance_dirty(root, nr);
1844         return ret;
1845 }
1846
1847 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
1848 {
1849         struct inode *inode = dentry->d_inode;
1850         int err = 0;
1851         int ret;
1852         struct btrfs_root *root = BTRFS_I(dir)->root;
1853         struct btrfs_trans_handle *trans;
1854         unsigned long nr = 0;
1855
1856         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE) {
1857                 return -ENOTEMPTY;
1858         }
1859
1860         ret = btrfs_check_free_space(root, 1, 1);
1861         if (ret)
1862                 goto fail;
1863
1864         trans = btrfs_start_transaction(root, 1);
1865         btrfs_set_trans_block_group(trans, dir);
1866
1867         err = btrfs_orphan_add(trans, inode);
1868         if (err)
1869                 goto fail_trans;
1870
1871         /* now the directory is empty */
1872         err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
1873                                  dentry->d_name.name, dentry->d_name.len);
1874         if (!err) {
1875                 btrfs_i_size_write(inode, 0);
1876         }
1877
1878 fail_trans:
1879         nr = trans->blocks_used;
1880         ret = btrfs_end_transaction_throttle(trans, root);
1881 fail:
1882         btrfs_btree_balance_dirty(root, nr);
1883
1884         if (ret && !err)
1885                 err = ret;
1886         return err;
1887 }
1888
1889 /*
1890  * when truncating bytes in a file, it is possible to avoid reading
1891  * the leaves that contain only checksum items.  This can be the
1892  * majority of the IO required to delete a large file, but it must
1893  * be done carefully.
1894  *
1895  * The keys in the level just above the leaves are checked to make sure
1896  * the lowest key in a given leaf is a csum key, and starts at an offset
1897  * after the new  size.
1898  *
1899  * Then the key for the next leaf is checked to make sure it also has
1900  * a checksum item for the same file.  If it does, we know our target leaf
1901  * contains only checksum items, and it can be safely freed without reading
1902  * it.
1903  *
1904  * This is just an optimization targeted at large files.  It may do
1905  * nothing.  It will return 0 unless things went badly.
1906  */
1907 static noinline int drop_csum_leaves(struct btrfs_trans_handle *trans,
1908                                      struct btrfs_root *root,
1909                                      struct btrfs_path *path,
1910                                      struct inode *inode, u64 new_size)
1911 {
1912         struct btrfs_key key;
1913         int ret;
1914         int nritems;
1915         struct btrfs_key found_key;
1916         struct btrfs_key other_key;
1917         struct btrfs_leaf_ref *ref;
1918         u64 leaf_gen;
1919         u64 leaf_start;
1920
1921         path->lowest_level = 1;
1922         key.objectid = inode->i_ino;
1923         key.type = BTRFS_CSUM_ITEM_KEY;
1924         key.offset = new_size;
1925 again:
1926         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1927         if (ret < 0)
1928                 goto out;
1929
1930         if (path->nodes[1] == NULL) {
1931                 ret = 0;
1932                 goto out;
1933         }
1934         ret = 0;
1935         btrfs_node_key_to_cpu(path->nodes[1], &found_key, path->slots[1]);
1936         nritems = btrfs_header_nritems(path->nodes[1]);
1937
1938         if (!nritems)
1939                 goto out;
1940
1941         if (path->slots[1] >= nritems)
1942                 goto next_node;
1943
1944         /* did we find a key greater than anything we want to delete? */
1945         if (found_key.objectid > inode->i_ino ||
1946            (found_key.objectid == inode->i_ino && found_key.type > key.type))
1947                 goto out;
1948
1949         /* we check the next key in the node to make sure the leave contains
1950          * only checksum items.  This comparison doesn't work if our
1951          * leaf is the last one in the node
1952          */
1953         if (path->slots[1] + 1 >= nritems) {
1954 next_node:
1955                 /* search forward from the last key in the node, this
1956                  * will bring us into the next node in the tree
1957                  */
1958                 btrfs_node_key_to_cpu(path->nodes[1], &found_key, nritems - 1);
1959
1960                 /* unlikely, but we inc below, so check to be safe */
1961                 if (found_key.offset == (u64)-1)
1962                         goto out;
1963
1964                 /* search_forward needs a path with locks held, do the
1965                  * search again for the original key.  It is possible
1966                  * this will race with a balance and return a path that
1967                  * we could modify, but this drop is just an optimization
1968                  * and is allowed to miss some leaves.
1969                  */
1970                 btrfs_release_path(root, path);
1971                 found_key.offset++;
1972
1973                 /* setup a max key for search_forward */
1974                 other_key.offset = (u64)-1;
1975                 other_key.type = key.type;
1976                 other_key.objectid = key.objectid;
1977
1978                 path->keep_locks = 1;
1979                 ret = btrfs_search_forward(root, &found_key, &other_key,
1980                                            path, 0, 0);
1981                 path->keep_locks = 0;
1982                 if (ret || found_key.objectid != key.objectid ||
1983                     found_key.type != key.type) {
1984                         ret = 0;
1985                         goto out;
1986                 }
1987
1988                 key.offset = found_key.offset;
1989                 btrfs_release_path(root, path);
1990                 cond_resched();
1991                 goto again;
1992         }
1993
1994         /* we know there's one more slot after us in the tree,
1995          * read that key so we can verify it is also a checksum item
1996          */
1997         btrfs_node_key_to_cpu(path->nodes[1], &other_key, path->slots[1] + 1);
1998
1999         if (found_key.objectid < inode->i_ino)
2000                 goto next_key;
2001
2002         if (found_key.type != key.type || found_key.offset < new_size)
2003                 goto next_key;
2004
2005         /*
2006          * if the key for the next leaf isn't a csum key from this objectid,
2007          * we can't be sure there aren't good items inside this leaf.
2008          * Bail out
2009          */
2010         if (other_key.objectid != inode->i_ino || other_key.type != key.type)
2011                 goto out;
2012
2013         leaf_start = btrfs_node_blockptr(path->nodes[1], path->slots[1]);
2014         leaf_gen = btrfs_node_ptr_generation(path->nodes[1], path->slots[1]);
2015         /*
2016          * it is safe to delete this leaf, it contains only
2017          * csum items from this inode at an offset >= new_size
2018          */
2019         ret = btrfs_del_leaf(trans, root, path, leaf_start);
2020         BUG_ON(ret);
2021
2022         if (root->ref_cows && leaf_gen < trans->transid) {
2023                 ref = btrfs_alloc_leaf_ref(root, 0);
2024                 if (ref) {
2025                         ref->root_gen = root->root_key.offset;
2026                         ref->bytenr = leaf_start;
2027                         ref->owner = 0;
2028                         ref->generation = leaf_gen;
2029                         ref->nritems = 0;
2030
2031                         ret = btrfs_add_leaf_ref(root, ref, 0);
2032                         WARN_ON(ret);
2033                         btrfs_free_leaf_ref(root, ref);
2034                 } else {
2035                         WARN_ON(1);
2036                 }
2037         }
2038 next_key:
2039         btrfs_release_path(root, path);
2040
2041         if (other_key.objectid == inode->i_ino &&
2042             other_key.type == key.type && other_key.offset > key.offset) {
2043                 key.offset = other_key.offset;
2044                 cond_resched();
2045                 goto again;
2046         }
2047         ret = 0;
2048 out:
2049         /* fixup any changes we've made to the path */
2050         path->lowest_level = 0;
2051         path->keep_locks = 0;
2052         btrfs_release_path(root, path);
2053         return ret;
2054 }
2055
2056 /*
2057  * this can truncate away extent items, csum items and directory items.
2058  * It starts at a high offset and removes keys until it can't find
2059  * any higher than new_size
2060  *
2061  * csum items that cross the new i_size are truncated to the new size
2062  * as well.
2063  *
2064  * min_type is the minimum key type to truncate down to.  If set to 0, this
2065  * will kill all the items on this inode, including the INODE_ITEM_KEY.
2066  */
2067 noinline int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
2068                                         struct btrfs_root *root,
2069                                         struct inode *inode,
2070                                         u64 new_size, u32 min_type)
2071 {
2072         int ret;
2073         struct btrfs_path *path;
2074         struct btrfs_key key;
2075         struct btrfs_key found_key;
2076         u32 found_type;
2077         struct extent_buffer *leaf;
2078         struct btrfs_file_extent_item *fi;
2079         u64 extent_start = 0;
2080         u64 extent_num_bytes = 0;
2081         u64 item_end = 0;
2082         u64 root_gen = 0;
2083         u64 root_owner = 0;
2084         int found_extent;
2085         int del_item;
2086         int pending_del_nr = 0;
2087         int pending_del_slot = 0;
2088         int extent_type = -1;
2089         u64 mask = root->sectorsize - 1;
2090
2091         if (root->ref_cows)
2092                 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
2093         path = btrfs_alloc_path();
2094         path->reada = -1;
2095         BUG_ON(!path);
2096
2097         /* FIXME, add redo link to tree so we don't leak on crash */
2098         key.objectid = inode->i_ino;
2099         key.offset = (u64)-1;
2100         key.type = (u8)-1;
2101
2102         btrfs_init_path(path);
2103
2104         ret = drop_csum_leaves(trans, root, path, inode, new_size);
2105         BUG_ON(ret);
2106
2107 search_again:
2108         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2109         if (ret < 0) {
2110                 goto error;
2111         }
2112         if (ret > 0) {
2113                 /* there are no items in the tree for us to truncate, we're
2114                  * done
2115                  */
2116                 if (path->slots[0] == 0) {
2117                         ret = 0;
2118                         goto error;
2119                 }
2120                 path->slots[0]--;
2121         }
2122
2123         while(1) {
2124                 fi = NULL;
2125                 leaf = path->nodes[0];
2126                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2127                 found_type = btrfs_key_type(&found_key);
2128
2129                 if (found_key.objectid != inode->i_ino)
2130                         break;
2131
2132                 if (found_type < min_type)
2133                         break;
2134
2135                 item_end = found_key.offset;
2136                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
2137                         fi = btrfs_item_ptr(leaf, path->slots[0],
2138                                             struct btrfs_file_extent_item);
2139                         extent_type = btrfs_file_extent_type(leaf, fi);
2140                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
2141                                 item_end +=
2142                                     btrfs_file_extent_num_bytes(leaf, fi);
2143                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
2144                                 item_end += btrfs_file_extent_inline_len(leaf,
2145                                                                          fi);
2146                         }
2147                         item_end--;
2148                 }
2149                 if (found_type == BTRFS_CSUM_ITEM_KEY) {
2150                         ret = btrfs_csum_truncate(trans, root, path,
2151                                                   new_size);
2152                         BUG_ON(ret);
2153                 }
2154                 if (item_end < new_size) {
2155                         if (found_type == BTRFS_DIR_ITEM_KEY) {
2156                                 found_type = BTRFS_INODE_ITEM_KEY;
2157                         } else if (found_type == BTRFS_EXTENT_ITEM_KEY) {
2158                                 found_type = BTRFS_CSUM_ITEM_KEY;
2159                         } else if (found_type == BTRFS_EXTENT_DATA_KEY) {
2160                                 found_type = BTRFS_XATTR_ITEM_KEY;
2161                         } else if (found_type == BTRFS_XATTR_ITEM_KEY) {
2162                                 found_type = BTRFS_INODE_REF_KEY;
2163                         } else if (found_type) {
2164                                 found_type--;
2165                         } else {
2166                                 break;
2167                         }
2168                         btrfs_set_key_type(&key, found_type);
2169                         goto next;
2170                 }
2171                 if (found_key.offset >= new_size)
2172                         del_item = 1;
2173                 else
2174                         del_item = 0;
2175                 found_extent = 0;
2176
2177                 /* FIXME, shrink the extent if the ref count is only 1 */
2178                 if (found_type != BTRFS_EXTENT_DATA_KEY)
2179                         goto delete;
2180
2181                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
2182                         u64 num_dec;
2183                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
2184                         if (!del_item) {
2185                                 u64 orig_num_bytes =
2186                                         btrfs_file_extent_num_bytes(leaf, fi);
2187                                 extent_num_bytes = new_size -
2188                                         found_key.offset + root->sectorsize - 1;
2189                                 extent_num_bytes = extent_num_bytes &
2190                                         ~((u64)root->sectorsize - 1);
2191                                 btrfs_set_file_extent_num_bytes(leaf, fi,
2192                                                          extent_num_bytes);
2193                                 num_dec = (orig_num_bytes -
2194                                            extent_num_bytes);
2195                                 if (root->ref_cows && extent_start != 0)
2196                                         inode_sub_bytes(inode, num_dec);
2197                                 btrfs_mark_buffer_dirty(leaf);
2198                         } else {
2199                                 extent_num_bytes =
2200                                         btrfs_file_extent_disk_num_bytes(leaf,
2201                                                                          fi);
2202                                 /* FIXME blocksize != 4096 */
2203                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
2204                                 if (extent_start != 0) {
2205                                         found_extent = 1;
2206                                         if (root->ref_cows)
2207                                                 inode_sub_bytes(inode, num_dec);
2208                                 }
2209                                 root_gen = btrfs_header_generation(leaf);
2210                                 root_owner = btrfs_header_owner(leaf);
2211                         }
2212                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
2213                         /*
2214                          * we can't truncate inline items that have had
2215                          * special encodings
2216                          */
2217                         if (!del_item &&
2218                             btrfs_file_extent_compression(leaf, fi) == 0 &&
2219                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
2220                             btrfs_file_extent_other_encoding(leaf, fi) == 0) {
2221                                 u32 size = new_size - found_key.offset;
2222
2223                                 if (root->ref_cows) {
2224                                         inode_sub_bytes(inode, item_end + 1 -
2225                                                         new_size);
2226                                 }
2227                                 size =
2228                                     btrfs_file_extent_calc_inline_size(size);
2229                                 ret = btrfs_truncate_item(trans, root, path,
2230                                                           size, 1);
2231                                 BUG_ON(ret);
2232                         } else if (root->ref_cows) {
2233                                 inode_sub_bytes(inode, item_end + 1 -
2234                                                 found_key.offset);
2235                         }
2236                 }
2237 delete:
2238                 if (del_item) {
2239                         if (!pending_del_nr) {
2240                                 /* no pending yet, add ourselves */
2241                                 pending_del_slot = path->slots[0];
2242                                 pending_del_nr = 1;
2243                         } else if (pending_del_nr &&
2244                                    path->slots[0] + 1 == pending_del_slot) {
2245                                 /* hop on the pending chunk */
2246                                 pending_del_nr++;
2247                                 pending_del_slot = path->slots[0];
2248                         } else {
2249                                 printk("bad pending slot %d pending_del_nr %d pending_del_slot %d\n", path->slots[0], pending_del_nr, pending_del_slot);
2250                         }
2251                 } else {
2252                         break;
2253                 }
2254                 if (found_extent) {
2255                         ret = btrfs_free_extent(trans, root, extent_start,
2256                                                 extent_num_bytes,
2257                                                 leaf->start, root_owner,
2258                                                 root_gen, inode->i_ino, 0);
2259                         BUG_ON(ret);
2260                 }
2261 next:
2262                 if (path->slots[0] == 0) {
2263                         if (pending_del_nr)
2264                                 goto del_pending;
2265                         btrfs_release_path(root, path);
2266                         goto search_again;
2267                 }
2268
2269                 path->slots[0]--;
2270                 if (pending_del_nr &&
2271                     path->slots[0] + 1 != pending_del_slot) {
2272                         struct btrfs_key debug;
2273 del_pending:
2274                         btrfs_item_key_to_cpu(path->nodes[0], &debug,
2275                                               pending_del_slot);
2276                         ret = btrfs_del_items(trans, root, path,
2277                                               pending_del_slot,
2278                                               pending_del_nr);
2279                         BUG_ON(ret);
2280                         pending_del_nr = 0;
2281                         btrfs_release_path(root, path);
2282                         goto search_again;
2283                 }
2284         }
2285         ret = 0;
2286 error:
2287         if (pending_del_nr) {
2288                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
2289                                       pending_del_nr);
2290         }
2291         btrfs_free_path(path);
2292         inode->i_sb->s_dirt = 1;
2293         return ret;
2294 }
2295
2296 /*
2297  * taken from block_truncate_page, but does cow as it zeros out
2298  * any bytes left in the last page in the file.
2299  */
2300 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
2301 {
2302         struct inode *inode = mapping->host;
2303         struct btrfs_root *root = BTRFS_I(inode)->root;
2304         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2305         struct btrfs_ordered_extent *ordered;
2306         char *kaddr;
2307         u32 blocksize = root->sectorsize;
2308         pgoff_t index = from >> PAGE_CACHE_SHIFT;
2309         unsigned offset = from & (PAGE_CACHE_SIZE-1);
2310         struct page *page;
2311         int ret = 0;
2312         u64 page_start;
2313         u64 page_end;
2314
2315         if ((offset & (blocksize - 1)) == 0)
2316                 goto out;
2317
2318         ret = -ENOMEM;
2319 again:
2320         page = grab_cache_page(mapping, index);
2321         if (!page)
2322                 goto out;
2323
2324         page_start = page_offset(page);
2325         page_end = page_start + PAGE_CACHE_SIZE - 1;
2326
2327         if (!PageUptodate(page)) {
2328                 ret = btrfs_readpage(NULL, page);
2329                 lock_page(page);
2330                 if (page->mapping != mapping) {
2331                         unlock_page(page);
2332                         page_cache_release(page);
2333                         goto again;
2334                 }
2335                 if (!PageUptodate(page)) {
2336                         ret = -EIO;
2337                         goto out_unlock;
2338                 }
2339         }
2340         wait_on_page_writeback(page);
2341
2342         lock_extent(io_tree, page_start, page_end, GFP_NOFS);
2343         set_page_extent_mapped(page);
2344
2345         ordered = btrfs_lookup_ordered_extent(inode, page_start);
2346         if (ordered) {
2347                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
2348                 unlock_page(page);
2349                 page_cache_release(page);
2350                 btrfs_start_ordered_extent(inode, ordered, 1);
2351                 btrfs_put_ordered_extent(ordered);
2352                 goto again;
2353         }
2354
2355         btrfs_set_extent_delalloc(inode, page_start, page_end);
2356         ret = 0;
2357         if (offset != PAGE_CACHE_SIZE) {
2358                 kaddr = kmap(page);
2359                 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
2360                 flush_dcache_page(page);
2361                 kunmap(page);
2362         }
2363         ClearPageChecked(page);
2364         set_page_dirty(page);
2365         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
2366
2367 out_unlock:
2368         unlock_page(page);
2369         page_cache_release(page);
2370 out:
2371         return ret;
2372 }
2373
2374 int btrfs_cont_expand(struct inode *inode, loff_t size)
2375 {
2376         struct btrfs_trans_handle *trans;
2377         struct btrfs_root *root = BTRFS_I(inode)->root;
2378         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2379         struct extent_map *em;
2380         u64 mask = root->sectorsize - 1;
2381         u64 hole_start = (inode->i_size + mask) & ~mask;
2382         u64 block_end = (size + mask) & ~mask;
2383         u64 last_byte;
2384         u64 cur_offset;
2385         u64 hole_size;
2386         int err;
2387
2388         if (size <= hole_start)
2389                 return 0;
2390
2391         err = btrfs_check_free_space(root, 1, 0);
2392         if (err)
2393                 return err;
2394
2395         btrfs_truncate_page(inode->i_mapping, inode->i_size);
2396
2397         while (1) {
2398                 struct btrfs_ordered_extent *ordered;
2399                 btrfs_wait_ordered_range(inode, hole_start,
2400                                          block_end - hole_start);
2401                 lock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
2402                 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
2403                 if (!ordered)
2404                         break;
2405                 unlock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
2406                 btrfs_put_ordered_extent(ordered);
2407         }
2408
2409         trans = btrfs_start_transaction(root, 1);
2410         btrfs_set_trans_block_group(trans, inode);
2411
2412         cur_offset = hole_start;
2413         while (1) {
2414                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
2415                                 block_end - cur_offset, 0);
2416                 BUG_ON(IS_ERR(em) || !em);
2417                 last_byte = min(extent_map_end(em), block_end);
2418                 last_byte = (last_byte + mask) & ~mask;
2419                 if (test_bit(EXTENT_FLAG_VACANCY, &em->flags)) {
2420                         hole_size = last_byte - cur_offset;
2421                         err = btrfs_insert_file_extent(trans, root,
2422                                         inode->i_ino, cur_offset, 0,
2423                                         0, hole_size, 0, hole_size,
2424                                         0, 0, 0);
2425                         btrfs_drop_extent_cache(inode, hole_start,
2426                                         last_byte - 1, 0);
2427                 }
2428                 free_extent_map(em);
2429                 cur_offset = last_byte;
2430                 if (err || cur_offset >= block_end)
2431                         break;
2432         }
2433
2434         btrfs_end_transaction(trans, root);
2435         unlock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
2436         return err;
2437 }
2438
2439 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
2440 {
2441         struct inode *inode = dentry->d_inode;
2442         int err;
2443
2444         err = inode_change_ok(inode, attr);
2445         if (err)
2446                 return err;
2447
2448         if (S_ISREG(inode->i_mode) &&
2449             attr->ia_valid & ATTR_SIZE && attr->ia_size > inode->i_size) {
2450                 err = btrfs_cont_expand(inode, attr->ia_size);
2451                 if (err)
2452                         return err;
2453         }
2454
2455         err = inode_setattr(inode, attr);
2456
2457         if (!err && ((attr->ia_valid & ATTR_MODE)))
2458                 err = btrfs_acl_chmod(inode);
2459         return err;
2460 }
2461
2462 void btrfs_delete_inode(struct inode *inode)
2463 {
2464         struct btrfs_trans_handle *trans;
2465         struct btrfs_root *root = BTRFS_I(inode)->root;
2466         unsigned long nr;
2467         int ret;
2468
2469         truncate_inode_pages(&inode->i_data, 0);
2470         if (is_bad_inode(inode)) {
2471                 btrfs_orphan_del(NULL, inode);
2472                 goto no_delete;
2473         }
2474         btrfs_wait_ordered_range(inode, 0, (u64)-1);
2475
2476         btrfs_i_size_write(inode, 0);
2477         trans = btrfs_start_transaction(root, 1);
2478
2479         btrfs_set_trans_block_group(trans, inode);
2480         ret = btrfs_truncate_inode_items(trans, root, inode, inode->i_size, 0);
2481         if (ret) {
2482                 btrfs_orphan_del(NULL, inode);
2483                 goto no_delete_lock;
2484         }
2485
2486         btrfs_orphan_del(trans, inode);
2487
2488         nr = trans->blocks_used;
2489         clear_inode(inode);
2490
2491         btrfs_end_transaction(trans, root);
2492         btrfs_btree_balance_dirty(root, nr);
2493         return;
2494
2495 no_delete_lock:
2496         nr = trans->blocks_used;
2497         btrfs_end_transaction(trans, root);
2498         btrfs_btree_balance_dirty(root, nr);
2499 no_delete:
2500         clear_inode(inode);
2501 }
2502
2503 /*
2504  * this returns the key found in the dir entry in the location pointer.
2505  * If no dir entries were found, location->objectid is 0.
2506  */
2507 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
2508                                struct btrfs_key *location)
2509 {
2510         const char *name = dentry->d_name.name;
2511         int namelen = dentry->d_name.len;
2512         struct btrfs_dir_item *di;
2513         struct btrfs_path *path;
2514         struct btrfs_root *root = BTRFS_I(dir)->root;
2515         int ret = 0;
2516
2517         path = btrfs_alloc_path();
2518         BUG_ON(!path);
2519
2520         di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
2521                                     namelen, 0);
2522         if (IS_ERR(di))
2523                 ret = PTR_ERR(di);
2524         if (!di || IS_ERR(di)) {
2525                 goto out_err;
2526         }
2527         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
2528 out:
2529         btrfs_free_path(path);
2530         return ret;
2531 out_err:
2532         location->objectid = 0;
2533         goto out;
2534 }
2535
2536 /*
2537  * when we hit a tree root in a directory, the btrfs part of the inode
2538  * needs to be changed to reflect the root directory of the tree root.  This
2539  * is kind of like crossing a mount point.
2540  */
2541 static int fixup_tree_root_location(struct btrfs_root *root,
2542                              struct btrfs_key *location,
2543                              struct btrfs_root **sub_root,
2544                              struct dentry *dentry)
2545 {
2546         struct btrfs_root_item *ri;
2547
2548         if (btrfs_key_type(location) != BTRFS_ROOT_ITEM_KEY)
2549                 return 0;
2550         if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
2551                 return 0;
2552
2553         *sub_root = btrfs_read_fs_root(root->fs_info, location,
2554                                         dentry->d_name.name,
2555                                         dentry->d_name.len);
2556         if (IS_ERR(*sub_root))
2557                 return PTR_ERR(*sub_root);
2558
2559         ri = &(*sub_root)->root_item;
2560         location->objectid = btrfs_root_dirid(ri);
2561         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
2562         location->offset = 0;
2563
2564         return 0;
2565 }
2566
2567 static noinline void init_btrfs_i(struct inode *inode)
2568 {
2569         struct btrfs_inode *bi = BTRFS_I(inode);
2570
2571         bi->i_acl = NULL;
2572         bi->i_default_acl = NULL;
2573
2574         bi->generation = 0;
2575         bi->last_trans = 0;
2576         bi->logged_trans = 0;
2577         bi->delalloc_bytes = 0;
2578         bi->disk_i_size = 0;
2579         bi->flags = 0;
2580         bi->index_cnt = (u64)-1;
2581         bi->log_dirty_trans = 0;
2582         extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
2583         extent_io_tree_init(&BTRFS_I(inode)->io_tree,
2584                              inode->i_mapping, GFP_NOFS);
2585         extent_io_tree_init(&BTRFS_I(inode)->io_failure_tree,
2586                              inode->i_mapping, GFP_NOFS);
2587         INIT_LIST_HEAD(&BTRFS_I(inode)->delalloc_inodes);
2588         btrfs_ordered_inode_tree_init(&BTRFS_I(inode)->ordered_tree);
2589         mutex_init(&BTRFS_I(inode)->csum_mutex);
2590         mutex_init(&BTRFS_I(inode)->extent_mutex);
2591         mutex_init(&BTRFS_I(inode)->log_mutex);
2592 }
2593
2594 static int btrfs_init_locked_inode(struct inode *inode, void *p)
2595 {
2596         struct btrfs_iget_args *args = p;
2597         inode->i_ino = args->ino;
2598         init_btrfs_i(inode);
2599         BTRFS_I(inode)->root = args->root;
2600         return 0;
2601 }
2602
2603 static int btrfs_find_actor(struct inode *inode, void *opaque)
2604 {
2605         struct btrfs_iget_args *args = opaque;
2606         return (args->ino == inode->i_ino &&
2607                 args->root == BTRFS_I(inode)->root);
2608 }
2609
2610 struct inode *btrfs_ilookup(struct super_block *s, u64 objectid,
2611                             struct btrfs_root *root, int wait)
2612 {
2613         struct inode *inode;
2614         struct btrfs_iget_args args;
2615         args.ino = objectid;
2616         args.root = root;
2617
2618         if (wait) {
2619                 inode = ilookup5(s, objectid, btrfs_find_actor,
2620                                  (void *)&args);
2621         } else {
2622                 inode = ilookup5_nowait(s, objectid, btrfs_find_actor,
2623                                         (void *)&args);
2624         }
2625         return inode;
2626 }
2627
2628 struct inode *btrfs_iget_locked(struct super_block *s, u64 objectid,
2629                                 struct btrfs_root *root)
2630 {
2631         struct inode *inode;
2632         struct btrfs_iget_args args;
2633         args.ino = objectid;
2634         args.root = root;
2635
2636         inode = iget5_locked(s, objectid, btrfs_find_actor,
2637                              btrfs_init_locked_inode,
2638                              (void *)&args);
2639         return inode;
2640 }
2641
2642 /* Get an inode object given its location and corresponding root.
2643  * Returns in *is_new if the inode was read from disk
2644  */
2645 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
2646                          struct btrfs_root *root, int *is_new)
2647 {
2648         struct inode *inode;
2649
2650         inode = btrfs_iget_locked(s, location->objectid, root);
2651         if (!inode)
2652                 return ERR_PTR(-EACCES);
2653
2654         if (inode->i_state & I_NEW) {
2655                 BTRFS_I(inode)->root = root;
2656                 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
2657                 btrfs_read_locked_inode(inode);
2658                 unlock_new_inode(inode);
2659                 if (is_new)
2660                         *is_new = 1;
2661         } else {
2662                 if (is_new)
2663                         *is_new = 0;
2664         }
2665
2666         return inode;
2667 }
2668
2669 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
2670                                    struct nameidata *nd)
2671 {
2672         struct inode * inode;
2673         struct btrfs_inode *bi = BTRFS_I(dir);
2674         struct btrfs_root *root = bi->root;
2675         struct btrfs_root *sub_root = root;
2676         struct btrfs_key location;
2677         int ret, new, do_orphan = 0;
2678
2679         if (dentry->d_name.len > BTRFS_NAME_LEN)
2680                 return ERR_PTR(-ENAMETOOLONG);
2681
2682         ret = btrfs_inode_by_name(dir, dentry, &location);
2683
2684         if (ret < 0)
2685                 return ERR_PTR(ret);
2686
2687         inode = NULL;
2688         if (location.objectid) {
2689                 ret = fixup_tree_root_location(root, &location, &sub_root,
2690                                                 dentry);
2691                 if (ret < 0)
2692                         return ERR_PTR(ret);
2693                 if (ret > 0)
2694                         return ERR_PTR(-ENOENT);
2695                 inode = btrfs_iget(dir->i_sb, &location, sub_root, &new);
2696                 if (IS_ERR(inode))
2697                         return ERR_CAST(inode);
2698
2699                 /* the inode and parent dir are two different roots */
2700                 if (new && root != sub_root) {
2701                         igrab(inode);
2702                         sub_root->inode = inode;
2703                         do_orphan = 1;
2704                 }
2705         }
2706
2707         if (unlikely(do_orphan))
2708                 btrfs_orphan_cleanup(sub_root);
2709
2710         return d_splice_alias(inode, dentry);
2711 }
2712
2713 static unsigned char btrfs_filetype_table[] = {
2714         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
2715 };
2716
2717 static int btrfs_real_readdir(struct file *filp, void *dirent,
2718                               filldir_t filldir)
2719 {
2720         struct inode *inode = filp->f_dentry->d_inode;
2721         struct btrfs_root *root = BTRFS_I(inode)->root;
2722         struct btrfs_item *item;
2723         struct btrfs_dir_item *di;
2724         struct btrfs_key key;
2725         struct btrfs_key found_key;
2726         struct btrfs_path *path;
2727         int ret;
2728         u32 nritems;
2729         struct extent_buffer *leaf;
2730         int slot;
2731         int advance;
2732         unsigned char d_type;
2733         int over = 0;
2734         u32 di_cur;
2735         u32 di_total;
2736         u32 di_len;
2737         int key_type = BTRFS_DIR_INDEX_KEY;
2738         char tmp_name[32];
2739         char *name_ptr;
2740         int name_len;
2741
2742         /* FIXME, use a real flag for deciding about the key type */
2743         if (root->fs_info->tree_root == root)
2744                 key_type = BTRFS_DIR_ITEM_KEY;
2745
2746         /* special case for "." */
2747         if (filp->f_pos == 0) {
2748                 over = filldir(dirent, ".", 1,
2749                                1, inode->i_ino,
2750                                DT_DIR);
2751                 if (over)
2752                         return 0;
2753                 filp->f_pos = 1;
2754         }
2755         /* special case for .., just use the back ref */
2756         if (filp->f_pos == 1) {
2757                 u64 pino = parent_ino(filp->f_path.dentry);
2758                 over = filldir(dirent, "..", 2,
2759                                2, pino, DT_DIR);
2760                 if (over)
2761                         return 0;
2762                 filp->f_pos = 2;
2763         }
2764
2765         path = btrfs_alloc_path();
2766         path->reada = 2;
2767
2768         btrfs_set_key_type(&key, key_type);
2769         key.offset = filp->f_pos;
2770         key.objectid = inode->i_ino;
2771
2772         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2773         if (ret < 0)
2774                 goto err;
2775         advance = 0;
2776
2777         while (1) {
2778                 leaf = path->nodes[0];
2779                 nritems = btrfs_header_nritems(leaf);
2780                 slot = path->slots[0];
2781                 if (advance || slot >= nritems) {
2782                         if (slot >= nritems - 1) {
2783                                 ret = btrfs_next_leaf(root, path);
2784                                 if (ret)
2785                                         break;
2786                                 leaf = path->nodes[0];
2787                                 nritems = btrfs_header_nritems(leaf);
2788                                 slot = path->slots[0];
2789                         } else {
2790                                 slot++;
2791                                 path->slots[0]++;
2792                         }
2793                 }
2794                 advance = 1;
2795                 item = btrfs_item_nr(leaf, slot);
2796                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2797
2798                 if (found_key.objectid != key.objectid)
2799                         break;
2800                 if (btrfs_key_type(&found_key) != key_type)
2801                         break;
2802                 if (found_key.offset < filp->f_pos)
2803                         continue;
2804
2805                 filp->f_pos = found_key.offset;
2806
2807                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
2808                 di_cur = 0;
2809                 di_total = btrfs_item_size(leaf, item);
2810
2811                 while (di_cur < di_total) {
2812                         struct btrfs_key location;
2813
2814                         name_len = btrfs_dir_name_len(leaf, di);
2815                         if (name_len <= sizeof(tmp_name)) {
2816                                 name_ptr = tmp_name;
2817                         } else {
2818                                 name_ptr = kmalloc(name_len, GFP_NOFS);
2819                                 if (!name_ptr) {
2820                                         ret = -ENOMEM;
2821                                         goto err;
2822                                 }
2823                         }
2824                         read_extent_buffer(leaf, name_ptr,
2825                                            (unsigned long)(di + 1), name_len);
2826
2827                         d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
2828                         btrfs_dir_item_key_to_cpu(leaf, di, &location);
2829                         over = filldir(dirent, name_ptr, name_len,
2830                                        found_key.offset, location.objectid,
2831                                        d_type);
2832
2833                         if (name_ptr != tmp_name)
2834                                 kfree(name_ptr);
2835
2836                         if (over)
2837                                 goto nopos;
2838
2839                         di_len = btrfs_dir_name_len(leaf, di) +
2840                                  btrfs_dir_data_len(leaf, di) + sizeof(*di);
2841                         di_cur += di_len;
2842                         di = (struct btrfs_dir_item *)((char *)di + di_len);
2843                 }
2844         }
2845
2846         /* Reached end of directory/root. Bump pos past the last item. */
2847         if (key_type == BTRFS_DIR_INDEX_KEY)
2848                 filp->f_pos = INT_LIMIT(typeof(filp->f_pos));
2849         else
2850                 filp->f_pos++;
2851 nopos:
2852         ret = 0;
2853 err:
2854         btrfs_free_path(path);
2855         return ret;
2856 }
2857
2858 int btrfs_write_inode(struct inode *inode, int wait)
2859 {
2860         struct btrfs_root *root = BTRFS_I(inode)->root;
2861         struct btrfs_trans_handle *trans;
2862         int ret = 0;
2863
2864         if (root->fs_info->closing > 1)
2865                 return 0;
2866
2867         if (wait) {
2868                 trans = btrfs_join_transaction(root, 1);
2869                 btrfs_set_trans_block_group(trans, inode);
2870                 ret = btrfs_commit_transaction(trans, root);
2871         }
2872         return ret;
2873 }
2874
2875 /*
2876  * This is somewhat expensive, updating the tree every time the
2877  * inode changes.  But, it is most likely to find the inode in cache.
2878  * FIXME, needs more benchmarking...there are no reasons other than performance
2879  * to keep or drop this code.
2880  */
2881 void btrfs_dirty_inode(struct inode *inode)
2882 {
2883         struct btrfs_root *root = BTRFS_I(inode)->root;
2884         struct btrfs_trans_handle *trans;
2885
2886         trans = btrfs_join_transaction(root, 1);
2887         btrfs_set_trans_block_group(trans, inode);
2888         btrfs_update_inode(trans, root, inode);
2889         btrfs_end_transaction(trans, root);
2890 }
2891
2892 /*
2893  * find the highest existing sequence number in a directory
2894  * and then set the in-memory index_cnt variable to reflect
2895  * free sequence numbers
2896  */
2897 static int btrfs_set_inode_index_count(struct inode *inode)
2898 {
2899         struct btrfs_root *root = BTRFS_I(inode)->root;
2900         struct btrfs_key key, found_key;
2901         struct btrfs_path *path;
2902         struct extent_buffer *leaf;
2903         int ret;
2904
2905         key.objectid = inode->i_ino;
2906         btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
2907         key.offset = (u64)-1;
2908
2909         path = btrfs_alloc_path();
2910         if (!path)
2911                 return -ENOMEM;
2912
2913         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2914         if (ret < 0)
2915                 goto out;
2916         /* FIXME: we should be able to handle this */
2917         if (ret == 0)
2918                 goto out;
2919         ret = 0;
2920
2921         /*
2922          * MAGIC NUMBER EXPLANATION:
2923          * since we search a directory based on f_pos we have to start at 2
2924          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
2925          * else has to start at 2
2926          */
2927         if (path->slots[0] == 0) {
2928                 BTRFS_I(inode)->index_cnt = 2;
2929                 goto out;
2930         }
2931
2932         path->slots[0]--;
2933
2934         leaf = path->nodes[0];
2935         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2936
2937         if (found_key.objectid != inode->i_ino ||
2938             btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
2939                 BTRFS_I(inode)->index_cnt = 2;
2940                 goto out;
2941         }
2942
2943         BTRFS_I(inode)->index_cnt = found_key.offset + 1;
2944 out:
2945         btrfs_free_path(path);
2946         return ret;
2947 }
2948
2949 /*
2950  * helper to find a free sequence number in a given directory.  This current
2951  * code is very simple, later versions will do smarter things in the btree
2952  */
2953 static int btrfs_set_inode_index(struct inode *dir, struct inode *inode,
2954                                  u64 *index)
2955 {
2956         int ret = 0;
2957
2958         if (BTRFS_I(dir)->index_cnt == (u64)-1) {
2959                 ret = btrfs_set_inode_index_count(dir);
2960                 if (ret) {
2961                         return ret;
2962                 }
2963         }
2964
2965         *index = BTRFS_I(dir)->index_cnt;
2966         BTRFS_I(dir)->index_cnt++;
2967
2968         return ret;
2969 }
2970
2971 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
2972                                      struct btrfs_root *root,
2973                                      struct inode *dir,
2974                                      const char *name, int name_len,
2975                                      u64 ref_objectid,
2976                                      u64 objectid,
2977                                      struct btrfs_block_group_cache *group,
2978                                      int mode, u64 *index)
2979 {
2980         struct inode *inode;
2981         struct btrfs_inode_item *inode_item;
2982         struct btrfs_block_group_cache *new_inode_group;
2983         struct btrfs_key *location;
2984         struct btrfs_path *path;
2985         struct btrfs_inode_ref *ref;
2986         struct btrfs_key key[2];
2987         u32 sizes[2];
2988         unsigned long ptr;
2989         int ret;
2990         int owner;
2991
2992         path = btrfs_alloc_path();
2993         BUG_ON(!path);
2994
2995         inode = new_inode(root->fs_info->sb);
2996         if (!inode)
2997                 return ERR_PTR(-ENOMEM);
2998
2999         if (dir) {
3000                 ret = btrfs_set_inode_index(dir, inode, index);
3001                 if (ret)
3002                         return ERR_PTR(ret);
3003         }
3004         /*
3005          * index_cnt is ignored for everything but a dir,
3006          * btrfs_get_inode_index_count has an explanation for the magic
3007          * number
3008          */
3009         init_btrfs_i(inode);
3010         BTRFS_I(inode)->index_cnt = 2;
3011         BTRFS_I(inode)->root = root;
3012         BTRFS_I(inode)->generation = trans->transid;
3013
3014         if (mode & S_IFDIR)
3015                 owner = 0;
3016         else
3017                 owner = 1;
3018         new_inode_group = btrfs_find_block_group(root, group, 0,
3019                                        BTRFS_BLOCK_GROUP_METADATA, owner);
3020         if (!new_inode_group) {
3021                 printk("find_block group failed\n");
3022                 new_inode_group = group;
3023         }
3024         BTRFS_I(inode)->block_group = new_inode_group;
3025
3026         key[0].objectid = objectid;
3027         btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
3028         key[0].offset = 0;
3029
3030         key[1].objectid = objectid;
3031         btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
3032         key[1].offset = ref_objectid;
3033
3034         sizes[0] = sizeof(struct btrfs_inode_item);
3035         sizes[1] = name_len + sizeof(*ref);
3036
3037         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
3038         if (ret != 0)
3039                 goto fail;
3040
3041         if (objectid > root->highest_inode)
3042                 root->highest_inode = objectid;
3043
3044         inode->i_uid = current->fsuid;
3045         inode->i_gid = current->fsgid;
3046         inode->i_mode = mode;
3047         inode->i_ino = objectid;
3048         inode_set_bytes(inode, 0);
3049         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
3050         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3051                                   struct btrfs_inode_item);
3052         fill_inode_item(trans, path->nodes[0], inode_item, inode);
3053
3054         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
3055                              struct btrfs_inode_ref);
3056         btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
3057         btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
3058         ptr = (unsigned long)(ref + 1);
3059         write_extent_buffer(path->nodes[0], name, ptr, name_len);
3060
3061         btrfs_mark_buffer_dirty(path->nodes[0]);
3062         btrfs_free_path(path);
3063
3064         location = &BTRFS_I(inode)->location;
3065         location->objectid = objectid;
3066         location->offset = 0;
3067         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
3068
3069         insert_inode_hash(inode);
3070         return inode;
3071 fail:
3072         if (dir)
3073                 BTRFS_I(dir)->index_cnt--;
3074         btrfs_free_path(path);
3075         return ERR_PTR(ret);
3076 }
3077
3078 static inline u8 btrfs_inode_type(struct inode *inode)
3079 {
3080         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
3081 }
3082
3083 /*
3084  * utility function to add 'inode' into 'parent_inode' with
3085  * a give name and a given sequence number.
3086  * if 'add_backref' is true, also insert a backref from the
3087  * inode to the parent directory.
3088  */
3089 int btrfs_add_link(struct btrfs_trans_handle *trans,
3090                    struct inode *parent_inode, struct inode *inode,
3091                    const char *name, int name_len, int add_backref, u64 index)
3092 {
3093         int ret;
3094         struct btrfs_key key;
3095         struct btrfs_root *root = BTRFS_I(parent_inode)->root;
3096
3097         key.objectid = inode->i_ino;
3098         btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
3099         key.offset = 0;
3100
3101         ret = btrfs_insert_dir_item(trans, root, name, name_len,
3102                                     parent_inode->i_ino,
3103                                     &key, btrfs_inode_type(inode),
3104                                     index);
3105         if (ret == 0) {
3106                 if (add_backref) {
3107                         ret = btrfs_insert_inode_ref(trans, root,
3108                                                      name, name_len,
3109                                                      inode->i_ino,
3110                                                      parent_inode->i_ino,
3111                                                      index);
3112                 }
3113                 btrfs_i_size_write(parent_inode, parent_inode->i_size +
3114                                    name_len * 2);
3115                 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
3116                 ret = btrfs_update_inode(trans, root, parent_inode);
3117         }
3118         return ret;
3119 }
3120
3121 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
3122                             struct dentry *dentry, struct inode *inode,
3123                             int backref, u64 index)
3124 {
3125         int err = btrfs_add_link(trans, dentry->d_parent->d_inode,
3126                                  inode, dentry->d_name.name,
3127                                  dentry->d_name.len, backref, index);
3128         if (!err) {
3129                 d_instantiate(dentry, inode);
3130                 return 0;
3131         }
3132         if (err > 0)
3133                 err = -EEXIST;
3134         return err;
3135 }
3136
3137 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
3138                         int mode, dev_t rdev)
3139 {
3140         struct btrfs_trans_handle *trans;
3141         struct btrfs_root *root = BTRFS_I(dir)->root;
3142         struct inode *inode = NULL;
3143         int err;
3144         int drop_inode = 0;
3145         u64 objectid;
3146         unsigned long nr = 0;
3147         u64 index = 0;
3148
3149         if (!new_valid_dev(rdev))
3150                 return -EINVAL;
3151
3152         err = btrfs_check_free_space(root, 1, 0);
3153         if (err)
3154                 goto fail;
3155
3156         trans = btrfs_start_transaction(root, 1);
3157         btrfs_set_trans_block_group(trans, dir);
3158
3159         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
3160         if (err) {
3161                 err = -ENOSPC;
3162                 goto out_unlock;
3163         }
3164
3165         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
3166                                 dentry->d_name.len,
3167                                 dentry->d_parent->d_inode->i_ino, objectid,
3168                                 BTRFS_I(dir)->block_group, mode, &index);
3169         err = PTR_ERR(inode);
3170         if (IS_ERR(inode))
3171                 goto out_unlock;
3172
3173         err = btrfs_init_acl(inode, dir);
3174         if (err) {
3175                 drop_inode = 1;
3176                 goto out_unlock;
3177         }
3178
3179         btrfs_set_trans_block_group(trans, inode);
3180         err = btrfs_add_nondir(trans, dentry, inode, 0, index);
3181         if (err)
3182                 drop_inode = 1;
3183         else {
3184                 inode->i_op = &btrfs_special_inode_operations;
3185                 init_special_inode(inode, inode->i_mode, rdev);
3186                 btrfs_update_inode(trans, root, inode);
3187         }
3188         dir->i_sb->s_dirt = 1;
3189         btrfs_update_inode_block_group(trans, inode);
3190         btrfs_update_inode_block_group(trans, dir);
3191 out_unlock:
3192         nr = trans->blocks_used;
3193         btrfs_end_transaction_throttle(trans, root);
3194 fail:
3195         if (drop_inode) {
3196                 inode_dec_link_count(inode);
3197                 iput(inode);
3198         }
3199         btrfs_btree_balance_dirty(root, nr);
3200         return err;
3201 }
3202
3203 static int btrfs_create(struct inode *dir, struct dentry *dentry,
3204                         int mode, struct nameidata *nd)
3205 {
3206         struct btrfs_trans_handle *trans;
3207         struct btrfs_root *root = BTRFS_I(dir)->root;
3208         struct inode *inode = NULL;
3209         int err;
3210         int drop_inode = 0;
3211         unsigned long nr = 0;
3212         u64 objectid;
3213         u64 index = 0;
3214
3215         err = btrfs_check_free_space(root, 1, 0);
3216         if (err)
3217                 goto fail;
3218         trans = btrfs_start_transaction(root, 1);
3219         btrfs_set_trans_block_group(trans, dir);
3220
3221         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
3222         if (err) {
3223                 err = -ENOSPC;
3224                 goto out_unlock;
3225         }
3226
3227         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
3228                                 dentry->d_name.len,
3229                                 dentry->d_parent->d_inode->i_ino,
3230                                 objectid, BTRFS_I(dir)->block_group, mode,
3231                                 &index);
3232         err = PTR_ERR(inode);
3233         if (IS_ERR(inode))
3234                 goto out_unlock;
3235
3236         err = btrfs_init_acl(inode, dir);
3237         if (err) {
3238                 drop_inode = 1;
3239                 goto out_unlock;
3240         }
3241
3242         btrfs_set_trans_block_group(trans, inode);
3243         err = btrfs_add_nondir(trans, dentry, inode, 0, index);
3244         if (err)
3245                 drop_inode = 1;
3246         else {
3247                 inode->i_mapping->a_ops = &btrfs_aops;
3248                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3249                 inode->i_fop = &btrfs_file_operations;
3250                 inode->i_op = &btrfs_file_inode_operations;
3251                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3252         }
3253         dir->i_sb->s_dirt = 1;
3254         btrfs_update_inode_block_group(trans, inode);
3255         btrfs_update_inode_block_group(trans, dir);
3256 out_unlock:
3257         nr = trans->blocks_used;
3258         btrfs_end_transaction_throttle(trans, root);
3259 fail:
3260         if (drop_inode) {
3261                 inode_dec_link_count(inode);
3262                 iput(inode);
3263         }
3264         btrfs_btree_balance_dirty(root, nr);
3265         return err;
3266 }
3267
3268 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
3269                       struct dentry *dentry)
3270 {
3271         struct btrfs_trans_handle *trans;
3272         struct btrfs_root *root = BTRFS_I(dir)->root;
3273         struct inode *inode = old_dentry->d_inode;
3274         u64 index;
3275         unsigned long nr = 0;
3276         int err;
3277         int drop_inode = 0;
3278
3279         if (inode->i_nlink == 0)
3280                 return -ENOENT;
3281
3282         btrfs_inc_nlink(inode);
3283         err = btrfs_check_free_space(root, 1, 0);
3284         if (err)
3285                 goto fail;
3286         err = btrfs_set_inode_index(dir, inode, &index);
3287         if (err)
3288                 goto fail;
3289
3290         trans = btrfs_start_transaction(root, 1);
3291
3292         btrfs_set_trans_block_group(trans, dir);
3293         atomic_inc(&inode->i_count);
3294
3295         err = btrfs_add_nondir(trans, dentry, inode, 1, index);
3296
3297         if (err)
3298                 drop_inode = 1;
3299
3300         dir->i_sb->s_dirt = 1;
3301         btrfs_update_inode_block_group(trans, dir);
3302         err = btrfs_update_inode(trans, root, inode);
3303
3304         if (err)
3305                 drop_inode = 1;
3306
3307         nr = trans->blocks_used;
3308         btrfs_end_transaction_throttle(trans, root);
3309 fail:
3310         if (drop_inode) {
3311                 inode_dec_link_count(inode);
3312                 iput(inode);
3313         }
3314         btrfs_btree_balance_dirty(root, nr);
3315         return err;
3316 }
3317
3318 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
3319 {
3320         struct inode *inode = NULL;
3321         struct btrfs_trans_handle *trans;
3322         struct btrfs_root *root = BTRFS_I(dir)->root;
3323         int err = 0;
3324         int drop_on_err = 0;
3325         u64 objectid = 0;
3326         u64 index = 0;
3327         unsigned long nr = 1;
3328
3329         err = btrfs_check_free_space(root, 1, 0);
3330         if (err)
3331                 goto out_unlock;
3332
3333         trans = btrfs_start_transaction(root, 1);
3334         btrfs_set_trans_block_group(trans, dir);
3335
3336         if (IS_ERR(trans)) {
3337                 err = PTR_ERR(trans);
3338                 goto out_unlock;
3339         }
3340
3341         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
3342         if (err) {
3343                 err = -ENOSPC;
3344                 goto out_unlock;
3345         }
3346
3347         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
3348                                 dentry->d_name.len,
3349                                 dentry->d_parent->d_inode->i_ino, objectid,
3350                                 BTRFS_I(dir)->block_group, S_IFDIR | mode,
3351                                 &index);
3352         if (IS_ERR(inode)) {
3353                 err = PTR_ERR(inode);
3354                 goto out_fail;
3355         }
3356
3357         drop_on_err = 1;
3358
3359         err = btrfs_init_acl(inode, dir);
3360         if (err)
3361                 goto out_fail;
3362
3363         inode->i_op = &btrfs_dir_inode_operations;
3364         inode->i_fop = &btrfs_dir_file_operations;
3365         btrfs_set_trans_block_group(trans, inode);
3366
3367         btrfs_i_size_write(inode, 0);
3368         err = btrfs_update_inode(trans, root, inode);
3369         if (err)
3370                 goto out_fail;
3371
3372         err = btrfs_add_link(trans, dentry->d_parent->d_inode,
3373                                  inode, dentry->d_name.name,
3374                                  dentry->d_name.len, 0, index);
3375         if (err)
3376                 goto out_fail;
3377
3378         d_instantiate(dentry, inode);
3379         drop_on_err = 0;
3380         dir->i_sb->s_dirt = 1;
3381         btrfs_update_inode_block_group(trans, inode);
3382         btrfs_update_inode_block_group(trans, dir);
3383
3384 out_fail:
3385         nr = trans->blocks_used;
3386         btrfs_end_transaction_throttle(trans, root);
3387
3388 out_unlock:
3389         if (drop_on_err)
3390                 iput(inode);
3391         btrfs_btree_balance_dirty(root, nr);
3392         return err;
3393 }
3394
3395 /* helper for btfs_get_extent.  Given an existing extent in the tree,
3396  * and an extent that you want to insert, deal with overlap and insert
3397  * the new extent into the tree.
3398  */
3399 static int merge_extent_mapping(struct extent_map_tree *em_tree,
3400                                 struct extent_map *existing,
3401                                 struct extent_map *em,
3402                                 u64 map_start, u64 map_len)
3403 {
3404         u64 start_diff;
3405
3406         BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
3407         start_diff = map_start - em->start;
3408         em->start = map_start;
3409         em->len = map_len;
3410         if (em->block_start < EXTENT_MAP_LAST_BYTE &&
3411             !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3412                 em->block_start += start_diff;
3413                 em->block_len -= start_diff;
3414         }
3415         return add_extent_mapping(em_tree, em);
3416 }
3417
3418 static noinline int uncompress_inline(struct btrfs_path *path,
3419                                       struct inode *inode, struct page *page,
3420                                       size_t pg_offset, u64 extent_offset,
3421                                       struct btrfs_file_extent_item *item)
3422 {
3423         int ret;
3424         struct extent_buffer *leaf = path->nodes[0];
3425         char *tmp;
3426         size_t max_size;
3427         unsigned long inline_size;
3428         unsigned long ptr;
3429
3430         WARN_ON(pg_offset != 0);
3431         max_size = btrfs_file_extent_ram_bytes(leaf, item);
3432         inline_size = btrfs_file_extent_inline_item_len(leaf,
3433                                         btrfs_item_nr(leaf, path->slots[0]));
3434         tmp = kmalloc(inline_size, GFP_NOFS);
3435         ptr = btrfs_file_extent_inline_start(item);
3436
3437         read_extent_buffer(leaf, tmp, ptr, inline_size);
3438
3439         max_size = min(PAGE_CACHE_SIZE, max_size);
3440         ret = btrfs_zlib_decompress(tmp, page, extent_offset,
3441                                     inline_size, max_size);
3442         if (ret) {
3443                 char *kaddr = kmap_atomic(page, KM_USER0);
3444                 unsigned long copy_size = min_t(u64,
3445                                   PAGE_CACHE_SIZE - pg_offset,
3446                                   max_size - extent_offset);
3447                 memset(kaddr + pg_offset, 0, copy_size);
3448                 kunmap_atomic(kaddr, KM_USER0);
3449         }
3450         kfree(tmp);
3451         return 0;
3452 }
3453
3454 /*
3455  * a bit scary, this does extent mapping from logical file offset to the disk.
3456  * the ugly parts come from merging extents from the disk with the
3457  * in-ram representation.  This gets more complex because of the data=ordered code,
3458  * where the in-ram extents might be locked pending data=ordered completion.
3459  *
3460  * This also copies inline extents directly into the page.
3461  */
3462 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
3463                                     size_t pg_offset, u64 start, u64 len,
3464                                     int create)
3465 {
3466         int ret;
3467         int err = 0;
3468         u64 bytenr;
3469         u64 extent_start = 0;
3470         u64 extent_end = 0;
3471         u64 objectid = inode->i_ino;
3472         u32 found_type;
3473         struct btrfs_path *path = NULL;
3474         struct btrfs_root *root = BTRFS_I(inode)->root;
3475         struct btrfs_file_extent_item *item;
3476         struct extent_buffer *leaf;
3477         struct btrfs_key found_key;
3478         struct extent_map *em = NULL;
3479         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
3480         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3481         struct btrfs_trans_handle *trans = NULL;
3482         int compressed;
3483
3484 again:
3485         spin_lock(&em_tree->lock);
3486         em = lookup_extent_mapping(em_tree, start, len);
3487         if (em)
3488                 em->bdev = root->fs_info->fs_devices->latest_bdev;
3489         spin_unlock(&em_tree->lock);
3490
3491         if (em) {
3492                 if (em->start > start || em->start + em->len <= start)
3493                         free_extent_map(em);
3494                 else if (em->block_start == EXTENT_MAP_INLINE && page)
3495                         free_extent_map(em);
3496                 else
3497                         goto out;
3498         }
3499         em = alloc_extent_map(GFP_NOFS);
3500         if (!em) {
3501                 err = -ENOMEM;
3502                 goto out;
3503         }
3504         em->bdev = root->fs_info->fs_devices->latest_bdev;
3505         em->start = EXTENT_MAP_HOLE;
3506         em->len = (u64)-1;
3507         em->block_len = (u64)-1;
3508
3509         if (!path) {
3510                 path = btrfs_alloc_path();
3511                 BUG_ON(!path);
3512         }
3513
3514         ret = btrfs_lookup_file_extent(trans, root, path,
3515                                        objectid, start, trans != NULL);
3516         if (ret < 0) {
3517                 err = ret;
3518                 goto out;
3519         }
3520
3521         if (ret != 0) {
3522                 if (path->slots[0] == 0)
3523                         goto not_found;
3524                 path->slots[0]--;
3525         }
3526
3527         leaf = path->nodes[0];
3528         item = btrfs_item_ptr(leaf, path->slots[0],
3529                               struct btrfs_file_extent_item);
3530         /* are we inside the extent that was found? */
3531         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3532         found_type = btrfs_key_type(&found_key);
3533         if (found_key.objectid != objectid ||
3534             found_type != BTRFS_EXTENT_DATA_KEY) {
3535                 goto not_found;
3536         }
3537
3538         found_type = btrfs_file_extent_type(leaf, item);
3539         extent_start = found_key.offset;
3540         compressed = btrfs_file_extent_compression(leaf, item);
3541         if (found_type == BTRFS_FILE_EXTENT_REG ||
3542             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
3543                 extent_end = extent_start +
3544                        btrfs_file_extent_num_bytes(leaf, item);
3545         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
3546                 size_t size;
3547                 size = btrfs_file_extent_inline_len(leaf, item);
3548                 extent_end = (extent_start + size + root->sectorsize - 1) &
3549                         ~((u64)root->sectorsize - 1);
3550         }
3551
3552         if (start >= extent_end) {
3553                 path->slots[0]++;
3554                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
3555                         ret = btrfs_next_leaf(root, path);
3556                         if (ret < 0) {
3557                                 err = ret;
3558                                 goto out;
3559                         }
3560                         if (ret > 0)
3561                                 goto not_found;
3562                         leaf = path->nodes[0];
3563                 }
3564                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3565                 if (found_key.objectid != objectid ||
3566                     found_key.type != BTRFS_EXTENT_DATA_KEY)
3567                         goto not_found;
3568                 if (start + len <= found_key.offset)
3569                         goto not_found;
3570                 em->start = start;
3571                 em->len = found_key.offset - start;
3572                 goto not_found_em;
3573         }
3574
3575         if (found_type == BTRFS_FILE_EXTENT_REG ||
3576             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
3577                 em->start = extent_start;
3578                 em->len = extent_end - extent_start;
3579                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
3580                 if (bytenr == 0) {
3581                         em->block_start = EXTENT_MAP_HOLE;
3582                         goto insert;
3583                 }
3584                 if (compressed) {
3585                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3586                         em->block_start = bytenr;
3587                         em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
3588                                                                          item);
3589                 } else {
3590                         bytenr += btrfs_file_extent_offset(leaf, item);
3591                         em->block_start = bytenr;
3592                         em->block_len = em->len;
3593                         if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
3594                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
3595                 }
3596                 goto insert;
3597         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
3598                 unsigned long ptr;
3599                 char *map;
3600                 size_t size;
3601                 size_t extent_offset;
3602                 size_t copy_size;
3603
3604                 em->block_start = EXTENT_MAP_INLINE;
3605                 if (!page || create) {
3606                         em->start = extent_start;
3607                         em->len = extent_end - extent_start;
3608                         goto out;
3609                 }
3610
3611                 size = btrfs_file_extent_inline_len(leaf, item);
3612                 extent_offset = page_offset(page) + pg_offset - extent_start;
3613                 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
3614                                 size - extent_offset);
3615                 em->start = extent_start + extent_offset;
3616                 em->len = (copy_size + root->sectorsize - 1) &
3617                         ~((u64)root->sectorsize - 1);
3618                 if (compressed)
3619                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3620                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
3621                 if (create == 0 && !PageUptodate(page)) {
3622                         if (btrfs_file_extent_compression(leaf, item) ==
3623                             BTRFS_COMPRESS_ZLIB) {
3624                                 ret = uncompress_inline(path, inode, page,
3625                                                         pg_offset,
3626                                                         extent_offset, item);
3627                                 BUG_ON(ret);
3628                         } else {
3629                                 map = kmap(page);
3630                                 read_extent_buffer(leaf, map + pg_offset, ptr,
3631                                                    copy_size);
3632                                 kunmap(page);
3633                         }
3634                         flush_dcache_page(page);
3635                 } else if (create && PageUptodate(page)) {
3636                         if (!trans) {
3637                                 kunmap(page);
3638                                 free_extent_map(em);
3639                                 em = NULL;
3640                                 btrfs_release_path(root, path);
3641                                 trans = btrfs_join_transaction(root, 1);
3642                                 goto again;
3643                         }
3644                         map = kmap(page);
3645                         write_extent_buffer(leaf, map + pg_offset, ptr,
3646                                             copy_size);
3647                         kunmap(page);
3648                         btrfs_mark_buffer_dirty(leaf);
3649                 }
3650                 set_extent_uptodate(io_tree, em->start,
3651                                     extent_map_end(em) - 1, GFP_NOFS);
3652                 goto insert;
3653         } else {
3654                 printk("unkknown found_type %d\n", found_type);
3655                 WARN_ON(1);
3656         }
3657 not_found:
3658         em->start = start;
3659         em->len = len;
3660 not_found_em:
3661         em->block_start = EXTENT_MAP_HOLE;
3662         set_bit(EXTENT_FLAG_VACANCY, &em->flags);
3663 insert:
3664         btrfs_release_path(root, path);
3665         if (em->start > start || extent_map_end(em) <= start) {
3666                 printk("bad extent! em: [%Lu %Lu] passed [%Lu %Lu]\n", em->start, em->len, start, len);
3667                 err = -EIO;
3668                 goto out;
3669         }
3670
3671         err = 0;
3672         spin_lock(&em_tree->lock);
3673         ret = add_extent_mapping(em_tree, em);
3674         /* it is possible that someone inserted the extent into the tree
3675          * while we had the lock dropped.  It is also possible that
3676          * an overlapping map exists in the tree
3677          */
3678         if (ret == -EEXIST) {
3679                 struct extent_map *existing;
3680
3681                 ret = 0;
3682
3683                 existing = lookup_extent_mapping(em_tree, start, len);
3684                 if (existing && (existing->start > start ||
3685                     existing->start + existing->len <= start)) {
3686                         free_extent_map(existing);
3687                         existing = NULL;
3688                 }
3689                 if (!existing) {
3690                         existing = lookup_extent_mapping(em_tree, em->start,
3691                                                          em->len);
3692                         if (existing) {
3693                                 err = merge_extent_mapping(em_tree, existing,
3694                                                            em, start,
3695                                                            root->sectorsize);
3696                                 free_extent_map(existing);
3697                                 if (err) {
3698                                         free_extent_map(em);
3699                                         em = NULL;
3700                                 }
3701                         } else {
3702                                 err = -EIO;
3703                                 printk("failing to insert %Lu %Lu\n",
3704                                        start, len);
3705                                 free_extent_map(em);
3706                                 em = NULL;
3707                         }
3708                 } else {
3709                         free_extent_map(em);
3710                         em = existing;
3711                         err = 0;
3712                 }
3713         }
3714         spin_unlock(&em_tree->lock);
3715 out:
3716         if (path)
3717                 btrfs_free_path(path);
3718         if (trans) {
3719                 ret = btrfs_end_transaction(trans, root);
3720                 if (!err) {
3721                         err = ret;
3722                 }
3723         }
3724         if (err) {
3725                 free_extent_map(em);
3726                 WARN_ON(1);
3727                 return ERR_PTR(err);
3728         }
3729         return em;
3730 }
3731
3732 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
3733                         const struct iovec *iov, loff_t offset,
3734                         unsigned long nr_segs)
3735 {
3736         return -EINVAL;
3737 }
3738
3739 static sector_t btrfs_bmap(struct address_space *mapping, sector_t iblock)
3740 {
3741         return extent_bmap(mapping, iblock, btrfs_get_extent);
3742 }
3743
3744 int btrfs_readpage(struct file *file, struct page *page)
3745 {
3746         struct extent_io_tree *tree;
3747         tree = &BTRFS_I(page->mapping->host)->io_tree;
3748         return extent_read_full_page(tree, page, btrfs_get_extent);
3749 }
3750
3751 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
3752 {
3753         struct extent_io_tree *tree;
3754
3755
3756         if (current->flags & PF_MEMALLOC) {
3757                 redirty_page_for_writepage(wbc, page);
3758                 unlock_page(page);
3759                 return 0;
3760         }
3761         tree = &BTRFS_I(page->mapping->host)->io_tree;
3762         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
3763 }
3764
3765 int btrfs_writepages(struct address_space *mapping,
3766                      struct writeback_control *wbc)
3767 {
3768         struct extent_io_tree *tree;
3769         tree = &BTRFS_I(mapping->host)->io_tree;
3770         return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
3771 }
3772
3773 static int
3774 btrfs_readpages(struct file *file, struct address_space *mapping,
3775                 struct list_head *pages, unsigned nr_pages)
3776 {
3777         struct extent_io_tree *tree;
3778         tree = &BTRFS_I(mapping->host)->io_tree;
3779         return extent_readpages(tree, mapping, pages, nr_pages,
3780                                 btrfs_get_extent);
3781 }
3782 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
3783 {
3784         struct extent_io_tree *tree;
3785         struct extent_map_tree *map;
3786         int ret;
3787
3788         tree = &BTRFS_I(page->mapping->host)->io_tree;
3789         map = &BTRFS_I(page->mapping->host)->extent_tree;
3790         ret = try_release_extent_mapping(map, tree, page, gfp_flags);
3791         if (ret == 1) {
3792                 ClearPagePrivate(page);
3793                 set_page_private(page, 0);
3794                 page_cache_release(page);
3795         }
3796         return ret;
3797 }
3798
3799 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
3800 {
3801         if (PageWriteback(page) || PageDirty(page))
3802                 return 0;
3803         return __btrfs_releasepage(page, gfp_flags);
3804 }
3805
3806 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
3807 {
3808         struct extent_io_tree *tree;
3809         struct btrfs_ordered_extent *ordered;
3810         u64 page_start = page_offset(page);
3811         u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
3812
3813         wait_on_page_writeback(page);
3814         tree = &BTRFS_I(page->mapping->host)->io_tree;
3815         if (offset) {
3816                 btrfs_releasepage(page, GFP_NOFS);
3817                 return;
3818         }
3819
3820         lock_extent(tree, page_start, page_end, GFP_NOFS);
3821         ordered = btrfs_lookup_ordered_extent(page->mapping->host,
3822                                            page_offset(page));
3823         if (ordered) {
3824                 /*
3825                  * IO on this page will never be started, so we need
3826                  * to account for any ordered extents now
3827                  */
3828                 clear_extent_bit(tree, page_start, page_end,
3829                                  EXTENT_DIRTY | EXTENT_DELALLOC |
3830                                  EXTENT_LOCKED, 1, 0, GFP_NOFS);
3831                 btrfs_finish_ordered_io(page->mapping->host,
3832                                         page_start, page_end);
3833                 btrfs_put_ordered_extent(ordered);
3834                 lock_extent(tree, page_start, page_end, GFP_NOFS);
3835         }
3836         clear_extent_bit(tree, page_start, page_end,
3837                  EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
3838                  EXTENT_ORDERED,
3839                  1, 1, GFP_NOFS);
3840         __btrfs_releasepage(page, GFP_NOFS);
3841
3842         ClearPageChecked(page);
3843         if (PagePrivate(page)) {
3844                 ClearPagePrivate(page);
3845                 set_page_private(page, 0);
3846                 page_cache_release(page);
3847         }
3848 }
3849
3850 /*
3851  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
3852  * called from a page fault handler when a page is first dirtied. Hence we must
3853  * be careful to check for EOF conditions here. We set the page up correctly
3854  * for a written page which means we get ENOSPC checking when writing into
3855  * holes and correct delalloc and unwritten extent mapping on filesystems that
3856  * support these features.
3857  *
3858  * We are not allowed to take the i_mutex here so we have to play games to
3859  * protect against truncate races as the page could now be beyond EOF.  Because
3860  * vmtruncate() writes the inode size before removing pages, once we have the
3861  * page lock we can determine safely if the page is beyond EOF. If it is not
3862  * beyond EOF, then the page is guaranteed safe against truncation until we
3863  * unlock the page.
3864  */
3865 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct page *page)
3866 {
3867         struct inode *inode = fdentry(vma->vm_file)->d_inode;
3868         struct btrfs_root *root = BTRFS_I(inode)->root;
3869         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3870         struct btrfs_ordered_extent *ordered;
3871         char *kaddr;
3872         unsigned long zero_start;
3873         loff_t size;
3874         int ret;
3875         u64 page_start;
3876         u64 page_end;
3877
3878         ret = btrfs_check_free_space(root, PAGE_CACHE_SIZE, 0);
3879         if (ret)
3880                 goto out;
3881
3882         ret = -EINVAL;
3883 again:
3884         lock_page(page);
3885         size = i_size_read(inode);
3886         page_start = page_offset(page);
3887         page_end = page_start + PAGE_CACHE_SIZE - 1;
3888
3889         if ((page->mapping != inode->i_mapping) ||
3890             (page_start >= size)) {
3891                 /* page got truncated out from underneath us */
3892                 goto out_unlock;
3893         }
3894         wait_on_page_writeback(page);
3895
3896         lock_extent(io_tree, page_start, page_end, GFP_NOFS);
3897         set_page_extent_mapped(page);
3898
3899         /*
3900          * we can't set the delalloc bits if there are pending ordered
3901          * extents.  Drop our locks and wait for them to finish
3902          */
3903         ordered = btrfs_lookup_ordered_extent(inode, page_start);
3904         if (ordered) {
3905                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
3906                 unlock_page(page);
3907                 btrfs_start_ordered_extent(inode, ordered, 1);
3908                 btrfs_put_ordered_extent(ordered);
3909                 goto again;
3910         }
3911
3912         btrfs_set_extent_delalloc(inode, page_start, page_end);
3913         ret = 0;
3914
3915         /* page is wholly or partially inside EOF */
3916         if (page_start + PAGE_CACHE_SIZE > size)
3917                 zero_start = size & ~PAGE_CACHE_MASK;
3918         else
3919                 zero_start = PAGE_CACHE_SIZE;
3920
3921         if (zero_start != PAGE_CACHE_SIZE) {
3922                 kaddr = kmap(page);
3923                 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
3924                 flush_dcache_page(page);
3925                 kunmap(page);
3926         }
3927         ClearPageChecked(page);
3928         set_page_dirty(page);
3929         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
3930
3931 out_unlock:
3932         unlock_page(page);
3933 out:
3934         return ret;
3935 }
3936
3937 static void btrfs_truncate(struct inode *inode)
3938 {
3939         struct btrfs_root *root = BTRFS_I(inode)->root;
3940         int ret;
3941         struct btrfs_trans_handle *trans;
3942         unsigned long nr;
3943         u64 mask = root->sectorsize - 1;
3944
3945         if (!S_ISREG(inode->i_mode))
3946                 return;
3947         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
3948                 return;
3949
3950         btrfs_truncate_page(inode->i_mapping, inode->i_size);
3951         btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
3952
3953         trans = btrfs_start_transaction(root, 1);
3954         btrfs_set_trans_block_group(trans, inode);
3955         btrfs_i_size_write(inode, inode->i_size);
3956
3957         ret = btrfs_orphan_add(trans, inode);
3958         if (ret)
3959                 goto out;
3960         /* FIXME, add redo link to tree so we don't leak on crash */
3961         ret = btrfs_truncate_inode_items(trans, root, inode, inode->i_size,
3962                                       BTRFS_EXTENT_DATA_KEY);
3963         btrfs_update_inode(trans, root, inode);
3964
3965         ret = btrfs_orphan_del(trans, inode);
3966         BUG_ON(ret);
3967
3968 out:
3969         nr = trans->blocks_used;
3970         ret = btrfs_end_transaction_throttle(trans, root);
3971         BUG_ON(ret);
3972         btrfs_btree_balance_dirty(root, nr);
3973 }
3974
3975 /*
3976  * Invalidate a single dcache entry at the root of the filesystem.
3977  * Needed after creation of snapshot or subvolume.
3978  */
3979 void btrfs_invalidate_dcache_root(struct btrfs_root *root, char *name,
3980                                   int namelen)
3981 {
3982         struct dentry *alias, *entry;
3983         struct qstr qstr;
3984
3985         alias = d_find_alias(root->fs_info->sb->s_root->d_inode);
3986         if (alias) {
3987                 qstr.name = name;
3988                 qstr.len = namelen;
3989                 /* change me if btrfs ever gets a d_hash operation */
3990                 qstr.hash = full_name_hash(qstr.name, qstr.len);
3991                 entry = d_lookup(alias, &qstr);
3992                 dput(alias);
3993                 if (entry) {
3994                         d_invalidate(entry);
3995                         dput(entry);
3996                 }
3997         }
3998 }
3999
4000 /*
4001  * create a new subvolume directory/inode (helper for the ioctl).
4002  */
4003 int btrfs_create_subvol_root(struct btrfs_root *new_root, struct dentry *dentry,
4004                 struct btrfs_trans_handle *trans, u64 new_dirid,
4005                 struct btrfs_block_group_cache *block_group)
4006 {
4007         struct inode *inode;
4008         int error;
4009         u64 index = 0;
4010
4011         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
4012                                 new_dirid, block_group, S_IFDIR | 0700, &index);
4013         if (IS_ERR(inode))
4014                 return PTR_ERR(inode);
4015         inode->i_op = &btrfs_dir_inode_operations;
4016         inode->i_fop = &btrfs_dir_file_operations;
4017         new_root->inode = inode;
4018
4019         inode->i_nlink = 1;
4020         btrfs_i_size_write(inode, 0);
4021
4022         error = btrfs_update_inode(trans, new_root, inode);
4023         if (error)
4024                 return error;
4025
4026         atomic_inc(&inode->i_count);
4027         d_instantiate(dentry, inode);
4028         return 0;
4029 }
4030
4031 /* helper function for file defrag and space balancing.  This
4032  * forces readahead on a given range of bytes in an inode
4033  */
4034 unsigned long btrfs_force_ra(struct address_space *mapping,
4035                               struct file_ra_state *ra, struct file *file,
4036                               pgoff_t offset, pgoff_t last_index)
4037 {
4038         pgoff_t req_size = last_index - offset + 1;
4039
4040         page_cache_sync_readahead(mapping, ra, file, offset, req_size);
4041         return offset + req_size;
4042 }
4043
4044 struct inode *btrfs_alloc_inode(struct super_block *sb)
4045 {
4046         struct btrfs_inode *ei;
4047
4048         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
4049         if (!ei)
4050                 return NULL;
4051         ei->last_trans = 0;
4052         ei->logged_trans = 0;
4053         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
4054         ei->i_acl = BTRFS_ACL_NOT_CACHED;
4055         ei->i_default_acl = BTRFS_ACL_NOT_CACHED;
4056         INIT_LIST_HEAD(&ei->i_orphan);
4057         return &ei->vfs_inode;
4058 }
4059
4060 void btrfs_destroy_inode(struct inode *inode)
4061 {
4062         struct btrfs_ordered_extent *ordered;
4063         WARN_ON(!list_empty(&inode->i_dentry));
4064         WARN_ON(inode->i_data.nrpages);
4065
4066         if (BTRFS_I(inode)->i_acl &&
4067             BTRFS_I(inode)->i_acl != BTRFS_ACL_NOT_CACHED)
4068                 posix_acl_release(BTRFS_I(inode)->i_acl);
4069         if (BTRFS_I(inode)->i_default_acl &&
4070             BTRFS_I(inode)->i_default_acl != BTRFS_ACL_NOT_CACHED)
4071                 posix_acl_release(BTRFS_I(inode)->i_default_acl);
4072
4073         spin_lock(&BTRFS_I(inode)->root->list_lock);
4074         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
4075                 printk(KERN_ERR "BTRFS: inode %lu: inode still on the orphan"
4076                        " list\n", inode->i_ino);
4077                 dump_stack();
4078         }
4079         spin_unlock(&BTRFS_I(inode)->root->list_lock);
4080
4081         while(1) {
4082                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
4083                 if (!ordered)
4084                         break;
4085                 else {
4086                         printk("found ordered extent %Lu %Lu\n",
4087                                ordered->file_offset, ordered->len);
4088                         btrfs_remove_ordered_extent(inode, ordered);
4089                         btrfs_put_ordered_extent(ordered);
4090                         btrfs_put_ordered_extent(ordered);
4091                 }
4092         }
4093         btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
4094         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
4095 }
4096
4097 static void init_once(void *foo)
4098 {
4099         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
4100
4101         inode_init_once(&ei->vfs_inode);
4102 }
4103
4104 void btrfs_destroy_cachep(void)
4105 {
4106         if (btrfs_inode_cachep)
4107                 kmem_cache_destroy(btrfs_inode_cachep);
4108         if (btrfs_trans_handle_cachep)
4109                 kmem_cache_destroy(btrfs_trans_handle_cachep);
4110         if (btrfs_transaction_cachep)
4111                 kmem_cache_destroy(btrfs_transaction_cachep);
4112         if (btrfs_bit_radix_cachep)
4113                 kmem_cache_destroy(btrfs_bit_radix_cachep);
4114         if (btrfs_path_cachep)
4115                 kmem_cache_destroy(btrfs_path_cachep);
4116 }
4117
4118 struct kmem_cache *btrfs_cache_create(const char *name, size_t size,
4119                                        unsigned long extra_flags,
4120                                        void (*ctor)(void *))
4121 {
4122         return kmem_cache_create(name, size, 0, (SLAB_RECLAIM_ACCOUNT |
4123                                  SLAB_MEM_SPREAD | extra_flags), ctor);
4124 }
4125
4126 int btrfs_init_cachep(void)
4127 {
4128         btrfs_inode_cachep = btrfs_cache_create("btrfs_inode_cache",
4129                                           sizeof(struct btrfs_inode),
4130                                           0, init_once);
4131         if (!btrfs_inode_cachep)
4132                 goto fail;
4133         btrfs_trans_handle_cachep =
4134                         btrfs_cache_create("btrfs_trans_handle_cache",
4135                                            sizeof(struct btrfs_trans_handle),
4136                                            0, NULL);
4137         if (!btrfs_trans_handle_cachep)
4138                 goto fail;
4139         btrfs_transaction_cachep = btrfs_cache_create("btrfs_transaction_cache",
4140                                              sizeof(struct btrfs_transaction),
4141                                              0, NULL);
4142         if (!btrfs_transaction_cachep)
4143                 goto fail;
4144         btrfs_path_cachep = btrfs_cache_create("btrfs_path_cache",
4145                                          sizeof(struct btrfs_path),
4146                                          0, NULL);
4147         if (!btrfs_path_cachep)
4148                 goto fail;
4149         btrfs_bit_radix_cachep = btrfs_cache_create("btrfs_radix", 256,
4150                                               SLAB_DESTROY_BY_RCU, NULL);
4151         if (!btrfs_bit_radix_cachep)
4152                 goto fail;
4153         return 0;
4154 fail:
4155         btrfs_destroy_cachep();
4156         return -ENOMEM;
4157 }
4158
4159 static int btrfs_getattr(struct vfsmount *mnt,
4160                          struct dentry *dentry, struct kstat *stat)
4161 {
4162         struct inode *inode = dentry->d_inode;
4163         generic_fillattr(inode, stat);
4164         stat->blksize = PAGE_CACHE_SIZE;
4165         stat->blocks = (inode_get_bytes(inode) +
4166                         BTRFS_I(inode)->delalloc_bytes) >> 9;
4167         return 0;
4168 }
4169
4170 static int btrfs_rename(struct inode * old_dir, struct dentry *old_dentry,
4171                            struct inode * new_dir,struct dentry *new_dentry)
4172 {
4173         struct btrfs_trans_handle *trans;
4174         struct btrfs_root *root = BTRFS_I(old_dir)->root;
4175         struct inode *new_inode = new_dentry->d_inode;
4176         struct inode *old_inode = old_dentry->d_inode;
4177         struct timespec ctime = CURRENT_TIME;
4178         u64 index = 0;
4179         int ret;
4180
4181         if (S_ISDIR(old_inode->i_mode) && new_inode &&
4182             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) {
4183                 return -ENOTEMPTY;
4184         }
4185
4186         ret = btrfs_check_free_space(root, 1, 0);
4187         if (ret)
4188                 goto out_unlock;
4189
4190         trans = btrfs_start_transaction(root, 1);
4191
4192         btrfs_set_trans_block_group(trans, new_dir);
4193
4194         btrfs_inc_nlink(old_dentry->d_inode);
4195         old_dir->i_ctime = old_dir->i_mtime = ctime;
4196         new_dir->i_ctime = new_dir->i_mtime = ctime;
4197         old_inode->i_ctime = ctime;
4198
4199         ret = btrfs_unlink_inode(trans, root, old_dir, old_dentry->d_inode,
4200                                  old_dentry->d_name.name,
4201                                  old_dentry->d_name.len);
4202         if (ret)
4203                 goto out_fail;
4204
4205         if (new_inode) {
4206                 new_inode->i_ctime = CURRENT_TIME;
4207                 ret = btrfs_unlink_inode(trans, root, new_dir,
4208                                          new_dentry->d_inode,
4209                                          new_dentry->d_name.name,
4210                                          new_dentry->d_name.len);
4211                 if (ret)
4212                         goto out_fail;
4213                 if (new_inode->i_nlink == 0) {
4214                         ret = btrfs_orphan_add(trans, new_dentry->d_inode);
4215                         if (ret)
4216                                 goto out_fail;
4217                 }
4218
4219         }
4220         ret = btrfs_set_inode_index(new_dir, old_inode, &index);
4221         if (ret)
4222                 goto out_fail;
4223
4224         ret = btrfs_add_link(trans, new_dentry->d_parent->d_inode,
4225                              old_inode, new_dentry->d_name.name,
4226                              new_dentry->d_name.len, 1, index);
4227         if (ret)
4228                 goto out_fail;
4229
4230 out_fail:
4231         btrfs_end_transaction_throttle(trans, root);
4232 out_unlock:
4233         return ret;
4234 }
4235
4236 /*
4237  * some fairly slow code that needs optimization. This walks the list
4238  * of all the inodes with pending delalloc and forces them to disk.
4239  */
4240 int btrfs_start_delalloc_inodes(struct btrfs_root *root)
4241 {
4242         struct list_head *head = &root->fs_info->delalloc_inodes;
4243         struct btrfs_inode *binode;
4244         struct inode *inode;
4245         unsigned long flags;
4246
4247         spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
4248         while(!list_empty(head)) {
4249                 binode = list_entry(head->next, struct btrfs_inode,
4250                                     delalloc_inodes);
4251                 inode = igrab(&binode->vfs_inode);
4252                 if (!inode)
4253                         list_del_init(&binode->delalloc_inodes);
4254                 spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
4255                 if (inode) {
4256                         filemap_flush(inode->i_mapping);
4257                         iput(inode);
4258                 }
4259                 cond_resched();
4260                 spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
4261         }
4262         spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
4263
4264         /* the filemap_flush will queue IO into the worker threads, but
4265          * we have to make sure the IO is actually started and that
4266          * ordered extents get created before we return
4267          */
4268         atomic_inc(&root->fs_info->async_submit_draining);
4269         while(atomic_read(&root->fs_info->nr_async_submits)) {
4270                 wait_event(root->fs_info->async_submit_wait,
4271                    (atomic_read(&root->fs_info->nr_async_submits) == 0));
4272         }
4273         atomic_dec(&root->fs_info->async_submit_draining);
4274         return 0;
4275 }
4276
4277 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
4278                          const char *symname)
4279 {
4280         struct btrfs_trans_handle *trans;
4281         struct btrfs_root *root = BTRFS_I(dir)->root;
4282         struct btrfs_path *path;
4283         struct btrfs_key key;
4284         struct inode *inode = NULL;
4285         int err;
4286         int drop_inode = 0;
4287         u64 objectid;
4288         u64 index = 0 ;
4289         int name_len;
4290         int datasize;
4291         unsigned long ptr;
4292         struct btrfs_file_extent_item *ei;
4293         struct extent_buffer *leaf;
4294         unsigned long nr = 0;
4295
4296         name_len = strlen(symname) + 1;
4297         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
4298                 return -ENAMETOOLONG;
4299
4300         err = btrfs_check_free_space(root, 1, 0);
4301         if (err)
4302                 goto out_fail;
4303
4304         trans = btrfs_start_transaction(root, 1);
4305         btrfs_set_trans_block_group(trans, dir);
4306
4307         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
4308         if (err) {
4309                 err = -ENOSPC;
4310                 goto out_unlock;
4311         }
4312
4313         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4314                                 dentry->d_name.len,
4315                                 dentry->d_parent->d_inode->i_ino, objectid,
4316                                 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO,
4317                                 &index);
4318         err = PTR_ERR(inode);
4319         if (IS_ERR(inode))
4320                 goto out_unlock;
4321
4322         err = btrfs_init_acl(inode, dir);
4323         if (err) {
4324                 drop_inode = 1;
4325                 goto out_unlock;
4326         }
4327
4328         btrfs_set_trans_block_group(trans, inode);
4329         err = btrfs_add_nondir(trans, dentry, inode, 0, index);
4330         if (err)
4331                 drop_inode = 1;
4332         else {
4333                 inode->i_mapping->a_ops = &btrfs_aops;
4334                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4335                 inode->i_fop = &btrfs_file_operations;
4336                 inode->i_op = &btrfs_file_inode_operations;
4337                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4338         }
4339         dir->i_sb->s_dirt = 1;
4340         btrfs_update_inode_block_group(trans, inode);
4341         btrfs_update_inode_block_group(trans, dir);
4342         if (drop_inode)
4343                 goto out_unlock;
4344
4345         path = btrfs_alloc_path();
4346         BUG_ON(!path);
4347         key.objectid = inode->i_ino;
4348         key.offset = 0;
4349         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
4350         datasize = btrfs_file_extent_calc_inline_size(name_len);
4351         err = btrfs_insert_empty_item(trans, root, path, &key,
4352                                       datasize);
4353         if (err) {
4354                 drop_inode = 1;
4355                 goto out_unlock;
4356         }
4357         leaf = path->nodes[0];
4358         ei = btrfs_item_ptr(leaf, path->slots[0],
4359                             struct btrfs_file_extent_item);
4360         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
4361         btrfs_set_file_extent_type(leaf, ei,
4362                                    BTRFS_FILE_EXTENT_INLINE);
4363         btrfs_set_file_extent_encryption(leaf, ei, 0);
4364         btrfs_set_file_extent_compression(leaf, ei, 0);
4365         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
4366         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
4367
4368         ptr = btrfs_file_extent_inline_start(ei);
4369         write_extent_buffer(leaf, symname, ptr, name_len);
4370         btrfs_mark_buffer_dirty(leaf);
4371         btrfs_free_path(path);
4372
4373         inode->i_op = &btrfs_symlink_inode_operations;
4374         inode->i_mapping->a_ops = &btrfs_symlink_aops;
4375         inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4376         inode_set_bytes(inode, name_len);
4377         btrfs_i_size_write(inode, name_len - 1);
4378         err = btrfs_update_inode(trans, root, inode);
4379         if (err)
4380                 drop_inode = 1;
4381
4382 out_unlock:
4383         nr = trans->blocks_used;
4384         btrfs_end_transaction_throttle(trans, root);
4385 out_fail:
4386         if (drop_inode) {
4387                 inode_dec_link_count(inode);
4388                 iput(inode);
4389         }
4390         btrfs_btree_balance_dirty(root, nr);
4391         return err;
4392 }
4393
4394 static int prealloc_file_range(struct inode *inode, u64 start, u64 end,
4395                                u64 alloc_hint, int mode)
4396 {
4397         struct btrfs_trans_handle *trans;
4398         struct btrfs_root *root = BTRFS_I(inode)->root;
4399         struct btrfs_key ins;
4400         u64 alloc_size;
4401         u64 cur_offset = start;
4402         u64 num_bytes = end - start;
4403         int ret = 0;
4404
4405         trans = btrfs_join_transaction(root, 1);
4406         BUG_ON(!trans);
4407         btrfs_set_trans_block_group(trans, inode);
4408
4409         while (num_bytes > 0) {
4410                 alloc_size = min(num_bytes, root->fs_info->max_extent);
4411                 ret = btrfs_reserve_extent(trans, root, alloc_size,
4412                                            root->sectorsize, 0, alloc_hint,
4413                                            (u64)-1, &ins, 1);
4414                 if (ret) {
4415                         WARN_ON(1);
4416                         goto out;
4417                 }
4418                 ret = insert_reserved_file_extent(trans, inode,
4419                                                   cur_offset, ins.objectid,
4420                                                   ins.offset, ins.offset,
4421                                                   ins.offset, 0, 0, 0,
4422                                                   BTRFS_FILE_EXTENT_PREALLOC);
4423                 BUG_ON(ret);
4424                 num_bytes -= ins.offset;
4425                 cur_offset += ins.offset;
4426                 alloc_hint = ins.objectid + ins.offset;
4427         }
4428 out:
4429         if (cur_offset > start) {
4430                 inode->i_ctime = CURRENT_TIME;
4431                 btrfs_set_flag(inode, PREALLOC);
4432                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4433                     cur_offset > i_size_read(inode))
4434                         btrfs_i_size_write(inode, cur_offset);
4435                 ret = btrfs_update_inode(trans, root, inode);
4436                 BUG_ON(ret);
4437         }
4438
4439         btrfs_end_transaction(trans, root);
4440         return ret;
4441 }
4442
4443 static long btrfs_fallocate(struct inode *inode, int mode,
4444                             loff_t offset, loff_t len)
4445 {
4446         u64 cur_offset;
4447         u64 last_byte;
4448         u64 alloc_start;
4449         u64 alloc_end;
4450         u64 alloc_hint = 0;
4451         u64 mask = BTRFS_I(inode)->root->sectorsize - 1;
4452         struct extent_map *em;
4453         int ret;
4454
4455         alloc_start = offset & ~mask;
4456         alloc_end =  (offset + len + mask) & ~mask;
4457
4458         mutex_lock(&inode->i_mutex);
4459         if (alloc_start > inode->i_size) {
4460                 ret = btrfs_cont_expand(inode, alloc_start);
4461                 if (ret)
4462                         goto out;
4463         }
4464
4465         while (1) {
4466                 struct btrfs_ordered_extent *ordered;
4467                 lock_extent(&BTRFS_I(inode)->io_tree, alloc_start,
4468                             alloc_end - 1, GFP_NOFS);
4469                 ordered = btrfs_lookup_first_ordered_extent(inode,
4470                                                             alloc_end - 1);
4471                 if (ordered &&
4472                     ordered->file_offset + ordered->len > alloc_start &&
4473                     ordered->file_offset < alloc_end) {
4474                         btrfs_put_ordered_extent(ordered);
4475                         unlock_extent(&BTRFS_I(inode)->io_tree,
4476                                       alloc_start, alloc_end - 1, GFP_NOFS);
4477                         btrfs_wait_ordered_range(inode, alloc_start,
4478                                                  alloc_end - alloc_start);
4479                 } else {
4480                         if (ordered)
4481                                 btrfs_put_ordered_extent(ordered);
4482                         break;
4483                 }
4484         }
4485
4486         cur_offset = alloc_start;
4487         while (1) {
4488                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4489                                       alloc_end - cur_offset, 0);
4490                 BUG_ON(IS_ERR(em) || !em);
4491                 last_byte = min(extent_map_end(em), alloc_end);
4492                 last_byte = (last_byte + mask) & ~mask;
4493                 if (em->block_start == EXTENT_MAP_HOLE) {
4494                         ret = prealloc_file_range(inode, cur_offset,
4495                                         last_byte, alloc_hint, mode);
4496                         if (ret < 0) {
4497                                 free_extent_map(em);
4498                                 break;
4499                         }
4500                 }
4501                 if (em->block_start <= EXTENT_MAP_LAST_BYTE)
4502                         alloc_hint = em->block_start;
4503                 free_extent_map(em);
4504
4505                 cur_offset = last_byte;
4506                 if (cur_offset >= alloc_end) {
4507                         ret = 0;
4508                         break;
4509                 }
4510         }
4511         unlock_extent(&BTRFS_I(inode)->io_tree, alloc_start, alloc_end - 1,
4512                       GFP_NOFS);
4513 out:
4514         mutex_unlock(&inode->i_mutex);
4515         return ret;
4516 }
4517
4518 static int btrfs_set_page_dirty(struct page *page)
4519 {
4520         return __set_page_dirty_nobuffers(page);
4521 }
4522
4523 static int btrfs_permission(struct inode *inode, int mask)
4524 {
4525         if (btrfs_test_flag(inode, READONLY) && (mask & MAY_WRITE))
4526                 return -EACCES;
4527         return generic_permission(inode, mask, btrfs_check_acl);
4528 }
4529
4530 static struct inode_operations btrfs_dir_inode_operations = {
4531         .lookup         = btrfs_lookup,
4532         .create         = btrfs_create,
4533         .unlink         = btrfs_unlink,
4534         .link           = btrfs_link,
4535         .mkdir          = btrfs_mkdir,
4536         .rmdir          = btrfs_rmdir,
4537         .rename         = btrfs_rename,
4538         .symlink        = btrfs_symlink,
4539         .setattr        = btrfs_setattr,
4540         .mknod          = btrfs_mknod,
4541         .setxattr       = btrfs_setxattr,
4542         .getxattr       = btrfs_getxattr,
4543         .listxattr      = btrfs_listxattr,
4544         .removexattr    = btrfs_removexattr,
4545         .permission     = btrfs_permission,
4546 };
4547 static struct inode_operations btrfs_dir_ro_inode_operations = {
4548         .lookup         = btrfs_lookup,
4549         .permission     = btrfs_permission,
4550 };
4551 static struct file_operations btrfs_dir_file_operations = {
4552         .llseek         = generic_file_llseek,
4553         .read           = generic_read_dir,
4554         .readdir        = btrfs_real_readdir,
4555         .unlocked_ioctl = btrfs_ioctl,
4556 #ifdef CONFIG_COMPAT
4557         .compat_ioctl   = btrfs_ioctl,
4558 #endif
4559         .release        = btrfs_release_file,
4560         .fsync          = btrfs_sync_file,
4561 };
4562
4563 static struct extent_io_ops btrfs_extent_io_ops = {
4564         .fill_delalloc = run_delalloc_range,
4565         .submit_bio_hook = btrfs_submit_bio_hook,
4566         .merge_bio_hook = btrfs_merge_bio_hook,
4567         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
4568         .writepage_end_io_hook = btrfs_writepage_end_io_hook,
4569         .writepage_start_hook = btrfs_writepage_start_hook,
4570         .readpage_io_failed_hook = btrfs_io_failed_hook,
4571         .set_bit_hook = btrfs_set_bit_hook,
4572         .clear_bit_hook = btrfs_clear_bit_hook,
4573 };
4574
4575 static struct address_space_operations btrfs_aops = {
4576         .readpage       = btrfs_readpage,
4577         .writepage      = btrfs_writepage,
4578         .writepages     = btrfs_writepages,
4579         .readpages      = btrfs_readpages,
4580         .sync_page      = block_sync_page,
4581         .bmap           = btrfs_bmap,
4582         .direct_IO      = btrfs_direct_IO,
4583         .invalidatepage = btrfs_invalidatepage,
4584         .releasepage    = btrfs_releasepage,
4585         .set_page_dirty = btrfs_set_page_dirty,
4586 };
4587
4588 static struct address_space_operations btrfs_symlink_aops = {
4589         .readpage       = btrfs_readpage,
4590         .writepage      = btrfs_writepage,
4591         .invalidatepage = btrfs_invalidatepage,
4592         .releasepage    = btrfs_releasepage,
4593 };
4594
4595 static struct inode_operations btrfs_file_inode_operations = {
4596         .truncate       = btrfs_truncate,
4597         .getattr        = btrfs_getattr,
4598         .setattr        = btrfs_setattr,
4599         .setxattr       = btrfs_setxattr,
4600         .getxattr       = btrfs_getxattr,
4601         .listxattr      = btrfs_listxattr,
4602         .removexattr    = btrfs_removexattr,
4603         .permission     = btrfs_permission,
4604         .fallocate      = btrfs_fallocate,
4605 };
4606 static struct inode_operations btrfs_special_inode_operations = {
4607         .getattr        = btrfs_getattr,
4608         .setattr        = btrfs_setattr,
4609         .permission     = btrfs_permission,
4610         .setxattr       = btrfs_setxattr,
4611         .getxattr       = btrfs_getxattr,
4612         .listxattr      = btrfs_listxattr,
4613         .removexattr    = btrfs_removexattr,
4614 };
4615 static struct inode_operations btrfs_symlink_inode_operations = {
4616         .readlink       = generic_readlink,
4617         .follow_link    = page_follow_link_light,
4618         .put_link       = page_put_link,
4619         .permission     = btrfs_permission,
4620 };