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