]> git.karo-electronics.de Git - karo-tx-linux.git/blob - fs/btrfs/inode.c
Btrfs: tweak the delayed inode reservations again
[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/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include "compat.h"
42 #include "ctree.h"
43 #include "disk-io.h"
44 #include "transaction.h"
45 #include "btrfs_inode.h"
46 #include "ioctl.h"
47 #include "print-tree.h"
48 #include "ordered-data.h"
49 #include "xattr.h"
50 #include "tree-log.h"
51 #include "volumes.h"
52 #include "compression.h"
53 #include "locking.h"
54 #include "free-space-cache.h"
55 #include "inode-map.h"
56
57 struct btrfs_iget_args {
58         u64 ino;
59         struct btrfs_root *root;
60 };
61
62 static const struct inode_operations btrfs_dir_inode_operations;
63 static const struct inode_operations btrfs_symlink_inode_operations;
64 static const struct inode_operations btrfs_dir_ro_inode_operations;
65 static const struct inode_operations btrfs_special_inode_operations;
66 static const struct inode_operations btrfs_file_inode_operations;
67 static const struct address_space_operations btrfs_aops;
68 static const struct address_space_operations btrfs_symlink_aops;
69 static const struct file_operations btrfs_dir_file_operations;
70 static struct extent_io_ops btrfs_extent_io_ops;
71
72 static struct kmem_cache *btrfs_inode_cachep;
73 struct kmem_cache *btrfs_trans_handle_cachep;
74 struct kmem_cache *btrfs_transaction_cachep;
75 struct kmem_cache *btrfs_path_cachep;
76 struct kmem_cache *btrfs_free_space_cachep;
77
78 #define S_SHIFT 12
79 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
80         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
81         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
82         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
83         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
84         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
85         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
86         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
87 };
88
89 static int btrfs_setsize(struct inode *inode, loff_t newsize);
90 static int btrfs_truncate(struct inode *inode);
91 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
92 static noinline int cow_file_range(struct inode *inode,
93                                    struct page *locked_page,
94                                    u64 start, u64 end, int *page_started,
95                                    unsigned long *nr_written, int unlock);
96 static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
97                                 struct btrfs_root *root, struct inode *inode);
98
99 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
100                                      struct inode *inode,  struct inode *dir,
101                                      const struct qstr *qstr)
102 {
103         int err;
104
105         err = btrfs_init_acl(trans, inode, dir);
106         if (!err)
107                 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
108         return err;
109 }
110
111 /*
112  * this does all the hard work for inserting an inline extent into
113  * the btree.  The caller should have done a btrfs_drop_extents so that
114  * no overlapping inline items exist in the btree
115  */
116 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
117                                 struct btrfs_root *root, struct inode *inode,
118                                 u64 start, size_t size, size_t compressed_size,
119                                 int compress_type,
120                                 struct page **compressed_pages)
121 {
122         struct btrfs_key key;
123         struct btrfs_path *path;
124         struct extent_buffer *leaf;
125         struct page *page = NULL;
126         char *kaddr;
127         unsigned long ptr;
128         struct btrfs_file_extent_item *ei;
129         int err = 0;
130         int ret;
131         size_t cur_size = size;
132         size_t datasize;
133         unsigned long offset;
134
135         if (compressed_size && compressed_pages)
136                 cur_size = compressed_size;
137
138         path = btrfs_alloc_path();
139         if (!path)
140                 return -ENOMEM;
141
142         path->leave_spinning = 1;
143
144         key.objectid = btrfs_ino(inode);
145         key.offset = start;
146         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
147         datasize = btrfs_file_extent_calc_inline_size(cur_size);
148
149         inode_add_bytes(inode, size);
150         ret = btrfs_insert_empty_item(trans, root, path, &key,
151                                       datasize);
152         BUG_ON(ret);
153         if (ret) {
154                 err = ret;
155                 goto fail;
156         }
157         leaf = path->nodes[0];
158         ei = btrfs_item_ptr(leaf, path->slots[0],
159                             struct btrfs_file_extent_item);
160         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
161         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
162         btrfs_set_file_extent_encryption(leaf, ei, 0);
163         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
164         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
165         ptr = btrfs_file_extent_inline_start(ei);
166
167         if (compress_type != BTRFS_COMPRESS_NONE) {
168                 struct page *cpage;
169                 int i = 0;
170                 while (compressed_size > 0) {
171                         cpage = compressed_pages[i];
172                         cur_size = min_t(unsigned long, compressed_size,
173                                        PAGE_CACHE_SIZE);
174
175                         kaddr = kmap_atomic(cpage, KM_USER0);
176                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
177                         kunmap_atomic(kaddr, KM_USER0);
178
179                         i++;
180                         ptr += cur_size;
181                         compressed_size -= cur_size;
182                 }
183                 btrfs_set_file_extent_compression(leaf, ei,
184                                                   compress_type);
185         } else {
186                 page = find_get_page(inode->i_mapping,
187                                      start >> PAGE_CACHE_SHIFT);
188                 btrfs_set_file_extent_compression(leaf, ei, 0);
189                 kaddr = kmap_atomic(page, KM_USER0);
190                 offset = start & (PAGE_CACHE_SIZE - 1);
191                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
192                 kunmap_atomic(kaddr, KM_USER0);
193                 page_cache_release(page);
194         }
195         btrfs_mark_buffer_dirty(leaf);
196         btrfs_free_path(path);
197
198         /*
199          * we're an inline extent, so nobody can
200          * extend the file past i_size without locking
201          * a page we already have locked.
202          *
203          * We must do any isize and inode updates
204          * before we unlock the pages.  Otherwise we
205          * could end up racing with unlink.
206          */
207         BTRFS_I(inode)->disk_i_size = inode->i_size;
208         btrfs_update_inode(trans, root, inode);
209
210         return 0;
211 fail:
212         btrfs_free_path(path);
213         return err;
214 }
215
216
217 /*
218  * conditionally insert an inline extent into the file.  This
219  * does the checks required to make sure the data is small enough
220  * to fit as an inline extent.
221  */
222 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
223                                  struct btrfs_root *root,
224                                  struct inode *inode, u64 start, u64 end,
225                                  size_t compressed_size, int compress_type,
226                                  struct page **compressed_pages)
227 {
228         u64 isize = i_size_read(inode);
229         u64 actual_end = min(end + 1, isize);
230         u64 inline_len = actual_end - start;
231         u64 aligned_end = (end + root->sectorsize - 1) &
232                         ~((u64)root->sectorsize - 1);
233         u64 hint_byte;
234         u64 data_len = inline_len;
235         int ret;
236
237         if (compressed_size)
238                 data_len = compressed_size;
239
240         if (start > 0 ||
241             actual_end >= PAGE_CACHE_SIZE ||
242             data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
243             (!compressed_size &&
244             (actual_end & (root->sectorsize - 1)) == 0) ||
245             end + 1 < isize ||
246             data_len > root->fs_info->max_inline) {
247                 return 1;
248         }
249
250         ret = btrfs_drop_extents(trans, inode, start, aligned_end,
251                                  &hint_byte, 1);
252         BUG_ON(ret);
253
254         if (isize > actual_end)
255                 inline_len = min_t(u64, isize, actual_end);
256         ret = insert_inline_extent(trans, root, inode, start,
257                                    inline_len, compressed_size,
258                                    compress_type, compressed_pages);
259         BUG_ON(ret);
260         btrfs_delalloc_release_metadata(inode, end + 1 - start);
261         btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
262         return 0;
263 }
264
265 struct async_extent {
266         u64 start;
267         u64 ram_size;
268         u64 compressed_size;
269         struct page **pages;
270         unsigned long nr_pages;
271         int compress_type;
272         struct list_head list;
273 };
274
275 struct async_cow {
276         struct inode *inode;
277         struct btrfs_root *root;
278         struct page *locked_page;
279         u64 start;
280         u64 end;
281         struct list_head extents;
282         struct btrfs_work work;
283 };
284
285 static noinline int add_async_extent(struct async_cow *cow,
286                                      u64 start, u64 ram_size,
287                                      u64 compressed_size,
288                                      struct page **pages,
289                                      unsigned long nr_pages,
290                                      int compress_type)
291 {
292         struct async_extent *async_extent;
293
294         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
295         BUG_ON(!async_extent);
296         async_extent->start = start;
297         async_extent->ram_size = ram_size;
298         async_extent->compressed_size = compressed_size;
299         async_extent->pages = pages;
300         async_extent->nr_pages = nr_pages;
301         async_extent->compress_type = compress_type;
302         list_add_tail(&async_extent->list, &cow->extents);
303         return 0;
304 }
305
306 /*
307  * we create compressed extents in two phases.  The first
308  * phase compresses a range of pages that have already been
309  * locked (both pages and state bits are locked).
310  *
311  * This is done inside an ordered work queue, and the compression
312  * is spread across many cpus.  The actual IO submission is step
313  * two, and the ordered work queue takes care of making sure that
314  * happens in the same order things were put onto the queue by
315  * writepages and friends.
316  *
317  * If this code finds it can't get good compression, it puts an
318  * entry onto the work queue to write the uncompressed bytes.  This
319  * makes sure that both compressed inodes and uncompressed inodes
320  * are written in the same order that pdflush sent them down.
321  */
322 static noinline int compress_file_range(struct inode *inode,
323                                         struct page *locked_page,
324                                         u64 start, u64 end,
325                                         struct async_cow *async_cow,
326                                         int *num_added)
327 {
328         struct btrfs_root *root = BTRFS_I(inode)->root;
329         struct btrfs_trans_handle *trans;
330         u64 num_bytes;
331         u64 blocksize = root->sectorsize;
332         u64 actual_end;
333         u64 isize = i_size_read(inode);
334         int ret = 0;
335         struct page **pages = NULL;
336         unsigned long nr_pages;
337         unsigned long nr_pages_ret = 0;
338         unsigned long total_compressed = 0;
339         unsigned long total_in = 0;
340         unsigned long max_compressed = 128 * 1024;
341         unsigned long max_uncompressed = 128 * 1024;
342         int i;
343         int will_compress;
344         int compress_type = root->fs_info->compress_type;
345
346         /* if this is a small write inside eof, kick off a defragbot */
347         if (end <= BTRFS_I(inode)->disk_i_size && (end - start + 1) < 16 * 1024)
348                 btrfs_add_inode_defrag(NULL, inode);
349
350         actual_end = min_t(u64, isize, end + 1);
351 again:
352         will_compress = 0;
353         nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
354         nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
355
356         /*
357          * we don't want to send crud past the end of i_size through
358          * compression, that's just a waste of CPU time.  So, if the
359          * end of the file is before the start of our current
360          * requested range of bytes, we bail out to the uncompressed
361          * cleanup code that can deal with all of this.
362          *
363          * It isn't really the fastest way to fix things, but this is a
364          * very uncommon corner.
365          */
366         if (actual_end <= start)
367                 goto cleanup_and_bail_uncompressed;
368
369         total_compressed = actual_end - start;
370
371         /* we want to make sure that amount of ram required to uncompress
372          * an extent is reasonable, so we limit the total size in ram
373          * of a compressed extent to 128k.  This is a crucial number
374          * because it also controls how easily we can spread reads across
375          * cpus for decompression.
376          *
377          * We also want to make sure the amount of IO required to do
378          * a random read is reasonably small, so we limit the size of
379          * a compressed extent to 128k.
380          */
381         total_compressed = min(total_compressed, max_uncompressed);
382         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
383         num_bytes = max(blocksize,  num_bytes);
384         total_in = 0;
385         ret = 0;
386
387         /*
388          * we do compression for mount -o compress and when the
389          * inode has not been flagged as nocompress.  This flag can
390          * change at any time if we discover bad compression ratios.
391          */
392         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
393             (btrfs_test_opt(root, COMPRESS) ||
394              (BTRFS_I(inode)->force_compress) ||
395              (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
396                 WARN_ON(pages);
397                 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
398                 if (!pages) {
399                         /* just bail out to the uncompressed code */
400                         goto cont;
401                 }
402
403                 if (BTRFS_I(inode)->force_compress)
404                         compress_type = BTRFS_I(inode)->force_compress;
405
406                 ret = btrfs_compress_pages(compress_type,
407                                            inode->i_mapping, start,
408                                            total_compressed, pages,
409                                            nr_pages, &nr_pages_ret,
410                                            &total_in,
411                                            &total_compressed,
412                                            max_compressed);
413
414                 if (!ret) {
415                         unsigned long offset = total_compressed &
416                                 (PAGE_CACHE_SIZE - 1);
417                         struct page *page = pages[nr_pages_ret - 1];
418                         char *kaddr;
419
420                         /* zero the tail end of the last page, we might be
421                          * sending it down to disk
422                          */
423                         if (offset) {
424                                 kaddr = kmap_atomic(page, KM_USER0);
425                                 memset(kaddr + offset, 0,
426                                        PAGE_CACHE_SIZE - offset);
427                                 kunmap_atomic(kaddr, KM_USER0);
428                         }
429                         will_compress = 1;
430                 }
431         }
432 cont:
433         if (start == 0) {
434                 trans = btrfs_join_transaction(root);
435                 BUG_ON(IS_ERR(trans));
436                 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
437
438                 /* lets try to make an inline extent */
439                 if (ret || total_in < (actual_end - start)) {
440                         /* we didn't compress the entire range, try
441                          * to make an uncompressed inline extent.
442                          */
443                         ret = cow_file_range_inline(trans, root, inode,
444                                                     start, end, 0, 0, NULL);
445                 } else {
446                         /* try making a compressed inline extent */
447                         ret = cow_file_range_inline(trans, root, inode,
448                                                     start, end,
449                                                     total_compressed,
450                                                     compress_type, pages);
451                 }
452                 if (ret == 0) {
453                         /*
454                          * inline extent creation worked, we don't need
455                          * to create any more async work items.  Unlock
456                          * and free up our temp pages.
457                          */
458                         extent_clear_unlock_delalloc(inode,
459                              &BTRFS_I(inode)->io_tree,
460                              start, end, NULL,
461                              EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
462                              EXTENT_CLEAR_DELALLOC |
463                              EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
464
465                         btrfs_end_transaction(trans, root);
466                         goto free_pages_out;
467                 }
468                 btrfs_end_transaction(trans, root);
469         }
470
471         if (will_compress) {
472                 /*
473                  * we aren't doing an inline extent round the compressed size
474                  * up to a block size boundary so the allocator does sane
475                  * things
476                  */
477                 total_compressed = (total_compressed + blocksize - 1) &
478                         ~(blocksize - 1);
479
480                 /*
481                  * one last check to make sure the compression is really a
482                  * win, compare the page count read with the blocks on disk
483                  */
484                 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
485                         ~(PAGE_CACHE_SIZE - 1);
486                 if (total_compressed >= total_in) {
487                         will_compress = 0;
488                 } else {
489                         num_bytes = total_in;
490                 }
491         }
492         if (!will_compress && pages) {
493                 /*
494                  * the compression code ran but failed to make things smaller,
495                  * free any pages it allocated and our page pointer array
496                  */
497                 for (i = 0; i < nr_pages_ret; i++) {
498                         WARN_ON(pages[i]->mapping);
499                         page_cache_release(pages[i]);
500                 }
501                 kfree(pages);
502                 pages = NULL;
503                 total_compressed = 0;
504                 nr_pages_ret = 0;
505
506                 /* flag the file so we don't compress in the future */
507                 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
508                     !(BTRFS_I(inode)->force_compress)) {
509                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
510                 }
511         }
512         if (will_compress) {
513                 *num_added += 1;
514
515                 /* the async work queues will take care of doing actual
516                  * allocation on disk for these compressed pages,
517                  * and will submit them to the elevator.
518                  */
519                 add_async_extent(async_cow, start, num_bytes,
520                                  total_compressed, pages, nr_pages_ret,
521                                  compress_type);
522
523                 if (start + num_bytes < end) {
524                         start += num_bytes;
525                         pages = NULL;
526                         cond_resched();
527                         goto again;
528                 }
529         } else {
530 cleanup_and_bail_uncompressed:
531                 /*
532                  * No compression, but we still need to write the pages in
533                  * the file we've been given so far.  redirty the locked
534                  * page if it corresponds to our extent and set things up
535                  * for the async work queue to run cow_file_range to do
536                  * the normal delalloc dance
537                  */
538                 if (page_offset(locked_page) >= start &&
539                     page_offset(locked_page) <= end) {
540                         __set_page_dirty_nobuffers(locked_page);
541                         /* unlocked later on in the async handlers */
542                 }
543                 add_async_extent(async_cow, start, end - start + 1,
544                                  0, NULL, 0, BTRFS_COMPRESS_NONE);
545                 *num_added += 1;
546         }
547
548 out:
549         return 0;
550
551 free_pages_out:
552         for (i = 0; i < nr_pages_ret; i++) {
553                 WARN_ON(pages[i]->mapping);
554                 page_cache_release(pages[i]);
555         }
556         kfree(pages);
557
558         goto out;
559 }
560
561 /*
562  * phase two of compressed writeback.  This is the ordered portion
563  * of the code, which only gets called in the order the work was
564  * queued.  We walk all the async extents created by compress_file_range
565  * and send them down to the disk.
566  */
567 static noinline int submit_compressed_extents(struct inode *inode,
568                                               struct async_cow *async_cow)
569 {
570         struct async_extent *async_extent;
571         u64 alloc_hint = 0;
572         struct btrfs_trans_handle *trans;
573         struct btrfs_key ins;
574         struct extent_map *em;
575         struct btrfs_root *root = BTRFS_I(inode)->root;
576         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
577         struct extent_io_tree *io_tree;
578         int ret = 0;
579
580         if (list_empty(&async_cow->extents))
581                 return 0;
582
583
584         while (!list_empty(&async_cow->extents)) {
585                 async_extent = list_entry(async_cow->extents.next,
586                                           struct async_extent, list);
587                 list_del(&async_extent->list);
588
589                 io_tree = &BTRFS_I(inode)->io_tree;
590
591 retry:
592                 /* did the compression code fall back to uncompressed IO? */
593                 if (!async_extent->pages) {
594                         int page_started = 0;
595                         unsigned long nr_written = 0;
596
597                         lock_extent(io_tree, async_extent->start,
598                                          async_extent->start +
599                                          async_extent->ram_size - 1, GFP_NOFS);
600
601                         /* allocate blocks */
602                         ret = cow_file_range(inode, async_cow->locked_page,
603                                              async_extent->start,
604                                              async_extent->start +
605                                              async_extent->ram_size - 1,
606                                              &page_started, &nr_written, 0);
607
608                         /*
609                          * if page_started, cow_file_range inserted an
610                          * inline extent and took care of all the unlocking
611                          * and IO for us.  Otherwise, we need to submit
612                          * all those pages down to the drive.
613                          */
614                         if (!page_started && !ret)
615                                 extent_write_locked_range(io_tree,
616                                                   inode, async_extent->start,
617                                                   async_extent->start +
618                                                   async_extent->ram_size - 1,
619                                                   btrfs_get_extent,
620                                                   WB_SYNC_ALL);
621                         kfree(async_extent);
622                         cond_resched();
623                         continue;
624                 }
625
626                 lock_extent(io_tree, async_extent->start,
627                             async_extent->start + async_extent->ram_size - 1,
628                             GFP_NOFS);
629
630                 trans = btrfs_join_transaction(root);
631                 BUG_ON(IS_ERR(trans));
632                 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
633                 ret = btrfs_reserve_extent(trans, root,
634                                            async_extent->compressed_size,
635                                            async_extent->compressed_size,
636                                            0, alloc_hint,
637                                            (u64)-1, &ins, 1);
638                 btrfs_end_transaction(trans, root);
639
640                 if (ret) {
641                         int i;
642                         for (i = 0; i < async_extent->nr_pages; i++) {
643                                 WARN_ON(async_extent->pages[i]->mapping);
644                                 page_cache_release(async_extent->pages[i]);
645                         }
646                         kfree(async_extent->pages);
647                         async_extent->nr_pages = 0;
648                         async_extent->pages = NULL;
649                         unlock_extent(io_tree, async_extent->start,
650                                       async_extent->start +
651                                       async_extent->ram_size - 1, GFP_NOFS);
652                         goto retry;
653                 }
654
655                 /*
656                  * here we're doing allocation and writeback of the
657                  * compressed pages
658                  */
659                 btrfs_drop_extent_cache(inode, async_extent->start,
660                                         async_extent->start +
661                                         async_extent->ram_size - 1, 0);
662
663                 em = alloc_extent_map();
664                 BUG_ON(!em);
665                 em->start = async_extent->start;
666                 em->len = async_extent->ram_size;
667                 em->orig_start = em->start;
668
669                 em->block_start = ins.objectid;
670                 em->block_len = ins.offset;
671                 em->bdev = root->fs_info->fs_devices->latest_bdev;
672                 em->compress_type = async_extent->compress_type;
673                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
674                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
675
676                 while (1) {
677                         write_lock(&em_tree->lock);
678                         ret = add_extent_mapping(em_tree, em);
679                         write_unlock(&em_tree->lock);
680                         if (ret != -EEXIST) {
681                                 free_extent_map(em);
682                                 break;
683                         }
684                         btrfs_drop_extent_cache(inode, async_extent->start,
685                                                 async_extent->start +
686                                                 async_extent->ram_size - 1, 0);
687                 }
688
689                 ret = btrfs_add_ordered_extent_compress(inode,
690                                                 async_extent->start,
691                                                 ins.objectid,
692                                                 async_extent->ram_size,
693                                                 ins.offset,
694                                                 BTRFS_ORDERED_COMPRESSED,
695                                                 async_extent->compress_type);
696                 BUG_ON(ret);
697
698                 /*
699                  * clear dirty, set writeback and unlock the pages.
700                  */
701                 extent_clear_unlock_delalloc(inode,
702                                 &BTRFS_I(inode)->io_tree,
703                                 async_extent->start,
704                                 async_extent->start +
705                                 async_extent->ram_size - 1,
706                                 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
707                                 EXTENT_CLEAR_UNLOCK |
708                                 EXTENT_CLEAR_DELALLOC |
709                                 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
710
711                 ret = btrfs_submit_compressed_write(inode,
712                                     async_extent->start,
713                                     async_extent->ram_size,
714                                     ins.objectid,
715                                     ins.offset, async_extent->pages,
716                                     async_extent->nr_pages);
717
718                 BUG_ON(ret);
719                 alloc_hint = ins.objectid + ins.offset;
720                 kfree(async_extent);
721                 cond_resched();
722         }
723
724         return 0;
725 }
726
727 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
728                                       u64 num_bytes)
729 {
730         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
731         struct extent_map *em;
732         u64 alloc_hint = 0;
733
734         read_lock(&em_tree->lock);
735         em = search_extent_mapping(em_tree, start, num_bytes);
736         if (em) {
737                 /*
738                  * if block start isn't an actual block number then find the
739                  * first block in this inode and use that as a hint.  If that
740                  * block is also bogus then just don't worry about it.
741                  */
742                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
743                         free_extent_map(em);
744                         em = search_extent_mapping(em_tree, 0, 0);
745                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
746                                 alloc_hint = em->block_start;
747                         if (em)
748                                 free_extent_map(em);
749                 } else {
750                         alloc_hint = em->block_start;
751                         free_extent_map(em);
752                 }
753         }
754         read_unlock(&em_tree->lock);
755
756         return alloc_hint;
757 }
758
759 /*
760  * when extent_io.c finds a delayed allocation range in the file,
761  * the call backs end up in this code.  The basic idea is to
762  * allocate extents on disk for the range, and create ordered data structs
763  * in ram to track those extents.
764  *
765  * locked_page is the page that writepage had locked already.  We use
766  * it to make sure we don't do extra locks or unlocks.
767  *
768  * *page_started is set to one if we unlock locked_page and do everything
769  * required to start IO on it.  It may be clean and already done with
770  * IO when we return.
771  */
772 static noinline int cow_file_range(struct inode *inode,
773                                    struct page *locked_page,
774                                    u64 start, u64 end, int *page_started,
775                                    unsigned long *nr_written,
776                                    int unlock)
777 {
778         struct btrfs_root *root = BTRFS_I(inode)->root;
779         struct btrfs_trans_handle *trans;
780         u64 alloc_hint = 0;
781         u64 num_bytes;
782         unsigned long ram_size;
783         u64 disk_num_bytes;
784         u64 cur_alloc_size;
785         u64 blocksize = root->sectorsize;
786         struct btrfs_key ins;
787         struct extent_map *em;
788         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
789         int ret = 0;
790
791         BUG_ON(btrfs_is_free_space_inode(root, inode));
792         trans = btrfs_join_transaction(root);
793         BUG_ON(IS_ERR(trans));
794         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
795
796         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
797         num_bytes = max(blocksize,  num_bytes);
798         disk_num_bytes = num_bytes;
799         ret = 0;
800
801         /* if this is a small write inside eof, kick off defrag */
802         if (end <= BTRFS_I(inode)->disk_i_size && num_bytes < 64 * 1024)
803                 btrfs_add_inode_defrag(trans, inode);
804
805         if (start == 0) {
806                 /* lets try to make an inline extent */
807                 ret = cow_file_range_inline(trans, root, inode,
808                                             start, end, 0, 0, NULL);
809                 if (ret == 0) {
810                         extent_clear_unlock_delalloc(inode,
811                                      &BTRFS_I(inode)->io_tree,
812                                      start, end, NULL,
813                                      EXTENT_CLEAR_UNLOCK_PAGE |
814                                      EXTENT_CLEAR_UNLOCK |
815                                      EXTENT_CLEAR_DELALLOC |
816                                      EXTENT_CLEAR_DIRTY |
817                                      EXTENT_SET_WRITEBACK |
818                                      EXTENT_END_WRITEBACK);
819
820                         *nr_written = *nr_written +
821                              (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
822                         *page_started = 1;
823                         ret = 0;
824                         goto out;
825                 }
826         }
827
828         BUG_ON(disk_num_bytes >
829                btrfs_super_total_bytes(root->fs_info->super_copy));
830
831         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
832         btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
833
834         while (disk_num_bytes > 0) {
835                 unsigned long op;
836
837                 cur_alloc_size = disk_num_bytes;
838                 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
839                                            root->sectorsize, 0, alloc_hint,
840                                            (u64)-1, &ins, 1);
841                 BUG_ON(ret);
842
843                 em = alloc_extent_map();
844                 BUG_ON(!em);
845                 em->start = start;
846                 em->orig_start = em->start;
847                 ram_size = ins.offset;
848                 em->len = ins.offset;
849
850                 em->block_start = ins.objectid;
851                 em->block_len = ins.offset;
852                 em->bdev = root->fs_info->fs_devices->latest_bdev;
853                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
854
855                 while (1) {
856                         write_lock(&em_tree->lock);
857                         ret = add_extent_mapping(em_tree, em);
858                         write_unlock(&em_tree->lock);
859                         if (ret != -EEXIST) {
860                                 free_extent_map(em);
861                                 break;
862                         }
863                         btrfs_drop_extent_cache(inode, start,
864                                                 start + ram_size - 1, 0);
865                 }
866
867                 cur_alloc_size = ins.offset;
868                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
869                                                ram_size, cur_alloc_size, 0);
870                 BUG_ON(ret);
871
872                 if (root->root_key.objectid ==
873                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
874                         ret = btrfs_reloc_clone_csums(inode, start,
875                                                       cur_alloc_size);
876                         BUG_ON(ret);
877                 }
878
879                 if (disk_num_bytes < cur_alloc_size)
880                         break;
881
882                 /* we're not doing compressed IO, don't unlock the first
883                  * page (which the caller expects to stay locked), don't
884                  * clear any dirty bits and don't set any writeback bits
885                  *
886                  * Do set the Private2 bit so we know this page was properly
887                  * setup for writepage
888                  */
889                 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
890                 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
891                         EXTENT_SET_PRIVATE2;
892
893                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
894                                              start, start + ram_size - 1,
895                                              locked_page, op);
896                 disk_num_bytes -= cur_alloc_size;
897                 num_bytes -= cur_alloc_size;
898                 alloc_hint = ins.objectid + ins.offset;
899                 start += cur_alloc_size;
900         }
901 out:
902         ret = 0;
903         btrfs_end_transaction(trans, root);
904
905         return ret;
906 }
907
908 /*
909  * work queue call back to started compression on a file and pages
910  */
911 static noinline void async_cow_start(struct btrfs_work *work)
912 {
913         struct async_cow *async_cow;
914         int num_added = 0;
915         async_cow = container_of(work, struct async_cow, work);
916
917         compress_file_range(async_cow->inode, async_cow->locked_page,
918                             async_cow->start, async_cow->end, async_cow,
919                             &num_added);
920         if (num_added == 0)
921                 async_cow->inode = NULL;
922 }
923
924 /*
925  * work queue call back to submit previously compressed pages
926  */
927 static noinline void async_cow_submit(struct btrfs_work *work)
928 {
929         struct async_cow *async_cow;
930         struct btrfs_root *root;
931         unsigned long nr_pages;
932
933         async_cow = container_of(work, struct async_cow, work);
934
935         root = async_cow->root;
936         nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
937                 PAGE_CACHE_SHIFT;
938
939         atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
940
941         if (atomic_read(&root->fs_info->async_delalloc_pages) <
942             5 * 1042 * 1024 &&
943             waitqueue_active(&root->fs_info->async_submit_wait))
944                 wake_up(&root->fs_info->async_submit_wait);
945
946         if (async_cow->inode)
947                 submit_compressed_extents(async_cow->inode, async_cow);
948 }
949
950 static noinline void async_cow_free(struct btrfs_work *work)
951 {
952         struct async_cow *async_cow;
953         async_cow = container_of(work, struct async_cow, work);
954         kfree(async_cow);
955 }
956
957 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
958                                 u64 start, u64 end, int *page_started,
959                                 unsigned long *nr_written)
960 {
961         struct async_cow *async_cow;
962         struct btrfs_root *root = BTRFS_I(inode)->root;
963         unsigned long nr_pages;
964         u64 cur_end;
965         int limit = 10 * 1024 * 1042;
966
967         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
968                          1, 0, NULL, GFP_NOFS);
969         while (start < end) {
970                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
971                 BUG_ON(!async_cow);
972                 async_cow->inode = inode;
973                 async_cow->root = root;
974                 async_cow->locked_page = locked_page;
975                 async_cow->start = start;
976
977                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
978                         cur_end = end;
979                 else
980                         cur_end = min(end, start + 512 * 1024 - 1);
981
982                 async_cow->end = cur_end;
983                 INIT_LIST_HEAD(&async_cow->extents);
984
985                 async_cow->work.func = async_cow_start;
986                 async_cow->work.ordered_func = async_cow_submit;
987                 async_cow->work.ordered_free = async_cow_free;
988                 async_cow->work.flags = 0;
989
990                 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
991                         PAGE_CACHE_SHIFT;
992                 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
993
994                 btrfs_queue_worker(&root->fs_info->delalloc_workers,
995                                    &async_cow->work);
996
997                 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
998                         wait_event(root->fs_info->async_submit_wait,
999                            (atomic_read(&root->fs_info->async_delalloc_pages) <
1000                             limit));
1001                 }
1002
1003                 while (atomic_read(&root->fs_info->async_submit_draining) &&
1004                       atomic_read(&root->fs_info->async_delalloc_pages)) {
1005                         wait_event(root->fs_info->async_submit_wait,
1006                           (atomic_read(&root->fs_info->async_delalloc_pages) ==
1007                            0));
1008                 }
1009
1010                 *nr_written += nr_pages;
1011                 start = cur_end + 1;
1012         }
1013         *page_started = 1;
1014         return 0;
1015 }
1016
1017 static noinline int csum_exist_in_range(struct btrfs_root *root,
1018                                         u64 bytenr, u64 num_bytes)
1019 {
1020         int ret;
1021         struct btrfs_ordered_sum *sums;
1022         LIST_HEAD(list);
1023
1024         ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1025                                        bytenr + num_bytes - 1, &list, 0);
1026         if (ret == 0 && list_empty(&list))
1027                 return 0;
1028
1029         while (!list_empty(&list)) {
1030                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1031                 list_del(&sums->list);
1032                 kfree(sums);
1033         }
1034         return 1;
1035 }
1036
1037 /*
1038  * when nowcow writeback call back.  This checks for snapshots or COW copies
1039  * of the extents that exist in the file, and COWs the file as required.
1040  *
1041  * If no cow copies or snapshots exist, we write directly to the existing
1042  * blocks on disk
1043  */
1044 static noinline int run_delalloc_nocow(struct inode *inode,
1045                                        struct page *locked_page,
1046                               u64 start, u64 end, int *page_started, int force,
1047                               unsigned long *nr_written)
1048 {
1049         struct btrfs_root *root = BTRFS_I(inode)->root;
1050         struct btrfs_trans_handle *trans;
1051         struct extent_buffer *leaf;
1052         struct btrfs_path *path;
1053         struct btrfs_file_extent_item *fi;
1054         struct btrfs_key found_key;
1055         u64 cow_start;
1056         u64 cur_offset;
1057         u64 extent_end;
1058         u64 extent_offset;
1059         u64 disk_bytenr;
1060         u64 num_bytes;
1061         int extent_type;
1062         int ret;
1063         int type;
1064         int nocow;
1065         int check_prev = 1;
1066         bool nolock;
1067         u64 ino = btrfs_ino(inode);
1068
1069         path = btrfs_alloc_path();
1070         if (!path)
1071                 return -ENOMEM;
1072
1073         nolock = btrfs_is_free_space_inode(root, inode);
1074
1075         if (nolock)
1076                 trans = btrfs_join_transaction_nolock(root);
1077         else
1078                 trans = btrfs_join_transaction(root);
1079
1080         BUG_ON(IS_ERR(trans));
1081         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1082
1083         cow_start = (u64)-1;
1084         cur_offset = start;
1085         while (1) {
1086                 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1087                                                cur_offset, 0);
1088                 BUG_ON(ret < 0);
1089                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1090                         leaf = path->nodes[0];
1091                         btrfs_item_key_to_cpu(leaf, &found_key,
1092                                               path->slots[0] - 1);
1093                         if (found_key.objectid == ino &&
1094                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1095                                 path->slots[0]--;
1096                 }
1097                 check_prev = 0;
1098 next_slot:
1099                 leaf = path->nodes[0];
1100                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1101                         ret = btrfs_next_leaf(root, path);
1102                         if (ret < 0)
1103                                 BUG_ON(1);
1104                         if (ret > 0)
1105                                 break;
1106                         leaf = path->nodes[0];
1107                 }
1108
1109                 nocow = 0;
1110                 disk_bytenr = 0;
1111                 num_bytes = 0;
1112                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1113
1114                 if (found_key.objectid > ino ||
1115                     found_key.type > BTRFS_EXTENT_DATA_KEY ||
1116                     found_key.offset > end)
1117                         break;
1118
1119                 if (found_key.offset > cur_offset) {
1120                         extent_end = found_key.offset;
1121                         extent_type = 0;
1122                         goto out_check;
1123                 }
1124
1125                 fi = btrfs_item_ptr(leaf, path->slots[0],
1126                                     struct btrfs_file_extent_item);
1127                 extent_type = btrfs_file_extent_type(leaf, fi);
1128
1129                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1130                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1131                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1132                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1133                         extent_end = found_key.offset +
1134                                 btrfs_file_extent_num_bytes(leaf, fi);
1135                         if (extent_end <= start) {
1136                                 path->slots[0]++;
1137                                 goto next_slot;
1138                         }
1139                         if (disk_bytenr == 0)
1140                                 goto out_check;
1141                         if (btrfs_file_extent_compression(leaf, fi) ||
1142                             btrfs_file_extent_encryption(leaf, fi) ||
1143                             btrfs_file_extent_other_encoding(leaf, fi))
1144                                 goto out_check;
1145                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1146                                 goto out_check;
1147                         if (btrfs_extent_readonly(root, disk_bytenr))
1148                                 goto out_check;
1149                         if (btrfs_cross_ref_exist(trans, root, ino,
1150                                                   found_key.offset -
1151                                                   extent_offset, disk_bytenr))
1152                                 goto out_check;
1153                         disk_bytenr += extent_offset;
1154                         disk_bytenr += cur_offset - found_key.offset;
1155                         num_bytes = min(end + 1, extent_end) - cur_offset;
1156                         /*
1157                          * force cow if csum exists in the range.
1158                          * this ensure that csum for a given extent are
1159                          * either valid or do not exist.
1160                          */
1161                         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1162                                 goto out_check;
1163                         nocow = 1;
1164                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1165                         extent_end = found_key.offset +
1166                                 btrfs_file_extent_inline_len(leaf, fi);
1167                         extent_end = ALIGN(extent_end, root->sectorsize);
1168                 } else {
1169                         BUG_ON(1);
1170                 }
1171 out_check:
1172                 if (extent_end <= start) {
1173                         path->slots[0]++;
1174                         goto next_slot;
1175                 }
1176                 if (!nocow) {
1177                         if (cow_start == (u64)-1)
1178                                 cow_start = cur_offset;
1179                         cur_offset = extent_end;
1180                         if (cur_offset > end)
1181                                 break;
1182                         path->slots[0]++;
1183                         goto next_slot;
1184                 }
1185
1186                 btrfs_release_path(path);
1187                 if (cow_start != (u64)-1) {
1188                         ret = cow_file_range(inode, locked_page, cow_start,
1189                                         found_key.offset - 1, page_started,
1190                                         nr_written, 1);
1191                         BUG_ON(ret);
1192                         cow_start = (u64)-1;
1193                 }
1194
1195                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1196                         struct extent_map *em;
1197                         struct extent_map_tree *em_tree;
1198                         em_tree = &BTRFS_I(inode)->extent_tree;
1199                         em = alloc_extent_map();
1200                         BUG_ON(!em);
1201                         em->start = cur_offset;
1202                         em->orig_start = em->start;
1203                         em->len = num_bytes;
1204                         em->block_len = num_bytes;
1205                         em->block_start = disk_bytenr;
1206                         em->bdev = root->fs_info->fs_devices->latest_bdev;
1207                         set_bit(EXTENT_FLAG_PINNED, &em->flags);
1208                         while (1) {
1209                                 write_lock(&em_tree->lock);
1210                                 ret = add_extent_mapping(em_tree, em);
1211                                 write_unlock(&em_tree->lock);
1212                                 if (ret != -EEXIST) {
1213                                         free_extent_map(em);
1214                                         break;
1215                                 }
1216                                 btrfs_drop_extent_cache(inode, em->start,
1217                                                 em->start + em->len - 1, 0);
1218                         }
1219                         type = BTRFS_ORDERED_PREALLOC;
1220                 } else {
1221                         type = BTRFS_ORDERED_NOCOW;
1222                 }
1223
1224                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1225                                                num_bytes, num_bytes, type);
1226                 BUG_ON(ret);
1227
1228                 if (root->root_key.objectid ==
1229                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1230                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1231                                                       num_bytes);
1232                         BUG_ON(ret);
1233                 }
1234
1235                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1236                                 cur_offset, cur_offset + num_bytes - 1,
1237                                 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1238                                 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1239                                 EXTENT_SET_PRIVATE2);
1240                 cur_offset = extent_end;
1241                 if (cur_offset > end)
1242                         break;
1243         }
1244         btrfs_release_path(path);
1245
1246         if (cur_offset <= end && cow_start == (u64)-1)
1247                 cow_start = cur_offset;
1248         if (cow_start != (u64)-1) {
1249                 ret = cow_file_range(inode, locked_page, cow_start, end,
1250                                      page_started, nr_written, 1);
1251                 BUG_ON(ret);
1252         }
1253
1254         if (nolock) {
1255                 ret = btrfs_end_transaction_nolock(trans, root);
1256                 BUG_ON(ret);
1257         } else {
1258                 ret = btrfs_end_transaction(trans, root);
1259                 BUG_ON(ret);
1260         }
1261         btrfs_free_path(path);
1262         return 0;
1263 }
1264
1265 /*
1266  * extent_io.c call back to do delayed allocation processing
1267  */
1268 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1269                               u64 start, u64 end, int *page_started,
1270                               unsigned long *nr_written)
1271 {
1272         int ret;
1273         struct btrfs_root *root = BTRFS_I(inode)->root;
1274
1275         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
1276                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1277                                          page_started, 1, nr_written);
1278         else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
1279                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1280                                          page_started, 0, nr_written);
1281         else if (!btrfs_test_opt(root, COMPRESS) &&
1282                  !(BTRFS_I(inode)->force_compress) &&
1283                  !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))
1284                 ret = cow_file_range(inode, locked_page, start, end,
1285                                       page_started, nr_written, 1);
1286         else
1287                 ret = cow_file_range_async(inode, locked_page, start, end,
1288                                            page_started, nr_written);
1289         return ret;
1290 }
1291
1292 static void btrfs_split_extent_hook(struct inode *inode,
1293                                     struct extent_state *orig, u64 split)
1294 {
1295         /* not delalloc, ignore it */
1296         if (!(orig->state & EXTENT_DELALLOC))
1297                 return;
1298
1299         spin_lock(&BTRFS_I(inode)->lock);
1300         BTRFS_I(inode)->outstanding_extents++;
1301         spin_unlock(&BTRFS_I(inode)->lock);
1302 }
1303
1304 /*
1305  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1306  * extents so we can keep track of new extents that are just merged onto old
1307  * extents, such as when we are doing sequential writes, so we can properly
1308  * account for the metadata space we'll need.
1309  */
1310 static void btrfs_merge_extent_hook(struct inode *inode,
1311                                     struct extent_state *new,
1312                                     struct extent_state *other)
1313 {
1314         /* not delalloc, ignore it */
1315         if (!(other->state & EXTENT_DELALLOC))
1316                 return;
1317
1318         spin_lock(&BTRFS_I(inode)->lock);
1319         BTRFS_I(inode)->outstanding_extents--;
1320         spin_unlock(&BTRFS_I(inode)->lock);
1321 }
1322
1323 /*
1324  * extent_io.c set_bit_hook, used to track delayed allocation
1325  * bytes in this file, and to maintain the list of inodes that
1326  * have pending delalloc work to be done.
1327  */
1328 static void btrfs_set_bit_hook(struct inode *inode,
1329                                struct extent_state *state, int *bits)
1330 {
1331
1332         /*
1333          * set_bit and clear bit hooks normally require _irqsave/restore
1334          * but in this case, we are only testing for the DELALLOC
1335          * bit, which is only set or cleared with irqs on
1336          */
1337         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1338                 struct btrfs_root *root = BTRFS_I(inode)->root;
1339                 u64 len = state->end + 1 - state->start;
1340                 bool do_list = !btrfs_is_free_space_inode(root, inode);
1341
1342                 if (*bits & EXTENT_FIRST_DELALLOC) {
1343                         *bits &= ~EXTENT_FIRST_DELALLOC;
1344                 } else {
1345                         spin_lock(&BTRFS_I(inode)->lock);
1346                         BTRFS_I(inode)->outstanding_extents++;
1347                         spin_unlock(&BTRFS_I(inode)->lock);
1348                 }
1349
1350                 spin_lock(&root->fs_info->delalloc_lock);
1351                 BTRFS_I(inode)->delalloc_bytes += len;
1352                 root->fs_info->delalloc_bytes += len;
1353                 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1354                         list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1355                                       &root->fs_info->delalloc_inodes);
1356                 }
1357                 spin_unlock(&root->fs_info->delalloc_lock);
1358         }
1359 }
1360
1361 /*
1362  * extent_io.c clear_bit_hook, see set_bit_hook for why
1363  */
1364 static void btrfs_clear_bit_hook(struct inode *inode,
1365                                  struct extent_state *state, int *bits)
1366 {
1367         /*
1368          * set_bit and clear bit hooks normally require _irqsave/restore
1369          * but in this case, we are only testing for the DELALLOC
1370          * bit, which is only set or cleared with irqs on
1371          */
1372         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1373                 struct btrfs_root *root = BTRFS_I(inode)->root;
1374                 u64 len = state->end + 1 - state->start;
1375                 bool do_list = !btrfs_is_free_space_inode(root, inode);
1376
1377                 if (*bits & EXTENT_FIRST_DELALLOC) {
1378                         *bits &= ~EXTENT_FIRST_DELALLOC;
1379                 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1380                         spin_lock(&BTRFS_I(inode)->lock);
1381                         BTRFS_I(inode)->outstanding_extents--;
1382                         spin_unlock(&BTRFS_I(inode)->lock);
1383                 }
1384
1385                 if (*bits & EXTENT_DO_ACCOUNTING)
1386                         btrfs_delalloc_release_metadata(inode, len);
1387
1388                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1389                     && do_list)
1390                         btrfs_free_reserved_data_space(inode, len);
1391
1392                 spin_lock(&root->fs_info->delalloc_lock);
1393                 root->fs_info->delalloc_bytes -= len;
1394                 BTRFS_I(inode)->delalloc_bytes -= len;
1395
1396                 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1397                     !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1398                         list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1399                 }
1400                 spin_unlock(&root->fs_info->delalloc_lock);
1401         }
1402 }
1403
1404 /*
1405  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1406  * we don't create bios that span stripes or chunks
1407  */
1408 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1409                          size_t size, struct bio *bio,
1410                          unsigned long bio_flags)
1411 {
1412         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1413         struct btrfs_mapping_tree *map_tree;
1414         u64 logical = (u64)bio->bi_sector << 9;
1415         u64 length = 0;
1416         u64 map_length;
1417         int ret;
1418
1419         if (bio_flags & EXTENT_BIO_COMPRESSED)
1420                 return 0;
1421
1422         length = bio->bi_size;
1423         map_tree = &root->fs_info->mapping_tree;
1424         map_length = length;
1425         ret = btrfs_map_block(map_tree, READ, logical,
1426                               &map_length, NULL, 0);
1427
1428         if (map_length < length + size)
1429                 return 1;
1430         return ret;
1431 }
1432
1433 /*
1434  * in order to insert checksums into the metadata in large chunks,
1435  * we wait until bio submission time.   All the pages in the bio are
1436  * checksummed and sums are attached onto the ordered extent record.
1437  *
1438  * At IO completion time the cums attached on the ordered extent record
1439  * are inserted into the btree
1440  */
1441 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1442                                     struct bio *bio, int mirror_num,
1443                                     unsigned long bio_flags,
1444                                     u64 bio_offset)
1445 {
1446         struct btrfs_root *root = BTRFS_I(inode)->root;
1447         int ret = 0;
1448
1449         ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1450         BUG_ON(ret);
1451         return 0;
1452 }
1453
1454 /*
1455  * in order to insert checksums into the metadata in large chunks,
1456  * we wait until bio submission time.   All the pages in the bio are
1457  * checksummed and sums are attached onto the ordered extent record.
1458  *
1459  * At IO completion time the cums attached on the ordered extent record
1460  * are inserted into the btree
1461  */
1462 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1463                           int mirror_num, unsigned long bio_flags,
1464                           u64 bio_offset)
1465 {
1466         struct btrfs_root *root = BTRFS_I(inode)->root;
1467         return btrfs_map_bio(root, rw, bio, mirror_num, 1);
1468 }
1469
1470 /*
1471  * extent_io.c submission hook. This does the right thing for csum calculation
1472  * on write, or reading the csums from the tree before a read
1473  */
1474 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1475                           int mirror_num, unsigned long bio_flags,
1476                           u64 bio_offset)
1477 {
1478         struct btrfs_root *root = BTRFS_I(inode)->root;
1479         int ret = 0;
1480         int skip_sum;
1481
1482         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1483
1484         if (btrfs_is_free_space_inode(root, inode))
1485                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 2);
1486         else
1487                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
1488         BUG_ON(ret);
1489
1490         if (!(rw & REQ_WRITE)) {
1491                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1492                         return btrfs_submit_compressed_read(inode, bio,
1493                                                     mirror_num, bio_flags);
1494                 } else if (!skip_sum) {
1495                         ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1496                         if (ret)
1497                                 return ret;
1498                 }
1499                 goto mapit;
1500         } else if (!skip_sum) {
1501                 /* csum items have already been cloned */
1502                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1503                         goto mapit;
1504                 /* we're doing a write, do the async checksumming */
1505                 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1506                                    inode, rw, bio, mirror_num,
1507                                    bio_flags, bio_offset,
1508                                    __btrfs_submit_bio_start,
1509                                    __btrfs_submit_bio_done);
1510         }
1511
1512 mapit:
1513         return btrfs_map_bio(root, rw, bio, mirror_num, 0);
1514 }
1515
1516 /*
1517  * given a list of ordered sums record them in the inode.  This happens
1518  * at IO completion time based on sums calculated at bio submission time.
1519  */
1520 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1521                              struct inode *inode, u64 file_offset,
1522                              struct list_head *list)
1523 {
1524         struct btrfs_ordered_sum *sum;
1525
1526         list_for_each_entry(sum, list, list) {
1527                 btrfs_csum_file_blocks(trans,
1528                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
1529         }
1530         return 0;
1531 }
1532
1533 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1534                               struct extent_state **cached_state)
1535 {
1536         if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
1537                 WARN_ON(1);
1538         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1539                                    cached_state, GFP_NOFS);
1540 }
1541
1542 /* see btrfs_writepage_start_hook for details on why this is required */
1543 struct btrfs_writepage_fixup {
1544         struct page *page;
1545         struct btrfs_work work;
1546 };
1547
1548 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1549 {
1550         struct btrfs_writepage_fixup *fixup;
1551         struct btrfs_ordered_extent *ordered;
1552         struct extent_state *cached_state = NULL;
1553         struct page *page;
1554         struct inode *inode;
1555         u64 page_start;
1556         u64 page_end;
1557
1558         fixup = container_of(work, struct btrfs_writepage_fixup, work);
1559         page = fixup->page;
1560 again:
1561         lock_page(page);
1562         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1563                 ClearPageChecked(page);
1564                 goto out_page;
1565         }
1566
1567         inode = page->mapping->host;
1568         page_start = page_offset(page);
1569         page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1570
1571         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1572                          &cached_state, GFP_NOFS);
1573
1574         /* already ordered? We're done */
1575         if (PagePrivate2(page))
1576                 goto out;
1577
1578         ordered = btrfs_lookup_ordered_extent(inode, page_start);
1579         if (ordered) {
1580                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1581                                      page_end, &cached_state, GFP_NOFS);
1582                 unlock_page(page);
1583                 btrfs_start_ordered_extent(inode, ordered, 1);
1584                 goto again;
1585         }
1586
1587         BUG();
1588         btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1589         ClearPageChecked(page);
1590 out:
1591         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1592                              &cached_state, GFP_NOFS);
1593 out_page:
1594         unlock_page(page);
1595         page_cache_release(page);
1596         kfree(fixup);
1597 }
1598
1599 /*
1600  * There are a few paths in the higher layers of the kernel that directly
1601  * set the page dirty bit without asking the filesystem if it is a
1602  * good idea.  This causes problems because we want to make sure COW
1603  * properly happens and the data=ordered rules are followed.
1604  *
1605  * In our case any range that doesn't have the ORDERED bit set
1606  * hasn't been properly setup for IO.  We kick off an async process
1607  * to fix it up.  The async helper will wait for ordered extents, set
1608  * the delalloc bit and make it safe to write the page.
1609  */
1610 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1611 {
1612         struct inode *inode = page->mapping->host;
1613         struct btrfs_writepage_fixup *fixup;
1614         struct btrfs_root *root = BTRFS_I(inode)->root;
1615
1616         /* this page is properly in the ordered list */
1617         if (TestClearPagePrivate2(page))
1618                 return 0;
1619
1620         if (PageChecked(page))
1621                 return -EAGAIN;
1622
1623         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1624         if (!fixup)
1625                 return -EAGAIN;
1626
1627         SetPageChecked(page);
1628         page_cache_get(page);
1629         fixup->work.func = btrfs_writepage_fixup_worker;
1630         fixup->page = page;
1631         btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1632         return -EAGAIN;
1633 }
1634
1635 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1636                                        struct inode *inode, u64 file_pos,
1637                                        u64 disk_bytenr, u64 disk_num_bytes,
1638                                        u64 num_bytes, u64 ram_bytes,
1639                                        u8 compression, u8 encryption,
1640                                        u16 other_encoding, int extent_type)
1641 {
1642         struct btrfs_root *root = BTRFS_I(inode)->root;
1643         struct btrfs_file_extent_item *fi;
1644         struct btrfs_path *path;
1645         struct extent_buffer *leaf;
1646         struct btrfs_key ins;
1647         u64 hint;
1648         int ret;
1649
1650         path = btrfs_alloc_path();
1651         if (!path)
1652                 return -ENOMEM;
1653
1654         path->leave_spinning = 1;
1655
1656         /*
1657          * we may be replacing one extent in the tree with another.
1658          * The new extent is pinned in the extent map, and we don't want
1659          * to drop it from the cache until it is completely in the btree.
1660          *
1661          * So, tell btrfs_drop_extents to leave this extent in the cache.
1662          * the caller is expected to unpin it and allow it to be merged
1663          * with the others.
1664          */
1665         ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1666                                  &hint, 0);
1667         BUG_ON(ret);
1668
1669         ins.objectid = btrfs_ino(inode);
1670         ins.offset = file_pos;
1671         ins.type = BTRFS_EXTENT_DATA_KEY;
1672         ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1673         BUG_ON(ret);
1674         leaf = path->nodes[0];
1675         fi = btrfs_item_ptr(leaf, path->slots[0],
1676                             struct btrfs_file_extent_item);
1677         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1678         btrfs_set_file_extent_type(leaf, fi, extent_type);
1679         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1680         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1681         btrfs_set_file_extent_offset(leaf, fi, 0);
1682         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1683         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1684         btrfs_set_file_extent_compression(leaf, fi, compression);
1685         btrfs_set_file_extent_encryption(leaf, fi, encryption);
1686         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1687
1688         btrfs_unlock_up_safe(path, 1);
1689         btrfs_set_lock_blocking(leaf);
1690
1691         btrfs_mark_buffer_dirty(leaf);
1692
1693         inode_add_bytes(inode, num_bytes);
1694
1695         ins.objectid = disk_bytenr;
1696         ins.offset = disk_num_bytes;
1697         ins.type = BTRFS_EXTENT_ITEM_KEY;
1698         ret = btrfs_alloc_reserved_file_extent(trans, root,
1699                                         root->root_key.objectid,
1700                                         btrfs_ino(inode), file_pos, &ins);
1701         BUG_ON(ret);
1702         btrfs_free_path(path);
1703
1704         return 0;
1705 }
1706
1707 /*
1708  * helper function for btrfs_finish_ordered_io, this
1709  * just reads in some of the csum leaves to prime them into ram
1710  * before we start the transaction.  It limits the amount of btree
1711  * reads required while inside the transaction.
1712  */
1713 /* as ordered data IO finishes, this gets called so we can finish
1714  * an ordered extent if the range of bytes in the file it covers are
1715  * fully written.
1716  */
1717 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
1718 {
1719         struct btrfs_root *root = BTRFS_I(inode)->root;
1720         struct btrfs_trans_handle *trans = NULL;
1721         struct btrfs_ordered_extent *ordered_extent = NULL;
1722         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1723         struct extent_state *cached_state = NULL;
1724         int compress_type = 0;
1725         int ret;
1726         bool nolock;
1727
1728         ret = btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
1729                                              end - start + 1);
1730         if (!ret)
1731                 return 0;
1732         BUG_ON(!ordered_extent);
1733
1734         nolock = btrfs_is_free_space_inode(root, inode);
1735
1736         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1737                 BUG_ON(!list_empty(&ordered_extent->list));
1738                 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1739                 if (!ret) {
1740                         if (nolock)
1741                                 trans = btrfs_join_transaction_nolock(root);
1742                         else
1743                                 trans = btrfs_join_transaction(root);
1744                         BUG_ON(IS_ERR(trans));
1745                         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1746                         ret = btrfs_update_inode_fallback(trans, root, inode);
1747                         BUG_ON(ret);
1748                 }
1749                 goto out;
1750         }
1751
1752         lock_extent_bits(io_tree, ordered_extent->file_offset,
1753                          ordered_extent->file_offset + ordered_extent->len - 1,
1754                          0, &cached_state, GFP_NOFS);
1755
1756         if (nolock)
1757                 trans = btrfs_join_transaction_nolock(root);
1758         else
1759                 trans = btrfs_join_transaction(root);
1760         BUG_ON(IS_ERR(trans));
1761         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1762
1763         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1764                 compress_type = ordered_extent->compress_type;
1765         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1766                 BUG_ON(compress_type);
1767                 ret = btrfs_mark_extent_written(trans, inode,
1768                                                 ordered_extent->file_offset,
1769                                                 ordered_extent->file_offset +
1770                                                 ordered_extent->len);
1771                 BUG_ON(ret);
1772         } else {
1773                 BUG_ON(root == root->fs_info->tree_root);
1774                 ret = insert_reserved_file_extent(trans, inode,
1775                                                 ordered_extent->file_offset,
1776                                                 ordered_extent->start,
1777                                                 ordered_extent->disk_len,
1778                                                 ordered_extent->len,
1779                                                 ordered_extent->len,
1780                                                 compress_type, 0, 0,
1781                                                 BTRFS_FILE_EXTENT_REG);
1782                 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1783                                    ordered_extent->file_offset,
1784                                    ordered_extent->len);
1785                 BUG_ON(ret);
1786         }
1787         unlock_extent_cached(io_tree, ordered_extent->file_offset,
1788                              ordered_extent->file_offset +
1789                              ordered_extent->len - 1, &cached_state, GFP_NOFS);
1790
1791         add_pending_csums(trans, inode, ordered_extent->file_offset,
1792                           &ordered_extent->list);
1793
1794         ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1795         if (!ret || !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1796                 ret = btrfs_update_inode_fallback(trans, root, inode);
1797                 BUG_ON(ret);
1798         }
1799         ret = 0;
1800 out:
1801         if (root != root->fs_info->tree_root)
1802                 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1803         if (trans) {
1804                 if (nolock)
1805                         btrfs_end_transaction_nolock(trans, root);
1806                 else
1807                         btrfs_end_transaction(trans, root);
1808         }
1809
1810         /* once for us */
1811         btrfs_put_ordered_extent(ordered_extent);
1812         /* once for the tree */
1813         btrfs_put_ordered_extent(ordered_extent);
1814
1815         return 0;
1816 }
1817
1818 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1819                                 struct extent_state *state, int uptodate)
1820 {
1821         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
1822
1823         ClearPagePrivate2(page);
1824         return btrfs_finish_ordered_io(page->mapping->host, start, end);
1825 }
1826
1827 /*
1828  * when reads are done, we need to check csums to verify the data is correct
1829  * if there's a match, we allow the bio to finish.  If not, the code in
1830  * extent_io.c will try to find good copies for us.
1831  */
1832 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
1833                                struct extent_state *state)
1834 {
1835         size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
1836         struct inode *inode = page->mapping->host;
1837         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1838         char *kaddr;
1839         u64 private = ~(u32)0;
1840         int ret;
1841         struct btrfs_root *root = BTRFS_I(inode)->root;
1842         u32 csum = ~(u32)0;
1843
1844         if (PageChecked(page)) {
1845                 ClearPageChecked(page);
1846                 goto good;
1847         }
1848
1849         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
1850                 goto good;
1851
1852         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
1853             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
1854                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
1855                                   GFP_NOFS);
1856                 return 0;
1857         }
1858
1859         if (state && state->start == start) {
1860                 private = state->private;
1861                 ret = 0;
1862         } else {
1863                 ret = get_state_private(io_tree, start, &private);
1864         }
1865         kaddr = kmap_atomic(page, KM_USER0);
1866         if (ret)
1867                 goto zeroit;
1868
1869         csum = btrfs_csum_data(root, kaddr + offset, csum,  end - start + 1);
1870         btrfs_csum_final(csum, (char *)&csum);
1871         if (csum != private)
1872                 goto zeroit;
1873
1874         kunmap_atomic(kaddr, KM_USER0);
1875 good:
1876         return 0;
1877
1878 zeroit:
1879         printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
1880                        "private %llu\n",
1881                        (unsigned long long)btrfs_ino(page->mapping->host),
1882                        (unsigned long long)start, csum,
1883                        (unsigned long long)private);
1884         memset(kaddr + offset, 1, end - start + 1);
1885         flush_dcache_page(page);
1886         kunmap_atomic(kaddr, KM_USER0);
1887         if (private == 0)
1888                 return 0;
1889         return -EIO;
1890 }
1891
1892 struct delayed_iput {
1893         struct list_head list;
1894         struct inode *inode;
1895 };
1896
1897 void btrfs_add_delayed_iput(struct inode *inode)
1898 {
1899         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
1900         struct delayed_iput *delayed;
1901
1902         if (atomic_add_unless(&inode->i_count, -1, 1))
1903                 return;
1904
1905         delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
1906         delayed->inode = inode;
1907
1908         spin_lock(&fs_info->delayed_iput_lock);
1909         list_add_tail(&delayed->list, &fs_info->delayed_iputs);
1910         spin_unlock(&fs_info->delayed_iput_lock);
1911 }
1912
1913 void btrfs_run_delayed_iputs(struct btrfs_root *root)
1914 {
1915         LIST_HEAD(list);
1916         struct btrfs_fs_info *fs_info = root->fs_info;
1917         struct delayed_iput *delayed;
1918         int empty;
1919
1920         spin_lock(&fs_info->delayed_iput_lock);
1921         empty = list_empty(&fs_info->delayed_iputs);
1922         spin_unlock(&fs_info->delayed_iput_lock);
1923         if (empty)
1924                 return;
1925
1926         down_read(&root->fs_info->cleanup_work_sem);
1927         spin_lock(&fs_info->delayed_iput_lock);
1928         list_splice_init(&fs_info->delayed_iputs, &list);
1929         spin_unlock(&fs_info->delayed_iput_lock);
1930
1931         while (!list_empty(&list)) {
1932                 delayed = list_entry(list.next, struct delayed_iput, list);
1933                 list_del(&delayed->list);
1934                 iput(delayed->inode);
1935                 kfree(delayed);
1936         }
1937         up_read(&root->fs_info->cleanup_work_sem);
1938 }
1939
1940 enum btrfs_orphan_cleanup_state {
1941         ORPHAN_CLEANUP_STARTED  = 1,
1942         ORPHAN_CLEANUP_DONE     = 2,
1943 };
1944
1945 /*
1946  * This is called in transaction commmit time. If there are no orphan
1947  * files in the subvolume, it removes orphan item and frees block_rsv
1948  * structure.
1949  */
1950 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
1951                               struct btrfs_root *root)
1952 {
1953         int ret;
1954
1955         if (!list_empty(&root->orphan_list) ||
1956             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
1957                 return;
1958
1959         if (root->orphan_item_inserted &&
1960             btrfs_root_refs(&root->root_item) > 0) {
1961                 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
1962                                             root->root_key.objectid);
1963                 BUG_ON(ret);
1964                 root->orphan_item_inserted = 0;
1965         }
1966
1967         if (root->orphan_block_rsv) {
1968                 WARN_ON(root->orphan_block_rsv->size > 0);
1969                 btrfs_free_block_rsv(root, root->orphan_block_rsv);
1970                 root->orphan_block_rsv = NULL;
1971         }
1972 }
1973
1974 /*
1975  * This creates an orphan entry for the given inode in case something goes
1976  * wrong in the middle of an unlink/truncate.
1977  *
1978  * NOTE: caller of this function should reserve 5 units of metadata for
1979  *       this function.
1980  */
1981 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
1982 {
1983         struct btrfs_root *root = BTRFS_I(inode)->root;
1984         struct btrfs_block_rsv *block_rsv = NULL;
1985         int reserve = 0;
1986         int insert = 0;
1987         int ret;
1988
1989         if (!root->orphan_block_rsv) {
1990                 block_rsv = btrfs_alloc_block_rsv(root);
1991                 if (!block_rsv)
1992                         return -ENOMEM;
1993         }
1994
1995         spin_lock(&root->orphan_lock);
1996         if (!root->orphan_block_rsv) {
1997                 root->orphan_block_rsv = block_rsv;
1998         } else if (block_rsv) {
1999                 btrfs_free_block_rsv(root, block_rsv);
2000                 block_rsv = NULL;
2001         }
2002
2003         if (list_empty(&BTRFS_I(inode)->i_orphan)) {
2004                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2005 #if 0
2006                 /*
2007                  * For proper ENOSPC handling, we should do orphan
2008                  * cleanup when mounting. But this introduces backward
2009                  * compatibility issue.
2010                  */
2011                 if (!xchg(&root->orphan_item_inserted, 1))
2012                         insert = 2;
2013                 else
2014                         insert = 1;
2015 #endif
2016                 insert = 1;
2017         }
2018
2019         if (!BTRFS_I(inode)->orphan_meta_reserved) {
2020                 BTRFS_I(inode)->orphan_meta_reserved = 1;
2021                 reserve = 1;
2022         }
2023         spin_unlock(&root->orphan_lock);
2024
2025         /* grab metadata reservation from transaction handle */
2026         if (reserve) {
2027                 ret = btrfs_orphan_reserve_metadata(trans, inode);
2028                 BUG_ON(ret);
2029         }
2030
2031         /* insert an orphan item to track this unlinked/truncated file */
2032         if (insert >= 1) {
2033                 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2034                 BUG_ON(ret);
2035         }
2036
2037         /* insert an orphan item to track subvolume contains orphan files */
2038         if (insert >= 2) {
2039                 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2040                                                root->root_key.objectid);
2041                 BUG_ON(ret);
2042         }
2043         return 0;
2044 }
2045
2046 /*
2047  * We have done the truncate/delete so we can go ahead and remove the orphan
2048  * item for this particular inode.
2049  */
2050 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2051 {
2052         struct btrfs_root *root = BTRFS_I(inode)->root;
2053         int delete_item = 0;
2054         int release_rsv = 0;
2055         int ret = 0;
2056
2057         spin_lock(&root->orphan_lock);
2058         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
2059                 list_del_init(&BTRFS_I(inode)->i_orphan);
2060                 delete_item = 1;
2061         }
2062
2063         if (BTRFS_I(inode)->orphan_meta_reserved) {
2064                 BTRFS_I(inode)->orphan_meta_reserved = 0;
2065                 release_rsv = 1;
2066         }
2067         spin_unlock(&root->orphan_lock);
2068
2069         if (trans && delete_item) {
2070                 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
2071                 BUG_ON(ret);
2072         }
2073
2074         if (release_rsv)
2075                 btrfs_orphan_release_metadata(inode);
2076
2077         return 0;
2078 }
2079
2080 /*
2081  * this cleans up any orphans that may be left on the list from the last use
2082  * of this root.
2083  */
2084 int btrfs_orphan_cleanup(struct btrfs_root *root)
2085 {
2086         struct btrfs_path *path;
2087         struct extent_buffer *leaf;
2088         struct btrfs_key key, found_key;
2089         struct btrfs_trans_handle *trans;
2090         struct inode *inode;
2091         u64 last_objectid = 0;
2092         int ret = 0, nr_unlink = 0, nr_truncate = 0;
2093
2094         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2095                 return 0;
2096
2097         path = btrfs_alloc_path();
2098         if (!path) {
2099                 ret = -ENOMEM;
2100                 goto out;
2101         }
2102         path->reada = -1;
2103
2104         key.objectid = BTRFS_ORPHAN_OBJECTID;
2105         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2106         key.offset = (u64)-1;
2107
2108         while (1) {
2109                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2110                 if (ret < 0)
2111                         goto out;
2112
2113                 /*
2114                  * if ret == 0 means we found what we were searching for, which
2115                  * is weird, but possible, so only screw with path if we didn't
2116                  * find the key and see if we have stuff that matches
2117                  */
2118                 if (ret > 0) {
2119                         ret = 0;
2120                         if (path->slots[0] == 0)
2121                                 break;
2122                         path->slots[0]--;
2123                 }
2124
2125                 /* pull out the item */
2126                 leaf = path->nodes[0];
2127                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2128
2129                 /* make sure the item matches what we want */
2130                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2131                         break;
2132                 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2133                         break;
2134
2135                 /* release the path since we're done with it */
2136                 btrfs_release_path(path);
2137
2138                 /*
2139                  * this is where we are basically btrfs_lookup, without the
2140                  * crossing root thing.  we store the inode number in the
2141                  * offset of the orphan item.
2142                  */
2143
2144                 if (found_key.offset == last_objectid) {
2145                         printk(KERN_ERR "btrfs: Error removing orphan entry, "
2146                                "stopping orphan cleanup\n");
2147                         ret = -EINVAL;
2148                         goto out;
2149                 }
2150
2151                 last_objectid = found_key.offset;
2152
2153                 found_key.objectid = found_key.offset;
2154                 found_key.type = BTRFS_INODE_ITEM_KEY;
2155                 found_key.offset = 0;
2156                 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2157                 ret = PTR_RET(inode);
2158                 if (ret && ret != -ESTALE)
2159                         goto out;
2160
2161                 /*
2162                  * Inode is already gone but the orphan item is still there,
2163                  * kill the orphan item.
2164                  */
2165                 if (ret == -ESTALE) {
2166                         trans = btrfs_start_transaction(root, 1);
2167                         if (IS_ERR(trans)) {
2168                                 ret = PTR_ERR(trans);
2169                                 goto out;
2170                         }
2171                         ret = btrfs_del_orphan_item(trans, root,
2172                                                     found_key.objectid);
2173                         BUG_ON(ret);
2174                         btrfs_end_transaction(trans, root);
2175                         continue;
2176                 }
2177
2178                 /*
2179                  * add this inode to the orphan list so btrfs_orphan_del does
2180                  * the proper thing when we hit it
2181                  */
2182                 spin_lock(&root->orphan_lock);
2183                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2184                 spin_unlock(&root->orphan_lock);
2185
2186                 /* if we have links, this was a truncate, lets do that */
2187                 if (inode->i_nlink) {
2188                         if (!S_ISREG(inode->i_mode)) {
2189                                 WARN_ON(1);
2190                                 iput(inode);
2191                                 continue;
2192                         }
2193                         nr_truncate++;
2194                         ret = btrfs_truncate(inode);
2195                 } else {
2196                         nr_unlink++;
2197                 }
2198
2199                 /* this will do delete_inode and everything for us */
2200                 iput(inode);
2201                 if (ret)
2202                         goto out;
2203         }
2204         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2205
2206         if (root->orphan_block_rsv)
2207                 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2208                                         (u64)-1);
2209
2210         if (root->orphan_block_rsv || root->orphan_item_inserted) {
2211                 trans = btrfs_join_transaction(root);
2212                 if (!IS_ERR(trans))
2213                         btrfs_end_transaction(trans, root);
2214         }
2215
2216         if (nr_unlink)
2217                 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2218         if (nr_truncate)
2219                 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2220
2221 out:
2222         if (ret)
2223                 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2224         btrfs_free_path(path);
2225         return ret;
2226 }
2227
2228 /*
2229  * very simple check to peek ahead in the leaf looking for xattrs.  If we
2230  * don't find any xattrs, we know there can't be any acls.
2231  *
2232  * slot is the slot the inode is in, objectid is the objectid of the inode
2233  */
2234 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2235                                           int slot, u64 objectid)
2236 {
2237         u32 nritems = btrfs_header_nritems(leaf);
2238         struct btrfs_key found_key;
2239         int scanned = 0;
2240
2241         slot++;
2242         while (slot < nritems) {
2243                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2244
2245                 /* we found a different objectid, there must not be acls */
2246                 if (found_key.objectid != objectid)
2247                         return 0;
2248
2249                 /* we found an xattr, assume we've got an acl */
2250                 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2251                         return 1;
2252
2253                 /*
2254                  * we found a key greater than an xattr key, there can't
2255                  * be any acls later on
2256                  */
2257                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2258                         return 0;
2259
2260                 slot++;
2261                 scanned++;
2262
2263                 /*
2264                  * it goes inode, inode backrefs, xattrs, extents,
2265                  * so if there are a ton of hard links to an inode there can
2266                  * be a lot of backrefs.  Don't waste time searching too hard,
2267                  * this is just an optimization
2268                  */
2269                 if (scanned >= 8)
2270                         break;
2271         }
2272         /* we hit the end of the leaf before we found an xattr or
2273          * something larger than an xattr.  We have to assume the inode
2274          * has acls
2275          */
2276         return 1;
2277 }
2278
2279 /*
2280  * read an inode from the btree into the in-memory inode
2281  */
2282 static void btrfs_read_locked_inode(struct inode *inode)
2283 {
2284         struct btrfs_path *path;
2285         struct extent_buffer *leaf;
2286         struct btrfs_inode_item *inode_item;
2287         struct btrfs_timespec *tspec;
2288         struct btrfs_root *root = BTRFS_I(inode)->root;
2289         struct btrfs_key location;
2290         int maybe_acls;
2291         u32 rdev;
2292         int ret;
2293         bool filled = false;
2294
2295         ret = btrfs_fill_inode(inode, &rdev);
2296         if (!ret)
2297                 filled = true;
2298
2299         path = btrfs_alloc_path();
2300         if (!path)
2301                 goto make_bad;
2302
2303         path->leave_spinning = 1;
2304         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2305
2306         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2307         if (ret)
2308                 goto make_bad;
2309
2310         leaf = path->nodes[0];
2311
2312         if (filled)
2313                 goto cache_acl;
2314
2315         inode_item = btrfs_item_ptr(leaf, path->slots[0],
2316                                     struct btrfs_inode_item);
2317         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2318         inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
2319         inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2320         inode->i_gid = btrfs_inode_gid(leaf, inode_item);
2321         btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2322
2323         tspec = btrfs_inode_atime(inode_item);
2324         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2325         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2326
2327         tspec = btrfs_inode_mtime(inode_item);
2328         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2329         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2330
2331         tspec = btrfs_inode_ctime(inode_item);
2332         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2333         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2334
2335         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2336         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2337         BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
2338         inode->i_generation = BTRFS_I(inode)->generation;
2339         inode->i_rdev = 0;
2340         rdev = btrfs_inode_rdev(leaf, inode_item);
2341
2342         BTRFS_I(inode)->index_cnt = (u64)-1;
2343         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2344 cache_acl:
2345         /*
2346          * try to precache a NULL acl entry for files that don't have
2347          * any xattrs or acls
2348          */
2349         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
2350                                            btrfs_ino(inode));
2351         if (!maybe_acls)
2352                 cache_no_acl(inode);
2353
2354         btrfs_free_path(path);
2355
2356         switch (inode->i_mode & S_IFMT) {
2357         case S_IFREG:
2358                 inode->i_mapping->a_ops = &btrfs_aops;
2359                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2360                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2361                 inode->i_fop = &btrfs_file_operations;
2362                 inode->i_op = &btrfs_file_inode_operations;
2363                 break;
2364         case S_IFDIR:
2365                 inode->i_fop = &btrfs_dir_file_operations;
2366                 if (root == root->fs_info->tree_root)
2367                         inode->i_op = &btrfs_dir_ro_inode_operations;
2368                 else
2369                         inode->i_op = &btrfs_dir_inode_operations;
2370                 break;
2371         case S_IFLNK:
2372                 inode->i_op = &btrfs_symlink_inode_operations;
2373                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2374                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2375                 break;
2376         default:
2377                 inode->i_op = &btrfs_special_inode_operations;
2378                 init_special_inode(inode, inode->i_mode, rdev);
2379                 break;
2380         }
2381
2382         btrfs_update_iflags(inode);
2383         return;
2384
2385 make_bad:
2386         btrfs_free_path(path);
2387         make_bad_inode(inode);
2388 }
2389
2390 /*
2391  * given a leaf and an inode, copy the inode fields into the leaf
2392  */
2393 static void fill_inode_item(struct btrfs_trans_handle *trans,
2394                             struct extent_buffer *leaf,
2395                             struct btrfs_inode_item *item,
2396                             struct inode *inode)
2397 {
2398         btrfs_set_inode_uid(leaf, item, inode->i_uid);
2399         btrfs_set_inode_gid(leaf, item, inode->i_gid);
2400         btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2401         btrfs_set_inode_mode(leaf, item, inode->i_mode);
2402         btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2403
2404         btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2405                                inode->i_atime.tv_sec);
2406         btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2407                                 inode->i_atime.tv_nsec);
2408
2409         btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2410                                inode->i_mtime.tv_sec);
2411         btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2412                                 inode->i_mtime.tv_nsec);
2413
2414         btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2415                                inode->i_ctime.tv_sec);
2416         btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2417                                 inode->i_ctime.tv_nsec);
2418
2419         btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2420         btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2421         btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
2422         btrfs_set_inode_transid(leaf, item, trans->transid);
2423         btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2424         btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2425         btrfs_set_inode_block_group(leaf, item, 0);
2426 }
2427
2428 /*
2429  * copy everything in the in-memory inode into the btree.
2430  */
2431 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
2432                                 struct btrfs_root *root, struct inode *inode)
2433 {
2434         struct btrfs_inode_item *inode_item;
2435         struct btrfs_path *path;
2436         struct extent_buffer *leaf;
2437         int ret;
2438
2439         path = btrfs_alloc_path();
2440         if (!path)
2441                 return -ENOMEM;
2442
2443         path->leave_spinning = 1;
2444         ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
2445                                  1);
2446         if (ret) {
2447                 if (ret > 0)
2448                         ret = -ENOENT;
2449                 goto failed;
2450         }
2451
2452         btrfs_unlock_up_safe(path, 1);
2453         leaf = path->nodes[0];
2454         inode_item = btrfs_item_ptr(leaf, path->slots[0],
2455                                     struct btrfs_inode_item);
2456
2457         fill_inode_item(trans, leaf, inode_item, inode);
2458         btrfs_mark_buffer_dirty(leaf);
2459         btrfs_set_inode_last_trans(trans, inode);
2460         ret = 0;
2461 failed:
2462         btrfs_free_path(path);
2463         return ret;
2464 }
2465
2466 /*
2467  * copy everything in the in-memory inode into the btree.
2468  */
2469 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2470                                 struct btrfs_root *root, struct inode *inode)
2471 {
2472         int ret;
2473
2474         /*
2475          * If the inode is a free space inode, we can deadlock during commit
2476          * if we put it into the delayed code.
2477          *
2478          * The data relocation inode should also be directly updated
2479          * without delay
2480          */
2481         if (!btrfs_is_free_space_inode(root, inode)
2482             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
2483                 ret = btrfs_delayed_update_inode(trans, root, inode);
2484                 if (!ret)
2485                         btrfs_set_inode_last_trans(trans, inode);
2486                 return ret;
2487         }
2488
2489         return btrfs_update_inode_item(trans, root, inode);
2490 }
2491
2492 static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
2493                                 struct btrfs_root *root, struct inode *inode)
2494 {
2495         int ret;
2496
2497         ret = btrfs_update_inode(trans, root, inode);
2498         if (ret == -ENOSPC)
2499                 return btrfs_update_inode_item(trans, root, inode);
2500         return ret;
2501 }
2502
2503 /*
2504  * unlink helper that gets used here in inode.c and in the tree logging
2505  * recovery code.  It remove a link in a directory with a given name, and
2506  * also drops the back refs in the inode to the directory
2507  */
2508 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2509                                 struct btrfs_root *root,
2510                                 struct inode *dir, struct inode *inode,
2511                                 const char *name, int name_len)
2512 {
2513         struct btrfs_path *path;
2514         int ret = 0;
2515         struct extent_buffer *leaf;
2516         struct btrfs_dir_item *di;
2517         struct btrfs_key key;
2518         u64 index;
2519         u64 ino = btrfs_ino(inode);
2520         u64 dir_ino = btrfs_ino(dir);
2521
2522         path = btrfs_alloc_path();
2523         if (!path) {
2524                 ret = -ENOMEM;
2525                 goto out;
2526         }
2527
2528         path->leave_spinning = 1;
2529         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2530                                     name, name_len, -1);
2531         if (IS_ERR(di)) {
2532                 ret = PTR_ERR(di);
2533                 goto err;
2534         }
2535         if (!di) {
2536                 ret = -ENOENT;
2537                 goto err;
2538         }
2539         leaf = path->nodes[0];
2540         btrfs_dir_item_key_to_cpu(leaf, di, &key);
2541         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2542         if (ret)
2543                 goto err;
2544         btrfs_release_path(path);
2545
2546         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
2547                                   dir_ino, &index);
2548         if (ret) {
2549                 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2550                        "inode %llu parent %llu\n", name_len, name,
2551                        (unsigned long long)ino, (unsigned long long)dir_ino);
2552                 goto err;
2553         }
2554
2555         ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2556         if (ret)
2557                 goto err;
2558
2559         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2560                                          inode, dir_ino);
2561         BUG_ON(ret != 0 && ret != -ENOENT);
2562
2563         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2564                                            dir, index);
2565         if (ret == -ENOENT)
2566                 ret = 0;
2567 err:
2568         btrfs_free_path(path);
2569         if (ret)
2570                 goto out;
2571
2572         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2573         inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2574         btrfs_update_inode(trans, root, dir);
2575 out:
2576         return ret;
2577 }
2578
2579 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2580                        struct btrfs_root *root,
2581                        struct inode *dir, struct inode *inode,
2582                        const char *name, int name_len)
2583 {
2584         int ret;
2585         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
2586         if (!ret) {
2587                 btrfs_drop_nlink(inode);
2588                 ret = btrfs_update_inode(trans, root, inode);
2589         }
2590         return ret;
2591 }
2592                 
2593
2594 /* helper to check if there is any shared block in the path */
2595 static int check_path_shared(struct btrfs_root *root,
2596                              struct btrfs_path *path)
2597 {
2598         struct extent_buffer *eb;
2599         int level;
2600         u64 refs = 1;
2601
2602         for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2603                 int ret;
2604
2605                 if (!path->nodes[level])
2606                         break;
2607                 eb = path->nodes[level];
2608                 if (!btrfs_block_can_be_shared(root, eb))
2609                         continue;
2610                 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2611                                                &refs, NULL);
2612                 if (refs > 1)
2613                         return 1;
2614         }
2615         return 0;
2616 }
2617
2618 /*
2619  * helper to start transaction for unlink and rmdir.
2620  *
2621  * unlink and rmdir are special in btrfs, they do not always free space.
2622  * so in enospc case, we should make sure they will free space before
2623  * allowing them to use the global metadata reservation.
2624  */
2625 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2626                                                        struct dentry *dentry)
2627 {
2628         struct btrfs_trans_handle *trans;
2629         struct btrfs_root *root = BTRFS_I(dir)->root;
2630         struct btrfs_path *path;
2631         struct btrfs_inode_ref *ref;
2632         struct btrfs_dir_item *di;
2633         struct inode *inode = dentry->d_inode;
2634         u64 index;
2635         int check_link = 1;
2636         int err = -ENOSPC;
2637         int ret;
2638         u64 ino = btrfs_ino(inode);
2639         u64 dir_ino = btrfs_ino(dir);
2640
2641         /*
2642          * 1 for the possible orphan item
2643          * 1 for the dir item
2644          * 1 for the dir index
2645          * 1 for the inode ref
2646          * 1 for the inode ref in the tree log
2647          * 2 for the dir entries in the log
2648          * 1 for the inode
2649          */
2650         trans = btrfs_start_transaction(root, 8);
2651         if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2652                 return trans;
2653
2654         if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2655                 return ERR_PTR(-ENOSPC);
2656
2657         /* check if there is someone else holds reference */
2658         if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2659                 return ERR_PTR(-ENOSPC);
2660
2661         if (atomic_read(&inode->i_count) > 2)
2662                 return ERR_PTR(-ENOSPC);
2663
2664         if (xchg(&root->fs_info->enospc_unlink, 1))
2665                 return ERR_PTR(-ENOSPC);
2666
2667         path = btrfs_alloc_path();
2668         if (!path) {
2669                 root->fs_info->enospc_unlink = 0;
2670                 return ERR_PTR(-ENOMEM);
2671         }
2672
2673         /* 1 for the orphan item */
2674         trans = btrfs_start_transaction(root, 1);
2675         if (IS_ERR(trans)) {
2676                 btrfs_free_path(path);
2677                 root->fs_info->enospc_unlink = 0;
2678                 return trans;
2679         }
2680
2681         path->skip_locking = 1;
2682         path->search_commit_root = 1;
2683
2684         ret = btrfs_lookup_inode(trans, root, path,
2685                                 &BTRFS_I(dir)->location, 0);
2686         if (ret < 0) {
2687                 err = ret;
2688                 goto out;
2689         }
2690         if (ret == 0) {
2691                 if (check_path_shared(root, path))
2692                         goto out;
2693         } else {
2694                 check_link = 0;
2695         }
2696         btrfs_release_path(path);
2697
2698         ret = btrfs_lookup_inode(trans, root, path,
2699                                 &BTRFS_I(inode)->location, 0);
2700         if (ret < 0) {
2701                 err = ret;
2702                 goto out;
2703         }
2704         if (ret == 0) {
2705                 if (check_path_shared(root, path))
2706                         goto out;
2707         } else {
2708                 check_link = 0;
2709         }
2710         btrfs_release_path(path);
2711
2712         if (ret == 0 && S_ISREG(inode->i_mode)) {
2713                 ret = btrfs_lookup_file_extent(trans, root, path,
2714                                                ino, (u64)-1, 0);
2715                 if (ret < 0) {
2716                         err = ret;
2717                         goto out;
2718                 }
2719                 BUG_ON(ret == 0);
2720                 if (check_path_shared(root, path))
2721                         goto out;
2722                 btrfs_release_path(path);
2723         }
2724
2725         if (!check_link) {
2726                 err = 0;
2727                 goto out;
2728         }
2729
2730         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2731                                 dentry->d_name.name, dentry->d_name.len, 0);
2732         if (IS_ERR(di)) {
2733                 err = PTR_ERR(di);
2734                 goto out;
2735         }
2736         if (di) {
2737                 if (check_path_shared(root, path))
2738                         goto out;
2739         } else {
2740                 err = 0;
2741                 goto out;
2742         }
2743         btrfs_release_path(path);
2744
2745         ref = btrfs_lookup_inode_ref(trans, root, path,
2746                                 dentry->d_name.name, dentry->d_name.len,
2747                                 ino, dir_ino, 0);
2748         if (IS_ERR(ref)) {
2749                 err = PTR_ERR(ref);
2750                 goto out;
2751         }
2752         BUG_ON(!ref);
2753         if (check_path_shared(root, path))
2754                 goto out;
2755         index = btrfs_inode_ref_index(path->nodes[0], ref);
2756         btrfs_release_path(path);
2757
2758         /*
2759          * This is a commit root search, if we can lookup inode item and other
2760          * relative items in the commit root, it means the transaction of
2761          * dir/file creation has been committed, and the dir index item that we
2762          * delay to insert has also been inserted into the commit root. So
2763          * we needn't worry about the delayed insertion of the dir index item
2764          * here.
2765          */
2766         di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
2767                                 dentry->d_name.name, dentry->d_name.len, 0);
2768         if (IS_ERR(di)) {
2769                 err = PTR_ERR(di);
2770                 goto out;
2771         }
2772         BUG_ON(ret == -ENOENT);
2773         if (check_path_shared(root, path))
2774                 goto out;
2775
2776         err = 0;
2777 out:
2778         btrfs_free_path(path);
2779         /* Migrate the orphan reservation over */
2780         if (!err)
2781                 err = btrfs_block_rsv_migrate(trans->block_rsv,
2782                                 &root->fs_info->global_block_rsv,
2783                                 trans->bytes_reserved);
2784
2785         if (err) {
2786                 btrfs_end_transaction(trans, root);
2787                 root->fs_info->enospc_unlink = 0;
2788                 return ERR_PTR(err);
2789         }
2790
2791         trans->block_rsv = &root->fs_info->global_block_rsv;
2792         return trans;
2793 }
2794
2795 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
2796                                struct btrfs_root *root)
2797 {
2798         if (trans->block_rsv == &root->fs_info->global_block_rsv) {
2799                 btrfs_block_rsv_release(root, trans->block_rsv,
2800                                         trans->bytes_reserved);
2801                 trans->block_rsv = &root->fs_info->trans_block_rsv;
2802                 BUG_ON(!root->fs_info->enospc_unlink);
2803                 root->fs_info->enospc_unlink = 0;
2804         }
2805         btrfs_end_transaction_throttle(trans, root);
2806 }
2807
2808 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
2809 {
2810         struct btrfs_root *root = BTRFS_I(dir)->root;
2811         struct btrfs_trans_handle *trans;
2812         struct inode *inode = dentry->d_inode;
2813         int ret;
2814         unsigned long nr = 0;
2815
2816         trans = __unlink_start_trans(dir, dentry);
2817         if (IS_ERR(trans))
2818                 return PTR_ERR(trans);
2819
2820         btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
2821
2822         ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2823                                  dentry->d_name.name, dentry->d_name.len);
2824         if (ret)
2825                 goto out;
2826
2827         if (inode->i_nlink == 0) {
2828                 ret = btrfs_orphan_add(trans, inode);
2829                 if (ret)
2830                         goto out;
2831         }
2832
2833 out:
2834         nr = trans->blocks_used;
2835         __unlink_end_trans(trans, root);
2836         btrfs_btree_balance_dirty(root, nr);
2837         return ret;
2838 }
2839
2840 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
2841                         struct btrfs_root *root,
2842                         struct inode *dir, u64 objectid,
2843                         const char *name, int name_len)
2844 {
2845         struct btrfs_path *path;
2846         struct extent_buffer *leaf;
2847         struct btrfs_dir_item *di;
2848         struct btrfs_key key;
2849         u64 index;
2850         int ret;
2851         u64 dir_ino = btrfs_ino(dir);
2852
2853         path = btrfs_alloc_path();
2854         if (!path)
2855                 return -ENOMEM;
2856
2857         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2858                                    name, name_len, -1);
2859         BUG_ON(IS_ERR_OR_NULL(di));
2860
2861         leaf = path->nodes[0];
2862         btrfs_dir_item_key_to_cpu(leaf, di, &key);
2863         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2864         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2865         BUG_ON(ret);
2866         btrfs_release_path(path);
2867
2868         ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
2869                                  objectid, root->root_key.objectid,
2870                                  dir_ino, &index, name, name_len);
2871         if (ret < 0) {
2872                 BUG_ON(ret != -ENOENT);
2873                 di = btrfs_search_dir_index_item(root, path, dir_ino,
2874                                                  name, name_len);
2875                 BUG_ON(IS_ERR_OR_NULL(di));
2876
2877                 leaf = path->nodes[0];
2878                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2879                 btrfs_release_path(path);
2880                 index = key.offset;
2881         }
2882         btrfs_release_path(path);
2883
2884         ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2885         BUG_ON(ret);
2886
2887         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2888         dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2889         ret = btrfs_update_inode(trans, root, dir);
2890         BUG_ON(ret);
2891
2892         btrfs_free_path(path);
2893         return 0;
2894 }
2895
2896 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
2897 {
2898         struct inode *inode = dentry->d_inode;
2899         int err = 0;
2900         struct btrfs_root *root = BTRFS_I(dir)->root;
2901         struct btrfs_trans_handle *trans;
2902         unsigned long nr = 0;
2903
2904         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
2905             btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
2906                 return -ENOTEMPTY;
2907
2908         trans = __unlink_start_trans(dir, dentry);
2909         if (IS_ERR(trans))
2910                 return PTR_ERR(trans);
2911
2912         if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
2913                 err = btrfs_unlink_subvol(trans, root, dir,
2914                                           BTRFS_I(inode)->location.objectid,
2915                                           dentry->d_name.name,
2916                                           dentry->d_name.len);
2917                 goto out;
2918         }
2919
2920         err = btrfs_orphan_add(trans, inode);
2921         if (err)
2922                 goto out;
2923
2924         /* now the directory is empty */
2925         err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2926                                  dentry->d_name.name, dentry->d_name.len);
2927         if (!err)
2928                 btrfs_i_size_write(inode, 0);
2929 out:
2930         nr = trans->blocks_used;
2931         __unlink_end_trans(trans, root);
2932         btrfs_btree_balance_dirty(root, nr);
2933
2934         return err;
2935 }
2936
2937 /*
2938  * this can truncate away extent items, csum items and directory items.
2939  * It starts at a high offset and removes keys until it can't find
2940  * any higher than new_size
2941  *
2942  * csum items that cross the new i_size are truncated to the new size
2943  * as well.
2944  *
2945  * min_type is the minimum key type to truncate down to.  If set to 0, this
2946  * will kill all the items on this inode, including the INODE_ITEM_KEY.
2947  */
2948 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
2949                                struct btrfs_root *root,
2950                                struct inode *inode,
2951                                u64 new_size, u32 min_type)
2952 {
2953         struct btrfs_path *path;
2954         struct extent_buffer *leaf;
2955         struct btrfs_file_extent_item *fi;
2956         struct btrfs_key key;
2957         struct btrfs_key found_key;
2958         u64 extent_start = 0;
2959         u64 extent_num_bytes = 0;
2960         u64 extent_offset = 0;
2961         u64 item_end = 0;
2962         u64 mask = root->sectorsize - 1;
2963         u32 found_type = (u8)-1;
2964         int found_extent;
2965         int del_item;
2966         int pending_del_nr = 0;
2967         int pending_del_slot = 0;
2968         int extent_type = -1;
2969         int encoding;
2970         int ret;
2971         int err = 0;
2972         u64 ino = btrfs_ino(inode);
2973
2974         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
2975
2976         path = btrfs_alloc_path();
2977         if (!path)
2978                 return -ENOMEM;
2979         path->reada = -1;
2980
2981         if (root->ref_cows || root == root->fs_info->tree_root)
2982                 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
2983
2984         /*
2985          * This function is also used to drop the items in the log tree before
2986          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
2987          * it is used to drop the loged items. So we shouldn't kill the delayed
2988          * items.
2989          */
2990         if (min_type == 0 && root == BTRFS_I(inode)->root)
2991                 btrfs_kill_delayed_inode_items(inode);
2992
2993         key.objectid = ino;
2994         key.offset = (u64)-1;
2995         key.type = (u8)-1;
2996
2997 search_again:
2998         path->leave_spinning = 1;
2999         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3000         if (ret < 0) {
3001                 err = ret;
3002                 goto out;
3003         }
3004
3005         if (ret > 0) {
3006                 /* there are no items in the tree for us to truncate, we're
3007                  * done
3008                  */
3009                 if (path->slots[0] == 0)
3010                         goto out;
3011                 path->slots[0]--;
3012         }
3013
3014         while (1) {
3015                 fi = NULL;
3016                 leaf = path->nodes[0];
3017                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3018                 found_type = btrfs_key_type(&found_key);
3019                 encoding = 0;
3020
3021                 if (found_key.objectid != ino)
3022                         break;
3023
3024                 if (found_type < min_type)
3025                         break;
3026
3027                 item_end = found_key.offset;
3028                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3029                         fi = btrfs_item_ptr(leaf, path->slots[0],
3030                                             struct btrfs_file_extent_item);
3031                         extent_type = btrfs_file_extent_type(leaf, fi);
3032                         encoding = btrfs_file_extent_compression(leaf, fi);
3033                         encoding |= btrfs_file_extent_encryption(leaf, fi);
3034                         encoding |= btrfs_file_extent_other_encoding(leaf, fi);
3035
3036                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3037                                 item_end +=
3038                                     btrfs_file_extent_num_bytes(leaf, fi);
3039                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3040                                 item_end += btrfs_file_extent_inline_len(leaf,
3041                                                                          fi);
3042                         }
3043                         item_end--;
3044                 }
3045                 if (found_type > min_type) {
3046                         del_item = 1;
3047                 } else {
3048                         if (item_end < new_size)
3049                                 break;
3050                         if (found_key.offset >= new_size)
3051                                 del_item = 1;
3052                         else
3053                                 del_item = 0;
3054                 }
3055                 found_extent = 0;
3056                 /* FIXME, shrink the extent if the ref count is only 1 */
3057                 if (found_type != BTRFS_EXTENT_DATA_KEY)
3058                         goto delete;
3059
3060                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3061                         u64 num_dec;
3062                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3063                         if (!del_item && !encoding) {
3064                                 u64 orig_num_bytes =
3065                                         btrfs_file_extent_num_bytes(leaf, fi);
3066                                 extent_num_bytes = new_size -
3067                                         found_key.offset + root->sectorsize - 1;
3068                                 extent_num_bytes = extent_num_bytes &
3069                                         ~((u64)root->sectorsize - 1);
3070                                 btrfs_set_file_extent_num_bytes(leaf, fi,
3071                                                          extent_num_bytes);
3072                                 num_dec = (orig_num_bytes -
3073                                            extent_num_bytes);
3074                                 if (root->ref_cows && extent_start != 0)
3075                                         inode_sub_bytes(inode, num_dec);
3076                                 btrfs_mark_buffer_dirty(leaf);
3077                         } else {
3078                                 extent_num_bytes =
3079                                         btrfs_file_extent_disk_num_bytes(leaf,
3080                                                                          fi);
3081                                 extent_offset = found_key.offset -
3082                                         btrfs_file_extent_offset(leaf, fi);
3083
3084                                 /* FIXME blocksize != 4096 */
3085                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3086                                 if (extent_start != 0) {
3087                                         found_extent = 1;
3088                                         if (root->ref_cows)
3089                                                 inode_sub_bytes(inode, num_dec);
3090                                 }
3091                         }
3092                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3093                         /*
3094                          * we can't truncate inline items that have had
3095                          * special encodings
3096                          */
3097                         if (!del_item &&
3098                             btrfs_file_extent_compression(leaf, fi) == 0 &&
3099                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
3100                             btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3101                                 u32 size = new_size - found_key.offset;
3102
3103                                 if (root->ref_cows) {
3104                                         inode_sub_bytes(inode, item_end + 1 -
3105                                                         new_size);
3106                                 }
3107                                 size =
3108                                     btrfs_file_extent_calc_inline_size(size);
3109                                 ret = btrfs_truncate_item(trans, root, path,
3110                                                           size, 1);
3111                         } else if (root->ref_cows) {
3112                                 inode_sub_bytes(inode, item_end + 1 -
3113                                                 found_key.offset);
3114                         }
3115                 }
3116 delete:
3117                 if (del_item) {
3118                         if (!pending_del_nr) {
3119                                 /* no pending yet, add ourselves */
3120                                 pending_del_slot = path->slots[0];
3121                                 pending_del_nr = 1;
3122                         } else if (pending_del_nr &&
3123                                    path->slots[0] + 1 == pending_del_slot) {
3124                                 /* hop on the pending chunk */
3125                                 pending_del_nr++;
3126                                 pending_del_slot = path->slots[0];
3127                         } else {
3128                                 BUG();
3129                         }
3130                 } else {
3131                         break;
3132                 }
3133                 if (found_extent && (root->ref_cows ||
3134                                      root == root->fs_info->tree_root)) {
3135                         btrfs_set_path_blocking(path);
3136                         ret = btrfs_free_extent(trans, root, extent_start,
3137                                                 extent_num_bytes, 0,
3138                                                 btrfs_header_owner(leaf),
3139                                                 ino, extent_offset);
3140                         BUG_ON(ret);
3141                 }
3142
3143                 if (found_type == BTRFS_INODE_ITEM_KEY)
3144                         break;
3145
3146                 if (path->slots[0] == 0 ||
3147                     path->slots[0] != pending_del_slot) {
3148                         if (root->ref_cows &&
3149                             BTRFS_I(inode)->location.objectid !=
3150                                                 BTRFS_FREE_INO_OBJECTID) {
3151                                 err = -EAGAIN;
3152                                 goto out;
3153                         }
3154                         if (pending_del_nr) {
3155                                 ret = btrfs_del_items(trans, root, path,
3156                                                 pending_del_slot,
3157                                                 pending_del_nr);
3158                                 BUG_ON(ret);
3159                                 pending_del_nr = 0;
3160                         }
3161                         btrfs_release_path(path);
3162                         goto search_again;
3163                 } else {
3164                         path->slots[0]--;
3165                 }
3166         }
3167 out:
3168         if (pending_del_nr) {
3169                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3170                                       pending_del_nr);
3171                 BUG_ON(ret);
3172         }
3173         btrfs_free_path(path);
3174         return err;
3175 }
3176
3177 /*
3178  * taken from block_truncate_page, but does cow as it zeros out
3179  * any bytes left in the last page in the file.
3180  */
3181 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3182 {
3183         struct inode *inode = mapping->host;
3184         struct btrfs_root *root = BTRFS_I(inode)->root;
3185         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3186         struct btrfs_ordered_extent *ordered;
3187         struct extent_state *cached_state = NULL;
3188         char *kaddr;
3189         u32 blocksize = root->sectorsize;
3190         pgoff_t index = from >> PAGE_CACHE_SHIFT;
3191         unsigned offset = from & (PAGE_CACHE_SIZE-1);
3192         struct page *page;
3193         gfp_t mask = btrfs_alloc_write_mask(mapping);
3194         int ret = 0;
3195         u64 page_start;
3196         u64 page_end;
3197
3198         if ((offset & (blocksize - 1)) == 0)
3199                 goto out;
3200         ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3201         if (ret)
3202                 goto out;
3203
3204         ret = -ENOMEM;
3205 again:
3206         page = find_or_create_page(mapping, index, mask);
3207         if (!page) {
3208                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3209                 goto out;
3210         }
3211
3212         page_start = page_offset(page);
3213         page_end = page_start + PAGE_CACHE_SIZE - 1;
3214
3215         if (!PageUptodate(page)) {
3216                 ret = btrfs_readpage(NULL, page);
3217                 lock_page(page);
3218                 if (page->mapping != mapping) {
3219                         unlock_page(page);
3220                         page_cache_release(page);
3221                         goto again;
3222                 }
3223                 if (!PageUptodate(page)) {
3224                         ret = -EIO;
3225                         goto out_unlock;
3226                 }
3227         }
3228         wait_on_page_writeback(page);
3229
3230         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
3231                          GFP_NOFS);
3232         set_page_extent_mapped(page);
3233
3234         ordered = btrfs_lookup_ordered_extent(inode, page_start);
3235         if (ordered) {
3236                 unlock_extent_cached(io_tree, page_start, page_end,
3237                                      &cached_state, GFP_NOFS);
3238                 unlock_page(page);
3239                 page_cache_release(page);
3240                 btrfs_start_ordered_extent(inode, ordered, 1);
3241                 btrfs_put_ordered_extent(ordered);
3242                 goto again;
3243         }
3244
3245         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3246                           EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
3247                           0, 0, &cached_state, GFP_NOFS);
3248
3249         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3250                                         &cached_state);
3251         if (ret) {
3252                 unlock_extent_cached(io_tree, page_start, page_end,
3253                                      &cached_state, GFP_NOFS);
3254                 goto out_unlock;
3255         }
3256
3257         ret = 0;
3258         if (offset != PAGE_CACHE_SIZE) {
3259                 kaddr = kmap(page);
3260                 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3261                 flush_dcache_page(page);
3262                 kunmap(page);
3263         }
3264         ClearPageChecked(page);
3265         set_page_dirty(page);
3266         unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3267                              GFP_NOFS);
3268
3269 out_unlock:
3270         if (ret)
3271                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3272         unlock_page(page);
3273         page_cache_release(page);
3274 out:
3275         return ret;
3276 }
3277
3278 /*
3279  * This function puts in dummy file extents for the area we're creating a hole
3280  * for.  So if we are truncating this file to a larger size we need to insert
3281  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3282  * the range between oldsize and size
3283  */
3284 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
3285 {
3286         struct btrfs_trans_handle *trans;
3287         struct btrfs_root *root = BTRFS_I(inode)->root;
3288         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3289         struct extent_map *em = NULL;
3290         struct extent_state *cached_state = NULL;
3291         u64 mask = root->sectorsize - 1;
3292         u64 hole_start = (oldsize + mask) & ~mask;
3293         u64 block_end = (size + mask) & ~mask;
3294         u64 last_byte;
3295         u64 cur_offset;
3296         u64 hole_size;
3297         int err = 0;
3298
3299         if (size <= hole_start)
3300                 return 0;
3301
3302         while (1) {
3303                 struct btrfs_ordered_extent *ordered;
3304                 btrfs_wait_ordered_range(inode, hole_start,
3305                                          block_end - hole_start);
3306                 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3307                                  &cached_state, GFP_NOFS);
3308                 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3309                 if (!ordered)
3310                         break;
3311                 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3312                                      &cached_state, GFP_NOFS);
3313                 btrfs_put_ordered_extent(ordered);
3314         }
3315
3316         cur_offset = hole_start;
3317         while (1) {
3318                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3319                                 block_end - cur_offset, 0);
3320                 BUG_ON(IS_ERR_OR_NULL(em));
3321                 last_byte = min(extent_map_end(em), block_end);
3322                 last_byte = (last_byte + mask) & ~mask;
3323                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3324                         u64 hint_byte = 0;
3325                         hole_size = last_byte - cur_offset;
3326
3327                         trans = btrfs_start_transaction(root, 2);
3328                         if (IS_ERR(trans)) {
3329                                 err = PTR_ERR(trans);
3330                                 break;
3331                         }
3332
3333                         err = btrfs_drop_extents(trans, inode, cur_offset,
3334                                                  cur_offset + hole_size,
3335                                                  &hint_byte, 1);
3336                         if (err) {
3337                                 btrfs_end_transaction(trans, root);
3338                                 break;
3339                         }
3340
3341                         err = btrfs_insert_file_extent(trans, root,
3342                                         btrfs_ino(inode), cur_offset, 0,
3343                                         0, hole_size, 0, hole_size,
3344                                         0, 0, 0);
3345                         if (err) {
3346                                 btrfs_end_transaction(trans, root);
3347                                 break;
3348                         }
3349
3350                         btrfs_drop_extent_cache(inode, hole_start,
3351                                         last_byte - 1, 0);
3352
3353                         btrfs_end_transaction(trans, root);
3354                 }
3355                 free_extent_map(em);
3356                 em = NULL;
3357                 cur_offset = last_byte;
3358                 if (cur_offset >= block_end)
3359                         break;
3360         }
3361
3362         free_extent_map(em);
3363         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3364                              GFP_NOFS);
3365         return err;
3366 }
3367
3368 static int btrfs_setsize(struct inode *inode, loff_t newsize)
3369 {
3370         loff_t oldsize = i_size_read(inode);
3371         int ret;
3372
3373         if (newsize == oldsize)
3374                 return 0;
3375
3376         if (newsize > oldsize) {
3377                 i_size_write(inode, newsize);
3378                 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3379                 truncate_pagecache(inode, oldsize, newsize);
3380                 ret = btrfs_cont_expand(inode, oldsize, newsize);
3381                 if (ret) {
3382                         btrfs_setsize(inode, oldsize);
3383                         return ret;
3384                 }
3385
3386                 mark_inode_dirty(inode);
3387         } else {
3388
3389                 /*
3390                  * We're truncating a file that used to have good data down to
3391                  * zero. Make sure it gets into the ordered flush list so that
3392                  * any new writes get down to disk quickly.
3393                  */
3394                 if (newsize == 0)
3395                         BTRFS_I(inode)->ordered_data_close = 1;
3396
3397                 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3398                 truncate_setsize(inode, newsize);
3399                 ret = btrfs_truncate(inode);
3400         }
3401
3402         return ret;
3403 }
3404
3405 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3406 {
3407         struct inode *inode = dentry->d_inode;
3408         struct btrfs_root *root = BTRFS_I(inode)->root;
3409         int err;
3410
3411         if (btrfs_root_readonly(root))
3412                 return -EROFS;
3413
3414         err = inode_change_ok(inode, attr);
3415         if (err)
3416                 return err;
3417
3418         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3419                 err = btrfs_setsize(inode, attr->ia_size);
3420                 if (err)
3421                         return err;
3422         }
3423
3424         if (attr->ia_valid) {
3425                 setattr_copy(inode, attr);
3426                 mark_inode_dirty(inode);
3427
3428                 if (attr->ia_valid & ATTR_MODE)
3429                         err = btrfs_acl_chmod(inode);
3430         }
3431
3432         return err;
3433 }
3434
3435 void btrfs_evict_inode(struct inode *inode)
3436 {
3437         struct btrfs_trans_handle *trans;
3438         struct btrfs_root *root = BTRFS_I(inode)->root;
3439         struct btrfs_block_rsv *rsv, *global_rsv;
3440         u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
3441         unsigned long nr;
3442         int ret;
3443
3444         trace_btrfs_inode_evict(inode);
3445
3446         truncate_inode_pages(&inode->i_data, 0);
3447         if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3448                                btrfs_is_free_space_inode(root, inode)))
3449                 goto no_delete;
3450
3451         if (is_bad_inode(inode)) {
3452                 btrfs_orphan_del(NULL, inode);
3453                 goto no_delete;
3454         }
3455         /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3456         btrfs_wait_ordered_range(inode, 0, (u64)-1);
3457
3458         if (root->fs_info->log_root_recovering) {
3459                 BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
3460                 goto no_delete;
3461         }
3462
3463         if (inode->i_nlink > 0) {
3464                 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3465                 goto no_delete;
3466         }
3467
3468         rsv = btrfs_alloc_block_rsv(root);
3469         if (!rsv) {
3470                 btrfs_orphan_del(NULL, inode);
3471                 goto no_delete;
3472         }
3473         rsv->size = min_size;
3474         global_rsv = &root->fs_info->global_block_rsv;
3475
3476         btrfs_i_size_write(inode, 0);
3477
3478         /*
3479          * This is a bit simpler than btrfs_truncate since
3480          *
3481          * 1) We've already reserved our space for our orphan item in the
3482          *    unlink.
3483          * 2) We're going to delete the inode item, so we don't need to update
3484          *    it at all.
3485          *
3486          * So we just need to reserve some slack space in case we add bytes when
3487          * doing the truncate.
3488          */
3489         while (1) {
3490                 ret = btrfs_block_rsv_refill(root, rsv, min_size);
3491
3492                 /*
3493                  * Try and steal from the global reserve since we will
3494                  * likely not use this space anyway, we want to try as
3495                  * hard as possible to get this to work.
3496                  */
3497                 if (ret)
3498                         ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
3499
3500                 if (ret) {
3501                         printk(KERN_WARNING "Could not get space for a "
3502                                "delete, will truncate on mount %d\n", ret);
3503                         btrfs_orphan_del(NULL, inode);
3504                         btrfs_free_block_rsv(root, rsv);
3505                         goto no_delete;
3506                 }
3507
3508                 trans = btrfs_start_transaction(root, 0);
3509                 if (IS_ERR(trans)) {
3510                         btrfs_orphan_del(NULL, inode);
3511                         btrfs_free_block_rsv(root, rsv);
3512                         goto no_delete;
3513                 }
3514
3515                 trans->block_rsv = rsv;
3516
3517                 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3518                 if (ret != -EAGAIN)
3519                         break;
3520
3521                 nr = trans->blocks_used;
3522                 btrfs_end_transaction(trans, root);
3523                 trans = NULL;
3524                 btrfs_btree_balance_dirty(root, nr);
3525         }
3526
3527         btrfs_free_block_rsv(root, rsv);
3528
3529         if (ret == 0) {
3530                 trans->block_rsv = root->orphan_block_rsv;
3531                 ret = btrfs_orphan_del(trans, inode);
3532                 BUG_ON(ret);
3533         }
3534
3535         trans->block_rsv = &root->fs_info->trans_block_rsv;
3536         if (!(root == root->fs_info->tree_root ||
3537               root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
3538                 btrfs_return_ino(root, btrfs_ino(inode));
3539
3540         nr = trans->blocks_used;
3541         btrfs_end_transaction(trans, root);
3542         btrfs_btree_balance_dirty(root, nr);
3543 no_delete:
3544         end_writeback(inode);
3545         return;
3546 }
3547
3548 /*
3549  * this returns the key found in the dir entry in the location pointer.
3550  * If no dir entries were found, location->objectid is 0.
3551  */
3552 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3553                                struct btrfs_key *location)
3554 {
3555         const char *name = dentry->d_name.name;
3556         int namelen = dentry->d_name.len;
3557         struct btrfs_dir_item *di;
3558         struct btrfs_path *path;
3559         struct btrfs_root *root = BTRFS_I(dir)->root;
3560         int ret = 0;
3561
3562         path = btrfs_alloc_path();
3563         if (!path)
3564                 return -ENOMEM;
3565
3566         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
3567                                     namelen, 0);
3568         if (IS_ERR(di))
3569                 ret = PTR_ERR(di);
3570
3571         if (IS_ERR_OR_NULL(di))
3572                 goto out_err;
3573
3574         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
3575 out:
3576         btrfs_free_path(path);
3577         return ret;
3578 out_err:
3579         location->objectid = 0;
3580         goto out;
3581 }
3582
3583 /*
3584  * when we hit a tree root in a directory, the btrfs part of the inode
3585  * needs to be changed to reflect the root directory of the tree root.  This
3586  * is kind of like crossing a mount point.
3587  */
3588 static int fixup_tree_root_location(struct btrfs_root *root,
3589                                     struct inode *dir,
3590                                     struct dentry *dentry,
3591                                     struct btrfs_key *location,
3592                                     struct btrfs_root **sub_root)
3593 {
3594         struct btrfs_path *path;
3595         struct btrfs_root *new_root;
3596         struct btrfs_root_ref *ref;
3597         struct extent_buffer *leaf;
3598         int ret;
3599         int err = 0;
3600
3601         path = btrfs_alloc_path();
3602         if (!path) {
3603                 err = -ENOMEM;
3604                 goto out;
3605         }
3606
3607         err = -ENOENT;
3608         ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3609                                   BTRFS_I(dir)->root->root_key.objectid,
3610                                   location->objectid);
3611         if (ret) {
3612                 if (ret < 0)
3613                         err = ret;
3614                 goto out;
3615         }
3616
3617         leaf = path->nodes[0];
3618         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3619         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
3620             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3621                 goto out;
3622
3623         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3624                                    (unsigned long)(ref + 1),
3625                                    dentry->d_name.len);
3626         if (ret)
3627                 goto out;
3628
3629         btrfs_release_path(path);
3630
3631         new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3632         if (IS_ERR(new_root)) {
3633                 err = PTR_ERR(new_root);
3634                 goto out;
3635         }
3636
3637         if (btrfs_root_refs(&new_root->root_item) == 0) {
3638                 err = -ENOENT;
3639                 goto out;
3640         }
3641
3642         *sub_root = new_root;
3643         location->objectid = btrfs_root_dirid(&new_root->root_item);
3644         location->type = BTRFS_INODE_ITEM_KEY;
3645         location->offset = 0;
3646         err = 0;
3647 out:
3648         btrfs_free_path(path);
3649         return err;
3650 }
3651
3652 static void inode_tree_add(struct inode *inode)
3653 {
3654         struct btrfs_root *root = BTRFS_I(inode)->root;
3655         struct btrfs_inode *entry;
3656         struct rb_node **p;
3657         struct rb_node *parent;
3658         u64 ino = btrfs_ino(inode);
3659 again:
3660         p = &root->inode_tree.rb_node;
3661         parent = NULL;
3662
3663         if (inode_unhashed(inode))
3664                 return;
3665
3666         spin_lock(&root->inode_lock);
3667         while (*p) {
3668                 parent = *p;
3669                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3670
3671                 if (ino < btrfs_ino(&entry->vfs_inode))
3672                         p = &parent->rb_left;
3673                 else if (ino > btrfs_ino(&entry->vfs_inode))
3674                         p = &parent->rb_right;
3675                 else {
3676                         WARN_ON(!(entry->vfs_inode.i_state &
3677                                   (I_WILL_FREE | I_FREEING)));
3678                         rb_erase(parent, &root->inode_tree);
3679                         RB_CLEAR_NODE(parent);
3680                         spin_unlock(&root->inode_lock);
3681                         goto again;
3682                 }
3683         }
3684         rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3685         rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3686         spin_unlock(&root->inode_lock);
3687 }
3688
3689 static void inode_tree_del(struct inode *inode)
3690 {
3691         struct btrfs_root *root = BTRFS_I(inode)->root;
3692         int empty = 0;
3693
3694         spin_lock(&root->inode_lock);
3695         if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
3696                 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3697                 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
3698                 empty = RB_EMPTY_ROOT(&root->inode_tree);
3699         }
3700         spin_unlock(&root->inode_lock);
3701
3702         /*
3703          * Free space cache has inodes in the tree root, but the tree root has a
3704          * root_refs of 0, so this could end up dropping the tree root as a
3705          * snapshot, so we need the extra !root->fs_info->tree_root check to
3706          * make sure we don't drop it.
3707          */
3708         if (empty && btrfs_root_refs(&root->root_item) == 0 &&
3709             root != root->fs_info->tree_root) {
3710                 synchronize_srcu(&root->fs_info->subvol_srcu);
3711                 spin_lock(&root->inode_lock);
3712                 empty = RB_EMPTY_ROOT(&root->inode_tree);
3713                 spin_unlock(&root->inode_lock);
3714                 if (empty)
3715                         btrfs_add_dead_root(root);
3716         }
3717 }
3718
3719 int btrfs_invalidate_inodes(struct btrfs_root *root)
3720 {
3721         struct rb_node *node;
3722         struct rb_node *prev;
3723         struct btrfs_inode *entry;
3724         struct inode *inode;
3725         u64 objectid = 0;
3726
3727         WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3728
3729         spin_lock(&root->inode_lock);
3730 again:
3731         node = root->inode_tree.rb_node;
3732         prev = NULL;
3733         while (node) {
3734                 prev = node;
3735                 entry = rb_entry(node, struct btrfs_inode, rb_node);
3736
3737                 if (objectid < btrfs_ino(&entry->vfs_inode))
3738                         node = node->rb_left;
3739                 else if (objectid > btrfs_ino(&entry->vfs_inode))
3740                         node = node->rb_right;
3741                 else
3742                         break;
3743         }
3744         if (!node) {
3745                 while (prev) {
3746                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
3747                         if (objectid <= btrfs_ino(&entry->vfs_inode)) {
3748                                 node = prev;
3749                                 break;
3750                         }
3751                         prev = rb_next(prev);
3752                 }
3753         }
3754         while (node) {
3755                 entry = rb_entry(node, struct btrfs_inode, rb_node);
3756                 objectid = btrfs_ino(&entry->vfs_inode) + 1;
3757                 inode = igrab(&entry->vfs_inode);
3758                 if (inode) {
3759                         spin_unlock(&root->inode_lock);
3760                         if (atomic_read(&inode->i_count) > 1)
3761                                 d_prune_aliases(inode);
3762                         /*
3763                          * btrfs_drop_inode will have it removed from
3764                          * the inode cache when its usage count
3765                          * hits zero.
3766                          */
3767                         iput(inode);
3768                         cond_resched();
3769                         spin_lock(&root->inode_lock);
3770                         goto again;
3771                 }
3772
3773                 if (cond_resched_lock(&root->inode_lock))
3774                         goto again;
3775
3776                 node = rb_next(node);
3777         }
3778         spin_unlock(&root->inode_lock);
3779         return 0;
3780 }
3781
3782 static int btrfs_init_locked_inode(struct inode *inode, void *p)
3783 {
3784         struct btrfs_iget_args *args = p;
3785         inode->i_ino = args->ino;
3786         BTRFS_I(inode)->root = args->root;
3787         btrfs_set_inode_space_info(args->root, inode);
3788         return 0;
3789 }
3790
3791 static int btrfs_find_actor(struct inode *inode, void *opaque)
3792 {
3793         struct btrfs_iget_args *args = opaque;
3794         return args->ino == btrfs_ino(inode) &&
3795                 args->root == BTRFS_I(inode)->root;
3796 }
3797
3798 static struct inode *btrfs_iget_locked(struct super_block *s,
3799                                        u64 objectid,
3800                                        struct btrfs_root *root)
3801 {
3802         struct inode *inode;
3803         struct btrfs_iget_args args;
3804         args.ino = objectid;
3805         args.root = root;
3806
3807         inode = iget5_locked(s, objectid, btrfs_find_actor,
3808                              btrfs_init_locked_inode,
3809                              (void *)&args);
3810         return inode;
3811 }
3812
3813 /* Get an inode object given its location and corresponding root.
3814  * Returns in *is_new if the inode was read from disk
3815  */
3816 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
3817                          struct btrfs_root *root, int *new)
3818 {
3819         struct inode *inode;
3820
3821         inode = btrfs_iget_locked(s, location->objectid, root);
3822         if (!inode)
3823                 return ERR_PTR(-ENOMEM);
3824
3825         if (inode->i_state & I_NEW) {
3826                 BTRFS_I(inode)->root = root;
3827                 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
3828                 btrfs_read_locked_inode(inode);
3829                 if (!is_bad_inode(inode)) {
3830                         inode_tree_add(inode);
3831                         unlock_new_inode(inode);
3832                         if (new)
3833                                 *new = 1;
3834                 } else {
3835                         unlock_new_inode(inode);
3836                         iput(inode);
3837                         inode = ERR_PTR(-ESTALE);
3838                 }
3839         }
3840
3841         return inode;
3842 }
3843
3844 static struct inode *new_simple_dir(struct super_block *s,
3845                                     struct btrfs_key *key,
3846                                     struct btrfs_root *root)
3847 {
3848         struct inode *inode = new_inode(s);
3849
3850         if (!inode)
3851                 return ERR_PTR(-ENOMEM);
3852
3853         BTRFS_I(inode)->root = root;
3854         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
3855         BTRFS_I(inode)->dummy_inode = 1;
3856
3857         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
3858         inode->i_op = &simple_dir_inode_operations;
3859         inode->i_fop = &simple_dir_operations;
3860         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
3861         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
3862
3863         return inode;
3864 }
3865
3866 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
3867 {
3868         struct inode *inode;
3869         struct btrfs_root *root = BTRFS_I(dir)->root;
3870         struct btrfs_root *sub_root = root;
3871         struct btrfs_key location;
3872         int index;
3873         int ret = 0;
3874
3875         if (dentry->d_name.len > BTRFS_NAME_LEN)
3876                 return ERR_PTR(-ENAMETOOLONG);
3877
3878         if (unlikely(d_need_lookup(dentry))) {
3879                 memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key));
3880                 kfree(dentry->d_fsdata);
3881                 dentry->d_fsdata = NULL;
3882                 /* This thing is hashed, drop it for now */
3883                 d_drop(dentry);
3884         } else {
3885                 ret = btrfs_inode_by_name(dir, dentry, &location);
3886         }
3887
3888         if (ret < 0)
3889                 return ERR_PTR(ret);
3890
3891         if (location.objectid == 0)
3892                 return NULL;
3893
3894         if (location.type == BTRFS_INODE_ITEM_KEY) {
3895                 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
3896                 return inode;
3897         }
3898
3899         BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
3900
3901         index = srcu_read_lock(&root->fs_info->subvol_srcu);
3902         ret = fixup_tree_root_location(root, dir, dentry,
3903                                        &location, &sub_root);
3904         if (ret < 0) {
3905                 if (ret != -ENOENT)
3906                         inode = ERR_PTR(ret);
3907                 else
3908                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
3909         } else {
3910                 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
3911         }
3912         srcu_read_unlock(&root->fs_info->subvol_srcu, index);
3913
3914         if (!IS_ERR(inode) && root != sub_root) {
3915                 down_read(&root->fs_info->cleanup_work_sem);
3916                 if (!(inode->i_sb->s_flags & MS_RDONLY))
3917                         ret = btrfs_orphan_cleanup(sub_root);
3918                 up_read(&root->fs_info->cleanup_work_sem);
3919                 if (ret)
3920                         inode = ERR_PTR(ret);
3921         }
3922
3923         return inode;
3924 }
3925
3926 static int btrfs_dentry_delete(const struct dentry *dentry)
3927 {
3928         struct btrfs_root *root;
3929
3930         if (!dentry->d_inode && !IS_ROOT(dentry))
3931                 dentry = dentry->d_parent;
3932
3933         if (dentry->d_inode) {
3934                 root = BTRFS_I(dentry->d_inode)->root;
3935                 if (btrfs_root_refs(&root->root_item) == 0)
3936                         return 1;
3937         }
3938         return 0;
3939 }
3940
3941 static void btrfs_dentry_release(struct dentry *dentry)
3942 {
3943         if (dentry->d_fsdata)
3944                 kfree(dentry->d_fsdata);
3945 }
3946
3947 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
3948                                    struct nameidata *nd)
3949 {
3950         struct dentry *ret;
3951
3952         ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
3953         if (unlikely(d_need_lookup(dentry))) {
3954                 spin_lock(&dentry->d_lock);
3955                 dentry->d_flags &= ~DCACHE_NEED_LOOKUP;
3956                 spin_unlock(&dentry->d_lock);
3957         }
3958         return ret;
3959 }
3960
3961 unsigned char btrfs_filetype_table[] = {
3962         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
3963 };
3964
3965 static int btrfs_real_readdir(struct file *filp, void *dirent,
3966                               filldir_t filldir)
3967 {
3968         struct inode *inode = filp->f_dentry->d_inode;
3969         struct btrfs_root *root = BTRFS_I(inode)->root;
3970         struct btrfs_item *item;
3971         struct btrfs_dir_item *di;
3972         struct btrfs_key key;
3973         struct btrfs_key found_key;
3974         struct btrfs_path *path;
3975         struct list_head ins_list;
3976         struct list_head del_list;
3977         struct qstr q;
3978         int ret;
3979         struct extent_buffer *leaf;
3980         int slot;
3981         unsigned char d_type;
3982         int over = 0;
3983         u32 di_cur;
3984         u32 di_total;
3985         u32 di_len;
3986         int key_type = BTRFS_DIR_INDEX_KEY;
3987         char tmp_name[32];
3988         char *name_ptr;
3989         int name_len;
3990         int is_curr = 0;        /* filp->f_pos points to the current index? */
3991
3992         /* FIXME, use a real flag for deciding about the key type */
3993         if (root->fs_info->tree_root == root)
3994                 key_type = BTRFS_DIR_ITEM_KEY;
3995
3996         /* special case for "." */
3997         if (filp->f_pos == 0) {
3998                 over = filldir(dirent, ".", 1,
3999                                filp->f_pos, btrfs_ino(inode), DT_DIR);
4000                 if (over)
4001                         return 0;
4002                 filp->f_pos = 1;
4003         }
4004         /* special case for .., just use the back ref */
4005         if (filp->f_pos == 1) {
4006                 u64 pino = parent_ino(filp->f_path.dentry);
4007                 over = filldir(dirent, "..", 2,
4008                                filp->f_pos, pino, DT_DIR);
4009                 if (over)
4010                         return 0;
4011                 filp->f_pos = 2;
4012         }
4013         path = btrfs_alloc_path();
4014         if (!path)
4015                 return -ENOMEM;
4016
4017         path->reada = 1;
4018
4019         if (key_type == BTRFS_DIR_INDEX_KEY) {
4020                 INIT_LIST_HEAD(&ins_list);
4021                 INIT_LIST_HEAD(&del_list);
4022                 btrfs_get_delayed_items(inode, &ins_list, &del_list);
4023         }
4024
4025         btrfs_set_key_type(&key, key_type);
4026         key.offset = filp->f_pos;
4027         key.objectid = btrfs_ino(inode);
4028
4029         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4030         if (ret < 0)
4031                 goto err;
4032
4033         while (1) {
4034                 leaf = path->nodes[0];
4035                 slot = path->slots[0];
4036                 if (slot >= btrfs_header_nritems(leaf)) {
4037                         ret = btrfs_next_leaf(root, path);
4038                         if (ret < 0)
4039                                 goto err;
4040                         else if (ret > 0)
4041                                 break;
4042                         continue;
4043                 }
4044
4045                 item = btrfs_item_nr(leaf, slot);
4046                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4047
4048                 if (found_key.objectid != key.objectid)
4049                         break;
4050                 if (btrfs_key_type(&found_key) != key_type)
4051                         break;
4052                 if (found_key.offset < filp->f_pos)
4053                         goto next;
4054                 if (key_type == BTRFS_DIR_INDEX_KEY &&
4055                     btrfs_should_delete_dir_index(&del_list,
4056                                                   found_key.offset))
4057                         goto next;
4058
4059                 filp->f_pos = found_key.offset;
4060                 is_curr = 1;
4061
4062                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4063                 di_cur = 0;
4064                 di_total = btrfs_item_size(leaf, item);
4065
4066                 while (di_cur < di_total) {
4067                         struct btrfs_key location;
4068                         struct dentry *tmp;
4069
4070                         if (verify_dir_item(root, leaf, di))
4071                                 break;
4072
4073                         name_len = btrfs_dir_name_len(leaf, di);
4074                         if (name_len <= sizeof(tmp_name)) {
4075                                 name_ptr = tmp_name;
4076                         } else {
4077                                 name_ptr = kmalloc(name_len, GFP_NOFS);
4078                                 if (!name_ptr) {
4079                                         ret = -ENOMEM;
4080                                         goto err;
4081                                 }
4082                         }
4083                         read_extent_buffer(leaf, name_ptr,
4084                                            (unsigned long)(di + 1), name_len);
4085
4086                         d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4087                         btrfs_dir_item_key_to_cpu(leaf, di, &location);
4088
4089                         q.name = name_ptr;
4090                         q.len = name_len;
4091                         q.hash = full_name_hash(q.name, q.len);
4092                         tmp = d_lookup(filp->f_dentry, &q);
4093                         if (!tmp) {
4094                                 struct btrfs_key *newkey;
4095
4096                                 newkey = kzalloc(sizeof(struct btrfs_key),
4097                                                  GFP_NOFS);
4098                                 if (!newkey)
4099                                         goto no_dentry;
4100                                 tmp = d_alloc(filp->f_dentry, &q);
4101                                 if (!tmp) {
4102                                         kfree(newkey);
4103                                         dput(tmp);
4104                                         goto no_dentry;
4105                                 }
4106                                 memcpy(newkey, &location,
4107                                        sizeof(struct btrfs_key));
4108                                 tmp->d_fsdata = newkey;
4109                                 tmp->d_flags |= DCACHE_NEED_LOOKUP;
4110                                 d_rehash(tmp);
4111                                 dput(tmp);
4112                         } else {
4113                                 dput(tmp);
4114                         }
4115 no_dentry:
4116                         /* is this a reference to our own snapshot? If so
4117                          * skip it
4118                          */
4119                         if (location.type == BTRFS_ROOT_ITEM_KEY &&
4120                             location.objectid == root->root_key.objectid) {
4121                                 over = 0;
4122                                 goto skip;
4123                         }
4124                         over = filldir(dirent, name_ptr, name_len,
4125                                        found_key.offset, location.objectid,
4126                                        d_type);
4127
4128 skip:
4129                         if (name_ptr != tmp_name)
4130                                 kfree(name_ptr);
4131
4132                         if (over)
4133                                 goto nopos;
4134                         di_len = btrfs_dir_name_len(leaf, di) +
4135                                  btrfs_dir_data_len(leaf, di) + sizeof(*di);
4136                         di_cur += di_len;
4137                         di = (struct btrfs_dir_item *)((char *)di + di_len);
4138                 }
4139 next:
4140                 path->slots[0]++;
4141         }
4142
4143         if (key_type == BTRFS_DIR_INDEX_KEY) {
4144                 if (is_curr)
4145                         filp->f_pos++;
4146                 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
4147                                                       &ins_list);
4148                 if (ret)
4149                         goto nopos;
4150         }
4151
4152         /* Reached end of directory/root. Bump pos past the last item. */
4153         if (key_type == BTRFS_DIR_INDEX_KEY)
4154                 /*
4155                  * 32-bit glibc will use getdents64, but then strtol -
4156                  * so the last number we can serve is this.
4157                  */
4158                 filp->f_pos = 0x7fffffff;
4159         else
4160                 filp->f_pos++;
4161 nopos:
4162         ret = 0;
4163 err:
4164         if (key_type == BTRFS_DIR_INDEX_KEY)
4165                 btrfs_put_delayed_items(&ins_list, &del_list);
4166         btrfs_free_path(path);
4167         return ret;
4168 }
4169
4170 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4171 {
4172         struct btrfs_root *root = BTRFS_I(inode)->root;
4173         struct btrfs_trans_handle *trans;
4174         int ret = 0;
4175         bool nolock = false;
4176
4177         if (BTRFS_I(inode)->dummy_inode)
4178                 return 0;
4179
4180         if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(root, inode))
4181                 nolock = true;
4182
4183         if (wbc->sync_mode == WB_SYNC_ALL) {
4184                 if (nolock)
4185                         trans = btrfs_join_transaction_nolock(root);
4186                 else
4187                         trans = btrfs_join_transaction(root);
4188                 if (IS_ERR(trans))
4189                         return PTR_ERR(trans);
4190                 if (nolock)
4191                         ret = btrfs_end_transaction_nolock(trans, root);
4192                 else
4193                         ret = btrfs_commit_transaction(trans, root);
4194         }
4195         return ret;
4196 }
4197
4198 /*
4199  * This is somewhat expensive, updating the tree every time the
4200  * inode changes.  But, it is most likely to find the inode in cache.
4201  * FIXME, needs more benchmarking...there are no reasons other than performance
4202  * to keep or drop this code.
4203  */
4204 void btrfs_dirty_inode(struct inode *inode, int flags)
4205 {
4206         struct btrfs_root *root = BTRFS_I(inode)->root;
4207         struct btrfs_trans_handle *trans;
4208         int ret;
4209
4210         if (BTRFS_I(inode)->dummy_inode)
4211                 return;
4212
4213         trans = btrfs_join_transaction(root);
4214         BUG_ON(IS_ERR(trans));
4215
4216         ret = btrfs_update_inode(trans, root, inode);
4217         if (ret && ret == -ENOSPC) {
4218                 /* whoops, lets try again with the full transaction */
4219                 btrfs_end_transaction(trans, root);
4220                 trans = btrfs_start_transaction(root, 1);
4221                 if (IS_ERR(trans)) {
4222                         printk_ratelimited(KERN_ERR "btrfs: fail to "
4223                                        "dirty  inode %llu error %ld\n",
4224                                        (unsigned long long)btrfs_ino(inode),
4225                                        PTR_ERR(trans));
4226                         return;
4227                 }
4228
4229                 ret = btrfs_update_inode(trans, root, inode);
4230                 if (ret) {
4231                         printk_ratelimited(KERN_ERR "btrfs: fail to "
4232                                        "dirty  inode %llu error %d\n",
4233                                        (unsigned long long)btrfs_ino(inode),
4234                                        ret);
4235                 }
4236         }
4237         btrfs_end_transaction(trans, root);
4238         if (BTRFS_I(inode)->delayed_node)
4239                 btrfs_balance_delayed_items(root);
4240 }
4241
4242 /*
4243  * find the highest existing sequence number in a directory
4244  * and then set the in-memory index_cnt variable to reflect
4245  * free sequence numbers
4246  */
4247 static int btrfs_set_inode_index_count(struct inode *inode)
4248 {
4249         struct btrfs_root *root = BTRFS_I(inode)->root;
4250         struct btrfs_key key, found_key;
4251         struct btrfs_path *path;
4252         struct extent_buffer *leaf;
4253         int ret;
4254
4255         key.objectid = btrfs_ino(inode);
4256         btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4257         key.offset = (u64)-1;
4258
4259         path = btrfs_alloc_path();
4260         if (!path)
4261                 return -ENOMEM;
4262
4263         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4264         if (ret < 0)
4265                 goto out;
4266         /* FIXME: we should be able to handle this */
4267         if (ret == 0)
4268                 goto out;
4269         ret = 0;
4270
4271         /*
4272          * MAGIC NUMBER EXPLANATION:
4273          * since we search a directory based on f_pos we have to start at 2
4274          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4275          * else has to start at 2
4276          */
4277         if (path->slots[0] == 0) {
4278                 BTRFS_I(inode)->index_cnt = 2;
4279                 goto out;
4280         }
4281
4282         path->slots[0]--;
4283
4284         leaf = path->nodes[0];
4285         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4286
4287         if (found_key.objectid != btrfs_ino(inode) ||
4288             btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4289                 BTRFS_I(inode)->index_cnt = 2;
4290                 goto out;
4291         }
4292
4293         BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4294 out:
4295         btrfs_free_path(path);
4296         return ret;
4297 }
4298
4299 /*
4300  * helper to find a free sequence number in a given directory.  This current
4301  * code is very simple, later versions will do smarter things in the btree
4302  */
4303 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4304 {
4305         int ret = 0;
4306
4307         if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4308                 ret = btrfs_inode_delayed_dir_index_count(dir);
4309                 if (ret) {
4310                         ret = btrfs_set_inode_index_count(dir);
4311                         if (ret)
4312                                 return ret;
4313                 }
4314         }
4315
4316         *index = BTRFS_I(dir)->index_cnt;
4317         BTRFS_I(dir)->index_cnt++;
4318
4319         return ret;
4320 }
4321
4322 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4323                                      struct btrfs_root *root,
4324                                      struct inode *dir,
4325                                      const char *name, int name_len,
4326                                      u64 ref_objectid, u64 objectid, int mode,
4327                                      u64 *index)
4328 {
4329         struct inode *inode;
4330         struct btrfs_inode_item *inode_item;
4331         struct btrfs_key *location;
4332         struct btrfs_path *path;
4333         struct btrfs_inode_ref *ref;
4334         struct btrfs_key key[2];
4335         u32 sizes[2];
4336         unsigned long ptr;
4337         int ret;
4338         int owner;
4339
4340         path = btrfs_alloc_path();
4341         if (!path)
4342                 return ERR_PTR(-ENOMEM);
4343
4344         inode = new_inode(root->fs_info->sb);
4345         if (!inode) {
4346                 btrfs_free_path(path);
4347                 return ERR_PTR(-ENOMEM);
4348         }
4349
4350         /*
4351          * we have to initialize this early, so we can reclaim the inode
4352          * number if we fail afterwards in this function.
4353          */
4354         inode->i_ino = objectid;
4355
4356         if (dir) {
4357                 trace_btrfs_inode_request(dir);
4358
4359                 ret = btrfs_set_inode_index(dir, index);
4360                 if (ret) {
4361                         btrfs_free_path(path);
4362                         iput(inode);
4363                         return ERR_PTR(ret);
4364                 }
4365         }
4366         /*
4367          * index_cnt is ignored for everything but a dir,
4368          * btrfs_get_inode_index_count has an explanation for the magic
4369          * number
4370          */
4371         BTRFS_I(inode)->index_cnt = 2;
4372         BTRFS_I(inode)->root = root;
4373         BTRFS_I(inode)->generation = trans->transid;
4374         inode->i_generation = BTRFS_I(inode)->generation;
4375         btrfs_set_inode_space_info(root, inode);
4376
4377         if (S_ISDIR(mode))
4378                 owner = 0;
4379         else
4380                 owner = 1;
4381
4382         key[0].objectid = objectid;
4383         btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4384         key[0].offset = 0;
4385
4386         key[1].objectid = objectid;
4387         btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4388         key[1].offset = ref_objectid;
4389
4390         sizes[0] = sizeof(struct btrfs_inode_item);
4391         sizes[1] = name_len + sizeof(*ref);
4392
4393         path->leave_spinning = 1;
4394         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4395         if (ret != 0)
4396                 goto fail;
4397
4398         inode_init_owner(inode, dir, mode);
4399         inode_set_bytes(inode, 0);
4400         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4401         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4402                                   struct btrfs_inode_item);
4403         fill_inode_item(trans, path->nodes[0], inode_item, inode);
4404
4405         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4406                              struct btrfs_inode_ref);
4407         btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4408         btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4409         ptr = (unsigned long)(ref + 1);
4410         write_extent_buffer(path->nodes[0], name, ptr, name_len);
4411
4412         btrfs_mark_buffer_dirty(path->nodes[0]);
4413         btrfs_free_path(path);
4414
4415         location = &BTRFS_I(inode)->location;
4416         location->objectid = objectid;
4417         location->offset = 0;
4418         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4419
4420         btrfs_inherit_iflags(inode, dir);
4421
4422         if (S_ISREG(mode)) {
4423                 if (btrfs_test_opt(root, NODATASUM))
4424                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4425                 if (btrfs_test_opt(root, NODATACOW) ||
4426                     (BTRFS_I(dir)->flags & BTRFS_INODE_NODATACOW))
4427                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4428         }
4429
4430         insert_inode_hash(inode);
4431         inode_tree_add(inode);
4432
4433         trace_btrfs_inode_new(inode);
4434         btrfs_set_inode_last_trans(trans, inode);
4435
4436         return inode;
4437 fail:
4438         if (dir)
4439                 BTRFS_I(dir)->index_cnt--;
4440         btrfs_free_path(path);
4441         iput(inode);
4442         return ERR_PTR(ret);
4443 }
4444
4445 static inline u8 btrfs_inode_type(struct inode *inode)
4446 {
4447         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4448 }
4449
4450 /*
4451  * utility function to add 'inode' into 'parent_inode' with
4452  * a give name and a given sequence number.
4453  * if 'add_backref' is true, also insert a backref from the
4454  * inode to the parent directory.
4455  */
4456 int btrfs_add_link(struct btrfs_trans_handle *trans,
4457                    struct inode *parent_inode, struct inode *inode,
4458                    const char *name, int name_len, int add_backref, u64 index)
4459 {
4460         int ret = 0;
4461         struct btrfs_key key;
4462         struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4463         u64 ino = btrfs_ino(inode);
4464         u64 parent_ino = btrfs_ino(parent_inode);
4465
4466         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4467                 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4468         } else {
4469                 key.objectid = ino;
4470                 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4471                 key.offset = 0;
4472         }
4473
4474         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4475                 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4476                                          key.objectid, root->root_key.objectid,
4477                                          parent_ino, index, name, name_len);
4478         } else if (add_backref) {
4479                 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
4480                                              parent_ino, index);
4481         }
4482
4483         if (ret == 0) {
4484                 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4485                                             parent_inode, &key,
4486                                             btrfs_inode_type(inode), index);
4487                 BUG_ON(ret);
4488
4489                 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4490                                    name_len * 2);
4491                 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4492                 ret = btrfs_update_inode(trans, root, parent_inode);
4493         }
4494         return ret;
4495 }
4496
4497 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4498                             struct inode *dir, struct dentry *dentry,
4499                             struct inode *inode, int backref, u64 index)
4500 {
4501         int err = btrfs_add_link(trans, dir, inode,
4502                                  dentry->d_name.name, dentry->d_name.len,
4503                                  backref, index);
4504         if (!err) {
4505                 d_instantiate(dentry, inode);
4506                 return 0;
4507         }
4508         if (err > 0)
4509                 err = -EEXIST;
4510         return err;
4511 }
4512
4513 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4514                         int mode, dev_t rdev)
4515 {
4516         struct btrfs_trans_handle *trans;
4517         struct btrfs_root *root = BTRFS_I(dir)->root;
4518         struct inode *inode = NULL;
4519         int err;
4520         int drop_inode = 0;
4521         u64 objectid;
4522         unsigned long nr = 0;
4523         u64 index = 0;
4524
4525         if (!new_valid_dev(rdev))
4526                 return -EINVAL;
4527
4528         /*
4529          * 2 for inode item and ref
4530          * 2 for dir items
4531          * 1 for xattr if selinux is on
4532          */
4533         trans = btrfs_start_transaction(root, 5);
4534         if (IS_ERR(trans))
4535                 return PTR_ERR(trans);
4536
4537         err = btrfs_find_free_ino(root, &objectid);
4538         if (err)
4539                 goto out_unlock;
4540
4541         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4542                                 dentry->d_name.len, btrfs_ino(dir), objectid,
4543                                 mode, &index);
4544         if (IS_ERR(inode)) {
4545                 err = PTR_ERR(inode);
4546                 goto out_unlock;
4547         }
4548
4549         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4550         if (err) {
4551                 drop_inode = 1;
4552                 goto out_unlock;
4553         }
4554
4555         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4556         if (err)
4557                 drop_inode = 1;
4558         else {
4559                 inode->i_op = &btrfs_special_inode_operations;
4560                 init_special_inode(inode, inode->i_mode, rdev);
4561                 btrfs_update_inode(trans, root, inode);
4562         }
4563 out_unlock:
4564         nr = trans->blocks_used;
4565         btrfs_end_transaction_throttle(trans, root);
4566         btrfs_btree_balance_dirty(root, nr);
4567         if (drop_inode) {
4568                 inode_dec_link_count(inode);
4569                 iput(inode);
4570         }
4571         return err;
4572 }
4573
4574 static int btrfs_create(struct inode *dir, struct dentry *dentry,
4575                         int mode, struct nameidata *nd)
4576 {
4577         struct btrfs_trans_handle *trans;
4578         struct btrfs_root *root = BTRFS_I(dir)->root;
4579         struct inode *inode = NULL;
4580         int drop_inode = 0;
4581         int err;
4582         unsigned long nr = 0;
4583         u64 objectid;
4584         u64 index = 0;
4585
4586         /*
4587          * 2 for inode item and ref
4588          * 2 for dir items
4589          * 1 for xattr if selinux is on
4590          */
4591         trans = btrfs_start_transaction(root, 5);
4592         if (IS_ERR(trans))
4593                 return PTR_ERR(trans);
4594
4595         err = btrfs_find_free_ino(root, &objectid);
4596         if (err)
4597                 goto out_unlock;
4598
4599         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4600                                 dentry->d_name.len, btrfs_ino(dir), objectid,
4601                                 mode, &index);
4602         if (IS_ERR(inode)) {
4603                 err = PTR_ERR(inode);
4604                 goto out_unlock;
4605         }
4606
4607         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4608         if (err) {
4609                 drop_inode = 1;
4610                 goto out_unlock;
4611         }
4612
4613         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4614         if (err)
4615                 drop_inode = 1;
4616         else {
4617                 inode->i_mapping->a_ops = &btrfs_aops;
4618                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4619                 inode->i_fop = &btrfs_file_operations;
4620                 inode->i_op = &btrfs_file_inode_operations;
4621                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4622         }
4623 out_unlock:
4624         nr = trans->blocks_used;
4625         btrfs_end_transaction_throttle(trans, root);
4626         if (drop_inode) {
4627                 inode_dec_link_count(inode);
4628                 iput(inode);
4629         }
4630         btrfs_btree_balance_dirty(root, nr);
4631         return err;
4632 }
4633
4634 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4635                       struct dentry *dentry)
4636 {
4637         struct btrfs_trans_handle *trans;
4638         struct btrfs_root *root = BTRFS_I(dir)->root;
4639         struct inode *inode = old_dentry->d_inode;
4640         u64 index;
4641         unsigned long nr = 0;
4642         int err;
4643         int drop_inode = 0;
4644
4645         /* do not allow sys_link's with other subvols of the same device */
4646         if (root->objectid != BTRFS_I(inode)->root->objectid)
4647                 return -EXDEV;
4648
4649         if (inode->i_nlink == ~0U)
4650                 return -EMLINK;
4651
4652         err = btrfs_set_inode_index(dir, &index);
4653         if (err)
4654                 goto fail;
4655
4656         /*
4657          * 2 items for inode and inode ref
4658          * 2 items for dir items
4659          * 1 item for parent inode
4660          */
4661         trans = btrfs_start_transaction(root, 5);
4662         if (IS_ERR(trans)) {
4663                 err = PTR_ERR(trans);
4664                 goto fail;
4665         }
4666
4667         btrfs_inc_nlink(inode);
4668         inode->i_ctime = CURRENT_TIME;
4669         ihold(inode);
4670
4671         err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
4672
4673         if (err) {
4674                 drop_inode = 1;
4675         } else {
4676                 struct dentry *parent = dentry->d_parent;
4677                 err = btrfs_update_inode(trans, root, inode);
4678                 BUG_ON(err);
4679                 btrfs_log_new_name(trans, inode, NULL, parent);
4680         }
4681
4682         nr = trans->blocks_used;
4683         btrfs_end_transaction_throttle(trans, root);
4684 fail:
4685         if (drop_inode) {
4686                 inode_dec_link_count(inode);
4687                 iput(inode);
4688         }
4689         btrfs_btree_balance_dirty(root, nr);
4690         return err;
4691 }
4692
4693 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
4694 {
4695         struct inode *inode = NULL;
4696         struct btrfs_trans_handle *trans;
4697         struct btrfs_root *root = BTRFS_I(dir)->root;
4698         int err = 0;
4699         int drop_on_err = 0;
4700         u64 objectid = 0;
4701         u64 index = 0;
4702         unsigned long nr = 1;
4703
4704         /*
4705          * 2 items for inode and ref
4706          * 2 items for dir items
4707          * 1 for xattr if selinux is on
4708          */
4709         trans = btrfs_start_transaction(root, 5);
4710         if (IS_ERR(trans))
4711                 return PTR_ERR(trans);
4712
4713         err = btrfs_find_free_ino(root, &objectid);
4714         if (err)
4715                 goto out_fail;
4716
4717         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4718                                 dentry->d_name.len, btrfs_ino(dir), objectid,
4719                                 S_IFDIR | mode, &index);
4720         if (IS_ERR(inode)) {
4721                 err = PTR_ERR(inode);
4722                 goto out_fail;
4723         }
4724
4725         drop_on_err = 1;
4726
4727         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4728         if (err)
4729                 goto out_fail;
4730
4731         inode->i_op = &btrfs_dir_inode_operations;
4732         inode->i_fop = &btrfs_dir_file_operations;
4733
4734         btrfs_i_size_write(inode, 0);
4735         err = btrfs_update_inode(trans, root, inode);
4736         if (err)
4737                 goto out_fail;
4738
4739         err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
4740                              dentry->d_name.len, 0, index);
4741         if (err)
4742                 goto out_fail;
4743
4744         d_instantiate(dentry, inode);
4745         drop_on_err = 0;
4746
4747 out_fail:
4748         nr = trans->blocks_used;
4749         btrfs_end_transaction_throttle(trans, root);
4750         if (drop_on_err)
4751                 iput(inode);
4752         btrfs_btree_balance_dirty(root, nr);
4753         return err;
4754 }
4755
4756 /* helper for btfs_get_extent.  Given an existing extent in the tree,
4757  * and an extent that you want to insert, deal with overlap and insert
4758  * the new extent into the tree.
4759  */
4760 static int merge_extent_mapping(struct extent_map_tree *em_tree,
4761                                 struct extent_map *existing,
4762                                 struct extent_map *em,
4763                                 u64 map_start, u64 map_len)
4764 {
4765         u64 start_diff;
4766
4767         BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
4768         start_diff = map_start - em->start;
4769         em->start = map_start;
4770         em->len = map_len;
4771         if (em->block_start < EXTENT_MAP_LAST_BYTE &&
4772             !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
4773                 em->block_start += start_diff;
4774                 em->block_len -= start_diff;
4775         }
4776         return add_extent_mapping(em_tree, em);
4777 }
4778
4779 static noinline int uncompress_inline(struct btrfs_path *path,
4780                                       struct inode *inode, struct page *page,
4781                                       size_t pg_offset, u64 extent_offset,
4782                                       struct btrfs_file_extent_item *item)
4783 {
4784         int ret;
4785         struct extent_buffer *leaf = path->nodes[0];
4786         char *tmp;
4787         size_t max_size;
4788         unsigned long inline_size;
4789         unsigned long ptr;
4790         int compress_type;
4791
4792         WARN_ON(pg_offset != 0);
4793         compress_type = btrfs_file_extent_compression(leaf, item);
4794         max_size = btrfs_file_extent_ram_bytes(leaf, item);
4795         inline_size = btrfs_file_extent_inline_item_len(leaf,
4796                                         btrfs_item_nr(leaf, path->slots[0]));
4797         tmp = kmalloc(inline_size, GFP_NOFS);
4798         if (!tmp)
4799                 return -ENOMEM;
4800         ptr = btrfs_file_extent_inline_start(item);
4801
4802         read_extent_buffer(leaf, tmp, ptr, inline_size);
4803
4804         max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
4805         ret = btrfs_decompress(compress_type, tmp, page,
4806                                extent_offset, inline_size, max_size);
4807         if (ret) {
4808                 char *kaddr = kmap_atomic(page, KM_USER0);
4809                 unsigned long copy_size = min_t(u64,
4810                                   PAGE_CACHE_SIZE - pg_offset,
4811                                   max_size - extent_offset);
4812                 memset(kaddr + pg_offset, 0, copy_size);
4813                 kunmap_atomic(kaddr, KM_USER0);
4814         }
4815         kfree(tmp);
4816         return 0;
4817 }
4818
4819 /*
4820  * a bit scary, this does extent mapping from logical file offset to the disk.
4821  * the ugly parts come from merging extents from the disk with the in-ram
4822  * representation.  This gets more complex because of the data=ordered code,
4823  * where the in-ram extents might be locked pending data=ordered completion.
4824  *
4825  * This also copies inline extents directly into the page.
4826  */
4827
4828 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
4829                                     size_t pg_offset, u64 start, u64 len,
4830                                     int create)
4831 {
4832         int ret;
4833         int err = 0;
4834         u64 bytenr;
4835         u64 extent_start = 0;
4836         u64 extent_end = 0;
4837         u64 objectid = btrfs_ino(inode);
4838         u32 found_type;
4839         struct btrfs_path *path = NULL;
4840         struct btrfs_root *root = BTRFS_I(inode)->root;
4841         struct btrfs_file_extent_item *item;
4842         struct extent_buffer *leaf;
4843         struct btrfs_key found_key;
4844         struct extent_map *em = NULL;
4845         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4846         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4847         struct btrfs_trans_handle *trans = NULL;
4848         int compress_type;
4849
4850 again:
4851         read_lock(&em_tree->lock);
4852         em = lookup_extent_mapping(em_tree, start, len);
4853         if (em)
4854                 em->bdev = root->fs_info->fs_devices->latest_bdev;
4855         read_unlock(&em_tree->lock);
4856
4857         if (em) {
4858                 if (em->start > start || em->start + em->len <= start)
4859                         free_extent_map(em);
4860                 else if (em->block_start == EXTENT_MAP_INLINE && page)
4861                         free_extent_map(em);
4862                 else
4863                         goto out;
4864         }
4865         em = alloc_extent_map();
4866         if (!em) {
4867                 err = -ENOMEM;
4868                 goto out;
4869         }
4870         em->bdev = root->fs_info->fs_devices->latest_bdev;
4871         em->start = EXTENT_MAP_HOLE;
4872         em->orig_start = EXTENT_MAP_HOLE;
4873         em->len = (u64)-1;
4874         em->block_len = (u64)-1;
4875
4876         if (!path) {
4877                 path = btrfs_alloc_path();
4878                 if (!path) {
4879                         err = -ENOMEM;
4880                         goto out;
4881                 }
4882                 /*
4883                  * Chances are we'll be called again, so go ahead and do
4884                  * readahead
4885                  */
4886                 path->reada = 1;
4887         }
4888
4889         ret = btrfs_lookup_file_extent(trans, root, path,
4890                                        objectid, start, trans != NULL);
4891         if (ret < 0) {
4892                 err = ret;
4893                 goto out;
4894         }
4895
4896         if (ret != 0) {
4897                 if (path->slots[0] == 0)
4898                         goto not_found;
4899                 path->slots[0]--;
4900         }
4901
4902         leaf = path->nodes[0];
4903         item = btrfs_item_ptr(leaf, path->slots[0],
4904                               struct btrfs_file_extent_item);
4905         /* are we inside the extent that was found? */
4906         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4907         found_type = btrfs_key_type(&found_key);
4908         if (found_key.objectid != objectid ||
4909             found_type != BTRFS_EXTENT_DATA_KEY) {
4910                 goto not_found;
4911         }
4912
4913         found_type = btrfs_file_extent_type(leaf, item);
4914         extent_start = found_key.offset;
4915         compress_type = btrfs_file_extent_compression(leaf, item);
4916         if (found_type == BTRFS_FILE_EXTENT_REG ||
4917             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
4918                 extent_end = extent_start +
4919                        btrfs_file_extent_num_bytes(leaf, item);
4920         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
4921                 size_t size;
4922                 size = btrfs_file_extent_inline_len(leaf, item);
4923                 extent_end = (extent_start + size + root->sectorsize - 1) &
4924                         ~((u64)root->sectorsize - 1);
4925         }
4926
4927         if (start >= extent_end) {
4928                 path->slots[0]++;
4929                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4930                         ret = btrfs_next_leaf(root, path);
4931                         if (ret < 0) {
4932                                 err = ret;
4933                                 goto out;
4934                         }
4935                         if (ret > 0)
4936                                 goto not_found;
4937                         leaf = path->nodes[0];
4938                 }
4939                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4940                 if (found_key.objectid != objectid ||
4941                     found_key.type != BTRFS_EXTENT_DATA_KEY)
4942                         goto not_found;
4943                 if (start + len <= found_key.offset)
4944                         goto not_found;
4945                 em->start = start;
4946                 em->len = found_key.offset - start;
4947                 goto not_found_em;
4948         }
4949
4950         if (found_type == BTRFS_FILE_EXTENT_REG ||
4951             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
4952                 em->start = extent_start;
4953                 em->len = extent_end - extent_start;
4954                 em->orig_start = extent_start -
4955                                  btrfs_file_extent_offset(leaf, item);
4956                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
4957                 if (bytenr == 0) {
4958                         em->block_start = EXTENT_MAP_HOLE;
4959                         goto insert;
4960                 }
4961                 if (compress_type != BTRFS_COMPRESS_NONE) {
4962                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
4963                         em->compress_type = compress_type;
4964                         em->block_start = bytenr;
4965                         em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
4966                                                                          item);
4967                 } else {
4968                         bytenr += btrfs_file_extent_offset(leaf, item);
4969                         em->block_start = bytenr;
4970                         em->block_len = em->len;
4971                         if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
4972                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
4973                 }
4974                 goto insert;
4975         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
4976                 unsigned long ptr;
4977                 char *map;
4978                 size_t size;
4979                 size_t extent_offset;
4980                 size_t copy_size;
4981
4982                 em->block_start = EXTENT_MAP_INLINE;
4983                 if (!page || create) {
4984                         em->start = extent_start;
4985                         em->len = extent_end - extent_start;
4986                         goto out;
4987                 }
4988
4989                 size = btrfs_file_extent_inline_len(leaf, item);
4990                 extent_offset = page_offset(page) + pg_offset - extent_start;
4991                 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
4992                                 size - extent_offset);
4993                 em->start = extent_start + extent_offset;
4994                 em->len = (copy_size + root->sectorsize - 1) &
4995                         ~((u64)root->sectorsize - 1);
4996                 em->orig_start = EXTENT_MAP_INLINE;
4997                 if (compress_type) {
4998                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
4999                         em->compress_type = compress_type;
5000                 }
5001                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5002                 if (create == 0 && !PageUptodate(page)) {
5003                         if (btrfs_file_extent_compression(leaf, item) !=
5004                             BTRFS_COMPRESS_NONE) {
5005                                 ret = uncompress_inline(path, inode, page,
5006                                                         pg_offset,
5007                                                         extent_offset, item);
5008                                 BUG_ON(ret);
5009                         } else {
5010                                 map = kmap(page);
5011                                 read_extent_buffer(leaf, map + pg_offset, ptr,
5012                                                    copy_size);
5013                                 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5014                                         memset(map + pg_offset + copy_size, 0,
5015                                                PAGE_CACHE_SIZE - pg_offset -
5016                                                copy_size);
5017                                 }
5018                                 kunmap(page);
5019                         }
5020                         flush_dcache_page(page);
5021                 } else if (create && PageUptodate(page)) {
5022                         WARN_ON(1);
5023                         if (!trans) {
5024                                 kunmap(page);
5025                                 free_extent_map(em);
5026                                 em = NULL;
5027
5028                                 btrfs_release_path(path);
5029                                 trans = btrfs_join_transaction(root);
5030
5031                                 if (IS_ERR(trans))
5032                                         return ERR_CAST(trans);
5033                                 goto again;
5034                         }
5035                         map = kmap(page);
5036                         write_extent_buffer(leaf, map + pg_offset, ptr,
5037                                             copy_size);
5038                         kunmap(page);
5039                         btrfs_mark_buffer_dirty(leaf);
5040                 }
5041                 set_extent_uptodate(io_tree, em->start,
5042                                     extent_map_end(em) - 1, NULL, GFP_NOFS);
5043                 goto insert;
5044         } else {
5045                 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
5046                 WARN_ON(1);
5047         }
5048 not_found:
5049         em->start = start;
5050         em->len = len;
5051 not_found_em:
5052         em->block_start = EXTENT_MAP_HOLE;
5053         set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5054 insert:
5055         btrfs_release_path(path);
5056         if (em->start > start || extent_map_end(em) <= start) {
5057                 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5058                        "[%llu %llu]\n", (unsigned long long)em->start,
5059                        (unsigned long long)em->len,
5060                        (unsigned long long)start,
5061                        (unsigned long long)len);
5062                 err = -EIO;
5063                 goto out;
5064         }
5065
5066         err = 0;
5067         write_lock(&em_tree->lock);
5068         ret = add_extent_mapping(em_tree, em);
5069         /* it is possible that someone inserted the extent into the tree
5070          * while we had the lock dropped.  It is also possible that
5071          * an overlapping map exists in the tree
5072          */
5073         if (ret == -EEXIST) {
5074                 struct extent_map *existing;
5075
5076                 ret = 0;
5077
5078                 existing = lookup_extent_mapping(em_tree, start, len);
5079                 if (existing && (existing->start > start ||
5080                     existing->start + existing->len <= start)) {
5081                         free_extent_map(existing);
5082                         existing = NULL;
5083                 }
5084                 if (!existing) {
5085                         existing = lookup_extent_mapping(em_tree, em->start,
5086                                                          em->len);
5087                         if (existing) {
5088                                 err = merge_extent_mapping(em_tree, existing,
5089                                                            em, start,
5090                                                            root->sectorsize);
5091                                 free_extent_map(existing);
5092                                 if (err) {
5093                                         free_extent_map(em);
5094                                         em = NULL;
5095                                 }
5096                         } else {
5097                                 err = -EIO;
5098                                 free_extent_map(em);
5099                                 em = NULL;
5100                         }
5101                 } else {
5102                         free_extent_map(em);
5103                         em = existing;
5104                         err = 0;
5105                 }
5106         }
5107         write_unlock(&em_tree->lock);
5108 out:
5109
5110         trace_btrfs_get_extent(root, em);
5111
5112         if (path)
5113                 btrfs_free_path(path);
5114         if (trans) {
5115                 ret = btrfs_end_transaction(trans, root);
5116                 if (!err)
5117                         err = ret;
5118         }
5119         if (err) {
5120                 free_extent_map(em);
5121                 return ERR_PTR(err);
5122         }
5123         return em;
5124 }
5125
5126 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5127                                            size_t pg_offset, u64 start, u64 len,
5128                                            int create)
5129 {
5130         struct extent_map *em;
5131         struct extent_map *hole_em = NULL;
5132         u64 range_start = start;
5133         u64 end;
5134         u64 found;
5135         u64 found_end;
5136         int err = 0;
5137
5138         em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5139         if (IS_ERR(em))
5140                 return em;
5141         if (em) {
5142                 /*
5143                  * if our em maps to a hole, there might
5144                  * actually be delalloc bytes behind it
5145                  */
5146                 if (em->block_start != EXTENT_MAP_HOLE)
5147                         return em;
5148                 else
5149                         hole_em = em;
5150         }
5151
5152         /* check to see if we've wrapped (len == -1 or similar) */
5153         end = start + len;
5154         if (end < start)
5155                 end = (u64)-1;
5156         else
5157                 end -= 1;
5158
5159         em = NULL;
5160
5161         /* ok, we didn't find anything, lets look for delalloc */
5162         found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5163                                  end, len, EXTENT_DELALLOC, 1);
5164         found_end = range_start + found;
5165         if (found_end < range_start)
5166                 found_end = (u64)-1;
5167
5168         /*
5169          * we didn't find anything useful, return
5170          * the original results from get_extent()
5171          */
5172         if (range_start > end || found_end <= start) {
5173                 em = hole_em;
5174                 hole_em = NULL;
5175                 goto out;
5176         }
5177
5178         /* adjust the range_start to make sure it doesn't
5179          * go backwards from the start they passed in
5180          */
5181         range_start = max(start,range_start);
5182         found = found_end - range_start;
5183
5184         if (found > 0) {
5185                 u64 hole_start = start;
5186                 u64 hole_len = len;
5187
5188                 em = alloc_extent_map();
5189                 if (!em) {
5190                         err = -ENOMEM;
5191                         goto out;
5192                 }
5193                 /*
5194                  * when btrfs_get_extent can't find anything it
5195                  * returns one huge hole
5196                  *
5197                  * make sure what it found really fits our range, and
5198                  * adjust to make sure it is based on the start from
5199                  * the caller
5200                  */
5201                 if (hole_em) {
5202                         u64 calc_end = extent_map_end(hole_em);
5203
5204                         if (calc_end <= start || (hole_em->start > end)) {
5205                                 free_extent_map(hole_em);
5206                                 hole_em = NULL;
5207                         } else {
5208                                 hole_start = max(hole_em->start, start);
5209                                 hole_len = calc_end - hole_start;
5210                         }
5211                 }
5212                 em->bdev = NULL;
5213                 if (hole_em && range_start > hole_start) {
5214                         /* our hole starts before our delalloc, so we
5215                          * have to return just the parts of the hole
5216                          * that go until  the delalloc starts
5217                          */
5218                         em->len = min(hole_len,
5219                                       range_start - hole_start);
5220                         em->start = hole_start;
5221                         em->orig_start = hole_start;
5222                         /*
5223                          * don't adjust block start at all,
5224                          * it is fixed at EXTENT_MAP_HOLE
5225                          */
5226                         em->block_start = hole_em->block_start;
5227                         em->block_len = hole_len;
5228                 } else {
5229                         em->start = range_start;
5230                         em->len = found;
5231                         em->orig_start = range_start;
5232                         em->block_start = EXTENT_MAP_DELALLOC;
5233                         em->block_len = found;
5234                 }
5235         } else if (hole_em) {
5236                 return hole_em;
5237         }
5238 out:
5239
5240         free_extent_map(hole_em);
5241         if (err) {
5242                 free_extent_map(em);
5243                 return ERR_PTR(err);
5244         }
5245         return em;
5246 }
5247
5248 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5249                                                   struct extent_map *em,
5250                                                   u64 start, u64 len)
5251 {
5252         struct btrfs_root *root = BTRFS_I(inode)->root;
5253         struct btrfs_trans_handle *trans;
5254         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5255         struct btrfs_key ins;
5256         u64 alloc_hint;
5257         int ret;
5258         bool insert = false;
5259
5260         /*
5261          * Ok if the extent map we looked up is a hole and is for the exact
5262          * range we want, there is no reason to allocate a new one, however if
5263          * it is not right then we need to free this one and drop the cache for
5264          * our range.
5265          */
5266         if (em->block_start != EXTENT_MAP_HOLE || em->start != start ||
5267             em->len != len) {
5268                 free_extent_map(em);
5269                 em = NULL;
5270                 insert = true;
5271                 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5272         }
5273
5274         trans = btrfs_join_transaction(root);
5275         if (IS_ERR(trans))
5276                 return ERR_CAST(trans);
5277
5278         if (start <= BTRFS_I(inode)->disk_i_size && len < 64 * 1024)
5279                 btrfs_add_inode_defrag(trans, inode);
5280
5281         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5282
5283         alloc_hint = get_extent_allocation_hint(inode, start, len);
5284         ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5285                                    alloc_hint, (u64)-1, &ins, 1);
5286         if (ret) {
5287                 em = ERR_PTR(ret);
5288                 goto out;
5289         }
5290
5291         if (!em) {
5292                 em = alloc_extent_map();
5293                 if (!em) {
5294                         em = ERR_PTR(-ENOMEM);
5295                         goto out;
5296                 }
5297         }
5298
5299         em->start = start;
5300         em->orig_start = em->start;
5301         em->len = ins.offset;
5302
5303         em->block_start = ins.objectid;
5304         em->block_len = ins.offset;
5305         em->bdev = root->fs_info->fs_devices->latest_bdev;
5306
5307         /*
5308          * We need to do this because if we're using the original em we searched
5309          * for, we could have EXTENT_FLAG_VACANCY set, and we don't want that.
5310          */
5311         em->flags = 0;
5312         set_bit(EXTENT_FLAG_PINNED, &em->flags);
5313
5314         while (insert) {
5315                 write_lock(&em_tree->lock);
5316                 ret = add_extent_mapping(em_tree, em);
5317                 write_unlock(&em_tree->lock);
5318                 if (ret != -EEXIST)
5319                         break;
5320                 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5321         }
5322
5323         ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5324                                            ins.offset, ins.offset, 0);
5325         if (ret) {
5326                 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5327                 em = ERR_PTR(ret);
5328         }
5329 out:
5330         btrfs_end_transaction(trans, root);
5331         return em;
5332 }
5333
5334 /*
5335  * returns 1 when the nocow is safe, < 1 on error, 0 if the
5336  * block must be cow'd
5337  */
5338 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5339                                       struct inode *inode, u64 offset, u64 len)
5340 {
5341         struct btrfs_path *path;
5342         int ret;
5343         struct extent_buffer *leaf;
5344         struct btrfs_root *root = BTRFS_I(inode)->root;
5345         struct btrfs_file_extent_item *fi;
5346         struct btrfs_key key;
5347         u64 disk_bytenr;
5348         u64 backref_offset;
5349         u64 extent_end;
5350         u64 num_bytes;
5351         int slot;
5352         int found_type;
5353
5354         path = btrfs_alloc_path();
5355         if (!path)
5356                 return -ENOMEM;
5357
5358         ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
5359                                        offset, 0);
5360         if (ret < 0)
5361                 goto out;
5362
5363         slot = path->slots[0];
5364         if (ret == 1) {
5365                 if (slot == 0) {
5366                         /* can't find the item, must cow */
5367                         ret = 0;
5368                         goto out;
5369                 }
5370                 slot--;
5371         }
5372         ret = 0;
5373         leaf = path->nodes[0];
5374         btrfs_item_key_to_cpu(leaf, &key, slot);
5375         if (key.objectid != btrfs_ino(inode) ||
5376             key.type != BTRFS_EXTENT_DATA_KEY) {
5377                 /* not our file or wrong item type, must cow */
5378                 goto out;
5379         }
5380
5381         if (key.offset > offset) {
5382                 /* Wrong offset, must cow */
5383                 goto out;
5384         }
5385
5386         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5387         found_type = btrfs_file_extent_type(leaf, fi);
5388         if (found_type != BTRFS_FILE_EXTENT_REG &&
5389             found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5390                 /* not a regular extent, must cow */
5391                 goto out;
5392         }
5393         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5394         backref_offset = btrfs_file_extent_offset(leaf, fi);
5395
5396         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5397         if (extent_end < offset + len) {
5398                 /* extent doesn't include our full range, must cow */
5399                 goto out;
5400         }
5401
5402         if (btrfs_extent_readonly(root, disk_bytenr))
5403                 goto out;
5404
5405         /*
5406          * look for other files referencing this extent, if we
5407          * find any we must cow
5408          */
5409         if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
5410                                   key.offset - backref_offset, disk_bytenr))
5411                 goto out;
5412
5413         /*
5414          * adjust disk_bytenr and num_bytes to cover just the bytes
5415          * in this extent we are about to write.  If there
5416          * are any csums in that range we have to cow in order
5417          * to keep the csums correct
5418          */
5419         disk_bytenr += backref_offset;
5420         disk_bytenr += offset - key.offset;
5421         num_bytes = min(offset + len, extent_end) - offset;
5422         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5423                                 goto out;
5424         /*
5425          * all of the above have passed, it is safe to overwrite this extent
5426          * without cow
5427          */
5428         ret = 1;
5429 out:
5430         btrfs_free_path(path);
5431         return ret;
5432 }
5433
5434 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5435                                    struct buffer_head *bh_result, int create)
5436 {
5437         struct extent_map *em;
5438         struct btrfs_root *root = BTRFS_I(inode)->root;
5439         u64 start = iblock << inode->i_blkbits;
5440         u64 len = bh_result->b_size;
5441         struct btrfs_trans_handle *trans;
5442
5443         em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5444         if (IS_ERR(em))
5445                 return PTR_ERR(em);
5446
5447         /*
5448          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5449          * io.  INLINE is special, and we could probably kludge it in here, but
5450          * it's still buffered so for safety lets just fall back to the generic
5451          * buffered path.
5452          *
5453          * For COMPRESSED we _have_ to read the entire extent in so we can
5454          * decompress it, so there will be buffering required no matter what we
5455          * do, so go ahead and fallback to buffered.
5456          *
5457          * We return -ENOTBLK because thats what makes DIO go ahead and go back
5458          * to buffered IO.  Don't blame me, this is the price we pay for using
5459          * the generic code.
5460          */
5461         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5462             em->block_start == EXTENT_MAP_INLINE) {
5463                 free_extent_map(em);
5464                 return -ENOTBLK;
5465         }
5466
5467         /* Just a good old fashioned hole, return */
5468         if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5469                         test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5470                 free_extent_map(em);
5471                 /* DIO will do one hole at a time, so just unlock a sector */
5472                 unlock_extent(&BTRFS_I(inode)->io_tree, start,
5473                               start + root->sectorsize - 1, GFP_NOFS);
5474                 return 0;
5475         }
5476
5477         /*
5478          * We don't allocate a new extent in the following cases
5479          *
5480          * 1) The inode is marked as NODATACOW.  In this case we'll just use the
5481          * existing extent.
5482          * 2) The extent is marked as PREALLOC.  We're good to go here and can
5483          * just use the extent.
5484          *
5485          */
5486         if (!create) {
5487                 len = em->len - (start - em->start);
5488                 goto map;
5489         }
5490
5491         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5492             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5493              em->block_start != EXTENT_MAP_HOLE)) {
5494                 int type;
5495                 int ret;
5496                 u64 block_start;
5497
5498                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5499                         type = BTRFS_ORDERED_PREALLOC;
5500                 else
5501                         type = BTRFS_ORDERED_NOCOW;
5502                 len = min(len, em->len - (start - em->start));
5503                 block_start = em->block_start + (start - em->start);
5504
5505                 /*
5506                  * we're not going to log anything, but we do need
5507                  * to make sure the current transaction stays open
5508                  * while we look for nocow cross refs
5509                  */
5510                 trans = btrfs_join_transaction(root);
5511                 if (IS_ERR(trans))
5512                         goto must_cow;
5513
5514                 if (can_nocow_odirect(trans, inode, start, len) == 1) {
5515                         ret = btrfs_add_ordered_extent_dio(inode, start,
5516                                            block_start, len, len, type);
5517                         btrfs_end_transaction(trans, root);
5518                         if (ret) {
5519                                 free_extent_map(em);
5520                                 return ret;
5521                         }
5522                         goto unlock;
5523                 }
5524                 btrfs_end_transaction(trans, root);
5525         }
5526 must_cow:
5527         /*
5528          * this will cow the extent, reset the len in case we changed
5529          * it above
5530          */
5531         len = bh_result->b_size;
5532         em = btrfs_new_extent_direct(inode, em, start, len);
5533         if (IS_ERR(em))
5534                 return PTR_ERR(em);
5535         len = min(len, em->len - (start - em->start));
5536 unlock:
5537         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, start + len - 1,
5538                           EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DIRTY, 1,
5539                           0, NULL, GFP_NOFS);
5540 map:
5541         bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
5542                 inode->i_blkbits;
5543         bh_result->b_size = len;
5544         bh_result->b_bdev = em->bdev;
5545         set_buffer_mapped(bh_result);
5546         if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5547                 set_buffer_new(bh_result);
5548
5549         free_extent_map(em);
5550
5551         return 0;
5552 }
5553
5554 struct btrfs_dio_private {
5555         struct inode *inode;
5556         u64 logical_offset;
5557         u64 disk_bytenr;
5558         u64 bytes;
5559         u32 *csums;
5560         void *private;
5561
5562         /* number of bios pending for this dio */
5563         atomic_t pending_bios;
5564
5565         /* IO errors */
5566         int errors;
5567
5568         struct bio *orig_bio;
5569 };
5570
5571 static void btrfs_endio_direct_read(struct bio *bio, int err)
5572 {
5573         struct btrfs_dio_private *dip = bio->bi_private;
5574         struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
5575         struct bio_vec *bvec = bio->bi_io_vec;
5576         struct inode *inode = dip->inode;
5577         struct btrfs_root *root = BTRFS_I(inode)->root;
5578         u64 start;
5579         u32 *private = dip->csums;
5580
5581         start = dip->logical_offset;
5582         do {
5583                 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
5584                         struct page *page = bvec->bv_page;
5585                         char *kaddr;
5586                         u32 csum = ~(u32)0;
5587                         unsigned long flags;
5588
5589                         local_irq_save(flags);
5590                         kaddr = kmap_atomic(page, KM_IRQ0);
5591                         csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
5592                                                csum, bvec->bv_len);
5593                         btrfs_csum_final(csum, (char *)&csum);
5594                         kunmap_atomic(kaddr, KM_IRQ0);
5595                         local_irq_restore(flags);
5596
5597                         flush_dcache_page(bvec->bv_page);
5598                         if (csum != *private) {
5599                                 printk(KERN_ERR "btrfs csum failed ino %llu off"
5600                                       " %llu csum %u private %u\n",
5601                                       (unsigned long long)btrfs_ino(inode),
5602                                       (unsigned long long)start,
5603                                       csum, *private);
5604                                 err = -EIO;
5605                         }
5606                 }
5607
5608                 start += bvec->bv_len;
5609                 private++;
5610                 bvec++;
5611         } while (bvec <= bvec_end);
5612
5613         unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
5614                       dip->logical_offset + dip->bytes - 1, GFP_NOFS);
5615         bio->bi_private = dip->private;
5616
5617         kfree(dip->csums);
5618         kfree(dip);
5619
5620         /* If we had a csum failure make sure to clear the uptodate flag */
5621         if (err)
5622                 clear_bit(BIO_UPTODATE, &bio->bi_flags);
5623         dio_end_io(bio, err);
5624 }
5625
5626 static void btrfs_endio_direct_write(struct bio *bio, int err)
5627 {
5628         struct btrfs_dio_private *dip = bio->bi_private;
5629         struct inode *inode = dip->inode;
5630         struct btrfs_root *root = BTRFS_I(inode)->root;
5631         struct btrfs_trans_handle *trans;
5632         struct btrfs_ordered_extent *ordered = NULL;
5633         struct extent_state *cached_state = NULL;
5634         u64 ordered_offset = dip->logical_offset;
5635         u64 ordered_bytes = dip->bytes;
5636         int ret;
5637
5638         if (err)
5639                 goto out_done;
5640 again:
5641         ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
5642                                                    &ordered_offset,
5643                                                    ordered_bytes);
5644         if (!ret)
5645                 goto out_test;
5646
5647         BUG_ON(!ordered);
5648
5649         trans = btrfs_join_transaction(root);
5650         if (IS_ERR(trans)) {
5651                 err = -ENOMEM;
5652                 goto out;
5653         }
5654         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5655
5656         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
5657                 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5658                 if (!ret)
5659                         err = btrfs_update_inode_fallback(trans, root, inode);
5660                 goto out;
5661         }
5662
5663         lock_extent_bits(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5664                          ordered->file_offset + ordered->len - 1, 0,
5665                          &cached_state, GFP_NOFS);
5666
5667         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags)) {
5668                 ret = btrfs_mark_extent_written(trans, inode,
5669                                                 ordered->file_offset,
5670                                                 ordered->file_offset +
5671                                                 ordered->len);
5672                 if (ret) {
5673                         err = ret;
5674                         goto out_unlock;
5675                 }
5676         } else {
5677                 ret = insert_reserved_file_extent(trans, inode,
5678                                                   ordered->file_offset,
5679                                                   ordered->start,
5680                                                   ordered->disk_len,
5681                                                   ordered->len,
5682                                                   ordered->len,
5683                                                   0, 0, 0,
5684                                                   BTRFS_FILE_EXTENT_REG);
5685                 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
5686                                    ordered->file_offset, ordered->len);
5687                 if (ret) {
5688                         err = ret;
5689                         WARN_ON(1);
5690                         goto out_unlock;
5691                 }
5692         }
5693
5694         add_pending_csums(trans, inode, ordered->file_offset, &ordered->list);
5695         ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5696         if (!ret || !test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags))
5697                 btrfs_update_inode_fallback(trans, root, inode);
5698         ret = 0;
5699 out_unlock:
5700         unlock_extent_cached(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5701                              ordered->file_offset + ordered->len - 1,
5702                              &cached_state, GFP_NOFS);
5703 out:
5704         btrfs_delalloc_release_metadata(inode, ordered->len);
5705         btrfs_end_transaction(trans, root);
5706         ordered_offset = ordered->file_offset + ordered->len;
5707         btrfs_put_ordered_extent(ordered);
5708         btrfs_put_ordered_extent(ordered);
5709
5710 out_test:
5711         /*
5712          * our bio might span multiple ordered extents.  If we haven't
5713          * completed the accounting for the whole dio, go back and try again
5714          */
5715         if (ordered_offset < dip->logical_offset + dip->bytes) {
5716                 ordered_bytes = dip->logical_offset + dip->bytes -
5717                         ordered_offset;
5718                 goto again;
5719         }
5720 out_done:
5721         bio->bi_private = dip->private;
5722
5723         kfree(dip->csums);
5724         kfree(dip);
5725
5726         /* If we had an error make sure to clear the uptodate flag */
5727         if (err)
5728                 clear_bit(BIO_UPTODATE, &bio->bi_flags);
5729         dio_end_io(bio, err);
5730 }
5731
5732 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
5733                                     struct bio *bio, int mirror_num,
5734                                     unsigned long bio_flags, u64 offset)
5735 {
5736         int ret;
5737         struct btrfs_root *root = BTRFS_I(inode)->root;
5738         ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
5739         BUG_ON(ret);
5740         return 0;
5741 }
5742
5743 static void btrfs_end_dio_bio(struct bio *bio, int err)
5744 {
5745         struct btrfs_dio_private *dip = bio->bi_private;
5746
5747         if (err) {
5748                 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
5749                       "sector %#Lx len %u err no %d\n",
5750                       (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
5751                       (unsigned long long)bio->bi_sector, bio->bi_size, err);
5752                 dip->errors = 1;
5753
5754                 /*
5755                  * before atomic variable goto zero, we must make sure
5756                  * dip->errors is perceived to be set.
5757                  */
5758                 smp_mb__before_atomic_dec();
5759         }
5760
5761         /* if there are more bios still pending for this dio, just exit */
5762         if (!atomic_dec_and_test(&dip->pending_bios))
5763                 goto out;
5764
5765         if (dip->errors)
5766                 bio_io_error(dip->orig_bio);
5767         else {
5768                 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
5769                 bio_endio(dip->orig_bio, 0);
5770         }
5771 out:
5772         bio_put(bio);
5773 }
5774
5775 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
5776                                        u64 first_sector, gfp_t gfp_flags)
5777 {
5778         int nr_vecs = bio_get_nr_vecs(bdev);
5779         return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
5780 }
5781
5782 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
5783                                          int rw, u64 file_offset, int skip_sum,
5784                                          u32 *csums, int async_submit)
5785 {
5786         int write = rw & REQ_WRITE;
5787         struct btrfs_root *root = BTRFS_I(inode)->root;
5788         int ret;
5789
5790         bio_get(bio);
5791         ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
5792         if (ret)
5793                 goto err;
5794
5795         if (skip_sum)
5796                 goto map;
5797
5798         if (write && async_submit) {
5799                 ret = btrfs_wq_submit_bio(root->fs_info,
5800                                    inode, rw, bio, 0, 0,
5801                                    file_offset,
5802                                    __btrfs_submit_bio_start_direct_io,
5803                                    __btrfs_submit_bio_done);
5804                 goto err;
5805         } else if (write) {
5806                 /*
5807                  * If we aren't doing async submit, calculate the csum of the
5808                  * bio now.
5809                  */
5810                 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
5811                 if (ret)
5812                         goto err;
5813         } else if (!skip_sum) {
5814                 ret = btrfs_lookup_bio_sums_dio(root, inode, bio,
5815                                           file_offset, csums);
5816                 if (ret)
5817                         goto err;
5818         }
5819
5820 map:
5821         ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
5822 err:
5823         bio_put(bio);
5824         return ret;
5825 }
5826
5827 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
5828                                     int skip_sum)
5829 {
5830         struct inode *inode = dip->inode;
5831         struct btrfs_root *root = BTRFS_I(inode)->root;
5832         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5833         struct bio *bio;
5834         struct bio *orig_bio = dip->orig_bio;
5835         struct bio_vec *bvec = orig_bio->bi_io_vec;
5836         u64 start_sector = orig_bio->bi_sector;
5837         u64 file_offset = dip->logical_offset;
5838         u64 submit_len = 0;
5839         u64 map_length;
5840         int nr_pages = 0;
5841         u32 *csums = dip->csums;
5842         int ret = 0;
5843         int async_submit = 0;
5844         int write = rw & REQ_WRITE;
5845
5846         map_length = orig_bio->bi_size;
5847         ret = btrfs_map_block(map_tree, READ, start_sector << 9,
5848                               &map_length, NULL, 0);
5849         if (ret) {
5850                 bio_put(orig_bio);
5851                 return -EIO;
5852         }
5853
5854         if (map_length >= orig_bio->bi_size) {
5855                 bio = orig_bio;
5856                 goto submit;
5857         }
5858
5859         async_submit = 1;
5860         bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
5861         if (!bio)
5862                 return -ENOMEM;
5863         bio->bi_private = dip;
5864         bio->bi_end_io = btrfs_end_dio_bio;
5865         atomic_inc(&dip->pending_bios);
5866
5867         while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
5868                 if (unlikely(map_length < submit_len + bvec->bv_len ||
5869                     bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5870                                  bvec->bv_offset) < bvec->bv_len)) {
5871                         /*
5872                          * inc the count before we submit the bio so
5873                          * we know the end IO handler won't happen before
5874                          * we inc the count. Otherwise, the dip might get freed
5875                          * before we're done setting it up
5876                          */
5877                         atomic_inc(&dip->pending_bios);
5878                         ret = __btrfs_submit_dio_bio(bio, inode, rw,
5879                                                      file_offset, skip_sum,
5880                                                      csums, async_submit);
5881                         if (ret) {
5882                                 bio_put(bio);
5883                                 atomic_dec(&dip->pending_bios);
5884                                 goto out_err;
5885                         }
5886
5887                         /* Write's use the ordered csums */
5888                         if (!write && !skip_sum)
5889                                 csums = csums + nr_pages;
5890                         start_sector += submit_len >> 9;
5891                         file_offset += submit_len;
5892
5893                         submit_len = 0;
5894                         nr_pages = 0;
5895
5896                         bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
5897                                                   start_sector, GFP_NOFS);
5898                         if (!bio)
5899                                 goto out_err;
5900                         bio->bi_private = dip;
5901                         bio->bi_end_io = btrfs_end_dio_bio;
5902
5903                         map_length = orig_bio->bi_size;
5904                         ret = btrfs_map_block(map_tree, READ, start_sector << 9,
5905                                               &map_length, NULL, 0);
5906                         if (ret) {
5907                                 bio_put(bio);
5908                                 goto out_err;
5909                         }
5910                 } else {
5911                         submit_len += bvec->bv_len;
5912                         nr_pages ++;
5913                         bvec++;
5914                 }
5915         }
5916
5917 submit:
5918         ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
5919                                      csums, async_submit);
5920         if (!ret)
5921                 return 0;
5922
5923         bio_put(bio);
5924 out_err:
5925         dip->errors = 1;
5926         /*
5927          * before atomic variable goto zero, we must
5928          * make sure dip->errors is perceived to be set.
5929          */
5930         smp_mb__before_atomic_dec();
5931         if (atomic_dec_and_test(&dip->pending_bios))
5932                 bio_io_error(dip->orig_bio);
5933
5934         /* bio_end_io() will handle error, so we needn't return it */
5935         return 0;
5936 }
5937
5938 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
5939                                 loff_t file_offset)
5940 {
5941         struct btrfs_root *root = BTRFS_I(inode)->root;
5942         struct btrfs_dio_private *dip;
5943         struct bio_vec *bvec = bio->bi_io_vec;
5944         int skip_sum;
5945         int write = rw & REQ_WRITE;
5946         int ret = 0;
5947
5948         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
5949
5950         dip = kmalloc(sizeof(*dip), GFP_NOFS);
5951         if (!dip) {
5952                 ret = -ENOMEM;
5953                 goto free_ordered;
5954         }
5955         dip->csums = NULL;
5956
5957         /* Write's use the ordered csum stuff, so we don't need dip->csums */
5958         if (!write && !skip_sum) {
5959                 dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
5960                 if (!dip->csums) {
5961                         kfree(dip);
5962                         ret = -ENOMEM;
5963                         goto free_ordered;
5964                 }
5965         }
5966
5967         dip->private = bio->bi_private;
5968         dip->inode = inode;
5969         dip->logical_offset = file_offset;
5970
5971         dip->bytes = 0;
5972         do {
5973                 dip->bytes += bvec->bv_len;
5974                 bvec++;
5975         } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
5976
5977         dip->disk_bytenr = (u64)bio->bi_sector << 9;
5978         bio->bi_private = dip;
5979         dip->errors = 0;
5980         dip->orig_bio = bio;
5981         atomic_set(&dip->pending_bios, 0);
5982
5983         if (write)
5984                 bio->bi_end_io = btrfs_endio_direct_write;
5985         else
5986                 bio->bi_end_io = btrfs_endio_direct_read;
5987
5988         ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
5989         if (!ret)
5990                 return;
5991 free_ordered:
5992         /*
5993          * If this is a write, we need to clean up the reserved space and kill
5994          * the ordered extent.
5995          */
5996         if (write) {
5997                 struct btrfs_ordered_extent *ordered;
5998                 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
5999                 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6000                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6001                         btrfs_free_reserved_extent(root, ordered->start,
6002                                                    ordered->disk_len);
6003                 btrfs_put_ordered_extent(ordered);
6004                 btrfs_put_ordered_extent(ordered);
6005         }
6006         bio_endio(bio, ret);
6007 }
6008
6009 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6010                         const struct iovec *iov, loff_t offset,
6011                         unsigned long nr_segs)
6012 {
6013         int seg;
6014         int i;
6015         size_t size;
6016         unsigned long addr;
6017         unsigned blocksize_mask = root->sectorsize - 1;
6018         ssize_t retval = -EINVAL;
6019         loff_t end = offset;
6020
6021         if (offset & blocksize_mask)
6022                 goto out;
6023
6024         /* Check the memory alignment.  Blocks cannot straddle pages */
6025         for (seg = 0; seg < nr_segs; seg++) {
6026                 addr = (unsigned long)iov[seg].iov_base;
6027                 size = iov[seg].iov_len;
6028                 end += size;
6029                 if ((addr & blocksize_mask) || (size & blocksize_mask))
6030                         goto out;
6031
6032                 /* If this is a write we don't need to check anymore */
6033                 if (rw & WRITE)
6034                         continue;
6035
6036                 /*
6037                  * Check to make sure we don't have duplicate iov_base's in this
6038                  * iovec, if so return EINVAL, otherwise we'll get csum errors
6039                  * when reading back.
6040                  */
6041                 for (i = seg + 1; i < nr_segs; i++) {
6042                         if (iov[seg].iov_base == iov[i].iov_base)
6043                                 goto out;
6044                 }
6045         }
6046         retval = 0;
6047 out:
6048         return retval;
6049 }
6050 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6051                         const struct iovec *iov, loff_t offset,
6052                         unsigned long nr_segs)
6053 {
6054         struct file *file = iocb->ki_filp;
6055         struct inode *inode = file->f_mapping->host;
6056         struct btrfs_ordered_extent *ordered;
6057         struct extent_state *cached_state = NULL;
6058         u64 lockstart, lockend;
6059         ssize_t ret;
6060         int writing = rw & WRITE;
6061         int write_bits = 0;
6062         size_t count = iov_length(iov, nr_segs);
6063
6064         if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6065                             offset, nr_segs)) {
6066                 return 0;
6067         }
6068
6069         lockstart = offset;
6070         lockend = offset + count - 1;
6071
6072         if (writing) {
6073                 ret = btrfs_delalloc_reserve_space(inode, count);
6074                 if (ret)
6075                         goto out;
6076         }
6077
6078         while (1) {
6079                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6080                                  0, &cached_state, GFP_NOFS);
6081                 /*
6082                  * We're concerned with the entire range that we're going to be
6083                  * doing DIO to, so we need to make sure theres no ordered
6084                  * extents in this range.
6085                  */
6086                 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6087                                                      lockend - lockstart + 1);
6088                 if (!ordered)
6089                         break;
6090                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6091                                      &cached_state, GFP_NOFS);
6092                 btrfs_start_ordered_extent(inode, ordered, 1);
6093                 btrfs_put_ordered_extent(ordered);
6094                 cond_resched();
6095         }
6096
6097         /*
6098          * we don't use btrfs_set_extent_delalloc because we don't want
6099          * the dirty or uptodate bits
6100          */
6101         if (writing) {
6102                 write_bits = EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING;
6103                 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6104                                      EXTENT_DELALLOC, 0, NULL, &cached_state,
6105                                      GFP_NOFS);
6106                 if (ret) {
6107                         clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6108                                          lockend, EXTENT_LOCKED | write_bits,
6109                                          1, 0, &cached_state, GFP_NOFS);
6110                         goto out;
6111                 }
6112         }
6113
6114         free_extent_state(cached_state);
6115         cached_state = NULL;
6116
6117         ret = __blockdev_direct_IO(rw, iocb, inode,
6118                    BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6119                    iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6120                    btrfs_submit_direct, 0);
6121
6122         if (ret < 0 && ret != -EIOCBQUEUED) {
6123                 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset,
6124                               offset + iov_length(iov, nr_segs) - 1,
6125                               EXTENT_LOCKED | write_bits, 1, 0,
6126                               &cached_state, GFP_NOFS);
6127         } else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
6128                 /*
6129                  * We're falling back to buffered, unlock the section we didn't
6130                  * do IO on.
6131                  */
6132                 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset + ret,
6133                               offset + iov_length(iov, nr_segs) - 1,
6134                               EXTENT_LOCKED | write_bits, 1, 0,
6135                               &cached_state, GFP_NOFS);
6136         }
6137 out:
6138         free_extent_state(cached_state);
6139         return ret;
6140 }
6141
6142 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6143                 __u64 start, __u64 len)
6144 {
6145         return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
6146 }
6147
6148 int btrfs_readpage(struct file *file, struct page *page)
6149 {
6150         struct extent_io_tree *tree;
6151         tree = &BTRFS_I(page->mapping->host)->io_tree;
6152         return extent_read_full_page(tree, page, btrfs_get_extent, 0);
6153 }
6154
6155 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
6156 {
6157         struct extent_io_tree *tree;
6158
6159
6160         if (current->flags & PF_MEMALLOC) {
6161                 redirty_page_for_writepage(wbc, page);
6162                 unlock_page(page);
6163                 return 0;
6164         }
6165         tree = &BTRFS_I(page->mapping->host)->io_tree;
6166         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
6167 }
6168
6169 int btrfs_writepages(struct address_space *mapping,
6170                      struct writeback_control *wbc)
6171 {
6172         struct extent_io_tree *tree;
6173
6174         tree = &BTRFS_I(mapping->host)->io_tree;
6175         return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6176 }
6177
6178 static int
6179 btrfs_readpages(struct file *file, struct address_space *mapping,
6180                 struct list_head *pages, unsigned nr_pages)
6181 {
6182         struct extent_io_tree *tree;
6183         tree = &BTRFS_I(mapping->host)->io_tree;
6184         return extent_readpages(tree, mapping, pages, nr_pages,
6185                                 btrfs_get_extent);
6186 }
6187 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6188 {
6189         struct extent_io_tree *tree;
6190         struct extent_map_tree *map;
6191         int ret;
6192
6193         tree = &BTRFS_I(page->mapping->host)->io_tree;
6194         map = &BTRFS_I(page->mapping->host)->extent_tree;
6195         ret = try_release_extent_mapping(map, tree, page, gfp_flags);
6196         if (ret == 1) {
6197                 ClearPagePrivate(page);
6198                 set_page_private(page, 0);
6199                 page_cache_release(page);
6200         }
6201         return ret;
6202 }
6203
6204 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6205 {
6206         if (PageWriteback(page) || PageDirty(page))
6207                 return 0;
6208         return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
6209 }
6210
6211 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
6212 {
6213         struct extent_io_tree *tree;
6214         struct btrfs_ordered_extent *ordered;
6215         struct extent_state *cached_state = NULL;
6216         u64 page_start = page_offset(page);
6217         u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
6218
6219
6220         /*
6221          * we have the page locked, so new writeback can't start,
6222          * and the dirty bit won't be cleared while we are here.
6223          *
6224          * Wait for IO on this page so that we can safely clear
6225          * the PagePrivate2 bit and do ordered accounting
6226          */
6227         wait_on_page_writeback(page);
6228
6229         tree = &BTRFS_I(page->mapping->host)->io_tree;
6230         if (offset) {
6231                 btrfs_releasepage(page, GFP_NOFS);
6232                 return;
6233         }
6234         lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6235                          GFP_NOFS);
6236         ordered = btrfs_lookup_ordered_extent(page->mapping->host,
6237                                            page_offset(page));
6238         if (ordered) {
6239                 /*
6240                  * IO on this page will never be started, so we need
6241                  * to account for any ordered extents now
6242                  */
6243                 clear_extent_bit(tree, page_start, page_end,
6244                                  EXTENT_DIRTY | EXTENT_DELALLOC |
6245                                  EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
6246                                  &cached_state, GFP_NOFS);
6247                 /*
6248                  * whoever cleared the private bit is responsible
6249                  * for the finish_ordered_io
6250                  */
6251                 if (TestClearPagePrivate2(page)) {
6252                         btrfs_finish_ordered_io(page->mapping->host,
6253                                                 page_start, page_end);
6254                 }
6255                 btrfs_put_ordered_extent(ordered);
6256                 cached_state = NULL;
6257                 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6258                                  GFP_NOFS);
6259         }
6260         clear_extent_bit(tree, page_start, page_end,
6261                  EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
6262                  EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
6263         __btrfs_releasepage(page, GFP_NOFS);
6264
6265         ClearPageChecked(page);
6266         if (PagePrivate(page)) {
6267                 ClearPagePrivate(page);
6268                 set_page_private(page, 0);
6269                 page_cache_release(page);
6270         }
6271 }
6272
6273 /*
6274  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6275  * called from a page fault handler when a page is first dirtied. Hence we must
6276  * be careful to check for EOF conditions here. We set the page up correctly
6277  * for a written page which means we get ENOSPC checking when writing into
6278  * holes and correct delalloc and unwritten extent mapping on filesystems that
6279  * support these features.
6280  *
6281  * We are not allowed to take the i_mutex here so we have to play games to
6282  * protect against truncate races as the page could now be beyond EOF.  Because
6283  * vmtruncate() writes the inode size before removing pages, once we have the
6284  * page lock we can determine safely if the page is beyond EOF. If it is not
6285  * beyond EOF, then the page is guaranteed safe against truncation until we
6286  * unlock the page.
6287  */
6288 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6289 {
6290         struct page *page = vmf->page;
6291         struct inode *inode = fdentry(vma->vm_file)->d_inode;
6292         struct btrfs_root *root = BTRFS_I(inode)->root;
6293         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6294         struct btrfs_ordered_extent *ordered;
6295         struct extent_state *cached_state = NULL;
6296         char *kaddr;
6297         unsigned long zero_start;
6298         loff_t size;
6299         int ret;
6300         u64 page_start;
6301         u64 page_end;
6302
6303         ret  = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6304         if (ret) {
6305                 if (ret == -ENOMEM)
6306                         ret = VM_FAULT_OOM;
6307                 else /* -ENOSPC, -EIO, etc */
6308                         ret = VM_FAULT_SIGBUS;
6309                 goto out;
6310         }
6311
6312         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6313 again:
6314         lock_page(page);
6315         size = i_size_read(inode);
6316         page_start = page_offset(page);
6317         page_end = page_start + PAGE_CACHE_SIZE - 1;
6318
6319         if ((page->mapping != inode->i_mapping) ||
6320             (page_start >= size)) {
6321                 /* page got truncated out from underneath us */
6322                 goto out_unlock;
6323         }
6324         wait_on_page_writeback(page);
6325
6326         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
6327                          GFP_NOFS);
6328         set_page_extent_mapped(page);
6329
6330         /*
6331          * we can't set the delalloc bits if there are pending ordered
6332          * extents.  Drop our locks and wait for them to finish
6333          */
6334         ordered = btrfs_lookup_ordered_extent(inode, page_start);
6335         if (ordered) {
6336                 unlock_extent_cached(io_tree, page_start, page_end,
6337                                      &cached_state, GFP_NOFS);
6338                 unlock_page(page);
6339                 btrfs_start_ordered_extent(inode, ordered, 1);
6340                 btrfs_put_ordered_extent(ordered);
6341                 goto again;
6342         }
6343
6344         /*
6345          * XXX - page_mkwrite gets called every time the page is dirtied, even
6346          * if it was already dirty, so for space accounting reasons we need to
6347          * clear any delalloc bits for the range we are fixing to save.  There
6348          * is probably a better way to do this, but for now keep consistent with
6349          * prepare_pages in the normal write path.
6350          */
6351         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6352                           EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
6353                           0, 0, &cached_state, GFP_NOFS);
6354
6355         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6356                                         &cached_state);
6357         if (ret) {
6358                 unlock_extent_cached(io_tree, page_start, page_end,
6359                                      &cached_state, GFP_NOFS);
6360                 ret = VM_FAULT_SIGBUS;
6361                 goto out_unlock;
6362         }
6363         ret = 0;
6364
6365         /* page is wholly or partially inside EOF */
6366         if (page_start + PAGE_CACHE_SIZE > size)
6367                 zero_start = size & ~PAGE_CACHE_MASK;
6368         else
6369                 zero_start = PAGE_CACHE_SIZE;
6370
6371         if (zero_start != PAGE_CACHE_SIZE) {
6372                 kaddr = kmap(page);
6373                 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6374                 flush_dcache_page(page);
6375                 kunmap(page);
6376         }
6377         ClearPageChecked(page);
6378         set_page_dirty(page);
6379         SetPageUptodate(page);
6380
6381         BTRFS_I(inode)->last_trans = root->fs_info->generation;
6382         BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6383
6384         unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6385
6386 out_unlock:
6387         if (!ret)
6388                 return VM_FAULT_LOCKED;
6389         unlock_page(page);
6390         btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6391 out:
6392         return ret;
6393 }
6394
6395 static int btrfs_truncate(struct inode *inode)
6396 {
6397         struct btrfs_root *root = BTRFS_I(inode)->root;
6398         struct btrfs_block_rsv *rsv;
6399         int ret;
6400         int err = 0;
6401         struct btrfs_trans_handle *trans;
6402         unsigned long nr;
6403         u64 mask = root->sectorsize - 1;
6404         u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
6405
6406         ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
6407         if (ret)
6408                 return ret;
6409
6410         btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6411         btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6412
6413         /*
6414          * Yes ladies and gentelment, this is indeed ugly.  The fact is we have
6415          * 3 things going on here
6416          *
6417          * 1) We need to reserve space for our orphan item and the space to
6418          * delete our orphan item.  Lord knows we don't want to have a dangling
6419          * orphan item because we didn't reserve space to remove it.
6420          *
6421          * 2) We need to reserve space to update our inode.
6422          *
6423          * 3) We need to have something to cache all the space that is going to
6424          * be free'd up by the truncate operation, but also have some slack
6425          * space reserved in case it uses space during the truncate (thank you
6426          * very much snapshotting).
6427          *
6428          * And we need these to all be seperate.  The fact is we can use alot of
6429          * space doing the truncate, and we have no earthly idea how much space
6430          * we will use, so we need the truncate reservation to be seperate so it
6431          * doesn't end up using space reserved for updating the inode or
6432          * removing the orphan item.  We also need to be able to stop the
6433          * transaction and start a new one, which means we need to be able to
6434          * update the inode several times, and we have no idea of knowing how
6435          * many times that will be, so we can't just reserve 1 item for the
6436          * entirety of the opration, so that has to be done seperately as well.
6437          * Then there is the orphan item, which does indeed need to be held on
6438          * to for the whole operation, and we need nobody to touch this reserved
6439          * space except the orphan code.
6440          *
6441          * So that leaves us with
6442          *
6443          * 1) root->orphan_block_rsv - for the orphan deletion.
6444          * 2) rsv - for the truncate reservation, which we will steal from the
6445          * transaction reservation.
6446          * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
6447          * updating the inode.
6448          */
6449         rsv = btrfs_alloc_block_rsv(root);
6450         if (!rsv)
6451                 return -ENOMEM;
6452         rsv->size = min_size;
6453
6454         /*
6455          * 1 for the truncate slack space
6456          * 1 for the orphan item we're going to add
6457          * 1 for the orphan item deletion
6458          * 1 for updating the inode.
6459          */
6460         trans = btrfs_start_transaction(root, 4);
6461         if (IS_ERR(trans)) {
6462                 err = PTR_ERR(trans);
6463                 goto out;
6464         }
6465
6466         /* Migrate the slack space for the truncate to our reserve */
6467         ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
6468                                       min_size);
6469         BUG_ON(ret);
6470
6471         ret = btrfs_orphan_add(trans, inode);
6472         if (ret) {
6473                 btrfs_end_transaction(trans, root);
6474                 goto out;
6475         }
6476
6477         /*
6478          * setattr is responsible for setting the ordered_data_close flag,
6479          * but that is only tested during the last file release.  That
6480          * could happen well after the next commit, leaving a great big
6481          * window where new writes may get lost if someone chooses to write
6482          * to this file after truncating to zero
6483          *
6484          * The inode doesn't have any dirty data here, and so if we commit
6485          * this is a noop.  If someone immediately starts writing to the inode
6486          * it is very likely we'll catch some of their writes in this
6487          * transaction, and the commit will find this file on the ordered
6488          * data list with good things to send down.
6489          *
6490          * This is a best effort solution, there is still a window where
6491          * using truncate to replace the contents of the file will
6492          * end up with a zero length file after a crash.
6493          */
6494         if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
6495                 btrfs_add_ordered_operation(trans, root, inode);
6496
6497         while (1) {
6498                 ret = btrfs_block_rsv_refill(root, rsv, min_size);
6499                 if (ret) {
6500                         /*
6501                          * This can only happen with the original transaction we
6502                          * started above, every other time we shouldn't have a
6503                          * transaction started yet.
6504                          */
6505                         if (ret == -EAGAIN)
6506                                 goto end_trans;
6507                         err = ret;
6508                         break;
6509                 }
6510
6511                 if (!trans) {
6512                         /* Just need the 1 for updating the inode */
6513                         trans = btrfs_start_transaction(root, 1);
6514                         if (IS_ERR(trans)) {
6515                                 err = PTR_ERR(trans);
6516                                 goto out;
6517                         }
6518                 }
6519
6520                 trans->block_rsv = rsv;
6521
6522                 ret = btrfs_truncate_inode_items(trans, root, inode,
6523                                                  inode->i_size,
6524                                                  BTRFS_EXTENT_DATA_KEY);
6525                 if (ret != -EAGAIN) {
6526                         err = ret;
6527                         break;
6528                 }
6529
6530                 trans->block_rsv = &root->fs_info->trans_block_rsv;
6531                 ret = btrfs_update_inode(trans, root, inode);
6532                 if (ret) {
6533                         err = ret;
6534                         break;
6535                 }
6536 end_trans:
6537                 nr = trans->blocks_used;
6538                 btrfs_end_transaction(trans, root);
6539                 trans = NULL;
6540                 btrfs_btree_balance_dirty(root, nr);
6541         }
6542
6543         if (ret == 0 && inode->i_nlink > 0) {
6544                 trans->block_rsv = root->orphan_block_rsv;
6545                 ret = btrfs_orphan_del(trans, inode);
6546                 if (ret)
6547                         err = ret;
6548         } else if (ret && inode->i_nlink > 0) {
6549                 /*
6550                  * Failed to do the truncate, remove us from the in memory
6551                  * orphan list.
6552                  */
6553                 ret = btrfs_orphan_del(NULL, inode);
6554         }
6555
6556         if (trans) {
6557                 trans->block_rsv = &root->fs_info->trans_block_rsv;
6558                 ret = btrfs_update_inode(trans, root, inode);
6559                 if (ret && !err)
6560                         err = ret;
6561
6562                 nr = trans->blocks_used;
6563                 ret = btrfs_end_transaction_throttle(trans, root);
6564                 btrfs_btree_balance_dirty(root, nr);
6565         }
6566
6567 out:
6568         btrfs_free_block_rsv(root, rsv);
6569
6570         if (ret && !err)
6571                 err = ret;
6572
6573         return err;
6574 }
6575
6576 /*
6577  * create a new subvolume directory/inode (helper for the ioctl).
6578  */
6579 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
6580                              struct btrfs_root *new_root, u64 new_dirid)
6581 {
6582         struct inode *inode;
6583         int err;
6584         u64 index = 0;
6585
6586         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
6587                                 new_dirid, S_IFDIR | 0700, &index);
6588         if (IS_ERR(inode))
6589                 return PTR_ERR(inode);
6590         inode->i_op = &btrfs_dir_inode_operations;
6591         inode->i_fop = &btrfs_dir_file_operations;
6592
6593         inode->i_nlink = 1;
6594         btrfs_i_size_write(inode, 0);
6595
6596         err = btrfs_update_inode(trans, new_root, inode);
6597         BUG_ON(err);
6598
6599         iput(inode);
6600         return 0;
6601 }
6602
6603 struct inode *btrfs_alloc_inode(struct super_block *sb)
6604 {
6605         struct btrfs_inode *ei;
6606         struct inode *inode;
6607
6608         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
6609         if (!ei)
6610                 return NULL;
6611
6612         ei->root = NULL;
6613         ei->space_info = NULL;
6614         ei->generation = 0;
6615         ei->sequence = 0;
6616         ei->last_trans = 0;
6617         ei->last_sub_trans = 0;
6618         ei->logged_trans = 0;
6619         ei->delalloc_bytes = 0;
6620         ei->disk_i_size = 0;
6621         ei->flags = 0;
6622         ei->csum_bytes = 0;
6623         ei->index_cnt = (u64)-1;
6624         ei->last_unlink_trans = 0;
6625
6626         spin_lock_init(&ei->lock);
6627         ei->outstanding_extents = 0;
6628         ei->reserved_extents = 0;
6629
6630         ei->ordered_data_close = 0;
6631         ei->orphan_meta_reserved = 0;
6632         ei->dummy_inode = 0;
6633         ei->in_defrag = 0;
6634         ei->delalloc_meta_reserved = 0;
6635         ei->force_compress = BTRFS_COMPRESS_NONE;
6636
6637         ei->delayed_node = NULL;
6638
6639         inode = &ei->vfs_inode;
6640         extent_map_tree_init(&ei->extent_tree);
6641         extent_io_tree_init(&ei->io_tree, &inode->i_data);
6642         extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
6643         mutex_init(&ei->log_mutex);
6644         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
6645         INIT_LIST_HEAD(&ei->i_orphan);
6646         INIT_LIST_HEAD(&ei->delalloc_inodes);
6647         INIT_LIST_HEAD(&ei->ordered_operations);
6648         RB_CLEAR_NODE(&ei->rb_node);
6649
6650         return inode;
6651 }
6652
6653 static void btrfs_i_callback(struct rcu_head *head)
6654 {
6655         struct inode *inode = container_of(head, struct inode, i_rcu);
6656         INIT_LIST_HEAD(&inode->i_dentry);
6657         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
6658 }
6659
6660 void btrfs_destroy_inode(struct inode *inode)
6661 {
6662         struct btrfs_ordered_extent *ordered;
6663         struct btrfs_root *root = BTRFS_I(inode)->root;
6664
6665         WARN_ON(!list_empty(&inode->i_dentry));
6666         WARN_ON(inode->i_data.nrpages);
6667         WARN_ON(BTRFS_I(inode)->outstanding_extents);
6668         WARN_ON(BTRFS_I(inode)->reserved_extents);
6669         WARN_ON(BTRFS_I(inode)->delalloc_bytes);
6670         WARN_ON(BTRFS_I(inode)->csum_bytes);
6671
6672         /*
6673          * This can happen where we create an inode, but somebody else also
6674          * created the same inode and we need to destroy the one we already
6675          * created.
6676          */
6677         if (!root)
6678                 goto free;
6679
6680         /*
6681          * Make sure we're properly removed from the ordered operation
6682          * lists.
6683          */
6684         smp_mb();
6685         if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
6686                 spin_lock(&root->fs_info->ordered_extent_lock);
6687                 list_del_init(&BTRFS_I(inode)->ordered_operations);
6688                 spin_unlock(&root->fs_info->ordered_extent_lock);
6689         }
6690
6691         spin_lock(&root->orphan_lock);
6692         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
6693                 printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
6694                        (unsigned long long)btrfs_ino(inode));
6695                 list_del_init(&BTRFS_I(inode)->i_orphan);
6696         }
6697         spin_unlock(&root->orphan_lock);
6698
6699         while (1) {
6700                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
6701                 if (!ordered)
6702                         break;
6703                 else {
6704                         printk(KERN_ERR "btrfs found ordered "
6705                                "extent %llu %llu on inode cleanup\n",
6706                                (unsigned long long)ordered->file_offset,
6707                                (unsigned long long)ordered->len);
6708                         btrfs_remove_ordered_extent(inode, ordered);
6709                         btrfs_put_ordered_extent(ordered);
6710                         btrfs_put_ordered_extent(ordered);
6711                 }
6712         }
6713         inode_tree_del(inode);
6714         btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
6715 free:
6716         btrfs_remove_delayed_node(inode);
6717         call_rcu(&inode->i_rcu, btrfs_i_callback);
6718 }
6719
6720 int btrfs_drop_inode(struct inode *inode)
6721 {
6722         struct btrfs_root *root = BTRFS_I(inode)->root;
6723
6724         if (btrfs_root_refs(&root->root_item) == 0 &&
6725             !btrfs_is_free_space_inode(root, inode))
6726                 return 1;
6727         else
6728                 return generic_drop_inode(inode);
6729 }
6730
6731 static void init_once(void *foo)
6732 {
6733         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
6734
6735         inode_init_once(&ei->vfs_inode);
6736 }
6737
6738 void btrfs_destroy_cachep(void)
6739 {
6740         if (btrfs_inode_cachep)
6741                 kmem_cache_destroy(btrfs_inode_cachep);
6742         if (btrfs_trans_handle_cachep)
6743                 kmem_cache_destroy(btrfs_trans_handle_cachep);
6744         if (btrfs_transaction_cachep)
6745                 kmem_cache_destroy(btrfs_transaction_cachep);
6746         if (btrfs_path_cachep)
6747                 kmem_cache_destroy(btrfs_path_cachep);
6748         if (btrfs_free_space_cachep)
6749                 kmem_cache_destroy(btrfs_free_space_cachep);
6750 }
6751
6752 int btrfs_init_cachep(void)
6753 {
6754         btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
6755                         sizeof(struct btrfs_inode), 0,
6756                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
6757         if (!btrfs_inode_cachep)
6758                 goto fail;
6759
6760         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
6761                         sizeof(struct btrfs_trans_handle), 0,
6762                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6763         if (!btrfs_trans_handle_cachep)
6764                 goto fail;
6765
6766         btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
6767                         sizeof(struct btrfs_transaction), 0,
6768                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6769         if (!btrfs_transaction_cachep)
6770                 goto fail;
6771
6772         btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
6773                         sizeof(struct btrfs_path), 0,
6774                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6775         if (!btrfs_path_cachep)
6776                 goto fail;
6777
6778         btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space_cache",
6779                         sizeof(struct btrfs_free_space), 0,
6780                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6781         if (!btrfs_free_space_cachep)
6782                 goto fail;
6783
6784         return 0;
6785 fail:
6786         btrfs_destroy_cachep();
6787         return -ENOMEM;
6788 }
6789
6790 static int btrfs_getattr(struct vfsmount *mnt,
6791                          struct dentry *dentry, struct kstat *stat)
6792 {
6793         struct inode *inode = dentry->d_inode;
6794         generic_fillattr(inode, stat);
6795         stat->dev = BTRFS_I(inode)->root->anon_dev;
6796         stat->blksize = PAGE_CACHE_SIZE;
6797         stat->blocks = (inode_get_bytes(inode) +
6798                         BTRFS_I(inode)->delalloc_bytes) >> 9;
6799         return 0;
6800 }
6801
6802 /*
6803  * If a file is moved, it will inherit the cow and compression flags of the new
6804  * directory.
6805  */
6806 static void fixup_inode_flags(struct inode *dir, struct inode *inode)
6807 {
6808         struct btrfs_inode *b_dir = BTRFS_I(dir);
6809         struct btrfs_inode *b_inode = BTRFS_I(inode);
6810
6811         if (b_dir->flags & BTRFS_INODE_NODATACOW)
6812                 b_inode->flags |= BTRFS_INODE_NODATACOW;
6813         else
6814                 b_inode->flags &= ~BTRFS_INODE_NODATACOW;
6815
6816         if (b_dir->flags & BTRFS_INODE_COMPRESS)
6817                 b_inode->flags |= BTRFS_INODE_COMPRESS;
6818         else
6819                 b_inode->flags &= ~BTRFS_INODE_COMPRESS;
6820 }
6821
6822 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
6823                            struct inode *new_dir, struct dentry *new_dentry)
6824 {
6825         struct btrfs_trans_handle *trans;
6826         struct btrfs_root *root = BTRFS_I(old_dir)->root;
6827         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
6828         struct inode *new_inode = new_dentry->d_inode;
6829         struct inode *old_inode = old_dentry->d_inode;
6830         struct timespec ctime = CURRENT_TIME;
6831         u64 index = 0;
6832         u64 root_objectid;
6833         int ret;
6834         u64 old_ino = btrfs_ino(old_inode);
6835
6836         if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6837                 return -EPERM;
6838
6839         /* we only allow rename subvolume link between subvolumes */
6840         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
6841                 return -EXDEV;
6842
6843         if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
6844             (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
6845                 return -ENOTEMPTY;
6846
6847         if (S_ISDIR(old_inode->i_mode) && new_inode &&
6848             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
6849                 return -ENOTEMPTY;
6850         /*
6851          * we're using rename to replace one file with another.
6852          * and the replacement file is large.  Start IO on it now so
6853          * we don't add too much work to the end of the transaction
6854          */
6855         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
6856             old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
6857                 filemap_flush(old_inode->i_mapping);
6858
6859         /* close the racy window with snapshot create/destroy ioctl */
6860         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
6861                 down_read(&root->fs_info->subvol_sem);
6862         /*
6863          * We want to reserve the absolute worst case amount of items.  So if
6864          * both inodes are subvols and we need to unlink them then that would
6865          * require 4 item modifications, but if they are both normal inodes it
6866          * would require 5 item modifications, so we'll assume their normal
6867          * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
6868          * should cover the worst case number of items we'll modify.
6869          */
6870         trans = btrfs_start_transaction(root, 20);
6871         if (IS_ERR(trans)) {
6872                 ret = PTR_ERR(trans);
6873                 goto out_notrans;
6874         }
6875
6876         if (dest != root)
6877                 btrfs_record_root_in_trans(trans, dest);
6878
6879         ret = btrfs_set_inode_index(new_dir, &index);
6880         if (ret)
6881                 goto out_fail;
6882
6883         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6884                 /* force full log commit if subvolume involved. */
6885                 root->fs_info->last_trans_log_full_commit = trans->transid;
6886         } else {
6887                 ret = btrfs_insert_inode_ref(trans, dest,
6888                                              new_dentry->d_name.name,
6889                                              new_dentry->d_name.len,
6890                                              old_ino,
6891                                              btrfs_ino(new_dir), index);
6892                 if (ret)
6893                         goto out_fail;
6894                 /*
6895                  * this is an ugly little race, but the rename is required
6896                  * to make sure that if we crash, the inode is either at the
6897                  * old name or the new one.  pinning the log transaction lets
6898                  * us make sure we don't allow a log commit to come in after
6899                  * we unlink the name but before we add the new name back in.
6900                  */
6901                 btrfs_pin_log_trans(root);
6902         }
6903         /*
6904          * make sure the inode gets flushed if it is replacing
6905          * something.
6906          */
6907         if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
6908                 btrfs_add_ordered_operation(trans, root, old_inode);
6909
6910         old_dir->i_ctime = old_dir->i_mtime = ctime;
6911         new_dir->i_ctime = new_dir->i_mtime = ctime;
6912         old_inode->i_ctime = ctime;
6913
6914         if (old_dentry->d_parent != new_dentry->d_parent)
6915                 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
6916
6917         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6918                 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
6919                 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
6920                                         old_dentry->d_name.name,
6921                                         old_dentry->d_name.len);
6922         } else {
6923                 ret = __btrfs_unlink_inode(trans, root, old_dir,
6924                                         old_dentry->d_inode,
6925                                         old_dentry->d_name.name,
6926                                         old_dentry->d_name.len);
6927                 if (!ret)
6928                         ret = btrfs_update_inode(trans, root, old_inode);
6929         }
6930         BUG_ON(ret);
6931
6932         if (new_inode) {
6933                 new_inode->i_ctime = CURRENT_TIME;
6934                 if (unlikely(btrfs_ino(new_inode) ==
6935                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
6936                         root_objectid = BTRFS_I(new_inode)->location.objectid;
6937                         ret = btrfs_unlink_subvol(trans, dest, new_dir,
6938                                                 root_objectid,
6939                                                 new_dentry->d_name.name,
6940                                                 new_dentry->d_name.len);
6941                         BUG_ON(new_inode->i_nlink == 0);
6942                 } else {
6943                         ret = btrfs_unlink_inode(trans, dest, new_dir,
6944                                                  new_dentry->d_inode,
6945                                                  new_dentry->d_name.name,
6946                                                  new_dentry->d_name.len);
6947                 }
6948                 BUG_ON(ret);
6949                 if (new_inode->i_nlink == 0) {
6950                         ret = btrfs_orphan_add(trans, new_dentry->d_inode);
6951                         BUG_ON(ret);
6952                 }
6953         }
6954
6955         fixup_inode_flags(new_dir, old_inode);
6956
6957         ret = btrfs_add_link(trans, new_dir, old_inode,
6958                              new_dentry->d_name.name,
6959                              new_dentry->d_name.len, 0, index);
6960         BUG_ON(ret);
6961
6962         if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
6963                 struct dentry *parent = new_dentry->d_parent;
6964                 btrfs_log_new_name(trans, old_inode, old_dir, parent);
6965                 btrfs_end_log_trans(root);
6966         }
6967 out_fail:
6968         btrfs_end_transaction_throttle(trans, root);
6969 out_notrans:
6970         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
6971                 up_read(&root->fs_info->subvol_sem);
6972
6973         return ret;
6974 }
6975
6976 /*
6977  * some fairly slow code that needs optimization. This walks the list
6978  * of all the inodes with pending delalloc and forces them to disk.
6979  */
6980 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
6981 {
6982         struct list_head *head = &root->fs_info->delalloc_inodes;
6983         struct btrfs_inode *binode;
6984         struct inode *inode;
6985
6986         if (root->fs_info->sb->s_flags & MS_RDONLY)
6987                 return -EROFS;
6988
6989         spin_lock(&root->fs_info->delalloc_lock);
6990         while (!list_empty(head)) {
6991                 binode = list_entry(head->next, struct btrfs_inode,
6992                                     delalloc_inodes);
6993                 inode = igrab(&binode->vfs_inode);
6994                 if (!inode)
6995                         list_del_init(&binode->delalloc_inodes);
6996                 spin_unlock(&root->fs_info->delalloc_lock);
6997                 if (inode) {
6998                         filemap_flush(inode->i_mapping);
6999                         if (delay_iput)
7000                                 btrfs_add_delayed_iput(inode);
7001                         else
7002                                 iput(inode);
7003                 }
7004                 cond_resched();
7005                 spin_lock(&root->fs_info->delalloc_lock);
7006         }
7007         spin_unlock(&root->fs_info->delalloc_lock);
7008
7009         /* the filemap_flush will queue IO into the worker threads, but
7010          * we have to make sure the IO is actually started and that
7011          * ordered extents get created before we return
7012          */
7013         atomic_inc(&root->fs_info->async_submit_draining);
7014         while (atomic_read(&root->fs_info->nr_async_submits) ||
7015               atomic_read(&root->fs_info->async_delalloc_pages)) {
7016                 wait_event(root->fs_info->async_submit_wait,
7017                    (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7018                     atomic_read(&root->fs_info->async_delalloc_pages) == 0));
7019         }
7020         atomic_dec(&root->fs_info->async_submit_draining);
7021         return 0;
7022 }
7023
7024 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7025                          const char *symname)
7026 {
7027         struct btrfs_trans_handle *trans;
7028         struct btrfs_root *root = BTRFS_I(dir)->root;
7029         struct btrfs_path *path;
7030         struct btrfs_key key;
7031         struct inode *inode = NULL;
7032         int err;
7033         int drop_inode = 0;
7034         u64 objectid;
7035         u64 index = 0 ;
7036         int name_len;
7037         int datasize;
7038         unsigned long ptr;
7039         struct btrfs_file_extent_item *ei;
7040         struct extent_buffer *leaf;
7041         unsigned long nr = 0;
7042
7043         name_len = strlen(symname) + 1;
7044         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7045                 return -ENAMETOOLONG;
7046
7047         /*
7048          * 2 items for inode item and ref
7049          * 2 items for dir items
7050          * 1 item for xattr if selinux is on
7051          */
7052         trans = btrfs_start_transaction(root, 5);
7053         if (IS_ERR(trans))
7054                 return PTR_ERR(trans);
7055
7056         err = btrfs_find_free_ino(root, &objectid);
7057         if (err)
7058                 goto out_unlock;
7059
7060         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
7061                                 dentry->d_name.len, btrfs_ino(dir), objectid,
7062                                 S_IFLNK|S_IRWXUGO, &index);
7063         if (IS_ERR(inode)) {
7064                 err = PTR_ERR(inode);
7065                 goto out_unlock;
7066         }
7067
7068         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
7069         if (err) {
7070                 drop_inode = 1;
7071                 goto out_unlock;
7072         }
7073
7074         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
7075         if (err)
7076                 drop_inode = 1;
7077         else {
7078                 inode->i_mapping->a_ops = &btrfs_aops;
7079                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7080                 inode->i_fop = &btrfs_file_operations;
7081                 inode->i_op = &btrfs_file_inode_operations;
7082                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
7083         }
7084         if (drop_inode)
7085                 goto out_unlock;
7086
7087         path = btrfs_alloc_path();
7088         if (!path) {
7089                 err = -ENOMEM;
7090                 drop_inode = 1;
7091                 goto out_unlock;
7092         }
7093         key.objectid = btrfs_ino(inode);
7094         key.offset = 0;
7095         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7096         datasize = btrfs_file_extent_calc_inline_size(name_len);
7097         err = btrfs_insert_empty_item(trans, root, path, &key,
7098                                       datasize);
7099         if (err) {
7100                 drop_inode = 1;
7101                 btrfs_free_path(path);
7102                 goto out_unlock;
7103         }
7104         leaf = path->nodes[0];
7105         ei = btrfs_item_ptr(leaf, path->slots[0],
7106                             struct btrfs_file_extent_item);
7107         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7108         btrfs_set_file_extent_type(leaf, ei,
7109                                    BTRFS_FILE_EXTENT_INLINE);
7110         btrfs_set_file_extent_encryption(leaf, ei, 0);
7111         btrfs_set_file_extent_compression(leaf, ei, 0);
7112         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7113         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7114
7115         ptr = btrfs_file_extent_inline_start(ei);
7116         write_extent_buffer(leaf, symname, ptr, name_len);
7117         btrfs_mark_buffer_dirty(leaf);
7118         btrfs_free_path(path);
7119
7120         inode->i_op = &btrfs_symlink_inode_operations;
7121         inode->i_mapping->a_ops = &btrfs_symlink_aops;
7122         inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7123         inode_set_bytes(inode, name_len);
7124         btrfs_i_size_write(inode, name_len - 1);
7125         err = btrfs_update_inode(trans, root, inode);
7126         if (err)
7127                 drop_inode = 1;
7128
7129 out_unlock:
7130         nr = trans->blocks_used;
7131         btrfs_end_transaction_throttle(trans, root);
7132         if (drop_inode) {
7133                 inode_dec_link_count(inode);
7134                 iput(inode);
7135         }
7136         btrfs_btree_balance_dirty(root, nr);
7137         return err;
7138 }
7139
7140 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7141                                        u64 start, u64 num_bytes, u64 min_size,
7142                                        loff_t actual_len, u64 *alloc_hint,
7143                                        struct btrfs_trans_handle *trans)
7144 {
7145         struct btrfs_root *root = BTRFS_I(inode)->root;
7146         struct btrfs_key ins;
7147         u64 cur_offset = start;
7148         u64 i_size;
7149         int ret = 0;
7150         bool own_trans = true;
7151
7152         if (trans)
7153                 own_trans = false;
7154         while (num_bytes > 0) {
7155                 if (own_trans) {
7156                         trans = btrfs_start_transaction(root, 3);
7157                         if (IS_ERR(trans)) {
7158                                 ret = PTR_ERR(trans);
7159                                 break;
7160                         }
7161                 }
7162
7163                 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7164                                            0, *alloc_hint, (u64)-1, &ins, 1);
7165                 if (ret) {
7166                         if (own_trans)
7167                                 btrfs_end_transaction(trans, root);
7168                         break;
7169                 }
7170
7171                 ret = insert_reserved_file_extent(trans, inode,
7172                                                   cur_offset, ins.objectid,
7173                                                   ins.offset, ins.offset,
7174                                                   ins.offset, 0, 0, 0,
7175                                                   BTRFS_FILE_EXTENT_PREALLOC);
7176                 BUG_ON(ret);
7177                 btrfs_drop_extent_cache(inode, cur_offset,
7178                                         cur_offset + ins.offset -1, 0);
7179
7180                 num_bytes -= ins.offset;
7181                 cur_offset += ins.offset;
7182                 *alloc_hint = ins.objectid + ins.offset;
7183
7184                 inode->i_ctime = CURRENT_TIME;
7185                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
7186                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
7187                     (actual_len > inode->i_size) &&
7188                     (cur_offset > inode->i_size)) {
7189                         if (cur_offset > actual_len)
7190                                 i_size = actual_len;
7191                         else
7192                                 i_size = cur_offset;
7193                         i_size_write(inode, i_size);
7194                         btrfs_ordered_update_i_size(inode, i_size, NULL);
7195                 }
7196
7197                 ret = btrfs_update_inode(trans, root, inode);
7198                 BUG_ON(ret);
7199
7200                 if (own_trans)
7201                         btrfs_end_transaction(trans, root);
7202         }
7203         return ret;
7204 }
7205
7206 int btrfs_prealloc_file_range(struct inode *inode, int mode,
7207                               u64 start, u64 num_bytes, u64 min_size,
7208                               loff_t actual_len, u64 *alloc_hint)
7209 {
7210         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7211                                            min_size, actual_len, alloc_hint,
7212                                            NULL);
7213 }
7214
7215 int btrfs_prealloc_file_range_trans(struct inode *inode,
7216                                     struct btrfs_trans_handle *trans, int mode,
7217                                     u64 start, u64 num_bytes, u64 min_size,
7218                                     loff_t actual_len, u64 *alloc_hint)
7219 {
7220         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7221                                            min_size, actual_len, alloc_hint, trans);
7222 }
7223
7224 static int btrfs_set_page_dirty(struct page *page)
7225 {
7226         return __set_page_dirty_nobuffers(page);
7227 }
7228
7229 static int btrfs_permission(struct inode *inode, int mask)
7230 {
7231         struct btrfs_root *root = BTRFS_I(inode)->root;
7232         umode_t mode = inode->i_mode;
7233
7234         if (mask & MAY_WRITE &&
7235             (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
7236                 if (btrfs_root_readonly(root))
7237                         return -EROFS;
7238                 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
7239                         return -EACCES;
7240         }
7241         return generic_permission(inode, mask);
7242 }
7243
7244 static const struct inode_operations btrfs_dir_inode_operations = {
7245         .getattr        = btrfs_getattr,
7246         .lookup         = btrfs_lookup,
7247         .create         = btrfs_create,
7248         .unlink         = btrfs_unlink,
7249         .link           = btrfs_link,
7250         .mkdir          = btrfs_mkdir,
7251         .rmdir          = btrfs_rmdir,
7252         .rename         = btrfs_rename,
7253         .symlink        = btrfs_symlink,
7254         .setattr        = btrfs_setattr,
7255         .mknod          = btrfs_mknod,
7256         .setxattr       = btrfs_setxattr,
7257         .getxattr       = btrfs_getxattr,
7258         .listxattr      = btrfs_listxattr,
7259         .removexattr    = btrfs_removexattr,
7260         .permission     = btrfs_permission,
7261         .get_acl        = btrfs_get_acl,
7262 };
7263 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7264         .lookup         = btrfs_lookup,
7265         .permission     = btrfs_permission,
7266         .get_acl        = btrfs_get_acl,
7267 };
7268
7269 static const struct file_operations btrfs_dir_file_operations = {
7270         .llseek         = generic_file_llseek,
7271         .read           = generic_read_dir,
7272         .readdir        = btrfs_real_readdir,
7273         .unlocked_ioctl = btrfs_ioctl,
7274 #ifdef CONFIG_COMPAT
7275         .compat_ioctl   = btrfs_ioctl,
7276 #endif
7277         .release        = btrfs_release_file,
7278         .fsync          = btrfs_sync_file,
7279 };
7280
7281 static struct extent_io_ops btrfs_extent_io_ops = {
7282         .fill_delalloc = run_delalloc_range,
7283         .submit_bio_hook = btrfs_submit_bio_hook,
7284         .merge_bio_hook = btrfs_merge_bio_hook,
7285         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
7286         .writepage_end_io_hook = btrfs_writepage_end_io_hook,
7287         .writepage_start_hook = btrfs_writepage_start_hook,
7288         .set_bit_hook = btrfs_set_bit_hook,
7289         .clear_bit_hook = btrfs_clear_bit_hook,
7290         .merge_extent_hook = btrfs_merge_extent_hook,
7291         .split_extent_hook = btrfs_split_extent_hook,
7292 };
7293
7294 /*
7295  * btrfs doesn't support the bmap operation because swapfiles
7296  * use bmap to make a mapping of extents in the file.  They assume
7297  * these extents won't change over the life of the file and they
7298  * use the bmap result to do IO directly to the drive.
7299  *
7300  * the btrfs bmap call would return logical addresses that aren't
7301  * suitable for IO and they also will change frequently as COW
7302  * operations happen.  So, swapfile + btrfs == corruption.
7303  *
7304  * For now we're avoiding this by dropping bmap.
7305  */
7306 static const struct address_space_operations btrfs_aops = {
7307         .readpage       = btrfs_readpage,
7308         .writepage      = btrfs_writepage,
7309         .writepages     = btrfs_writepages,
7310         .readpages      = btrfs_readpages,
7311         .direct_IO      = btrfs_direct_IO,
7312         .invalidatepage = btrfs_invalidatepage,
7313         .releasepage    = btrfs_releasepage,
7314         .set_page_dirty = btrfs_set_page_dirty,
7315         .error_remove_page = generic_error_remove_page,
7316 };
7317
7318 static const struct address_space_operations btrfs_symlink_aops = {
7319         .readpage       = btrfs_readpage,
7320         .writepage      = btrfs_writepage,
7321         .invalidatepage = btrfs_invalidatepage,
7322         .releasepage    = btrfs_releasepage,
7323 };
7324
7325 static const struct inode_operations btrfs_file_inode_operations = {
7326         .getattr        = btrfs_getattr,
7327         .setattr        = btrfs_setattr,
7328         .setxattr       = btrfs_setxattr,
7329         .getxattr       = btrfs_getxattr,
7330         .listxattr      = btrfs_listxattr,
7331         .removexattr    = btrfs_removexattr,
7332         .permission     = btrfs_permission,
7333         .fiemap         = btrfs_fiemap,
7334         .get_acl        = btrfs_get_acl,
7335 };
7336 static const struct inode_operations btrfs_special_inode_operations = {
7337         .getattr        = btrfs_getattr,
7338         .setattr        = btrfs_setattr,
7339         .permission     = btrfs_permission,
7340         .setxattr       = btrfs_setxattr,
7341         .getxattr       = btrfs_getxattr,
7342         .listxattr      = btrfs_listxattr,
7343         .removexattr    = btrfs_removexattr,
7344         .get_acl        = btrfs_get_acl,
7345 };
7346 static const struct inode_operations btrfs_symlink_inode_operations = {
7347         .readlink       = generic_readlink,
7348         .follow_link    = page_follow_link_light,
7349         .put_link       = page_put_link,
7350         .getattr        = btrfs_getattr,
7351         .permission     = btrfs_permission,
7352         .setxattr       = btrfs_setxattr,
7353         .getxattr       = btrfs_getxattr,
7354         .listxattr      = btrfs_listxattr,
7355         .removexattr    = btrfs_removexattr,
7356         .get_acl        = btrfs_get_acl,
7357 };
7358
7359 const struct dentry_operations btrfs_dentry_operations = {
7360         .d_delete       = btrfs_dentry_delete,
7361         .d_release      = btrfs_dentry_release,
7362 };