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