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