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