Btrfs: Fix looping on readdir of the subvol roots
[linux-2.6] / fs / btrfs / inode.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/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         if (key_type == BTRFS_DIR_INDEX_KEY)
1469                 filp->f_pos = INT_LIMIT(typeof(filp->f_pos));
1470         else
1471                 filp->f_pos++;
1472 nopos:
1473         ret = 0;
1474 err:
1475         btrfs_release_path(root, path);
1476         btrfs_free_path(path);
1477         mutex_unlock(&root->fs_info->fs_mutex);
1478         return ret;
1479 }
1480
1481 int btrfs_write_inode(struct inode *inode, int wait)
1482 {
1483         struct btrfs_root *root = BTRFS_I(inode)->root;
1484         struct btrfs_trans_handle *trans;
1485         int ret = 0;
1486
1487         if (wait) {
1488                 mutex_lock(&root->fs_info->fs_mutex);
1489                 trans = btrfs_start_transaction(root, 1);
1490                 btrfs_set_trans_block_group(trans, inode);
1491                 ret = btrfs_commit_transaction(trans, root);
1492                 mutex_unlock(&root->fs_info->fs_mutex);
1493         }
1494         return ret;
1495 }
1496
1497 /*
1498  * This is somewhat expensive, updating the tree every time the
1499  * inode changes.  But, it is most likely to find the inode in cache.
1500  * FIXME, needs more benchmarking...there are no reasons other than performance
1501  * to keep or drop this code.
1502  */
1503 void btrfs_dirty_inode(struct inode *inode)
1504 {
1505         struct btrfs_root *root = BTRFS_I(inode)->root;
1506         struct btrfs_trans_handle *trans;
1507
1508         mutex_lock(&root->fs_info->fs_mutex);
1509         trans = btrfs_start_transaction(root, 1);
1510         btrfs_set_trans_block_group(trans, inode);
1511         btrfs_update_inode(trans, root, inode);
1512         btrfs_end_transaction(trans, root);
1513         mutex_unlock(&root->fs_info->fs_mutex);
1514 }
1515
1516 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
1517                                      struct btrfs_root *root,
1518                                      const char *name, int name_len,
1519                                      u64 ref_objectid,
1520                                      u64 objectid,
1521                                      struct btrfs_block_group_cache *group,
1522                                      int mode)
1523 {
1524         struct inode *inode;
1525         struct btrfs_inode_item *inode_item;
1526         struct btrfs_key *location;
1527         struct btrfs_path *path;
1528         struct btrfs_inode_ref *ref;
1529         struct btrfs_key key[2];
1530         u32 sizes[2];
1531         unsigned long ptr;
1532         int ret;
1533         int owner;
1534
1535         path = btrfs_alloc_path();
1536         BUG_ON(!path);
1537
1538         inode = new_inode(root->fs_info->sb);
1539         if (!inode)
1540                 return ERR_PTR(-ENOMEM);
1541
1542         extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
1543         extent_io_tree_init(&BTRFS_I(inode)->io_tree,
1544                              inode->i_mapping, GFP_NOFS);
1545         BTRFS_I(inode)->delalloc_bytes = 0;
1546         BTRFS_I(inode)->root = root;
1547
1548         if (mode & S_IFDIR)
1549                 owner = 0;
1550         else
1551                 owner = 1;
1552         group = btrfs_find_block_group(root, group, 0, 0, owner);
1553         BTRFS_I(inode)->block_group = group;
1554         BTRFS_I(inode)->flags = 0;
1555
1556         key[0].objectid = objectid;
1557         btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
1558         key[0].offset = 0;
1559
1560         key[1].objectid = objectid;
1561         btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
1562         key[1].offset = ref_objectid;
1563
1564         sizes[0] = sizeof(struct btrfs_inode_item);
1565         sizes[1] = name_len + sizeof(*ref);
1566
1567         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
1568         if (ret != 0)
1569                 goto fail;
1570
1571         if (objectid > root->highest_inode)
1572                 root->highest_inode = objectid;
1573
1574         inode->i_uid = current->fsuid;
1575         inode->i_gid = current->fsgid;
1576         inode->i_mode = mode;
1577         inode->i_ino = objectid;
1578         inode->i_blocks = 0;
1579         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
1580         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1581                                   struct btrfs_inode_item);
1582         fill_inode_item(path->nodes[0], inode_item, inode);
1583
1584         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
1585                              struct btrfs_inode_ref);
1586         btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
1587         ptr = (unsigned long)(ref + 1);
1588         write_extent_buffer(path->nodes[0], name, ptr, name_len);
1589
1590         btrfs_mark_buffer_dirty(path->nodes[0]);
1591         btrfs_free_path(path);
1592
1593         location = &BTRFS_I(inode)->location;
1594         location->objectid = objectid;
1595         location->offset = 0;
1596         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
1597
1598         insert_inode_hash(inode);
1599         return inode;
1600 fail:
1601         btrfs_free_path(path);
1602         return ERR_PTR(ret);
1603 }
1604
1605 static inline u8 btrfs_inode_type(struct inode *inode)
1606 {
1607         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
1608 }
1609
1610 static int btrfs_add_link(struct btrfs_trans_handle *trans,
1611                             struct dentry *dentry, struct inode *inode,
1612                             int add_backref)
1613 {
1614         int ret;
1615         struct btrfs_key key;
1616         struct btrfs_root *root = BTRFS_I(dentry->d_parent->d_inode)->root;
1617         struct inode *parent_inode;
1618
1619         key.objectid = inode->i_ino;
1620         btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
1621         key.offset = 0;
1622
1623         ret = btrfs_insert_dir_item(trans, root,
1624                                     dentry->d_name.name, dentry->d_name.len,
1625                                     dentry->d_parent->d_inode->i_ino,
1626                                     &key, btrfs_inode_type(inode));
1627         if (ret == 0) {
1628                 if (add_backref) {
1629                         ret = btrfs_insert_inode_ref(trans, root,
1630                                              dentry->d_name.name,
1631                                              dentry->d_name.len,
1632                                              inode->i_ino,
1633                                              dentry->d_parent->d_inode->i_ino);
1634                 }
1635                 parent_inode = dentry->d_parent->d_inode;
1636                 parent_inode->i_size += dentry->d_name.len * 2;
1637                 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
1638                 ret = btrfs_update_inode(trans, root,
1639                                          dentry->d_parent->d_inode);
1640         }
1641         return ret;
1642 }
1643
1644 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
1645                             struct dentry *dentry, struct inode *inode,
1646                             int backref)
1647 {
1648         int err = btrfs_add_link(trans, dentry, inode, backref);
1649         if (!err) {
1650                 d_instantiate(dentry, inode);
1651                 return 0;
1652         }
1653         if (err > 0)
1654                 err = -EEXIST;
1655         return err;
1656 }
1657
1658 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
1659                         int mode, dev_t rdev)
1660 {
1661         struct btrfs_trans_handle *trans;
1662         struct btrfs_root *root = BTRFS_I(dir)->root;
1663         struct inode *inode = NULL;
1664         int err;
1665         int drop_inode = 0;
1666         u64 objectid;
1667         unsigned long nr = 0;
1668
1669         if (!new_valid_dev(rdev))
1670                 return -EINVAL;
1671
1672         mutex_lock(&root->fs_info->fs_mutex);
1673         err = btrfs_check_free_space(root, 1, 0);
1674         if (err)
1675                 goto fail;
1676
1677         trans = btrfs_start_transaction(root, 1);
1678         btrfs_set_trans_block_group(trans, dir);
1679
1680         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
1681         if (err) {
1682                 err = -ENOSPC;
1683                 goto out_unlock;
1684         }
1685
1686         inode = btrfs_new_inode(trans, root, dentry->d_name.name,
1687                                 dentry->d_name.len,
1688                                 dentry->d_parent->d_inode->i_ino, objectid,
1689                                 BTRFS_I(dir)->block_group, mode);
1690         err = PTR_ERR(inode);
1691         if (IS_ERR(inode))
1692                 goto out_unlock;
1693
1694         btrfs_set_trans_block_group(trans, inode);
1695         err = btrfs_add_nondir(trans, dentry, inode, 0);
1696         if (err)
1697                 drop_inode = 1;
1698         else {
1699                 inode->i_op = &btrfs_special_inode_operations;
1700                 init_special_inode(inode, inode->i_mode, rdev);
1701                 btrfs_update_inode(trans, root, inode);
1702         }
1703         dir->i_sb->s_dirt = 1;
1704         btrfs_update_inode_block_group(trans, inode);
1705         btrfs_update_inode_block_group(trans, dir);
1706 out_unlock:
1707         nr = trans->blocks_used;
1708         btrfs_end_transaction(trans, root);
1709 fail:
1710         mutex_unlock(&root->fs_info->fs_mutex);
1711
1712         if (drop_inode) {
1713                 inode_dec_link_count(inode);
1714                 iput(inode);
1715         }
1716         btrfs_btree_balance_dirty(root, nr);
1717         btrfs_throttle(root);
1718         return err;
1719 }
1720
1721 static int btrfs_create(struct inode *dir, struct dentry *dentry,
1722                         int mode, struct nameidata *nd)
1723 {
1724         struct btrfs_trans_handle *trans;
1725         struct btrfs_root *root = BTRFS_I(dir)->root;
1726         struct inode *inode = NULL;
1727         int err;
1728         int drop_inode = 0;
1729         unsigned long nr = 0;
1730         u64 objectid;
1731
1732         mutex_lock(&root->fs_info->fs_mutex);
1733         err = btrfs_check_free_space(root, 1, 0);
1734         if (err)
1735                 goto fail;
1736         trans = btrfs_start_transaction(root, 1);
1737         btrfs_set_trans_block_group(trans, dir);
1738
1739         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
1740         if (err) {
1741                 err = -ENOSPC;
1742                 goto out_unlock;
1743         }
1744
1745         inode = btrfs_new_inode(trans, root, dentry->d_name.name,
1746                                 dentry->d_name.len,
1747                                 dentry->d_parent->d_inode->i_ino,
1748                                 objectid, BTRFS_I(dir)->block_group, mode);
1749         err = PTR_ERR(inode);
1750         if (IS_ERR(inode))
1751                 goto out_unlock;
1752
1753         btrfs_set_trans_block_group(trans, inode);
1754         err = btrfs_add_nondir(trans, dentry, inode, 0);
1755         if (err)
1756                 drop_inode = 1;
1757         else {
1758                 inode->i_mapping->a_ops = &btrfs_aops;
1759                 inode->i_fop = &btrfs_file_operations;
1760                 inode->i_op = &btrfs_file_inode_operations;
1761                 extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
1762                 extent_io_tree_init(&BTRFS_I(inode)->io_tree,
1763                                      inode->i_mapping, GFP_NOFS);
1764                 BTRFS_I(inode)->delalloc_bytes = 0;
1765                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
1766         }
1767         dir->i_sb->s_dirt = 1;
1768         btrfs_update_inode_block_group(trans, inode);
1769         btrfs_update_inode_block_group(trans, dir);
1770 out_unlock:
1771         nr = trans->blocks_used;
1772         btrfs_end_transaction(trans, root);
1773 fail:
1774         mutex_unlock(&root->fs_info->fs_mutex);
1775
1776         if (drop_inode) {
1777                 inode_dec_link_count(inode);
1778                 iput(inode);
1779         }
1780         btrfs_btree_balance_dirty(root, nr);
1781         btrfs_throttle(root);
1782         return err;
1783 }
1784
1785 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
1786                       struct dentry *dentry)
1787 {
1788         struct btrfs_trans_handle *trans;
1789         struct btrfs_root *root = BTRFS_I(dir)->root;
1790         struct inode *inode = old_dentry->d_inode;
1791         unsigned long nr = 0;
1792         int err;
1793         int drop_inode = 0;
1794
1795         if (inode->i_nlink == 0)
1796                 return -ENOENT;
1797
1798 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,18)
1799         inode->i_nlink++;
1800 #else
1801         inc_nlink(inode);
1802 #endif
1803         mutex_lock(&root->fs_info->fs_mutex);
1804         err = btrfs_check_free_space(root, 1, 0);
1805         if (err)
1806                 goto fail;
1807         trans = btrfs_start_transaction(root, 1);
1808
1809         btrfs_set_trans_block_group(trans, dir);
1810         atomic_inc(&inode->i_count);
1811         err = btrfs_add_nondir(trans, dentry, inode, 1);
1812
1813         if (err)
1814                 drop_inode = 1;
1815
1816         dir->i_sb->s_dirt = 1;
1817         btrfs_update_inode_block_group(trans, dir);
1818         err = btrfs_update_inode(trans, root, inode);
1819
1820         if (err)
1821                 drop_inode = 1;
1822
1823         nr = trans->blocks_used;
1824         btrfs_end_transaction(trans, root);
1825 fail:
1826         mutex_unlock(&root->fs_info->fs_mutex);
1827
1828         if (drop_inode) {
1829                 inode_dec_link_count(inode);
1830                 iput(inode);
1831         }
1832         btrfs_btree_balance_dirty(root, nr);
1833         btrfs_throttle(root);
1834         return err;
1835 }
1836
1837 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
1838 {
1839         struct inode *inode;
1840         struct btrfs_trans_handle *trans;
1841         struct btrfs_root *root = BTRFS_I(dir)->root;
1842         int err = 0;
1843         int drop_on_err = 0;
1844         u64 objectid;
1845         unsigned long nr = 1;
1846
1847         mutex_lock(&root->fs_info->fs_mutex);
1848         err = btrfs_check_free_space(root, 1, 0);
1849         if (err)
1850                 goto out_unlock;
1851
1852         trans = btrfs_start_transaction(root, 1);
1853         btrfs_set_trans_block_group(trans, dir);
1854
1855         if (IS_ERR(trans)) {
1856                 err = PTR_ERR(trans);
1857                 goto out_unlock;
1858         }
1859
1860         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
1861         if (err) {
1862                 err = -ENOSPC;
1863                 goto out_unlock;
1864         }
1865
1866         inode = btrfs_new_inode(trans, root, dentry->d_name.name,
1867                                 dentry->d_name.len,
1868                                 dentry->d_parent->d_inode->i_ino, objectid,
1869                                 BTRFS_I(dir)->block_group, S_IFDIR | mode);
1870         if (IS_ERR(inode)) {
1871                 err = PTR_ERR(inode);
1872                 goto out_fail;
1873         }
1874
1875         drop_on_err = 1;
1876         inode->i_op = &btrfs_dir_inode_operations;
1877         inode->i_fop = &btrfs_dir_file_operations;
1878         btrfs_set_trans_block_group(trans, inode);
1879
1880         inode->i_size = 0;
1881         err = btrfs_update_inode(trans, root, inode);
1882         if (err)
1883                 goto out_fail;
1884
1885         err = btrfs_add_link(trans, dentry, inode, 0);
1886         if (err)
1887                 goto out_fail;
1888
1889         d_instantiate(dentry, inode);
1890         drop_on_err = 0;
1891         dir->i_sb->s_dirt = 1;
1892         btrfs_update_inode_block_group(trans, inode);
1893         btrfs_update_inode_block_group(trans, dir);
1894
1895 out_fail:
1896         nr = trans->blocks_used;
1897         btrfs_end_transaction(trans, root);
1898
1899 out_unlock:
1900         mutex_unlock(&root->fs_info->fs_mutex);
1901         if (drop_on_err)
1902                 iput(inode);
1903         btrfs_btree_balance_dirty(root, nr);
1904         btrfs_throttle(root);
1905         return err;
1906 }
1907
1908 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
1909                                     size_t pg_offset, u64 start, u64 len,
1910                                     int create)
1911 {
1912         int ret;
1913         int err = 0;
1914         u64 bytenr;
1915         u64 extent_start = 0;
1916         u64 extent_end = 0;
1917         u64 objectid = inode->i_ino;
1918         u32 found_type;
1919         struct btrfs_path *path;
1920         struct btrfs_root *root = BTRFS_I(inode)->root;
1921         struct btrfs_file_extent_item *item;
1922         struct extent_buffer *leaf;
1923         struct btrfs_key found_key;
1924         struct extent_map *em = NULL;
1925         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1926         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1927         struct btrfs_trans_handle *trans = NULL;
1928
1929         path = btrfs_alloc_path();
1930         BUG_ON(!path);
1931         mutex_lock(&root->fs_info->fs_mutex);
1932
1933 again:
1934         spin_lock(&em_tree->lock);
1935         em = lookup_extent_mapping(em_tree, start, len);
1936         spin_unlock(&em_tree->lock);
1937
1938         if (em) {
1939                 if (em->start > start) {
1940                         printk("get_extent lookup [%Lu %Lu] em [%Lu %Lu]\n",
1941                                start, len, em->start, em->len);
1942                         WARN_ON(1);
1943                 }
1944                 if (em->block_start == EXTENT_MAP_INLINE && page)
1945                         free_extent_map(em);
1946                 else
1947                         goto out;
1948         }
1949         em = alloc_extent_map(GFP_NOFS);
1950         if (!em) {
1951                 err = -ENOMEM;
1952                 goto out;
1953         }
1954
1955         em->start = EXTENT_MAP_HOLE;
1956         em->len = (u64)-1;
1957         em->bdev = inode->i_sb->s_bdev;
1958         ret = btrfs_lookup_file_extent(trans, root, path,
1959                                        objectid, start, trans != NULL);
1960         if (ret < 0) {
1961                 err = ret;
1962                 goto out;
1963         }
1964
1965         if (ret != 0) {
1966                 if (path->slots[0] == 0)
1967                         goto not_found;
1968                 path->slots[0]--;
1969         }
1970
1971         leaf = path->nodes[0];
1972         item = btrfs_item_ptr(leaf, path->slots[0],
1973                               struct btrfs_file_extent_item);
1974         /* are we inside the extent that was found? */
1975         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1976         found_type = btrfs_key_type(&found_key);
1977         if (found_key.objectid != objectid ||
1978             found_type != BTRFS_EXTENT_DATA_KEY) {
1979                 goto not_found;
1980         }
1981
1982         found_type = btrfs_file_extent_type(leaf, item);
1983         extent_start = found_key.offset;
1984         if (found_type == BTRFS_FILE_EXTENT_REG) {
1985                 extent_end = extent_start +
1986                        btrfs_file_extent_num_bytes(leaf, item);
1987                 err = 0;
1988                 if (start < extent_start || start >= extent_end) {
1989                         em->start = start;
1990                         if (start < extent_start) {
1991                                 if (start + len <= extent_start)
1992                                         goto not_found;
1993                                 em->len = extent_end - extent_start;
1994                         } else {
1995                                 em->len = len;
1996                         }
1997                         goto not_found_em;
1998                 }
1999                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
2000                 if (bytenr == 0) {
2001                         em->start = extent_start;
2002                         em->len = extent_end - extent_start;
2003                         em->block_start = EXTENT_MAP_HOLE;
2004                         goto insert;
2005                 }
2006                 bytenr += btrfs_file_extent_offset(leaf, item);
2007                 em->block_start = bytenr;
2008                 em->start = extent_start;
2009                 em->len = extent_end - extent_start;
2010                 goto insert;
2011         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
2012                 u64 page_start;
2013                 unsigned long ptr;
2014                 char *map;
2015                 size_t size;
2016                 size_t extent_offset;
2017                 size_t copy_size;
2018
2019                 size = btrfs_file_extent_inline_len(leaf, btrfs_item_nr(leaf,
2020                                                     path->slots[0]));
2021                 extent_end = (extent_start + size + root->sectorsize - 1) &
2022                         ~((u64)root->sectorsize - 1);
2023                 if (start < extent_start || start >= extent_end) {
2024                         em->start = start;
2025                         if (start < extent_start) {
2026                                 if (start + len <= extent_start)
2027                                         goto not_found;
2028                                 em->len = extent_end - extent_start;
2029                         } else {
2030                                 em->len = len;
2031                         }
2032                         goto not_found_em;
2033                 }
2034                 em->block_start = EXTENT_MAP_INLINE;
2035
2036                 if (!page) {
2037                         em->start = extent_start;
2038                         em->len = size;
2039                         goto out;
2040                 }
2041
2042                 page_start = page_offset(page) + pg_offset;
2043                 extent_offset = page_start - extent_start;
2044                 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
2045                                 size - extent_offset);
2046                 em->start = extent_start + extent_offset;
2047                 em->len = (copy_size + root->sectorsize - 1) &
2048                         ~((u64)root->sectorsize - 1);
2049                 map = kmap(page);
2050                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
2051                 if (create == 0 && !PageUptodate(page)) {
2052                         read_extent_buffer(leaf, map + pg_offset, ptr,
2053                                            copy_size);
2054                         flush_dcache_page(page);
2055                 } else if (create && PageUptodate(page)) {
2056                         if (!trans) {
2057                                 kunmap(page);
2058                                 free_extent_map(em);
2059                                 em = NULL;
2060                                 btrfs_release_path(root, path);
2061                                 trans = btrfs_start_transaction(root, 1);
2062                                 goto again;
2063                         }
2064                         write_extent_buffer(leaf, map + pg_offset, ptr,
2065                                             copy_size);
2066                         btrfs_mark_buffer_dirty(leaf);
2067                 }
2068                 kunmap(page);
2069                 set_extent_uptodate(io_tree, em->start,
2070                                     extent_map_end(em) - 1, GFP_NOFS);
2071                 goto insert;
2072         } else {
2073                 printk("unkknown found_type %d\n", found_type);
2074                 WARN_ON(1);
2075         }
2076 not_found:
2077         em->start = start;
2078         em->len = len;
2079 not_found_em:
2080         em->block_start = EXTENT_MAP_HOLE;
2081 insert:
2082         btrfs_release_path(root, path);
2083         if (em->start > start || extent_map_end(em) <= start) {
2084                 printk("bad extent! em: [%Lu %Lu] passed [%Lu %Lu]\n", em->start, em->len, start, len);
2085                 err = -EIO;
2086                 goto out;
2087         }
2088
2089         err = 0;
2090         spin_lock(&em_tree->lock);
2091         ret = add_extent_mapping(em_tree, em);
2092         if (ret == -EEXIST) {
2093                 free_extent_map(em);
2094                 em = lookup_extent_mapping(em_tree, start, len);
2095                 if (!em) {
2096                         err = -EIO;
2097                         printk("failing to insert %Lu %Lu\n", start, len);
2098                 }
2099         }
2100         spin_unlock(&em_tree->lock);
2101 out:
2102         btrfs_free_path(path);
2103         if (trans) {
2104                 ret = btrfs_end_transaction(trans, root);
2105                 if (!err)
2106                         err = ret;
2107         }
2108         mutex_unlock(&root->fs_info->fs_mutex);
2109         if (err) {
2110                 free_extent_map(em);
2111                 WARN_ON(1);
2112                 return ERR_PTR(err);
2113         }
2114         return em;
2115 }
2116
2117 static sector_t btrfs_bmap(struct address_space *mapping, sector_t iblock)
2118 {
2119         return extent_bmap(mapping, iblock, btrfs_get_extent);
2120 }
2121
2122 int btrfs_readpage(struct file *file, struct page *page)
2123 {
2124         struct extent_io_tree *tree;
2125         tree = &BTRFS_I(page->mapping->host)->io_tree;
2126         return extent_read_full_page(tree, page, btrfs_get_extent);
2127 }
2128
2129 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
2130 {
2131         struct extent_io_tree *tree;
2132
2133
2134         if (current->flags & PF_MEMALLOC) {
2135                 redirty_page_for_writepage(wbc, page);
2136                 unlock_page(page);
2137                 return 0;
2138         }
2139         tree = &BTRFS_I(page->mapping->host)->io_tree;
2140         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
2141 }
2142
2143 static int btrfs_writepages(struct address_space *mapping,
2144                             struct writeback_control *wbc)
2145 {
2146         struct extent_io_tree *tree;
2147         tree = &BTRFS_I(mapping->host)->io_tree;
2148         return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
2149 }
2150
2151 static int
2152 btrfs_readpages(struct file *file, struct address_space *mapping,
2153                 struct list_head *pages, unsigned nr_pages)
2154 {
2155         struct extent_io_tree *tree;
2156         tree = &BTRFS_I(mapping->host)->io_tree;
2157         return extent_readpages(tree, mapping, pages, nr_pages,
2158                                 btrfs_get_extent);
2159 }
2160
2161 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
2162 {
2163         struct extent_io_tree *tree;
2164         struct extent_map_tree *map;
2165         int ret;
2166
2167         tree = &BTRFS_I(page->mapping->host)->io_tree;
2168         map = &BTRFS_I(page->mapping->host)->extent_tree;
2169         ret = try_release_extent_mapping(map, tree, page, gfp_flags);
2170         if (ret == 1) {
2171                 ClearPagePrivate(page);
2172                 set_page_private(page, 0);
2173                 page_cache_release(page);
2174         }
2175         return ret;
2176 }
2177
2178 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
2179 {
2180         struct extent_io_tree *tree;
2181
2182         tree = &BTRFS_I(page->mapping->host)->io_tree;
2183         extent_invalidatepage(tree, page, offset);
2184         btrfs_releasepage(page, GFP_NOFS);
2185 }
2186
2187 /*
2188  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
2189  * called from a page fault handler when a page is first dirtied. Hence we must
2190  * be careful to check for EOF conditions here. We set the page up correctly
2191  * for a written page which means we get ENOSPC checking when writing into
2192  * holes and correct delalloc and unwritten extent mapping on filesystems that
2193  * support these features.
2194  *
2195  * We are not allowed to take the i_mutex here so we have to play games to
2196  * protect against truncate races as the page could now be beyond EOF.  Because
2197  * vmtruncate() writes the inode size before removing pages, once we have the
2198  * page lock we can determine safely if the page is beyond EOF. If it is not
2199  * beyond EOF, then the page is guaranteed safe against truncation until we
2200  * unlock the page.
2201  */
2202 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct page *page)
2203 {
2204         struct inode *inode = fdentry(vma->vm_file)->d_inode;
2205         struct btrfs_root *root = BTRFS_I(inode)->root;
2206         unsigned long end;
2207         loff_t size;
2208         int ret;
2209         u64 page_start;
2210
2211         mutex_lock(&root->fs_info->fs_mutex);
2212         ret = btrfs_check_free_space(root, PAGE_CACHE_SIZE, 0);
2213         mutex_unlock(&root->fs_info->fs_mutex);
2214         if (ret)
2215                 goto out;
2216
2217         ret = -EINVAL;
2218
2219         lock_page(page);
2220         wait_on_page_writeback(page);
2221         size = i_size_read(inode);
2222         page_start = (u64)page->index << PAGE_CACHE_SHIFT;
2223
2224         if ((page->mapping != inode->i_mapping) ||
2225             (page_start > size)) {
2226                 /* page got truncated out from underneath us */
2227                 goto out_unlock;
2228         }
2229
2230         /* page is wholly or partially inside EOF */
2231         if (page_start + PAGE_CACHE_SIZE > size)
2232                 end = size & ~PAGE_CACHE_MASK;
2233         else
2234                 end = PAGE_CACHE_SIZE;
2235
2236         ret = btrfs_cow_one_page(inode, page, end);
2237
2238 out_unlock:
2239         unlock_page(page);
2240 out:
2241         return ret;
2242 }
2243
2244 static void btrfs_truncate(struct inode *inode)
2245 {
2246         struct btrfs_root *root = BTRFS_I(inode)->root;
2247         int ret;
2248         struct btrfs_trans_handle *trans;
2249         unsigned long nr;
2250
2251         if (!S_ISREG(inode->i_mode))
2252                 return;
2253         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
2254                 return;
2255
2256         btrfs_truncate_page(inode->i_mapping, inode->i_size);
2257
2258         mutex_lock(&root->fs_info->fs_mutex);
2259         trans = btrfs_start_transaction(root, 1);
2260         btrfs_set_trans_block_group(trans, inode);
2261
2262         /* FIXME, add redo link to tree so we don't leak on crash */
2263         ret = btrfs_truncate_in_trans(trans, root, inode,
2264                                       BTRFS_EXTENT_DATA_KEY);
2265         btrfs_update_inode(trans, root, inode);
2266         nr = trans->blocks_used;
2267
2268         ret = btrfs_end_transaction(trans, root);
2269         BUG_ON(ret);
2270         mutex_unlock(&root->fs_info->fs_mutex);
2271         btrfs_btree_balance_dirty(root, nr);
2272         btrfs_throttle(root);
2273 }
2274
2275 static int noinline create_subvol(struct btrfs_root *root, char *name,
2276                                   int namelen)
2277 {
2278         struct btrfs_trans_handle *trans;
2279         struct btrfs_key key;
2280         struct btrfs_root_item root_item;
2281         struct btrfs_inode_item *inode_item;
2282         struct extent_buffer *leaf;
2283         struct btrfs_root *new_root = root;
2284         struct inode *inode;
2285         struct inode *dir;
2286         int ret;
2287         int err;
2288         u64 objectid;
2289         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
2290         unsigned long nr = 1;
2291
2292         mutex_lock(&root->fs_info->fs_mutex);
2293         ret = btrfs_check_free_space(root, 1, 0);
2294         if (ret)
2295                 goto fail_commit;
2296
2297         trans = btrfs_start_transaction(root, 1);
2298         BUG_ON(!trans);
2299
2300         ret = btrfs_find_free_objectid(trans, root->fs_info->tree_root,
2301                                        0, &objectid);
2302         if (ret)
2303                 goto fail;
2304
2305         leaf = __btrfs_alloc_free_block(trans, root, root->leafsize,
2306                                         objectid, trans->transid, 0, 0,
2307                                         0, 0);
2308         if (IS_ERR(leaf))
2309                 return PTR_ERR(leaf);
2310
2311         btrfs_set_header_nritems(leaf, 0);
2312         btrfs_set_header_level(leaf, 0);
2313         btrfs_set_header_bytenr(leaf, leaf->start);
2314         btrfs_set_header_generation(leaf, trans->transid);
2315         btrfs_set_header_owner(leaf, objectid);
2316
2317         write_extent_buffer(leaf, root->fs_info->fsid,
2318                             (unsigned long)btrfs_header_fsid(leaf),
2319                             BTRFS_FSID_SIZE);
2320         btrfs_mark_buffer_dirty(leaf);
2321
2322         inode_item = &root_item.inode;
2323         memset(inode_item, 0, sizeof(*inode_item));
2324         inode_item->generation = cpu_to_le64(1);
2325         inode_item->size = cpu_to_le64(3);
2326         inode_item->nlink = cpu_to_le32(1);
2327         inode_item->nblocks = cpu_to_le64(1);
2328         inode_item->mode = cpu_to_le32(S_IFDIR | 0755);
2329
2330         btrfs_set_root_bytenr(&root_item, leaf->start);
2331         btrfs_set_root_level(&root_item, 0);
2332         btrfs_set_root_refs(&root_item, 1);
2333         btrfs_set_root_used(&root_item, 0);
2334
2335         memset(&root_item.drop_progress, 0, sizeof(root_item.drop_progress));
2336         root_item.drop_level = 0;
2337
2338         free_extent_buffer(leaf);
2339         leaf = NULL;
2340
2341         btrfs_set_root_dirid(&root_item, new_dirid);
2342
2343         key.objectid = objectid;
2344         key.offset = 1;
2345         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
2346         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
2347                                 &root_item);
2348         if (ret)
2349                 goto fail;
2350
2351         /*
2352          * insert the directory item
2353          */
2354         key.offset = (u64)-1;
2355         dir = root->fs_info->sb->s_root->d_inode;
2356         ret = btrfs_insert_dir_item(trans, root->fs_info->tree_root,
2357                                     name, namelen, dir->i_ino, &key,
2358                                     BTRFS_FT_DIR);
2359         if (ret)
2360                 goto fail;
2361
2362         ret = btrfs_insert_inode_ref(trans, root->fs_info->tree_root,
2363                              name, namelen, objectid,
2364                              root->fs_info->sb->s_root->d_inode->i_ino);
2365         if (ret)
2366                 goto fail;
2367
2368         ret = btrfs_commit_transaction(trans, root);
2369         if (ret)
2370                 goto fail_commit;
2371
2372         new_root = btrfs_read_fs_root(root->fs_info, &key, name, namelen);
2373         BUG_ON(!new_root);
2374
2375         trans = btrfs_start_transaction(new_root, 1);
2376         BUG_ON(!trans);
2377
2378         inode = btrfs_new_inode(trans, new_root, "..", 2, new_dirid,
2379                                 new_dirid,
2380                                 BTRFS_I(dir)->block_group, S_IFDIR | 0700);
2381         if (IS_ERR(inode))
2382                 goto fail;
2383         inode->i_op = &btrfs_dir_inode_operations;
2384         inode->i_fop = &btrfs_dir_file_operations;
2385         new_root->inode = inode;
2386
2387         ret = btrfs_insert_inode_ref(trans, new_root, "..", 2, new_dirid,
2388                                      new_dirid);
2389         inode->i_nlink = 1;
2390         inode->i_size = 0;
2391         ret = btrfs_update_inode(trans, new_root, inode);
2392         if (ret)
2393                 goto fail;
2394 fail:
2395         nr = trans->blocks_used;
2396         err = btrfs_commit_transaction(trans, new_root);
2397         if (err && !ret)
2398                 ret = err;
2399 fail_commit:
2400         mutex_unlock(&root->fs_info->fs_mutex);
2401         btrfs_btree_balance_dirty(root, nr);
2402         btrfs_throttle(root);
2403         return ret;
2404 }
2405
2406 static int create_snapshot(struct btrfs_root *root, char *name, int namelen)
2407 {
2408         struct btrfs_pending_snapshot *pending_snapshot;
2409         struct btrfs_trans_handle *trans;
2410         int ret;
2411         int err;
2412         unsigned long nr = 0;
2413
2414         if (!root->ref_cows)
2415                 return -EINVAL;
2416
2417         mutex_lock(&root->fs_info->fs_mutex);
2418         ret = btrfs_check_free_space(root, 1, 0);
2419         if (ret)
2420                 goto fail_unlock;
2421
2422         pending_snapshot = kmalloc(sizeof(*pending_snapshot), GFP_NOFS);
2423         if (!pending_snapshot) {
2424                 ret = -ENOMEM;
2425                 goto fail_unlock;
2426         }
2427         pending_snapshot->name = kmalloc(namelen + 1, GFP_NOFS);
2428         if (!pending_snapshot->name) {
2429                 ret = -ENOMEM;
2430                 kfree(pending_snapshot);
2431                 goto fail_unlock;
2432         }
2433         memcpy(pending_snapshot->name, name, namelen);
2434         pending_snapshot->name[namelen] = '\0';
2435         trans = btrfs_start_transaction(root, 1);
2436         BUG_ON(!trans);
2437         pending_snapshot->root = root;
2438         list_add(&pending_snapshot->list,
2439                  &trans->transaction->pending_snapshots);
2440         ret = btrfs_update_inode(trans, root, root->inode);
2441         err = btrfs_commit_transaction(trans, root);
2442
2443 fail_unlock:
2444         mutex_unlock(&root->fs_info->fs_mutex);
2445         btrfs_btree_balance_dirty(root, nr);
2446         btrfs_throttle(root);
2447         return ret;
2448 }
2449
2450 unsigned long btrfs_force_ra(struct address_space *mapping,
2451                               struct file_ra_state *ra, struct file *file,
2452                               pgoff_t offset, pgoff_t last_index)
2453 {
2454         pgoff_t req_size;
2455
2456 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
2457         req_size = last_index - offset + 1;
2458         offset = page_cache_readahead(mapping, ra, file, offset, req_size);
2459         return offset;
2460 #else
2461         req_size = min(last_index - offset + 1, (pgoff_t)128);
2462         page_cache_sync_readahead(mapping, ra, file, offset, req_size);
2463         return offset + req_size;
2464 #endif
2465 }
2466
2467 int btrfs_defrag_file(struct file *file) {
2468         struct inode *inode = fdentry(file)->d_inode;
2469         struct btrfs_root *root = BTRFS_I(inode)->root;
2470         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2471         struct page *page;
2472         unsigned long last_index;
2473         unsigned long ra_index = 0;
2474         u64 page_start;
2475         u64 page_end;
2476         unsigned long i;
2477         int ret;
2478
2479         mutex_lock(&root->fs_info->fs_mutex);
2480         ret = btrfs_check_free_space(root, inode->i_size, 0);
2481         mutex_unlock(&root->fs_info->fs_mutex);
2482         if (ret)
2483                 return -ENOSPC;
2484
2485         mutex_lock(&inode->i_mutex);
2486         last_index = inode->i_size >> PAGE_CACHE_SHIFT;
2487         for (i = 0; i <= last_index; i++) {
2488                 if (i == ra_index) {
2489                         ra_index = btrfs_force_ra(inode->i_mapping,
2490                                                   &file->f_ra,
2491                                                   file, ra_index, last_index);
2492                 }
2493                 page = grab_cache_page(inode->i_mapping, i);
2494                 if (!page)
2495                         goto out_unlock;
2496                 if (!PageUptodate(page)) {
2497                         btrfs_readpage(NULL, page);
2498                         lock_page(page);
2499                         if (!PageUptodate(page)) {
2500                                 unlock_page(page);
2501                                 page_cache_release(page);
2502                                 goto out_unlock;
2503                         }
2504                 }
2505                 page_start = (u64)page->index << PAGE_CACHE_SHIFT;
2506                 page_end = page_start + PAGE_CACHE_SIZE - 1;
2507
2508                 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
2509                 set_extent_delalloc(io_tree, page_start,
2510                                     page_end, GFP_NOFS);
2511
2512                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
2513                 set_page_dirty(page);
2514                 unlock_page(page);
2515                 page_cache_release(page);
2516                 balance_dirty_pages_ratelimited_nr(inode->i_mapping, 1);
2517         }
2518
2519 out_unlock:
2520         mutex_unlock(&inode->i_mutex);
2521         return 0;
2522 }
2523
2524 static int btrfs_ioctl_resize(struct btrfs_root *root, void __user *arg)
2525 {
2526         u64 new_size;
2527         u64 old_size;
2528         struct btrfs_ioctl_vol_args *vol_args;
2529         struct btrfs_trans_handle *trans;
2530         char *sizestr;
2531         int ret = 0;
2532         int namelen;
2533         int mod = 0;
2534
2535         vol_args = kmalloc(sizeof(*vol_args), GFP_NOFS);
2536
2537         if (!vol_args)
2538                 return -ENOMEM;
2539
2540         if (copy_from_user(vol_args, arg, sizeof(*vol_args))) {
2541                 ret = -EFAULT;
2542                 goto out;
2543         }
2544         namelen = strlen(vol_args->name);
2545         if (namelen > BTRFS_VOL_NAME_MAX) {
2546                 ret = -EINVAL;
2547                 goto out;
2548         }
2549
2550         sizestr = vol_args->name;
2551         if (!strcmp(sizestr, "max"))
2552                 new_size = root->fs_info->sb->s_bdev->bd_inode->i_size;
2553         else {
2554                 if (sizestr[0] == '-') {
2555                         mod = -1;
2556                         sizestr++;
2557                 } else if (sizestr[0] == '+') {
2558                         mod = 1;
2559                         sizestr++;
2560                 }
2561                 new_size = btrfs_parse_size(sizestr);
2562                 if (new_size == 0) {
2563                         ret = -EINVAL;
2564                         goto out;
2565                 }
2566         }
2567
2568         mutex_lock(&root->fs_info->fs_mutex);
2569         old_size = btrfs_super_total_bytes(&root->fs_info->super_copy);
2570
2571         if (mod < 0) {
2572                 if (new_size > old_size) {
2573                         ret = -EINVAL;
2574                         goto out_unlock;
2575                 }
2576                 new_size = old_size - new_size;
2577         } else if (mod > 0) {
2578                 new_size = old_size + new_size;
2579         }
2580
2581         if (new_size < 256 * 1024 * 1024) {
2582                 ret = -EINVAL;
2583                 goto out_unlock;
2584         }
2585         if (new_size > root->fs_info->sb->s_bdev->bd_inode->i_size) {
2586                 ret = -EFBIG;
2587                 goto out_unlock;
2588         }
2589
2590         do_div(new_size, root->sectorsize);
2591         new_size *= root->sectorsize;
2592
2593 printk("new size is %Lu\n", new_size);
2594         if (new_size > old_size) {
2595                 trans = btrfs_start_transaction(root, 1);
2596                 ret = btrfs_grow_extent_tree(trans, root, new_size);
2597                 btrfs_commit_transaction(trans, root);
2598         } else {
2599                 ret = btrfs_shrink_extent_tree(root, new_size);
2600         }
2601
2602 out_unlock:
2603         mutex_unlock(&root->fs_info->fs_mutex);
2604 out:
2605         kfree(vol_args);
2606         return ret;
2607 }
2608
2609 static int noinline btrfs_ioctl_snap_create(struct btrfs_root *root,
2610                                             void __user *arg)
2611 {
2612         struct btrfs_ioctl_vol_args *vol_args;
2613         struct btrfs_dir_item *di;
2614         struct btrfs_path *path;
2615         u64 root_dirid;
2616         int namelen;
2617         int ret;
2618
2619         vol_args = kmalloc(sizeof(*vol_args), GFP_NOFS);
2620
2621         if (!vol_args)
2622                 return -ENOMEM;
2623
2624         if (copy_from_user(vol_args, arg, sizeof(*vol_args))) {
2625                 ret = -EFAULT;
2626                 goto out;
2627         }
2628
2629         namelen = strlen(vol_args->name);
2630         if (namelen > BTRFS_VOL_NAME_MAX) {
2631                 ret = -EINVAL;
2632                 goto out;
2633         }
2634         if (strchr(vol_args->name, '/')) {
2635                 ret = -EINVAL;
2636                 goto out;
2637         }
2638
2639         path = btrfs_alloc_path();
2640         if (!path) {
2641                 ret = -ENOMEM;
2642                 goto out;
2643         }
2644
2645         root_dirid = root->fs_info->sb->s_root->d_inode->i_ino,
2646         mutex_lock(&root->fs_info->fs_mutex);
2647         di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root,
2648                             path, root_dirid,
2649                             vol_args->name, namelen, 0);
2650         mutex_unlock(&root->fs_info->fs_mutex);
2651         btrfs_free_path(path);
2652
2653         if (di && !IS_ERR(di)) {
2654                 ret = -EEXIST;
2655                 goto out;
2656         }
2657
2658         if (IS_ERR(di)) {
2659                 ret = PTR_ERR(di);
2660                 goto out;
2661         }
2662
2663         if (root == root->fs_info->tree_root)
2664                 ret = create_subvol(root, vol_args->name, namelen);
2665         else
2666                 ret = create_snapshot(root, vol_args->name, namelen);
2667 out:
2668         kfree(vol_args);
2669         return ret;
2670 }
2671
2672 static int btrfs_ioctl_defrag(struct file *file)
2673 {
2674         struct inode *inode = fdentry(file)->d_inode;
2675         struct btrfs_root *root = BTRFS_I(inode)->root;
2676
2677         switch (inode->i_mode & S_IFMT) {
2678         case S_IFDIR:
2679                 mutex_lock(&root->fs_info->fs_mutex);
2680                 btrfs_defrag_root(root, 0);
2681                 btrfs_defrag_root(root->fs_info->extent_root, 0);
2682                 mutex_unlock(&root->fs_info->fs_mutex);
2683                 break;
2684         case S_IFREG:
2685                 btrfs_defrag_file(file);
2686                 break;
2687         }
2688
2689         return 0;
2690 }
2691
2692 long btrfs_ioctl(struct file *file, unsigned int
2693                 cmd, unsigned long arg)
2694 {
2695         struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
2696
2697         switch (cmd) {
2698         case BTRFS_IOC_SNAP_CREATE:
2699                 return btrfs_ioctl_snap_create(root, (void __user *)arg);
2700         case BTRFS_IOC_DEFRAG:
2701                 return btrfs_ioctl_defrag(file);
2702         case BTRFS_IOC_RESIZE:
2703                 return btrfs_ioctl_resize(root, (void __user *)arg);
2704         }
2705
2706         return -ENOTTY;
2707 }
2708
2709 /*
2710  * Called inside transaction, so use GFP_NOFS
2711  */
2712 struct inode *btrfs_alloc_inode(struct super_block *sb)
2713 {
2714         struct btrfs_inode *ei;
2715
2716         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
2717         if (!ei)
2718                 return NULL;
2719         ei->last_trans = 0;
2720         ei->ordered_trans = 0;
2721         return &ei->vfs_inode;
2722 }
2723
2724 void btrfs_destroy_inode(struct inode *inode)
2725 {
2726         WARN_ON(!list_empty(&inode->i_dentry));
2727         WARN_ON(inode->i_data.nrpages);
2728
2729         btrfs_drop_extent_cache(inode, 0, (u64)-1);
2730         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
2731 }
2732
2733 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,23)
2734 static void init_once(struct kmem_cache * cachep, void *foo)
2735 #else
2736 static void init_once(void * foo, struct kmem_cache * cachep,
2737                       unsigned long flags)
2738 #endif
2739 {
2740         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
2741
2742         inode_init_once(&ei->vfs_inode);
2743 }
2744
2745 void btrfs_destroy_cachep(void)
2746 {
2747         if (btrfs_inode_cachep)
2748                 kmem_cache_destroy(btrfs_inode_cachep);
2749         if (btrfs_trans_handle_cachep)
2750                 kmem_cache_destroy(btrfs_trans_handle_cachep);
2751         if (btrfs_transaction_cachep)
2752                 kmem_cache_destroy(btrfs_transaction_cachep);
2753         if (btrfs_bit_radix_cachep)
2754                 kmem_cache_destroy(btrfs_bit_radix_cachep);
2755         if (btrfs_path_cachep)
2756                 kmem_cache_destroy(btrfs_path_cachep);
2757 }
2758
2759 struct kmem_cache *btrfs_cache_create(const char *name, size_t size,
2760                                        unsigned long extra_flags,
2761 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,23)
2762                                        void (*ctor)(struct kmem_cache *, void *)
2763 #else
2764                                        void (*ctor)(void *, struct kmem_cache *,
2765                                                     unsigned long)
2766 #endif
2767                                      )
2768 {
2769         return kmem_cache_create(name, size, 0, (SLAB_RECLAIM_ACCOUNT |
2770                                  SLAB_MEM_SPREAD | extra_flags), ctor
2771 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
2772                                  ,NULL
2773 #endif
2774                                 );
2775 }
2776
2777 int btrfs_init_cachep(void)
2778 {
2779         btrfs_inode_cachep = btrfs_cache_create("btrfs_inode_cache",
2780                                           sizeof(struct btrfs_inode),
2781                                           0, init_once);
2782         if (!btrfs_inode_cachep)
2783                 goto fail;
2784         btrfs_trans_handle_cachep =
2785                         btrfs_cache_create("btrfs_trans_handle_cache",
2786                                            sizeof(struct btrfs_trans_handle),
2787                                            0, NULL);
2788         if (!btrfs_trans_handle_cachep)
2789                 goto fail;
2790         btrfs_transaction_cachep = btrfs_cache_create("btrfs_transaction_cache",
2791                                              sizeof(struct btrfs_transaction),
2792                                              0, NULL);
2793         if (!btrfs_transaction_cachep)
2794                 goto fail;
2795         btrfs_path_cachep = btrfs_cache_create("btrfs_path_cache",
2796                                          sizeof(struct btrfs_path),
2797                                          0, NULL);
2798         if (!btrfs_path_cachep)
2799                 goto fail;
2800         btrfs_bit_radix_cachep = btrfs_cache_create("btrfs_radix", 256,
2801                                               SLAB_DESTROY_BY_RCU, NULL);
2802         if (!btrfs_bit_radix_cachep)
2803                 goto fail;
2804         return 0;
2805 fail:
2806         btrfs_destroy_cachep();
2807         return -ENOMEM;
2808 }
2809
2810 static int btrfs_getattr(struct vfsmount *mnt,
2811                          struct dentry *dentry, struct kstat *stat)
2812 {
2813         struct inode *inode = dentry->d_inode;
2814         generic_fillattr(inode, stat);
2815         stat->blksize = PAGE_CACHE_SIZE;
2816         stat->blocks = inode->i_blocks + (BTRFS_I(inode)->delalloc_bytes >> 9);
2817         return 0;
2818 }
2819
2820 static int btrfs_rename(struct inode * old_dir, struct dentry *old_dentry,
2821                            struct inode * new_dir,struct dentry *new_dentry)
2822 {
2823         struct btrfs_trans_handle *trans;
2824         struct btrfs_root *root = BTRFS_I(old_dir)->root;
2825         struct inode *new_inode = new_dentry->d_inode;
2826         struct inode *old_inode = old_dentry->d_inode;
2827         struct timespec ctime = CURRENT_TIME;
2828         struct btrfs_path *path;
2829         int ret;
2830
2831         if (S_ISDIR(old_inode->i_mode) && new_inode &&
2832             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) {
2833                 return -ENOTEMPTY;
2834         }
2835
2836         mutex_lock(&root->fs_info->fs_mutex);
2837         ret = btrfs_check_free_space(root, 1, 0);
2838         if (ret)
2839                 goto out_unlock;
2840
2841         trans = btrfs_start_transaction(root, 1);
2842
2843         btrfs_set_trans_block_group(trans, new_dir);
2844         path = btrfs_alloc_path();
2845         if (!path) {
2846                 ret = -ENOMEM;
2847                 goto out_fail;
2848         }
2849
2850         old_dentry->d_inode->i_nlink++;
2851         old_dir->i_ctime = old_dir->i_mtime = ctime;
2852         new_dir->i_ctime = new_dir->i_mtime = ctime;
2853         old_inode->i_ctime = ctime;
2854
2855         ret = btrfs_unlink_trans(trans, root, old_dir, old_dentry);
2856         if (ret)
2857                 goto out_fail;
2858
2859         if (new_inode) {
2860                 new_inode->i_ctime = CURRENT_TIME;
2861                 ret = btrfs_unlink_trans(trans, root, new_dir, new_dentry);
2862                 if (ret)
2863                         goto out_fail;
2864         }
2865         ret = btrfs_add_link(trans, new_dentry, old_inode, 1);
2866         if (ret)
2867                 goto out_fail;
2868
2869 out_fail:
2870         btrfs_free_path(path);
2871         btrfs_end_transaction(trans, root);
2872 out_unlock:
2873         mutex_unlock(&root->fs_info->fs_mutex);
2874         return ret;
2875 }
2876
2877 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
2878                          const char *symname)
2879 {
2880         struct btrfs_trans_handle *trans;
2881         struct btrfs_root *root = BTRFS_I(dir)->root;
2882         struct btrfs_path *path;
2883         struct btrfs_key key;
2884         struct inode *inode = NULL;
2885         int err;
2886         int drop_inode = 0;
2887         u64 objectid;
2888         int name_len;
2889         int datasize;
2890         unsigned long ptr;
2891         struct btrfs_file_extent_item *ei;
2892         struct extent_buffer *leaf;
2893         unsigned long nr = 0;
2894
2895         name_len = strlen(symname) + 1;
2896         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
2897                 return -ENAMETOOLONG;
2898
2899         mutex_lock(&root->fs_info->fs_mutex);
2900         err = btrfs_check_free_space(root, 1, 0);
2901         if (err)
2902                 goto out_fail;
2903
2904         trans = btrfs_start_transaction(root, 1);
2905         btrfs_set_trans_block_group(trans, dir);
2906
2907         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
2908         if (err) {
2909                 err = -ENOSPC;
2910                 goto out_unlock;
2911         }
2912
2913         inode = btrfs_new_inode(trans, root, dentry->d_name.name,
2914                                 dentry->d_name.len,
2915                                 dentry->d_parent->d_inode->i_ino, objectid,
2916                                 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO);
2917         err = PTR_ERR(inode);
2918         if (IS_ERR(inode))
2919                 goto out_unlock;
2920
2921         btrfs_set_trans_block_group(trans, inode);
2922         err = btrfs_add_nondir(trans, dentry, inode, 0);
2923         if (err)
2924                 drop_inode = 1;
2925         else {
2926                 inode->i_mapping->a_ops = &btrfs_aops;
2927                 inode->i_fop = &btrfs_file_operations;
2928                 inode->i_op = &btrfs_file_inode_operations;
2929                 extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
2930                 extent_io_tree_init(&BTRFS_I(inode)->io_tree,
2931                                      inode->i_mapping, GFP_NOFS);
2932                 BTRFS_I(inode)->delalloc_bytes = 0;
2933                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2934         }
2935         dir->i_sb->s_dirt = 1;
2936         btrfs_update_inode_block_group(trans, inode);
2937         btrfs_update_inode_block_group(trans, dir);
2938         if (drop_inode)
2939                 goto out_unlock;
2940
2941         path = btrfs_alloc_path();
2942         BUG_ON(!path);
2943         key.objectid = inode->i_ino;
2944         key.offset = 0;
2945         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
2946         datasize = btrfs_file_extent_calc_inline_size(name_len);
2947         err = btrfs_insert_empty_item(trans, root, path, &key,
2948                                       datasize);
2949         if (err) {
2950                 drop_inode = 1;
2951                 goto out_unlock;
2952         }
2953         leaf = path->nodes[0];
2954         ei = btrfs_item_ptr(leaf, path->slots[0],
2955                             struct btrfs_file_extent_item);
2956         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
2957         btrfs_set_file_extent_type(leaf, ei,
2958                                    BTRFS_FILE_EXTENT_INLINE);
2959         ptr = btrfs_file_extent_inline_start(ei);
2960         write_extent_buffer(leaf, symname, ptr, name_len);
2961         btrfs_mark_buffer_dirty(leaf);
2962         btrfs_free_path(path);
2963
2964         inode->i_op = &btrfs_symlink_inode_operations;
2965         inode->i_mapping->a_ops = &btrfs_symlink_aops;
2966         inode->i_size = name_len - 1;
2967         err = btrfs_update_inode(trans, root, inode);
2968         if (err)
2969                 drop_inode = 1;
2970
2971 out_unlock:
2972         nr = trans->blocks_used;
2973         btrfs_end_transaction(trans, root);
2974 out_fail:
2975         mutex_unlock(&root->fs_info->fs_mutex);
2976         if (drop_inode) {
2977                 inode_dec_link_count(inode);
2978                 iput(inode);
2979         }
2980         btrfs_btree_balance_dirty(root, nr);
2981         btrfs_throttle(root);
2982         return err;
2983 }
2984 static int btrfs_permission(struct inode *inode, int mask,
2985                             struct nameidata *nd)
2986 {
2987         if (btrfs_test_flag(inode, READONLY) && (mask & MAY_WRITE))
2988                 return -EACCES;
2989         return generic_permission(inode, mask, NULL);
2990 }
2991
2992 static struct inode_operations btrfs_dir_inode_operations = {
2993         .lookup         = btrfs_lookup,
2994         .create         = btrfs_create,
2995         .unlink         = btrfs_unlink,
2996         .link           = btrfs_link,
2997         .mkdir          = btrfs_mkdir,
2998         .rmdir          = btrfs_rmdir,
2999         .rename         = btrfs_rename,
3000         .symlink        = btrfs_symlink,
3001         .setattr        = btrfs_setattr,
3002         .mknod          = btrfs_mknod,
3003         .setxattr       = generic_setxattr,
3004         .getxattr       = generic_getxattr,
3005         .listxattr      = btrfs_listxattr,
3006         .removexattr    = generic_removexattr,
3007         .permission     = btrfs_permission,
3008 };
3009 static struct inode_operations btrfs_dir_ro_inode_operations = {
3010         .lookup         = btrfs_lookup,
3011         .permission     = btrfs_permission,
3012 };
3013 static struct file_operations btrfs_dir_file_operations = {
3014         .llseek         = generic_file_llseek,
3015         .read           = generic_read_dir,
3016         .readdir        = btrfs_readdir,
3017         .unlocked_ioctl = btrfs_ioctl,
3018 #ifdef CONFIG_COMPAT
3019         .compat_ioctl   = btrfs_ioctl,
3020 #endif
3021 };
3022
3023 static struct extent_io_ops btrfs_extent_io_ops = {
3024         .fill_delalloc = run_delalloc_range,
3025         .writepage_io_hook = btrfs_writepage_io_hook,
3026         .readpage_io_hook = btrfs_readpage_io_hook,
3027         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
3028         .set_bit_hook = btrfs_set_bit_hook,
3029         .clear_bit_hook = btrfs_clear_bit_hook,
3030 };
3031
3032 static struct address_space_operations btrfs_aops = {
3033         .readpage       = btrfs_readpage,
3034         .writepage      = btrfs_writepage,
3035         .writepages     = btrfs_writepages,
3036         .readpages      = btrfs_readpages,
3037         .sync_page      = block_sync_page,
3038         .bmap           = btrfs_bmap,
3039         .invalidatepage = btrfs_invalidatepage,
3040         .releasepage    = btrfs_releasepage,
3041         .set_page_dirty = __set_page_dirty_nobuffers,
3042 };
3043
3044 static struct address_space_operations btrfs_symlink_aops = {
3045         .readpage       = btrfs_readpage,
3046         .writepage      = btrfs_writepage,
3047         .invalidatepage = btrfs_invalidatepage,
3048         .releasepage    = btrfs_releasepage,
3049 };
3050
3051 static struct inode_operations btrfs_file_inode_operations = {
3052         .truncate       = btrfs_truncate,
3053         .getattr        = btrfs_getattr,
3054         .setattr        = btrfs_setattr,
3055         .setxattr       = generic_setxattr,
3056         .getxattr       = generic_getxattr,
3057         .listxattr      = btrfs_listxattr,
3058         .removexattr    = generic_removexattr,
3059         .permission     = btrfs_permission,
3060 };
3061 static struct inode_operations btrfs_special_inode_operations = {
3062         .getattr        = btrfs_getattr,
3063         .setattr        = btrfs_setattr,
3064         .permission     = btrfs_permission,
3065 };
3066 static struct inode_operations btrfs_symlink_inode_operations = {
3067         .readlink       = generic_readlink,
3068         .follow_link    = page_follow_link_light,
3069         .put_link       = page_put_link,
3070         .permission     = btrfs_permission,
3071 };