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