]> git.karo-electronics.de Git - karo-tx-linux.git/blob - fs/btrfs/inode.c
btrfs_get_extent should treat inline extents as though they hold a whole block
[karo-tx-linux.git] / fs / btrfs / inode.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/buffer_head.h>
20 #include <linux/fs.h>
21 #include <linux/pagemap.h>
22 #include <linux/highmem.h>
23 #include <linux/time.h>
24 #include <linux/init.h>
25 #include <linux/string.h>
26 #include <linux/smp_lock.h>
27 #include <linux/backing-dev.h>
28 #include <linux/mpage.h>
29 #include <linux/swap.h>
30 #include <linux/writeback.h>
31 #include <linux/statfs.h>
32 #include <linux/compat.h>
33 #include <linux/bit_spinlock.h>
34 #include <linux/version.h>
35 #include "ctree.h"
36 #include "disk-io.h"
37 #include "transaction.h"
38 #include "btrfs_inode.h"
39 #include "ioctl.h"
40 #include "print-tree.h"
41
42 struct btrfs_iget_args {
43         u64 ino;
44         struct btrfs_root *root;
45 };
46
47 static struct inode_operations btrfs_dir_inode_operations;
48 static struct inode_operations btrfs_symlink_inode_operations;
49 static struct inode_operations btrfs_dir_ro_inode_operations;
50 static struct inode_operations btrfs_special_inode_operations;
51 static struct inode_operations btrfs_file_inode_operations;
52 static struct address_space_operations btrfs_aops;
53 static struct address_space_operations btrfs_symlink_aops;
54 static struct file_operations btrfs_dir_file_operations;
55 static struct extent_map_ops btrfs_extent_map_ops;
56
57 static struct kmem_cache *btrfs_inode_cachep;
58 struct kmem_cache *btrfs_trans_handle_cachep;
59 struct kmem_cache *btrfs_transaction_cachep;
60 struct kmem_cache *btrfs_bit_radix_cachep;
61 struct kmem_cache *btrfs_path_cachep;
62
63 #define S_SHIFT 12
64 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
65         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
66         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
67         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
68         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
69         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
70         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
71         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
72 };
73
74 static int run_delalloc_range(struct inode *inode, u64 start, u64 end)
75 {
76         struct btrfs_root *root = BTRFS_I(inode)->root;
77         struct btrfs_trans_handle *trans;
78         struct btrfs_key ins;
79         u64 alloc_hint = 0;
80         u64 num_blocks;
81         int ret;
82         u64 blocksize = 1 << inode->i_blkbits;
83
84         mutex_lock(&root->fs_info->fs_mutex);
85         trans = btrfs_start_transaction(root, 1);
86         btrfs_set_trans_block_group(trans, inode);
87         BUG_ON(!trans);
88         num_blocks = (end - start + blocksize) & ~(blocksize - 1);
89         ret = btrfs_drop_extents(trans, root, inode,
90                                  start, start + num_blocks, &alloc_hint);
91         num_blocks = num_blocks >> inode->i_blkbits;
92         ret = btrfs_alloc_extent(trans, root, inode->i_ino, num_blocks, 0,
93                                  alloc_hint, (u64)-1, &ins, 1);
94         if (ret) {
95                 WARN_ON(1);
96                 goto out;
97         }
98         ret = btrfs_insert_file_extent(trans, root, inode->i_ino,
99                                        start, ins.objectid, ins.offset,
100                                        ins.offset);
101 out:
102         btrfs_end_transaction(trans, root);
103         mutex_unlock(&root->fs_info->fs_mutex);
104         return ret;
105 }
106
107 int btrfs_writepage_io_hook(struct page *page, u64 start, u64 end)
108 {
109         struct inode *inode = page->mapping->host;
110         struct btrfs_root *root = BTRFS_I(inode)->root;
111         struct btrfs_trans_handle *trans;
112         char *kaddr;
113         int ret;
114         u64 page_start = page->index << PAGE_CACHE_SHIFT;
115         size_t offset = start - page_start;
116
117         mutex_lock(&root->fs_info->fs_mutex);
118         trans = btrfs_start_transaction(root, 1);
119         btrfs_set_trans_block_group(trans, inode);
120         kaddr = kmap(page);
121         btrfs_csum_file_block(trans, root, inode->i_ino,
122                               start, kaddr + offset, end - start + 1);
123         kunmap(page);
124         ret = btrfs_end_transaction(trans, root);
125         BUG_ON(ret);
126         mutex_unlock(&root->fs_info->fs_mutex);
127         return ret;
128 }
129
130 int btrfs_readpage_io_hook(struct page *page, u64 start, u64 end)
131 {
132         int ret = 0;
133         struct inode *inode = page->mapping->host;
134         struct btrfs_root *root = BTRFS_I(inode)->root;
135         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
136         struct btrfs_csum_item *item;
137         struct btrfs_path *path = NULL;
138         u64 private;
139
140         mutex_lock(&root->fs_info->fs_mutex);
141         path = btrfs_alloc_path();
142         item = btrfs_lookup_csum(NULL, root, path, inode->i_ino, start, 0);
143         if (IS_ERR(item)) {
144                 ret = PTR_ERR(item);
145                 /* a csum that isn't present is a preallocated region. */
146                 if (ret == -ENOENT || ret == -EFBIG)
147                         ret = 0;
148                 private = 0;
149                 goto out;
150         }
151         memcpy((char *)&private, &item->csum, BTRFS_CRC32_SIZE);
152         set_state_private(em_tree, start, private);
153 out:
154         if (path)
155                 btrfs_free_path(path);
156         mutex_unlock(&root->fs_info->fs_mutex);
157         return ret;
158 }
159
160 int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end)
161 {
162         char csum[BTRFS_CRC32_SIZE];
163         size_t offset = start - (page->index << PAGE_CACHE_SHIFT);
164         struct inode *inode = page->mapping->host;
165         struct btrfs_root *root = BTRFS_I(inode)->root;
166         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
167         char *kaddr;
168         u64 private;
169         int ret;
170
171         ret = get_state_private(em_tree, start, &private);
172         kaddr = kmap_atomic(page, KM_IRQ0);
173         if (ret) {
174                 goto zeroit;
175         }
176         ret = btrfs_csum_data(root, kaddr + offset, end - start + 1, csum);
177         BUG_ON(ret);
178         if (memcmp(csum, &private, BTRFS_CRC32_SIZE)) {
179                 goto zeroit;
180         }
181         kunmap_atomic(kaddr, KM_IRQ0);
182         return 0;
183
184 zeroit:
185         printk("btrfs csum failed ino %lu off %llu\n",
186                page->mapping->host->i_ino, (unsigned long long)start);
187         memset(kaddr + offset, 1, end - start + 1); flush_dcache_page(page);
188         kunmap_atomic(kaddr, KM_IRQ0);
189         return 0;
190 }
191
192 void btrfs_read_locked_inode(struct inode *inode)
193 {
194         struct btrfs_path *path;
195         struct btrfs_inode_item *inode_item;
196         struct btrfs_root *root = BTRFS_I(inode)->root;
197         struct btrfs_key location;
198         u64 alloc_group_block;
199         u32 rdev;
200         int ret;
201
202         path = btrfs_alloc_path();
203         BUG_ON(!path);
204         mutex_lock(&root->fs_info->fs_mutex);
205
206         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
207         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
208         if (ret) {
209                 goto make_bad;
210         }
211         inode_item = btrfs_item_ptr(btrfs_buffer_leaf(path->nodes[0]),
212                                   path->slots[0],
213                                   struct btrfs_inode_item);
214
215         inode->i_mode = btrfs_inode_mode(inode_item);
216         inode->i_nlink = btrfs_inode_nlink(inode_item);
217         inode->i_uid = btrfs_inode_uid(inode_item);
218         inode->i_gid = btrfs_inode_gid(inode_item);
219         inode->i_size = btrfs_inode_size(inode_item);
220         inode->i_atime.tv_sec = btrfs_timespec_sec(&inode_item->atime);
221         inode->i_atime.tv_nsec = btrfs_timespec_nsec(&inode_item->atime);
222         inode->i_mtime.tv_sec = btrfs_timespec_sec(&inode_item->mtime);
223         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(&inode_item->mtime);
224         inode->i_ctime.tv_sec = btrfs_timespec_sec(&inode_item->ctime);
225         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(&inode_item->ctime);
226         inode->i_blocks = btrfs_inode_nblocks(inode_item);
227         inode->i_generation = btrfs_inode_generation(inode_item);
228         inode->i_rdev = 0;
229         rdev = btrfs_inode_rdev(inode_item);
230         alloc_group_block = btrfs_inode_block_group(inode_item);
231         BTRFS_I(inode)->block_group = btrfs_lookup_block_group(root->fs_info,
232                                                        alloc_group_block);
233
234         btrfs_free_path(path);
235         inode_item = NULL;
236
237         mutex_unlock(&root->fs_info->fs_mutex);
238
239         switch (inode->i_mode & S_IFMT) {
240         case S_IFREG:
241                 inode->i_mapping->a_ops = &btrfs_aops;
242                 BTRFS_I(inode)->extent_tree.ops = &btrfs_extent_map_ops;
243                 inode->i_fop = &btrfs_file_operations;
244                 inode->i_op = &btrfs_file_inode_operations;
245                 break;
246         case S_IFDIR:
247                 inode->i_fop = &btrfs_dir_file_operations;
248                 if (root == root->fs_info->tree_root)
249                         inode->i_op = &btrfs_dir_ro_inode_operations;
250                 else
251                         inode->i_op = &btrfs_dir_inode_operations;
252                 break;
253         case S_IFLNK:
254                 inode->i_op = &btrfs_symlink_inode_operations;
255                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
256                 break;
257         default:
258                 init_special_inode(inode, inode->i_mode, rdev);
259                 break;
260         }
261         return;
262
263 make_bad:
264         btrfs_release_path(root, path);
265         btrfs_free_path(path);
266         mutex_unlock(&root->fs_info->fs_mutex);
267         make_bad_inode(inode);
268 }
269
270 static void fill_inode_item(struct btrfs_inode_item *item,
271                             struct inode *inode)
272 {
273         btrfs_set_inode_uid(item, inode->i_uid);
274         btrfs_set_inode_gid(item, inode->i_gid);
275         btrfs_set_inode_size(item, inode->i_size);
276         btrfs_set_inode_mode(item, inode->i_mode);
277         btrfs_set_inode_nlink(item, inode->i_nlink);
278         btrfs_set_timespec_sec(&item->atime, inode->i_atime.tv_sec);
279         btrfs_set_timespec_nsec(&item->atime, inode->i_atime.tv_nsec);
280         btrfs_set_timespec_sec(&item->mtime, inode->i_mtime.tv_sec);
281         btrfs_set_timespec_nsec(&item->mtime, inode->i_mtime.tv_nsec);
282         btrfs_set_timespec_sec(&item->ctime, inode->i_ctime.tv_sec);
283         btrfs_set_timespec_nsec(&item->ctime, inode->i_ctime.tv_nsec);
284         btrfs_set_inode_nblocks(item, inode->i_blocks);
285         btrfs_set_inode_generation(item, inode->i_generation);
286         btrfs_set_inode_rdev(item, inode->i_rdev);
287         btrfs_set_inode_block_group(item,
288                                     BTRFS_I(inode)->block_group->key.objectid);
289 }
290
291 int btrfs_update_inode(struct btrfs_trans_handle *trans,
292                               struct btrfs_root *root,
293                               struct inode *inode)
294 {
295         struct btrfs_inode_item *inode_item;
296         struct btrfs_path *path;
297         int ret;
298
299         path = btrfs_alloc_path();
300         BUG_ON(!path);
301         ret = btrfs_lookup_inode(trans, root, path,
302                                  &BTRFS_I(inode)->location, 1);
303         if (ret) {
304                 if (ret > 0)
305                         ret = -ENOENT;
306                 goto failed;
307         }
308
309         inode_item = btrfs_item_ptr(btrfs_buffer_leaf(path->nodes[0]),
310                                   path->slots[0],
311                                   struct btrfs_inode_item);
312
313         fill_inode_item(inode_item, inode);
314         btrfs_mark_buffer_dirty(path->nodes[0]);
315         btrfs_set_inode_last_trans(trans, inode);
316         ret = 0;
317 failed:
318         btrfs_release_path(root, path);
319         btrfs_free_path(path);
320         return ret;
321 }
322
323
324 static int btrfs_unlink_trans(struct btrfs_trans_handle *trans,
325                               struct btrfs_root *root,
326                               struct inode *dir,
327                               struct dentry *dentry)
328 {
329         struct btrfs_path *path;
330         const char *name = dentry->d_name.name;
331         int name_len = dentry->d_name.len;
332         int ret = 0;
333         u64 objectid;
334         struct btrfs_dir_item *di;
335
336         path = btrfs_alloc_path();
337         if (!path) {
338                 ret = -ENOMEM;
339                 goto err;
340         }
341
342         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
343                                     name, name_len, -1);
344         if (IS_ERR(di)) {
345                 ret = PTR_ERR(di);
346                 goto err;
347         }
348         if (!di) {
349                 ret = -ENOENT;
350                 goto err;
351         }
352         objectid = btrfs_disk_key_objectid(&di->location);
353         ret = btrfs_delete_one_dir_name(trans, root, path, di);
354         if (ret)
355                 goto err;
356         btrfs_release_path(root, path);
357
358         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
359                                          objectid, name, name_len, -1);
360         if (IS_ERR(di)) {
361                 ret = PTR_ERR(di);
362                 goto err;
363         }
364         if (!di) {
365                 ret = -ENOENT;
366                 goto err;
367         }
368         ret = btrfs_delete_one_dir_name(trans, root, path, di);
369
370         dentry->d_inode->i_ctime = dir->i_ctime;
371 err:
372         btrfs_free_path(path);
373         if (!ret) {
374                 dir->i_size -= name_len * 2;
375                 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
376                 btrfs_update_inode(trans, root, dir);
377                 drop_nlink(dentry->d_inode);
378                 ret = btrfs_update_inode(trans, root, dentry->d_inode);
379                 dir->i_sb->s_dirt = 1;
380         }
381         return ret;
382 }
383
384 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
385 {
386         struct btrfs_root *root;
387         struct btrfs_trans_handle *trans;
388         int ret;
389         unsigned long nr;
390
391         root = BTRFS_I(dir)->root;
392         mutex_lock(&root->fs_info->fs_mutex);
393         trans = btrfs_start_transaction(root, 1);
394         btrfs_set_trans_block_group(trans, dir);
395         ret = btrfs_unlink_trans(trans, root, dir, dentry);
396         nr = trans->blocks_used;
397         btrfs_end_transaction(trans, root);
398         mutex_unlock(&root->fs_info->fs_mutex);
399         btrfs_btree_balance_dirty(root, nr);
400         return ret;
401 }
402
403 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
404 {
405         struct inode *inode = dentry->d_inode;
406         int err;
407         int ret;
408         struct btrfs_root *root = BTRFS_I(dir)->root;
409         struct btrfs_path *path;
410         struct btrfs_key key;
411         struct btrfs_trans_handle *trans;
412         struct btrfs_key found_key;
413         int found_type;
414         struct btrfs_leaf *leaf;
415         char *goodnames = "..";
416         unsigned long nr;
417
418         path = btrfs_alloc_path();
419         BUG_ON(!path);
420         mutex_lock(&root->fs_info->fs_mutex);
421         trans = btrfs_start_transaction(root, 1);
422         btrfs_set_trans_block_group(trans, dir);
423         key.objectid = inode->i_ino;
424         key.offset = (u64)-1;
425         key.flags = (u32)-1;
426         while(1) {
427                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
428                 if (ret < 0) {
429                         err = ret;
430                         goto out;
431                 }
432                 BUG_ON(ret == 0);
433                 if (path->slots[0] == 0) {
434                         err = -ENOENT;
435                         goto out;
436                 }
437                 path->slots[0]--;
438                 leaf = btrfs_buffer_leaf(path->nodes[0]);
439                 btrfs_disk_key_to_cpu(&found_key,
440                                       &leaf->items[path->slots[0]].key);
441                 found_type = btrfs_key_type(&found_key);
442                 if (found_key.objectid != inode->i_ino) {
443                         err = -ENOENT;
444                         goto out;
445                 }
446                 if ((found_type != BTRFS_DIR_ITEM_KEY &&
447                      found_type != BTRFS_DIR_INDEX_KEY) ||
448                     (!btrfs_match_dir_item_name(root, path, goodnames, 2) &&
449                     !btrfs_match_dir_item_name(root, path, goodnames, 1))) {
450                         err = -ENOTEMPTY;
451                         goto out;
452                 }
453                 ret = btrfs_del_item(trans, root, path);
454                 BUG_ON(ret);
455
456                 if (found_type == BTRFS_DIR_ITEM_KEY && found_key.offset == 1)
457                         break;
458                 btrfs_release_path(root, path);
459         }
460         ret = 0;
461         btrfs_release_path(root, path);
462
463         /* now the directory is empty */
464         err = btrfs_unlink_trans(trans, root, dir, dentry);
465         if (!err) {
466                 inode->i_size = 0;
467         }
468 out:
469         btrfs_release_path(root, path);
470         btrfs_free_path(path);
471         mutex_unlock(&root->fs_info->fs_mutex);
472         nr = trans->blocks_used;
473         ret = btrfs_end_transaction(trans, root);
474         btrfs_btree_balance_dirty(root, nr);
475         if (ret && !err)
476                 err = ret;
477         return err;
478 }
479
480 static int btrfs_free_inode(struct btrfs_trans_handle *trans,
481                             struct btrfs_root *root,
482                             struct inode *inode)
483 {
484         struct btrfs_path *path;
485         int ret;
486
487         clear_inode(inode);
488
489         path = btrfs_alloc_path();
490         BUG_ON(!path);
491         ret = btrfs_lookup_inode(trans, root, path,
492                                  &BTRFS_I(inode)->location, -1);
493         if (ret > 0)
494                 ret = -ENOENT;
495         if (!ret)
496                 ret = btrfs_del_item(trans, root, path);
497         btrfs_free_path(path);
498         return ret;
499 }
500
501 /*
502  * this can truncate away extent items, csum items and directory items.
503  * It starts at a high offset and removes keys until it can't find
504  * any higher than i_size.
505  *
506  * csum items that cross the new i_size are truncated to the new size
507  * as well.
508  */
509 static int btrfs_truncate_in_trans(struct btrfs_trans_handle *trans,
510                                    struct btrfs_root *root,
511                                    struct inode *inode)
512 {
513         int ret;
514         struct btrfs_path *path;
515         struct btrfs_key key;
516         struct btrfs_disk_key *found_key;
517         u32 found_type;
518         struct btrfs_leaf *leaf;
519         struct btrfs_file_extent_item *fi;
520         u64 extent_start = 0;
521         u64 extent_num_blocks = 0;
522         u64 item_end = 0;
523         int found_extent;
524         int del_item;
525
526         btrfs_drop_extent_cache(inode, inode->i_size, (u64)-1);
527         path = btrfs_alloc_path();
528         path->reada = -1;
529         BUG_ON(!path);
530         /* FIXME, add redo link to tree so we don't leak on crash */
531         key.objectid = inode->i_ino;
532         key.offset = (u64)-1;
533         key.flags = (u32)-1;
534         while(1) {
535                 btrfs_init_path(path);
536                 fi = NULL;
537                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
538                 if (ret < 0) {
539                         goto error;
540                 }
541                 if (ret > 0) {
542                         BUG_ON(path->slots[0] == 0);
543                         path->slots[0]--;
544                 }
545                 leaf = btrfs_buffer_leaf(path->nodes[0]);
546                 found_key = &leaf->items[path->slots[0]].key;
547                 found_type = btrfs_disk_key_type(found_key);
548
549                 if (btrfs_disk_key_objectid(found_key) != inode->i_ino)
550                         break;
551                 if (found_type != BTRFS_CSUM_ITEM_KEY &&
552                     found_type != BTRFS_DIR_ITEM_KEY &&
553                     found_type != BTRFS_DIR_INDEX_KEY &&
554                     found_type != BTRFS_EXTENT_DATA_KEY)
555                         break;
556
557                 item_end = btrfs_disk_key_offset(found_key);
558                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
559                         fi = btrfs_item_ptr(btrfs_buffer_leaf(path->nodes[0]),
560                                             path->slots[0],
561                                             struct btrfs_file_extent_item);
562                         if (btrfs_file_extent_type(fi) !=
563                             BTRFS_FILE_EXTENT_INLINE) {
564                                 item_end += btrfs_file_extent_num_blocks(fi) <<
565                                                 inode->i_blkbits;
566                         }
567                 }
568                 if (found_type == BTRFS_CSUM_ITEM_KEY) {
569                         ret = btrfs_csum_truncate(trans, root, path,
570                                                   inode->i_size);
571                         BUG_ON(ret);
572                 }
573                 if (item_end < inode->i_size) {
574                         if (found_type == BTRFS_DIR_ITEM_KEY) {
575                                 found_type = BTRFS_INODE_ITEM_KEY;
576                         } else if (found_type == BTRFS_EXTENT_ITEM_KEY) {
577                                 found_type = BTRFS_CSUM_ITEM_KEY;
578                         } else if (found_type) {
579                                 found_type--;
580                         } else {
581                                 break;
582                         }
583                         btrfs_set_key_type(&key, found_type);
584                         continue;
585                 }
586                 if (btrfs_disk_key_offset(found_key) >= inode->i_size)
587                         del_item = 1;
588                 else
589                         del_item = 0;
590                 found_extent = 0;
591
592                 /* FIXME, shrink the extent if the ref count is only 1 */
593                 if (found_type == BTRFS_EXTENT_DATA_KEY &&
594                            btrfs_file_extent_type(fi) !=
595                            BTRFS_FILE_EXTENT_INLINE) {
596                         u64 num_dec;
597                         extent_start = btrfs_file_extent_disk_blocknr(fi);
598                         if (!del_item) {
599                                 u64 orig_num_blocks =
600                                         btrfs_file_extent_num_blocks(fi);
601                                 extent_num_blocks = inode->i_size -
602                                         btrfs_disk_key_offset(found_key) +
603                                         root->blocksize - 1;
604                                 extent_num_blocks >>= inode->i_blkbits;
605                                 btrfs_set_file_extent_num_blocks(fi,
606                                                          extent_num_blocks);
607                                 num_dec = (orig_num_blocks -
608                                            extent_num_blocks) << 3;
609                                 if (extent_start != 0) {
610                                         inode->i_blocks -= num_dec;
611                                 }
612                                 btrfs_mark_buffer_dirty(path->nodes[0]);
613                         } else {
614                                 extent_num_blocks =
615                                         btrfs_file_extent_disk_num_blocks(fi);
616                                 /* FIXME blocksize != 4096 */
617                                 num_dec = btrfs_file_extent_num_blocks(fi) << 3;
618                                 if (extent_start != 0) {
619                                         found_extent = 1;
620                                         inode->i_blocks -= num_dec;
621                                 }
622                         }
623                 }
624                 if (del_item) {
625                         ret = btrfs_del_item(trans, root, path);
626                         if (ret)
627                                 goto error;
628                 } else {
629                         break;
630                 }
631                 btrfs_release_path(root, path);
632                 if (found_extent) {
633                         ret = btrfs_free_extent(trans, root, extent_start,
634                                                 extent_num_blocks, 0);
635                         BUG_ON(ret);
636                 }
637         }
638         ret = 0;
639 error:
640         btrfs_release_path(root, path);
641         btrfs_free_path(path);
642         inode->i_sb->s_dirt = 1;
643         return ret;
644 }
645
646 static int btrfs_cow_one_page(struct inode *inode, struct page *page,
647                               size_t zero_start)
648 {
649         char *kaddr;
650         int ret = 0;
651         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
652         u64 page_start = page->index << PAGE_CACHE_SHIFT;
653         u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
654
655         set_page_extent_mapped(page);
656
657         lock_extent(em_tree, page_start, page_end, GFP_NOFS);
658         set_extent_delalloc(&BTRFS_I(inode)->extent_tree, page_start,
659                             page_end, GFP_NOFS);
660         if (zero_start != PAGE_CACHE_SIZE) {
661                 kaddr = kmap(page);
662                 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
663                 flush_dcache_page(page);
664                 kunmap(page);
665         }
666         set_page_dirty(page);
667         unlock_extent(em_tree, page_start, page_end, GFP_NOFS);
668
669         return ret;
670 }
671
672 /*
673  * taken from block_truncate_page, but does cow as it zeros out
674  * any bytes left in the last page in the file.
675  */
676 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
677 {
678         struct inode *inode = mapping->host;
679         unsigned blocksize = 1 << inode->i_blkbits;
680         pgoff_t index = from >> PAGE_CACHE_SHIFT;
681         unsigned offset = from & (PAGE_CACHE_SIZE-1);
682         struct page *page;
683         int ret = 0;
684         u64 page_start;
685
686         if ((offset & (blocksize - 1)) == 0)
687                 goto out;
688
689         down_read(&BTRFS_I(inode)->root->snap_sem);
690         ret = -ENOMEM;
691         page = grab_cache_page(mapping, index);
692         if (!page)
693                 goto out;
694         if (!PageUptodate(page)) {
695                 ret = btrfs_readpage(NULL, page);
696                 lock_page(page);
697                 if (!PageUptodate(page)) {
698                         ret = -EIO;
699                         goto out;
700                 }
701         }
702         page_start = page->index << PAGE_CACHE_SHIFT;
703
704         ret = btrfs_cow_one_page(inode, page, offset);
705
706         unlock_page(page);
707         page_cache_release(page);
708         up_read(&BTRFS_I(inode)->root->snap_sem);
709 out:
710         return ret;
711 }
712
713 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
714 {
715         struct inode *inode = dentry->d_inode;
716         int err;
717
718         err = inode_change_ok(inode, attr);
719         if (err)
720                 return err;
721
722         if (S_ISREG(inode->i_mode) &&
723             attr->ia_valid & ATTR_SIZE && attr->ia_size > inode->i_size) {
724                 struct btrfs_trans_handle *trans;
725                 struct btrfs_root *root = BTRFS_I(inode)->root;
726                 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
727
728                 u64 mask = root->blocksize - 1;
729                 u64 pos = (inode->i_size + mask) & ~mask;
730                 u64 block_end = attr->ia_size | mask;
731                 u64 hole_size;
732                 u64 alloc_hint;
733
734                 if (attr->ia_size <= pos)
735                         goto out;
736
737                 btrfs_truncate_page(inode->i_mapping, inode->i_size);
738
739                 lock_extent(em_tree, pos, block_end, GFP_NOFS);
740                 hole_size = (attr->ia_size - pos + mask) & ~mask;
741
742                 mutex_lock(&root->fs_info->fs_mutex);
743                 trans = btrfs_start_transaction(root, 1);
744                 btrfs_set_trans_block_group(trans, inode);
745                 err = btrfs_drop_extents(trans, root, inode,
746                                          pos, pos + hole_size, &alloc_hint);
747
748                 hole_size >>= inode->i_blkbits;
749
750                 err = btrfs_insert_file_extent(trans, root, inode->i_ino,
751                                                pos, 0, 0, hole_size);
752                 btrfs_end_transaction(trans, root);
753                 mutex_unlock(&root->fs_info->fs_mutex);
754                 unlock_extent(em_tree, pos, block_end, GFP_NOFS);
755                 if (err)
756                         return err;
757         }
758 out:
759         err = inode_setattr(inode, attr);
760
761         return err;
762 }
763 void btrfs_delete_inode(struct inode *inode)
764 {
765         struct btrfs_trans_handle *trans;
766         struct btrfs_root *root = BTRFS_I(inode)->root;
767         unsigned long nr;
768         int ret;
769
770         truncate_inode_pages(&inode->i_data, 0);
771         if (is_bad_inode(inode)) {
772                 goto no_delete;
773         }
774         inode->i_size = 0;
775         mutex_lock(&root->fs_info->fs_mutex);
776         trans = btrfs_start_transaction(root, 1);
777         btrfs_set_trans_block_group(trans, inode);
778         ret = btrfs_truncate_in_trans(trans, root, inode);
779         if (ret)
780                 goto no_delete_lock;
781         ret = btrfs_free_inode(trans, root, inode);
782         if (ret)
783                 goto no_delete_lock;
784         nr = trans->blocks_used;
785         btrfs_end_transaction(trans, root);
786         mutex_unlock(&root->fs_info->fs_mutex);
787         btrfs_btree_balance_dirty(root, nr);
788         return;
789
790 no_delete_lock:
791         nr = trans->blocks_used;
792         btrfs_end_transaction(trans, root);
793         mutex_unlock(&root->fs_info->fs_mutex);
794         btrfs_btree_balance_dirty(root, nr);
795 no_delete:
796         clear_inode(inode);
797 }
798
799 /*
800  * this returns the key found in the dir entry in the location pointer.
801  * If no dir entries were found, location->objectid is 0.
802  */
803 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
804                                struct btrfs_key *location)
805 {
806         const char *name = dentry->d_name.name;
807         int namelen = dentry->d_name.len;
808         struct btrfs_dir_item *di;
809         struct btrfs_path *path;
810         struct btrfs_root *root = BTRFS_I(dir)->root;
811         int ret;
812
813         path = btrfs_alloc_path();
814         BUG_ON(!path);
815         di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
816                                     namelen, 0);
817         if (!di || IS_ERR(di)) {
818                 location->objectid = 0;
819                 ret = 0;
820                 goto out;
821         }
822         btrfs_disk_key_to_cpu(location, &di->location);
823 out:
824         btrfs_release_path(root, path);
825         btrfs_free_path(path);
826         return ret;
827 }
828
829 /*
830  * when we hit a tree root in a directory, the btrfs part of the inode
831  * needs to be changed to reflect the root directory of the tree root.  This
832  * is kind of like crossing a mount point.
833  */
834 static int fixup_tree_root_location(struct btrfs_root *root,
835                              struct btrfs_key *location,
836                              struct btrfs_root **sub_root,
837                              struct dentry *dentry)
838 {
839         struct btrfs_path *path;
840         struct btrfs_root_item *ri;
841
842         if (btrfs_key_type(location) != BTRFS_ROOT_ITEM_KEY)
843                 return 0;
844         if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
845                 return 0;
846
847         path = btrfs_alloc_path();
848         BUG_ON(!path);
849         mutex_lock(&root->fs_info->fs_mutex);
850
851         *sub_root = btrfs_read_fs_root(root->fs_info, location,
852                                         dentry->d_name.name,
853                                         dentry->d_name.len);
854         if (IS_ERR(*sub_root))
855                 return PTR_ERR(*sub_root);
856
857         ri = &(*sub_root)->root_item;
858         location->objectid = btrfs_root_dirid(ri);
859         location->flags = 0;
860         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
861         location->offset = 0;
862
863         btrfs_free_path(path);
864         mutex_unlock(&root->fs_info->fs_mutex);
865         return 0;
866 }
867
868 static int btrfs_init_locked_inode(struct inode *inode, void *p)
869 {
870         struct btrfs_iget_args *args = p;
871         inode->i_ino = args->ino;
872         BTRFS_I(inode)->root = args->root;
873         extent_map_tree_init(&BTRFS_I(inode)->extent_tree,
874                              inode->i_mapping, GFP_NOFS);
875         return 0;
876 }
877
878 static int btrfs_find_actor(struct inode *inode, void *opaque)
879 {
880         struct btrfs_iget_args *args = opaque;
881         return (args->ino == inode->i_ino &&
882                 args->root == BTRFS_I(inode)->root);
883 }
884
885 struct inode *btrfs_iget_locked(struct super_block *s, u64 objectid,
886                                 struct btrfs_root *root)
887 {
888         struct inode *inode;
889         struct btrfs_iget_args args;
890         args.ino = objectid;
891         args.root = root;
892
893         inode = iget5_locked(s, objectid, btrfs_find_actor,
894                              btrfs_init_locked_inode,
895                              (void *)&args);
896         return inode;
897 }
898
899 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
900                                    struct nameidata *nd)
901 {
902         struct inode * inode;
903         struct btrfs_inode *bi = BTRFS_I(dir);
904         struct btrfs_root *root = bi->root;
905         struct btrfs_root *sub_root = root;
906         struct btrfs_key location;
907         int ret;
908
909         if (dentry->d_name.len > BTRFS_NAME_LEN)
910                 return ERR_PTR(-ENAMETOOLONG);
911         mutex_lock(&root->fs_info->fs_mutex);
912         ret = btrfs_inode_by_name(dir, dentry, &location);
913         mutex_unlock(&root->fs_info->fs_mutex);
914         if (ret < 0)
915                 return ERR_PTR(ret);
916         inode = NULL;
917         if (location.objectid) {
918                 ret = fixup_tree_root_location(root, &location, &sub_root,
919                                                 dentry);
920                 if (ret < 0)
921                         return ERR_PTR(ret);
922                 if (ret > 0)
923                         return ERR_PTR(-ENOENT);
924                 inode = btrfs_iget_locked(dir->i_sb, location.objectid,
925                                           sub_root);
926                 if (!inode)
927                         return ERR_PTR(-EACCES);
928                 if (inode->i_state & I_NEW) {
929                         /* the inode and parent dir are two different roots */
930                         if (sub_root != root) {
931                                 igrab(inode);
932                                 sub_root->inode = inode;
933                         }
934                         BTRFS_I(inode)->root = sub_root;
935                         memcpy(&BTRFS_I(inode)->location, &location,
936                                sizeof(location));
937                         btrfs_read_locked_inode(inode);
938                         unlock_new_inode(inode);
939                 }
940         }
941         return d_splice_alias(inode, dentry);
942 }
943
944 static unsigned char btrfs_filetype_table[] = {
945         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
946 };
947
948 static int btrfs_readdir(struct file *filp, void *dirent, filldir_t filldir)
949 {
950         struct inode *inode = filp->f_path.dentry->d_inode;
951         struct btrfs_root *root = BTRFS_I(inode)->root;
952         struct btrfs_item *item;
953         struct btrfs_dir_item *di;
954         struct btrfs_key key;
955         struct btrfs_path *path;
956         int ret;
957         u32 nritems;
958         struct btrfs_leaf *leaf;
959         int slot;
960         int advance;
961         unsigned char d_type;
962         int over = 0;
963         u32 di_cur;
964         u32 di_total;
965         u32 di_len;
966         int key_type = BTRFS_DIR_INDEX_KEY;
967
968         /* FIXME, use a real flag for deciding about the key type */
969         if (root->fs_info->tree_root == root)
970                 key_type = BTRFS_DIR_ITEM_KEY;
971         mutex_lock(&root->fs_info->fs_mutex);
972         key.objectid = inode->i_ino;
973         key.flags = 0;
974         btrfs_set_key_type(&key, key_type);
975         key.offset = filp->f_pos;
976         path = btrfs_alloc_path();
977         path->reada = 2;
978         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
979         if (ret < 0)
980                 goto err;
981         advance = 0;
982         while(1) {
983                 leaf = btrfs_buffer_leaf(path->nodes[0]);
984                 nritems = btrfs_header_nritems(&leaf->header);
985                 slot = path->slots[0];
986                 if (advance || slot >= nritems) {
987                         if (slot >= nritems -1) {
988                                 ret = btrfs_next_leaf(root, path);
989                                 if (ret)
990                                         break;
991                                 leaf = btrfs_buffer_leaf(path->nodes[0]);
992                                 nritems = btrfs_header_nritems(&leaf->header);
993                                 slot = path->slots[0];
994                         } else {
995                                 slot++;
996                                 path->slots[0]++;
997                         }
998                 }
999                 advance = 1;
1000                 item = leaf->items + slot;
1001                 if (btrfs_disk_key_objectid(&item->key) != key.objectid)
1002                         break;
1003                 if (btrfs_disk_key_type(&item->key) != key_type)
1004                         break;
1005                 if (btrfs_disk_key_offset(&item->key) < filp->f_pos)
1006                         continue;
1007                 filp->f_pos = btrfs_disk_key_offset(&item->key);
1008                 advance = 1;
1009                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
1010                 di_cur = 0;
1011                 di_total = btrfs_item_size(leaf->items + slot);
1012                 while(di_cur < di_total) {
1013                         d_type = btrfs_filetype_table[btrfs_dir_type(di)];
1014                         over = filldir(dirent, (const char *)(di + 1),
1015                                        btrfs_dir_name_len(di),
1016                                        btrfs_disk_key_offset(&item->key),
1017                                        btrfs_disk_key_objectid(&di->location),
1018                                        d_type);
1019                         if (over)
1020                                 goto nopos;
1021                         di_len = btrfs_dir_name_len(di) + sizeof(*di);
1022                         di_cur += di_len;
1023                         di = (struct btrfs_dir_item *)((char *)di + di_len);
1024                 }
1025         }
1026         filp->f_pos++;
1027 nopos:
1028         ret = 0;
1029 err:
1030         btrfs_release_path(root, path);
1031         btrfs_free_path(path);
1032         mutex_unlock(&root->fs_info->fs_mutex);
1033         return ret;
1034 }
1035
1036 int btrfs_write_inode(struct inode *inode, int wait)
1037 {
1038         struct btrfs_root *root = BTRFS_I(inode)->root;
1039         struct btrfs_trans_handle *trans;
1040         int ret = 0;
1041
1042         if (wait) {
1043                 mutex_lock(&root->fs_info->fs_mutex);
1044                 trans = btrfs_start_transaction(root, 1);
1045                 btrfs_set_trans_block_group(trans, inode);
1046                 ret = btrfs_commit_transaction(trans, root);
1047                 mutex_unlock(&root->fs_info->fs_mutex);
1048         }
1049         return ret;
1050 }
1051
1052 /*
1053  * This is somewhat expensive, updating the tree every time the
1054  * inode changes.  But, it is most likely to find the inode in cache.
1055  * FIXME, needs more benchmarking...there are no reasons other than performance
1056  * to keep or drop this code.
1057  */
1058 void btrfs_dirty_inode(struct inode *inode)
1059 {
1060         struct btrfs_root *root = BTRFS_I(inode)->root;
1061         struct btrfs_trans_handle *trans;
1062
1063         mutex_lock(&root->fs_info->fs_mutex);
1064         trans = btrfs_start_transaction(root, 1);
1065         btrfs_set_trans_block_group(trans, inode);
1066         btrfs_update_inode(trans, root, inode);
1067         btrfs_end_transaction(trans, root);
1068         mutex_unlock(&root->fs_info->fs_mutex);
1069 }
1070
1071 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
1072                                      struct btrfs_root *root,
1073                                      u64 objectid,
1074                                      struct btrfs_block_group_cache *group,
1075                                      int mode)
1076 {
1077         struct inode *inode;
1078         struct btrfs_inode_item inode_item;
1079         struct btrfs_key *location;
1080         int ret;
1081         int owner;
1082
1083         inode = new_inode(root->fs_info->sb);
1084         if (!inode)
1085                 return ERR_PTR(-ENOMEM);
1086
1087         extent_map_tree_init(&BTRFS_I(inode)->extent_tree,
1088                              inode->i_mapping, GFP_NOFS);
1089         BTRFS_I(inode)->root = root;
1090
1091         if (mode & S_IFDIR)
1092                 owner = 0;
1093         else
1094                 owner = 1;
1095         group = btrfs_find_block_group(root, group, 0, 0, owner);
1096         BTRFS_I(inode)->block_group = group;
1097
1098         inode->i_uid = current->fsuid;
1099         inode->i_gid = current->fsgid;
1100         inode->i_mode = mode;
1101         inode->i_ino = objectid;
1102         inode->i_blocks = 0;
1103         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
1104         fill_inode_item(&inode_item, inode);
1105         location = &BTRFS_I(inode)->location;
1106         location->objectid = objectid;
1107         location->flags = 0;
1108         location->offset = 0;
1109         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
1110
1111         ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
1112         if (ret)
1113                 return ERR_PTR(ret);
1114         insert_inode_hash(inode);
1115         return inode;
1116 }
1117
1118 static inline u8 btrfs_inode_type(struct inode *inode)
1119 {
1120         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
1121 }
1122
1123 static int btrfs_add_link(struct btrfs_trans_handle *trans,
1124                             struct dentry *dentry, struct inode *inode)
1125 {
1126         int ret;
1127         struct btrfs_key key;
1128         struct btrfs_root *root = BTRFS_I(dentry->d_parent->d_inode)->root;
1129         struct inode *parent_inode;
1130         key.objectid = inode->i_ino;
1131         key.flags = 0;
1132         btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
1133         key.offset = 0;
1134
1135         ret = btrfs_insert_dir_item(trans, root,
1136                                     dentry->d_name.name, dentry->d_name.len,
1137                                     dentry->d_parent->d_inode->i_ino,
1138                                     &key, btrfs_inode_type(inode));
1139         if (ret == 0) {
1140                 parent_inode = dentry->d_parent->d_inode;
1141                 parent_inode->i_size += dentry->d_name.len * 2;
1142                 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
1143                 ret = btrfs_update_inode(trans, root,
1144                                          dentry->d_parent->d_inode);
1145         }
1146         return ret;
1147 }
1148
1149 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
1150                             struct dentry *dentry, struct inode *inode)
1151 {
1152         int err = btrfs_add_link(trans, dentry, inode);
1153         if (!err) {
1154                 d_instantiate(dentry, inode);
1155                 return 0;
1156         }
1157         if (err > 0)
1158                 err = -EEXIST;
1159         return err;
1160 }
1161
1162 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
1163                         int mode, dev_t rdev)
1164 {
1165         struct btrfs_trans_handle *trans;
1166         struct btrfs_root *root = BTRFS_I(dir)->root;
1167         struct inode *inode;
1168         int err;
1169         int drop_inode = 0;
1170         u64 objectid;
1171         unsigned long nr;
1172
1173         if (!new_valid_dev(rdev))
1174                 return -EINVAL;
1175
1176         mutex_lock(&root->fs_info->fs_mutex);
1177         trans = btrfs_start_transaction(root, 1);
1178         btrfs_set_trans_block_group(trans, dir);
1179
1180         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
1181         if (err) {
1182                 err = -ENOSPC;
1183                 goto out_unlock;
1184         }
1185
1186         inode = btrfs_new_inode(trans, root, objectid,
1187                                 BTRFS_I(dir)->block_group, mode);
1188         err = PTR_ERR(inode);
1189         if (IS_ERR(inode))
1190                 goto out_unlock;
1191
1192         btrfs_set_trans_block_group(trans, inode);
1193         err = btrfs_add_nondir(trans, dentry, inode);
1194         if (err)
1195                 drop_inode = 1;
1196         else {
1197                 inode->i_op = &btrfs_special_inode_operations;
1198                 init_special_inode(inode, inode->i_mode, rdev);
1199                 btrfs_update_inode(trans, root, inode);
1200         }
1201         dir->i_sb->s_dirt = 1;
1202         btrfs_update_inode_block_group(trans, inode);
1203         btrfs_update_inode_block_group(trans, dir);
1204 out_unlock:
1205         nr = trans->blocks_used;
1206         btrfs_end_transaction(trans, root);
1207         mutex_unlock(&root->fs_info->fs_mutex);
1208
1209         if (drop_inode) {
1210                 inode_dec_link_count(inode);
1211                 iput(inode);
1212         }
1213         btrfs_btree_balance_dirty(root, nr);
1214         return err;
1215 }
1216
1217 static int btrfs_create(struct inode *dir, struct dentry *dentry,
1218                         int mode, struct nameidata *nd)
1219 {
1220         struct btrfs_trans_handle *trans;
1221         struct btrfs_root *root = BTRFS_I(dir)->root;
1222         struct inode *inode;
1223         int err;
1224         int drop_inode = 0;
1225         unsigned long nr;
1226         u64 objectid;
1227
1228         mutex_lock(&root->fs_info->fs_mutex);
1229         trans = btrfs_start_transaction(root, 1);
1230         btrfs_set_trans_block_group(trans, dir);
1231
1232         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
1233         if (err) {
1234                 err = -ENOSPC;
1235                 goto out_unlock;
1236         }
1237
1238         inode = btrfs_new_inode(trans, root, objectid,
1239                                 BTRFS_I(dir)->block_group, mode);
1240         err = PTR_ERR(inode);
1241         if (IS_ERR(inode))
1242                 goto out_unlock;
1243
1244         btrfs_set_trans_block_group(trans, inode);
1245         err = btrfs_add_nondir(trans, dentry, inode);
1246         if (err)
1247                 drop_inode = 1;
1248         else {
1249                 inode->i_mapping->a_ops = &btrfs_aops;
1250                 inode->i_fop = &btrfs_file_operations;
1251                 inode->i_op = &btrfs_file_inode_operations;
1252                 extent_map_tree_init(&BTRFS_I(inode)->extent_tree,
1253                                      inode->i_mapping, GFP_NOFS);
1254                 BTRFS_I(inode)->extent_tree.ops = &btrfs_extent_map_ops;
1255         }
1256         dir->i_sb->s_dirt = 1;
1257         btrfs_update_inode_block_group(trans, inode);
1258         btrfs_update_inode_block_group(trans, dir);
1259 out_unlock:
1260         nr = trans->blocks_used;
1261         btrfs_end_transaction(trans, root);
1262         mutex_unlock(&root->fs_info->fs_mutex);
1263
1264         if (drop_inode) {
1265                 inode_dec_link_count(inode);
1266                 iput(inode);
1267         }
1268         btrfs_btree_balance_dirty(root, nr);
1269         return err;
1270 }
1271
1272 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
1273                       struct dentry *dentry)
1274 {
1275         struct btrfs_trans_handle *trans;
1276         struct btrfs_root *root = BTRFS_I(dir)->root;
1277         struct inode *inode = old_dentry->d_inode;
1278         unsigned long nr;
1279         int err;
1280         int drop_inode = 0;
1281
1282         if (inode->i_nlink == 0)
1283                 return -ENOENT;
1284
1285         inc_nlink(inode);
1286         mutex_lock(&root->fs_info->fs_mutex);
1287         trans = btrfs_start_transaction(root, 1);
1288         btrfs_set_trans_block_group(trans, dir);
1289         atomic_inc(&inode->i_count);
1290         err = btrfs_add_nondir(trans, dentry, inode);
1291         if (err)
1292                 drop_inode = 1;
1293         dir->i_sb->s_dirt = 1;
1294         btrfs_update_inode_block_group(trans, dir);
1295         err = btrfs_update_inode(trans, root, inode);
1296         if (err)
1297                 drop_inode = 1;
1298
1299         nr = trans->blocks_used;
1300         btrfs_end_transaction(trans, root);
1301         mutex_unlock(&root->fs_info->fs_mutex);
1302
1303         if (drop_inode) {
1304                 inode_dec_link_count(inode);
1305                 iput(inode);
1306         }
1307         btrfs_btree_balance_dirty(root, nr);
1308         return err;
1309 }
1310
1311 static int btrfs_make_empty_dir(struct btrfs_trans_handle *trans,
1312                                 struct btrfs_root *root,
1313                                 u64 objectid, u64 dirid)
1314 {
1315         int ret;
1316         char buf[2];
1317         struct btrfs_key key;
1318
1319         buf[0] = '.';
1320         buf[1] = '.';
1321
1322         key.objectid = objectid;
1323         key.offset = 0;
1324         key.flags = 0;
1325         btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
1326
1327         ret = btrfs_insert_dir_item(trans, root, buf, 1, objectid,
1328                                     &key, BTRFS_FT_DIR);
1329         if (ret)
1330                 goto error;
1331         key.objectid = dirid;
1332         ret = btrfs_insert_dir_item(trans, root, buf, 2, objectid,
1333                                     &key, BTRFS_FT_DIR);
1334         if (ret)
1335                 goto error;
1336 error:
1337         return ret;
1338 }
1339
1340 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
1341 {
1342         struct inode *inode;
1343         struct btrfs_trans_handle *trans;
1344         struct btrfs_root *root = BTRFS_I(dir)->root;
1345         int err = 0;
1346         int drop_on_err = 0;
1347         u64 objectid;
1348         unsigned long nr = 1;
1349
1350         mutex_lock(&root->fs_info->fs_mutex);
1351         trans = btrfs_start_transaction(root, 1);
1352         btrfs_set_trans_block_group(trans, dir);
1353         if (IS_ERR(trans)) {
1354                 err = PTR_ERR(trans);
1355                 goto out_unlock;
1356         }
1357
1358         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
1359         if (err) {
1360                 err = -ENOSPC;
1361                 goto out_unlock;
1362         }
1363
1364         inode = btrfs_new_inode(trans, root, objectid,
1365                                 BTRFS_I(dir)->block_group, S_IFDIR | mode);
1366         if (IS_ERR(inode)) {
1367                 err = PTR_ERR(inode);
1368                 goto out_fail;
1369         }
1370         drop_on_err = 1;
1371         inode->i_op = &btrfs_dir_inode_operations;
1372         inode->i_fop = &btrfs_dir_file_operations;
1373         btrfs_set_trans_block_group(trans, inode);
1374
1375         err = btrfs_make_empty_dir(trans, root, inode->i_ino, dir->i_ino);
1376         if (err)
1377                 goto out_fail;
1378
1379         inode->i_size = 6;
1380         err = btrfs_update_inode(trans, root, inode);
1381         if (err)
1382                 goto out_fail;
1383         err = btrfs_add_link(trans, dentry, inode);
1384         if (err)
1385                 goto out_fail;
1386         d_instantiate(dentry, inode);
1387         drop_on_err = 0;
1388         dir->i_sb->s_dirt = 1;
1389         btrfs_update_inode_block_group(trans, inode);
1390         btrfs_update_inode_block_group(trans, dir);
1391
1392 out_fail:
1393         nr = trans->blocks_used;
1394         btrfs_end_transaction(trans, root);
1395 out_unlock:
1396         mutex_unlock(&root->fs_info->fs_mutex);
1397         if (drop_on_err)
1398                 iput(inode);
1399         btrfs_btree_balance_dirty(root, nr);
1400         return err;
1401 }
1402
1403 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
1404                                     size_t page_offset, u64 start, u64 end,
1405                                     int create)
1406 {
1407         int ret;
1408         int err = 0;
1409         u64 blocknr;
1410         u64 extent_start = 0;
1411         u64 extent_end = 0;
1412         u64 objectid = inode->i_ino;
1413         u32 found_type;
1414         int failed_insert = 0;
1415         struct btrfs_path *path;
1416         struct btrfs_root *root = BTRFS_I(inode)->root;
1417         struct btrfs_file_extent_item *item;
1418         struct btrfs_leaf *leaf;
1419         struct btrfs_disk_key *found_key;
1420         struct extent_map *em = NULL;
1421         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1422         struct btrfs_trans_handle *trans = NULL;
1423
1424         path = btrfs_alloc_path();
1425         BUG_ON(!path);
1426         mutex_lock(&root->fs_info->fs_mutex);
1427
1428 again:
1429         em = lookup_extent_mapping(em_tree, start, end);
1430         if (em) {
1431                 goto out;
1432         }
1433         if (!em) {
1434                 em = alloc_extent_map(GFP_NOFS);
1435                 if (!em) {
1436                         err = -ENOMEM;
1437                         goto out;
1438                 }
1439                 em->start = 0;
1440                 em->end = 0;
1441         }
1442         em->bdev = inode->i_sb->s_bdev;
1443         ret = btrfs_lookup_file_extent(NULL, root, path,
1444                                        objectid, start, 0);
1445         if (ret < 0) {
1446                 err = ret;
1447                 goto out;
1448         }
1449
1450         if (ret != 0) {
1451                 if (path->slots[0] == 0)
1452                         goto not_found;
1453                 path->slots[0]--;
1454         }
1455
1456         item = btrfs_item_ptr(btrfs_buffer_leaf(path->nodes[0]), path->slots[0],
1457                               struct btrfs_file_extent_item);
1458         leaf = btrfs_buffer_leaf(path->nodes[0]);
1459         blocknr = btrfs_file_extent_disk_blocknr(item);
1460         blocknr += btrfs_file_extent_offset(item);
1461
1462         /* are we inside the extent that was found? */
1463         found_key = &leaf->items[path->slots[0]].key;
1464         found_type = btrfs_disk_key_type(found_key);
1465         if (btrfs_disk_key_objectid(found_key) != objectid ||
1466             found_type != BTRFS_EXTENT_DATA_KEY) {
1467                 goto not_found;
1468         }
1469
1470         found_type = btrfs_file_extent_type(item);
1471         extent_start = btrfs_disk_key_offset(&leaf->items[path->slots[0]].key);
1472         if (found_type == BTRFS_FILE_EXTENT_REG) {
1473                 extent_end = extent_start +
1474                        (btrfs_file_extent_num_blocks(item) << inode->i_blkbits);
1475                 err = 0;
1476                 if (start < extent_start || start >= extent_end) {
1477                         em->start = start;
1478                         if (start < extent_start) {
1479                                 if (end < extent_start)
1480                                         goto not_found;
1481                                 em->end = extent_end - 1;
1482                         } else {
1483                                 em->end = end;
1484                         }
1485                         goto not_found_em;
1486                 }
1487                 if (btrfs_file_extent_disk_blocknr(item) == 0) {
1488                         em->start = extent_start;
1489                         em->end = extent_end - 1;
1490                         em->block_start = 0;
1491                         em->block_end = 0;
1492                         goto insert;
1493                 }
1494                 em->block_start = blocknr << inode->i_blkbits;
1495                 em->block_end = em->block_start +
1496                         (btrfs_file_extent_num_blocks(item) <<
1497                          inode->i_blkbits) - 1;
1498                 em->start = extent_start;
1499                 em->end = extent_end - 1;
1500                 goto insert;
1501         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
1502                 char *ptr;
1503                 char *map;
1504                 u32 size;
1505
1506                 size = btrfs_file_extent_inline_len(leaf->items +
1507                                                     path->slots[0]);
1508                 extent_end = extent_start | ((u64)root->blocksize - 1);
1509                 if (start < extent_start || start >= extent_end) {
1510                         em->start = start;
1511                         if (start < extent_start) {
1512                                 if (end < extent_start)
1513                                         goto not_found;
1514                                 em->end = extent_end;
1515                         } else {
1516                                 em->end = end;
1517                         }
1518                         goto not_found_em;
1519                 }
1520                 em->block_start = EXTENT_MAP_INLINE;
1521                 em->block_end = EXTENT_MAP_INLINE;
1522                 em->start = extent_start;
1523                 em->end = extent_end;
1524                 if (!page) {
1525                         goto insert;
1526                 }
1527                 ptr = btrfs_file_extent_inline_start(item);
1528                 map = kmap(page);
1529                 memcpy(map + page_offset, ptr, size);
1530                 memset(map + page_offset + size, 0,
1531                        root->blocksize - (page_offset + size));
1532                 flush_dcache_page(page);
1533                 kunmap(page);
1534                 set_extent_uptodate(em_tree, extent_start,
1535                                     extent_end, GFP_NOFS);
1536                 goto insert;
1537         } else {
1538                 printk("unkknown found_type %d\n", found_type);
1539                 WARN_ON(1);
1540         }
1541 not_found:
1542         em->start = start;
1543         em->end = end;
1544 not_found_em:
1545         em->block_start = 0;
1546         em->block_end = 0;
1547 insert:
1548         btrfs_release_path(root, path);
1549         if (em->start > start || em->end < start) {
1550                 printk("bad extent! em: [%Lu %Lu] passed [%Lu %Lu]\n", em->start, em->end, start, end);
1551                 err = -EIO;
1552                 goto out;
1553         }
1554         ret = add_extent_mapping(em_tree, em);
1555         if (ret == -EEXIST) {
1556                 free_extent_map(em);
1557                 em = NULL;
1558                 failed_insert++;
1559                 if (failed_insert > 5) {
1560                         printk("failing to insert %Lu %Lu\n", start, end);
1561                         err = -EIO;
1562                         goto out;
1563                 }
1564                 goto again;
1565         }
1566         err = 0;
1567 out:
1568         btrfs_free_path(path);
1569         if (trans) {
1570                 ret = btrfs_end_transaction(trans, root);
1571                 if (!err)
1572                         err = ret;
1573         }
1574         mutex_unlock(&root->fs_info->fs_mutex);
1575         if (err) {
1576                 free_extent_map(em);
1577                 WARN_ON(1);
1578                 return ERR_PTR(err);
1579         }
1580         return em;
1581 }
1582
1583 static sector_t btrfs_bmap(struct address_space *mapping, sector_t iblock)
1584 {
1585         return extent_bmap(mapping, iblock, btrfs_get_extent);
1586 }
1587
1588 static int btrfs_prepare_write(struct file *file, struct page *page,
1589                                unsigned from, unsigned to)
1590 {
1591         return extent_prepare_write(&BTRFS_I(page->mapping->host)->extent_tree,
1592                                     page->mapping->host, page, from, to,
1593                                     btrfs_get_extent);
1594 }
1595
1596 int btrfs_readpage(struct file *file, struct page *page)
1597 {
1598         struct extent_map_tree *tree;
1599         tree = &BTRFS_I(page->mapping->host)->extent_tree;
1600         return extent_read_full_page(tree, page, btrfs_get_extent);
1601 }
1602 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
1603 {
1604         struct extent_map_tree *tree;
1605
1606
1607         if (current->flags & PF_MEMALLOC) {
1608                 redirty_page_for_writepage(wbc, page);
1609                 unlock_page(page);
1610                 return 0;
1611         }
1612         tree = &BTRFS_I(page->mapping->host)->extent_tree;
1613         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
1614 }
1615
1616 static int btrfs_releasepage(struct page *page, gfp_t unused_gfp_flags)
1617 {
1618         struct extent_map_tree *tree;
1619         int ret;
1620
1621         if (page->private != 1) {
1622                 WARN_ON(1);
1623                 return try_to_free_buffers(page);
1624         }
1625         tree = &BTRFS_I(page->mapping->host)->extent_tree;
1626         ret = try_release_extent_mapping(tree, page);
1627         if (ret == 1) {
1628                 ClearPagePrivate(page);
1629                 set_page_private(page, 0);
1630                 page_cache_release(page);
1631         }
1632         return ret;
1633 }
1634
1635 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
1636 {
1637         struct extent_map_tree *tree;
1638
1639         tree = &BTRFS_I(page->mapping->host)->extent_tree;
1640         extent_invalidatepage(tree, page, offset);
1641         btrfs_releasepage(page, GFP_NOFS);
1642 }
1643
1644 /*
1645  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
1646  * called from a page fault handler when a page is first dirtied. Hence we must
1647  * be careful to check for EOF conditions here. We set the page up correctly
1648  * for a written page which means we get ENOSPC checking when writing into
1649  * holes and correct delalloc and unwritten extent mapping on filesystems that
1650  * support these features.
1651  *
1652  * We are not allowed to take the i_mutex here so we have to play games to
1653  * protect against truncate races as the page could now be beyond EOF.  Because
1654  * vmtruncate() writes the inode size before removing pages, once we have the
1655  * page lock we can determine safely if the page is beyond EOF. If it is not
1656  * beyond EOF, then the page is guaranteed safe against truncation until we
1657  * unlock the page.
1658  */
1659 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct page *page)
1660 {
1661         struct inode *inode = vma->vm_file->f_path.dentry->d_inode;
1662         unsigned long end;
1663         loff_t size;
1664         int ret = -EINVAL;
1665         u64 page_start;
1666
1667         down_read(&BTRFS_I(inode)->root->snap_sem);
1668         lock_page(page);
1669         wait_on_page_writeback(page);
1670         size = i_size_read(inode);
1671         page_start = page->index << PAGE_CACHE_SHIFT;
1672
1673         if ((page->mapping != inode->i_mapping) ||
1674             (page_start > size)) {
1675                 /* page got truncated out from underneath us */
1676                 goto out_unlock;
1677         }
1678
1679         /* page is wholly or partially inside EOF */
1680         if (page_start + PAGE_CACHE_SIZE > size)
1681                 end = size & ~PAGE_CACHE_MASK;
1682         else
1683                 end = PAGE_CACHE_SIZE;
1684
1685         ret = btrfs_cow_one_page(inode, page, end);
1686
1687 out_unlock:
1688         up_read(&BTRFS_I(inode)->root->snap_sem);
1689         unlock_page(page);
1690         return ret;
1691 }
1692
1693 static void btrfs_truncate(struct inode *inode)
1694 {
1695         struct btrfs_root *root = BTRFS_I(inode)->root;
1696         int ret;
1697         struct btrfs_trans_handle *trans;
1698         unsigned long nr;
1699
1700         if (!S_ISREG(inode->i_mode))
1701                 return;
1702         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
1703                 return;
1704
1705         btrfs_truncate_page(inode->i_mapping, inode->i_size);
1706
1707         mutex_lock(&root->fs_info->fs_mutex);
1708         trans = btrfs_start_transaction(root, 1);
1709         btrfs_set_trans_block_group(trans, inode);
1710
1711         /* FIXME, add redo link to tree so we don't leak on crash */
1712         ret = btrfs_truncate_in_trans(trans, root, inode);
1713         btrfs_update_inode(trans, root, inode);
1714         nr = trans->blocks_used;
1715         ret = btrfs_end_transaction(trans, root);
1716         BUG_ON(ret);
1717         mutex_unlock(&root->fs_info->fs_mutex);
1718         btrfs_btree_balance_dirty(root, nr);
1719 }
1720
1721 int btrfs_commit_write(struct file *file, struct page *page,
1722                        unsigned from, unsigned to)
1723 {
1724         return extent_commit_write(&BTRFS_I(page->mapping->host)->extent_tree,
1725                                    page->mapping->host, page, from, to);
1726 }
1727
1728 static int create_subvol(struct btrfs_root *root, char *name, int namelen)
1729 {
1730         struct btrfs_trans_handle *trans;
1731         struct btrfs_key key;
1732         struct btrfs_root_item root_item;
1733         struct btrfs_inode_item *inode_item;
1734         struct buffer_head *subvol;
1735         struct btrfs_leaf *leaf;
1736         struct btrfs_root *new_root;
1737         struct inode *inode;
1738         struct inode *dir;
1739         int ret;
1740         int err;
1741         u64 objectid;
1742         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
1743         unsigned long nr = 1;
1744
1745         mutex_lock(&root->fs_info->fs_mutex);
1746         trans = btrfs_start_transaction(root, 1);
1747         BUG_ON(!trans);
1748
1749         subvol = btrfs_alloc_free_block(trans, root, 0, 0);
1750         if (IS_ERR(subvol))
1751                 return PTR_ERR(subvol);
1752         leaf = btrfs_buffer_leaf(subvol);
1753         btrfs_set_header_nritems(&leaf->header, 0);
1754         btrfs_set_header_level(&leaf->header, 0);
1755         btrfs_set_header_blocknr(&leaf->header, bh_blocknr(subvol));
1756         btrfs_set_header_generation(&leaf->header, trans->transid);
1757         btrfs_set_header_owner(&leaf->header, root->root_key.objectid);
1758         memcpy(leaf->header.fsid, root->fs_info->disk_super->fsid,
1759                sizeof(leaf->header.fsid));
1760         btrfs_mark_buffer_dirty(subvol);
1761
1762         inode_item = &root_item.inode;
1763         memset(inode_item, 0, sizeof(*inode_item));
1764         btrfs_set_inode_generation(inode_item, 1);
1765         btrfs_set_inode_size(inode_item, 3);
1766         btrfs_set_inode_nlink(inode_item, 1);
1767         btrfs_set_inode_nblocks(inode_item, 1);
1768         btrfs_set_inode_mode(inode_item, S_IFDIR | 0755);
1769
1770         btrfs_set_root_blocknr(&root_item, bh_blocknr(subvol));
1771         btrfs_set_root_refs(&root_item, 1);
1772         btrfs_set_root_blocks_used(&root_item, 0);
1773         memset(&root_item.drop_progress, 0, sizeof(root_item.drop_progress));
1774         root_item.drop_level = 0;
1775         brelse(subvol);
1776         subvol = NULL;
1777
1778         ret = btrfs_find_free_objectid(trans, root->fs_info->tree_root,
1779                                        0, &objectid);
1780         if (ret)
1781                 goto fail;
1782
1783         btrfs_set_root_dirid(&root_item, new_dirid);
1784
1785         key.objectid = objectid;
1786         key.offset = 1;
1787         key.flags = 0;
1788         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
1789         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
1790                                 &root_item);
1791         if (ret)
1792                 goto fail;
1793
1794         /*
1795          * insert the directory item
1796          */
1797         key.offset = (u64)-1;
1798         dir = root->fs_info->sb->s_root->d_inode;
1799         ret = btrfs_insert_dir_item(trans, root->fs_info->tree_root,
1800                                     name, namelen, dir->i_ino, &key,
1801                                     BTRFS_FT_DIR);
1802         if (ret)
1803                 goto fail;
1804
1805         ret = btrfs_commit_transaction(trans, root);
1806         if (ret)
1807                 goto fail_commit;
1808
1809         new_root = btrfs_read_fs_root(root->fs_info, &key, name, namelen);
1810         BUG_ON(!new_root);
1811
1812         trans = btrfs_start_transaction(new_root, 1);
1813         BUG_ON(!trans);
1814
1815         inode = btrfs_new_inode(trans, new_root, new_dirid,
1816                                 BTRFS_I(dir)->block_group, S_IFDIR | 0700);
1817         if (IS_ERR(inode))
1818                 goto fail;
1819         inode->i_op = &btrfs_dir_inode_operations;
1820         inode->i_fop = &btrfs_dir_file_operations;
1821         new_root->inode = inode;
1822
1823         ret = btrfs_make_empty_dir(trans, new_root, new_dirid, new_dirid);
1824         if (ret)
1825                 goto fail;
1826
1827         inode->i_nlink = 1;
1828         inode->i_size = 6;
1829         ret = btrfs_update_inode(trans, new_root, inode);
1830         if (ret)
1831                 goto fail;
1832 fail:
1833         nr = trans->blocks_used;
1834         err = btrfs_commit_transaction(trans, root);
1835         if (err && !ret)
1836                 ret = err;
1837 fail_commit:
1838         mutex_unlock(&root->fs_info->fs_mutex);
1839         btrfs_btree_balance_dirty(root, nr);
1840         return ret;
1841 }
1842
1843 static int create_snapshot(struct btrfs_root *root, char *name, int namelen)
1844 {
1845         struct btrfs_trans_handle *trans;
1846         struct btrfs_key key;
1847         struct btrfs_root_item new_root_item;
1848         struct buffer_head *tmp;
1849         int ret;
1850         int err;
1851         u64 objectid;
1852         unsigned long nr;
1853
1854         if (!root->ref_cows)
1855                 return -EINVAL;
1856
1857         down_write(&root->snap_sem);
1858         freeze_bdev(root->fs_info->sb->s_bdev);
1859         thaw_bdev(root->fs_info->sb->s_bdev, root->fs_info->sb);
1860
1861         mutex_lock(&root->fs_info->fs_mutex);
1862         trans = btrfs_start_transaction(root, 1);
1863         BUG_ON(!trans);
1864
1865         ret = btrfs_update_inode(trans, root, root->inode);
1866         if (ret)
1867                 goto fail;
1868
1869         ret = btrfs_find_free_objectid(trans, root->fs_info->tree_root,
1870                                        0, &objectid);
1871         if (ret)
1872                 goto fail;
1873
1874         memcpy(&new_root_item, &root->root_item,
1875                sizeof(new_root_item));
1876
1877         key.objectid = objectid;
1878         key.offset = 1;
1879         key.flags = 0;
1880         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
1881         btrfs_cow_block(trans, root, root->node, NULL, 0, &tmp);
1882         btrfs_set_root_blocknr(&new_root_item, bh_blocknr(root->node));
1883
1884         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
1885                                 &new_root_item);
1886         if (ret)
1887                 goto fail;
1888
1889         /*
1890          * insert the directory item
1891          */
1892         key.offset = (u64)-1;
1893         ret = btrfs_insert_dir_item(trans, root->fs_info->tree_root,
1894                                     name, namelen,
1895                                     root->fs_info->sb->s_root->d_inode->i_ino,
1896                                     &key, BTRFS_FT_DIR);
1897
1898         if (ret)
1899                 goto fail;
1900
1901         ret = btrfs_inc_root_ref(trans, root);
1902         if (ret)
1903                 goto fail;
1904 fail:
1905         nr = trans->blocks_used;
1906         err = btrfs_commit_transaction(trans, root);
1907         if (err && !ret)
1908                 ret = err;
1909         mutex_unlock(&root->fs_info->fs_mutex);
1910         up_write(&root->snap_sem);
1911         btrfs_btree_balance_dirty(root, nr);
1912         return ret;
1913 }
1914
1915 static unsigned long force_ra(struct address_space *mapping,
1916                               struct file_ra_state *ra, struct file *file,
1917                               pgoff_t offset, pgoff_t last_index)
1918 {
1919         pgoff_t req_size;
1920
1921 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
1922         req_size = last_index - offset + 1;
1923         offset = page_cache_readahead(mapping, ra, file, offset, req_size);
1924         return offset;
1925 #else
1926         req_size = min(last_index - offset + 1, (pgoff_t)128);
1927         page_cache_sync_readahead(mapping, ra, file, offset, req_size);
1928         return offset + req_size;
1929 #endif
1930 }
1931
1932 int btrfs_defrag_file(struct file *file) {
1933         struct inode *inode = file->f_path.dentry->d_inode;
1934         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1935         struct page *page;
1936         unsigned long last_index;
1937         unsigned long ra_index = 0;
1938         u64 page_start;
1939         u64 page_end;
1940         unsigned long i;
1941
1942         mutex_lock(&inode->i_mutex);
1943         last_index = inode->i_size >> PAGE_CACHE_SHIFT;
1944         for (i = 0; i <= last_index; i++) {
1945                 if (i == ra_index) {
1946                         ra_index = force_ra(inode->i_mapping, &file->f_ra,
1947                                             file, ra_index, last_index);
1948                 }
1949                 page = grab_cache_page(inode->i_mapping, i);
1950                 if (!page)
1951                         goto out_unlock;
1952                 if (!PageUptodate(page)) {
1953                         btrfs_readpage(NULL, page);
1954                         lock_page(page);
1955                         if (!PageUptodate(page)) {
1956                                 unlock_page(page);
1957                                 page_cache_release(page);
1958                                 goto out_unlock;
1959                         }
1960                 }
1961                 page_start = page->index << PAGE_CACHE_SHIFT;
1962                 page_end = page_start + PAGE_CACHE_SIZE - 1;
1963
1964                 lock_extent(em_tree, page_start, page_end, GFP_NOFS);
1965                 set_extent_delalloc(em_tree, page_start,
1966                                     page_end, GFP_NOFS);
1967                 unlock_extent(em_tree, page_start, page_end, GFP_NOFS);
1968                 set_page_dirty(page);
1969                 unlock_page(page);
1970                 page_cache_release(page);
1971                 balance_dirty_pages_ratelimited_nr(inode->i_mapping, 1);
1972         }
1973
1974 out_unlock:
1975         mutex_unlock(&inode->i_mutex);
1976         return 0;
1977 }
1978
1979 static int btrfs_ioctl_snap_create(struct btrfs_root *root, void __user *arg)
1980 {
1981         struct btrfs_ioctl_vol_args vol_args;
1982         struct btrfs_dir_item *di;
1983         struct btrfs_path *path;
1984         int namelen;
1985         u64 root_dirid;
1986
1987         if (copy_from_user(&vol_args, arg, sizeof(vol_args)))
1988                 return -EFAULT;
1989         
1990         namelen = strlen(vol_args.name);
1991         if (namelen > BTRFS_VOL_NAME_MAX)
1992                 return -EINVAL;
1993         if (strchr(vol_args.name, '/'))
1994                 return -EINVAL;
1995
1996         path = btrfs_alloc_path();
1997         if (!path)
1998                 return -ENOMEM;
1999
2000         root_dirid = root->fs_info->sb->s_root->d_inode->i_ino,
2001         mutex_lock(&root->fs_info->fs_mutex);
2002         di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root,
2003                             path, root_dirid,
2004                             vol_args.name, namelen, 0);
2005         mutex_unlock(&root->fs_info->fs_mutex);
2006         btrfs_free_path(path);
2007         if (di && !IS_ERR(di))
2008                 return -EEXIST;
2009         if (IS_ERR(di))
2010                 return PTR_ERR(di);
2011
2012         if (root == root->fs_info->tree_root)
2013                 return create_subvol(root, vol_args.name, namelen);
2014         return create_snapshot(root, vol_args.name, namelen);
2015 }
2016
2017 static int btrfs_ioctl_defrag(struct file *file)
2018 {
2019         struct inode *inode = file->f_path.dentry->d_inode;
2020         struct btrfs_root *root = BTRFS_I(inode)->root;
2021
2022         switch (inode->i_mode & S_IFMT) {
2023         case S_IFDIR:
2024                 mutex_lock(&root->fs_info->fs_mutex);
2025                 btrfs_defrag_root(root, 0);
2026                 btrfs_defrag_root(root->fs_info->extent_root, 0);
2027                 mutex_unlock(&root->fs_info->fs_mutex);
2028                 break;
2029         case S_IFREG:
2030                 btrfs_defrag_file(file);
2031                 break;
2032         }
2033
2034         return 0;
2035 }
2036
2037 long btrfs_ioctl(struct file *file, unsigned int
2038                 cmd, unsigned long arg)
2039 {
2040         struct btrfs_root *root = BTRFS_I(file->f_path.dentry->d_inode)->root;
2041
2042         switch (cmd) {
2043         case BTRFS_IOC_SNAP_CREATE:
2044                 return btrfs_ioctl_snap_create(root, (void __user *)arg);
2045         case BTRFS_IOC_DEFRAG:
2046                 return btrfs_ioctl_defrag(file);
2047         }
2048
2049         return -ENOTTY;
2050 }
2051
2052 /*
2053  * Called inside transaction, so use GFP_NOFS
2054  */
2055 struct inode *btrfs_alloc_inode(struct super_block *sb)
2056 {
2057         struct btrfs_inode *ei;
2058
2059         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
2060         if (!ei)
2061                 return NULL;
2062         ei->last_trans = 0;
2063         return &ei->vfs_inode;
2064 }
2065
2066 void btrfs_destroy_inode(struct inode *inode)
2067 {
2068         WARN_ON(!list_empty(&inode->i_dentry));
2069         WARN_ON(inode->i_data.nrpages);
2070
2071         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
2072 }
2073
2074 static void init_once(void * foo, struct kmem_cache * cachep,
2075                       unsigned long flags)
2076 {
2077         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
2078
2079         inode_init_once(&ei->vfs_inode);
2080 }
2081
2082 void btrfs_destroy_cachep(void)
2083 {
2084         if (btrfs_inode_cachep)
2085                 kmem_cache_destroy(btrfs_inode_cachep);
2086         if (btrfs_trans_handle_cachep)
2087                 kmem_cache_destroy(btrfs_trans_handle_cachep);
2088         if (btrfs_transaction_cachep)
2089                 kmem_cache_destroy(btrfs_transaction_cachep);
2090         if (btrfs_bit_radix_cachep)
2091                 kmem_cache_destroy(btrfs_bit_radix_cachep);
2092         if (btrfs_path_cachep)
2093                 kmem_cache_destroy(btrfs_path_cachep);
2094 }
2095
2096 struct kmem_cache *btrfs_cache_create(const char *name, size_t size,
2097                                        unsigned long extra_flags,
2098                                        void (*ctor)(void *, struct kmem_cache *,
2099                                                     unsigned long))
2100 {
2101         return kmem_cache_create(name, size, 0, (SLAB_RECLAIM_ACCOUNT |
2102                                  SLAB_MEM_SPREAD | extra_flags), ctor
2103 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
2104                                  ,NULL
2105 #endif
2106                                 );
2107 }
2108
2109 int btrfs_init_cachep(void)
2110 {
2111         btrfs_inode_cachep = btrfs_cache_create("btrfs_inode_cache",
2112                                           sizeof(struct btrfs_inode),
2113                                           0, init_once);
2114         if (!btrfs_inode_cachep)
2115                 goto fail;
2116         btrfs_trans_handle_cachep =
2117                         btrfs_cache_create("btrfs_trans_handle_cache",
2118                                            sizeof(struct btrfs_trans_handle),
2119                                            0, NULL);
2120         if (!btrfs_trans_handle_cachep)
2121                 goto fail;
2122         btrfs_transaction_cachep = btrfs_cache_create("btrfs_transaction_cache",
2123                                              sizeof(struct btrfs_transaction),
2124                                              0, NULL);
2125         if (!btrfs_transaction_cachep)
2126                 goto fail;
2127         btrfs_path_cachep = btrfs_cache_create("btrfs_path_cache",
2128                                          sizeof(struct btrfs_path),
2129                                          0, NULL);
2130         if (!btrfs_path_cachep)
2131                 goto fail;
2132         btrfs_bit_radix_cachep = btrfs_cache_create("btrfs_radix", 256,
2133                                               SLAB_DESTROY_BY_RCU, NULL);
2134         if (!btrfs_bit_radix_cachep)
2135                 goto fail;
2136         return 0;
2137 fail:
2138         btrfs_destroy_cachep();
2139         return -ENOMEM;
2140 }
2141
2142 static int btrfs_getattr(struct vfsmount *mnt,
2143                          struct dentry *dentry, struct kstat *stat)
2144 {
2145         struct inode *inode = dentry->d_inode;
2146         generic_fillattr(inode, stat);
2147         stat->blksize = 256 * 1024;
2148         return 0;
2149 }
2150
2151 static int btrfs_rename(struct inode * old_dir, struct dentry *old_dentry,
2152                            struct inode * new_dir,struct dentry *new_dentry)
2153 {
2154         struct btrfs_trans_handle *trans;
2155         struct btrfs_root *root = BTRFS_I(old_dir)->root;
2156         struct inode *new_inode = new_dentry->d_inode;
2157         struct inode *old_inode = old_dentry->d_inode;
2158         struct timespec ctime = CURRENT_TIME;
2159         struct btrfs_path *path;
2160         struct btrfs_dir_item *di;
2161         int ret;
2162
2163         if (S_ISDIR(old_inode->i_mode) && new_inode &&
2164             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) {
2165                 return -ENOTEMPTY;
2166         }
2167         mutex_lock(&root->fs_info->fs_mutex);
2168         trans = btrfs_start_transaction(root, 1);
2169         btrfs_set_trans_block_group(trans, new_dir);
2170         path = btrfs_alloc_path();
2171         if (!path) {
2172                 ret = -ENOMEM;
2173                 goto out_fail;
2174         }
2175
2176         old_dentry->d_inode->i_nlink++;
2177         old_dir->i_ctime = old_dir->i_mtime = ctime;
2178         new_dir->i_ctime = new_dir->i_mtime = ctime;
2179         old_inode->i_ctime = ctime;
2180         if (S_ISDIR(old_inode->i_mode) && old_dir != new_dir) {
2181                 struct btrfs_key *location = &BTRFS_I(new_dir)->location;
2182                 u64 old_parent_oid;
2183                 di = btrfs_lookup_dir_item(trans, root, path, old_inode->i_ino,
2184                                            "..", 2, -1);
2185                 if (IS_ERR(di)) {
2186                         ret = PTR_ERR(di);
2187                         goto out_fail;
2188                 }
2189                 if (!di) {
2190                         ret = -ENOENT;
2191                         goto out_fail;
2192                 }
2193                 old_parent_oid = btrfs_disk_key_objectid(&di->location);
2194                 ret = btrfs_del_item(trans, root, path);
2195                 if (ret) {
2196                         goto out_fail;
2197                 }
2198                 btrfs_release_path(root, path);
2199
2200                 di = btrfs_lookup_dir_index_item(trans, root, path,
2201                                                  old_inode->i_ino,
2202                                                  old_parent_oid,
2203                                                  "..", 2, -1);
2204                 if (IS_ERR(di)) {
2205                         ret = PTR_ERR(di);
2206                         goto out_fail;
2207                 }
2208                 if (!di) {
2209                         ret = -ENOENT;
2210                         goto out_fail;
2211                 }
2212                 ret = btrfs_del_item(trans, root, path);
2213                 if (ret) {
2214                         goto out_fail;
2215                 }
2216                 btrfs_release_path(root, path);
2217
2218                 ret = btrfs_insert_dir_item(trans, root, "..", 2,
2219                                             old_inode->i_ino, location,
2220                                             BTRFS_FT_DIR);
2221                 if (ret)
2222                         goto out_fail;
2223         }
2224
2225
2226         ret = btrfs_unlink_trans(trans, root, old_dir, old_dentry);
2227         if (ret)
2228                 goto out_fail;
2229
2230         if (new_inode) {
2231                 new_inode->i_ctime = CURRENT_TIME;
2232                 ret = btrfs_unlink_trans(trans, root, new_dir, new_dentry);
2233                 if (ret)
2234                         goto out_fail;
2235         }
2236         ret = btrfs_add_link(trans, new_dentry, old_inode);
2237         if (ret)
2238                 goto out_fail;
2239
2240 out_fail:
2241         btrfs_free_path(path);
2242         btrfs_end_transaction(trans, root);
2243         mutex_unlock(&root->fs_info->fs_mutex);
2244         return ret;
2245 }
2246
2247 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
2248                          const char *symname)
2249 {
2250         struct btrfs_trans_handle *trans;
2251         struct btrfs_root *root = BTRFS_I(dir)->root;
2252         struct btrfs_path *path;
2253         struct btrfs_key key;
2254         struct inode *inode;
2255         int err;
2256         int drop_inode = 0;
2257         u64 objectid;
2258         int name_len;
2259         int datasize;
2260         char *ptr;
2261         struct btrfs_file_extent_item *ei;
2262         unsigned long nr;
2263
2264         name_len = strlen(symname) + 1;
2265         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
2266                 return -ENAMETOOLONG;
2267         mutex_lock(&root->fs_info->fs_mutex);
2268         trans = btrfs_start_transaction(root, 1);
2269         btrfs_set_trans_block_group(trans, dir);
2270
2271         err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
2272         if (err) {
2273                 err = -ENOSPC;
2274                 goto out_unlock;
2275         }
2276
2277         inode = btrfs_new_inode(trans, root, objectid,
2278                                 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO);
2279         err = PTR_ERR(inode);
2280         if (IS_ERR(inode))
2281                 goto out_unlock;
2282
2283         btrfs_set_trans_block_group(trans, inode);
2284         err = btrfs_add_nondir(trans, dentry, inode);
2285         if (err)
2286                 drop_inode = 1;
2287         else {
2288                 inode->i_mapping->a_ops = &btrfs_aops;
2289                 inode->i_fop = &btrfs_file_operations;
2290                 inode->i_op = &btrfs_file_inode_operations;
2291                 extent_map_tree_init(&BTRFS_I(inode)->extent_tree,
2292                                      inode->i_mapping, GFP_NOFS);
2293                 BTRFS_I(inode)->extent_tree.ops = &btrfs_extent_map_ops;
2294         }
2295         dir->i_sb->s_dirt = 1;
2296         btrfs_update_inode_block_group(trans, inode);
2297         btrfs_update_inode_block_group(trans, dir);
2298         if (drop_inode)
2299                 goto out_unlock;
2300
2301         path = btrfs_alloc_path();
2302         BUG_ON(!path);
2303         key.objectid = inode->i_ino;
2304         key.offset = 0;
2305         key.flags = 0;
2306         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
2307         datasize = btrfs_file_extent_calc_inline_size(name_len);
2308         err = btrfs_insert_empty_item(trans, root, path, &key,
2309                                       datasize);
2310         if (err) {
2311                 drop_inode = 1;
2312                 goto out_unlock;
2313         }
2314         ei = btrfs_item_ptr(btrfs_buffer_leaf(path->nodes[0]),
2315                path->slots[0], struct btrfs_file_extent_item);
2316         btrfs_set_file_extent_generation(ei, trans->transid);
2317         btrfs_set_file_extent_type(ei,
2318                                    BTRFS_FILE_EXTENT_INLINE);
2319         ptr = btrfs_file_extent_inline_start(ei);
2320         btrfs_memcpy(root, path->nodes[0]->b_data,
2321                      ptr, symname, name_len);
2322         btrfs_mark_buffer_dirty(path->nodes[0]);
2323         btrfs_free_path(path);
2324         inode->i_op = &btrfs_symlink_inode_operations;
2325         inode->i_mapping->a_ops = &btrfs_symlink_aops;
2326         inode->i_size = name_len - 1;
2327         err = btrfs_update_inode(trans, root, inode);
2328         if (err)
2329                 drop_inode = 1;
2330
2331 out_unlock:
2332         nr = trans->blocks_used;
2333         btrfs_end_transaction(trans, root);
2334         mutex_unlock(&root->fs_info->fs_mutex);
2335         if (drop_inode) {
2336                 inode_dec_link_count(inode);
2337                 iput(inode);
2338         }
2339         btrfs_btree_balance_dirty(root, nr);
2340         return err;
2341 }
2342
2343 static struct inode_operations btrfs_dir_inode_operations = {
2344         .lookup         = btrfs_lookup,
2345         .create         = btrfs_create,
2346         .unlink         = btrfs_unlink,
2347         .link           = btrfs_link,
2348         .mkdir          = btrfs_mkdir,
2349         .rmdir          = btrfs_rmdir,
2350         .rename         = btrfs_rename,
2351         .symlink        = btrfs_symlink,
2352         .setattr        = btrfs_setattr,
2353         .mknod          = btrfs_mknod,
2354 };
2355
2356 static struct inode_operations btrfs_dir_ro_inode_operations = {
2357         .lookup         = btrfs_lookup,
2358 };
2359
2360 static struct file_operations btrfs_dir_file_operations = {
2361         .llseek         = generic_file_llseek,
2362         .read           = generic_read_dir,
2363         .readdir        = btrfs_readdir,
2364         .unlocked_ioctl = btrfs_ioctl,
2365 #ifdef CONFIG_COMPAT
2366         .compat_ioctl   = btrfs_ioctl,
2367 #endif
2368 };
2369
2370 static struct extent_map_ops btrfs_extent_map_ops = {
2371         .fill_delalloc = run_delalloc_range,
2372         .writepage_io_hook = btrfs_writepage_io_hook,
2373         .readpage_io_hook = btrfs_readpage_io_hook,
2374         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
2375 };
2376
2377 static struct address_space_operations btrfs_aops = {
2378         .readpage       = btrfs_readpage,
2379         .writepage      = btrfs_writepage,
2380         .sync_page      = block_sync_page,
2381         .prepare_write  = btrfs_prepare_write,
2382         .commit_write   = btrfs_commit_write,
2383         .bmap           = btrfs_bmap,
2384         .invalidatepage = btrfs_invalidatepage,
2385         .releasepage    = btrfs_releasepage,
2386         .set_page_dirty = __set_page_dirty_nobuffers,
2387 };
2388
2389 static struct address_space_operations btrfs_symlink_aops = {
2390         .readpage       = btrfs_readpage,
2391         .writepage      = btrfs_writepage,
2392         .invalidatepage = btrfs_invalidatepage,
2393         .releasepage    = btrfs_releasepage,
2394 };
2395
2396 static struct inode_operations btrfs_file_inode_operations = {
2397         .truncate       = btrfs_truncate,
2398         .getattr        = btrfs_getattr,
2399         .setattr        = btrfs_setattr,
2400 };
2401
2402 static struct inode_operations btrfs_special_inode_operations = {
2403         .getattr        = btrfs_getattr,
2404         .setattr        = btrfs_setattr,
2405 };
2406
2407 static struct inode_operations btrfs_symlink_inode_operations = {
2408         .readlink       = generic_readlink,
2409         .follow_link    = page_follow_link_light,
2410         .put_link       = page_put_link,
2411 };