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