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