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