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