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