Btrfs: Update nodatacow mode to support cloned single files and resizing
[linux-2.6-block.git] / fs / btrfs / inode.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/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 "ctree.h"
40 #include "disk-io.h"
41 #include "transaction.h"
42 #include "btrfs_inode.h"
43 #include "ioctl.h"
44 #include "print-tree.h"
45 #include "volumes.h"
46
47 struct btrfs_iget_args {
48         u64 ino;
49         struct btrfs_root *root;
50 };
51
52 static struct inode_operations btrfs_dir_inode_operations;
53 static struct inode_operations btrfs_symlink_inode_operations;
54 static struct inode_operations btrfs_dir_ro_inode_operations;
55 static struct inode_operations btrfs_special_inode_operations;
56 static struct inode_operations btrfs_file_inode_operations;
57 static struct address_space_operations btrfs_aops;
58 static struct address_space_operations btrfs_symlink_aops;
59 static struct file_operations btrfs_dir_file_operations;
60 static struct extent_io_ops btrfs_extent_io_ops;
61
62 static struct kmem_cache *btrfs_inode_cachep;
63 struct kmem_cache *btrfs_trans_handle_cachep;
64 struct kmem_cache *btrfs_transaction_cachep;
65 struct kmem_cache *btrfs_bit_radix_cachep;
66 struct kmem_cache *btrfs_path_cachep;
67
68 #define S_SHIFT 12
69 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
70         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
71         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
72         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
73         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
74         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
75         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
76         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
77 };
78
79 int btrfs_check_free_space(struct btrfs_root *root, u64 num_required,
80                            int for_del)
81 {
82         u64 total = btrfs_super_total_bytes(&root->fs_info->super_copy);
83         u64 used = btrfs_super_bytes_used(&root->fs_info->super_copy);
84         u64 thresh;
85         unsigned long flags;
86         int ret = 0;
87
88         if (for_del)
89                 thresh = total * 90;
90         else
91                 thresh = total * 85;
92
93         do_div(thresh, 100);
94
95         spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
96         if (used + root->fs_info->delalloc_bytes + num_required > thresh)
97                 ret = -ENOSPC;
98         spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
99         return ret;
100 }
101
102 static int cow_file_range(struct inode *inode, u64 start, u64 end)
103 {
104         struct btrfs_root *root = BTRFS_I(inode)->root;
105         struct btrfs_trans_handle *trans;
106         u64 alloc_hint = 0;
107         u64 num_bytes;
108         u64 cur_alloc_size;
109         u64 blocksize = root->sectorsize;
110         u64 orig_start = start;
111         u64 orig_num_bytes;
112         struct btrfs_key ins;
113         int ret;
114
115         trans = btrfs_start_transaction(root, 1);
116         BUG_ON(!trans);
117         btrfs_set_trans_block_group(trans, inode);
118
119         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
120         num_bytes = max(blocksize,  num_bytes);
121         ret = btrfs_drop_extents(trans, root, inode,
122                                  start, start + num_bytes, start, &alloc_hint);
123         orig_num_bytes = num_bytes;
124
125         if (alloc_hint == EXTENT_MAP_INLINE)
126                 goto out;
127
128         BUG_ON(num_bytes > btrfs_super_total_bytes(&root->fs_info->super_copy));
129
130         while(num_bytes > 0) {
131                 cur_alloc_size = min(num_bytes, root->fs_info->max_extent);
132                 ret = btrfs_alloc_extent(trans, root, cur_alloc_size,
133                                          root->sectorsize,
134                                          root->root_key.objectid,
135                                          trans->transid,
136                                          inode->i_ino, start, 0,
137                                          alloc_hint, (u64)-1, &ins, 1);
138                 if (ret) {
139                         WARN_ON(1);
140                         goto out;
141                 }
142                 cur_alloc_size = ins.offset;
143                 ret = btrfs_insert_file_extent(trans, root, inode->i_ino,
144                                                start, ins.objectid, ins.offset,
145                                                ins.offset, 0);
146                 inode->i_blocks += ins.offset >> 9;
147                 btrfs_check_file(root, inode);
148                 if (num_bytes < cur_alloc_size) {
149                         printk("num_bytes %Lu cur_alloc %Lu\n", num_bytes,
150                                cur_alloc_size);
151                         break;
152                 }
153                 num_bytes -= cur_alloc_size;
154                 alloc_hint = ins.objectid + ins.offset;
155                 start += cur_alloc_size;
156         }
157         btrfs_drop_extent_cache(inode, orig_start,
158                                 orig_start + orig_num_bytes - 1);
159         btrfs_add_ordered_inode(inode);
160         btrfs_update_inode(trans, root, inode);
161 out:
162         btrfs_end_transaction(trans, root);
163         return ret;
164 }
165
166 static int run_delalloc_nocow(struct inode *inode, u64 start, u64 end)
167 {
168         u64 extent_start;
169         u64 extent_end;
170         u64 bytenr;
171         u64 cow_end;
172         u64 loops = 0;
173         u64 total_fs_bytes;
174         struct btrfs_root *root = BTRFS_I(inode)->root;
175         struct btrfs_block_group_cache *block_group;
176         struct extent_buffer *leaf;
177         int found_type;
178         struct btrfs_path *path;
179         struct btrfs_file_extent_item *item;
180         int ret;
181         int err;
182         struct btrfs_key found_key;
183
184         total_fs_bytes = btrfs_super_total_bytes(&root->fs_info->super_copy);
185         path = btrfs_alloc_path();
186         BUG_ON(!path);
187 again:
188         ret = btrfs_lookup_file_extent(NULL, root, path,
189                                        inode->i_ino, start, 0);
190         if (ret < 0) {
191                 btrfs_free_path(path);
192                 return ret;
193         }
194
195         cow_end = end;
196         if (ret != 0) {
197                 if (path->slots[0] == 0)
198                         goto not_found;
199                 path->slots[0]--;
200         }
201
202         leaf = path->nodes[0];
203         item = btrfs_item_ptr(leaf, path->slots[0],
204                               struct btrfs_file_extent_item);
205
206         /* are we inside the extent that was found? */
207         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
208         found_type = btrfs_key_type(&found_key);
209         if (found_key.objectid != inode->i_ino ||
210             found_type != BTRFS_EXTENT_DATA_KEY) {
211                 goto not_found;
212         }
213
214         found_type = btrfs_file_extent_type(leaf, item);
215         extent_start = found_key.offset;
216         if (found_type == BTRFS_FILE_EXTENT_REG) {
217                 u64 extent_num_bytes;
218
219                 extent_num_bytes = btrfs_file_extent_num_bytes(leaf, item);
220                 extent_end = extent_start + extent_num_bytes;
221                 err = 0;
222
223                 if (loops && start != extent_start)
224                         goto not_found;
225
226                 if (start < extent_start || start >= extent_end)
227                         goto not_found;
228
229                 cow_end = min(end, extent_end - 1);
230                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
231                 if (bytenr == 0)
232                         goto not_found;
233
234                 if (btrfs_count_snapshots_in_path(root, path, inode->i_ino,
235                                                   bytenr) != 1) {
236                         goto not_found;
237                 }
238
239                 /*
240                  * we may be called by the resizer, make sure we're inside
241                  * the limits of the FS
242                  */
243                 block_group = btrfs_lookup_block_group(root->fs_info,
244                                                        bytenr);
245                 if (!block_group || block_group->ro)
246                         goto not_found;
247
248
249                 start = extent_end;
250         } else {
251                 goto not_found;
252         }
253 loop:
254         if (start > end) {
255                 btrfs_free_path(path);
256                 return 0;
257         }
258         btrfs_release_path(root, path);
259         loops++;
260         goto again;
261
262 not_found:
263         cow_file_range(inode, start, cow_end);
264         start = cow_end + 1;
265         goto loop;
266 }
267
268 static int run_delalloc_range(struct inode *inode, u64 start, u64 end)
269 {
270         struct btrfs_root *root = BTRFS_I(inode)->root;
271         int ret;
272         mutex_lock(&root->fs_info->fs_mutex);
273         if (btrfs_test_opt(root, NODATACOW) ||
274             btrfs_test_flag(inode, NODATACOW))
275                 ret = run_delalloc_nocow(inode, start, end);
276         else
277                 ret = cow_file_range(inode, start, end);
278
279         mutex_unlock(&root->fs_info->fs_mutex);
280         return ret;
281 }
282
283 int btrfs_set_bit_hook(struct inode *inode, u64 start, u64 end,
284                        unsigned long old, unsigned long bits)
285 {
286         unsigned long flags;
287         if (!(old & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
288                 struct btrfs_root *root = BTRFS_I(inode)->root;
289                 spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
290                 BTRFS_I(inode)->delalloc_bytes += end - start + 1;
291                 root->fs_info->delalloc_bytes += end - start + 1;
292                 spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
293         }
294         return 0;
295 }
296
297 int btrfs_clear_bit_hook(struct inode *inode, u64 start, u64 end,
298                          unsigned long old, unsigned long bits)
299 {
300         if ((old & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
301                 struct btrfs_root *root = BTRFS_I(inode)->root;
302                 unsigned long flags;
303
304                 spin_lock_irqsave(&root->fs_info->delalloc_lock, flags);
305                 if (end - start + 1 > root->fs_info->delalloc_bytes) {
306                         printk("warning: delalloc account %Lu %Lu\n",
307                                end - start + 1, root->fs_info->delalloc_bytes);
308                         root->fs_info->delalloc_bytes = 0;
309                         BTRFS_I(inode)->delalloc_bytes = 0;
310                 } else {
311                         root->fs_info->delalloc_bytes -= end - start + 1;
312                         BTRFS_I(inode)->delalloc_bytes -= end - start + 1;
313                 }
314                 spin_unlock_irqrestore(&root->fs_info->delalloc_lock, flags);
315         }
316         return 0;
317 }
318
319 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
320                          size_t size, struct bio *bio)
321 {
322         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
323         struct btrfs_mapping_tree *map_tree;
324         u64 logical = bio->bi_sector << 9;
325         u64 length = 0;
326         u64 map_length;
327         int ret;
328
329         length = bio->bi_size;
330         map_tree = &root->fs_info->mapping_tree;
331         map_length = length;
332         ret = btrfs_map_block(map_tree, READ, logical,
333                               &map_length, NULL, 0);
334
335         if (map_length < length + size) {
336                 return 1;
337         }
338         return 0;
339 }
340
341 int __btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
342                           int mirror_num)
343 {
344         struct btrfs_root *root = BTRFS_I(inode)->root;
345         struct btrfs_trans_handle *trans;
346         int ret = 0;
347         char *sums = NULL;
348
349         ret = btrfs_csum_one_bio(root, bio, &sums);
350         BUG_ON(ret);
351
352         mutex_lock(&root->fs_info->fs_mutex);
353         trans = btrfs_start_transaction(root, 1);
354
355         btrfs_set_trans_block_group(trans, inode);
356         btrfs_csum_file_blocks(trans, root, inode, bio, sums);
357
358         ret = btrfs_end_transaction(trans, root);
359         BUG_ON(ret);
360         mutex_unlock(&root->fs_info->fs_mutex);
361
362         kfree(sums);
363
364         return btrfs_map_bio(root, rw, bio, mirror_num);
365 }
366
367 int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
368                           int mirror_num)
369 {
370         struct btrfs_root *root = BTRFS_I(inode)->root;
371         int ret = 0;
372
373         if (!(rw & (1 << BIO_RW))) {
374                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
375                 BUG_ON(ret);
376                 goto mapit;
377         }
378
379         if (btrfs_test_opt(root, NODATASUM) ||
380             btrfs_test_flag(inode, NODATASUM)) {
381                 goto mapit;
382         }
383
384         return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
385                                    inode, rw, bio, mirror_num,
386                                    __btrfs_submit_bio_hook);
387 mapit:
388         return btrfs_map_bio(root, rw, bio, mirror_num);
389 }
390
391 int btrfs_readpage_io_hook(struct page *page, u64 start, u64 end)
392 {
393         int ret = 0;
394         struct inode *inode = page->mapping->host;
395         struct btrfs_root *root = BTRFS_I(inode)->root;
396         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
397         struct btrfs_csum_item *item;
398         struct btrfs_path *path = NULL;
399         u32 csum;
400
401         if (btrfs_test_opt(root, NODATASUM) ||
402             btrfs_test_flag(inode, NODATASUM))
403                 return 0;
404
405         mutex_lock(&root->fs_info->fs_mutex);
406         path = btrfs_alloc_path();
407         item = btrfs_lookup_csum(NULL, root, path, inode->i_ino, start, 0);
408         if (IS_ERR(item)) {
409                 ret = PTR_ERR(item);
410                 /* a csum that isn't present is a preallocated region. */
411                 if (ret == -ENOENT || ret == -EFBIG)
412                         ret = 0;
413                 csum = 0;
414                 printk("no csum found for inode %lu start %Lu\n", inode->i_ino, start);
415                 goto out;
416         }
417         read_extent_buffer(path->nodes[0], &csum, (unsigned long)item,
418                            BTRFS_CRC32_SIZE);
419         set_state_private(io_tree, start, csum);
420 out:
421         if (path)
422                 btrfs_free_path(path);
423         mutex_unlock(&root->fs_info->fs_mutex);
424         return ret;
425 }
426
427 struct io_failure_record {
428         struct page *page;
429         u64 start;
430         u64 len;
431         u64 logical;
432         int last_mirror;
433 };
434
435 int btrfs_readpage_io_failed_hook(struct bio *failed_bio,
436                                   struct page *page, u64 start, u64 end,
437                                   struct extent_state *state)
438 {
439         struct io_failure_record *failrec = NULL;
440         u64 private;
441         struct extent_map *em;
442         struct inode *inode = page->mapping->host;
443         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
444         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
445         struct bio *bio;
446         int num_copies;
447         int ret;
448         u64 logical;
449
450         ret = get_state_private(failure_tree, start, &private);
451         if (ret) {
452                 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
453                 if (!failrec)
454                         return -ENOMEM;
455                 failrec->start = start;
456                 failrec->len = end - start + 1;
457                 failrec->last_mirror = 0;
458
459                 spin_lock(&em_tree->lock);
460                 em = lookup_extent_mapping(em_tree, start, failrec->len);
461                 if (em->start > start || em->start + em->len < start) {
462                         free_extent_map(em);
463                         em = NULL;
464                 }
465                 spin_unlock(&em_tree->lock);
466
467                 if (!em || IS_ERR(em)) {
468                         kfree(failrec);
469                         return -EIO;
470                 }
471                 logical = start - em->start;
472                 logical = em->block_start + logical;
473                 failrec->logical = logical;
474                 free_extent_map(em);
475                 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
476                                 EXTENT_DIRTY, GFP_NOFS);
477                 set_state_private(failure_tree, start,
478                                  (u64)(unsigned long)failrec);
479         } else {
480                 failrec = (struct io_failure_record *)(unsigned long)private;
481         }
482         num_copies = btrfs_num_copies(
483                               &BTRFS_I(inode)->root->fs_info->mapping_tree,
484                               failrec->logical, failrec->len);
485         failrec->last_mirror++;
486         if (!state) {
487                 spin_lock_irq(&BTRFS_I(inode)->io_tree.lock);
488                 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
489                                                     failrec->start,
490                                                     EXTENT_LOCKED);
491                 if (state && state->start != failrec->start)
492                         state = NULL;
493                 spin_unlock_irq(&BTRFS_I(inode)->io_tree.lock);
494         }
495         if (!state || failrec->last_mirror > num_copies) {
496                 set_state_private(failure_tree, failrec->start, 0);
497                 clear_extent_bits(failure_tree, failrec->start,
498                                   failrec->start + failrec->len - 1,
499                                   EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
500                 kfree(failrec);
501                 return -EIO;
502         }
503         bio = bio_alloc(GFP_NOFS, 1);
504         bio->bi_private = state;
505         bio->bi_end_io = failed_bio->bi_end_io;
506         bio->bi_sector = failrec->logical >> 9;
507         bio->bi_bdev = failed_bio->bi_bdev;
508         bio->bi_size = 0;
509         bio_add_page(bio, page, failrec->len, start - page_offset(page));
510         btrfs_submit_bio_hook(inode, READ, bio, failrec->last_mirror);
511         return 0;
512 }
513
514 int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
515                                struct extent_state *state)
516 {
517         size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
518         struct inode *inode = page->mapping->host;
519         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
520         char *kaddr;
521         u64 private = ~(u32)0;
522         int ret;
523         struct btrfs_root *root = BTRFS_I(inode)->root;
524         u32 csum = ~(u32)0;
525         unsigned long flags;
526
527         if (btrfs_test_opt(root, NODATASUM) ||
528             btrfs_test_flag(inode, NODATASUM))
529                 return 0;
530         if (state && state->start == start) {
531                 private = state->private;
532                 ret = 0;
533         } else {
534                 ret = get_state_private(io_tree, start, &private);
535         }
536         local_irq_save(flags);
537         kaddr = kmap_atomic(page, KM_IRQ0);
538         if (ret) {
539                 goto zeroit;
540         }
541         csum = btrfs_csum_data(root, kaddr + offset, csum,  end - start + 1);
542         btrfs_csum_final(csum, (char *)&csum);
543         if (csum != private) {
544                 goto zeroit;
545         }
546         kunmap_atomic(kaddr, KM_IRQ0);
547         local_irq_restore(flags);
548
549         /* if the io failure tree for this inode is non-empty,
550          * check to see if we've recovered from a failed IO
551          */
552         private = 0;
553         if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
554                              (u64)-1, 1, EXTENT_DIRTY)) {
555                 u64 private_failure;
556                 struct io_failure_record *failure;
557                 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
558                                         start, &private_failure);
559                 if (ret == 0) {
560                         failure = (struct io_failure_record *)(unsigned long)
561                                    private_failure;
562                         set_state_private(&BTRFS_I(inode)->io_failure_tree,
563                                           failure->start, 0);
564                         clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
565                                           failure->start,
566                                           failure->start + failure->len - 1,
567                                           EXTENT_DIRTY | EXTENT_LOCKED,
568                                           GFP_NOFS);
569                         kfree(failure);
570                 }
571         }
572         return 0;
573
574 zeroit:
575         printk("btrfs csum failed ino %lu off %llu csum %u private %Lu\n",
576                page->mapping->host->i_ino, (unsigned long long)start, csum,
577                private);
578         memset(kaddr + offset, 1, end - start + 1);
579         flush_dcache_page(page);
580         kunmap_atomic(kaddr, KM_IRQ0);
581         local_irq_restore(flags);
582         if (private == 0)
583                 return 0;
584         return -EIO;
585 }
586
587 void btrfs_read_locked_inode(struct inode *inode)
588 {
589         struct btrfs_path *path;
590         struct extent_buffer *leaf;
591         struct btrfs_inode_item *inode_item;
592         struct btrfs_timespec *tspec;
593         struct btrfs_root *root = BTRFS_I(inode)->root;
594         struct btrfs_key location;
595         u64 alloc_group_block;
596         u32 rdev;
597         int ret;
598
599         path = btrfs_alloc_path();
600         BUG_ON(!path);
601         mutex_lock(&root->fs_info->fs_mutex);
602         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
603
604         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
605         if (ret)
606                 goto make_bad;
607
608         leaf = path->nodes[0];
609         inode_item = btrfs_item_ptr(leaf, path->slots[0],
610                                     struct btrfs_inode_item);
611
612         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
613         inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
614         inode->i_uid = btrfs_inode_uid(leaf, inode_item);
615         inode->i_gid = btrfs_inode_gid(leaf, inode_item);
616         inode->i_size = btrfs_inode_size(leaf, inode_item);
617
618         tspec = btrfs_inode_atime(inode_item);
619         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
620         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
621
622         tspec = btrfs_inode_mtime(inode_item);
623         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
624         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
625
626         tspec = btrfs_inode_ctime(inode_item);
627         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
628         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
629
630         inode->i_blocks = btrfs_inode_nblocks(leaf, inode_item);
631         inode->i_generation = btrfs_inode_generation(leaf, inode_item);
632         inode->i_rdev = 0;
633         rdev = btrfs_inode_rdev(leaf, inode_item);
634
635         alloc_group_block = btrfs_inode_block_group(leaf, inode_item);
636         BTRFS_I(inode)->block_group = btrfs_lookup_block_group(root->fs_info,
637                                                        alloc_group_block);
638         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
639         if (!BTRFS_I(inode)->block_group) {
640                 BTRFS_I(inode)->block_group = btrfs_find_block_group(root,
641                                                  NULL, 0,
642                                                  BTRFS_BLOCK_GROUP_METADATA, 0);
643         }
644         btrfs_free_path(path);
645         inode_item = NULL;
646
647         mutex_unlock(&root->fs_info->fs_mutex);
648
649         switch (inode->i_mode & S_IFMT) {
650         case S_IFREG:
651                 inode->i_mapping->a_ops = &btrfs_aops;
652                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
653                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
654                 inode->i_fop = &btrfs_file_operations;
655                 inode->i_op = &btrfs_file_inode_operations;
656                 break;
657         case S_IFDIR:
658                 inode->i_fop = &btrfs_dir_file_operations;
659                 if (root == root->fs_info->tree_root)
660                         inode->i_op = &btrfs_dir_ro_inode_operations;
661                 else
662                         inode->i_op = &btrfs_dir_inode_operations;
663                 break;
664         case S_IFLNK:
665                 inode->i_op = &btrfs_symlink_inode_operations;
666                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
667                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
668                 break;
669         default:
670                 init_special_inode(inode, inode->i_mode, rdev);
671                 break;
672         }
673         return;
674
675 make_bad:
676         btrfs_release_path(root, path);
677         btrfs_free_path(path);
678         mutex_unlock(&root->fs_info->fs_mutex);
679         make_bad_inode(inode);
680 }
681
682 static void fill_inode_item(struct extent_buffer *leaf,
683                             struct btrfs_inode_item *item,
684                             struct inode *inode)
685 {
686         btrfs_set_inode_uid(leaf, item, inode->i_uid);
687         btrfs_set_inode_gid(leaf, item, inode->i_gid);
688         btrfs_set_inode_size(leaf, item, inode->i_size);
689         btrfs_set_inode_mode(leaf, item, inode->i_mode);
690         btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
691
692         btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
693                                inode->i_atime.tv_sec);
694         btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
695                                 inode->i_atime.tv_nsec);
696
697         btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
698                                inode->i_mtime.tv_sec);
699         btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
700                                 inode->i_mtime.tv_nsec);
701
702         btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
703                                inode->i_ctime.tv_sec);
704         btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
705                                 inode->i_ctime.tv_nsec);
706
707         btrfs_set_inode_nblocks(leaf, item, inode->i_blocks);
708         btrfs_set_inode_generation(leaf, item, inode->i_generation);
709         btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
710         btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
711         btrfs_set_inode_block_group(leaf, item,
712                                     BTRFS_I(inode)->block_group->key.objectid);
713 }
714
715 int btrfs_update_inode(struct btrfs_trans_handle *trans,
716                               struct btrfs_root *root,
717                               struct inode *inode)
718 {
719         struct btrfs_inode_item *inode_item;
720         struct btrfs_path *path;
721         struct extent_buffer *leaf;
722         int ret;
723
724         path = btrfs_alloc_path();
725         BUG_ON(!path);
726         ret = btrfs_lookup_inode(trans, root, path,
727                                  &BTRFS_I(inode)->location, 1);
728         if (ret) {
729                 if (ret > 0)
730                         ret = -ENOENT;
731                 goto failed;
732         }
733
734         leaf = path->nodes[0];
735         inode_item = btrfs_item_ptr(leaf, path->slots[0],
736                                   struct btrfs_inode_item);
737
738         fill_inode_item(leaf, inode_item, inode);
739         btrfs_mark_buffer_dirty(leaf);
740         btrfs_set_inode_last_trans(trans, inode);
741         ret = 0;
742 failed:
743         btrfs_release_path(root, path);
744         btrfs_free_path(path);
745         return ret;
746 }
747
748
749 static int btrfs_unlink_trans(struct btrfs_trans_handle *trans,
750                               struct btrfs_root *root,
751                               struct inode *dir,
752                               struct dentry *dentry)
753 {
754         struct btrfs_path *path;
755         const char *name = dentry->d_name.name;
756         int name_len = dentry->d_name.len;
757         int ret = 0;
758         struct extent_buffer *leaf;
759         struct btrfs_dir_item *di;
760         struct btrfs_key key;
761
762         path = btrfs_alloc_path();
763         if (!path) {
764                 ret = -ENOMEM;
765                 goto err;
766         }
767
768         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
769                                     name, name_len, -1);
770         if (IS_ERR(di)) {
771                 ret = PTR_ERR(di);
772                 goto err;
773         }
774         if (!di) {
775                 ret = -ENOENT;
776                 goto err;
777         }
778         leaf = path->nodes[0];
779         btrfs_dir_item_key_to_cpu(leaf, di, &key);
780         ret = btrfs_delete_one_dir_name(trans, root, path, di);
781         if (ret)
782                 goto err;
783         btrfs_release_path(root, path);
784
785         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
786                                          key.objectid, name, name_len, -1);
787         if (IS_ERR(di)) {
788                 ret = PTR_ERR(di);
789                 goto err;
790         }
791         if (!di) {
792                 ret = -ENOENT;
793                 goto err;
794         }
795         ret = btrfs_delete_one_dir_name(trans, root, path, di);
796
797         dentry->d_inode->i_ctime = dir->i_ctime;
798         ret = btrfs_del_inode_ref(trans, root, name, name_len,
799                                   dentry->d_inode->i_ino,
800                                   dentry->d_parent->d_inode->i_ino);
801         if (ret) {
802                 printk("failed to delete reference to %.*s, "
803                        "inode %lu parent %lu\n", name_len, name,
804                        dentry->d_inode->i_ino,
805                        dentry->d_parent->d_inode->i_ino);
806         }
807 err:
808         btrfs_free_path(path);
809         if (!ret) {
810                 dir->i_size -= name_len * 2;
811                 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
812                 btrfs_update_inode(trans, root, dir);
813 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,18)
814                 dentry->d_inode->i_nlink--;
815 #else
816                 drop_nlink(dentry->d_inode);
817 #endif
818                 ret = btrfs_update_inode(trans, root, dentry->d_inode);
819                 dir->i_sb->s_dirt = 1;
820         }
821         return ret;
822 }
823
824 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
825 {
826         struct btrfs_root *root;
827         struct btrfs_trans_handle *trans;
828         struct inode *inode = dentry->d_inode;
829         int ret;
830         unsigned long nr = 0;
831
832         root = BTRFS_I(dir)->root;
833         mutex_lock(&root->fs_info->fs_mutex);
834
835         ret = btrfs_check_free_space(root, 1, 1);
836         if (ret)
837                 goto fail;
838
839         trans = btrfs_start_transaction(root, 1);
840
841         btrfs_set_trans_block_group(trans, dir);
842         ret = btrfs_unlink_trans(trans, root, dir, dentry);
843         nr = trans->blocks_used;
844
845         if (inode->i_nlink == 0) {
846                 int found;
847                 /* if the inode isn't linked anywhere,
848                  * we don't need to worry about
849                  * data=ordered
850                  */
851                 found = btrfs_del_ordered_inode(inode);
852                 if (found == 1) {
853                         atomic_dec(&inode->i_count);
854                 }
855         }
856
857         btrfs_end_transaction(trans, root);
858 fail:
859         mutex_unlock(&root->fs_info->fs_mutex);
860         btrfs_btree_balance_dirty(root, nr);
861         btrfs_throttle(root);
862         return ret;
863 }
864
865 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
866 {
867         struct inode *inode = dentry->d_inode;
868         int err = 0;
869         int ret;
870         struct btrfs_root *root = BTRFS_I(dir)->root;
871         struct btrfs_trans_handle *trans;
872         unsigned long nr = 0;
873
874         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
875                 return -ENOTEMPTY;
876
877         mutex_lock(&root->fs_info->fs_mutex);
878         ret = btrfs_check_free_space(root, 1, 1);
879         if (ret)
880                 goto fail;
881
882         trans = btrfs_start_transaction(root, 1);
883         btrfs_set_trans_block_group(trans, dir);
884
885         /* now the directory is empty */
886         err = btrfs_unlink_trans(trans, root, dir, dentry);
887         if (!err) {
888                 inode->i_size = 0;
889         }
890
891         nr = trans->blocks_used;
892         ret = btrfs_end_transaction(trans, root);
893 fail:
894         mutex_unlock(&root->fs_info->fs_mutex);
895         btrfs_btree_balance_dirty(root, nr);
896         btrfs_throttle(root);
897
898         if (ret && !err)
899                 err = ret;
900         return err;
901 }
902
903 /*
904  * this can truncate away extent items, csum items and directory items.
905  * It starts at a high offset and removes keys until it can't find
906  * any higher than i_size.
907  *
908  * csum items that cross the new i_size are truncated to the new size
909  * as well.
910  */
911 static int btrfs_truncate_in_trans(struct btrfs_trans_handle *trans,
912                                    struct btrfs_root *root,
913                                    struct inode *inode,
914                                    u32 min_type)
915 {
916         int ret;
917         struct btrfs_path *path;
918         struct btrfs_key key;
919         struct btrfs_key found_key;
920         u32 found_type;
921         struct extent_buffer *leaf;
922         struct btrfs_file_extent_item *fi;
923         u64 extent_start = 0;
924         u64 extent_num_bytes = 0;
925         u64 item_end = 0;
926         u64 root_gen = 0;
927         u64 root_owner = 0;
928         int found_extent;
929         int del_item;
930         int pending_del_nr = 0;
931         int pending_del_slot = 0;
932         int extent_type = -1;
933         u64 mask = root->sectorsize - 1;
934
935         btrfs_drop_extent_cache(inode, inode->i_size & (~mask), (u64)-1);
936         path = btrfs_alloc_path();
937         path->reada = -1;
938         BUG_ON(!path);
939
940         /* FIXME, add redo link to tree so we don't leak on crash */
941         key.objectid = inode->i_ino;
942         key.offset = (u64)-1;
943         key.type = (u8)-1;
944
945         btrfs_init_path(path);
946 search_again:
947         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
948         if (ret < 0) {
949                 goto error;
950         }
951         if (ret > 0) {
952                 BUG_ON(path->slots[0] == 0);
953                 path->slots[0]--;
954         }
955
956         while(1) {
957                 fi = NULL;
958                 leaf = path->nodes[0];
959                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
960                 found_type = btrfs_key_type(&found_key);
961
962                 if (found_key.objectid != inode->i_ino)
963                         break;
964
965                 if (found_type < min_type)
966                         break;
967
968                 item_end = found_key.offset;
969                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
970                         fi = btrfs_item_ptr(leaf, path->slots[0],
971                                             struct btrfs_file_extent_item);
972                         extent_type = btrfs_file_extent_type(leaf, fi);
973                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
974                                 item_end +=
975                                     btrfs_file_extent_num_bytes(leaf, fi);
976                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
977                                 struct btrfs_item *item = btrfs_item_nr(leaf,
978                                                                 path->slots[0]);
979                                 item_end += btrfs_file_extent_inline_len(leaf,
980                                                                          item);
981                         }
982                         item_end--;
983                 }
984                 if (found_type == BTRFS_CSUM_ITEM_KEY) {
985                         ret = btrfs_csum_truncate(trans, root, path,
986                                                   inode->i_size);
987                         BUG_ON(ret);
988                 }
989                 if (item_end < inode->i_size) {
990                         if (found_type == BTRFS_DIR_ITEM_KEY) {
991                                 found_type = BTRFS_INODE_ITEM_KEY;
992                         } else if (found_type == BTRFS_EXTENT_ITEM_KEY) {
993                                 found_type = BTRFS_CSUM_ITEM_KEY;
994                         } else if (found_type == BTRFS_EXTENT_DATA_KEY) {
995                                 found_type = BTRFS_XATTR_ITEM_KEY;
996                         } else if (found_type == BTRFS_XATTR_ITEM_KEY) {
997                                 found_type = BTRFS_INODE_REF_KEY;
998                         } else if (found_type) {
999                                 found_type--;
1000                         } else {
1001                                 break;
1002                         }
1003                         btrfs_set_key_type(&key, found_type);
1004                         goto next;
1005                 }
1006                 if (found_key.offset >= inode->i_size)
1007                         del_item = 1;
1008                 else
1009                         del_item = 0;
1010                 found_extent = 0;
1011
1012                 /* FIXME, shrink the extent if the ref count is only 1 */
1013                 if (found_type != BTRFS_EXTENT_DATA_KEY)
1014                         goto delete;
1015
1016                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
1017                         u64 num_dec;
1018                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
1019                         if (!del_item) {
1020                                 u64 orig_num_bytes =
1021                                         btrfs_file_extent_num_bytes(leaf, fi);
1022                                 extent_num_bytes = inode->i_size -
1023                                         found_key.offset + root->sectorsize - 1;
1024                                 extent_num_bytes = extent_num_bytes &
1025                                         ~((u64)root->sectorsize - 1);
1026                                 btrfs_set_file_extent_num_bytes(leaf, fi,
1027                                                          extent_num_bytes);
1028                                 num_dec = (orig_num_bytes -
1029                                            extent_num_bytes);
1030                                 if (extent_start != 0)
1031                                         dec_i_blocks(inode, num_dec);
1032                                 btrfs_mark_buffer_dirty(leaf);
1033                         } else {
1034                                 extent_num_bytes =
1035                                         btrfs_file_extent_disk_num_bytes(leaf,
1036                                                                          fi);
1037                                 /* FIXME blocksize != 4096 */
1038                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
1039                                 if (extent_start != 0) {
1040                                         found_extent = 1;
1041                                         dec_i_blocks(inode, num_dec);
1042                                 }
1043                                 root_gen = btrfs_header_generation(leaf);
1044                                 root_owner = btrfs_header_owner(leaf);
1045                         }
1046                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1047                         if (!del_item) {
1048                                 u32 newsize = inode->i_size - found_key.offset;
1049                                 dec_i_blocks(inode, item_end + 1 -
1050                                             found_key.offset - newsize);
1051                                 newsize =
1052                                     btrfs_file_extent_calc_inline_size(newsize);
1053                                 ret = btrfs_truncate_item(trans, root, path,
1054                                                           newsize, 1);
1055                                 BUG_ON(ret);
1056                         } else {
1057                                 dec_i_blocks(inode, item_end + 1 -
1058                                              found_key.offset);
1059                         }
1060                 }
1061 delete:
1062                 if (del_item) {
1063                         if (!pending_del_nr) {
1064                                 /* no pending yet, add ourselves */
1065                                 pending_del_slot = path->slots[0];
1066                                 pending_del_nr = 1;
1067                         } else if (pending_del_nr &&
1068                                    path->slots[0] + 1 == pending_del_slot) {
1069                                 /* hop on the pending chunk */
1070                                 pending_del_nr++;
1071                                 pending_del_slot = path->slots[0];
1072                         } else {
1073                                 printk("bad pending slot %d pending_del_nr %d pending_del_slot %d\n", path->slots[0], pending_del_nr, pending_del_slot);
1074                         }
1075                 } else {
1076                         break;
1077                 }
1078                 if (found_extent) {
1079                         ret = btrfs_free_extent(trans, root, extent_start,
1080                                                 extent_num_bytes,
1081                                                 root_owner,
1082                                                 root_gen, inode->i_ino,
1083                                                 found_key.offset, 0);
1084                         BUG_ON(ret);
1085                 }
1086 next:
1087                 if (path->slots[0] == 0) {
1088                         if (pending_del_nr)
1089                                 goto del_pending;
1090                         btrfs_release_path(root, path);
1091                         goto search_again;
1092                 }
1093
1094                 path->slots[0]--;
1095                 if (pending_del_nr &&
1096                     path->slots[0] + 1 != pending_del_slot) {
1097                         struct btrfs_key debug;
1098 del_pending:
1099                         btrfs_item_key_to_cpu(path->nodes[0], &debug,
1100                                               pending_del_slot);
1101                         ret = btrfs_del_items(trans, root, path,
1102                                               pending_del_slot,
1103                                               pending_del_nr);
1104                         BUG_ON(ret);
1105                         pending_del_nr = 0;
1106                         btrfs_release_path(root, path);
1107                         goto search_again;
1108                 }
1109         }
1110         ret = 0;
1111 error:
1112         if (pending_del_nr) {
1113                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
1114                                       pending_del_nr);
1115         }
1116         btrfs_release_path(root, path);
1117         btrfs_free_path(path);
1118         inode->i_sb->s_dirt = 1;
1119         return ret;
1120 }
1121
1122 static int btrfs_cow_one_page(struct inode *inode, struct page *page,
1123                               size_t zero_start)
1124 {
1125         char *kaddr;
1126         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1127         u64 page_start = (u64)page->index << PAGE_CACHE_SHIFT;
1128         u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
1129         int ret = 0;
1130
1131         WARN_ON(!PageLocked(page));
1132         set_page_extent_mapped(page);
1133
1134         lock_extent(io_tree, page_start, page_end, GFP_NOFS);
1135         set_extent_delalloc(&BTRFS_I(inode)->io_tree, page_start,
1136                             page_end, GFP_NOFS);
1137
1138         if (zero_start != PAGE_CACHE_SIZE) {
1139                 kaddr = kmap(page);
1140                 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
1141                 flush_dcache_page(page);
1142                 kunmap(page);
1143         }
1144         set_page_dirty(page);
1145         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
1146
1147         return ret;
1148 }
1149
1150 /*
1151  * taken from block_truncate_page, but does cow as it zeros out
1152  * any bytes left in the last page in the file.
1153  */
1154 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
1155 {
1156         struct inode *inode = mapping->host;
1157         struct btrfs_root *root = BTRFS_I(inode)->root;
1158         u32 blocksize = root->sectorsize;
1159         pgoff_t index = from >> PAGE_CACHE_SHIFT;
1160         unsigned offset = from & (PAGE_CACHE_SIZE-1);
1161         struct page *page;
1162         int ret = 0;
1163         u64 page_start;
1164
1165         if ((offset & (blocksize - 1)) == 0)
1166                 goto out;
1167
1168         ret = -ENOMEM;
1169         page = grab_cache_page(mapping, index);
1170         if (!page)
1171                 goto out;
1172         if (!PageUptodate(page)) {
1173                 ret = btrfs_readpage(NULL, page);
1174                 lock_page(page);
1175                 if (!PageUptodate(page)) {
1176                         ret = -EIO;
1177                         goto out;
1178                 }
1179         }
1180         page_start = (u64)page->index << PAGE_CACHE_SHIFT;
1181
1182         ret = btrfs_cow_one_page(inode, page, offset);
1183
1184         unlock_page(page);
1185         page_cache_release(page);
1186 out:
1187         return ret;
1188 }
1189
1190 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
1191 {
1192         struct inode *inode = dentry->d_inode;
1193         int err;
1194
1195         err = inode_change_ok(inode, attr);
1196         if (err)
1197                 return err;
1198
1199         if (S_ISREG(inode->i_mode) &&
1200             attr->ia_valid & ATTR_SIZE && attr->ia_size > inode->i_size) {
1201                 struct btrfs_trans_handle *trans;
1202                 struct btrfs_root *root = BTRFS_I(inode)->root;
1203                 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1204
1205                 u64 mask = root->sectorsize - 1;
1206                 u64 hole_start = (inode->i_size + mask) & ~mask;
1207                 u64 block_end = (attr->ia_size + mask) & ~mask;
1208                 u64 hole_size;
1209                 u64 alloc_hint = 0;
1210
1211                 if (attr->ia_size <= hole_start)
1212                         goto out;
1213
1214                 mutex_lock(&root->fs_info->fs_mutex);
1215                 err = btrfs_check_free_space(root, 1, 0);
1216                 mutex_unlock(&root->fs_info->fs_mutex);
1217                 if (err)
1218                         goto fail;
1219
1220                 btrfs_truncate_page(inode->i_mapping, inode->i_size);
1221
1222                 lock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
1223                 hole_size = block_end - hole_start;
1224
1225                 mutex_lock(&root->fs_info->fs_mutex);
1226                 trans = btrfs_start_transaction(root, 1);
1227                 btrfs_set_trans_block_group(trans, inode);
1228                 err = btrfs_drop_extents(trans, root, inode,
1229                                          hole_start, block_end, hole_start,
1230                                          &alloc_hint);
1231
1232                 if (alloc_hint != EXTENT_MAP_INLINE) {
1233                         err = btrfs_insert_file_extent(trans, root,
1234                                                        inode->i_ino,
1235                                                        hole_start, 0, 0,
1236                                                        hole_size, 0);
1237                         btrfs_drop_extent_cache(inode, hole_start,
1238                                                 (u64)-1);
1239                         btrfs_check_file(root, inode);
1240                 }
1241                 btrfs_end_transaction(trans, root);
1242                 mutex_unlock(&root->fs_info->fs_mutex);
1243                 unlock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
1244                 if (err)
1245                         return err;
1246         }
1247 out:
1248         err = inode_setattr(inode, attr);
1249 fail:
1250         return err;
1251 }
1252
1253 void btrfs_put_inode(struct inode *inode)
1254 {
1255         int ret;
1256
1257         if (!BTRFS_I(inode)->ordered_trans) {
1258                 return;
1259         }
1260
1261         if (mapping_tagged(inode->i_mapping, PAGECACHE_TAG_DIRTY) ||
1262             mapping_tagged(inode->i_mapping, PAGECACHE_TAG_WRITEBACK))
1263                 return;
1264
1265         ret = btrfs_del_ordered_inode(inode);
1266         if (ret == 1) {
1267                 atomic_dec(&inode->i_count);
1268         }
1269 }
1270
1271 void btrfs_delete_inode(struct inode *inode)
1272 {
1273         struct btrfs_trans_handle *trans;
1274         struct btrfs_root *root = BTRFS_I(inode)->root;
1275         unsigned long nr;
1276         int ret;
1277
1278         truncate_inode_pages(&inode->i_data, 0);
1279         if (is_bad_inode(inode)) {
1280                 goto no_delete;
1281         }
1282
1283         inode->i_size = 0;
1284         mutex_lock(&root->fs_info->fs_mutex);
1285         trans = btrfs_start_transaction(root, 1);
1286
1287         btrfs_set_trans_block_group(trans, inode);
1288         ret = btrfs_truncate_in_trans(trans, root, inode, 0);
1289         if (ret)
1290                 goto no_delete_lock;
1291
1292         nr = trans->blocks_used;
1293         clear_inode(inode);
1294
1295         btrfs_end_transaction(trans, root);
1296         mutex_unlock(&root->fs_info->fs_mutex);
1297         btrfs_btree_balance_dirty(root, nr);
1298         btrfs_throttle(root);
1299         return;
1300
1301 no_delete_lock:
1302         nr = trans->blocks_used;
1303         btrfs_end_transaction(trans, root);
1304         mutex_unlock(&root->fs_info->fs_mutex);
1305         btrfs_btree_balance_dirty(root, nr);
1306         btrfs_throttle(root);
1307 no_delete:
1308         clear_inode(inode);
1309 }
1310
1311 /*
1312  * this returns the key found in the dir entry in the location pointer.
1313  * If no dir entries were found, location->objectid is 0.
1314  */
1315 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
1316                                struct btrfs_key *location)
1317 {
1318         const char *name = dentry->d_name.name;
1319         int namelen = dentry->d_name.len;
1320         struct btrfs_dir_item *di;
1321         struct btrfs_path *path;
1322         struct btrfs_root *root = BTRFS_I(dir)->root;
1323         int ret = 0;
1324
1325         if (namelen == 1 && strcmp(name, ".") == 0) {
1326                 location->objectid = dir->i_ino;
1327                 location->type = BTRFS_INODE_ITEM_KEY;
1328                 location->offset = 0;
1329                 return 0;
1330         }
1331         path = btrfs_alloc_path();
1332         BUG_ON(!path);
1333
1334         if (namelen == 2 && strcmp(name, "..") == 0) {
1335                 struct btrfs_key key;
1336                 struct extent_buffer *leaf;
1337                 u32 nritems;
1338                 int slot;
1339
1340                 key.objectid = dir->i_ino;
1341                 btrfs_set_key_type(&key, BTRFS_INODE_REF_KEY);
1342                 key.offset = 0;
1343                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1344                 BUG_ON(ret == 0);
1345                 ret = 0;
1346
1347                 leaf = path->nodes[0];
1348                 slot = path->slots[0];
1349                 nritems = btrfs_header_nritems(leaf);
1350                 if (slot >= nritems)
1351                         goto out_err;
1352
1353                 btrfs_item_key_to_cpu(leaf, &key, slot);
1354                 if (key.objectid != dir->i_ino ||
1355                     key.type != BTRFS_INODE_REF_KEY) {
1356                         goto out_err;
1357                 }
1358                 location->objectid = key.offset;
1359                 location->type = BTRFS_INODE_ITEM_KEY;
1360                 location->offset = 0;
1361                 goto out;
1362         }
1363
1364         di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
1365                                     namelen, 0);
1366         if (IS_ERR(di))
1367                 ret = PTR_ERR(di);
1368         if (!di || IS_ERR(di)) {
1369                 goto out_err;
1370         }
1371         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
1372 out:
1373         btrfs_free_path(path);
1374         return ret;
1375 out_err:
1376         location->objectid = 0;
1377         goto out;
1378 }
1379
1380 /*
1381  * when we hit a tree root in a directory, the btrfs part of the inode
1382  * needs to be changed to reflect the root directory of the tree root.  This
1383  * is kind of like crossing a mount point.
1384  */
1385 static int fixup_tree_root_location(struct btrfs_root *root,
1386                              struct btrfs_key *location,
1387                              struct btrfs_root **sub_root,
1388                              struct dentry *dentry)
1389 {
1390         struct btrfs_path *path;
1391         struct btrfs_root_item *ri;
1392
1393         if (btrfs_key_type(location) != BTRFS_ROOT_ITEM_KEY)
1394                 return 0;
1395         if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1396                 return 0;
1397
1398         path = btrfs_alloc_path();
1399         BUG_ON(!path);
1400         mutex_lock(&root->fs_info->fs_mutex);
1401
1402         *sub_root = btrfs_read_fs_root(root->fs_info, location,
1403                                         dentry->d_name.name,
1404                                         dentry->d_name.len);
1405         if (IS_ERR(*sub_root))
1406                 return PTR_ERR(*sub_root);
1407
1408         ri = &(*sub_root)->root_item;
1409         location->objectid = btrfs_root_dirid(ri);
1410         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
1411         location->offset = 0;
1412
1413         btrfs_free_path(path);
1414         mutex_unlock(&root->fs_info->fs_mutex);
1415         return 0;
1416 }
1417
1418 static int btrfs_init_locked_inode(struct inode *inode, void *p)
1419 {
1420         struct btrfs_iget_args *args = p;
1421         inode->i_ino = args->ino;
1422         BTRFS_I(inode)->root = args->root;
1423         BTRFS_I(inode)->delalloc_bytes = 0;
1424         extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
1425         extent_io_tree_init(&BTRFS_I(inode)->io_tree,
1426                              inode->i_mapping, GFP_NOFS);
1427         extent_io_tree_init(&BTRFS_I(inode)->io_failure_tree,
1428                              inode->i_mapping, GFP_NOFS);
1429         atomic_set(&BTRFS_I(inode)->ordered_writeback, 0);
1430         return 0;
1431 }
1432
1433 static int btrfs_find_actor(struct inode *inode, void *opaque)
1434 {
1435         struct btrfs_iget_args *args = opaque;
1436         return (args->ino == inode->i_ino &&
1437                 args->root == BTRFS_I(inode)->root);
1438 }
1439
1440 struct inode *btrfs_ilookup(struct super_block *s, u64 objectid,
1441                             u64 root_objectid)
1442 {
1443         struct btrfs_iget_args args;
1444         args.ino = objectid;
1445         args.root = btrfs_lookup_fs_root(btrfs_sb(s)->fs_info, root_objectid);
1446
1447         if (!args.root)
1448                 return NULL;
1449
1450         return ilookup5(s, objectid, btrfs_find_actor, (void *)&args);
1451 }
1452
1453 struct inode *btrfs_iget_locked(struct super_block *s, u64 objectid,
1454                                 struct btrfs_root *root)
1455 {
1456         struct inode *inode;
1457         struct btrfs_iget_args args;
1458         args.ino = objectid;
1459         args.root = root;
1460
1461         inode = iget5_locked(s, objectid, btrfs_find_actor,
1462                              btrfs_init_locked_inode,
1463                              (void *)&args);
1464         return inode;
1465 }
1466
1467 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
1468                                    struct nameidata *nd)
1469 {
1470         struct inode * inode;
1471         struct btrfs_inode *bi = BTRFS_I(dir);
1472         struct btrfs_root *root = bi->root;
1473         struct btrfs_root *sub_root = root;
1474         struct btrfs_key location;
1475         int ret;
1476
1477         if (dentry->d_name.len > BTRFS_NAME_LEN)
1478                 return ERR_PTR(-ENAMETOOLONG);
1479
1480         mutex_lock(&root->fs_info->fs_mutex);
1481         ret = btrfs_inode_by_name(dir, dentry, &location);
1482         mutex_unlock(&root->fs_info->fs_mutex);
1483
1484         if (ret < 0)
1485                 return ERR_PTR(ret);
1486
1487         inode = NULL;
1488         if (location.objectid) {
1489                 ret = fixup_tree_root_location(root, &location, &sub_root,
1490                                                 dentry);
1491                 if (ret < 0)
1492                         return ERR_PTR(ret);
1493                 if (ret > 0)
1494                         return ERR_PTR(-ENOENT);
1495                 inode = btrfs_iget_locked(dir->i_sb, location.objectid,
1496                                           sub_root);
1497                 if (!inode)
1498                         return ERR_PTR(-EACCES);
1499                 if (inode->i_state & I_NEW) {
1500                         /* the inode and parent dir are two different roots */
1501                         if (sub_root != root) {
1502                                 igrab(inode);
1503                                 sub_root->inode = inode;
1504                         }
1505                         BTRFS_I(inode)->root = sub_root;
1506                         memcpy(&BTRFS_I(inode)->location, &location,
1507                                sizeof(location));
1508                         btrfs_read_locked_inode(inode);
1509                         unlock_new_inode(inode);
1510                 }
1511         }
1512         return d_splice_alias(inode, dentry);
1513 }
1514
1515 static unsigned char btrfs_filetype_table[] = {
1516         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
1517 };
1518
1519 static int btrfs_readdir(struct file *filp, void *dirent, filldir_t filldir)
1520 {
1521         struct inode *inode = filp->f_dentry->d_inode;
1522         struct btrfs_root *root = BTRFS_I(inode)->root;
1523         struct btrfs_item *item;
1524         struct btrfs_dir_item *di;
1525         struct btrfs_key key;
1526         struct btrfs_key found_key;
1527         struct btrfs_path *path;
1528         int ret;
1529         u32 nritems;
1530         struct extent_buffer *leaf;
1531         int slot;
1532         int advance;
1533         unsigned char d_type;
1534         int over = 0;
1535         u32 di_cur;
1536         u32 di_total;
1537         u32 di_len;
1538         int key_type = BTRFS_DIR_INDEX_KEY;
1539         char tmp_name[32];
1540         char *name_ptr;
1541         int name_len;
1542
1543         /* FIXME, use a real flag for deciding about the key type */
1544         if (root->fs_info->tree_root == root)
1545                 key_type = BTRFS_DIR_ITEM_KEY;
1546
1547         /* special case for "." */
1548         if (filp->f_pos == 0) {
1549                 over = filldir(dirent, ".", 1,
1550                                1, inode->i_ino,
1551                                DT_DIR);
1552                 if (over)
1553                         return 0;
1554                 filp->f_pos = 1;
1555         }
1556
1557         mutex_lock(&root->fs_info->fs_mutex);
1558         key.objectid = inode->i_ino;
1559         path = btrfs_alloc_path();
1560         path->reada = 2;
1561
1562         /* special case for .., just use the back ref */
1563         if (filp->f_pos == 1) {
1564                 btrfs_set_key_type(&key, BTRFS_INODE_REF_KEY);
1565                 key.offset = 0;
1566                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1567                 BUG_ON(ret == 0);
1568                 leaf = path->nodes[0];
1569                 slot = path->slots[0];
1570                 nritems = btrfs_header_nritems(leaf);
1571                 if (slot >= nritems) {
1572                         btrfs_release_path(root, path);
1573                         goto read_dir_items;
1574                 }
1575                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1576                 btrfs_release_path(root, path);
1577                 if (found_key.objectid != key.objectid ||
1578                     found_key.type != BTRFS_INODE_REF_KEY)
1579                         goto read_dir_items;
1580                 over = filldir(dirent, "..", 2,
1581                                2, found_key.offset, DT_DIR);
1582                 if (over)
1583                         goto nopos;
1584                 filp->f_pos = 2;
1585         }
1586
1587 read_dir_items:
1588         btrfs_set_key_type(&key, key_type);
1589         key.offset = filp->f_pos;
1590
1591         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1592         if (ret < 0)
1593                 goto err;
1594         advance = 0;
1595         while(1) {
1596                 leaf = path->nodes[0];
1597                 nritems = btrfs_header_nritems(leaf);
1598                 slot = path->slots[0];
1599                 if (advance || slot >= nritems) {
1600                         if (slot >= nritems -1) {
1601                                 ret = btrfs_next_leaf(root, path);
1602                                 if (ret)
1603                                         break;
1604                                 leaf = path->nodes[0];
1605                                 nritems = btrfs_header_nritems(leaf);
1606                                 slot = path->slots[0];
1607                         } else {
1608                                 slot++;
1609                                 path->slots[0]++;
1610                         }
1611                 }
1612                 advance = 1;
1613                 item = btrfs_item_nr(leaf, slot);
1614                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1615
1616                 if (found_key.objectid != key.objectid)
1617                         break;
1618                 if (btrfs_key_type(&found_key) != key_type)
1619                         break;
1620                 if (found_key.offset < filp->f_pos)
1621                         continue;
1622
1623                 filp->f_pos = found_key.offset;
1624                 advance = 1;
1625                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
1626                 di_cur = 0;
1627                 di_total = btrfs_item_size(leaf, item);
1628                 while(di_cur < di_total) {
1629                         struct btrfs_key location;
1630
1631                         name_len = btrfs_dir_name_len(leaf, di);
1632                         if (name_len < 32) {
1633                                 name_ptr = tmp_name;
1634                         } else {
1635                                 name_ptr = kmalloc(name_len, GFP_NOFS);
1636                                 BUG_ON(!name_ptr);
1637                         }
1638                         read_extent_buffer(leaf, name_ptr,
1639                                            (unsigned long)(di + 1), name_len);
1640
1641                         d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
1642                         btrfs_dir_item_key_to_cpu(leaf, di, &location);
1643                         over = filldir(dirent, name_ptr, name_len,
1644                                        found_key.offset,
1645                                        location.objectid,
1646                                        d_type);
1647
1648                         if (name_ptr != tmp_name)
1649                                 kfree(name_ptr);
1650
1651                         if (over)
1652                                 goto nopos;
1653                         di_len = btrfs_dir_name_len(leaf, di) +
1654                                 btrfs_dir_data_len(leaf, di) +sizeof(*di);
1655                         di_cur += di_len;
1656                         di = (struct btrfs_dir_item *)((char *)di + di_len);
1657                 }
1658         }
1659         if (key_type == BTRFS_DIR_INDEX_KEY)
1660                 filp->f_pos = INT_LIMIT(typeof(filp->f_pos));
1661         else
1662                 filp->f_pos++;
1663 nopos:
1664         ret = 0;
1665 err:
1666         btrfs_release_path(root, path);
1667         btrfs_free_path(path);
1668         mutex_unlock(&root->fs_info->fs_mutex);
1669         return ret;
1670 }
1671
1672 int btrfs_write_inode(struct inode *inode, int wait)
1673 {
1674         struct btrfs_root *root = BTRFS_I(inode)->root;
1675         struct btrfs_trans_handle *trans;
1676         int ret = 0;
1677
1678         if (wait) {
1679                 mutex_lock(&root->fs_info->fs_mutex);
1680                 trans = btrfs_start_transaction(root, 1);
1681                 btrfs_set_trans_block_group(trans, inode);
1682                 ret = btrfs_commit_transaction(trans, root);
1683                 mutex_unlock(&root->fs_info->fs_mutex);
1684         }
1685         return ret;
1686 }
1687
1688 /*
1689  * This is somewhat expensive, updating the tree every time the
1690  * inode changes.  But, it is most likely to find the inode in cache.
1691  * FIXME, needs more benchmarking...there are no reasons other than performance
1692  * to keep or drop this code.
1693  */
1694 void btrfs_dirty_inode(struct inode *inode)
1695 {
1696         struct btrfs_root *root = BTRFS_I(inode)->root;
1697         struct btrfs_trans_handle *trans;
1698
1699         mutex_lock(&root->fs_info->fs_mutex);
1700         trans = btrfs_start_transaction(root, 1);
1701         btrfs_set_trans_block_group(trans, inode);
1702         btrfs_update_inode(trans, root, inode);
1703         btrfs_end_transaction(trans, root);
1704         mutex_unlock(&root->fs_info->fs_mutex);
1705 }
1706
1707 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
1708                                      struct btrfs_root *root,
1709                                      const char *name, int name_len,
1710                                      u64 ref_objectid,
1711                                      u64 objectid,
1712                                      struct btrfs_block_group_cache *group,
1713                                      int mode)
1714 {
1715         struct inode *inode;
1716         struct btrfs_inode_item *inode_item;
1717         struct btrfs_block_group_cache *new_inode_group;
1718         struct btrfs_key *location;
1719         struct btrfs_path *path;
1720         struct btrfs_inode_ref *ref;
1721         struct btrfs_key key[2];
1722         u32 sizes[2];
1723         unsigned long ptr;
1724         int ret;
1725         int owner;
1726
1727         path = btrfs_alloc_path();
1728         BUG_ON(!path);
1729
1730         inode = new_inode(root->fs_info->sb);
1731         if (!inode)
1732                 return ERR_PTR(-ENOMEM);
1733
1734         extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
1735         extent_io_tree_init(&BTRFS_I(inode)->io_tree,
1736                              inode->i_mapping, GFP_NOFS);
1737         extent_io_tree_init(&BTRFS_I(inode)->io_failure_tree,
1738                              inode->i_mapping, GFP_NOFS);
1739         atomic_set(&BTRFS_I(inode)->ordered_writeback, 0);
1740         BTRFS_I(inode)->delalloc_bytes = 0;
1741         BTRFS_I(inode)->root = root;
1742
1743         if (mode & S_IFDIR)
1744                 owner = 0;
1745         else
1746                 owner = 1;
1747         new_inode_group = btrfs_find_block_group(root, group, 0,
1748                                        BTRFS_BLOCK_GROUP_METADATA, owner);
1749         if (!new_inode_group) {
1750                 printk("find_block group failed\n");
1751                 new_inode_group = group;
1752         }
1753         BTRFS_I(inode)->block_group = new_inode_group;
1754         BTRFS_I(inode)->flags = 0;
1755
1756         key[0].objectid = objectid;
1757         btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
1758         key[0].offset = 0;
1759
1760         key[1].objectid = objectid;
1761         btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
1762         key[1].offset = ref_objectid;
1763
1764         sizes[0] = sizeof(struct btrfs_inode_item);
1765         sizes[1] = name_len + sizeof(*ref);
1766
1767         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
1768         if (ret != 0)
1769                 goto fail;
1770
1771         if (objectid > root->highest_inode)
1772                 root->highest_inode = objectid;
1773
1774         inode->i_uid = current->fsuid;
1775         inode->i_gid = current->fsgid;
1776         inode->i_mode = mode;
1777         inode->i_ino = objectid;
1778         inode->i_blocks = 0;
1779         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
1780         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1781                                   struct btrfs_inode_item);
1782         fill_inode_item(path->nodes[0], inode_item, inode);
1783
1784         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
1785                              struct btrfs_inode_ref);
1786         btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
1787         ptr = (unsigned long)(ref + 1);
1788         write_extent_buffer(path->nodes[0], name, ptr, name_len);
1789
1790         btrfs_mark_buffer_dirty(path->nodes[0]);
1791         btrfs_free_path(path);
1792
1793         location = &BTRFS_I(inode)->location;
1794         location->objectid = objectid;
1795         location->offset = 0;
1796         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
1797
1798         insert_inode_hash(inode);
1799         return inode;
1800 fail:
1801         btrfs_free_path(path);
1802         return ERR_PTR(ret);
1803 }
1804
1805 static inline u8 btrfs_inode_type(struct inode *inode)
1806 {
1807         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
1808 }
1809
1810 static int btrfs_add_link(struct btrfs_trans_handle *trans,
1811                             struct dentry *dentry, struct inode *inode,
1812                             int add_backref)
1813 {
1814         int ret;
1815         struct btrfs_key key;
1816         struct btrfs_root *root = BTRFS_I(dentry->d_parent->d_inode)->root;
1817         struct inode *parent_inode;
1818
1819         key.objectid = inode->i_ino;
1820         btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
1821         key.offset = 0;
1822
1823         ret = btrfs_insert_dir_item(trans, root,
1824                                     dentry->d_name.name, dentry->d_name.len,
1825                                     dentry->d_parent->d_inode->i_ino,
1826                                     &key, btrfs_inode_type(inode));
1827         if (ret == 0) {
1828                 if (add_backref) {
1829                         ret = btrfs_insert_inode_ref(trans, root,
1830                                              dentry->d_name.name,
1831                                              dentry->d_name.len,
1832                                              inode->i_ino,
1833                                              dentry->d_parent->d_inode->i_ino);
1834                 }
1835                 parent_inode = dentry->d_parent->d_inode;
1836                 parent_inode->i_size += dentry->d_name.len * 2;
1837                 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
1838                 ret = btrfs_update_inode(trans, root,
1839                                          dentry->d_parent->d_inode);
1840         }
1841         return ret;
1842 }
1843
1844 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
1845                             struct dentry *dentry, struct inode *inode,
1846                             int backref)
1847 {
1848         int err = btrfs_add_link(trans, dentry, inode, backref);
1849         if (!err) {
1850                 d_instantiate(dentry, inode);
1851                 return 0;
1852         }
1853         if (err > 0)
1854                 err = -EEXIST;
1855         return err;
1856 }
1857
1858 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
1859                         int mode, dev_t rdev)
1860 {
1861         struct btrfs_trans_handle *trans;
1862         struct btrfs_root *root = BTRFS_I(dir)->root;
1863         struct inode *inode = NULL;
1864         int err;
1865         int drop_inode = 0;
1866         u64 objectid;
1867         unsigned long nr = 0;
1868
1869         if (!new_valid_dev(rdev))
1870                 return -EINVAL;
1871
1872         mutex_lock(&root->fs_info->fs_mutex);
1873         err = btrfs_check_free_space(root, 1, 0);
1874         if (err)
1875                 goto fail;
1876
1877         trans = btrfs_start_transaction(root, 1);
1878         btrfs_set_trans_block_group(trans, dir);
1879
1880         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
1881         if (err) {
1882                 err = -ENOSPC;
1883                 goto out_unlock;
1884         }
1885
1886         inode = btrfs_new_inode(trans, root, dentry->d_name.name,
1887                                 dentry->d_name.len,
1888                                 dentry->d_parent->d_inode->i_ino, objectid,
1889                                 BTRFS_I(dir)->block_group, mode);
1890         err = PTR_ERR(inode);
1891         if (IS_ERR(inode))
1892                 goto out_unlock;
1893
1894         btrfs_set_trans_block_group(trans, inode);
1895         err = btrfs_add_nondir(trans, dentry, inode, 0);
1896         if (err)
1897                 drop_inode = 1;
1898         else {
1899                 inode->i_op = &btrfs_special_inode_operations;
1900                 init_special_inode(inode, inode->i_mode, rdev);
1901                 btrfs_update_inode(trans, root, inode);
1902         }
1903         dir->i_sb->s_dirt = 1;
1904         btrfs_update_inode_block_group(trans, inode);
1905         btrfs_update_inode_block_group(trans, dir);
1906 out_unlock:
1907         nr = trans->blocks_used;
1908         btrfs_end_transaction(trans, root);
1909 fail:
1910         mutex_unlock(&root->fs_info->fs_mutex);
1911
1912         if (drop_inode) {
1913                 inode_dec_link_count(inode);
1914                 iput(inode);
1915         }
1916         btrfs_btree_balance_dirty(root, nr);
1917         btrfs_throttle(root);
1918         return err;
1919 }
1920
1921 static int btrfs_create(struct inode *dir, struct dentry *dentry,
1922                         int mode, struct nameidata *nd)
1923 {
1924         struct btrfs_trans_handle *trans;
1925         struct btrfs_root *root = BTRFS_I(dir)->root;
1926         struct inode *inode = NULL;
1927         int err;
1928         int drop_inode = 0;
1929         unsigned long nr = 0;
1930         u64 objectid;
1931
1932         mutex_lock(&root->fs_info->fs_mutex);
1933         err = btrfs_check_free_space(root, 1, 0);
1934         if (err)
1935                 goto fail;
1936         trans = btrfs_start_transaction(root, 1);
1937         btrfs_set_trans_block_group(trans, dir);
1938
1939         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
1940         if (err) {
1941                 err = -ENOSPC;
1942                 goto out_unlock;
1943         }
1944
1945         inode = btrfs_new_inode(trans, root, dentry->d_name.name,
1946                                 dentry->d_name.len,
1947                                 dentry->d_parent->d_inode->i_ino,
1948                                 objectid, BTRFS_I(dir)->block_group, mode);
1949         err = PTR_ERR(inode);
1950         if (IS_ERR(inode))
1951                 goto out_unlock;
1952
1953         btrfs_set_trans_block_group(trans, inode);
1954         err = btrfs_add_nondir(trans, dentry, inode, 0);
1955         if (err)
1956                 drop_inode = 1;
1957         else {
1958                 inode->i_mapping->a_ops = &btrfs_aops;
1959                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
1960                 inode->i_fop = &btrfs_file_operations;
1961                 inode->i_op = &btrfs_file_inode_operations;
1962                 extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
1963                 extent_io_tree_init(&BTRFS_I(inode)->io_tree,
1964                                      inode->i_mapping, GFP_NOFS);
1965                 extent_io_tree_init(&BTRFS_I(inode)->io_failure_tree,
1966                                      inode->i_mapping, GFP_NOFS);
1967                 BTRFS_I(inode)->delalloc_bytes = 0;
1968                 atomic_set(&BTRFS_I(inode)->ordered_writeback, 0);
1969                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
1970         }
1971         dir->i_sb->s_dirt = 1;
1972         btrfs_update_inode_block_group(trans, inode);
1973         btrfs_update_inode_block_group(trans, dir);
1974 out_unlock:
1975         nr = trans->blocks_used;
1976         btrfs_end_transaction(trans, root);
1977 fail:
1978         mutex_unlock(&root->fs_info->fs_mutex);
1979
1980         if (drop_inode) {
1981                 inode_dec_link_count(inode);
1982                 iput(inode);
1983         }
1984         btrfs_btree_balance_dirty(root, nr);
1985         btrfs_throttle(root);
1986         return err;
1987 }
1988
1989 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
1990                       struct dentry *dentry)
1991 {
1992         struct btrfs_trans_handle *trans;
1993         struct btrfs_root *root = BTRFS_I(dir)->root;
1994         struct inode *inode = old_dentry->d_inode;
1995         unsigned long nr = 0;
1996         int err;
1997         int drop_inode = 0;
1998
1999         if (inode->i_nlink == 0)
2000                 return -ENOENT;
2001
2002 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,18)
2003         inode->i_nlink++;
2004 #else
2005         inc_nlink(inode);
2006 #endif
2007         mutex_lock(&root->fs_info->fs_mutex);
2008         err = btrfs_check_free_space(root, 1, 0);
2009         if (err)
2010                 goto fail;
2011         trans = btrfs_start_transaction(root, 1);
2012
2013         btrfs_set_trans_block_group(trans, dir);
2014         atomic_inc(&inode->i_count);
2015         err = btrfs_add_nondir(trans, dentry, inode, 1);
2016
2017         if (err)
2018                 drop_inode = 1;
2019
2020         dir->i_sb->s_dirt = 1;
2021         btrfs_update_inode_block_group(trans, dir);
2022         err = btrfs_update_inode(trans, root, inode);
2023
2024         if (err)
2025                 drop_inode = 1;
2026
2027         nr = trans->blocks_used;
2028         btrfs_end_transaction(trans, root);
2029 fail:
2030         mutex_unlock(&root->fs_info->fs_mutex);
2031
2032         if (drop_inode) {
2033                 inode_dec_link_count(inode);
2034                 iput(inode);
2035         }
2036         btrfs_btree_balance_dirty(root, nr);
2037         btrfs_throttle(root);
2038         return err;
2039 }
2040
2041 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2042 {
2043         struct inode *inode = NULL;
2044         struct btrfs_trans_handle *trans;
2045         struct btrfs_root *root = BTRFS_I(dir)->root;
2046         int err = 0;
2047         int drop_on_err = 0;
2048         u64 objectid = 0;
2049         unsigned long nr = 1;
2050
2051         mutex_lock(&root->fs_info->fs_mutex);
2052         err = btrfs_check_free_space(root, 1, 0);
2053         if (err)
2054                 goto out_unlock;
2055
2056         trans = btrfs_start_transaction(root, 1);
2057         btrfs_set_trans_block_group(trans, dir);
2058
2059         if (IS_ERR(trans)) {
2060                 err = PTR_ERR(trans);
2061                 goto out_unlock;
2062         }
2063
2064         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
2065         if (err) {
2066                 err = -ENOSPC;
2067                 goto out_unlock;
2068         }
2069
2070         inode = btrfs_new_inode(trans, root, dentry->d_name.name,
2071                                 dentry->d_name.len,
2072                                 dentry->d_parent->d_inode->i_ino, objectid,
2073                                 BTRFS_I(dir)->block_group, S_IFDIR | mode);
2074         if (IS_ERR(inode)) {
2075                 err = PTR_ERR(inode);
2076                 goto out_fail;
2077         }
2078
2079         drop_on_err = 1;
2080         inode->i_op = &btrfs_dir_inode_operations;
2081         inode->i_fop = &btrfs_dir_file_operations;
2082         btrfs_set_trans_block_group(trans, inode);
2083
2084         inode->i_size = 0;
2085         err = btrfs_update_inode(trans, root, inode);
2086         if (err)
2087                 goto out_fail;
2088
2089         err = btrfs_add_link(trans, dentry, inode, 0);
2090         if (err)
2091                 goto out_fail;
2092
2093         d_instantiate(dentry, inode);
2094         drop_on_err = 0;
2095         dir->i_sb->s_dirt = 1;
2096         btrfs_update_inode_block_group(trans, inode);
2097         btrfs_update_inode_block_group(trans, dir);
2098
2099 out_fail:
2100         nr = trans->blocks_used;
2101         btrfs_end_transaction(trans, root);
2102
2103 out_unlock:
2104         mutex_unlock(&root->fs_info->fs_mutex);
2105         if (drop_on_err)
2106                 iput(inode);
2107         btrfs_btree_balance_dirty(root, nr);
2108         btrfs_throttle(root);
2109         return err;
2110 }
2111
2112 static int merge_extent_mapping(struct extent_map_tree *em_tree,
2113                                 struct extent_map *existing,
2114                                 struct extent_map *em)
2115 {
2116         u64 start_diff;
2117         u64 new_end;
2118         int ret = 0;
2119         int real_blocks = existing->block_start < EXTENT_MAP_LAST_BYTE;
2120
2121         if (real_blocks && em->block_start >= EXTENT_MAP_LAST_BYTE)
2122                 goto invalid;
2123
2124         if (!real_blocks && em->block_start != existing->block_start)
2125                 goto invalid;
2126
2127         new_end = max(existing->start + existing->len, em->start + em->len);
2128
2129         if (existing->start >= em->start) {
2130                 if (em->start + em->len < existing->start)
2131                         goto invalid;
2132
2133                 start_diff = existing->start - em->start;
2134                 if (real_blocks && em->block_start + start_diff !=
2135                     existing->block_start)
2136                         goto invalid;
2137
2138                 em->len = new_end - em->start;
2139
2140                 remove_extent_mapping(em_tree, existing);
2141                 /* free for the tree */
2142                 free_extent_map(existing);
2143                 ret = add_extent_mapping(em_tree, em);
2144
2145         } else if (em->start > existing->start) {
2146
2147                 if (existing->start + existing->len < em->start)
2148                         goto invalid;
2149
2150                 start_diff = em->start - existing->start;
2151                 if (real_blocks && existing->block_start + start_diff !=
2152                     em->block_start)
2153                         goto invalid;
2154
2155                 remove_extent_mapping(em_tree, existing);
2156                 em->block_start = existing->block_start;
2157                 em->start = existing->start;
2158                 em->len = new_end - existing->start;
2159                 free_extent_map(existing);
2160
2161                 ret = add_extent_mapping(em_tree, em);
2162         } else {
2163                 goto invalid;
2164         }
2165         return ret;
2166
2167 invalid:
2168         printk("invalid extent map merge [%Lu %Lu %Lu] [%Lu %Lu %Lu]\n",
2169                existing->start, existing->len, existing->block_start,
2170                em->start, em->len, em->block_start);
2171         return -EIO;
2172 }
2173
2174 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
2175                                     size_t pg_offset, u64 start, u64 len,
2176                                     int create)
2177 {
2178         int ret;
2179         int err = 0;
2180         u64 bytenr;
2181         u64 extent_start = 0;
2182         u64 extent_end = 0;
2183         u64 objectid = inode->i_ino;
2184         u32 found_type;
2185         struct btrfs_path *path;
2186         struct btrfs_root *root = BTRFS_I(inode)->root;
2187         struct btrfs_file_extent_item *item;
2188         struct extent_buffer *leaf;
2189         struct btrfs_key found_key;
2190         struct extent_map *em = NULL;
2191         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2192         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2193         struct btrfs_trans_handle *trans = NULL;
2194
2195         path = btrfs_alloc_path();
2196         BUG_ON(!path);
2197         mutex_lock(&root->fs_info->fs_mutex);
2198
2199 again:
2200         spin_lock(&em_tree->lock);
2201         em = lookup_extent_mapping(em_tree, start, len);
2202         if (em)
2203                 em->bdev = root->fs_info->fs_devices->latest_bdev;
2204         spin_unlock(&em_tree->lock);
2205
2206         if (em) {
2207                 if (em->start > start || em->start + em->len <= start)
2208                         free_extent_map(em);
2209                 else if (em->block_start == EXTENT_MAP_INLINE && page)
2210                         free_extent_map(em);
2211                 else
2212                         goto out;
2213         }
2214         em = alloc_extent_map(GFP_NOFS);
2215         if (!em) {
2216                 err = -ENOMEM;
2217                 goto out;
2218         }
2219
2220         em->start = EXTENT_MAP_HOLE;
2221         em->len = (u64)-1;
2222         em->bdev = root->fs_info->fs_devices->latest_bdev;
2223         ret = btrfs_lookup_file_extent(trans, root, path,
2224                                        objectid, start, trans != NULL);
2225         if (ret < 0) {
2226                 err = ret;
2227                 goto out;
2228         }
2229
2230         if (ret != 0) {
2231                 if (path->slots[0] == 0)
2232                         goto not_found;
2233                 path->slots[0]--;
2234         }
2235
2236         leaf = path->nodes[0];
2237         item = btrfs_item_ptr(leaf, path->slots[0],
2238                               struct btrfs_file_extent_item);
2239         /* are we inside the extent that was found? */
2240         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2241         found_type = btrfs_key_type(&found_key);
2242         if (found_key.objectid != objectid ||
2243             found_type != BTRFS_EXTENT_DATA_KEY) {
2244                 goto not_found;
2245         }
2246
2247         found_type = btrfs_file_extent_type(leaf, item);
2248         extent_start = found_key.offset;
2249         if (found_type == BTRFS_FILE_EXTENT_REG) {
2250                 extent_end = extent_start +
2251                        btrfs_file_extent_num_bytes(leaf, item);
2252                 err = 0;
2253                 if (start < extent_start || start >= extent_end) {
2254                         em->start = start;
2255                         if (start < extent_start) {
2256                                 if (start + len <= extent_start)
2257                                         goto not_found;
2258                                 em->len = extent_end - extent_start;
2259                         } else {
2260                                 em->len = len;
2261                         }
2262                         goto not_found_em;
2263                 }
2264                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
2265                 if (bytenr == 0) {
2266                         em->start = extent_start;
2267                         em->len = extent_end - extent_start;
2268                         em->block_start = EXTENT_MAP_HOLE;
2269                         goto insert;
2270                 }
2271                 bytenr += btrfs_file_extent_offset(leaf, item);
2272                 em->block_start = bytenr;
2273                 em->start = extent_start;
2274                 em->len = extent_end - extent_start;
2275                 goto insert;
2276         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
2277                 u64 page_start;
2278                 unsigned long ptr;
2279                 char *map;
2280                 size_t size;
2281                 size_t extent_offset;
2282                 size_t copy_size;
2283
2284                 size = btrfs_file_extent_inline_len(leaf, btrfs_item_nr(leaf,
2285                                                     path->slots[0]));
2286                 extent_end = (extent_start + size + root->sectorsize - 1) &
2287                         ~((u64)root->sectorsize - 1);
2288                 if (start < extent_start || start >= extent_end) {
2289                         em->start = start;
2290                         if (start < extent_start) {
2291                                 if (start + len <= extent_start)
2292                                         goto not_found;
2293                                 em->len = extent_end - extent_start;
2294                         } else {
2295                                 em->len = len;
2296                         }
2297                         goto not_found_em;
2298                 }
2299                 em->block_start = EXTENT_MAP_INLINE;
2300
2301                 if (!page) {
2302                         em->start = extent_start;
2303                         em->len = size;
2304                         goto out;
2305                 }
2306
2307                 page_start = page_offset(page) + pg_offset;
2308                 extent_offset = page_start - extent_start;
2309                 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
2310                                 size - extent_offset);
2311                 em->start = extent_start + extent_offset;
2312                 em->len = (copy_size + root->sectorsize - 1) &
2313                         ~((u64)root->sectorsize - 1);
2314                 map = kmap(page);
2315                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
2316                 if (create == 0 && !PageUptodate(page)) {
2317                         read_extent_buffer(leaf, map + pg_offset, ptr,
2318                                            copy_size);
2319                         flush_dcache_page(page);
2320                 } else if (create && PageUptodate(page)) {
2321                         if (!trans) {
2322                                 kunmap(page);
2323                                 free_extent_map(em);
2324                                 em = NULL;
2325                                 btrfs_release_path(root, path);
2326                                 trans = btrfs_start_transaction(root, 1);
2327                                 goto again;
2328                         }
2329                         write_extent_buffer(leaf, map + pg_offset, ptr,
2330                                             copy_size);
2331                         btrfs_mark_buffer_dirty(leaf);
2332                 }
2333                 kunmap(page);
2334                 set_extent_uptodate(io_tree, em->start,
2335                                     extent_map_end(em) - 1, GFP_NOFS);
2336                 goto insert;
2337         } else {
2338                 printk("unkknown found_type %d\n", found_type);
2339                 WARN_ON(1);
2340         }
2341 not_found:
2342         em->start = start;
2343         em->len = len;
2344 not_found_em:
2345         em->block_start = EXTENT_MAP_HOLE;
2346 insert:
2347         btrfs_release_path(root, path);
2348         if (em->start > start || extent_map_end(em) <= start) {
2349                 printk("bad extent! em: [%Lu %Lu] passed [%Lu %Lu]\n", em->start, em->len, start, len);
2350                 err = -EIO;
2351                 goto out;
2352         }
2353
2354         err = 0;
2355         spin_lock(&em_tree->lock);
2356         ret = add_extent_mapping(em_tree, em);
2357         /* it is possible that someone inserted the extent into the tree
2358          * while we had the lock dropped.  It is also possible that
2359          * an overlapping map exists in the tree
2360          */
2361         if (ret == -EEXIST) {
2362                 struct extent_map *existing;
2363                 existing = lookup_extent_mapping(em_tree, start, len);
2364                 if (existing && (existing->start > start ||
2365                     existing->start + existing->len <= start)) {
2366                         free_extent_map(existing);
2367                         existing = NULL;
2368                 }
2369                 if (!existing) {
2370                         existing = lookup_extent_mapping(em_tree, em->start,
2371                                                          em->len);
2372                         if (existing) {
2373                                 err = merge_extent_mapping(em_tree, existing,
2374                                                            em);
2375                                 free_extent_map(existing);
2376                                 if (err) {
2377                                         free_extent_map(em);
2378                                         em = NULL;
2379                                 }
2380                         } else {
2381                                 err = -EIO;
2382                                 printk("failing to insert %Lu %Lu\n",
2383                                        start, len);
2384                                 free_extent_map(em);
2385                                 em = NULL;
2386                         }
2387                 } else {
2388                         free_extent_map(em);
2389                         em = existing;
2390                 }
2391         }
2392         spin_unlock(&em_tree->lock);
2393 out:
2394         btrfs_free_path(path);
2395         if (trans) {
2396                 ret = btrfs_end_transaction(trans, root);
2397                 if (!err)
2398                         err = ret;
2399         }
2400         mutex_unlock(&root->fs_info->fs_mutex);
2401         if (err) {
2402                 free_extent_map(em);
2403                 WARN_ON(1);
2404                 return ERR_PTR(err);
2405         }
2406         return em;
2407 }
2408
2409 #if 0 /* waiting for O_DIRECT reads */
2410 static int btrfs_get_block(struct inode *inode, sector_t iblock,
2411                         struct buffer_head *bh_result, int create)
2412 {
2413         struct extent_map *em;
2414         u64 start = (u64)iblock << inode->i_blkbits;
2415         struct btrfs_multi_bio *multi = NULL;
2416         struct btrfs_root *root = BTRFS_I(inode)->root;
2417         u64 len;
2418         u64 logical;
2419         u64 map_length;
2420         int ret = 0;
2421
2422         em = btrfs_get_extent(inode, NULL, 0, start, bh_result->b_size, 0);
2423
2424         if (!em || IS_ERR(em))
2425                 goto out;
2426
2427         if (em->start > start || em->start + em->len <= start) {
2428             goto out;
2429         }
2430
2431         if (em->block_start == EXTENT_MAP_INLINE) {
2432                 ret = -EINVAL;
2433                 goto out;
2434         }
2435
2436         len = em->start + em->len - start;
2437         len = min_t(u64, len, INT_LIMIT(typeof(bh_result->b_size)));
2438
2439         if (em->block_start == EXTENT_MAP_HOLE ||
2440             em->block_start == EXTENT_MAP_DELALLOC) {
2441                 bh_result->b_size = len;
2442                 goto out;
2443         }
2444
2445         logical = start - em->start;
2446         logical = em->block_start + logical;
2447
2448         map_length = len;
2449         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
2450                               logical, &map_length, &multi, 0);
2451         BUG_ON(ret);
2452         bh_result->b_blocknr = multi->stripes[0].physical >> inode->i_blkbits;
2453         bh_result->b_size = min(map_length, len);
2454
2455         bh_result->b_bdev = multi->stripes[0].dev->bdev;
2456         set_buffer_mapped(bh_result);
2457         kfree(multi);
2458 out:
2459         free_extent_map(em);
2460         return ret;
2461 }
2462 #endif
2463
2464 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
2465                         const struct iovec *iov, loff_t offset,
2466                         unsigned long nr_segs)
2467 {
2468         return -EINVAL;
2469 #if 0
2470         struct file *file = iocb->ki_filp;
2471         struct inode *inode = file->f_mapping->host;
2472
2473         if (rw == WRITE)
2474                 return -EINVAL;
2475
2476         return blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
2477                                   offset, nr_segs, btrfs_get_block, NULL);
2478 #endif
2479 }
2480
2481 static sector_t btrfs_bmap(struct address_space *mapping, sector_t iblock)
2482 {
2483         return extent_bmap(mapping, iblock, btrfs_get_extent);
2484 }
2485
2486 int btrfs_readpage(struct file *file, struct page *page)
2487 {
2488         struct extent_io_tree *tree;
2489         tree = &BTRFS_I(page->mapping->host)->io_tree;
2490         return extent_read_full_page(tree, page, btrfs_get_extent);
2491 }
2492
2493 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
2494 {
2495         struct extent_io_tree *tree;
2496
2497
2498         if (current->flags & PF_MEMALLOC) {
2499                 redirty_page_for_writepage(wbc, page);
2500                 unlock_page(page);
2501                 return 0;
2502         }
2503         tree = &BTRFS_I(page->mapping->host)->io_tree;
2504         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
2505 }
2506
2507 static int btrfs_writepages(struct address_space *mapping,
2508                             struct writeback_control *wbc)
2509 {
2510         struct extent_io_tree *tree;
2511         tree = &BTRFS_I(mapping->host)->io_tree;
2512         return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
2513 }
2514
2515 static int
2516 btrfs_readpages(struct file *file, struct address_space *mapping,
2517                 struct list_head *pages, unsigned nr_pages)
2518 {
2519         struct extent_io_tree *tree;
2520         tree = &BTRFS_I(mapping->host)->io_tree;
2521         return extent_readpages(tree, mapping, pages, nr_pages,
2522                                 btrfs_get_extent);
2523 }
2524
2525 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
2526 {
2527         struct extent_io_tree *tree;
2528         struct extent_map_tree *map;
2529         int ret;
2530
2531         tree = &BTRFS_I(page->mapping->host)->io_tree;
2532         map = &BTRFS_I(page->mapping->host)->extent_tree;
2533         ret = try_release_extent_mapping(map, tree, page, gfp_flags);
2534         if (ret == 1) {
2535                 invalidate_extent_lru(tree, page_offset(page), PAGE_CACHE_SIZE);
2536                 ClearPagePrivate(page);
2537                 set_page_private(page, 0);
2538                 page_cache_release(page);
2539         }
2540         return ret;
2541 }
2542
2543 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
2544 {
2545         struct extent_io_tree *tree;
2546
2547         tree = &BTRFS_I(page->mapping->host)->io_tree;
2548         extent_invalidatepage(tree, page, offset);
2549         btrfs_releasepage(page, GFP_NOFS);
2550         if (PagePrivate(page)) {
2551                 invalidate_extent_lru(tree, page_offset(page), PAGE_CACHE_SIZE);
2552                 ClearPagePrivate(page);
2553                 set_page_private(page, 0);
2554                 page_cache_release(page);
2555         }
2556 }
2557
2558 /*
2559  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
2560  * called from a page fault handler when a page is first dirtied. Hence we must
2561  * be careful to check for EOF conditions here. We set the page up correctly
2562  * for a written page which means we get ENOSPC checking when writing into
2563  * holes and correct delalloc and unwritten extent mapping on filesystems that
2564  * support these features.
2565  *
2566  * We are not allowed to take the i_mutex here so we have to play games to
2567  * protect against truncate races as the page could now be beyond EOF.  Because
2568  * vmtruncate() writes the inode size before removing pages, once we have the
2569  * page lock we can determine safely if the page is beyond EOF. If it is not
2570  * beyond EOF, then the page is guaranteed safe against truncation until we
2571  * unlock the page.
2572  */
2573 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct page *page)
2574 {
2575         struct inode *inode = fdentry(vma->vm_file)->d_inode;
2576         struct btrfs_root *root = BTRFS_I(inode)->root;
2577         unsigned long end;
2578         loff_t size;
2579         int ret;
2580         u64 page_start;
2581
2582         mutex_lock(&root->fs_info->fs_mutex);
2583         ret = btrfs_check_free_space(root, PAGE_CACHE_SIZE, 0);
2584         mutex_unlock(&root->fs_info->fs_mutex);
2585         if (ret)
2586                 goto out;
2587
2588         ret = -EINVAL;
2589
2590         lock_page(page);
2591         wait_on_page_writeback(page);
2592         size = i_size_read(inode);
2593         page_start = (u64)page->index << PAGE_CACHE_SHIFT;
2594
2595         if ((page->mapping != inode->i_mapping) ||
2596             (page_start > size)) {
2597                 /* page got truncated out from underneath us */
2598                 goto out_unlock;
2599         }
2600
2601         /* page is wholly or partially inside EOF */
2602         if (page_start + PAGE_CACHE_SIZE > size)
2603                 end = size & ~PAGE_CACHE_MASK;
2604         else
2605                 end = PAGE_CACHE_SIZE;
2606
2607         ret = btrfs_cow_one_page(inode, page, end);
2608
2609 out_unlock:
2610         unlock_page(page);
2611 out:
2612         return ret;
2613 }
2614
2615 static void btrfs_truncate(struct inode *inode)
2616 {
2617         struct btrfs_root *root = BTRFS_I(inode)->root;
2618         int ret;
2619         struct btrfs_trans_handle *trans;
2620         unsigned long nr;
2621
2622         if (!S_ISREG(inode->i_mode))
2623                 return;
2624         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
2625                 return;
2626
2627         btrfs_truncate_page(inode->i_mapping, inode->i_size);
2628
2629         mutex_lock(&root->fs_info->fs_mutex);
2630         trans = btrfs_start_transaction(root, 1);
2631         btrfs_set_trans_block_group(trans, inode);
2632
2633         /* FIXME, add redo link to tree so we don't leak on crash */
2634         ret = btrfs_truncate_in_trans(trans, root, inode,
2635                                       BTRFS_EXTENT_DATA_KEY);
2636         btrfs_update_inode(trans, root, inode);
2637         nr = trans->blocks_used;
2638
2639         ret = btrfs_end_transaction(trans, root);
2640         BUG_ON(ret);
2641         mutex_unlock(&root->fs_info->fs_mutex);
2642         btrfs_btree_balance_dirty(root, nr);
2643         btrfs_throttle(root);
2644 }
2645
2646 static int noinline create_subvol(struct btrfs_root *root, char *name,
2647                                   int namelen)
2648 {
2649         struct btrfs_trans_handle *trans;
2650         struct btrfs_key key;
2651         struct btrfs_root_item root_item;
2652         struct btrfs_inode_item *inode_item;
2653         struct extent_buffer *leaf;
2654         struct btrfs_root *new_root = root;
2655         struct inode *inode;
2656         struct inode *dir;
2657         int ret;
2658         int err;
2659         u64 objectid;
2660         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
2661         unsigned long nr = 1;
2662
2663         mutex_lock(&root->fs_info->fs_mutex);
2664         ret = btrfs_check_free_space(root, 1, 0);
2665         if (ret)
2666                 goto fail_commit;
2667
2668         trans = btrfs_start_transaction(root, 1);
2669         BUG_ON(!trans);
2670
2671         ret = btrfs_find_free_objectid(trans, root->fs_info->tree_root,
2672                                        0, &objectid);
2673         if (ret)
2674                 goto fail;
2675
2676         leaf = __btrfs_alloc_free_block(trans, root, root->leafsize,
2677                                         objectid, trans->transid, 0, 0,
2678                                         0, 0);
2679         if (IS_ERR(leaf))
2680                 return PTR_ERR(leaf);
2681
2682         btrfs_set_header_nritems(leaf, 0);
2683         btrfs_set_header_level(leaf, 0);
2684         btrfs_set_header_bytenr(leaf, leaf->start);
2685         btrfs_set_header_generation(leaf, trans->transid);
2686         btrfs_set_header_owner(leaf, objectid);
2687
2688         write_extent_buffer(leaf, root->fs_info->fsid,
2689                             (unsigned long)btrfs_header_fsid(leaf),
2690                             BTRFS_FSID_SIZE);
2691         btrfs_mark_buffer_dirty(leaf);
2692
2693         inode_item = &root_item.inode;
2694         memset(inode_item, 0, sizeof(*inode_item));
2695         inode_item->generation = cpu_to_le64(1);
2696         inode_item->size = cpu_to_le64(3);
2697         inode_item->nlink = cpu_to_le32(1);
2698         inode_item->nblocks = cpu_to_le64(1);
2699         inode_item->mode = cpu_to_le32(S_IFDIR | 0755);
2700
2701         btrfs_set_root_bytenr(&root_item, leaf->start);
2702         btrfs_set_root_level(&root_item, 0);
2703         btrfs_set_root_refs(&root_item, 1);
2704         btrfs_set_root_used(&root_item, 0);
2705
2706         memset(&root_item.drop_progress, 0, sizeof(root_item.drop_progress));
2707         root_item.drop_level = 0;
2708
2709         free_extent_buffer(leaf);
2710         leaf = NULL;
2711
2712         btrfs_set_root_dirid(&root_item, new_dirid);
2713
2714         key.objectid = objectid;
2715         key.offset = 1;
2716         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
2717         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
2718                                 &root_item);
2719         if (ret)
2720                 goto fail;
2721
2722         /*
2723          * insert the directory item
2724          */
2725         key.offset = (u64)-1;
2726         dir = root->fs_info->sb->s_root->d_inode;
2727         ret = btrfs_insert_dir_item(trans, root->fs_info->tree_root,
2728                                     name, namelen, dir->i_ino, &key,
2729                                     BTRFS_FT_DIR);
2730         if (ret)
2731                 goto fail;
2732
2733         ret = btrfs_insert_inode_ref(trans, root->fs_info->tree_root,
2734                              name, namelen, objectid,
2735                              root->fs_info->sb->s_root->d_inode->i_ino);
2736         if (ret)
2737                 goto fail;
2738
2739         ret = btrfs_commit_transaction(trans, root);
2740         if (ret)
2741                 goto fail_commit;
2742
2743         new_root = btrfs_read_fs_root(root->fs_info, &key, name, namelen);
2744         BUG_ON(!new_root);
2745
2746         trans = btrfs_start_transaction(new_root, 1);
2747         BUG_ON(!trans);
2748
2749         inode = btrfs_new_inode(trans, new_root, "..", 2, new_dirid,
2750                                 new_dirid,
2751                                 BTRFS_I(dir)->block_group, S_IFDIR | 0700);
2752         if (IS_ERR(inode))
2753                 goto fail;
2754         inode->i_op = &btrfs_dir_inode_operations;
2755         inode->i_fop = &btrfs_dir_file_operations;
2756         new_root->inode = inode;
2757
2758         ret = btrfs_insert_inode_ref(trans, new_root, "..", 2, new_dirid,
2759                                      new_dirid);
2760         inode->i_nlink = 1;
2761         inode->i_size = 0;
2762         ret = btrfs_update_inode(trans, new_root, inode);
2763         if (ret)
2764                 goto fail;
2765 fail:
2766         nr = trans->blocks_used;
2767         err = btrfs_commit_transaction(trans, new_root);
2768         if (err && !ret)
2769                 ret = err;
2770 fail_commit:
2771         mutex_unlock(&root->fs_info->fs_mutex);
2772         btrfs_btree_balance_dirty(root, nr);
2773         btrfs_throttle(root);
2774         return ret;
2775 }
2776
2777 static int create_snapshot(struct btrfs_root *root, char *name, int namelen)
2778 {
2779         struct btrfs_pending_snapshot *pending_snapshot;
2780         struct btrfs_trans_handle *trans;
2781         int ret;
2782         int err;
2783         unsigned long nr = 0;
2784
2785         if (!root->ref_cows)
2786                 return -EINVAL;
2787
2788         mutex_lock(&root->fs_info->fs_mutex);
2789         ret = btrfs_check_free_space(root, 1, 0);
2790         if (ret)
2791                 goto fail_unlock;
2792
2793         pending_snapshot = kmalloc(sizeof(*pending_snapshot), GFP_NOFS);
2794         if (!pending_snapshot) {
2795                 ret = -ENOMEM;
2796                 goto fail_unlock;
2797         }
2798         pending_snapshot->name = kmalloc(namelen + 1, GFP_NOFS);
2799         if (!pending_snapshot->name) {
2800                 ret = -ENOMEM;
2801                 kfree(pending_snapshot);
2802                 goto fail_unlock;
2803         }
2804         memcpy(pending_snapshot->name, name, namelen);
2805         pending_snapshot->name[namelen] = '\0';
2806         trans = btrfs_start_transaction(root, 1);
2807         BUG_ON(!trans);
2808         pending_snapshot->root = root;
2809         list_add(&pending_snapshot->list,
2810                  &trans->transaction->pending_snapshots);
2811         ret = btrfs_update_inode(trans, root, root->inode);
2812         err = btrfs_commit_transaction(trans, root);
2813
2814 fail_unlock:
2815         mutex_unlock(&root->fs_info->fs_mutex);
2816         btrfs_btree_balance_dirty(root, nr);
2817         btrfs_throttle(root);
2818         return ret;
2819 }
2820
2821 unsigned long btrfs_force_ra(struct address_space *mapping,
2822                               struct file_ra_state *ra, struct file *file,
2823                               pgoff_t offset, pgoff_t last_index)
2824 {
2825         pgoff_t req_size = last_index - offset + 1;
2826
2827 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
2828         offset = page_cache_readahead(mapping, ra, file, offset, req_size);
2829         return offset;
2830 #else
2831         page_cache_sync_readahead(mapping, ra, file, offset, req_size);
2832         return offset + req_size;
2833 #endif
2834 }
2835
2836 int btrfs_defrag_file(struct file *file) {
2837         struct inode *inode = fdentry(file)->d_inode;
2838         struct btrfs_root *root = BTRFS_I(inode)->root;
2839         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2840         struct page *page;
2841         unsigned long last_index;
2842         unsigned long ra_pages = root->fs_info->bdi.ra_pages;
2843         unsigned long total_read = 0;
2844         u64 page_start;
2845         u64 page_end;
2846         unsigned long i;
2847         int ret;
2848
2849         mutex_lock(&root->fs_info->fs_mutex);
2850         ret = btrfs_check_free_space(root, inode->i_size, 0);
2851         mutex_unlock(&root->fs_info->fs_mutex);
2852         if (ret)
2853                 return -ENOSPC;
2854
2855         mutex_lock(&inode->i_mutex);
2856         last_index = inode->i_size >> PAGE_CACHE_SHIFT;
2857         for (i = 0; i <= last_index; i++) {
2858                 if (total_read % ra_pages == 0) {
2859                         btrfs_force_ra(inode->i_mapping, &file->f_ra, file, i,
2860                                        min(last_index, i + ra_pages - 1));
2861                 }
2862                 total_read++;
2863                 page = grab_cache_page(inode->i_mapping, i);
2864                 if (!page)
2865                         goto out_unlock;
2866                 if (!PageUptodate(page)) {
2867                         btrfs_readpage(NULL, page);
2868                         lock_page(page);
2869                         if (!PageUptodate(page)) {
2870                                 unlock_page(page);
2871                                 page_cache_release(page);
2872                                 goto out_unlock;
2873                         }
2874                 }
2875
2876 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,18)
2877                 ClearPageDirty(page);
2878 #else
2879                 cancel_dirty_page(page, PAGE_CACHE_SIZE);
2880 #endif
2881                 wait_on_page_writeback(page);
2882                 set_page_extent_mapped(page);
2883
2884                 page_start = (u64)page->index << PAGE_CACHE_SHIFT;
2885                 page_end = page_start + PAGE_CACHE_SIZE - 1;
2886
2887                 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
2888                 set_extent_delalloc(io_tree, page_start,
2889                                     page_end, GFP_NOFS);
2890
2891                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
2892                 set_page_dirty(page);
2893                 unlock_page(page);
2894                 page_cache_release(page);
2895                 balance_dirty_pages_ratelimited_nr(inode->i_mapping, 1);
2896         }
2897
2898 out_unlock:
2899         mutex_unlock(&inode->i_mutex);
2900         return 0;
2901 }
2902
2903 static int btrfs_ioctl_resize(struct btrfs_root *root, void __user *arg)
2904 {
2905         u64 new_size;
2906         u64 old_size;
2907         u64 devid = 1;
2908         struct btrfs_ioctl_vol_args *vol_args;
2909         struct btrfs_trans_handle *trans;
2910         struct btrfs_device *device = NULL;
2911         char *sizestr;
2912         char *devstr = NULL;
2913         int ret = 0;
2914         int namelen;
2915         int mod = 0;
2916
2917         vol_args = kmalloc(sizeof(*vol_args), GFP_NOFS);
2918
2919         if (!vol_args)
2920                 return -ENOMEM;
2921
2922         if (copy_from_user(vol_args, arg, sizeof(*vol_args))) {
2923                 ret = -EFAULT;
2924                 goto out;
2925         }
2926         namelen = strlen(vol_args->name);
2927         if (namelen > BTRFS_VOL_NAME_MAX) {
2928                 ret = -EINVAL;
2929                 goto out;
2930         }
2931
2932         mutex_lock(&root->fs_info->fs_mutex);
2933         sizestr = vol_args->name;
2934         devstr = strchr(sizestr, ':');
2935         if (devstr) {
2936                 char *end;
2937                 sizestr = devstr + 1;
2938                 *devstr = '\0';
2939                 devstr = vol_args->name;
2940                 devid = simple_strtoull(devstr, &end, 10);
2941 printk("resizing devid %Lu\n", devid);
2942         }
2943         device = btrfs_find_device(root, devid, NULL);
2944         if (!device) {
2945                 printk("resizer unable to find device %Lu\n", devid);
2946                 ret = -EINVAL;
2947                 goto out_unlock;
2948         }
2949         if (!strcmp(sizestr, "max"))
2950                 new_size = device->bdev->bd_inode->i_size;
2951         else {
2952                 if (sizestr[0] == '-') {
2953                         mod = -1;
2954                         sizestr++;
2955                 } else if (sizestr[0] == '+') {
2956                         mod = 1;
2957                         sizestr++;
2958                 }
2959                 new_size = btrfs_parse_size(sizestr);
2960                 if (new_size == 0) {
2961                         ret = -EINVAL;
2962                         goto out_unlock;
2963                 }
2964         }
2965
2966         old_size = device->total_bytes;
2967
2968         if (mod < 0) {
2969                 if (new_size > old_size) {
2970                         ret = -EINVAL;
2971                         goto out_unlock;
2972                 }
2973                 new_size = old_size - new_size;
2974         } else if (mod > 0) {
2975                 new_size = old_size + new_size;
2976         }
2977
2978         if (new_size < 256 * 1024 * 1024) {
2979                 ret = -EINVAL;
2980                 goto out_unlock;
2981         }
2982         if (new_size > device->bdev->bd_inode->i_size) {
2983                 ret = -EFBIG;
2984                 goto out_unlock;
2985         }
2986
2987         do_div(new_size, root->sectorsize);
2988         new_size *= root->sectorsize;
2989
2990 printk("new size for %s is %llu\n", device->name, (unsigned long long)new_size);
2991
2992         if (new_size > old_size) {
2993                 trans = btrfs_start_transaction(root, 1);
2994                 ret = btrfs_grow_device(trans, device, new_size);
2995                 btrfs_commit_transaction(trans, root);
2996         } else {
2997                 ret = btrfs_shrink_device(device, new_size);
2998         }
2999
3000 out_unlock:
3001         mutex_unlock(&root->fs_info->fs_mutex);
3002 out:
3003         kfree(vol_args);
3004         return ret;
3005 }
3006
3007 static int noinline btrfs_ioctl_snap_create(struct btrfs_root *root,
3008                                             void __user *arg)
3009 {
3010         struct btrfs_ioctl_vol_args *vol_args;
3011         struct btrfs_dir_item *di;
3012         struct btrfs_path *path;
3013         u64 root_dirid;
3014         int namelen;
3015         int ret;
3016
3017         vol_args = kmalloc(sizeof(*vol_args), GFP_NOFS);
3018
3019         if (!vol_args)
3020                 return -ENOMEM;
3021
3022         if (copy_from_user(vol_args, arg, sizeof(*vol_args))) {
3023                 ret = -EFAULT;
3024                 goto out;
3025         }
3026
3027         namelen = strlen(vol_args->name);
3028         if (namelen > BTRFS_VOL_NAME_MAX) {
3029                 ret = -EINVAL;
3030                 goto out;
3031         }
3032         if (strchr(vol_args->name, '/')) {
3033                 ret = -EINVAL;
3034                 goto out;
3035         }
3036
3037         path = btrfs_alloc_path();
3038         if (!path) {
3039                 ret = -ENOMEM;
3040                 goto out;
3041         }
3042
3043         root_dirid = root->fs_info->sb->s_root->d_inode->i_ino,
3044         mutex_lock(&root->fs_info->fs_mutex);
3045         di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root,
3046                             path, root_dirid,
3047                             vol_args->name, namelen, 0);
3048         mutex_unlock(&root->fs_info->fs_mutex);
3049         btrfs_free_path(path);
3050
3051         if (di && !IS_ERR(di)) {
3052                 ret = -EEXIST;
3053                 goto out;
3054         }
3055
3056         if (IS_ERR(di)) {
3057                 ret = PTR_ERR(di);
3058                 goto out;
3059         }
3060
3061         if (root == root->fs_info->tree_root)
3062                 ret = create_subvol(root, vol_args->name, namelen);
3063         else
3064                 ret = create_snapshot(root, vol_args->name, namelen);
3065 out:
3066         kfree(vol_args);
3067         return ret;
3068 }
3069
3070 static int btrfs_ioctl_defrag(struct file *file)
3071 {
3072         struct inode *inode = fdentry(file)->d_inode;
3073         struct btrfs_root *root = BTRFS_I(inode)->root;
3074
3075         switch (inode->i_mode & S_IFMT) {
3076         case S_IFDIR:
3077                 mutex_lock(&root->fs_info->fs_mutex);
3078                 btrfs_defrag_root(root, 0);
3079                 btrfs_defrag_root(root->fs_info->extent_root, 0);
3080                 mutex_unlock(&root->fs_info->fs_mutex);
3081                 break;
3082         case S_IFREG:
3083                 btrfs_defrag_file(file);
3084                 break;
3085         }
3086
3087         return 0;
3088 }
3089
3090 long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
3091 {
3092         struct btrfs_ioctl_vol_args *vol_args;
3093         int ret;
3094
3095         vol_args = kmalloc(sizeof(*vol_args), GFP_NOFS);
3096
3097         if (!vol_args)
3098                 return -ENOMEM;
3099
3100         if (copy_from_user(vol_args, arg, sizeof(*vol_args))) {
3101                 ret = -EFAULT;
3102                 goto out;
3103         }
3104         ret = btrfs_init_new_device(root, vol_args->name);
3105
3106 out:
3107         kfree(vol_args);
3108         return ret;
3109 }
3110
3111 long btrfs_ioctl_rm_dev(struct btrfs_root *root, void __user *arg)
3112 {
3113         struct btrfs_ioctl_vol_args *vol_args;
3114         int ret;
3115
3116         vol_args = kmalloc(sizeof(*vol_args), GFP_NOFS);
3117
3118         if (!vol_args)
3119                 return -ENOMEM;
3120
3121         if (copy_from_user(vol_args, arg, sizeof(*vol_args))) {
3122                 ret = -EFAULT;
3123                 goto out;
3124         }
3125         ret = btrfs_rm_device(root, vol_args->name);
3126
3127 out:
3128         kfree(vol_args);
3129         return ret;
3130 }
3131
3132 int dup_item_to_inode(struct btrfs_trans_handle *trans,
3133                        struct btrfs_root *root,
3134                        struct btrfs_path *path,
3135                        struct extent_buffer *leaf,
3136                        int slot,
3137                        struct btrfs_key *key,
3138                        u64 destino)
3139 {
3140         char *dup;
3141         int len = btrfs_item_size_nr(leaf, slot);
3142         struct btrfs_key ckey = *key;
3143         int ret = 0;
3144
3145         dup = kmalloc(len, GFP_NOFS);
3146         if (!dup)
3147                 return -ENOMEM;
3148
3149         read_extent_buffer(leaf, dup, btrfs_item_ptr_offset(leaf, slot), len);
3150         btrfs_release_path(root, path);
3151
3152         ckey.objectid = destino;
3153         ret = btrfs_insert_item(trans, root, &ckey, dup, len);
3154         kfree(dup);
3155         return ret;
3156 }
3157
3158 long btrfs_ioctl_clone(struct file *file, unsigned long src_fd)
3159 {
3160         struct inode *inode = fdentry(file)->d_inode;
3161         struct btrfs_root *root = BTRFS_I(inode)->root;
3162         struct file *src_file;
3163         struct inode *src;
3164         struct btrfs_trans_handle *trans;
3165         int ret;
3166         u64 pos;
3167         struct btrfs_path *path;
3168         struct btrfs_key key;
3169         struct extent_buffer *leaf;
3170         u32 nritems;
3171         int slot;
3172
3173         src_file = fget(src_fd);
3174         if (!src_file)
3175                 return -EBADF;
3176         src = src_file->f_dentry->d_inode;
3177
3178         ret = -EXDEV;
3179         if (src->i_sb != inode->i_sb)
3180                 goto out_fput;
3181
3182         if (inode < src) {
3183                 mutex_lock(&inode->i_mutex);
3184                 mutex_lock(&src->i_mutex);
3185         } else {
3186                 mutex_lock(&src->i_mutex);
3187                 mutex_lock(&inode->i_mutex);
3188         }
3189
3190         ret = -ENOTEMPTY;
3191         if (inode->i_size)
3192                 goto out_unlock;
3193
3194         /* do any pending delalloc/csum calc on src, one way or
3195            another, and lock file content */
3196         while (1) {
3197                 filemap_write_and_wait(src->i_mapping);
3198                 lock_extent(&BTRFS_I(src)->io_tree, 0, (u64)-1, GFP_NOFS);
3199                 if (BTRFS_I(src)->delalloc_bytes == 0)
3200                         break;
3201                 unlock_extent(&BTRFS_I(src)->io_tree, 0, (u64)-1, GFP_NOFS);
3202         }
3203
3204         mutex_lock(&root->fs_info->fs_mutex);
3205         trans = btrfs_start_transaction(root, 0);
3206         path = btrfs_alloc_path();
3207         if (!path) {
3208                 ret = -ENOMEM;
3209                 goto out;
3210         }
3211         key.offset = 0;
3212         key.type = BTRFS_EXTENT_DATA_KEY;
3213         key.objectid = src->i_ino;
3214         pos = 0;
3215         path->reada = 2;
3216
3217         while (1) {
3218                 /*
3219                  * note the key will change type as we walk through the
3220                  * tree.
3221                  */
3222                 ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
3223                 if (ret < 0)
3224                         goto out;
3225
3226                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3227                         ret = btrfs_next_leaf(root, path);
3228                         if (ret < 0)
3229                                 goto out;
3230                         if (ret > 0)
3231                                 break;
3232                 }
3233                 leaf = path->nodes[0];
3234                 slot = path->slots[0];
3235                 btrfs_item_key_to_cpu(leaf, &key, slot);
3236                 nritems = btrfs_header_nritems(leaf);
3237
3238                 if (btrfs_key_type(&key) > BTRFS_CSUM_ITEM_KEY ||
3239                     key.objectid != src->i_ino)
3240                         break;
3241
3242                 if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) {
3243                         struct btrfs_file_extent_item *extent;
3244                         int found_type;
3245                         pos = key.offset;
3246                         extent = btrfs_item_ptr(leaf, slot,
3247                                                 struct btrfs_file_extent_item);
3248                         found_type = btrfs_file_extent_type(leaf, extent);
3249                         if (found_type == BTRFS_FILE_EXTENT_REG) {
3250                                 u64 len = btrfs_file_extent_num_bytes(leaf,
3251                                                                       extent);
3252                                 u64 ds = btrfs_file_extent_disk_bytenr(leaf,
3253                                                                        extent);
3254                                 u64 dl = btrfs_file_extent_disk_num_bytes(leaf,
3255                                                                  extent);
3256                                 u64 off = btrfs_file_extent_offset(leaf,
3257                                                                    extent);
3258                                 btrfs_insert_file_extent(trans, root,
3259                                                          inode->i_ino, pos,
3260                                                          ds, dl, len, off);
3261                                 /* ds == 0 means there's a hole */
3262                                 if (ds != 0) {
3263                                         btrfs_inc_extent_ref(trans, root,
3264                                                      ds, dl,
3265                                                      root->root_key.objectid,
3266                                                      trans->transid,
3267                                                      inode->i_ino, pos);
3268                                 }
3269                                 pos = key.offset + len;
3270                         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
3271                                 ret = dup_item_to_inode(trans, root, path,
3272                                                         leaf, slot, &key,
3273                                                         inode->i_ino);
3274                                 if (ret)
3275                                         goto out;
3276                                 pos = key.offset + btrfs_item_size_nr(leaf,
3277                                                                       slot);
3278                         }
3279                 } else if (btrfs_key_type(&key) == BTRFS_CSUM_ITEM_KEY) {
3280                         ret = dup_item_to_inode(trans, root, path, leaf,
3281                                                 slot, &key, inode->i_ino);
3282
3283                         if (ret)
3284                                 goto out;
3285                 }
3286                 key.offset++;
3287                 btrfs_release_path(root, path);
3288         }
3289
3290         ret = 0;
3291 out:
3292         btrfs_free_path(path);
3293
3294         inode->i_blocks = src->i_blocks;
3295         i_size_write(inode, src->i_size);
3296         btrfs_update_inode(trans, root, inode);
3297
3298         unlock_extent(&BTRFS_I(src)->io_tree, 0, (u64)-1, GFP_NOFS);
3299
3300         btrfs_end_transaction(trans, root);
3301         mutex_unlock(&root->fs_info->fs_mutex);
3302
3303 out_unlock:
3304         mutex_unlock(&src->i_mutex);
3305         mutex_unlock(&inode->i_mutex);
3306 out_fput:
3307         fput(src_file);
3308         return ret;
3309 }
3310
3311 long btrfs_ioctl(struct file *file, unsigned int
3312                 cmd, unsigned long arg)
3313 {
3314         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
3315
3316         switch (cmd) {
3317         case BTRFS_IOC_SNAP_CREATE:
3318                 return btrfs_ioctl_snap_create(root, (void __user *)arg);
3319         case BTRFS_IOC_DEFRAG:
3320                 return btrfs_ioctl_defrag(file);
3321         case BTRFS_IOC_RESIZE:
3322                 return btrfs_ioctl_resize(root, (void __user *)arg);
3323         case BTRFS_IOC_ADD_DEV:
3324                 return btrfs_ioctl_add_dev(root, (void __user *)arg);
3325         case BTRFS_IOC_RM_DEV:
3326                 return btrfs_ioctl_rm_dev(root, (void __user *)arg);
3327         case BTRFS_IOC_BALANCE:
3328                 return btrfs_balance(root->fs_info->dev_root);
3329         case BTRFS_IOC_CLONE:
3330                 return btrfs_ioctl_clone(file, arg);
3331         }
3332
3333         return -ENOTTY;
3334 }
3335
3336 /*
3337  * Called inside transaction, so use GFP_NOFS
3338  */
3339 struct inode *btrfs_alloc_inode(struct super_block *sb)
3340 {
3341         struct btrfs_inode *ei;
3342
3343         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
3344         if (!ei)
3345                 return NULL;
3346         ei->last_trans = 0;
3347         ei->ordered_trans = 0;
3348         return &ei->vfs_inode;
3349 }
3350
3351 void btrfs_destroy_inode(struct inode *inode)
3352 {
3353         WARN_ON(!list_empty(&inode->i_dentry));
3354         WARN_ON(inode->i_data.nrpages);
3355
3356         btrfs_drop_extent_cache(inode, 0, (u64)-1);
3357         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
3358 }
3359
3360 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,23)
3361 static void init_once(struct kmem_cache * cachep, void *foo)
3362 #else
3363 static void init_once(void * foo, struct kmem_cache * cachep,
3364                       unsigned long flags)
3365 #endif
3366 {
3367         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
3368
3369         inode_init_once(&ei->vfs_inode);
3370 }
3371
3372 void btrfs_destroy_cachep(void)
3373 {
3374         if (btrfs_inode_cachep)
3375                 kmem_cache_destroy(btrfs_inode_cachep);
3376         if (btrfs_trans_handle_cachep)
3377                 kmem_cache_destroy(btrfs_trans_handle_cachep);
3378         if (btrfs_transaction_cachep)
3379                 kmem_cache_destroy(btrfs_transaction_cachep);
3380         if (btrfs_bit_radix_cachep)
3381                 kmem_cache_destroy(btrfs_bit_radix_cachep);
3382         if (btrfs_path_cachep)
3383                 kmem_cache_destroy(btrfs_path_cachep);
3384 }
3385
3386 struct kmem_cache *btrfs_cache_create(const char *name, size_t size,
3387                                        unsigned long extra_flags,
3388 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,23)
3389                                        void (*ctor)(struct kmem_cache *, void *)
3390 #else
3391                                        void (*ctor)(void *, struct kmem_cache *,
3392                                                     unsigned long)
3393 #endif
3394                                      )
3395 {
3396         return kmem_cache_create(name, size, 0, (SLAB_RECLAIM_ACCOUNT |
3397                                  SLAB_MEM_SPREAD | extra_flags), ctor
3398 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
3399                                  ,NULL
3400 #endif
3401                                 );
3402 }
3403
3404 int btrfs_init_cachep(void)
3405 {
3406         btrfs_inode_cachep = btrfs_cache_create("btrfs_inode_cache",
3407                                           sizeof(struct btrfs_inode),
3408                                           0, init_once);
3409         if (!btrfs_inode_cachep)
3410                 goto fail;
3411         btrfs_trans_handle_cachep =
3412                         btrfs_cache_create("btrfs_trans_handle_cache",
3413                                            sizeof(struct btrfs_trans_handle),
3414                                            0, NULL);
3415         if (!btrfs_trans_handle_cachep)
3416                 goto fail;
3417         btrfs_transaction_cachep = btrfs_cache_create("btrfs_transaction_cache",
3418                                              sizeof(struct btrfs_transaction),
3419                                              0, NULL);
3420         if (!btrfs_transaction_cachep)
3421                 goto fail;
3422         btrfs_path_cachep = btrfs_cache_create("btrfs_path_cache",
3423                                          sizeof(struct btrfs_path),
3424                                          0, NULL);
3425         if (!btrfs_path_cachep)
3426                 goto fail;
3427         btrfs_bit_radix_cachep = btrfs_cache_create("btrfs_radix", 256,
3428                                               SLAB_DESTROY_BY_RCU, NULL);
3429         if (!btrfs_bit_radix_cachep)
3430                 goto fail;
3431         return 0;
3432 fail:
3433         btrfs_destroy_cachep();
3434         return -ENOMEM;
3435 }
3436
3437 static int btrfs_getattr(struct vfsmount *mnt,
3438                          struct dentry *dentry, struct kstat *stat)
3439 {
3440         struct inode *inode = dentry->d_inode;
3441         generic_fillattr(inode, stat);
3442         stat->blksize = PAGE_CACHE_SIZE;
3443         stat->blocks = inode->i_blocks + (BTRFS_I(inode)->delalloc_bytes >> 9);
3444         return 0;
3445 }
3446
3447 static int btrfs_rename(struct inode * old_dir, struct dentry *old_dentry,
3448                            struct inode * new_dir,struct dentry *new_dentry)
3449 {
3450         struct btrfs_trans_handle *trans;
3451         struct btrfs_root *root = BTRFS_I(old_dir)->root;
3452         struct inode *new_inode = new_dentry->d_inode;
3453         struct inode *old_inode = old_dentry->d_inode;
3454         struct timespec ctime = CURRENT_TIME;
3455         struct btrfs_path *path;
3456         int ret;
3457
3458         if (S_ISDIR(old_inode->i_mode) && new_inode &&
3459             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) {
3460                 return -ENOTEMPTY;
3461         }
3462
3463         mutex_lock(&root->fs_info->fs_mutex);
3464         ret = btrfs_check_free_space(root, 1, 0);
3465         if (ret)
3466                 goto out_unlock;
3467
3468         trans = btrfs_start_transaction(root, 1);
3469
3470         btrfs_set_trans_block_group(trans, new_dir);
3471         path = btrfs_alloc_path();
3472         if (!path) {
3473                 ret = -ENOMEM;
3474                 goto out_fail;
3475         }
3476
3477         old_dentry->d_inode->i_nlink++;
3478         old_dir->i_ctime = old_dir->i_mtime = ctime;
3479         new_dir->i_ctime = new_dir->i_mtime = ctime;
3480         old_inode->i_ctime = ctime;
3481
3482         ret = btrfs_unlink_trans(trans, root, old_dir, old_dentry);
3483         if (ret)
3484                 goto out_fail;
3485
3486         if (new_inode) {
3487                 new_inode->i_ctime = CURRENT_TIME;
3488                 ret = btrfs_unlink_trans(trans, root, new_dir, new_dentry);
3489                 if (ret)
3490                         goto out_fail;
3491         }
3492         ret = btrfs_add_link(trans, new_dentry, old_inode, 1);
3493         if (ret)
3494                 goto out_fail;
3495
3496 out_fail:
3497         btrfs_free_path(path);
3498         btrfs_end_transaction(trans, root);
3499 out_unlock:
3500         mutex_unlock(&root->fs_info->fs_mutex);
3501         return ret;
3502 }
3503
3504 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
3505                          const char *symname)
3506 {
3507         struct btrfs_trans_handle *trans;
3508         struct btrfs_root *root = BTRFS_I(dir)->root;
3509         struct btrfs_path *path;
3510         struct btrfs_key key;
3511         struct inode *inode = NULL;
3512         int err;
3513         int drop_inode = 0;
3514         u64 objectid;
3515         int name_len;
3516         int datasize;
3517         unsigned long ptr;
3518         struct btrfs_file_extent_item *ei;
3519         struct extent_buffer *leaf;
3520         unsigned long nr = 0;
3521
3522         name_len = strlen(symname) + 1;
3523         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
3524                 return -ENAMETOOLONG;
3525
3526         mutex_lock(&root->fs_info->fs_mutex);
3527         err = btrfs_check_free_space(root, 1, 0);
3528         if (err)
3529                 goto out_fail;
3530
3531         trans = btrfs_start_transaction(root, 1);
3532         btrfs_set_trans_block_group(trans, dir);
3533
3534         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
3535         if (err) {
3536                 err = -ENOSPC;
3537                 goto out_unlock;
3538         }
3539
3540         inode = btrfs_new_inode(trans, root, dentry->d_name.name,
3541                                 dentry->d_name.len,
3542                                 dentry->d_parent->d_inode->i_ino, objectid,
3543                                 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO);
3544         err = PTR_ERR(inode);
3545         if (IS_ERR(inode))
3546                 goto out_unlock;
3547
3548         btrfs_set_trans_block_group(trans, inode);
3549         err = btrfs_add_nondir(trans, dentry, inode, 0);
3550         if (err)
3551                 drop_inode = 1;
3552         else {
3553                 inode->i_mapping->a_ops = &btrfs_aops;
3554                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3555                 inode->i_fop = &btrfs_file_operations;
3556                 inode->i_op = &btrfs_file_inode_operations;
3557                 extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
3558                 extent_io_tree_init(&BTRFS_I(inode)->io_tree,
3559                                      inode->i_mapping, GFP_NOFS);
3560                 extent_io_tree_init(&BTRFS_I(inode)->io_failure_tree,
3561                                      inode->i_mapping, GFP_NOFS);
3562                 BTRFS_I(inode)->delalloc_bytes = 0;
3563                 atomic_set(&BTRFS_I(inode)->ordered_writeback, 0);
3564                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3565         }
3566         dir->i_sb->s_dirt = 1;
3567         btrfs_update_inode_block_group(trans, inode);
3568         btrfs_update_inode_block_group(trans, dir);
3569         if (drop_inode)
3570                 goto out_unlock;
3571
3572         path = btrfs_alloc_path();
3573         BUG_ON(!path);
3574         key.objectid = inode->i_ino;
3575         key.offset = 0;
3576         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
3577         datasize = btrfs_file_extent_calc_inline_size(name_len);
3578         err = btrfs_insert_empty_item(trans, root, path, &key,
3579                                       datasize);
3580         if (err) {
3581                 drop_inode = 1;
3582                 goto out_unlock;
3583         }
3584         leaf = path->nodes[0];
3585         ei = btrfs_item_ptr(leaf, path->slots[0],
3586                             struct btrfs_file_extent_item);
3587         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
3588         btrfs_set_file_extent_type(leaf, ei,
3589                                    BTRFS_FILE_EXTENT_INLINE);
3590         ptr = btrfs_file_extent_inline_start(ei);
3591         write_extent_buffer(leaf, symname, ptr, name_len);
3592         btrfs_mark_buffer_dirty(leaf);
3593         btrfs_free_path(path);
3594
3595         inode->i_op = &btrfs_symlink_inode_operations;
3596         inode->i_mapping->a_ops = &btrfs_symlink_aops;
3597         inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3598         inode->i_size = name_len - 1;
3599         err = btrfs_update_inode(trans, root, inode);
3600         if (err)
3601                 drop_inode = 1;
3602
3603 out_unlock:
3604         nr = trans->blocks_used;
3605         btrfs_end_transaction(trans, root);
3606 out_fail:
3607         mutex_unlock(&root->fs_info->fs_mutex);
3608         if (drop_inode) {
3609                 inode_dec_link_count(inode);
3610                 iput(inode);
3611         }
3612         btrfs_btree_balance_dirty(root, nr);
3613         btrfs_throttle(root);
3614         return err;
3615 }
3616
3617 static int btrfs_permission(struct inode *inode, int mask,
3618                             struct nameidata *nd)
3619 {
3620         if (btrfs_test_flag(inode, READONLY) && (mask & MAY_WRITE))
3621                 return -EACCES;
3622         return generic_permission(inode, mask, NULL);
3623 }
3624
3625 static struct inode_operations btrfs_dir_inode_operations = {
3626         .lookup         = btrfs_lookup,
3627         .create         = btrfs_create,
3628         .unlink         = btrfs_unlink,
3629         .link           = btrfs_link,
3630         .mkdir          = btrfs_mkdir,
3631         .rmdir          = btrfs_rmdir,
3632         .rename         = btrfs_rename,
3633         .symlink        = btrfs_symlink,
3634         .setattr        = btrfs_setattr,
3635         .mknod          = btrfs_mknod,
3636         .setxattr       = generic_setxattr,
3637         .getxattr       = generic_getxattr,
3638         .listxattr      = btrfs_listxattr,
3639         .removexattr    = generic_removexattr,
3640         .permission     = btrfs_permission,
3641 };
3642 static struct inode_operations btrfs_dir_ro_inode_operations = {
3643         .lookup         = btrfs_lookup,
3644         .permission     = btrfs_permission,
3645 };
3646 static struct file_operations btrfs_dir_file_operations = {
3647         .llseek         = generic_file_llseek,
3648         .read           = generic_read_dir,
3649         .readdir        = btrfs_readdir,
3650         .unlocked_ioctl = btrfs_ioctl,
3651 #ifdef CONFIG_COMPAT
3652         .compat_ioctl   = btrfs_ioctl,
3653 #endif
3654 };
3655
3656 static struct extent_io_ops btrfs_extent_io_ops = {
3657         .fill_delalloc = run_delalloc_range,
3658         .submit_bio_hook = btrfs_submit_bio_hook,
3659         .merge_bio_hook = btrfs_merge_bio_hook,
3660         .readpage_io_hook = btrfs_readpage_io_hook,
3661         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
3662         .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
3663         .set_bit_hook = btrfs_set_bit_hook,
3664         .clear_bit_hook = btrfs_clear_bit_hook,
3665 };
3666
3667 static struct address_space_operations btrfs_aops = {
3668         .readpage       = btrfs_readpage,
3669         .writepage      = btrfs_writepage,
3670         .writepages     = btrfs_writepages,
3671         .readpages      = btrfs_readpages,
3672         .sync_page      = block_sync_page,
3673         .bmap           = btrfs_bmap,
3674         .direct_IO      = btrfs_direct_IO,
3675         .invalidatepage = btrfs_invalidatepage,
3676         .releasepage    = btrfs_releasepage,
3677         .set_page_dirty = __set_page_dirty_nobuffers,
3678 };
3679
3680 static struct address_space_operations btrfs_symlink_aops = {
3681         .readpage       = btrfs_readpage,
3682         .writepage      = btrfs_writepage,
3683         .invalidatepage = btrfs_invalidatepage,
3684         .releasepage    = btrfs_releasepage,
3685 };
3686
3687 static struct inode_operations btrfs_file_inode_operations = {
3688         .truncate       = btrfs_truncate,
3689         .getattr        = btrfs_getattr,
3690         .setattr        = btrfs_setattr,
3691         .setxattr       = generic_setxattr,
3692         .getxattr       = generic_getxattr,
3693         .listxattr      = btrfs_listxattr,
3694         .removexattr    = generic_removexattr,
3695         .permission     = btrfs_permission,
3696 };
3697 static struct inode_operations btrfs_special_inode_operations = {
3698         .getattr        = btrfs_getattr,
3699         .setattr        = btrfs_setattr,
3700         .permission     = btrfs_permission,
3701 };
3702 static struct inode_operations btrfs_symlink_inode_operations = {
3703         .readlink       = generic_readlink,
3704         .follow_link    = page_follow_link_light,
3705         .put_link       = page_put_link,
3706         .permission     = btrfs_permission,
3707 };