xref: /openbmc/linux/fs/btrfs/inode.c (revision 82df5b73)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/kernel.h>
7 #include <linux/bio.h>
8 #include <linux/buffer_head.h>
9 #include <linux/file.h>
10 #include <linux/fs.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/writeback.h>
18 #include <linux/compat.h>
19 #include <linux/xattr.h>
20 #include <linux/posix_acl.h>
21 #include <linux/falloc.h>
22 #include <linux/slab.h>
23 #include <linux/ratelimit.h>
24 #include <linux/btrfs.h>
25 #include <linux/blkdev.h>
26 #include <linux/posix_acl_xattr.h>
27 #include <linux/uio.h>
28 #include <linux/magic.h>
29 #include <linux/iversion.h>
30 #include <linux/swap.h>
31 #include <linux/migrate.h>
32 #include <linux/sched/mm.h>
33 #include <asm/unaligned.h>
34 #include "misc.h"
35 #include "ctree.h"
36 #include "disk-io.h"
37 #include "transaction.h"
38 #include "btrfs_inode.h"
39 #include "print-tree.h"
40 #include "ordered-data.h"
41 #include "xattr.h"
42 #include "tree-log.h"
43 #include "volumes.h"
44 #include "compression.h"
45 #include "locking.h"
46 #include "free-space-cache.h"
47 #include "inode-map.h"
48 #include "props.h"
49 #include "qgroup.h"
50 #include "delalloc-space.h"
51 #include "block-group.h"
52 #include "space-info.h"
53 
54 struct btrfs_iget_args {
55 	u64 ino;
56 	struct btrfs_root *root;
57 };
58 
59 struct btrfs_dio_data {
60 	u64 reserve;
61 	u64 unsubmitted_oe_range_start;
62 	u64 unsubmitted_oe_range_end;
63 	int overwrite;
64 };
65 
66 static const struct inode_operations btrfs_dir_inode_operations;
67 static const struct inode_operations btrfs_symlink_inode_operations;
68 static const struct inode_operations btrfs_special_inode_operations;
69 static const struct inode_operations btrfs_file_inode_operations;
70 static const struct address_space_operations btrfs_aops;
71 static const struct file_operations btrfs_dir_file_operations;
72 static const struct extent_io_ops btrfs_extent_io_ops;
73 
74 static struct kmem_cache *btrfs_inode_cachep;
75 struct kmem_cache *btrfs_trans_handle_cachep;
76 struct kmem_cache *btrfs_path_cachep;
77 struct kmem_cache *btrfs_free_space_cachep;
78 struct kmem_cache *btrfs_free_space_bitmap_cachep;
79 
80 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
81 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
82 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
83 static noinline int cow_file_range(struct inode *inode,
84 				   struct page *locked_page,
85 				   u64 start, u64 end, int *page_started,
86 				   unsigned long *nr_written, int unlock);
87 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
88 				       u64 orig_start, u64 block_start,
89 				       u64 block_len, u64 orig_block_len,
90 				       u64 ram_bytes, int compress_type,
91 				       int type);
92 
93 static void __endio_write_update_ordered(struct inode *inode,
94 					 const u64 offset, const u64 bytes,
95 					 const bool uptodate);
96 
97 /*
98  * Cleanup all submitted ordered extents in specified range to handle errors
99  * from the btrfs_run_delalloc_range() callback.
100  *
101  * NOTE: caller must ensure that when an error happens, it can not call
102  * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
103  * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
104  * to be released, which we want to happen only when finishing the ordered
105  * extent (btrfs_finish_ordered_io()).
106  */
107 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
108 						 struct page *locked_page,
109 						 u64 offset, u64 bytes)
110 {
111 	unsigned long index = offset >> PAGE_SHIFT;
112 	unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
113 	u64 page_start = page_offset(locked_page);
114 	u64 page_end = page_start + PAGE_SIZE - 1;
115 
116 	struct page *page;
117 
118 	while (index <= end_index) {
119 		page = find_get_page(inode->i_mapping, index);
120 		index++;
121 		if (!page)
122 			continue;
123 		ClearPagePrivate2(page);
124 		put_page(page);
125 	}
126 
127 	/*
128 	 * In case this page belongs to the delalloc range being instantiated
129 	 * then skip it, since the first page of a range is going to be
130 	 * properly cleaned up by the caller of run_delalloc_range
131 	 */
132 	if (page_start >= offset && page_end <= (offset + bytes - 1)) {
133 		offset += PAGE_SIZE;
134 		bytes -= PAGE_SIZE;
135 	}
136 
137 	return __endio_write_update_ordered(inode, offset, bytes, false);
138 }
139 
140 static int btrfs_dirty_inode(struct inode *inode);
141 
142 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
143 void btrfs_test_inode_set_ops(struct inode *inode)
144 {
145 	BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
146 }
147 #endif
148 
149 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
150 				     struct inode *inode,  struct inode *dir,
151 				     const struct qstr *qstr)
152 {
153 	int err;
154 
155 	err = btrfs_init_acl(trans, inode, dir);
156 	if (!err)
157 		err = btrfs_xattr_security_init(trans, inode, dir, qstr);
158 	return err;
159 }
160 
161 /*
162  * this does all the hard work for inserting an inline extent into
163  * the btree.  The caller should have done a btrfs_drop_extents so that
164  * no overlapping inline items exist in the btree
165  */
166 static int insert_inline_extent(struct btrfs_trans_handle *trans,
167 				struct btrfs_path *path, int extent_inserted,
168 				struct btrfs_root *root, struct inode *inode,
169 				u64 start, size_t size, size_t compressed_size,
170 				int compress_type,
171 				struct page **compressed_pages)
172 {
173 	struct extent_buffer *leaf;
174 	struct page *page = NULL;
175 	char *kaddr;
176 	unsigned long ptr;
177 	struct btrfs_file_extent_item *ei;
178 	int ret;
179 	size_t cur_size = size;
180 	unsigned long offset;
181 
182 	ASSERT((compressed_size > 0 && compressed_pages) ||
183 	       (compressed_size == 0 && !compressed_pages));
184 
185 	if (compressed_size && compressed_pages)
186 		cur_size = compressed_size;
187 
188 	inode_add_bytes(inode, size);
189 
190 	if (!extent_inserted) {
191 		struct btrfs_key key;
192 		size_t datasize;
193 
194 		key.objectid = btrfs_ino(BTRFS_I(inode));
195 		key.offset = start;
196 		key.type = BTRFS_EXTENT_DATA_KEY;
197 
198 		datasize = btrfs_file_extent_calc_inline_size(cur_size);
199 		path->leave_spinning = 1;
200 		ret = btrfs_insert_empty_item(trans, root, path, &key,
201 					      datasize);
202 		if (ret)
203 			goto fail;
204 	}
205 	leaf = path->nodes[0];
206 	ei = btrfs_item_ptr(leaf, path->slots[0],
207 			    struct btrfs_file_extent_item);
208 	btrfs_set_file_extent_generation(leaf, ei, trans->transid);
209 	btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
210 	btrfs_set_file_extent_encryption(leaf, ei, 0);
211 	btrfs_set_file_extent_other_encoding(leaf, ei, 0);
212 	btrfs_set_file_extent_ram_bytes(leaf, ei, size);
213 	ptr = btrfs_file_extent_inline_start(ei);
214 
215 	if (compress_type != BTRFS_COMPRESS_NONE) {
216 		struct page *cpage;
217 		int i = 0;
218 		while (compressed_size > 0) {
219 			cpage = compressed_pages[i];
220 			cur_size = min_t(unsigned long, compressed_size,
221 				       PAGE_SIZE);
222 
223 			kaddr = kmap_atomic(cpage);
224 			write_extent_buffer(leaf, kaddr, ptr, cur_size);
225 			kunmap_atomic(kaddr);
226 
227 			i++;
228 			ptr += cur_size;
229 			compressed_size -= cur_size;
230 		}
231 		btrfs_set_file_extent_compression(leaf, ei,
232 						  compress_type);
233 	} else {
234 		page = find_get_page(inode->i_mapping,
235 				     start >> PAGE_SHIFT);
236 		btrfs_set_file_extent_compression(leaf, ei, 0);
237 		kaddr = kmap_atomic(page);
238 		offset = offset_in_page(start);
239 		write_extent_buffer(leaf, kaddr + offset, ptr, size);
240 		kunmap_atomic(kaddr);
241 		put_page(page);
242 	}
243 	btrfs_mark_buffer_dirty(leaf);
244 	btrfs_release_path(path);
245 
246 	/*
247 	 * We align size to sectorsize for inline extents just for simplicity
248 	 * sake.
249 	 */
250 	size = ALIGN(size, root->fs_info->sectorsize);
251 	ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start, size);
252 	if (ret)
253 		goto fail;
254 
255 	/*
256 	 * we're an inline extent, so nobody can
257 	 * extend the file past i_size without locking
258 	 * a page we already have locked.
259 	 *
260 	 * We must do any isize and inode updates
261 	 * before we unlock the pages.  Otherwise we
262 	 * could end up racing with unlink.
263 	 */
264 	BTRFS_I(inode)->disk_i_size = inode->i_size;
265 	ret = btrfs_update_inode(trans, root, inode);
266 
267 fail:
268 	return ret;
269 }
270 
271 
272 /*
273  * conditionally insert an inline extent into the file.  This
274  * does the checks required to make sure the data is small enough
275  * to fit as an inline extent.
276  */
277 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
278 					  u64 end, size_t compressed_size,
279 					  int compress_type,
280 					  struct page **compressed_pages)
281 {
282 	struct btrfs_root *root = BTRFS_I(inode)->root;
283 	struct btrfs_fs_info *fs_info = root->fs_info;
284 	struct btrfs_trans_handle *trans;
285 	u64 isize = i_size_read(inode);
286 	u64 actual_end = min(end + 1, isize);
287 	u64 inline_len = actual_end - start;
288 	u64 aligned_end = ALIGN(end, fs_info->sectorsize);
289 	u64 data_len = inline_len;
290 	int ret;
291 	struct btrfs_path *path;
292 	int extent_inserted = 0;
293 	u32 extent_item_size;
294 
295 	if (compressed_size)
296 		data_len = compressed_size;
297 
298 	if (start > 0 ||
299 	    actual_end > fs_info->sectorsize ||
300 	    data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
301 	    (!compressed_size &&
302 	    (actual_end & (fs_info->sectorsize - 1)) == 0) ||
303 	    end + 1 < isize ||
304 	    data_len > fs_info->max_inline) {
305 		return 1;
306 	}
307 
308 	path = btrfs_alloc_path();
309 	if (!path)
310 		return -ENOMEM;
311 
312 	trans = btrfs_join_transaction(root);
313 	if (IS_ERR(trans)) {
314 		btrfs_free_path(path);
315 		return PTR_ERR(trans);
316 	}
317 	trans->block_rsv = &BTRFS_I(inode)->block_rsv;
318 
319 	if (compressed_size && compressed_pages)
320 		extent_item_size = btrfs_file_extent_calc_inline_size(
321 		   compressed_size);
322 	else
323 		extent_item_size = btrfs_file_extent_calc_inline_size(
324 		    inline_len);
325 
326 	ret = __btrfs_drop_extents(trans, root, inode, path,
327 				   start, aligned_end, NULL,
328 				   1, 1, extent_item_size, &extent_inserted);
329 	if (ret) {
330 		btrfs_abort_transaction(trans, ret);
331 		goto out;
332 	}
333 
334 	if (isize > actual_end)
335 		inline_len = min_t(u64, isize, actual_end);
336 	ret = insert_inline_extent(trans, path, extent_inserted,
337 				   root, inode, start,
338 				   inline_len, compressed_size,
339 				   compress_type, compressed_pages);
340 	if (ret && ret != -ENOSPC) {
341 		btrfs_abort_transaction(trans, ret);
342 		goto out;
343 	} else if (ret == -ENOSPC) {
344 		ret = 1;
345 		goto out;
346 	}
347 
348 	set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
349 	btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
350 out:
351 	/*
352 	 * Don't forget to free the reserved space, as for inlined extent
353 	 * it won't count as data extent, free them directly here.
354 	 * And at reserve time, it's always aligned to page size, so
355 	 * just free one page here.
356 	 */
357 	btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
358 	btrfs_free_path(path);
359 	btrfs_end_transaction(trans);
360 	return ret;
361 }
362 
363 struct async_extent {
364 	u64 start;
365 	u64 ram_size;
366 	u64 compressed_size;
367 	struct page **pages;
368 	unsigned long nr_pages;
369 	int compress_type;
370 	struct list_head list;
371 };
372 
373 struct async_chunk {
374 	struct inode *inode;
375 	struct page *locked_page;
376 	u64 start;
377 	u64 end;
378 	unsigned int write_flags;
379 	struct list_head extents;
380 	struct cgroup_subsys_state *blkcg_css;
381 	struct btrfs_work work;
382 	atomic_t *pending;
383 };
384 
385 struct async_cow {
386 	/* Number of chunks in flight; must be first in the structure */
387 	atomic_t num_chunks;
388 	struct async_chunk chunks[];
389 };
390 
391 static noinline int add_async_extent(struct async_chunk *cow,
392 				     u64 start, u64 ram_size,
393 				     u64 compressed_size,
394 				     struct page **pages,
395 				     unsigned long nr_pages,
396 				     int compress_type)
397 {
398 	struct async_extent *async_extent;
399 
400 	async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
401 	BUG_ON(!async_extent); /* -ENOMEM */
402 	async_extent->start = start;
403 	async_extent->ram_size = ram_size;
404 	async_extent->compressed_size = compressed_size;
405 	async_extent->pages = pages;
406 	async_extent->nr_pages = nr_pages;
407 	async_extent->compress_type = compress_type;
408 	list_add_tail(&async_extent->list, &cow->extents);
409 	return 0;
410 }
411 
412 /*
413  * Check if the inode has flags compatible with compression
414  */
415 static inline bool inode_can_compress(struct inode *inode)
416 {
417 	if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW ||
418 	    BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
419 		return false;
420 	return true;
421 }
422 
423 /*
424  * Check if the inode needs to be submitted to compression, based on mount
425  * options, defragmentation, properties or heuristics.
426  */
427 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
428 {
429 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
430 
431 	if (!inode_can_compress(inode)) {
432 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
433 			KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
434 			btrfs_ino(BTRFS_I(inode)));
435 		return 0;
436 	}
437 	/* force compress */
438 	if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
439 		return 1;
440 	/* defrag ioctl */
441 	if (BTRFS_I(inode)->defrag_compress)
442 		return 1;
443 	/* bad compression ratios */
444 	if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
445 		return 0;
446 	if (btrfs_test_opt(fs_info, COMPRESS) ||
447 	    BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
448 	    BTRFS_I(inode)->prop_compress)
449 		return btrfs_compress_heuristic(inode, start, end);
450 	return 0;
451 }
452 
453 static inline void inode_should_defrag(struct btrfs_inode *inode,
454 		u64 start, u64 end, u64 num_bytes, u64 small_write)
455 {
456 	/* If this is a small write inside eof, kick off a defrag */
457 	if (num_bytes < small_write &&
458 	    (start > 0 || end + 1 < inode->disk_i_size))
459 		btrfs_add_inode_defrag(NULL, inode);
460 }
461 
462 /*
463  * we create compressed extents in two phases.  The first
464  * phase compresses a range of pages that have already been
465  * locked (both pages and state bits are locked).
466  *
467  * This is done inside an ordered work queue, and the compression
468  * is spread across many cpus.  The actual IO submission is step
469  * two, and the ordered work queue takes care of making sure that
470  * happens in the same order things were put onto the queue by
471  * writepages and friends.
472  *
473  * If this code finds it can't get good compression, it puts an
474  * entry onto the work queue to write the uncompressed bytes.  This
475  * makes sure that both compressed inodes and uncompressed inodes
476  * are written in the same order that the flusher thread sent them
477  * down.
478  */
479 static noinline int compress_file_range(struct async_chunk *async_chunk)
480 {
481 	struct inode *inode = async_chunk->inode;
482 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
483 	u64 blocksize = fs_info->sectorsize;
484 	u64 start = async_chunk->start;
485 	u64 end = async_chunk->end;
486 	u64 actual_end;
487 	u64 i_size;
488 	int ret = 0;
489 	struct page **pages = NULL;
490 	unsigned long nr_pages;
491 	unsigned long total_compressed = 0;
492 	unsigned long total_in = 0;
493 	int i;
494 	int will_compress;
495 	int compress_type = fs_info->compress_type;
496 	int compressed_extents = 0;
497 	int redirty = 0;
498 
499 	inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
500 			SZ_16K);
501 
502 	/*
503 	 * We need to save i_size before now because it could change in between
504 	 * us evaluating the size and assigning it.  This is because we lock and
505 	 * unlock the page in truncate and fallocate, and then modify the i_size
506 	 * later on.
507 	 *
508 	 * The barriers are to emulate READ_ONCE, remove that once i_size_read
509 	 * does that for us.
510 	 */
511 	barrier();
512 	i_size = i_size_read(inode);
513 	barrier();
514 	actual_end = min_t(u64, i_size, end + 1);
515 again:
516 	will_compress = 0;
517 	nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
518 	BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
519 	nr_pages = min_t(unsigned long, nr_pages,
520 			BTRFS_MAX_COMPRESSED / PAGE_SIZE);
521 
522 	/*
523 	 * we don't want to send crud past the end of i_size through
524 	 * compression, that's just a waste of CPU time.  So, if the
525 	 * end of the file is before the start of our current
526 	 * requested range of bytes, we bail out to the uncompressed
527 	 * cleanup code that can deal with all of this.
528 	 *
529 	 * It isn't really the fastest way to fix things, but this is a
530 	 * very uncommon corner.
531 	 */
532 	if (actual_end <= start)
533 		goto cleanup_and_bail_uncompressed;
534 
535 	total_compressed = actual_end - start;
536 
537 	/*
538 	 * skip compression for a small file range(<=blocksize) that
539 	 * isn't an inline extent, since it doesn't save disk space at all.
540 	 */
541 	if (total_compressed <= blocksize &&
542 	   (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
543 		goto cleanup_and_bail_uncompressed;
544 
545 	total_compressed = min_t(unsigned long, total_compressed,
546 			BTRFS_MAX_UNCOMPRESSED);
547 	total_in = 0;
548 	ret = 0;
549 
550 	/*
551 	 * we do compression for mount -o compress and when the
552 	 * inode has not been flagged as nocompress.  This flag can
553 	 * change at any time if we discover bad compression ratios.
554 	 */
555 	if (inode_need_compress(inode, start, end)) {
556 		WARN_ON(pages);
557 		pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
558 		if (!pages) {
559 			/* just bail out to the uncompressed code */
560 			nr_pages = 0;
561 			goto cont;
562 		}
563 
564 		if (BTRFS_I(inode)->defrag_compress)
565 			compress_type = BTRFS_I(inode)->defrag_compress;
566 		else if (BTRFS_I(inode)->prop_compress)
567 			compress_type = BTRFS_I(inode)->prop_compress;
568 
569 		/*
570 		 * we need to call clear_page_dirty_for_io on each
571 		 * page in the range.  Otherwise applications with the file
572 		 * mmap'd can wander in and change the page contents while
573 		 * we are compressing them.
574 		 *
575 		 * If the compression fails for any reason, we set the pages
576 		 * dirty again later on.
577 		 *
578 		 * Note that the remaining part is redirtied, the start pointer
579 		 * has moved, the end is the original one.
580 		 */
581 		if (!redirty) {
582 			extent_range_clear_dirty_for_io(inode, start, end);
583 			redirty = 1;
584 		}
585 
586 		/* Compression level is applied here and only here */
587 		ret = btrfs_compress_pages(
588 			compress_type | (fs_info->compress_level << 4),
589 					   inode->i_mapping, start,
590 					   pages,
591 					   &nr_pages,
592 					   &total_in,
593 					   &total_compressed);
594 
595 		if (!ret) {
596 			unsigned long offset = offset_in_page(total_compressed);
597 			struct page *page = pages[nr_pages - 1];
598 			char *kaddr;
599 
600 			/* zero the tail end of the last page, we might be
601 			 * sending it down to disk
602 			 */
603 			if (offset) {
604 				kaddr = kmap_atomic(page);
605 				memset(kaddr + offset, 0,
606 				       PAGE_SIZE - offset);
607 				kunmap_atomic(kaddr);
608 			}
609 			will_compress = 1;
610 		}
611 	}
612 cont:
613 	if (start == 0) {
614 		/* lets try to make an inline extent */
615 		if (ret || total_in < actual_end) {
616 			/* we didn't compress the entire range, try
617 			 * to make an uncompressed inline extent.
618 			 */
619 			ret = cow_file_range_inline(inode, start, end, 0,
620 						    BTRFS_COMPRESS_NONE, NULL);
621 		} else {
622 			/* try making a compressed inline extent */
623 			ret = cow_file_range_inline(inode, start, end,
624 						    total_compressed,
625 						    compress_type, pages);
626 		}
627 		if (ret <= 0) {
628 			unsigned long clear_flags = EXTENT_DELALLOC |
629 				EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
630 				EXTENT_DO_ACCOUNTING;
631 			unsigned long page_error_op;
632 
633 			page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
634 
635 			/*
636 			 * inline extent creation worked or returned error,
637 			 * we don't need to create any more async work items.
638 			 * Unlock and free up our temp pages.
639 			 *
640 			 * We use DO_ACCOUNTING here because we need the
641 			 * delalloc_release_metadata to be done _after_ we drop
642 			 * our outstanding extent for clearing delalloc for this
643 			 * range.
644 			 */
645 			extent_clear_unlock_delalloc(inode, start, end, NULL,
646 						     clear_flags,
647 						     PAGE_UNLOCK |
648 						     PAGE_CLEAR_DIRTY |
649 						     PAGE_SET_WRITEBACK |
650 						     page_error_op |
651 						     PAGE_END_WRITEBACK);
652 
653 			for (i = 0; i < nr_pages; i++) {
654 				WARN_ON(pages[i]->mapping);
655 				put_page(pages[i]);
656 			}
657 			kfree(pages);
658 
659 			return 0;
660 		}
661 	}
662 
663 	if (will_compress) {
664 		/*
665 		 * we aren't doing an inline extent round the compressed size
666 		 * up to a block size boundary so the allocator does sane
667 		 * things
668 		 */
669 		total_compressed = ALIGN(total_compressed, blocksize);
670 
671 		/*
672 		 * one last check to make sure the compression is really a
673 		 * win, compare the page count read with the blocks on disk,
674 		 * compression must free at least one sector size
675 		 */
676 		total_in = ALIGN(total_in, PAGE_SIZE);
677 		if (total_compressed + blocksize <= total_in) {
678 			compressed_extents++;
679 
680 			/*
681 			 * The async work queues will take care of doing actual
682 			 * allocation on disk for these compressed pages, and
683 			 * will submit them to the elevator.
684 			 */
685 			add_async_extent(async_chunk, start, total_in,
686 					total_compressed, pages, nr_pages,
687 					compress_type);
688 
689 			if (start + total_in < end) {
690 				start += total_in;
691 				pages = NULL;
692 				cond_resched();
693 				goto again;
694 			}
695 			return compressed_extents;
696 		}
697 	}
698 	if (pages) {
699 		/*
700 		 * the compression code ran but failed to make things smaller,
701 		 * free any pages it allocated and our page pointer array
702 		 */
703 		for (i = 0; i < nr_pages; i++) {
704 			WARN_ON(pages[i]->mapping);
705 			put_page(pages[i]);
706 		}
707 		kfree(pages);
708 		pages = NULL;
709 		total_compressed = 0;
710 		nr_pages = 0;
711 
712 		/* flag the file so we don't compress in the future */
713 		if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
714 		    !(BTRFS_I(inode)->prop_compress)) {
715 			BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
716 		}
717 	}
718 cleanup_and_bail_uncompressed:
719 	/*
720 	 * No compression, but we still need to write the pages in the file
721 	 * we've been given so far.  redirty the locked page if it corresponds
722 	 * to our extent and set things up for the async work queue to run
723 	 * cow_file_range to do the normal delalloc dance.
724 	 */
725 	if (async_chunk->locked_page &&
726 	    (page_offset(async_chunk->locked_page) >= start &&
727 	     page_offset(async_chunk->locked_page)) <= end) {
728 		__set_page_dirty_nobuffers(async_chunk->locked_page);
729 		/* unlocked later on in the async handlers */
730 	}
731 
732 	if (redirty)
733 		extent_range_redirty_for_io(inode, start, end);
734 	add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
735 			 BTRFS_COMPRESS_NONE);
736 	compressed_extents++;
737 
738 	return compressed_extents;
739 }
740 
741 static void free_async_extent_pages(struct async_extent *async_extent)
742 {
743 	int i;
744 
745 	if (!async_extent->pages)
746 		return;
747 
748 	for (i = 0; i < async_extent->nr_pages; i++) {
749 		WARN_ON(async_extent->pages[i]->mapping);
750 		put_page(async_extent->pages[i]);
751 	}
752 	kfree(async_extent->pages);
753 	async_extent->nr_pages = 0;
754 	async_extent->pages = NULL;
755 }
756 
757 /*
758  * phase two of compressed writeback.  This is the ordered portion
759  * of the code, which only gets called in the order the work was
760  * queued.  We walk all the async extents created by compress_file_range
761  * and send them down to the disk.
762  */
763 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
764 {
765 	struct inode *inode = async_chunk->inode;
766 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
767 	struct async_extent *async_extent;
768 	u64 alloc_hint = 0;
769 	struct btrfs_key ins;
770 	struct extent_map *em;
771 	struct btrfs_root *root = BTRFS_I(inode)->root;
772 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
773 	int ret = 0;
774 
775 again:
776 	while (!list_empty(&async_chunk->extents)) {
777 		async_extent = list_entry(async_chunk->extents.next,
778 					  struct async_extent, list);
779 		list_del(&async_extent->list);
780 
781 retry:
782 		lock_extent(io_tree, async_extent->start,
783 			    async_extent->start + async_extent->ram_size - 1);
784 		/* did the compression code fall back to uncompressed IO? */
785 		if (!async_extent->pages) {
786 			int page_started = 0;
787 			unsigned long nr_written = 0;
788 
789 			/* allocate blocks */
790 			ret = cow_file_range(inode, async_chunk->locked_page,
791 					     async_extent->start,
792 					     async_extent->start +
793 					     async_extent->ram_size - 1,
794 					     &page_started, &nr_written, 0);
795 
796 			/* JDM XXX */
797 
798 			/*
799 			 * if page_started, cow_file_range inserted an
800 			 * inline extent and took care of all the unlocking
801 			 * and IO for us.  Otherwise, we need to submit
802 			 * all those pages down to the drive.
803 			 */
804 			if (!page_started && !ret)
805 				extent_write_locked_range(inode,
806 						  async_extent->start,
807 						  async_extent->start +
808 						  async_extent->ram_size - 1,
809 						  WB_SYNC_ALL);
810 			else if (ret && async_chunk->locked_page)
811 				unlock_page(async_chunk->locked_page);
812 			kfree(async_extent);
813 			cond_resched();
814 			continue;
815 		}
816 
817 		ret = btrfs_reserve_extent(root, async_extent->ram_size,
818 					   async_extent->compressed_size,
819 					   async_extent->compressed_size,
820 					   0, alloc_hint, &ins, 1, 1);
821 		if (ret) {
822 			free_async_extent_pages(async_extent);
823 
824 			if (ret == -ENOSPC) {
825 				unlock_extent(io_tree, async_extent->start,
826 					      async_extent->start +
827 					      async_extent->ram_size - 1);
828 
829 				/*
830 				 * we need to redirty the pages if we decide to
831 				 * fallback to uncompressed IO, otherwise we
832 				 * will not submit these pages down to lower
833 				 * layers.
834 				 */
835 				extent_range_redirty_for_io(inode,
836 						async_extent->start,
837 						async_extent->start +
838 						async_extent->ram_size - 1);
839 
840 				goto retry;
841 			}
842 			goto out_free;
843 		}
844 		/*
845 		 * here we're doing allocation and writeback of the
846 		 * compressed pages
847 		 */
848 		em = create_io_em(inode, async_extent->start,
849 				  async_extent->ram_size, /* len */
850 				  async_extent->start, /* orig_start */
851 				  ins.objectid, /* block_start */
852 				  ins.offset, /* block_len */
853 				  ins.offset, /* orig_block_len */
854 				  async_extent->ram_size, /* ram_bytes */
855 				  async_extent->compress_type,
856 				  BTRFS_ORDERED_COMPRESSED);
857 		if (IS_ERR(em))
858 			/* ret value is not necessary due to void function */
859 			goto out_free_reserve;
860 		free_extent_map(em);
861 
862 		ret = btrfs_add_ordered_extent_compress(inode,
863 						async_extent->start,
864 						ins.objectid,
865 						async_extent->ram_size,
866 						ins.offset,
867 						BTRFS_ORDERED_COMPRESSED,
868 						async_extent->compress_type);
869 		if (ret) {
870 			btrfs_drop_extent_cache(BTRFS_I(inode),
871 						async_extent->start,
872 						async_extent->start +
873 						async_extent->ram_size - 1, 0);
874 			goto out_free_reserve;
875 		}
876 		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
877 
878 		/*
879 		 * clear dirty, set writeback and unlock the pages.
880 		 */
881 		extent_clear_unlock_delalloc(inode, async_extent->start,
882 				async_extent->start +
883 				async_extent->ram_size - 1,
884 				NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
885 				PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
886 				PAGE_SET_WRITEBACK);
887 		if (btrfs_submit_compressed_write(inode,
888 				    async_extent->start,
889 				    async_extent->ram_size,
890 				    ins.objectid,
891 				    ins.offset, async_extent->pages,
892 				    async_extent->nr_pages,
893 				    async_chunk->write_flags,
894 				    async_chunk->blkcg_css)) {
895 			struct page *p = async_extent->pages[0];
896 			const u64 start = async_extent->start;
897 			const u64 end = start + async_extent->ram_size - 1;
898 
899 			p->mapping = inode->i_mapping;
900 			btrfs_writepage_endio_finish_ordered(p, start, end, 0);
901 
902 			p->mapping = NULL;
903 			extent_clear_unlock_delalloc(inode, start, end,
904 						     NULL, 0,
905 						     PAGE_END_WRITEBACK |
906 						     PAGE_SET_ERROR);
907 			free_async_extent_pages(async_extent);
908 		}
909 		alloc_hint = ins.objectid + ins.offset;
910 		kfree(async_extent);
911 		cond_resched();
912 	}
913 	return;
914 out_free_reserve:
915 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
916 	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
917 out_free:
918 	extent_clear_unlock_delalloc(inode, async_extent->start,
919 				     async_extent->start +
920 				     async_extent->ram_size - 1,
921 				     NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
922 				     EXTENT_DELALLOC_NEW |
923 				     EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
924 				     PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
925 				     PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
926 				     PAGE_SET_ERROR);
927 	free_async_extent_pages(async_extent);
928 	kfree(async_extent);
929 	goto again;
930 }
931 
932 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
933 				      u64 num_bytes)
934 {
935 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
936 	struct extent_map *em;
937 	u64 alloc_hint = 0;
938 
939 	read_lock(&em_tree->lock);
940 	em = search_extent_mapping(em_tree, start, num_bytes);
941 	if (em) {
942 		/*
943 		 * if block start isn't an actual block number then find the
944 		 * first block in this inode and use that as a hint.  If that
945 		 * block is also bogus then just don't worry about it.
946 		 */
947 		if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
948 			free_extent_map(em);
949 			em = search_extent_mapping(em_tree, 0, 0);
950 			if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
951 				alloc_hint = em->block_start;
952 			if (em)
953 				free_extent_map(em);
954 		} else {
955 			alloc_hint = em->block_start;
956 			free_extent_map(em);
957 		}
958 	}
959 	read_unlock(&em_tree->lock);
960 
961 	return alloc_hint;
962 }
963 
964 /*
965  * when extent_io.c finds a delayed allocation range in the file,
966  * the call backs end up in this code.  The basic idea is to
967  * allocate extents on disk for the range, and create ordered data structs
968  * in ram to track those extents.
969  *
970  * locked_page is the page that writepage had locked already.  We use
971  * it to make sure we don't do extra locks or unlocks.
972  *
973  * *page_started is set to one if we unlock locked_page and do everything
974  * required to start IO on it.  It may be clean and already done with
975  * IO when we return.
976  */
977 static noinline int cow_file_range(struct inode *inode,
978 				   struct page *locked_page,
979 				   u64 start, u64 end, int *page_started,
980 				   unsigned long *nr_written, int unlock)
981 {
982 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
983 	struct btrfs_root *root = BTRFS_I(inode)->root;
984 	u64 alloc_hint = 0;
985 	u64 num_bytes;
986 	unsigned long ram_size;
987 	u64 cur_alloc_size = 0;
988 	u64 blocksize = fs_info->sectorsize;
989 	struct btrfs_key ins;
990 	struct extent_map *em;
991 	unsigned clear_bits;
992 	unsigned long page_ops;
993 	bool extent_reserved = false;
994 	int ret = 0;
995 
996 	if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
997 		WARN_ON_ONCE(1);
998 		ret = -EINVAL;
999 		goto out_unlock;
1000 	}
1001 
1002 	num_bytes = ALIGN(end - start + 1, blocksize);
1003 	num_bytes = max(blocksize,  num_bytes);
1004 	ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1005 
1006 	inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
1007 
1008 	if (start == 0) {
1009 		/* lets try to make an inline extent */
1010 		ret = cow_file_range_inline(inode, start, end, 0,
1011 					    BTRFS_COMPRESS_NONE, NULL);
1012 		if (ret == 0) {
1013 			/*
1014 			 * We use DO_ACCOUNTING here because we need the
1015 			 * delalloc_release_metadata to be run _after_ we drop
1016 			 * our outstanding extent for clearing delalloc for this
1017 			 * range.
1018 			 */
1019 			extent_clear_unlock_delalloc(inode, start, end, NULL,
1020 				     EXTENT_LOCKED | EXTENT_DELALLOC |
1021 				     EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1022 				     EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1023 				     PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1024 				     PAGE_END_WRITEBACK);
1025 			*nr_written = *nr_written +
1026 			     (end - start + PAGE_SIZE) / PAGE_SIZE;
1027 			*page_started = 1;
1028 			goto out;
1029 		} else if (ret < 0) {
1030 			goto out_unlock;
1031 		}
1032 	}
1033 
1034 	alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1035 	btrfs_drop_extent_cache(BTRFS_I(inode), start,
1036 			start + num_bytes - 1, 0);
1037 
1038 	while (num_bytes > 0) {
1039 		cur_alloc_size = num_bytes;
1040 		ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1041 					   fs_info->sectorsize, 0, alloc_hint,
1042 					   &ins, 1, 1);
1043 		if (ret < 0)
1044 			goto out_unlock;
1045 		cur_alloc_size = ins.offset;
1046 		extent_reserved = true;
1047 
1048 		ram_size = ins.offset;
1049 		em = create_io_em(inode, start, ins.offset, /* len */
1050 				  start, /* orig_start */
1051 				  ins.objectid, /* block_start */
1052 				  ins.offset, /* block_len */
1053 				  ins.offset, /* orig_block_len */
1054 				  ram_size, /* ram_bytes */
1055 				  BTRFS_COMPRESS_NONE, /* compress_type */
1056 				  BTRFS_ORDERED_REGULAR /* type */);
1057 		if (IS_ERR(em)) {
1058 			ret = PTR_ERR(em);
1059 			goto out_reserve;
1060 		}
1061 		free_extent_map(em);
1062 
1063 		ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1064 					       ram_size, cur_alloc_size, 0);
1065 		if (ret)
1066 			goto out_drop_extent_cache;
1067 
1068 		if (root->root_key.objectid ==
1069 		    BTRFS_DATA_RELOC_TREE_OBJECTID) {
1070 			ret = btrfs_reloc_clone_csums(inode, start,
1071 						      cur_alloc_size);
1072 			/*
1073 			 * Only drop cache here, and process as normal.
1074 			 *
1075 			 * We must not allow extent_clear_unlock_delalloc()
1076 			 * at out_unlock label to free meta of this ordered
1077 			 * extent, as its meta should be freed by
1078 			 * btrfs_finish_ordered_io().
1079 			 *
1080 			 * So we must continue until @start is increased to
1081 			 * skip current ordered extent.
1082 			 */
1083 			if (ret)
1084 				btrfs_drop_extent_cache(BTRFS_I(inode), start,
1085 						start + ram_size - 1, 0);
1086 		}
1087 
1088 		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1089 
1090 		/* we're not doing compressed IO, don't unlock the first
1091 		 * page (which the caller expects to stay locked), don't
1092 		 * clear any dirty bits and don't set any writeback bits
1093 		 *
1094 		 * Do set the Private2 bit so we know this page was properly
1095 		 * setup for writepage
1096 		 */
1097 		page_ops = unlock ? PAGE_UNLOCK : 0;
1098 		page_ops |= PAGE_SET_PRIVATE2;
1099 
1100 		extent_clear_unlock_delalloc(inode, start,
1101 					     start + ram_size - 1,
1102 					     locked_page,
1103 					     EXTENT_LOCKED | EXTENT_DELALLOC,
1104 					     page_ops);
1105 		if (num_bytes < cur_alloc_size)
1106 			num_bytes = 0;
1107 		else
1108 			num_bytes -= cur_alloc_size;
1109 		alloc_hint = ins.objectid + ins.offset;
1110 		start += cur_alloc_size;
1111 		extent_reserved = false;
1112 
1113 		/*
1114 		 * btrfs_reloc_clone_csums() error, since start is increased
1115 		 * extent_clear_unlock_delalloc() at out_unlock label won't
1116 		 * free metadata of current ordered extent, we're OK to exit.
1117 		 */
1118 		if (ret)
1119 			goto out_unlock;
1120 	}
1121 out:
1122 	return ret;
1123 
1124 out_drop_extent_cache:
1125 	btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1126 out_reserve:
1127 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1128 	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1129 out_unlock:
1130 	clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1131 		EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1132 	page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1133 		PAGE_END_WRITEBACK;
1134 	/*
1135 	 * If we reserved an extent for our delalloc range (or a subrange) and
1136 	 * failed to create the respective ordered extent, then it means that
1137 	 * when we reserved the extent we decremented the extent's size from
1138 	 * the data space_info's bytes_may_use counter and incremented the
1139 	 * space_info's bytes_reserved counter by the same amount. We must make
1140 	 * sure extent_clear_unlock_delalloc() does not try to decrement again
1141 	 * the data space_info's bytes_may_use counter, therefore we do not pass
1142 	 * it the flag EXTENT_CLEAR_DATA_RESV.
1143 	 */
1144 	if (extent_reserved) {
1145 		extent_clear_unlock_delalloc(inode, start,
1146 					     start + cur_alloc_size - 1,
1147 					     locked_page,
1148 					     clear_bits,
1149 					     page_ops);
1150 		start += cur_alloc_size;
1151 		if (start >= end)
1152 			goto out;
1153 	}
1154 	extent_clear_unlock_delalloc(inode, start, end, locked_page,
1155 				     clear_bits | EXTENT_CLEAR_DATA_RESV,
1156 				     page_ops);
1157 	goto out;
1158 }
1159 
1160 /*
1161  * work queue call back to started compression on a file and pages
1162  */
1163 static noinline void async_cow_start(struct btrfs_work *work)
1164 {
1165 	struct async_chunk *async_chunk;
1166 	int compressed_extents;
1167 
1168 	async_chunk = container_of(work, struct async_chunk, work);
1169 
1170 	compressed_extents = compress_file_range(async_chunk);
1171 	if (compressed_extents == 0) {
1172 		btrfs_add_delayed_iput(async_chunk->inode);
1173 		async_chunk->inode = NULL;
1174 	}
1175 }
1176 
1177 /*
1178  * work queue call back to submit previously compressed pages
1179  */
1180 static noinline void async_cow_submit(struct btrfs_work *work)
1181 {
1182 	struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1183 						     work);
1184 	struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1185 	unsigned long nr_pages;
1186 
1187 	nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1188 		PAGE_SHIFT;
1189 
1190 	/* atomic_sub_return implies a barrier */
1191 	if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1192 	    5 * SZ_1M)
1193 		cond_wake_up_nomb(&fs_info->async_submit_wait);
1194 
1195 	/*
1196 	 * ->inode could be NULL if async_chunk_start has failed to compress,
1197 	 * in which case we don't have anything to submit, yet we need to
1198 	 * always adjust ->async_delalloc_pages as its paired with the init
1199 	 * happening in cow_file_range_async
1200 	 */
1201 	if (async_chunk->inode)
1202 		submit_compressed_extents(async_chunk);
1203 }
1204 
1205 static noinline void async_cow_free(struct btrfs_work *work)
1206 {
1207 	struct async_chunk *async_chunk;
1208 
1209 	async_chunk = container_of(work, struct async_chunk, work);
1210 	if (async_chunk->inode)
1211 		btrfs_add_delayed_iput(async_chunk->inode);
1212 	if (async_chunk->blkcg_css)
1213 		css_put(async_chunk->blkcg_css);
1214 	/*
1215 	 * Since the pointer to 'pending' is at the beginning of the array of
1216 	 * async_chunk's, freeing it ensures the whole array has been freed.
1217 	 */
1218 	if (atomic_dec_and_test(async_chunk->pending))
1219 		kvfree(async_chunk->pending);
1220 }
1221 
1222 static int cow_file_range_async(struct inode *inode,
1223 				struct writeback_control *wbc,
1224 				struct page *locked_page,
1225 				u64 start, u64 end, int *page_started,
1226 				unsigned long *nr_written)
1227 {
1228 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1229 	struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1230 	struct async_cow *ctx;
1231 	struct async_chunk *async_chunk;
1232 	unsigned long nr_pages;
1233 	u64 cur_end;
1234 	u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1235 	int i;
1236 	bool should_compress;
1237 	unsigned nofs_flag;
1238 	const unsigned int write_flags = wbc_to_write_flags(wbc);
1239 
1240 	unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
1241 
1242 	if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1243 	    !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1244 		num_chunks = 1;
1245 		should_compress = false;
1246 	} else {
1247 		should_compress = true;
1248 	}
1249 
1250 	nofs_flag = memalloc_nofs_save();
1251 	ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1252 	memalloc_nofs_restore(nofs_flag);
1253 
1254 	if (!ctx) {
1255 		unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1256 			EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1257 			EXTENT_DO_ACCOUNTING;
1258 		unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1259 			PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1260 			PAGE_SET_ERROR;
1261 
1262 		extent_clear_unlock_delalloc(inode, start, end, locked_page,
1263 					     clear_bits, page_ops);
1264 		return -ENOMEM;
1265 	}
1266 
1267 	async_chunk = ctx->chunks;
1268 	atomic_set(&ctx->num_chunks, num_chunks);
1269 
1270 	for (i = 0; i < num_chunks; i++) {
1271 		if (should_compress)
1272 			cur_end = min(end, start + SZ_512K - 1);
1273 		else
1274 			cur_end = end;
1275 
1276 		/*
1277 		 * igrab is called higher up in the call chain, take only the
1278 		 * lightweight reference for the callback lifetime
1279 		 */
1280 		ihold(inode);
1281 		async_chunk[i].pending = &ctx->num_chunks;
1282 		async_chunk[i].inode = inode;
1283 		async_chunk[i].start = start;
1284 		async_chunk[i].end = cur_end;
1285 		async_chunk[i].write_flags = write_flags;
1286 		INIT_LIST_HEAD(&async_chunk[i].extents);
1287 
1288 		/*
1289 		 * The locked_page comes all the way from writepage and its
1290 		 * the original page we were actually given.  As we spread
1291 		 * this large delalloc region across multiple async_chunk
1292 		 * structs, only the first struct needs a pointer to locked_page
1293 		 *
1294 		 * This way we don't need racey decisions about who is supposed
1295 		 * to unlock it.
1296 		 */
1297 		if (locked_page) {
1298 			/*
1299 			 * Depending on the compressibility, the pages might or
1300 			 * might not go through async.  We want all of them to
1301 			 * be accounted against wbc once.  Let's do it here
1302 			 * before the paths diverge.  wbc accounting is used
1303 			 * only for foreign writeback detection and doesn't
1304 			 * need full accuracy.  Just account the whole thing
1305 			 * against the first page.
1306 			 */
1307 			wbc_account_cgroup_owner(wbc, locked_page,
1308 						 cur_end - start);
1309 			async_chunk[i].locked_page = locked_page;
1310 			locked_page = NULL;
1311 		} else {
1312 			async_chunk[i].locked_page = NULL;
1313 		}
1314 
1315 		if (blkcg_css != blkcg_root_css) {
1316 			css_get(blkcg_css);
1317 			async_chunk[i].blkcg_css = blkcg_css;
1318 		} else {
1319 			async_chunk[i].blkcg_css = NULL;
1320 		}
1321 
1322 		btrfs_init_work(&async_chunk[i].work, async_cow_start,
1323 				async_cow_submit, async_cow_free);
1324 
1325 		nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1326 		atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1327 
1328 		btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1329 
1330 		*nr_written += nr_pages;
1331 		start = cur_end + 1;
1332 	}
1333 	*page_started = 1;
1334 	return 0;
1335 }
1336 
1337 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1338 					u64 bytenr, u64 num_bytes)
1339 {
1340 	int ret;
1341 	struct btrfs_ordered_sum *sums;
1342 	LIST_HEAD(list);
1343 
1344 	ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1345 				       bytenr + num_bytes - 1, &list, 0);
1346 	if (ret == 0 && list_empty(&list))
1347 		return 0;
1348 
1349 	while (!list_empty(&list)) {
1350 		sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1351 		list_del(&sums->list);
1352 		kfree(sums);
1353 	}
1354 	if (ret < 0)
1355 		return ret;
1356 	return 1;
1357 }
1358 
1359 static int fallback_to_cow(struct inode *inode, struct page *locked_page,
1360 			   const u64 start, const u64 end,
1361 			   int *page_started, unsigned long *nr_written)
1362 {
1363 	const bool is_space_ino = btrfs_is_free_space_inode(BTRFS_I(inode));
1364 	const u64 range_bytes = end + 1 - start;
1365 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1366 	u64 range_start = start;
1367 	u64 count;
1368 
1369 	/*
1370 	 * If EXTENT_NORESERVE is set it means that when the buffered write was
1371 	 * made we had not enough available data space and therefore we did not
1372 	 * reserve data space for it, since we though we could do NOCOW for the
1373 	 * respective file range (either there is prealloc extent or the inode
1374 	 * has the NOCOW bit set).
1375 	 *
1376 	 * However when we need to fallback to COW mode (because for example the
1377 	 * block group for the corresponding extent was turned to RO mode by a
1378 	 * scrub or relocation) we need to do the following:
1379 	 *
1380 	 * 1) We increment the bytes_may_use counter of the data space info.
1381 	 *    If COW succeeds, it allocates a new data extent and after doing
1382 	 *    that it decrements the space info's bytes_may_use counter and
1383 	 *    increments its bytes_reserved counter by the same amount (we do
1384 	 *    this at btrfs_add_reserved_bytes()). So we need to increment the
1385 	 *    bytes_may_use counter to compensate (when space is reserved at
1386 	 *    buffered write time, the bytes_may_use counter is incremented);
1387 	 *
1388 	 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1389 	 *    that if the COW path fails for any reason, it decrements (through
1390 	 *    extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1391 	 *    data space info, which we incremented in the step above.
1392 	 *
1393 	 * If we need to fallback to cow and the inode corresponds to a free
1394 	 * space cache inode, we must also increment bytes_may_use of the data
1395 	 * space_info for the same reason. Space caches always get a prealloc
1396 	 * extent for them, however scrub or balance may have set the block
1397 	 * group that contains that extent to RO mode.
1398 	 */
1399 	count = count_range_bits(io_tree, &range_start, end, range_bytes,
1400 				 EXTENT_NORESERVE, 0);
1401 	if (count > 0 || is_space_ino) {
1402 		const u64 bytes = is_space_ino ? range_bytes : count;
1403 		struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
1404 		struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1405 
1406 		spin_lock(&sinfo->lock);
1407 		btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1408 		spin_unlock(&sinfo->lock);
1409 
1410 		if (count > 0)
1411 			clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1412 					 0, 0, NULL);
1413 	}
1414 
1415 	return cow_file_range(inode, locked_page, start, end, page_started,
1416 			      nr_written, 1);
1417 }
1418 
1419 /*
1420  * when nowcow writeback call back.  This checks for snapshots or COW copies
1421  * of the extents that exist in the file, and COWs the file as required.
1422  *
1423  * If no cow copies or snapshots exist, we write directly to the existing
1424  * blocks on disk
1425  */
1426 static noinline int run_delalloc_nocow(struct inode *inode,
1427 				       struct page *locked_page,
1428 				       const u64 start, const u64 end,
1429 				       int *page_started, int force,
1430 				       unsigned long *nr_written)
1431 {
1432 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1433 	struct btrfs_root *root = BTRFS_I(inode)->root;
1434 	struct btrfs_path *path;
1435 	u64 cow_start = (u64)-1;
1436 	u64 cur_offset = start;
1437 	int ret;
1438 	bool check_prev = true;
1439 	const bool freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
1440 	u64 ino = btrfs_ino(BTRFS_I(inode));
1441 	bool nocow = false;
1442 	u64 disk_bytenr = 0;
1443 
1444 	path = btrfs_alloc_path();
1445 	if (!path) {
1446 		extent_clear_unlock_delalloc(inode, start, end, locked_page,
1447 					     EXTENT_LOCKED | EXTENT_DELALLOC |
1448 					     EXTENT_DO_ACCOUNTING |
1449 					     EXTENT_DEFRAG, PAGE_UNLOCK |
1450 					     PAGE_CLEAR_DIRTY |
1451 					     PAGE_SET_WRITEBACK |
1452 					     PAGE_END_WRITEBACK);
1453 		return -ENOMEM;
1454 	}
1455 
1456 	while (1) {
1457 		struct btrfs_key found_key;
1458 		struct btrfs_file_extent_item *fi;
1459 		struct extent_buffer *leaf;
1460 		u64 extent_end;
1461 		u64 extent_offset;
1462 		u64 num_bytes = 0;
1463 		u64 disk_num_bytes;
1464 		u64 ram_bytes;
1465 		int extent_type;
1466 
1467 		nocow = false;
1468 
1469 		ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1470 					       cur_offset, 0);
1471 		if (ret < 0)
1472 			goto error;
1473 
1474 		/*
1475 		 * If there is no extent for our range when doing the initial
1476 		 * search, then go back to the previous slot as it will be the
1477 		 * one containing the search offset
1478 		 */
1479 		if (ret > 0 && path->slots[0] > 0 && check_prev) {
1480 			leaf = path->nodes[0];
1481 			btrfs_item_key_to_cpu(leaf, &found_key,
1482 					      path->slots[0] - 1);
1483 			if (found_key.objectid == ino &&
1484 			    found_key.type == BTRFS_EXTENT_DATA_KEY)
1485 				path->slots[0]--;
1486 		}
1487 		check_prev = false;
1488 next_slot:
1489 		/* Go to next leaf if we have exhausted the current one */
1490 		leaf = path->nodes[0];
1491 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1492 			ret = btrfs_next_leaf(root, path);
1493 			if (ret < 0) {
1494 				if (cow_start != (u64)-1)
1495 					cur_offset = cow_start;
1496 				goto error;
1497 			}
1498 			if (ret > 0)
1499 				break;
1500 			leaf = path->nodes[0];
1501 		}
1502 
1503 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1504 
1505 		/* Didn't find anything for our INO */
1506 		if (found_key.objectid > ino)
1507 			break;
1508 		/*
1509 		 * Keep searching until we find an EXTENT_ITEM or there are no
1510 		 * more extents for this inode
1511 		 */
1512 		if (WARN_ON_ONCE(found_key.objectid < ino) ||
1513 		    found_key.type < BTRFS_EXTENT_DATA_KEY) {
1514 			path->slots[0]++;
1515 			goto next_slot;
1516 		}
1517 
1518 		/* Found key is not EXTENT_DATA_KEY or starts after req range */
1519 		if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1520 		    found_key.offset > end)
1521 			break;
1522 
1523 		/*
1524 		 * If the found extent starts after requested offset, then
1525 		 * adjust extent_end to be right before this extent begins
1526 		 */
1527 		if (found_key.offset > cur_offset) {
1528 			extent_end = found_key.offset;
1529 			extent_type = 0;
1530 			goto out_check;
1531 		}
1532 
1533 		/*
1534 		 * Found extent which begins before our range and potentially
1535 		 * intersect it
1536 		 */
1537 		fi = btrfs_item_ptr(leaf, path->slots[0],
1538 				    struct btrfs_file_extent_item);
1539 		extent_type = btrfs_file_extent_type(leaf, fi);
1540 
1541 		ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1542 		if (extent_type == BTRFS_FILE_EXTENT_REG ||
1543 		    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1544 			disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1545 			extent_offset = btrfs_file_extent_offset(leaf, fi);
1546 			extent_end = found_key.offset +
1547 				btrfs_file_extent_num_bytes(leaf, fi);
1548 			disk_num_bytes =
1549 				btrfs_file_extent_disk_num_bytes(leaf, fi);
1550 			/*
1551 			 * If the extent we got ends before our current offset,
1552 			 * skip to the next extent.
1553 			 */
1554 			if (extent_end <= cur_offset) {
1555 				path->slots[0]++;
1556 				goto next_slot;
1557 			}
1558 			/* Skip holes */
1559 			if (disk_bytenr == 0)
1560 				goto out_check;
1561 			/* Skip compressed/encrypted/encoded extents */
1562 			if (btrfs_file_extent_compression(leaf, fi) ||
1563 			    btrfs_file_extent_encryption(leaf, fi) ||
1564 			    btrfs_file_extent_other_encoding(leaf, fi))
1565 				goto out_check;
1566 			/*
1567 			 * If extent is created before the last volume's snapshot
1568 			 * this implies the extent is shared, hence we can't do
1569 			 * nocow. This is the same check as in
1570 			 * btrfs_cross_ref_exist but without calling
1571 			 * btrfs_search_slot.
1572 			 */
1573 			if (!freespace_inode &&
1574 			    btrfs_file_extent_generation(leaf, fi) <=
1575 			    btrfs_root_last_snapshot(&root->root_item))
1576 				goto out_check;
1577 			if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1578 				goto out_check;
1579 			/* If extent is RO, we must COW it */
1580 			if (btrfs_extent_readonly(fs_info, disk_bytenr))
1581 				goto out_check;
1582 			ret = btrfs_cross_ref_exist(root, ino,
1583 						    found_key.offset -
1584 						    extent_offset, disk_bytenr);
1585 			if (ret) {
1586 				/*
1587 				 * ret could be -EIO if the above fails to read
1588 				 * metadata.
1589 				 */
1590 				if (ret < 0) {
1591 					if (cow_start != (u64)-1)
1592 						cur_offset = cow_start;
1593 					goto error;
1594 				}
1595 
1596 				WARN_ON_ONCE(freespace_inode);
1597 				goto out_check;
1598 			}
1599 			disk_bytenr += extent_offset;
1600 			disk_bytenr += cur_offset - found_key.offset;
1601 			num_bytes = min(end + 1, extent_end) - cur_offset;
1602 			/*
1603 			 * If there are pending snapshots for this root, we
1604 			 * fall into common COW way
1605 			 */
1606 			if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1607 				goto out_check;
1608 			/*
1609 			 * force cow if csum exists in the range.
1610 			 * this ensure that csum for a given extent are
1611 			 * either valid or do not exist.
1612 			 */
1613 			ret = csum_exist_in_range(fs_info, disk_bytenr,
1614 						  num_bytes);
1615 			if (ret) {
1616 				/*
1617 				 * ret could be -EIO if the above fails to read
1618 				 * metadata.
1619 				 */
1620 				if (ret < 0) {
1621 					if (cow_start != (u64)-1)
1622 						cur_offset = cow_start;
1623 					goto error;
1624 				}
1625 				WARN_ON_ONCE(freespace_inode);
1626 				goto out_check;
1627 			}
1628 			if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1629 				goto out_check;
1630 			nocow = true;
1631 		} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1632 			extent_end = found_key.offset + ram_bytes;
1633 			extent_end = ALIGN(extent_end, fs_info->sectorsize);
1634 			/* Skip extents outside of our requested range */
1635 			if (extent_end <= start) {
1636 				path->slots[0]++;
1637 				goto next_slot;
1638 			}
1639 		} else {
1640 			/* If this triggers then we have a memory corruption */
1641 			BUG();
1642 		}
1643 out_check:
1644 		/*
1645 		 * If nocow is false then record the beginning of the range
1646 		 * that needs to be COWed
1647 		 */
1648 		if (!nocow) {
1649 			if (cow_start == (u64)-1)
1650 				cow_start = cur_offset;
1651 			cur_offset = extent_end;
1652 			if (cur_offset > end)
1653 				break;
1654 			path->slots[0]++;
1655 			goto next_slot;
1656 		}
1657 
1658 		btrfs_release_path(path);
1659 
1660 		/*
1661 		 * COW range from cow_start to found_key.offset - 1. As the key
1662 		 * will contain the beginning of the first extent that can be
1663 		 * NOCOW, following one which needs to be COW'ed
1664 		 */
1665 		if (cow_start != (u64)-1) {
1666 			ret = fallback_to_cow(inode, locked_page, cow_start,
1667 					      found_key.offset - 1,
1668 					      page_started, nr_written);
1669 			if (ret) {
1670 				if (nocow)
1671 					btrfs_dec_nocow_writers(fs_info,
1672 								disk_bytenr);
1673 				goto error;
1674 			}
1675 			cow_start = (u64)-1;
1676 		}
1677 
1678 		if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1679 			u64 orig_start = found_key.offset - extent_offset;
1680 			struct extent_map *em;
1681 
1682 			em = create_io_em(inode, cur_offset, num_bytes,
1683 					  orig_start,
1684 					  disk_bytenr, /* block_start */
1685 					  num_bytes, /* block_len */
1686 					  disk_num_bytes, /* orig_block_len */
1687 					  ram_bytes, BTRFS_COMPRESS_NONE,
1688 					  BTRFS_ORDERED_PREALLOC);
1689 			if (IS_ERR(em)) {
1690 				if (nocow)
1691 					btrfs_dec_nocow_writers(fs_info,
1692 								disk_bytenr);
1693 				ret = PTR_ERR(em);
1694 				goto error;
1695 			}
1696 			free_extent_map(em);
1697 			ret = btrfs_add_ordered_extent(inode, cur_offset,
1698 						       disk_bytenr, num_bytes,
1699 						       num_bytes,
1700 						       BTRFS_ORDERED_PREALLOC);
1701 			if (ret) {
1702 				btrfs_drop_extent_cache(BTRFS_I(inode),
1703 							cur_offset,
1704 							cur_offset + num_bytes - 1,
1705 							0);
1706 				goto error;
1707 			}
1708 		} else {
1709 			ret = btrfs_add_ordered_extent(inode, cur_offset,
1710 						       disk_bytenr, num_bytes,
1711 						       num_bytes,
1712 						       BTRFS_ORDERED_NOCOW);
1713 			if (ret)
1714 				goto error;
1715 		}
1716 
1717 		if (nocow)
1718 			btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1719 		nocow = false;
1720 
1721 		if (root->root_key.objectid ==
1722 		    BTRFS_DATA_RELOC_TREE_OBJECTID)
1723 			/*
1724 			 * Error handled later, as we must prevent
1725 			 * extent_clear_unlock_delalloc() in error handler
1726 			 * from freeing metadata of created ordered extent.
1727 			 */
1728 			ret = btrfs_reloc_clone_csums(inode, cur_offset,
1729 						      num_bytes);
1730 
1731 		extent_clear_unlock_delalloc(inode, cur_offset,
1732 					     cur_offset + num_bytes - 1,
1733 					     locked_page, EXTENT_LOCKED |
1734 					     EXTENT_DELALLOC |
1735 					     EXTENT_CLEAR_DATA_RESV,
1736 					     PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1737 
1738 		cur_offset = extent_end;
1739 
1740 		/*
1741 		 * btrfs_reloc_clone_csums() error, now we're OK to call error
1742 		 * handler, as metadata for created ordered extent will only
1743 		 * be freed by btrfs_finish_ordered_io().
1744 		 */
1745 		if (ret)
1746 			goto error;
1747 		if (cur_offset > end)
1748 			break;
1749 	}
1750 	btrfs_release_path(path);
1751 
1752 	if (cur_offset <= end && cow_start == (u64)-1)
1753 		cow_start = cur_offset;
1754 
1755 	if (cow_start != (u64)-1) {
1756 		cur_offset = end;
1757 		ret = fallback_to_cow(inode, locked_page, cow_start, end,
1758 				      page_started, nr_written);
1759 		if (ret)
1760 			goto error;
1761 	}
1762 
1763 error:
1764 	if (nocow)
1765 		btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1766 
1767 	if (ret && cur_offset < end)
1768 		extent_clear_unlock_delalloc(inode, cur_offset, end,
1769 					     locked_page, EXTENT_LOCKED |
1770 					     EXTENT_DELALLOC | EXTENT_DEFRAG |
1771 					     EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1772 					     PAGE_CLEAR_DIRTY |
1773 					     PAGE_SET_WRITEBACK |
1774 					     PAGE_END_WRITEBACK);
1775 	btrfs_free_path(path);
1776 	return ret;
1777 }
1778 
1779 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1780 {
1781 
1782 	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1783 	    !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1784 		return 0;
1785 
1786 	/*
1787 	 * @defrag_bytes is a hint value, no spinlock held here,
1788 	 * if is not zero, it means the file is defragging.
1789 	 * Force cow if given extent needs to be defragged.
1790 	 */
1791 	if (BTRFS_I(inode)->defrag_bytes &&
1792 	    test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1793 			   EXTENT_DEFRAG, 0, NULL))
1794 		return 1;
1795 
1796 	return 0;
1797 }
1798 
1799 /*
1800  * Function to process delayed allocation (create CoW) for ranges which are
1801  * being touched for the first time.
1802  */
1803 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1804 		u64 start, u64 end, int *page_started, unsigned long *nr_written,
1805 		struct writeback_control *wbc)
1806 {
1807 	int ret;
1808 	int force_cow = need_force_cow(inode, start, end);
1809 
1810 	if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1811 		ret = run_delalloc_nocow(inode, locked_page, start, end,
1812 					 page_started, 1, nr_written);
1813 	} else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1814 		ret = run_delalloc_nocow(inode, locked_page, start, end,
1815 					 page_started, 0, nr_written);
1816 	} else if (!inode_can_compress(inode) ||
1817 		   !inode_need_compress(inode, start, end)) {
1818 		ret = cow_file_range(inode, locked_page, start, end,
1819 				      page_started, nr_written, 1);
1820 	} else {
1821 		set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1822 			&BTRFS_I(inode)->runtime_flags);
1823 		ret = cow_file_range_async(inode, wbc, locked_page, start, end,
1824 					   page_started, nr_written);
1825 	}
1826 	if (ret)
1827 		btrfs_cleanup_ordered_extents(inode, locked_page, start,
1828 					      end - start + 1);
1829 	return ret;
1830 }
1831 
1832 void btrfs_split_delalloc_extent(struct inode *inode,
1833 				 struct extent_state *orig, u64 split)
1834 {
1835 	u64 size;
1836 
1837 	/* not delalloc, ignore it */
1838 	if (!(orig->state & EXTENT_DELALLOC))
1839 		return;
1840 
1841 	size = orig->end - orig->start + 1;
1842 	if (size > BTRFS_MAX_EXTENT_SIZE) {
1843 		u32 num_extents;
1844 		u64 new_size;
1845 
1846 		/*
1847 		 * See the explanation in btrfs_merge_delalloc_extent, the same
1848 		 * applies here, just in reverse.
1849 		 */
1850 		new_size = orig->end - split + 1;
1851 		num_extents = count_max_extents(new_size);
1852 		new_size = split - orig->start;
1853 		num_extents += count_max_extents(new_size);
1854 		if (count_max_extents(size) >= num_extents)
1855 			return;
1856 	}
1857 
1858 	spin_lock(&BTRFS_I(inode)->lock);
1859 	btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1860 	spin_unlock(&BTRFS_I(inode)->lock);
1861 }
1862 
1863 /*
1864  * Handle merged delayed allocation extents so we can keep track of new extents
1865  * that are just merged onto old extents, such as when we are doing sequential
1866  * writes, so we can properly account for the metadata space we'll need.
1867  */
1868 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1869 				 struct extent_state *other)
1870 {
1871 	u64 new_size, old_size;
1872 	u32 num_extents;
1873 
1874 	/* not delalloc, ignore it */
1875 	if (!(other->state & EXTENT_DELALLOC))
1876 		return;
1877 
1878 	if (new->start > other->start)
1879 		new_size = new->end - other->start + 1;
1880 	else
1881 		new_size = other->end - new->start + 1;
1882 
1883 	/* we're not bigger than the max, unreserve the space and go */
1884 	if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1885 		spin_lock(&BTRFS_I(inode)->lock);
1886 		btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1887 		spin_unlock(&BTRFS_I(inode)->lock);
1888 		return;
1889 	}
1890 
1891 	/*
1892 	 * We have to add up either side to figure out how many extents were
1893 	 * accounted for before we merged into one big extent.  If the number of
1894 	 * extents we accounted for is <= the amount we need for the new range
1895 	 * then we can return, otherwise drop.  Think of it like this
1896 	 *
1897 	 * [ 4k][MAX_SIZE]
1898 	 *
1899 	 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1900 	 * need 2 outstanding extents, on one side we have 1 and the other side
1901 	 * we have 1 so they are == and we can return.  But in this case
1902 	 *
1903 	 * [MAX_SIZE+4k][MAX_SIZE+4k]
1904 	 *
1905 	 * Each range on their own accounts for 2 extents, but merged together
1906 	 * they are only 3 extents worth of accounting, so we need to drop in
1907 	 * this case.
1908 	 */
1909 	old_size = other->end - other->start + 1;
1910 	num_extents = count_max_extents(old_size);
1911 	old_size = new->end - new->start + 1;
1912 	num_extents += count_max_extents(old_size);
1913 	if (count_max_extents(new_size) >= num_extents)
1914 		return;
1915 
1916 	spin_lock(&BTRFS_I(inode)->lock);
1917 	btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1918 	spin_unlock(&BTRFS_I(inode)->lock);
1919 }
1920 
1921 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1922 				      struct inode *inode)
1923 {
1924 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1925 
1926 	spin_lock(&root->delalloc_lock);
1927 	if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1928 		list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1929 			      &root->delalloc_inodes);
1930 		set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1931 			&BTRFS_I(inode)->runtime_flags);
1932 		root->nr_delalloc_inodes++;
1933 		if (root->nr_delalloc_inodes == 1) {
1934 			spin_lock(&fs_info->delalloc_root_lock);
1935 			BUG_ON(!list_empty(&root->delalloc_root));
1936 			list_add_tail(&root->delalloc_root,
1937 				      &fs_info->delalloc_roots);
1938 			spin_unlock(&fs_info->delalloc_root_lock);
1939 		}
1940 	}
1941 	spin_unlock(&root->delalloc_lock);
1942 }
1943 
1944 
1945 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1946 				struct btrfs_inode *inode)
1947 {
1948 	struct btrfs_fs_info *fs_info = root->fs_info;
1949 
1950 	if (!list_empty(&inode->delalloc_inodes)) {
1951 		list_del_init(&inode->delalloc_inodes);
1952 		clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1953 			  &inode->runtime_flags);
1954 		root->nr_delalloc_inodes--;
1955 		if (!root->nr_delalloc_inodes) {
1956 			ASSERT(list_empty(&root->delalloc_inodes));
1957 			spin_lock(&fs_info->delalloc_root_lock);
1958 			BUG_ON(list_empty(&root->delalloc_root));
1959 			list_del_init(&root->delalloc_root);
1960 			spin_unlock(&fs_info->delalloc_root_lock);
1961 		}
1962 	}
1963 }
1964 
1965 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1966 				     struct btrfs_inode *inode)
1967 {
1968 	spin_lock(&root->delalloc_lock);
1969 	__btrfs_del_delalloc_inode(root, inode);
1970 	spin_unlock(&root->delalloc_lock);
1971 }
1972 
1973 /*
1974  * Properly track delayed allocation bytes in the inode and to maintain the
1975  * list of inodes that have pending delalloc work to be done.
1976  */
1977 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1978 			       unsigned *bits)
1979 {
1980 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1981 
1982 	if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1983 		WARN_ON(1);
1984 	/*
1985 	 * set_bit and clear bit hooks normally require _irqsave/restore
1986 	 * but in this case, we are only testing for the DELALLOC
1987 	 * bit, which is only set or cleared with irqs on
1988 	 */
1989 	if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1990 		struct btrfs_root *root = BTRFS_I(inode)->root;
1991 		u64 len = state->end + 1 - state->start;
1992 		u32 num_extents = count_max_extents(len);
1993 		bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1994 
1995 		spin_lock(&BTRFS_I(inode)->lock);
1996 		btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1997 		spin_unlock(&BTRFS_I(inode)->lock);
1998 
1999 		/* For sanity tests */
2000 		if (btrfs_is_testing(fs_info))
2001 			return;
2002 
2003 		percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2004 					 fs_info->delalloc_batch);
2005 		spin_lock(&BTRFS_I(inode)->lock);
2006 		BTRFS_I(inode)->delalloc_bytes += len;
2007 		if (*bits & EXTENT_DEFRAG)
2008 			BTRFS_I(inode)->defrag_bytes += len;
2009 		if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2010 					 &BTRFS_I(inode)->runtime_flags))
2011 			btrfs_add_delalloc_inodes(root, inode);
2012 		spin_unlock(&BTRFS_I(inode)->lock);
2013 	}
2014 
2015 	if (!(state->state & EXTENT_DELALLOC_NEW) &&
2016 	    (*bits & EXTENT_DELALLOC_NEW)) {
2017 		spin_lock(&BTRFS_I(inode)->lock);
2018 		BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2019 			state->start;
2020 		spin_unlock(&BTRFS_I(inode)->lock);
2021 	}
2022 }
2023 
2024 /*
2025  * Once a range is no longer delalloc this function ensures that proper
2026  * accounting happens.
2027  */
2028 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2029 				 struct extent_state *state, unsigned *bits)
2030 {
2031 	struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2032 	struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2033 	u64 len = state->end + 1 - state->start;
2034 	u32 num_extents = count_max_extents(len);
2035 
2036 	if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
2037 		spin_lock(&inode->lock);
2038 		inode->defrag_bytes -= len;
2039 		spin_unlock(&inode->lock);
2040 	}
2041 
2042 	/*
2043 	 * set_bit and clear bit hooks normally require _irqsave/restore
2044 	 * but in this case, we are only testing for the DELALLOC
2045 	 * bit, which is only set or cleared with irqs on
2046 	 */
2047 	if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2048 		struct btrfs_root *root = inode->root;
2049 		bool do_list = !btrfs_is_free_space_inode(inode);
2050 
2051 		spin_lock(&inode->lock);
2052 		btrfs_mod_outstanding_extents(inode, -num_extents);
2053 		spin_unlock(&inode->lock);
2054 
2055 		/*
2056 		 * We don't reserve metadata space for space cache inodes so we
2057 		 * don't need to call delalloc_release_metadata if there is an
2058 		 * error.
2059 		 */
2060 		if (*bits & EXTENT_CLEAR_META_RESV &&
2061 		    root != fs_info->tree_root)
2062 			btrfs_delalloc_release_metadata(inode, len, false);
2063 
2064 		/* For sanity tests. */
2065 		if (btrfs_is_testing(fs_info))
2066 			return;
2067 
2068 		if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
2069 		    do_list && !(state->state & EXTENT_NORESERVE) &&
2070 		    (*bits & EXTENT_CLEAR_DATA_RESV))
2071 			btrfs_free_reserved_data_space_noquota(
2072 					&inode->vfs_inode,
2073 					state->start, len);
2074 
2075 		percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2076 					 fs_info->delalloc_batch);
2077 		spin_lock(&inode->lock);
2078 		inode->delalloc_bytes -= len;
2079 		if (do_list && inode->delalloc_bytes == 0 &&
2080 		    test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2081 					&inode->runtime_flags))
2082 			btrfs_del_delalloc_inode(root, inode);
2083 		spin_unlock(&inode->lock);
2084 	}
2085 
2086 	if ((state->state & EXTENT_DELALLOC_NEW) &&
2087 	    (*bits & EXTENT_DELALLOC_NEW)) {
2088 		spin_lock(&inode->lock);
2089 		ASSERT(inode->new_delalloc_bytes >= len);
2090 		inode->new_delalloc_bytes -= len;
2091 		spin_unlock(&inode->lock);
2092 	}
2093 }
2094 
2095 /*
2096  * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2097  * in a chunk's stripe. This function ensures that bios do not span a
2098  * stripe/chunk
2099  *
2100  * @page - The page we are about to add to the bio
2101  * @size - size we want to add to the bio
2102  * @bio - bio we want to ensure is smaller than a stripe
2103  * @bio_flags - flags of the bio
2104  *
2105  * return 1 if page cannot be added to the bio
2106  * return 0 if page can be added to the bio
2107  * return error otherwise
2108  */
2109 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2110 			     unsigned long bio_flags)
2111 {
2112 	struct inode *inode = page->mapping->host;
2113 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2114 	u64 logical = (u64)bio->bi_iter.bi_sector << 9;
2115 	u64 length = 0;
2116 	u64 map_length;
2117 	int ret;
2118 	struct btrfs_io_geometry geom;
2119 
2120 	if (bio_flags & EXTENT_BIO_COMPRESSED)
2121 		return 0;
2122 
2123 	length = bio->bi_iter.bi_size;
2124 	map_length = length;
2125 	ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length,
2126 				    &geom);
2127 	if (ret < 0)
2128 		return ret;
2129 
2130 	if (geom.len < length + size)
2131 		return 1;
2132 	return 0;
2133 }
2134 
2135 /*
2136  * in order to insert checksums into the metadata in large chunks,
2137  * we wait until bio submission time.   All the pages in the bio are
2138  * checksummed and sums are attached onto the ordered extent record.
2139  *
2140  * At IO completion time the cums attached on the ordered extent record
2141  * are inserted into the btree
2142  */
2143 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
2144 				    u64 bio_offset)
2145 {
2146 	struct inode *inode = private_data;
2147 	blk_status_t ret = 0;
2148 
2149 	ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2150 	BUG_ON(ret); /* -ENOMEM */
2151 	return 0;
2152 }
2153 
2154 /*
2155  * extent_io.c submission hook. This does the right thing for csum calculation
2156  * on write, or reading the csums from the tree before a read.
2157  *
2158  * Rules about async/sync submit,
2159  * a) read:				sync submit
2160  *
2161  * b) write without checksum:		sync submit
2162  *
2163  * c) write with checksum:
2164  *    c-1) if bio is issued by fsync:	sync submit
2165  *         (sync_writers != 0)
2166  *
2167  *    c-2) if root is reloc root:	sync submit
2168  *         (only in case of buffered IO)
2169  *
2170  *    c-3) otherwise:			async submit
2171  */
2172 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
2173 					  int mirror_num,
2174 					  unsigned long bio_flags)
2175 
2176 {
2177 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2178 	struct btrfs_root *root = BTRFS_I(inode)->root;
2179 	enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2180 	blk_status_t ret = 0;
2181 	int skip_sum;
2182 	int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2183 
2184 	skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2185 
2186 	if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2187 		metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2188 
2189 	if (bio_op(bio) != REQ_OP_WRITE) {
2190 		ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2191 		if (ret)
2192 			goto out;
2193 
2194 		if (bio_flags & EXTENT_BIO_COMPRESSED) {
2195 			ret = btrfs_submit_compressed_read(inode, bio,
2196 							   mirror_num,
2197 							   bio_flags);
2198 			goto out;
2199 		} else if (!skip_sum) {
2200 			ret = btrfs_lookup_bio_sums(inode, bio, (u64)-1, NULL);
2201 			if (ret)
2202 				goto out;
2203 		}
2204 		goto mapit;
2205 	} else if (async && !skip_sum) {
2206 		/* csum items have already been cloned */
2207 		if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2208 			goto mapit;
2209 		/* we're doing a write, do the async checksumming */
2210 		ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2211 					  0, inode, btrfs_submit_bio_start);
2212 		goto out;
2213 	} else if (!skip_sum) {
2214 		ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2215 		if (ret)
2216 			goto out;
2217 	}
2218 
2219 mapit:
2220 	ret = btrfs_map_bio(fs_info, bio, mirror_num);
2221 
2222 out:
2223 	if (ret) {
2224 		bio->bi_status = ret;
2225 		bio_endio(bio);
2226 	}
2227 	return ret;
2228 }
2229 
2230 /*
2231  * given a list of ordered sums record them in the inode.  This happens
2232  * at IO completion time based on sums calculated at bio submission time.
2233  */
2234 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2235 			     struct inode *inode, struct list_head *list)
2236 {
2237 	struct btrfs_ordered_sum *sum;
2238 	int ret;
2239 
2240 	list_for_each_entry(sum, list, list) {
2241 		trans->adding_csums = true;
2242 		ret = btrfs_csum_file_blocks(trans,
2243 		       BTRFS_I(inode)->root->fs_info->csum_root, sum);
2244 		trans->adding_csums = false;
2245 		if (ret)
2246 			return ret;
2247 	}
2248 	return 0;
2249 }
2250 
2251 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2252 			      unsigned int extra_bits,
2253 			      struct extent_state **cached_state)
2254 {
2255 	WARN_ON(PAGE_ALIGNED(end));
2256 	return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2257 				   extra_bits, cached_state);
2258 }
2259 
2260 /* see btrfs_writepage_start_hook for details on why this is required */
2261 struct btrfs_writepage_fixup {
2262 	struct page *page;
2263 	struct inode *inode;
2264 	struct btrfs_work work;
2265 };
2266 
2267 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2268 {
2269 	struct btrfs_writepage_fixup *fixup;
2270 	struct btrfs_ordered_extent *ordered;
2271 	struct extent_state *cached_state = NULL;
2272 	struct extent_changeset *data_reserved = NULL;
2273 	struct page *page;
2274 	struct inode *inode;
2275 	u64 page_start;
2276 	u64 page_end;
2277 	int ret = 0;
2278 	bool free_delalloc_space = true;
2279 
2280 	fixup = container_of(work, struct btrfs_writepage_fixup, work);
2281 	page = fixup->page;
2282 	inode = fixup->inode;
2283 	page_start = page_offset(page);
2284 	page_end = page_offset(page) + PAGE_SIZE - 1;
2285 
2286 	/*
2287 	 * This is similar to page_mkwrite, we need to reserve the space before
2288 	 * we take the page lock.
2289 	 */
2290 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2291 					   PAGE_SIZE);
2292 again:
2293 	lock_page(page);
2294 
2295 	/*
2296 	 * Before we queued this fixup, we took a reference on the page.
2297 	 * page->mapping may go NULL, but it shouldn't be moved to a different
2298 	 * address space.
2299 	 */
2300 	if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2301 		/*
2302 		 * Unfortunately this is a little tricky, either
2303 		 *
2304 		 * 1) We got here and our page had already been dealt with and
2305 		 *    we reserved our space, thus ret == 0, so we need to just
2306 		 *    drop our space reservation and bail.  This can happen the
2307 		 *    first time we come into the fixup worker, or could happen
2308 		 *    while waiting for the ordered extent.
2309 		 * 2) Our page was already dealt with, but we happened to get an
2310 		 *    ENOSPC above from the btrfs_delalloc_reserve_space.  In
2311 		 *    this case we obviously don't have anything to release, but
2312 		 *    because the page was already dealt with we don't want to
2313 		 *    mark the page with an error, so make sure we're resetting
2314 		 *    ret to 0.  This is why we have this check _before_ the ret
2315 		 *    check, because we do not want to have a surprise ENOSPC
2316 		 *    when the page was already properly dealt with.
2317 		 */
2318 		if (!ret) {
2319 			btrfs_delalloc_release_extents(BTRFS_I(inode),
2320 						       PAGE_SIZE);
2321 			btrfs_delalloc_release_space(inode, data_reserved,
2322 						     page_start, PAGE_SIZE,
2323 						     true);
2324 		}
2325 		ret = 0;
2326 		goto out_page;
2327 	}
2328 
2329 	/*
2330 	 * We can't mess with the page state unless it is locked, so now that
2331 	 * it is locked bail if we failed to make our space reservation.
2332 	 */
2333 	if (ret)
2334 		goto out_page;
2335 
2336 	lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2337 			 &cached_state);
2338 
2339 	/* already ordered? We're done */
2340 	if (PagePrivate2(page))
2341 		goto out_reserved;
2342 
2343 	ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2344 					PAGE_SIZE);
2345 	if (ordered) {
2346 		unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2347 				     page_end, &cached_state);
2348 		unlock_page(page);
2349 		btrfs_start_ordered_extent(inode, ordered, 1);
2350 		btrfs_put_ordered_extent(ordered);
2351 		goto again;
2352 	}
2353 
2354 	ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2355 					&cached_state);
2356 	if (ret)
2357 		goto out_reserved;
2358 
2359 	/*
2360 	 * Everything went as planned, we're now the owner of a dirty page with
2361 	 * delayed allocation bits set and space reserved for our COW
2362 	 * destination.
2363 	 *
2364 	 * The page was dirty when we started, nothing should have cleaned it.
2365 	 */
2366 	BUG_ON(!PageDirty(page));
2367 	free_delalloc_space = false;
2368 out_reserved:
2369 	btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2370 	if (free_delalloc_space)
2371 		btrfs_delalloc_release_space(inode, data_reserved, page_start,
2372 					     PAGE_SIZE, true);
2373 	unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2374 			     &cached_state);
2375 out_page:
2376 	if (ret) {
2377 		/*
2378 		 * We hit ENOSPC or other errors.  Update the mapping and page
2379 		 * to reflect the errors and clean the page.
2380 		 */
2381 		mapping_set_error(page->mapping, ret);
2382 		end_extent_writepage(page, ret, page_start, page_end);
2383 		clear_page_dirty_for_io(page);
2384 		SetPageError(page);
2385 	}
2386 	ClearPageChecked(page);
2387 	unlock_page(page);
2388 	put_page(page);
2389 	kfree(fixup);
2390 	extent_changeset_free(data_reserved);
2391 	/*
2392 	 * As a precaution, do a delayed iput in case it would be the last iput
2393 	 * that could need flushing space. Recursing back to fixup worker would
2394 	 * deadlock.
2395 	 */
2396 	btrfs_add_delayed_iput(inode);
2397 }
2398 
2399 /*
2400  * There are a few paths in the higher layers of the kernel that directly
2401  * set the page dirty bit without asking the filesystem if it is a
2402  * good idea.  This causes problems because we want to make sure COW
2403  * properly happens and the data=ordered rules are followed.
2404  *
2405  * In our case any range that doesn't have the ORDERED bit set
2406  * hasn't been properly setup for IO.  We kick off an async process
2407  * to fix it up.  The async helper will wait for ordered extents, set
2408  * the delalloc bit and make it safe to write the page.
2409  */
2410 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2411 {
2412 	struct inode *inode = page->mapping->host;
2413 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2414 	struct btrfs_writepage_fixup *fixup;
2415 
2416 	/* this page is properly in the ordered list */
2417 	if (TestClearPagePrivate2(page))
2418 		return 0;
2419 
2420 	/*
2421 	 * PageChecked is set below when we create a fixup worker for this page,
2422 	 * don't try to create another one if we're already PageChecked()
2423 	 *
2424 	 * The extent_io writepage code will redirty the page if we send back
2425 	 * EAGAIN.
2426 	 */
2427 	if (PageChecked(page))
2428 		return -EAGAIN;
2429 
2430 	fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2431 	if (!fixup)
2432 		return -EAGAIN;
2433 
2434 	/*
2435 	 * We are already holding a reference to this inode from
2436 	 * write_cache_pages.  We need to hold it because the space reservation
2437 	 * takes place outside of the page lock, and we can't trust
2438 	 * page->mapping outside of the page lock.
2439 	 */
2440 	ihold(inode);
2441 	SetPageChecked(page);
2442 	get_page(page);
2443 	btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2444 	fixup->page = page;
2445 	fixup->inode = inode;
2446 	btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2447 
2448 	return -EAGAIN;
2449 }
2450 
2451 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2452 				       struct inode *inode, u64 file_pos,
2453 				       u64 disk_bytenr, u64 disk_num_bytes,
2454 				       u64 num_bytes, u64 ram_bytes,
2455 				       u8 compression, u8 encryption,
2456 				       u16 other_encoding, int extent_type)
2457 {
2458 	struct btrfs_root *root = BTRFS_I(inode)->root;
2459 	struct btrfs_file_extent_item *fi;
2460 	struct btrfs_path *path;
2461 	struct extent_buffer *leaf;
2462 	struct btrfs_key ins;
2463 	u64 qg_released;
2464 	int extent_inserted = 0;
2465 	int ret;
2466 
2467 	path = btrfs_alloc_path();
2468 	if (!path)
2469 		return -ENOMEM;
2470 
2471 	/*
2472 	 * we may be replacing one extent in the tree with another.
2473 	 * The new extent is pinned in the extent map, and we don't want
2474 	 * to drop it from the cache until it is completely in the btree.
2475 	 *
2476 	 * So, tell btrfs_drop_extents to leave this extent in the cache.
2477 	 * the caller is expected to unpin it and allow it to be merged
2478 	 * with the others.
2479 	 */
2480 	ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2481 				   file_pos + num_bytes, NULL, 0,
2482 				   1, sizeof(*fi), &extent_inserted);
2483 	if (ret)
2484 		goto out;
2485 
2486 	if (!extent_inserted) {
2487 		ins.objectid = btrfs_ino(BTRFS_I(inode));
2488 		ins.offset = file_pos;
2489 		ins.type = BTRFS_EXTENT_DATA_KEY;
2490 
2491 		path->leave_spinning = 1;
2492 		ret = btrfs_insert_empty_item(trans, root, path, &ins,
2493 					      sizeof(*fi));
2494 		if (ret)
2495 			goto out;
2496 	}
2497 	leaf = path->nodes[0];
2498 	fi = btrfs_item_ptr(leaf, path->slots[0],
2499 			    struct btrfs_file_extent_item);
2500 	btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2501 	btrfs_set_file_extent_type(leaf, fi, extent_type);
2502 	btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2503 	btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2504 	btrfs_set_file_extent_offset(leaf, fi, 0);
2505 	btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2506 	btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2507 	btrfs_set_file_extent_compression(leaf, fi, compression);
2508 	btrfs_set_file_extent_encryption(leaf, fi, encryption);
2509 	btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2510 
2511 	btrfs_mark_buffer_dirty(leaf);
2512 	btrfs_release_path(path);
2513 
2514 	inode_add_bytes(inode, num_bytes);
2515 
2516 	ins.objectid = disk_bytenr;
2517 	ins.offset = disk_num_bytes;
2518 	ins.type = BTRFS_EXTENT_ITEM_KEY;
2519 
2520 	ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), file_pos,
2521 						ram_bytes);
2522 	if (ret)
2523 		goto out;
2524 
2525 	/*
2526 	 * Release the reserved range from inode dirty range map, as it is
2527 	 * already moved into delayed_ref_head
2528 	 */
2529 	ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2530 	if (ret < 0)
2531 		goto out;
2532 	qg_released = ret;
2533 	ret = btrfs_alloc_reserved_file_extent(trans, root,
2534 					       btrfs_ino(BTRFS_I(inode)),
2535 					       file_pos, qg_released, &ins);
2536 out:
2537 	btrfs_free_path(path);
2538 
2539 	return ret;
2540 }
2541 
2542 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2543 					 u64 start, u64 len)
2544 {
2545 	struct btrfs_block_group *cache;
2546 
2547 	cache = btrfs_lookup_block_group(fs_info, start);
2548 	ASSERT(cache);
2549 
2550 	spin_lock(&cache->lock);
2551 	cache->delalloc_bytes -= len;
2552 	spin_unlock(&cache->lock);
2553 
2554 	btrfs_put_block_group(cache);
2555 }
2556 
2557 /* as ordered data IO finishes, this gets called so we can finish
2558  * an ordered extent if the range of bytes in the file it covers are
2559  * fully written.
2560  */
2561 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2562 {
2563 	struct inode *inode = ordered_extent->inode;
2564 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2565 	struct btrfs_root *root = BTRFS_I(inode)->root;
2566 	struct btrfs_trans_handle *trans = NULL;
2567 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2568 	struct extent_state *cached_state = NULL;
2569 	u64 start, end;
2570 	int compress_type = 0;
2571 	int ret = 0;
2572 	u64 logical_len = ordered_extent->num_bytes;
2573 	bool freespace_inode;
2574 	bool truncated = false;
2575 	bool range_locked = false;
2576 	bool clear_new_delalloc_bytes = false;
2577 	bool clear_reserved_extent = true;
2578 	unsigned int clear_bits;
2579 
2580 	start = ordered_extent->file_offset;
2581 	end = start + ordered_extent->num_bytes - 1;
2582 
2583 	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2584 	    !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2585 	    !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2586 		clear_new_delalloc_bytes = true;
2587 
2588 	freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
2589 
2590 	if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2591 		ret = -EIO;
2592 		goto out;
2593 	}
2594 
2595 	btrfs_free_io_failure_record(BTRFS_I(inode), start, end);
2596 
2597 	if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2598 		truncated = true;
2599 		logical_len = ordered_extent->truncated_len;
2600 		/* Truncated the entire extent, don't bother adding */
2601 		if (!logical_len)
2602 			goto out;
2603 	}
2604 
2605 	if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2606 		BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2607 
2608 		/*
2609 		 * For mwrite(mmap + memset to write) case, we still reserve
2610 		 * space for NOCOW range.
2611 		 * As NOCOW won't cause a new delayed ref, just free the space
2612 		 */
2613 		btrfs_qgroup_free_data(inode, NULL, start,
2614 				       ordered_extent->num_bytes);
2615 		btrfs_inode_safe_disk_i_size_write(inode, 0);
2616 		if (freespace_inode)
2617 			trans = btrfs_join_transaction_spacecache(root);
2618 		else
2619 			trans = btrfs_join_transaction(root);
2620 		if (IS_ERR(trans)) {
2621 			ret = PTR_ERR(trans);
2622 			trans = NULL;
2623 			goto out;
2624 		}
2625 		trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2626 		ret = btrfs_update_inode_fallback(trans, root, inode);
2627 		if (ret) /* -ENOMEM or corruption */
2628 			btrfs_abort_transaction(trans, ret);
2629 		goto out;
2630 	}
2631 
2632 	range_locked = true;
2633 	lock_extent_bits(io_tree, start, end, &cached_state);
2634 
2635 	if (freespace_inode)
2636 		trans = btrfs_join_transaction_spacecache(root);
2637 	else
2638 		trans = btrfs_join_transaction(root);
2639 	if (IS_ERR(trans)) {
2640 		ret = PTR_ERR(trans);
2641 		trans = NULL;
2642 		goto out;
2643 	}
2644 
2645 	trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2646 
2647 	if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2648 		compress_type = ordered_extent->compress_type;
2649 	if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2650 		BUG_ON(compress_type);
2651 		btrfs_qgroup_free_data(inode, NULL, start,
2652 				       ordered_extent->num_bytes);
2653 		ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
2654 						ordered_extent->file_offset,
2655 						ordered_extent->file_offset +
2656 						logical_len);
2657 	} else {
2658 		BUG_ON(root == fs_info->tree_root);
2659 		ret = insert_reserved_file_extent(trans, inode, start,
2660 						ordered_extent->disk_bytenr,
2661 						ordered_extent->disk_num_bytes,
2662 						logical_len, logical_len,
2663 						compress_type, 0, 0,
2664 						BTRFS_FILE_EXTENT_REG);
2665 		if (!ret) {
2666 			clear_reserved_extent = false;
2667 			btrfs_release_delalloc_bytes(fs_info,
2668 						ordered_extent->disk_bytenr,
2669 						ordered_extent->disk_num_bytes);
2670 		}
2671 	}
2672 	unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2673 			   ordered_extent->file_offset,
2674 			   ordered_extent->num_bytes, trans->transid);
2675 	if (ret < 0) {
2676 		btrfs_abort_transaction(trans, ret);
2677 		goto out;
2678 	}
2679 
2680 	ret = add_pending_csums(trans, inode, &ordered_extent->list);
2681 	if (ret) {
2682 		btrfs_abort_transaction(trans, ret);
2683 		goto out;
2684 	}
2685 
2686 	btrfs_inode_safe_disk_i_size_write(inode, 0);
2687 	ret = btrfs_update_inode_fallback(trans, root, inode);
2688 	if (ret) { /* -ENOMEM or corruption */
2689 		btrfs_abort_transaction(trans, ret);
2690 		goto out;
2691 	}
2692 	ret = 0;
2693 out:
2694 	clear_bits = EXTENT_DEFRAG;
2695 	if (range_locked)
2696 		clear_bits |= EXTENT_LOCKED;
2697 	if (clear_new_delalloc_bytes)
2698 		clear_bits |= EXTENT_DELALLOC_NEW;
2699 	clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits,
2700 			 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
2701 			 &cached_state);
2702 
2703 	if (trans)
2704 		btrfs_end_transaction(trans);
2705 
2706 	if (ret || truncated) {
2707 		u64 unwritten_start = start;
2708 
2709 		if (truncated)
2710 			unwritten_start += logical_len;
2711 		clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
2712 
2713 		/* Drop the cache for the part of the extent we didn't write. */
2714 		btrfs_drop_extent_cache(BTRFS_I(inode), unwritten_start, end, 0);
2715 
2716 		/*
2717 		 * If the ordered extent had an IOERR or something else went
2718 		 * wrong we need to return the space for this ordered extent
2719 		 * back to the allocator.  We only free the extent in the
2720 		 * truncated case if we didn't write out the extent at all.
2721 		 *
2722 		 * If we made it past insert_reserved_file_extent before we
2723 		 * errored out then we don't need to do this as the accounting
2724 		 * has already been done.
2725 		 */
2726 		if ((ret || !logical_len) &&
2727 		    clear_reserved_extent &&
2728 		    !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2729 		    !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2730 			/*
2731 			 * Discard the range before returning it back to the
2732 			 * free space pool
2733 			 */
2734 			if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
2735 				btrfs_discard_extent(fs_info,
2736 						ordered_extent->disk_bytenr,
2737 						ordered_extent->disk_num_bytes,
2738 						NULL);
2739 			btrfs_free_reserved_extent(fs_info,
2740 					ordered_extent->disk_bytenr,
2741 					ordered_extent->disk_num_bytes, 1);
2742 		}
2743 	}
2744 
2745 	/*
2746 	 * This needs to be done to make sure anybody waiting knows we are done
2747 	 * updating everything for this ordered extent.
2748 	 */
2749 	btrfs_remove_ordered_extent(inode, ordered_extent);
2750 
2751 	/* once for us */
2752 	btrfs_put_ordered_extent(ordered_extent);
2753 	/* once for the tree */
2754 	btrfs_put_ordered_extent(ordered_extent);
2755 
2756 	return ret;
2757 }
2758 
2759 static void finish_ordered_fn(struct btrfs_work *work)
2760 {
2761 	struct btrfs_ordered_extent *ordered_extent;
2762 	ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2763 	btrfs_finish_ordered_io(ordered_extent);
2764 }
2765 
2766 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
2767 					  u64 end, int uptodate)
2768 {
2769 	struct inode *inode = page->mapping->host;
2770 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2771 	struct btrfs_ordered_extent *ordered_extent = NULL;
2772 	struct btrfs_workqueue *wq;
2773 
2774 	trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2775 
2776 	ClearPagePrivate2(page);
2777 	if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2778 					    end - start + 1, uptodate))
2779 		return;
2780 
2781 	if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2782 		wq = fs_info->endio_freespace_worker;
2783 	else
2784 		wq = fs_info->endio_write_workers;
2785 
2786 	btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
2787 	btrfs_queue_work(wq, &ordered_extent->work);
2788 }
2789 
2790 static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
2791 			   int icsum, struct page *page, int pgoff, u64 start,
2792 			   size_t len)
2793 {
2794 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2795 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
2796 	char *kaddr;
2797 	u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2798 	u8 *csum_expected;
2799 	u8 csum[BTRFS_CSUM_SIZE];
2800 
2801 	csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
2802 
2803 	kaddr = kmap_atomic(page);
2804 	shash->tfm = fs_info->csum_shash;
2805 
2806 	crypto_shash_digest(shash, kaddr + pgoff, len, csum);
2807 
2808 	if (memcmp(csum, csum_expected, csum_size))
2809 		goto zeroit;
2810 
2811 	kunmap_atomic(kaddr);
2812 	return 0;
2813 zeroit:
2814 	btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
2815 				    io_bio->mirror_num);
2816 	memset(kaddr + pgoff, 1, len);
2817 	flush_dcache_page(page);
2818 	kunmap_atomic(kaddr);
2819 	return -EIO;
2820 }
2821 
2822 /*
2823  * when reads are done, we need to check csums to verify the data is correct
2824  * if there's a match, we allow the bio to finish.  If not, the code in
2825  * extent_io.c will try to find good copies for us.
2826  */
2827 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2828 				      u64 phy_offset, struct page *page,
2829 				      u64 start, u64 end, int mirror)
2830 {
2831 	size_t offset = start - page_offset(page);
2832 	struct inode *inode = page->mapping->host;
2833 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2834 	struct btrfs_root *root = BTRFS_I(inode)->root;
2835 
2836 	if (PageChecked(page)) {
2837 		ClearPageChecked(page);
2838 		return 0;
2839 	}
2840 
2841 	if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2842 		return 0;
2843 
2844 	if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2845 	    test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2846 		clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
2847 		return 0;
2848 	}
2849 
2850 	phy_offset >>= inode->i_sb->s_blocksize_bits;
2851 	return check_data_csum(inode, io_bio, phy_offset, page, offset, start,
2852 			       (size_t)(end - start + 1));
2853 }
2854 
2855 /*
2856  * btrfs_add_delayed_iput - perform a delayed iput on @inode
2857  *
2858  * @inode: The inode we want to perform iput on
2859  *
2860  * This function uses the generic vfs_inode::i_count to track whether we should
2861  * just decrement it (in case it's > 1) or if this is the last iput then link
2862  * the inode to the delayed iput machinery. Delayed iputs are processed at
2863  * transaction commit time/superblock commit/cleaner kthread.
2864  */
2865 void btrfs_add_delayed_iput(struct inode *inode)
2866 {
2867 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2868 	struct btrfs_inode *binode = BTRFS_I(inode);
2869 
2870 	if (atomic_add_unless(&inode->i_count, -1, 1))
2871 		return;
2872 
2873 	atomic_inc(&fs_info->nr_delayed_iputs);
2874 	spin_lock(&fs_info->delayed_iput_lock);
2875 	ASSERT(list_empty(&binode->delayed_iput));
2876 	list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
2877 	spin_unlock(&fs_info->delayed_iput_lock);
2878 	if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
2879 		wake_up_process(fs_info->cleaner_kthread);
2880 }
2881 
2882 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
2883 				    struct btrfs_inode *inode)
2884 {
2885 	list_del_init(&inode->delayed_iput);
2886 	spin_unlock(&fs_info->delayed_iput_lock);
2887 	iput(&inode->vfs_inode);
2888 	if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
2889 		wake_up(&fs_info->delayed_iputs_wait);
2890 	spin_lock(&fs_info->delayed_iput_lock);
2891 }
2892 
2893 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
2894 				   struct btrfs_inode *inode)
2895 {
2896 	if (!list_empty(&inode->delayed_iput)) {
2897 		spin_lock(&fs_info->delayed_iput_lock);
2898 		if (!list_empty(&inode->delayed_iput))
2899 			run_delayed_iput_locked(fs_info, inode);
2900 		spin_unlock(&fs_info->delayed_iput_lock);
2901 	}
2902 }
2903 
2904 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
2905 {
2906 
2907 	spin_lock(&fs_info->delayed_iput_lock);
2908 	while (!list_empty(&fs_info->delayed_iputs)) {
2909 		struct btrfs_inode *inode;
2910 
2911 		inode = list_first_entry(&fs_info->delayed_iputs,
2912 				struct btrfs_inode, delayed_iput);
2913 		run_delayed_iput_locked(fs_info, inode);
2914 	}
2915 	spin_unlock(&fs_info->delayed_iput_lock);
2916 }
2917 
2918 /**
2919  * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
2920  * @fs_info - the fs_info for this fs
2921  * @return - EINTR if we were killed, 0 if nothing's pending
2922  *
2923  * This will wait on any delayed iputs that are currently running with KILLABLE
2924  * set.  Once they are all done running we will return, unless we are killed in
2925  * which case we return EINTR. This helps in user operations like fallocate etc
2926  * that might get blocked on the iputs.
2927  */
2928 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
2929 {
2930 	int ret = wait_event_killable(fs_info->delayed_iputs_wait,
2931 			atomic_read(&fs_info->nr_delayed_iputs) == 0);
2932 	if (ret)
2933 		return -EINTR;
2934 	return 0;
2935 }
2936 
2937 /*
2938  * This creates an orphan entry for the given inode in case something goes wrong
2939  * in the middle of an unlink.
2940  */
2941 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
2942 		     struct btrfs_inode *inode)
2943 {
2944 	int ret;
2945 
2946 	ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
2947 	if (ret && ret != -EEXIST) {
2948 		btrfs_abort_transaction(trans, ret);
2949 		return ret;
2950 	}
2951 
2952 	return 0;
2953 }
2954 
2955 /*
2956  * We have done the delete so we can go ahead and remove the orphan item for
2957  * this particular inode.
2958  */
2959 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
2960 			    struct btrfs_inode *inode)
2961 {
2962 	return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
2963 }
2964 
2965 /*
2966  * this cleans up any orphans that may be left on the list from the last use
2967  * of this root.
2968  */
2969 int btrfs_orphan_cleanup(struct btrfs_root *root)
2970 {
2971 	struct btrfs_fs_info *fs_info = root->fs_info;
2972 	struct btrfs_path *path;
2973 	struct extent_buffer *leaf;
2974 	struct btrfs_key key, found_key;
2975 	struct btrfs_trans_handle *trans;
2976 	struct inode *inode;
2977 	u64 last_objectid = 0;
2978 	int ret = 0, nr_unlink = 0;
2979 
2980 	if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2981 		return 0;
2982 
2983 	path = btrfs_alloc_path();
2984 	if (!path) {
2985 		ret = -ENOMEM;
2986 		goto out;
2987 	}
2988 	path->reada = READA_BACK;
2989 
2990 	key.objectid = BTRFS_ORPHAN_OBJECTID;
2991 	key.type = BTRFS_ORPHAN_ITEM_KEY;
2992 	key.offset = (u64)-1;
2993 
2994 	while (1) {
2995 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2996 		if (ret < 0)
2997 			goto out;
2998 
2999 		/*
3000 		 * if ret == 0 means we found what we were searching for, which
3001 		 * is weird, but possible, so only screw with path if we didn't
3002 		 * find the key and see if we have stuff that matches
3003 		 */
3004 		if (ret > 0) {
3005 			ret = 0;
3006 			if (path->slots[0] == 0)
3007 				break;
3008 			path->slots[0]--;
3009 		}
3010 
3011 		/* pull out the item */
3012 		leaf = path->nodes[0];
3013 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3014 
3015 		/* make sure the item matches what we want */
3016 		if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3017 			break;
3018 		if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3019 			break;
3020 
3021 		/* release the path since we're done with it */
3022 		btrfs_release_path(path);
3023 
3024 		/*
3025 		 * this is where we are basically btrfs_lookup, without the
3026 		 * crossing root thing.  we store the inode number in the
3027 		 * offset of the orphan item.
3028 		 */
3029 
3030 		if (found_key.offset == last_objectid) {
3031 			btrfs_err(fs_info,
3032 				  "Error removing orphan entry, stopping orphan cleanup");
3033 			ret = -EINVAL;
3034 			goto out;
3035 		}
3036 
3037 		last_objectid = found_key.offset;
3038 
3039 		found_key.objectid = found_key.offset;
3040 		found_key.type = BTRFS_INODE_ITEM_KEY;
3041 		found_key.offset = 0;
3042 		inode = btrfs_iget(fs_info->sb, last_objectid, root);
3043 		ret = PTR_ERR_OR_ZERO(inode);
3044 		if (ret && ret != -ENOENT)
3045 			goto out;
3046 
3047 		if (ret == -ENOENT && root == fs_info->tree_root) {
3048 			struct btrfs_root *dead_root;
3049 			struct btrfs_fs_info *fs_info = root->fs_info;
3050 			int is_dead_root = 0;
3051 
3052 			/*
3053 			 * this is an orphan in the tree root. Currently these
3054 			 * could come from 2 sources:
3055 			 *  a) a snapshot deletion in progress
3056 			 *  b) a free space cache inode
3057 			 * We need to distinguish those two, as the snapshot
3058 			 * orphan must not get deleted.
3059 			 * find_dead_roots already ran before us, so if this
3060 			 * is a snapshot deletion, we should find the root
3061 			 * in the fs_roots radix tree.
3062 			 */
3063 
3064 			spin_lock(&fs_info->fs_roots_radix_lock);
3065 			dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3066 							 (unsigned long)found_key.objectid);
3067 			if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3068 				is_dead_root = 1;
3069 			spin_unlock(&fs_info->fs_roots_radix_lock);
3070 
3071 			if (is_dead_root) {
3072 				/* prevent this orphan from being found again */
3073 				key.offset = found_key.objectid - 1;
3074 				continue;
3075 			}
3076 
3077 		}
3078 
3079 		/*
3080 		 * If we have an inode with links, there are a couple of
3081 		 * possibilities. Old kernels (before v3.12) used to create an
3082 		 * orphan item for truncate indicating that there were possibly
3083 		 * extent items past i_size that needed to be deleted. In v3.12,
3084 		 * truncate was changed to update i_size in sync with the extent
3085 		 * items, but the (useless) orphan item was still created. Since
3086 		 * v4.18, we don't create the orphan item for truncate at all.
3087 		 *
3088 		 * So, this item could mean that we need to do a truncate, but
3089 		 * only if this filesystem was last used on a pre-v3.12 kernel
3090 		 * and was not cleanly unmounted. The odds of that are quite
3091 		 * slim, and it's a pain to do the truncate now, so just delete
3092 		 * the orphan item.
3093 		 *
3094 		 * It's also possible that this orphan item was supposed to be
3095 		 * deleted but wasn't. The inode number may have been reused,
3096 		 * but either way, we can delete the orphan item.
3097 		 */
3098 		if (ret == -ENOENT || inode->i_nlink) {
3099 			if (!ret)
3100 				iput(inode);
3101 			trans = btrfs_start_transaction(root, 1);
3102 			if (IS_ERR(trans)) {
3103 				ret = PTR_ERR(trans);
3104 				goto out;
3105 			}
3106 			btrfs_debug(fs_info, "auto deleting %Lu",
3107 				    found_key.objectid);
3108 			ret = btrfs_del_orphan_item(trans, root,
3109 						    found_key.objectid);
3110 			btrfs_end_transaction(trans);
3111 			if (ret)
3112 				goto out;
3113 			continue;
3114 		}
3115 
3116 		nr_unlink++;
3117 
3118 		/* this will do delete_inode and everything for us */
3119 		iput(inode);
3120 	}
3121 	/* release the path since we're done with it */
3122 	btrfs_release_path(path);
3123 
3124 	root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3125 
3126 	if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3127 		trans = btrfs_join_transaction(root);
3128 		if (!IS_ERR(trans))
3129 			btrfs_end_transaction(trans);
3130 	}
3131 
3132 	if (nr_unlink)
3133 		btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3134 
3135 out:
3136 	if (ret)
3137 		btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3138 	btrfs_free_path(path);
3139 	return ret;
3140 }
3141 
3142 /*
3143  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3144  * don't find any xattrs, we know there can't be any acls.
3145  *
3146  * slot is the slot the inode is in, objectid is the objectid of the inode
3147  */
3148 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3149 					  int slot, u64 objectid,
3150 					  int *first_xattr_slot)
3151 {
3152 	u32 nritems = btrfs_header_nritems(leaf);
3153 	struct btrfs_key found_key;
3154 	static u64 xattr_access = 0;
3155 	static u64 xattr_default = 0;
3156 	int scanned = 0;
3157 
3158 	if (!xattr_access) {
3159 		xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3160 					strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3161 		xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3162 					strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3163 	}
3164 
3165 	slot++;
3166 	*first_xattr_slot = -1;
3167 	while (slot < nritems) {
3168 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
3169 
3170 		/* we found a different objectid, there must not be acls */
3171 		if (found_key.objectid != objectid)
3172 			return 0;
3173 
3174 		/* we found an xattr, assume we've got an acl */
3175 		if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3176 			if (*first_xattr_slot == -1)
3177 				*first_xattr_slot = slot;
3178 			if (found_key.offset == xattr_access ||
3179 			    found_key.offset == xattr_default)
3180 				return 1;
3181 		}
3182 
3183 		/*
3184 		 * we found a key greater than an xattr key, there can't
3185 		 * be any acls later on
3186 		 */
3187 		if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3188 			return 0;
3189 
3190 		slot++;
3191 		scanned++;
3192 
3193 		/*
3194 		 * it goes inode, inode backrefs, xattrs, extents,
3195 		 * so if there are a ton of hard links to an inode there can
3196 		 * be a lot of backrefs.  Don't waste time searching too hard,
3197 		 * this is just an optimization
3198 		 */
3199 		if (scanned >= 8)
3200 			break;
3201 	}
3202 	/* we hit the end of the leaf before we found an xattr or
3203 	 * something larger than an xattr.  We have to assume the inode
3204 	 * has acls
3205 	 */
3206 	if (*first_xattr_slot == -1)
3207 		*first_xattr_slot = slot;
3208 	return 1;
3209 }
3210 
3211 /*
3212  * read an inode from the btree into the in-memory inode
3213  */
3214 static int btrfs_read_locked_inode(struct inode *inode,
3215 				   struct btrfs_path *in_path)
3216 {
3217 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3218 	struct btrfs_path *path = in_path;
3219 	struct extent_buffer *leaf;
3220 	struct btrfs_inode_item *inode_item;
3221 	struct btrfs_root *root = BTRFS_I(inode)->root;
3222 	struct btrfs_key location;
3223 	unsigned long ptr;
3224 	int maybe_acls;
3225 	u32 rdev;
3226 	int ret;
3227 	bool filled = false;
3228 	int first_xattr_slot;
3229 
3230 	ret = btrfs_fill_inode(inode, &rdev);
3231 	if (!ret)
3232 		filled = true;
3233 
3234 	if (!path) {
3235 		path = btrfs_alloc_path();
3236 		if (!path)
3237 			return -ENOMEM;
3238 	}
3239 
3240 	memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3241 
3242 	ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3243 	if (ret) {
3244 		if (path != in_path)
3245 			btrfs_free_path(path);
3246 		return ret;
3247 	}
3248 
3249 	leaf = path->nodes[0];
3250 
3251 	if (filled)
3252 		goto cache_index;
3253 
3254 	inode_item = btrfs_item_ptr(leaf, path->slots[0],
3255 				    struct btrfs_inode_item);
3256 	inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3257 	set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3258 	i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3259 	i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3260 	btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3261 	btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3262 			round_up(i_size_read(inode), fs_info->sectorsize));
3263 
3264 	inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3265 	inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3266 
3267 	inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3268 	inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3269 
3270 	inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3271 	inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3272 
3273 	BTRFS_I(inode)->i_otime.tv_sec =
3274 		btrfs_timespec_sec(leaf, &inode_item->otime);
3275 	BTRFS_I(inode)->i_otime.tv_nsec =
3276 		btrfs_timespec_nsec(leaf, &inode_item->otime);
3277 
3278 	inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3279 	BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3280 	BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3281 
3282 	inode_set_iversion_queried(inode,
3283 				   btrfs_inode_sequence(leaf, inode_item));
3284 	inode->i_generation = BTRFS_I(inode)->generation;
3285 	inode->i_rdev = 0;
3286 	rdev = btrfs_inode_rdev(leaf, inode_item);
3287 
3288 	BTRFS_I(inode)->index_cnt = (u64)-1;
3289 	BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3290 
3291 cache_index:
3292 	/*
3293 	 * If we were modified in the current generation and evicted from memory
3294 	 * and then re-read we need to do a full sync since we don't have any
3295 	 * idea about which extents were modified before we were evicted from
3296 	 * cache.
3297 	 *
3298 	 * This is required for both inode re-read from disk and delayed inode
3299 	 * in delayed_nodes_tree.
3300 	 */
3301 	if (BTRFS_I(inode)->last_trans == fs_info->generation)
3302 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3303 			&BTRFS_I(inode)->runtime_flags);
3304 
3305 	/*
3306 	 * We don't persist the id of the transaction where an unlink operation
3307 	 * against the inode was last made. So here we assume the inode might
3308 	 * have been evicted, and therefore the exact value of last_unlink_trans
3309 	 * lost, and set it to last_trans to avoid metadata inconsistencies
3310 	 * between the inode and its parent if the inode is fsync'ed and the log
3311 	 * replayed. For example, in the scenario:
3312 	 *
3313 	 * touch mydir/foo
3314 	 * ln mydir/foo mydir/bar
3315 	 * sync
3316 	 * unlink mydir/bar
3317 	 * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
3318 	 * xfs_io -c fsync mydir/foo
3319 	 * <power failure>
3320 	 * mount fs, triggers fsync log replay
3321 	 *
3322 	 * We must make sure that when we fsync our inode foo we also log its
3323 	 * parent inode, otherwise after log replay the parent still has the
3324 	 * dentry with the "bar" name but our inode foo has a link count of 1
3325 	 * and doesn't have an inode ref with the name "bar" anymore.
3326 	 *
3327 	 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3328 	 * but it guarantees correctness at the expense of occasional full
3329 	 * transaction commits on fsync if our inode is a directory, or if our
3330 	 * inode is not a directory, logging its parent unnecessarily.
3331 	 */
3332 	BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3333 
3334 	path->slots[0]++;
3335 	if (inode->i_nlink != 1 ||
3336 	    path->slots[0] >= btrfs_header_nritems(leaf))
3337 		goto cache_acl;
3338 
3339 	btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3340 	if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3341 		goto cache_acl;
3342 
3343 	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3344 	if (location.type == BTRFS_INODE_REF_KEY) {
3345 		struct btrfs_inode_ref *ref;
3346 
3347 		ref = (struct btrfs_inode_ref *)ptr;
3348 		BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3349 	} else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3350 		struct btrfs_inode_extref *extref;
3351 
3352 		extref = (struct btrfs_inode_extref *)ptr;
3353 		BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3354 								     extref);
3355 	}
3356 cache_acl:
3357 	/*
3358 	 * try to precache a NULL acl entry for files that don't have
3359 	 * any xattrs or acls
3360 	 */
3361 	maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3362 			btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3363 	if (first_xattr_slot != -1) {
3364 		path->slots[0] = first_xattr_slot;
3365 		ret = btrfs_load_inode_props(inode, path);
3366 		if (ret)
3367 			btrfs_err(fs_info,
3368 				  "error loading props for ino %llu (root %llu): %d",
3369 				  btrfs_ino(BTRFS_I(inode)),
3370 				  root->root_key.objectid, ret);
3371 	}
3372 	if (path != in_path)
3373 		btrfs_free_path(path);
3374 
3375 	if (!maybe_acls)
3376 		cache_no_acl(inode);
3377 
3378 	switch (inode->i_mode & S_IFMT) {
3379 	case S_IFREG:
3380 		inode->i_mapping->a_ops = &btrfs_aops;
3381 		BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3382 		inode->i_fop = &btrfs_file_operations;
3383 		inode->i_op = &btrfs_file_inode_operations;
3384 		break;
3385 	case S_IFDIR:
3386 		inode->i_fop = &btrfs_dir_file_operations;
3387 		inode->i_op = &btrfs_dir_inode_operations;
3388 		break;
3389 	case S_IFLNK:
3390 		inode->i_op = &btrfs_symlink_inode_operations;
3391 		inode_nohighmem(inode);
3392 		inode->i_mapping->a_ops = &btrfs_aops;
3393 		break;
3394 	default:
3395 		inode->i_op = &btrfs_special_inode_operations;
3396 		init_special_inode(inode, inode->i_mode, rdev);
3397 		break;
3398 	}
3399 
3400 	btrfs_sync_inode_flags_to_i_flags(inode);
3401 	return 0;
3402 }
3403 
3404 /*
3405  * given a leaf and an inode, copy the inode fields into the leaf
3406  */
3407 static void fill_inode_item(struct btrfs_trans_handle *trans,
3408 			    struct extent_buffer *leaf,
3409 			    struct btrfs_inode_item *item,
3410 			    struct inode *inode)
3411 {
3412 	struct btrfs_map_token token;
3413 
3414 	btrfs_init_map_token(&token, leaf);
3415 
3416 	btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3417 	btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3418 	btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3419 	btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3420 	btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3421 
3422 	btrfs_set_token_timespec_sec(&token, &item->atime,
3423 				     inode->i_atime.tv_sec);
3424 	btrfs_set_token_timespec_nsec(&token, &item->atime,
3425 				      inode->i_atime.tv_nsec);
3426 
3427 	btrfs_set_token_timespec_sec(&token, &item->mtime,
3428 				     inode->i_mtime.tv_sec);
3429 	btrfs_set_token_timespec_nsec(&token, &item->mtime,
3430 				      inode->i_mtime.tv_nsec);
3431 
3432 	btrfs_set_token_timespec_sec(&token, &item->ctime,
3433 				     inode->i_ctime.tv_sec);
3434 	btrfs_set_token_timespec_nsec(&token, &item->ctime,
3435 				      inode->i_ctime.tv_nsec);
3436 
3437 	btrfs_set_token_timespec_sec(&token, &item->otime,
3438 				     BTRFS_I(inode)->i_otime.tv_sec);
3439 	btrfs_set_token_timespec_nsec(&token, &item->otime,
3440 				      BTRFS_I(inode)->i_otime.tv_nsec);
3441 
3442 	btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3443 	btrfs_set_token_inode_generation(&token, item,
3444 					 BTRFS_I(inode)->generation);
3445 	btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3446 	btrfs_set_token_inode_transid(&token, item, trans->transid);
3447 	btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3448 	btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3449 	btrfs_set_token_inode_block_group(&token, item, 0);
3450 }
3451 
3452 /*
3453  * copy everything in the in-memory inode into the btree.
3454  */
3455 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3456 				struct btrfs_root *root, struct inode *inode)
3457 {
3458 	struct btrfs_inode_item *inode_item;
3459 	struct btrfs_path *path;
3460 	struct extent_buffer *leaf;
3461 	int ret;
3462 
3463 	path = btrfs_alloc_path();
3464 	if (!path)
3465 		return -ENOMEM;
3466 
3467 	path->leave_spinning = 1;
3468 	ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3469 				 1);
3470 	if (ret) {
3471 		if (ret > 0)
3472 			ret = -ENOENT;
3473 		goto failed;
3474 	}
3475 
3476 	leaf = path->nodes[0];
3477 	inode_item = btrfs_item_ptr(leaf, path->slots[0],
3478 				    struct btrfs_inode_item);
3479 
3480 	fill_inode_item(trans, leaf, inode_item, inode);
3481 	btrfs_mark_buffer_dirty(leaf);
3482 	btrfs_set_inode_last_trans(trans, inode);
3483 	ret = 0;
3484 failed:
3485 	btrfs_free_path(path);
3486 	return ret;
3487 }
3488 
3489 /*
3490  * copy everything in the in-memory inode into the btree.
3491  */
3492 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3493 				struct btrfs_root *root, struct inode *inode)
3494 {
3495 	struct btrfs_fs_info *fs_info = root->fs_info;
3496 	int ret;
3497 
3498 	/*
3499 	 * If the inode is a free space inode, we can deadlock during commit
3500 	 * if we put it into the delayed code.
3501 	 *
3502 	 * The data relocation inode should also be directly updated
3503 	 * without delay
3504 	 */
3505 	if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3506 	    && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3507 	    && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3508 		btrfs_update_root_times(trans, root);
3509 
3510 		ret = btrfs_delayed_update_inode(trans, root, inode);
3511 		if (!ret)
3512 			btrfs_set_inode_last_trans(trans, inode);
3513 		return ret;
3514 	}
3515 
3516 	return btrfs_update_inode_item(trans, root, inode);
3517 }
3518 
3519 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3520 					 struct btrfs_root *root,
3521 					 struct inode *inode)
3522 {
3523 	int ret;
3524 
3525 	ret = btrfs_update_inode(trans, root, inode);
3526 	if (ret == -ENOSPC)
3527 		return btrfs_update_inode_item(trans, root, inode);
3528 	return ret;
3529 }
3530 
3531 /*
3532  * unlink helper that gets used here in inode.c and in the tree logging
3533  * recovery code.  It remove a link in a directory with a given name, and
3534  * also drops the back refs in the inode to the directory
3535  */
3536 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3537 				struct btrfs_root *root,
3538 				struct btrfs_inode *dir,
3539 				struct btrfs_inode *inode,
3540 				const char *name, int name_len)
3541 {
3542 	struct btrfs_fs_info *fs_info = root->fs_info;
3543 	struct btrfs_path *path;
3544 	int ret = 0;
3545 	struct btrfs_dir_item *di;
3546 	u64 index;
3547 	u64 ino = btrfs_ino(inode);
3548 	u64 dir_ino = btrfs_ino(dir);
3549 
3550 	path = btrfs_alloc_path();
3551 	if (!path) {
3552 		ret = -ENOMEM;
3553 		goto out;
3554 	}
3555 
3556 	path->leave_spinning = 1;
3557 	di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3558 				    name, name_len, -1);
3559 	if (IS_ERR_OR_NULL(di)) {
3560 		ret = di ? PTR_ERR(di) : -ENOENT;
3561 		goto err;
3562 	}
3563 	ret = btrfs_delete_one_dir_name(trans, root, path, di);
3564 	if (ret)
3565 		goto err;
3566 	btrfs_release_path(path);
3567 
3568 	/*
3569 	 * If we don't have dir index, we have to get it by looking up
3570 	 * the inode ref, since we get the inode ref, remove it directly,
3571 	 * it is unnecessary to do delayed deletion.
3572 	 *
3573 	 * But if we have dir index, needn't search inode ref to get it.
3574 	 * Since the inode ref is close to the inode item, it is better
3575 	 * that we delay to delete it, and just do this deletion when
3576 	 * we update the inode item.
3577 	 */
3578 	if (inode->dir_index) {
3579 		ret = btrfs_delayed_delete_inode_ref(inode);
3580 		if (!ret) {
3581 			index = inode->dir_index;
3582 			goto skip_backref;
3583 		}
3584 	}
3585 
3586 	ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3587 				  dir_ino, &index);
3588 	if (ret) {
3589 		btrfs_info(fs_info,
3590 			"failed to delete reference to %.*s, inode %llu parent %llu",
3591 			name_len, name, ino, dir_ino);
3592 		btrfs_abort_transaction(trans, ret);
3593 		goto err;
3594 	}
3595 skip_backref:
3596 	ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3597 	if (ret) {
3598 		btrfs_abort_transaction(trans, ret);
3599 		goto err;
3600 	}
3601 
3602 	ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3603 			dir_ino);
3604 	if (ret != 0 && ret != -ENOENT) {
3605 		btrfs_abort_transaction(trans, ret);
3606 		goto err;
3607 	}
3608 
3609 	ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3610 			index);
3611 	if (ret == -ENOENT)
3612 		ret = 0;
3613 	else if (ret)
3614 		btrfs_abort_transaction(trans, ret);
3615 
3616 	/*
3617 	 * If we have a pending delayed iput we could end up with the final iput
3618 	 * being run in btrfs-cleaner context.  If we have enough of these built
3619 	 * up we can end up burning a lot of time in btrfs-cleaner without any
3620 	 * way to throttle the unlinks.  Since we're currently holding a ref on
3621 	 * the inode we can run the delayed iput here without any issues as the
3622 	 * final iput won't be done until after we drop the ref we're currently
3623 	 * holding.
3624 	 */
3625 	btrfs_run_delayed_iput(fs_info, inode);
3626 err:
3627 	btrfs_free_path(path);
3628 	if (ret)
3629 		goto out;
3630 
3631 	btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3632 	inode_inc_iversion(&inode->vfs_inode);
3633 	inode_inc_iversion(&dir->vfs_inode);
3634 	inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3635 		dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3636 	ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
3637 out:
3638 	return ret;
3639 }
3640 
3641 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3642 		       struct btrfs_root *root,
3643 		       struct btrfs_inode *dir, struct btrfs_inode *inode,
3644 		       const char *name, int name_len)
3645 {
3646 	int ret;
3647 	ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3648 	if (!ret) {
3649 		drop_nlink(&inode->vfs_inode);
3650 		ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
3651 	}
3652 	return ret;
3653 }
3654 
3655 /*
3656  * helper to start transaction for unlink and rmdir.
3657  *
3658  * unlink and rmdir are special in btrfs, they do not always free space, so
3659  * if we cannot make our reservations the normal way try and see if there is
3660  * plenty of slack room in the global reserve to migrate, otherwise we cannot
3661  * allow the unlink to occur.
3662  */
3663 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3664 {
3665 	struct btrfs_root *root = BTRFS_I(dir)->root;
3666 
3667 	/*
3668 	 * 1 for the possible orphan item
3669 	 * 1 for the dir item
3670 	 * 1 for the dir index
3671 	 * 1 for the inode ref
3672 	 * 1 for the inode
3673 	 */
3674 	return btrfs_start_transaction_fallback_global_rsv(root, 5);
3675 }
3676 
3677 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3678 {
3679 	struct btrfs_root *root = BTRFS_I(dir)->root;
3680 	struct btrfs_trans_handle *trans;
3681 	struct inode *inode = d_inode(dentry);
3682 	int ret;
3683 
3684 	trans = __unlink_start_trans(dir);
3685 	if (IS_ERR(trans))
3686 		return PTR_ERR(trans);
3687 
3688 	btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
3689 			0);
3690 
3691 	ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
3692 			BTRFS_I(d_inode(dentry)), dentry->d_name.name,
3693 			dentry->d_name.len);
3694 	if (ret)
3695 		goto out;
3696 
3697 	if (inode->i_nlink == 0) {
3698 		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3699 		if (ret)
3700 			goto out;
3701 	}
3702 
3703 out:
3704 	btrfs_end_transaction(trans);
3705 	btrfs_btree_balance_dirty(root->fs_info);
3706 	return ret;
3707 }
3708 
3709 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3710 			       struct inode *dir, struct dentry *dentry)
3711 {
3712 	struct btrfs_root *root = BTRFS_I(dir)->root;
3713 	struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
3714 	struct btrfs_path *path;
3715 	struct extent_buffer *leaf;
3716 	struct btrfs_dir_item *di;
3717 	struct btrfs_key key;
3718 	const char *name = dentry->d_name.name;
3719 	int name_len = dentry->d_name.len;
3720 	u64 index;
3721 	int ret;
3722 	u64 objectid;
3723 	u64 dir_ino = btrfs_ino(BTRFS_I(dir));
3724 
3725 	if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
3726 		objectid = inode->root->root_key.objectid;
3727 	} else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3728 		objectid = inode->location.objectid;
3729 	} else {
3730 		WARN_ON(1);
3731 		return -EINVAL;
3732 	}
3733 
3734 	path = btrfs_alloc_path();
3735 	if (!path)
3736 		return -ENOMEM;
3737 
3738 	di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3739 				   name, name_len, -1);
3740 	if (IS_ERR_OR_NULL(di)) {
3741 		ret = di ? PTR_ERR(di) : -ENOENT;
3742 		goto out;
3743 	}
3744 
3745 	leaf = path->nodes[0];
3746 	btrfs_dir_item_key_to_cpu(leaf, di, &key);
3747 	WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3748 	ret = btrfs_delete_one_dir_name(trans, root, path, di);
3749 	if (ret) {
3750 		btrfs_abort_transaction(trans, ret);
3751 		goto out;
3752 	}
3753 	btrfs_release_path(path);
3754 
3755 	/*
3756 	 * This is a placeholder inode for a subvolume we didn't have a
3757 	 * reference to at the time of the snapshot creation.  In the meantime
3758 	 * we could have renamed the real subvol link into our snapshot, so
3759 	 * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
3760 	 * Instead simply lookup the dir_index_item for this entry so we can
3761 	 * remove it.  Otherwise we know we have a ref to the root and we can
3762 	 * call btrfs_del_root_ref, and it _shouldn't_ fail.
3763 	 */
3764 	if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3765 		di = btrfs_search_dir_index_item(root, path, dir_ino,
3766 						 name, name_len);
3767 		if (IS_ERR_OR_NULL(di)) {
3768 			if (!di)
3769 				ret = -ENOENT;
3770 			else
3771 				ret = PTR_ERR(di);
3772 			btrfs_abort_transaction(trans, ret);
3773 			goto out;
3774 		}
3775 
3776 		leaf = path->nodes[0];
3777 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3778 		index = key.offset;
3779 		btrfs_release_path(path);
3780 	} else {
3781 		ret = btrfs_del_root_ref(trans, objectid,
3782 					 root->root_key.objectid, dir_ino,
3783 					 &index, name, name_len);
3784 		if (ret) {
3785 			btrfs_abort_transaction(trans, ret);
3786 			goto out;
3787 		}
3788 	}
3789 
3790 	ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
3791 	if (ret) {
3792 		btrfs_abort_transaction(trans, ret);
3793 		goto out;
3794 	}
3795 
3796 	btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
3797 	inode_inc_iversion(dir);
3798 	dir->i_mtime = dir->i_ctime = current_time(dir);
3799 	ret = btrfs_update_inode_fallback(trans, root, dir);
3800 	if (ret)
3801 		btrfs_abort_transaction(trans, ret);
3802 out:
3803 	btrfs_free_path(path);
3804 	return ret;
3805 }
3806 
3807 /*
3808  * Helper to check if the subvolume references other subvolumes or if it's
3809  * default.
3810  */
3811 static noinline int may_destroy_subvol(struct btrfs_root *root)
3812 {
3813 	struct btrfs_fs_info *fs_info = root->fs_info;
3814 	struct btrfs_path *path;
3815 	struct btrfs_dir_item *di;
3816 	struct btrfs_key key;
3817 	u64 dir_id;
3818 	int ret;
3819 
3820 	path = btrfs_alloc_path();
3821 	if (!path)
3822 		return -ENOMEM;
3823 
3824 	/* Make sure this root isn't set as the default subvol */
3825 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
3826 	di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
3827 				   dir_id, "default", 7, 0);
3828 	if (di && !IS_ERR(di)) {
3829 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
3830 		if (key.objectid == root->root_key.objectid) {
3831 			ret = -EPERM;
3832 			btrfs_err(fs_info,
3833 				  "deleting default subvolume %llu is not allowed",
3834 				  key.objectid);
3835 			goto out;
3836 		}
3837 		btrfs_release_path(path);
3838 	}
3839 
3840 	key.objectid = root->root_key.objectid;
3841 	key.type = BTRFS_ROOT_REF_KEY;
3842 	key.offset = (u64)-1;
3843 
3844 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3845 	if (ret < 0)
3846 		goto out;
3847 	BUG_ON(ret == 0);
3848 
3849 	ret = 0;
3850 	if (path->slots[0] > 0) {
3851 		path->slots[0]--;
3852 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3853 		if (key.objectid == root->root_key.objectid &&
3854 		    key.type == BTRFS_ROOT_REF_KEY)
3855 			ret = -ENOTEMPTY;
3856 	}
3857 out:
3858 	btrfs_free_path(path);
3859 	return ret;
3860 }
3861 
3862 /* Delete all dentries for inodes belonging to the root */
3863 static void btrfs_prune_dentries(struct btrfs_root *root)
3864 {
3865 	struct btrfs_fs_info *fs_info = root->fs_info;
3866 	struct rb_node *node;
3867 	struct rb_node *prev;
3868 	struct btrfs_inode *entry;
3869 	struct inode *inode;
3870 	u64 objectid = 0;
3871 
3872 	if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
3873 		WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3874 
3875 	spin_lock(&root->inode_lock);
3876 again:
3877 	node = root->inode_tree.rb_node;
3878 	prev = NULL;
3879 	while (node) {
3880 		prev = node;
3881 		entry = rb_entry(node, struct btrfs_inode, rb_node);
3882 
3883 		if (objectid < btrfs_ino(entry))
3884 			node = node->rb_left;
3885 		else if (objectid > btrfs_ino(entry))
3886 			node = node->rb_right;
3887 		else
3888 			break;
3889 	}
3890 	if (!node) {
3891 		while (prev) {
3892 			entry = rb_entry(prev, struct btrfs_inode, rb_node);
3893 			if (objectid <= btrfs_ino(entry)) {
3894 				node = prev;
3895 				break;
3896 			}
3897 			prev = rb_next(prev);
3898 		}
3899 	}
3900 	while (node) {
3901 		entry = rb_entry(node, struct btrfs_inode, rb_node);
3902 		objectid = btrfs_ino(entry) + 1;
3903 		inode = igrab(&entry->vfs_inode);
3904 		if (inode) {
3905 			spin_unlock(&root->inode_lock);
3906 			if (atomic_read(&inode->i_count) > 1)
3907 				d_prune_aliases(inode);
3908 			/*
3909 			 * btrfs_drop_inode will have it removed from the inode
3910 			 * cache when its usage count hits zero.
3911 			 */
3912 			iput(inode);
3913 			cond_resched();
3914 			spin_lock(&root->inode_lock);
3915 			goto again;
3916 		}
3917 
3918 		if (cond_resched_lock(&root->inode_lock))
3919 			goto again;
3920 
3921 		node = rb_next(node);
3922 	}
3923 	spin_unlock(&root->inode_lock);
3924 }
3925 
3926 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
3927 {
3928 	struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
3929 	struct btrfs_root *root = BTRFS_I(dir)->root;
3930 	struct inode *inode = d_inode(dentry);
3931 	struct btrfs_root *dest = BTRFS_I(inode)->root;
3932 	struct btrfs_trans_handle *trans;
3933 	struct btrfs_block_rsv block_rsv;
3934 	u64 root_flags;
3935 	int ret;
3936 	int err;
3937 
3938 	/*
3939 	 * Don't allow to delete a subvolume with send in progress. This is
3940 	 * inside the inode lock so the error handling that has to drop the bit
3941 	 * again is not run concurrently.
3942 	 */
3943 	spin_lock(&dest->root_item_lock);
3944 	if (dest->send_in_progress) {
3945 		spin_unlock(&dest->root_item_lock);
3946 		btrfs_warn(fs_info,
3947 			   "attempt to delete subvolume %llu during send",
3948 			   dest->root_key.objectid);
3949 		return -EPERM;
3950 	}
3951 	root_flags = btrfs_root_flags(&dest->root_item);
3952 	btrfs_set_root_flags(&dest->root_item,
3953 			     root_flags | BTRFS_ROOT_SUBVOL_DEAD);
3954 	spin_unlock(&dest->root_item_lock);
3955 
3956 	down_write(&fs_info->subvol_sem);
3957 
3958 	err = may_destroy_subvol(dest);
3959 	if (err)
3960 		goto out_up_write;
3961 
3962 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
3963 	/*
3964 	 * One for dir inode,
3965 	 * two for dir entries,
3966 	 * two for root ref/backref.
3967 	 */
3968 	err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
3969 	if (err)
3970 		goto out_up_write;
3971 
3972 	trans = btrfs_start_transaction(root, 0);
3973 	if (IS_ERR(trans)) {
3974 		err = PTR_ERR(trans);
3975 		goto out_release;
3976 	}
3977 	trans->block_rsv = &block_rsv;
3978 	trans->bytes_reserved = block_rsv.size;
3979 
3980 	btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
3981 
3982 	ret = btrfs_unlink_subvol(trans, dir, dentry);
3983 	if (ret) {
3984 		err = ret;
3985 		btrfs_abort_transaction(trans, ret);
3986 		goto out_end_trans;
3987 	}
3988 
3989 	btrfs_record_root_in_trans(trans, dest);
3990 
3991 	memset(&dest->root_item.drop_progress, 0,
3992 		sizeof(dest->root_item.drop_progress));
3993 	dest->root_item.drop_level = 0;
3994 	btrfs_set_root_refs(&dest->root_item, 0);
3995 
3996 	if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
3997 		ret = btrfs_insert_orphan_item(trans,
3998 					fs_info->tree_root,
3999 					dest->root_key.objectid);
4000 		if (ret) {
4001 			btrfs_abort_transaction(trans, ret);
4002 			err = ret;
4003 			goto out_end_trans;
4004 		}
4005 	}
4006 
4007 	ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4008 				  BTRFS_UUID_KEY_SUBVOL,
4009 				  dest->root_key.objectid);
4010 	if (ret && ret != -ENOENT) {
4011 		btrfs_abort_transaction(trans, ret);
4012 		err = ret;
4013 		goto out_end_trans;
4014 	}
4015 	if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4016 		ret = btrfs_uuid_tree_remove(trans,
4017 					  dest->root_item.received_uuid,
4018 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4019 					  dest->root_key.objectid);
4020 		if (ret && ret != -ENOENT) {
4021 			btrfs_abort_transaction(trans, ret);
4022 			err = ret;
4023 			goto out_end_trans;
4024 		}
4025 	}
4026 
4027 out_end_trans:
4028 	trans->block_rsv = NULL;
4029 	trans->bytes_reserved = 0;
4030 	ret = btrfs_end_transaction(trans);
4031 	if (ret && !err)
4032 		err = ret;
4033 	inode->i_flags |= S_DEAD;
4034 out_release:
4035 	btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4036 out_up_write:
4037 	up_write(&fs_info->subvol_sem);
4038 	if (err) {
4039 		spin_lock(&dest->root_item_lock);
4040 		root_flags = btrfs_root_flags(&dest->root_item);
4041 		btrfs_set_root_flags(&dest->root_item,
4042 				root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4043 		spin_unlock(&dest->root_item_lock);
4044 	} else {
4045 		d_invalidate(dentry);
4046 		btrfs_prune_dentries(dest);
4047 		ASSERT(dest->send_in_progress == 0);
4048 
4049 		/* the last ref */
4050 		if (dest->ino_cache_inode) {
4051 			iput(dest->ino_cache_inode);
4052 			dest->ino_cache_inode = NULL;
4053 		}
4054 	}
4055 
4056 	return err;
4057 }
4058 
4059 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4060 {
4061 	struct inode *inode = d_inode(dentry);
4062 	int err = 0;
4063 	struct btrfs_root *root = BTRFS_I(dir)->root;
4064 	struct btrfs_trans_handle *trans;
4065 	u64 last_unlink_trans;
4066 
4067 	if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4068 		return -ENOTEMPTY;
4069 	if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4070 		return btrfs_delete_subvolume(dir, dentry);
4071 
4072 	trans = __unlink_start_trans(dir);
4073 	if (IS_ERR(trans))
4074 		return PTR_ERR(trans);
4075 
4076 	if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4077 		err = btrfs_unlink_subvol(trans, dir, dentry);
4078 		goto out;
4079 	}
4080 
4081 	err = btrfs_orphan_add(trans, BTRFS_I(inode));
4082 	if (err)
4083 		goto out;
4084 
4085 	last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4086 
4087 	/* now the directory is empty */
4088 	err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4089 			BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4090 			dentry->d_name.len);
4091 	if (!err) {
4092 		btrfs_i_size_write(BTRFS_I(inode), 0);
4093 		/*
4094 		 * Propagate the last_unlink_trans value of the deleted dir to
4095 		 * its parent directory. This is to prevent an unrecoverable
4096 		 * log tree in the case we do something like this:
4097 		 * 1) create dir foo
4098 		 * 2) create snapshot under dir foo
4099 		 * 3) delete the snapshot
4100 		 * 4) rmdir foo
4101 		 * 5) mkdir foo
4102 		 * 6) fsync foo or some file inside foo
4103 		 */
4104 		if (last_unlink_trans >= trans->transid)
4105 			BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4106 	}
4107 out:
4108 	btrfs_end_transaction(trans);
4109 	btrfs_btree_balance_dirty(root->fs_info);
4110 
4111 	return err;
4112 }
4113 
4114 /*
4115  * Return this if we need to call truncate_block for the last bit of the
4116  * truncate.
4117  */
4118 #define NEED_TRUNCATE_BLOCK 1
4119 
4120 /*
4121  * this can truncate away extent items, csum items and directory items.
4122  * It starts at a high offset and removes keys until it can't find
4123  * any higher than new_size
4124  *
4125  * csum items that cross the new i_size are truncated to the new size
4126  * as well.
4127  *
4128  * min_type is the minimum key type to truncate down to.  If set to 0, this
4129  * will kill all the items on this inode, including the INODE_ITEM_KEY.
4130  */
4131 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4132 			       struct btrfs_root *root,
4133 			       struct inode *inode,
4134 			       u64 new_size, u32 min_type)
4135 {
4136 	struct btrfs_fs_info *fs_info = root->fs_info;
4137 	struct btrfs_path *path;
4138 	struct extent_buffer *leaf;
4139 	struct btrfs_file_extent_item *fi;
4140 	struct btrfs_key key;
4141 	struct btrfs_key found_key;
4142 	u64 extent_start = 0;
4143 	u64 extent_num_bytes = 0;
4144 	u64 extent_offset = 0;
4145 	u64 item_end = 0;
4146 	u64 last_size = new_size;
4147 	u32 found_type = (u8)-1;
4148 	int found_extent;
4149 	int del_item;
4150 	int pending_del_nr = 0;
4151 	int pending_del_slot = 0;
4152 	int extent_type = -1;
4153 	int ret;
4154 	u64 ino = btrfs_ino(BTRFS_I(inode));
4155 	u64 bytes_deleted = 0;
4156 	bool be_nice = false;
4157 	bool should_throttle = false;
4158 	const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4159 	struct extent_state *cached_state = NULL;
4160 
4161 	BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4162 
4163 	/*
4164 	 * For non-free space inodes and non-shareable roots, we want to back
4165 	 * off from time to time.  This means all inodes in subvolume roots,
4166 	 * reloc roots, and data reloc roots.
4167 	 */
4168 	if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4169 	    test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4170 		be_nice = true;
4171 
4172 	path = btrfs_alloc_path();
4173 	if (!path)
4174 		return -ENOMEM;
4175 	path->reada = READA_BACK;
4176 
4177 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4178 		lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
4179 				 &cached_state);
4180 
4181 		/*
4182 		 * We want to drop from the next block forward in case this
4183 		 * new size is not block aligned since we will be keeping the
4184 		 * last block of the extent just the way it is.
4185 		 */
4186 		btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4187 					fs_info->sectorsize),
4188 					(u64)-1, 0);
4189 	}
4190 
4191 	/*
4192 	 * This function is also used to drop the items in the log tree before
4193 	 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4194 	 * it is used to drop the logged items. So we shouldn't kill the delayed
4195 	 * items.
4196 	 */
4197 	if (min_type == 0 && root == BTRFS_I(inode)->root)
4198 		btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4199 
4200 	key.objectid = ino;
4201 	key.offset = (u64)-1;
4202 	key.type = (u8)-1;
4203 
4204 search_again:
4205 	/*
4206 	 * with a 16K leaf size and 128MB extents, you can actually queue
4207 	 * up a huge file in a single leaf.  Most of the time that
4208 	 * bytes_deleted is > 0, it will be huge by the time we get here
4209 	 */
4210 	if (be_nice && bytes_deleted > SZ_32M &&
4211 	    btrfs_should_end_transaction(trans)) {
4212 		ret = -EAGAIN;
4213 		goto out;
4214 	}
4215 
4216 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4217 	if (ret < 0)
4218 		goto out;
4219 
4220 	if (ret > 0) {
4221 		ret = 0;
4222 		/* there are no items in the tree for us to truncate, we're
4223 		 * done
4224 		 */
4225 		if (path->slots[0] == 0)
4226 			goto out;
4227 		path->slots[0]--;
4228 	}
4229 
4230 	while (1) {
4231 		u64 clear_start = 0, clear_len = 0;
4232 
4233 		fi = NULL;
4234 		leaf = path->nodes[0];
4235 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4236 		found_type = found_key.type;
4237 
4238 		if (found_key.objectid != ino)
4239 			break;
4240 
4241 		if (found_type < min_type)
4242 			break;
4243 
4244 		item_end = found_key.offset;
4245 		if (found_type == BTRFS_EXTENT_DATA_KEY) {
4246 			fi = btrfs_item_ptr(leaf, path->slots[0],
4247 					    struct btrfs_file_extent_item);
4248 			extent_type = btrfs_file_extent_type(leaf, fi);
4249 			if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4250 				item_end +=
4251 				    btrfs_file_extent_num_bytes(leaf, fi);
4252 
4253 				trace_btrfs_truncate_show_fi_regular(
4254 					BTRFS_I(inode), leaf, fi,
4255 					found_key.offset);
4256 			} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4257 				item_end += btrfs_file_extent_ram_bytes(leaf,
4258 									fi);
4259 
4260 				trace_btrfs_truncate_show_fi_inline(
4261 					BTRFS_I(inode), leaf, fi, path->slots[0],
4262 					found_key.offset);
4263 			}
4264 			item_end--;
4265 		}
4266 		if (found_type > min_type) {
4267 			del_item = 1;
4268 		} else {
4269 			if (item_end < new_size)
4270 				break;
4271 			if (found_key.offset >= new_size)
4272 				del_item = 1;
4273 			else
4274 				del_item = 0;
4275 		}
4276 		found_extent = 0;
4277 		/* FIXME, shrink the extent if the ref count is only 1 */
4278 		if (found_type != BTRFS_EXTENT_DATA_KEY)
4279 			goto delete;
4280 
4281 		if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4282 			u64 num_dec;
4283 
4284 			clear_start = found_key.offset;
4285 			extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4286 			if (!del_item) {
4287 				u64 orig_num_bytes =
4288 					btrfs_file_extent_num_bytes(leaf, fi);
4289 				extent_num_bytes = ALIGN(new_size -
4290 						found_key.offset,
4291 						fs_info->sectorsize);
4292 				clear_start = ALIGN(new_size, fs_info->sectorsize);
4293 				btrfs_set_file_extent_num_bytes(leaf, fi,
4294 							 extent_num_bytes);
4295 				num_dec = (orig_num_bytes -
4296 					   extent_num_bytes);
4297 				if (test_bit(BTRFS_ROOT_SHAREABLE,
4298 					     &root->state) &&
4299 				    extent_start != 0)
4300 					inode_sub_bytes(inode, num_dec);
4301 				btrfs_mark_buffer_dirty(leaf);
4302 			} else {
4303 				extent_num_bytes =
4304 					btrfs_file_extent_disk_num_bytes(leaf,
4305 									 fi);
4306 				extent_offset = found_key.offset -
4307 					btrfs_file_extent_offset(leaf, fi);
4308 
4309 				/* FIXME blocksize != 4096 */
4310 				num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4311 				if (extent_start != 0) {
4312 					found_extent = 1;
4313 					if (test_bit(BTRFS_ROOT_SHAREABLE,
4314 						     &root->state))
4315 						inode_sub_bytes(inode, num_dec);
4316 				}
4317 			}
4318 			clear_len = num_dec;
4319 		} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4320 			/*
4321 			 * we can't truncate inline items that have had
4322 			 * special encodings
4323 			 */
4324 			if (!del_item &&
4325 			    btrfs_file_extent_encryption(leaf, fi) == 0 &&
4326 			    btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4327 			    btrfs_file_extent_compression(leaf, fi) == 0) {
4328 				u32 size = (u32)(new_size - found_key.offset);
4329 
4330 				btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4331 				size = btrfs_file_extent_calc_inline_size(size);
4332 				btrfs_truncate_item(path, size, 1);
4333 			} else if (!del_item) {
4334 				/*
4335 				 * We have to bail so the last_size is set to
4336 				 * just before this extent.
4337 				 */
4338 				ret = NEED_TRUNCATE_BLOCK;
4339 				break;
4340 			} else {
4341 				/*
4342 				 * Inline extents are special, we just treat
4343 				 * them as a full sector worth in the file
4344 				 * extent tree just for simplicity sake.
4345 				 */
4346 				clear_len = fs_info->sectorsize;
4347 			}
4348 
4349 			if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4350 				inode_sub_bytes(inode, item_end + 1 - new_size);
4351 		}
4352 delete:
4353 		/*
4354 		 * We use btrfs_truncate_inode_items() to clean up log trees for
4355 		 * multiple fsyncs, and in this case we don't want to clear the
4356 		 * file extent range because it's just the log.
4357 		 */
4358 		if (root == BTRFS_I(inode)->root) {
4359 			ret = btrfs_inode_clear_file_extent_range(BTRFS_I(inode),
4360 						  clear_start, clear_len);
4361 			if (ret) {
4362 				btrfs_abort_transaction(trans, ret);
4363 				break;
4364 			}
4365 		}
4366 
4367 		if (del_item)
4368 			last_size = found_key.offset;
4369 		else
4370 			last_size = new_size;
4371 		if (del_item) {
4372 			if (!pending_del_nr) {
4373 				/* no pending yet, add ourselves */
4374 				pending_del_slot = path->slots[0];
4375 				pending_del_nr = 1;
4376 			} else if (pending_del_nr &&
4377 				   path->slots[0] + 1 == pending_del_slot) {
4378 				/* hop on the pending chunk */
4379 				pending_del_nr++;
4380 				pending_del_slot = path->slots[0];
4381 			} else {
4382 				BUG();
4383 			}
4384 		} else {
4385 			break;
4386 		}
4387 		should_throttle = false;
4388 
4389 		if (found_extent &&
4390 		    root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4391 			struct btrfs_ref ref = { 0 };
4392 
4393 			bytes_deleted += extent_num_bytes;
4394 
4395 			btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4396 					extent_start, extent_num_bytes, 0);
4397 			ref.real_root = root->root_key.objectid;
4398 			btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4399 					ino, extent_offset);
4400 			ret = btrfs_free_extent(trans, &ref);
4401 			if (ret) {
4402 				btrfs_abort_transaction(trans, ret);
4403 				break;
4404 			}
4405 			if (be_nice) {
4406 				if (btrfs_should_throttle_delayed_refs(trans))
4407 					should_throttle = true;
4408 			}
4409 		}
4410 
4411 		if (found_type == BTRFS_INODE_ITEM_KEY)
4412 			break;
4413 
4414 		if (path->slots[0] == 0 ||
4415 		    path->slots[0] != pending_del_slot ||
4416 		    should_throttle) {
4417 			if (pending_del_nr) {
4418 				ret = btrfs_del_items(trans, root, path,
4419 						pending_del_slot,
4420 						pending_del_nr);
4421 				if (ret) {
4422 					btrfs_abort_transaction(trans, ret);
4423 					break;
4424 				}
4425 				pending_del_nr = 0;
4426 			}
4427 			btrfs_release_path(path);
4428 
4429 			/*
4430 			 * We can generate a lot of delayed refs, so we need to
4431 			 * throttle every once and a while and make sure we're
4432 			 * adding enough space to keep up with the work we are
4433 			 * generating.  Since we hold a transaction here we
4434 			 * can't flush, and we don't want to FLUSH_LIMIT because
4435 			 * we could have generated too many delayed refs to
4436 			 * actually allocate, so just bail if we're short and
4437 			 * let the normal reservation dance happen higher up.
4438 			 */
4439 			if (should_throttle) {
4440 				ret = btrfs_delayed_refs_rsv_refill(fs_info,
4441 							BTRFS_RESERVE_NO_FLUSH);
4442 				if (ret) {
4443 					ret = -EAGAIN;
4444 					break;
4445 				}
4446 			}
4447 			goto search_again;
4448 		} else {
4449 			path->slots[0]--;
4450 		}
4451 	}
4452 out:
4453 	if (ret >= 0 && pending_del_nr) {
4454 		int err;
4455 
4456 		err = btrfs_del_items(trans, root, path, pending_del_slot,
4457 				      pending_del_nr);
4458 		if (err) {
4459 			btrfs_abort_transaction(trans, err);
4460 			ret = err;
4461 		}
4462 	}
4463 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4464 		ASSERT(last_size >= new_size);
4465 		if (!ret && last_size > new_size)
4466 			last_size = new_size;
4467 		btrfs_inode_safe_disk_i_size_write(inode, last_size);
4468 		unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start,
4469 				     (u64)-1, &cached_state);
4470 	}
4471 
4472 	btrfs_free_path(path);
4473 	return ret;
4474 }
4475 
4476 /*
4477  * btrfs_truncate_block - read, zero a chunk and write a block
4478  * @inode - inode that we're zeroing
4479  * @from - the offset to start zeroing
4480  * @len - the length to zero, 0 to zero the entire range respective to the
4481  *	offset
4482  * @front - zero up to the offset instead of from the offset on
4483  *
4484  * This will find the block for the "from" offset and cow the block and zero the
4485  * part we want to zero.  This is used with truncate and hole punching.
4486  */
4487 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4488 			int front)
4489 {
4490 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4491 	struct address_space *mapping = inode->i_mapping;
4492 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4493 	struct btrfs_ordered_extent *ordered;
4494 	struct extent_state *cached_state = NULL;
4495 	struct extent_changeset *data_reserved = NULL;
4496 	char *kaddr;
4497 	u32 blocksize = fs_info->sectorsize;
4498 	pgoff_t index = from >> PAGE_SHIFT;
4499 	unsigned offset = from & (blocksize - 1);
4500 	struct page *page;
4501 	gfp_t mask = btrfs_alloc_write_mask(mapping);
4502 	int ret = 0;
4503 	u64 block_start;
4504 	u64 block_end;
4505 
4506 	if (IS_ALIGNED(offset, blocksize) &&
4507 	    (!len || IS_ALIGNED(len, blocksize)))
4508 		goto out;
4509 
4510 	block_start = round_down(from, blocksize);
4511 	block_end = block_start + blocksize - 1;
4512 
4513 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4514 					   block_start, blocksize);
4515 	if (ret)
4516 		goto out;
4517 
4518 again:
4519 	page = find_or_create_page(mapping, index, mask);
4520 	if (!page) {
4521 		btrfs_delalloc_release_space(inode, data_reserved,
4522 					     block_start, blocksize, true);
4523 		btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4524 		ret = -ENOMEM;
4525 		goto out;
4526 	}
4527 
4528 	if (!PageUptodate(page)) {
4529 		ret = btrfs_readpage(NULL, page);
4530 		lock_page(page);
4531 		if (page->mapping != mapping) {
4532 			unlock_page(page);
4533 			put_page(page);
4534 			goto again;
4535 		}
4536 		if (!PageUptodate(page)) {
4537 			ret = -EIO;
4538 			goto out_unlock;
4539 		}
4540 	}
4541 	wait_on_page_writeback(page);
4542 
4543 	lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4544 	set_page_extent_mapped(page);
4545 
4546 	ordered = btrfs_lookup_ordered_extent(inode, block_start);
4547 	if (ordered) {
4548 		unlock_extent_cached(io_tree, block_start, block_end,
4549 				     &cached_state);
4550 		unlock_page(page);
4551 		put_page(page);
4552 		btrfs_start_ordered_extent(inode, ordered, 1);
4553 		btrfs_put_ordered_extent(ordered);
4554 		goto again;
4555 	}
4556 
4557 	clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4558 			 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4559 			 0, 0, &cached_state);
4560 
4561 	ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4562 					&cached_state);
4563 	if (ret) {
4564 		unlock_extent_cached(io_tree, block_start, block_end,
4565 				     &cached_state);
4566 		goto out_unlock;
4567 	}
4568 
4569 	if (offset != blocksize) {
4570 		if (!len)
4571 			len = blocksize - offset;
4572 		kaddr = kmap(page);
4573 		if (front)
4574 			memset(kaddr + (block_start - page_offset(page)),
4575 				0, offset);
4576 		else
4577 			memset(kaddr + (block_start - page_offset(page)) +  offset,
4578 				0, len);
4579 		flush_dcache_page(page);
4580 		kunmap(page);
4581 	}
4582 	ClearPageChecked(page);
4583 	set_page_dirty(page);
4584 	unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4585 
4586 out_unlock:
4587 	if (ret)
4588 		btrfs_delalloc_release_space(inode, data_reserved, block_start,
4589 					     blocksize, true);
4590 	btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4591 	unlock_page(page);
4592 	put_page(page);
4593 out:
4594 	extent_changeset_free(data_reserved);
4595 	return ret;
4596 }
4597 
4598 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4599 			     u64 offset, u64 len)
4600 {
4601 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4602 	struct btrfs_trans_handle *trans;
4603 	int ret;
4604 
4605 	/*
4606 	 * Still need to make sure the inode looks like it's been updated so
4607 	 * that any holes get logged if we fsync.
4608 	 */
4609 	if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4610 		BTRFS_I(inode)->last_trans = fs_info->generation;
4611 		BTRFS_I(inode)->last_sub_trans = root->log_transid;
4612 		BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4613 		return 0;
4614 	}
4615 
4616 	/*
4617 	 * 1 - for the one we're dropping
4618 	 * 1 - for the one we're adding
4619 	 * 1 - for updating the inode.
4620 	 */
4621 	trans = btrfs_start_transaction(root, 3);
4622 	if (IS_ERR(trans))
4623 		return PTR_ERR(trans);
4624 
4625 	ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4626 	if (ret) {
4627 		btrfs_abort_transaction(trans, ret);
4628 		btrfs_end_transaction(trans);
4629 		return ret;
4630 	}
4631 
4632 	ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4633 			offset, 0, 0, len, 0, len, 0, 0, 0);
4634 	if (ret)
4635 		btrfs_abort_transaction(trans, ret);
4636 	else
4637 		btrfs_update_inode(trans, root, inode);
4638 	btrfs_end_transaction(trans);
4639 	return ret;
4640 }
4641 
4642 /*
4643  * This function puts in dummy file extents for the area we're creating a hole
4644  * for.  So if we are truncating this file to a larger size we need to insert
4645  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4646  * the range between oldsize and size
4647  */
4648 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4649 {
4650 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4651 	struct btrfs_root *root = BTRFS_I(inode)->root;
4652 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4653 	struct extent_map *em = NULL;
4654 	struct extent_state *cached_state = NULL;
4655 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4656 	u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4657 	u64 block_end = ALIGN(size, fs_info->sectorsize);
4658 	u64 last_byte;
4659 	u64 cur_offset;
4660 	u64 hole_size;
4661 	int err = 0;
4662 
4663 	/*
4664 	 * If our size started in the middle of a block we need to zero out the
4665 	 * rest of the block before we expand the i_size, otherwise we could
4666 	 * expose stale data.
4667 	 */
4668 	err = btrfs_truncate_block(inode, oldsize, 0, 0);
4669 	if (err)
4670 		return err;
4671 
4672 	if (size <= hole_start)
4673 		return 0;
4674 
4675 	btrfs_lock_and_flush_ordered_range(BTRFS_I(inode), hole_start,
4676 					   block_end - 1, &cached_state);
4677 	cur_offset = hole_start;
4678 	while (1) {
4679 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4680 				      block_end - cur_offset);
4681 		if (IS_ERR(em)) {
4682 			err = PTR_ERR(em);
4683 			em = NULL;
4684 			break;
4685 		}
4686 		last_byte = min(extent_map_end(em), block_end);
4687 		last_byte = ALIGN(last_byte, fs_info->sectorsize);
4688 		hole_size = last_byte - cur_offset;
4689 
4690 		if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4691 			struct extent_map *hole_em;
4692 
4693 			err = maybe_insert_hole(root, inode, cur_offset,
4694 						hole_size);
4695 			if (err)
4696 				break;
4697 
4698 			err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4699 							cur_offset, hole_size);
4700 			if (err)
4701 				break;
4702 
4703 			btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4704 						cur_offset + hole_size - 1, 0);
4705 			hole_em = alloc_extent_map();
4706 			if (!hole_em) {
4707 				set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4708 					&BTRFS_I(inode)->runtime_flags);
4709 				goto next;
4710 			}
4711 			hole_em->start = cur_offset;
4712 			hole_em->len = hole_size;
4713 			hole_em->orig_start = cur_offset;
4714 
4715 			hole_em->block_start = EXTENT_MAP_HOLE;
4716 			hole_em->block_len = 0;
4717 			hole_em->orig_block_len = 0;
4718 			hole_em->ram_bytes = hole_size;
4719 			hole_em->compress_type = BTRFS_COMPRESS_NONE;
4720 			hole_em->generation = fs_info->generation;
4721 
4722 			while (1) {
4723 				write_lock(&em_tree->lock);
4724 				err = add_extent_mapping(em_tree, hole_em, 1);
4725 				write_unlock(&em_tree->lock);
4726 				if (err != -EEXIST)
4727 					break;
4728 				btrfs_drop_extent_cache(BTRFS_I(inode),
4729 							cur_offset,
4730 							cur_offset +
4731 							hole_size - 1, 0);
4732 			}
4733 			free_extent_map(hole_em);
4734 		} else {
4735 			err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4736 							cur_offset, hole_size);
4737 			if (err)
4738 				break;
4739 		}
4740 next:
4741 		free_extent_map(em);
4742 		em = NULL;
4743 		cur_offset = last_byte;
4744 		if (cur_offset >= block_end)
4745 			break;
4746 	}
4747 	free_extent_map(em);
4748 	unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
4749 	return err;
4750 }
4751 
4752 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4753 {
4754 	struct btrfs_root *root = BTRFS_I(inode)->root;
4755 	struct btrfs_trans_handle *trans;
4756 	loff_t oldsize = i_size_read(inode);
4757 	loff_t newsize = attr->ia_size;
4758 	int mask = attr->ia_valid;
4759 	int ret;
4760 
4761 	/*
4762 	 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4763 	 * special case where we need to update the times despite not having
4764 	 * these flags set.  For all other operations the VFS set these flags
4765 	 * explicitly if it wants a timestamp update.
4766 	 */
4767 	if (newsize != oldsize) {
4768 		inode_inc_iversion(inode);
4769 		if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4770 			inode->i_ctime = inode->i_mtime =
4771 				current_time(inode);
4772 	}
4773 
4774 	if (newsize > oldsize) {
4775 		/*
4776 		 * Don't do an expanding truncate while snapshotting is ongoing.
4777 		 * This is to ensure the snapshot captures a fully consistent
4778 		 * state of this file - if the snapshot captures this expanding
4779 		 * truncation, it must capture all writes that happened before
4780 		 * this truncation.
4781 		 */
4782 		btrfs_drew_write_lock(&root->snapshot_lock);
4783 		ret = btrfs_cont_expand(inode, oldsize, newsize);
4784 		if (ret) {
4785 			btrfs_drew_write_unlock(&root->snapshot_lock);
4786 			return ret;
4787 		}
4788 
4789 		trans = btrfs_start_transaction(root, 1);
4790 		if (IS_ERR(trans)) {
4791 			btrfs_drew_write_unlock(&root->snapshot_lock);
4792 			return PTR_ERR(trans);
4793 		}
4794 
4795 		i_size_write(inode, newsize);
4796 		btrfs_inode_safe_disk_i_size_write(inode, 0);
4797 		pagecache_isize_extended(inode, oldsize, newsize);
4798 		ret = btrfs_update_inode(trans, root, inode);
4799 		btrfs_drew_write_unlock(&root->snapshot_lock);
4800 		btrfs_end_transaction(trans);
4801 	} else {
4802 
4803 		/*
4804 		 * We're truncating a file that used to have good data down to
4805 		 * zero. Make sure it gets into the ordered flush list so that
4806 		 * any new writes get down to disk quickly.
4807 		 */
4808 		if (newsize == 0)
4809 			set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4810 				&BTRFS_I(inode)->runtime_flags);
4811 
4812 		truncate_setsize(inode, newsize);
4813 
4814 		/* Disable nonlocked read DIO to avoid the endless truncate */
4815 		btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
4816 		inode_dio_wait(inode);
4817 		btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
4818 
4819 		ret = btrfs_truncate(inode, newsize == oldsize);
4820 		if (ret && inode->i_nlink) {
4821 			int err;
4822 
4823 			/*
4824 			 * Truncate failed, so fix up the in-memory size. We
4825 			 * adjusted disk_i_size down as we removed extents, so
4826 			 * wait for disk_i_size to be stable and then update the
4827 			 * in-memory size to match.
4828 			 */
4829 			err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
4830 			if (err)
4831 				return err;
4832 			i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4833 		}
4834 	}
4835 
4836 	return ret;
4837 }
4838 
4839 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4840 {
4841 	struct inode *inode = d_inode(dentry);
4842 	struct btrfs_root *root = BTRFS_I(inode)->root;
4843 	int err;
4844 
4845 	if (btrfs_root_readonly(root))
4846 		return -EROFS;
4847 
4848 	err = setattr_prepare(dentry, attr);
4849 	if (err)
4850 		return err;
4851 
4852 	if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4853 		err = btrfs_setsize(inode, attr);
4854 		if (err)
4855 			return err;
4856 	}
4857 
4858 	if (attr->ia_valid) {
4859 		setattr_copy(inode, attr);
4860 		inode_inc_iversion(inode);
4861 		err = btrfs_dirty_inode(inode);
4862 
4863 		if (!err && attr->ia_valid & ATTR_MODE)
4864 			err = posix_acl_chmod(inode, inode->i_mode);
4865 	}
4866 
4867 	return err;
4868 }
4869 
4870 /*
4871  * While truncating the inode pages during eviction, we get the VFS calling
4872  * btrfs_invalidatepage() against each page of the inode. This is slow because
4873  * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4874  * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4875  * extent_state structures over and over, wasting lots of time.
4876  *
4877  * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4878  * those expensive operations on a per page basis and do only the ordered io
4879  * finishing, while we release here the extent_map and extent_state structures,
4880  * without the excessive merging and splitting.
4881  */
4882 static void evict_inode_truncate_pages(struct inode *inode)
4883 {
4884 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4885 	struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4886 	struct rb_node *node;
4887 
4888 	ASSERT(inode->i_state & I_FREEING);
4889 	truncate_inode_pages_final(&inode->i_data);
4890 
4891 	write_lock(&map_tree->lock);
4892 	while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
4893 		struct extent_map *em;
4894 
4895 		node = rb_first_cached(&map_tree->map);
4896 		em = rb_entry(node, struct extent_map, rb_node);
4897 		clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4898 		clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4899 		remove_extent_mapping(map_tree, em);
4900 		free_extent_map(em);
4901 		if (need_resched()) {
4902 			write_unlock(&map_tree->lock);
4903 			cond_resched();
4904 			write_lock(&map_tree->lock);
4905 		}
4906 	}
4907 	write_unlock(&map_tree->lock);
4908 
4909 	/*
4910 	 * Keep looping until we have no more ranges in the io tree.
4911 	 * We can have ongoing bios started by readahead that have
4912 	 * their endio callback (extent_io.c:end_bio_extent_readpage)
4913 	 * still in progress (unlocked the pages in the bio but did not yet
4914 	 * unlocked the ranges in the io tree). Therefore this means some
4915 	 * ranges can still be locked and eviction started because before
4916 	 * submitting those bios, which are executed by a separate task (work
4917 	 * queue kthread), inode references (inode->i_count) were not taken
4918 	 * (which would be dropped in the end io callback of each bio).
4919 	 * Therefore here we effectively end up waiting for those bios and
4920 	 * anyone else holding locked ranges without having bumped the inode's
4921 	 * reference count - if we don't do it, when they access the inode's
4922 	 * io_tree to unlock a range it may be too late, leading to an
4923 	 * use-after-free issue.
4924 	 */
4925 	spin_lock(&io_tree->lock);
4926 	while (!RB_EMPTY_ROOT(&io_tree->state)) {
4927 		struct extent_state *state;
4928 		struct extent_state *cached_state = NULL;
4929 		u64 start;
4930 		u64 end;
4931 		unsigned state_flags;
4932 
4933 		node = rb_first(&io_tree->state);
4934 		state = rb_entry(node, struct extent_state, rb_node);
4935 		start = state->start;
4936 		end = state->end;
4937 		state_flags = state->state;
4938 		spin_unlock(&io_tree->lock);
4939 
4940 		lock_extent_bits(io_tree, start, end, &cached_state);
4941 
4942 		/*
4943 		 * If still has DELALLOC flag, the extent didn't reach disk,
4944 		 * and its reserved space won't be freed by delayed_ref.
4945 		 * So we need to free its reserved space here.
4946 		 * (Refer to comment in btrfs_invalidatepage, case 2)
4947 		 *
4948 		 * Note, end is the bytenr of last byte, so we need + 1 here.
4949 		 */
4950 		if (state_flags & EXTENT_DELALLOC)
4951 			btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
4952 
4953 		clear_extent_bit(io_tree, start, end,
4954 				 EXTENT_LOCKED | EXTENT_DELALLOC |
4955 				 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
4956 				 &cached_state);
4957 
4958 		cond_resched();
4959 		spin_lock(&io_tree->lock);
4960 	}
4961 	spin_unlock(&io_tree->lock);
4962 }
4963 
4964 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
4965 							struct btrfs_block_rsv *rsv)
4966 {
4967 	struct btrfs_fs_info *fs_info = root->fs_info;
4968 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4969 	struct btrfs_trans_handle *trans;
4970 	u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
4971 	int ret;
4972 
4973 	/*
4974 	 * Eviction should be taking place at some place safe because of our
4975 	 * delayed iputs.  However the normal flushing code will run delayed
4976 	 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
4977 	 *
4978 	 * We reserve the delayed_refs_extra here again because we can't use
4979 	 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
4980 	 * above.  We reserve our extra bit here because we generate a ton of
4981 	 * delayed refs activity by truncating.
4982 	 *
4983 	 * If we cannot make our reservation we'll attempt to steal from the
4984 	 * global reserve, because we really want to be able to free up space.
4985 	 */
4986 	ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
4987 				     BTRFS_RESERVE_FLUSH_EVICT);
4988 	if (ret) {
4989 		/*
4990 		 * Try to steal from the global reserve if there is space for
4991 		 * it.
4992 		 */
4993 		if (btrfs_check_space_for_delayed_refs(fs_info) ||
4994 		    btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
4995 			btrfs_warn(fs_info,
4996 				   "could not allocate space for delete; will truncate on mount");
4997 			return ERR_PTR(-ENOSPC);
4998 		}
4999 		delayed_refs_extra = 0;
5000 	}
5001 
5002 	trans = btrfs_join_transaction(root);
5003 	if (IS_ERR(trans))
5004 		return trans;
5005 
5006 	if (delayed_refs_extra) {
5007 		trans->block_rsv = &fs_info->trans_block_rsv;
5008 		trans->bytes_reserved = delayed_refs_extra;
5009 		btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5010 					delayed_refs_extra, 1);
5011 	}
5012 	return trans;
5013 }
5014 
5015 void btrfs_evict_inode(struct inode *inode)
5016 {
5017 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5018 	struct btrfs_trans_handle *trans;
5019 	struct btrfs_root *root = BTRFS_I(inode)->root;
5020 	struct btrfs_block_rsv *rsv;
5021 	int ret;
5022 
5023 	trace_btrfs_inode_evict(inode);
5024 
5025 	if (!root) {
5026 		clear_inode(inode);
5027 		return;
5028 	}
5029 
5030 	evict_inode_truncate_pages(inode);
5031 
5032 	if (inode->i_nlink &&
5033 	    ((btrfs_root_refs(&root->root_item) != 0 &&
5034 	      root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5035 	     btrfs_is_free_space_inode(BTRFS_I(inode))))
5036 		goto no_delete;
5037 
5038 	if (is_bad_inode(inode))
5039 		goto no_delete;
5040 
5041 	btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5042 
5043 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5044 		goto no_delete;
5045 
5046 	if (inode->i_nlink > 0) {
5047 		BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5048 		       root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5049 		goto no_delete;
5050 	}
5051 
5052 	ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5053 	if (ret)
5054 		goto no_delete;
5055 
5056 	rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5057 	if (!rsv)
5058 		goto no_delete;
5059 	rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5060 	rsv->failfast = 1;
5061 
5062 	btrfs_i_size_write(BTRFS_I(inode), 0);
5063 
5064 	while (1) {
5065 		trans = evict_refill_and_join(root, rsv);
5066 		if (IS_ERR(trans))
5067 			goto free_rsv;
5068 
5069 		trans->block_rsv = rsv;
5070 
5071 		ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5072 		trans->block_rsv = &fs_info->trans_block_rsv;
5073 		btrfs_end_transaction(trans);
5074 		btrfs_btree_balance_dirty(fs_info);
5075 		if (ret && ret != -ENOSPC && ret != -EAGAIN)
5076 			goto free_rsv;
5077 		else if (!ret)
5078 			break;
5079 	}
5080 
5081 	/*
5082 	 * Errors here aren't a big deal, it just means we leave orphan items in
5083 	 * the tree. They will be cleaned up on the next mount. If the inode
5084 	 * number gets reused, cleanup deletes the orphan item without doing
5085 	 * anything, and unlink reuses the existing orphan item.
5086 	 *
5087 	 * If it turns out that we are dropping too many of these, we might want
5088 	 * to add a mechanism for retrying these after a commit.
5089 	 */
5090 	trans = evict_refill_and_join(root, rsv);
5091 	if (!IS_ERR(trans)) {
5092 		trans->block_rsv = rsv;
5093 		btrfs_orphan_del(trans, BTRFS_I(inode));
5094 		trans->block_rsv = &fs_info->trans_block_rsv;
5095 		btrfs_end_transaction(trans);
5096 	}
5097 
5098 	if (!(root == fs_info->tree_root ||
5099 	      root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5100 		btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5101 
5102 free_rsv:
5103 	btrfs_free_block_rsv(fs_info, rsv);
5104 no_delete:
5105 	/*
5106 	 * If we didn't successfully delete, the orphan item will still be in
5107 	 * the tree and we'll retry on the next mount. Again, we might also want
5108 	 * to retry these periodically in the future.
5109 	 */
5110 	btrfs_remove_delayed_node(BTRFS_I(inode));
5111 	clear_inode(inode);
5112 }
5113 
5114 /*
5115  * Return the key found in the dir entry in the location pointer, fill @type
5116  * with BTRFS_FT_*, and return 0.
5117  *
5118  * If no dir entries were found, returns -ENOENT.
5119  * If found a corrupted location in dir entry, returns -EUCLEAN.
5120  */
5121 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5122 			       struct btrfs_key *location, u8 *type)
5123 {
5124 	const char *name = dentry->d_name.name;
5125 	int namelen = dentry->d_name.len;
5126 	struct btrfs_dir_item *di;
5127 	struct btrfs_path *path;
5128 	struct btrfs_root *root = BTRFS_I(dir)->root;
5129 	int ret = 0;
5130 
5131 	path = btrfs_alloc_path();
5132 	if (!path)
5133 		return -ENOMEM;
5134 
5135 	di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5136 			name, namelen, 0);
5137 	if (IS_ERR_OR_NULL(di)) {
5138 		ret = di ? PTR_ERR(di) : -ENOENT;
5139 		goto out;
5140 	}
5141 
5142 	btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5143 	if (location->type != BTRFS_INODE_ITEM_KEY &&
5144 	    location->type != BTRFS_ROOT_ITEM_KEY) {
5145 		ret = -EUCLEAN;
5146 		btrfs_warn(root->fs_info,
5147 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5148 			   __func__, name, btrfs_ino(BTRFS_I(dir)),
5149 			   location->objectid, location->type, location->offset);
5150 	}
5151 	if (!ret)
5152 		*type = btrfs_dir_type(path->nodes[0], di);
5153 out:
5154 	btrfs_free_path(path);
5155 	return ret;
5156 }
5157 
5158 /*
5159  * when we hit a tree root in a directory, the btrfs part of the inode
5160  * needs to be changed to reflect the root directory of the tree root.  This
5161  * is kind of like crossing a mount point.
5162  */
5163 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5164 				    struct inode *dir,
5165 				    struct dentry *dentry,
5166 				    struct btrfs_key *location,
5167 				    struct btrfs_root **sub_root)
5168 {
5169 	struct btrfs_path *path;
5170 	struct btrfs_root *new_root;
5171 	struct btrfs_root_ref *ref;
5172 	struct extent_buffer *leaf;
5173 	struct btrfs_key key;
5174 	int ret;
5175 	int err = 0;
5176 
5177 	path = btrfs_alloc_path();
5178 	if (!path) {
5179 		err = -ENOMEM;
5180 		goto out;
5181 	}
5182 
5183 	err = -ENOENT;
5184 	key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5185 	key.type = BTRFS_ROOT_REF_KEY;
5186 	key.offset = location->objectid;
5187 
5188 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5189 	if (ret) {
5190 		if (ret < 0)
5191 			err = ret;
5192 		goto out;
5193 	}
5194 
5195 	leaf = path->nodes[0];
5196 	ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5197 	if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5198 	    btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5199 		goto out;
5200 
5201 	ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5202 				   (unsigned long)(ref + 1),
5203 				   dentry->d_name.len);
5204 	if (ret)
5205 		goto out;
5206 
5207 	btrfs_release_path(path);
5208 
5209 	new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5210 	if (IS_ERR(new_root)) {
5211 		err = PTR_ERR(new_root);
5212 		goto out;
5213 	}
5214 
5215 	*sub_root = new_root;
5216 	location->objectid = btrfs_root_dirid(&new_root->root_item);
5217 	location->type = BTRFS_INODE_ITEM_KEY;
5218 	location->offset = 0;
5219 	err = 0;
5220 out:
5221 	btrfs_free_path(path);
5222 	return err;
5223 }
5224 
5225 static void inode_tree_add(struct inode *inode)
5226 {
5227 	struct btrfs_root *root = BTRFS_I(inode)->root;
5228 	struct btrfs_inode *entry;
5229 	struct rb_node **p;
5230 	struct rb_node *parent;
5231 	struct rb_node *new = &BTRFS_I(inode)->rb_node;
5232 	u64 ino = btrfs_ino(BTRFS_I(inode));
5233 
5234 	if (inode_unhashed(inode))
5235 		return;
5236 	parent = NULL;
5237 	spin_lock(&root->inode_lock);
5238 	p = &root->inode_tree.rb_node;
5239 	while (*p) {
5240 		parent = *p;
5241 		entry = rb_entry(parent, struct btrfs_inode, rb_node);
5242 
5243 		if (ino < btrfs_ino(entry))
5244 			p = &parent->rb_left;
5245 		else if (ino > btrfs_ino(entry))
5246 			p = &parent->rb_right;
5247 		else {
5248 			WARN_ON(!(entry->vfs_inode.i_state &
5249 				  (I_WILL_FREE | I_FREEING)));
5250 			rb_replace_node(parent, new, &root->inode_tree);
5251 			RB_CLEAR_NODE(parent);
5252 			spin_unlock(&root->inode_lock);
5253 			return;
5254 		}
5255 	}
5256 	rb_link_node(new, parent, p);
5257 	rb_insert_color(new, &root->inode_tree);
5258 	spin_unlock(&root->inode_lock);
5259 }
5260 
5261 static void inode_tree_del(struct inode *inode)
5262 {
5263 	struct btrfs_root *root = BTRFS_I(inode)->root;
5264 	int empty = 0;
5265 
5266 	spin_lock(&root->inode_lock);
5267 	if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5268 		rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5269 		RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5270 		empty = RB_EMPTY_ROOT(&root->inode_tree);
5271 	}
5272 	spin_unlock(&root->inode_lock);
5273 
5274 	if (empty && btrfs_root_refs(&root->root_item) == 0) {
5275 		spin_lock(&root->inode_lock);
5276 		empty = RB_EMPTY_ROOT(&root->inode_tree);
5277 		spin_unlock(&root->inode_lock);
5278 		if (empty)
5279 			btrfs_add_dead_root(root);
5280 	}
5281 }
5282 
5283 
5284 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5285 {
5286 	struct btrfs_iget_args *args = p;
5287 
5288 	inode->i_ino = args->ino;
5289 	BTRFS_I(inode)->location.objectid = args->ino;
5290 	BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5291 	BTRFS_I(inode)->location.offset = 0;
5292 	BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5293 	BUG_ON(args->root && !BTRFS_I(inode)->root);
5294 	return 0;
5295 }
5296 
5297 static int btrfs_find_actor(struct inode *inode, void *opaque)
5298 {
5299 	struct btrfs_iget_args *args = opaque;
5300 
5301 	return args->ino == BTRFS_I(inode)->location.objectid &&
5302 		args->root == BTRFS_I(inode)->root;
5303 }
5304 
5305 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5306 				       struct btrfs_root *root)
5307 {
5308 	struct inode *inode;
5309 	struct btrfs_iget_args args;
5310 	unsigned long hashval = btrfs_inode_hash(ino, root);
5311 
5312 	args.ino = ino;
5313 	args.root = root;
5314 
5315 	inode = iget5_locked(s, hashval, btrfs_find_actor,
5316 			     btrfs_init_locked_inode,
5317 			     (void *)&args);
5318 	return inode;
5319 }
5320 
5321 /*
5322  * Get an inode object given its inode number and corresponding root.
5323  * Path can be preallocated to prevent recursing back to iget through
5324  * allocator. NULL is also valid but may require an additional allocation
5325  * later.
5326  */
5327 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5328 			      struct btrfs_root *root, struct btrfs_path *path)
5329 {
5330 	struct inode *inode;
5331 
5332 	inode = btrfs_iget_locked(s, ino, root);
5333 	if (!inode)
5334 		return ERR_PTR(-ENOMEM);
5335 
5336 	if (inode->i_state & I_NEW) {
5337 		int ret;
5338 
5339 		ret = btrfs_read_locked_inode(inode, path);
5340 		if (!ret) {
5341 			inode_tree_add(inode);
5342 			unlock_new_inode(inode);
5343 		} else {
5344 			iget_failed(inode);
5345 			/*
5346 			 * ret > 0 can come from btrfs_search_slot called by
5347 			 * btrfs_read_locked_inode, this means the inode item
5348 			 * was not found.
5349 			 */
5350 			if (ret > 0)
5351 				ret = -ENOENT;
5352 			inode = ERR_PTR(ret);
5353 		}
5354 	}
5355 
5356 	return inode;
5357 }
5358 
5359 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5360 {
5361 	return btrfs_iget_path(s, ino, root, NULL);
5362 }
5363 
5364 static struct inode *new_simple_dir(struct super_block *s,
5365 				    struct btrfs_key *key,
5366 				    struct btrfs_root *root)
5367 {
5368 	struct inode *inode = new_inode(s);
5369 
5370 	if (!inode)
5371 		return ERR_PTR(-ENOMEM);
5372 
5373 	BTRFS_I(inode)->root = btrfs_grab_root(root);
5374 	memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5375 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5376 
5377 	inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5378 	/*
5379 	 * We only need lookup, the rest is read-only and there's no inode
5380 	 * associated with the dentry
5381 	 */
5382 	inode->i_op = &simple_dir_inode_operations;
5383 	inode->i_opflags &= ~IOP_XATTR;
5384 	inode->i_fop = &simple_dir_operations;
5385 	inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5386 	inode->i_mtime = current_time(inode);
5387 	inode->i_atime = inode->i_mtime;
5388 	inode->i_ctime = inode->i_mtime;
5389 	BTRFS_I(inode)->i_otime = inode->i_mtime;
5390 
5391 	return inode;
5392 }
5393 
5394 static inline u8 btrfs_inode_type(struct inode *inode)
5395 {
5396 	/*
5397 	 * Compile-time asserts that generic FT_* types still match
5398 	 * BTRFS_FT_* types
5399 	 */
5400 	BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5401 	BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5402 	BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5403 	BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5404 	BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5405 	BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5406 	BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5407 	BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5408 
5409 	return fs_umode_to_ftype(inode->i_mode);
5410 }
5411 
5412 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5413 {
5414 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5415 	struct inode *inode;
5416 	struct btrfs_root *root = BTRFS_I(dir)->root;
5417 	struct btrfs_root *sub_root = root;
5418 	struct btrfs_key location;
5419 	u8 di_type = 0;
5420 	int ret = 0;
5421 
5422 	if (dentry->d_name.len > BTRFS_NAME_LEN)
5423 		return ERR_PTR(-ENAMETOOLONG);
5424 
5425 	ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5426 	if (ret < 0)
5427 		return ERR_PTR(ret);
5428 
5429 	if (location.type == BTRFS_INODE_ITEM_KEY) {
5430 		inode = btrfs_iget(dir->i_sb, location.objectid, root);
5431 		if (IS_ERR(inode))
5432 			return inode;
5433 
5434 		/* Do extra check against inode mode with di_type */
5435 		if (btrfs_inode_type(inode) != di_type) {
5436 			btrfs_crit(fs_info,
5437 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5438 				  inode->i_mode, btrfs_inode_type(inode),
5439 				  di_type);
5440 			iput(inode);
5441 			return ERR_PTR(-EUCLEAN);
5442 		}
5443 		return inode;
5444 	}
5445 
5446 	ret = fixup_tree_root_location(fs_info, dir, dentry,
5447 				       &location, &sub_root);
5448 	if (ret < 0) {
5449 		if (ret != -ENOENT)
5450 			inode = ERR_PTR(ret);
5451 		else
5452 			inode = new_simple_dir(dir->i_sb, &location, sub_root);
5453 	} else {
5454 		inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5455 	}
5456 	if (root != sub_root)
5457 		btrfs_put_root(sub_root);
5458 
5459 	if (!IS_ERR(inode) && root != sub_root) {
5460 		down_read(&fs_info->cleanup_work_sem);
5461 		if (!sb_rdonly(inode->i_sb))
5462 			ret = btrfs_orphan_cleanup(sub_root);
5463 		up_read(&fs_info->cleanup_work_sem);
5464 		if (ret) {
5465 			iput(inode);
5466 			inode = ERR_PTR(ret);
5467 		}
5468 	}
5469 
5470 	return inode;
5471 }
5472 
5473 static int btrfs_dentry_delete(const struct dentry *dentry)
5474 {
5475 	struct btrfs_root *root;
5476 	struct inode *inode = d_inode(dentry);
5477 
5478 	if (!inode && !IS_ROOT(dentry))
5479 		inode = d_inode(dentry->d_parent);
5480 
5481 	if (inode) {
5482 		root = BTRFS_I(inode)->root;
5483 		if (btrfs_root_refs(&root->root_item) == 0)
5484 			return 1;
5485 
5486 		if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5487 			return 1;
5488 	}
5489 	return 0;
5490 }
5491 
5492 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5493 				   unsigned int flags)
5494 {
5495 	struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5496 
5497 	if (inode == ERR_PTR(-ENOENT))
5498 		inode = NULL;
5499 	return d_splice_alias(inode, dentry);
5500 }
5501 
5502 /*
5503  * All this infrastructure exists because dir_emit can fault, and we are holding
5504  * the tree lock when doing readdir.  For now just allocate a buffer and copy
5505  * our information into that, and then dir_emit from the buffer.  This is
5506  * similar to what NFS does, only we don't keep the buffer around in pagecache
5507  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
5508  * copy_to_user_inatomic so we don't have to worry about page faulting under the
5509  * tree lock.
5510  */
5511 static int btrfs_opendir(struct inode *inode, struct file *file)
5512 {
5513 	struct btrfs_file_private *private;
5514 
5515 	private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5516 	if (!private)
5517 		return -ENOMEM;
5518 	private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5519 	if (!private->filldir_buf) {
5520 		kfree(private);
5521 		return -ENOMEM;
5522 	}
5523 	file->private_data = private;
5524 	return 0;
5525 }
5526 
5527 struct dir_entry {
5528 	u64 ino;
5529 	u64 offset;
5530 	unsigned type;
5531 	int name_len;
5532 };
5533 
5534 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5535 {
5536 	while (entries--) {
5537 		struct dir_entry *entry = addr;
5538 		char *name = (char *)(entry + 1);
5539 
5540 		ctx->pos = get_unaligned(&entry->offset);
5541 		if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5542 					 get_unaligned(&entry->ino),
5543 					 get_unaligned(&entry->type)))
5544 			return 1;
5545 		addr += sizeof(struct dir_entry) +
5546 			get_unaligned(&entry->name_len);
5547 		ctx->pos++;
5548 	}
5549 	return 0;
5550 }
5551 
5552 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5553 {
5554 	struct inode *inode = file_inode(file);
5555 	struct btrfs_root *root = BTRFS_I(inode)->root;
5556 	struct btrfs_file_private *private = file->private_data;
5557 	struct btrfs_dir_item *di;
5558 	struct btrfs_key key;
5559 	struct btrfs_key found_key;
5560 	struct btrfs_path *path;
5561 	void *addr;
5562 	struct list_head ins_list;
5563 	struct list_head del_list;
5564 	int ret;
5565 	struct extent_buffer *leaf;
5566 	int slot;
5567 	char *name_ptr;
5568 	int name_len;
5569 	int entries = 0;
5570 	int total_len = 0;
5571 	bool put = false;
5572 	struct btrfs_key location;
5573 
5574 	if (!dir_emit_dots(file, ctx))
5575 		return 0;
5576 
5577 	path = btrfs_alloc_path();
5578 	if (!path)
5579 		return -ENOMEM;
5580 
5581 	addr = private->filldir_buf;
5582 	path->reada = READA_FORWARD;
5583 
5584 	INIT_LIST_HEAD(&ins_list);
5585 	INIT_LIST_HEAD(&del_list);
5586 	put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5587 
5588 again:
5589 	key.type = BTRFS_DIR_INDEX_KEY;
5590 	key.offset = ctx->pos;
5591 	key.objectid = btrfs_ino(BTRFS_I(inode));
5592 
5593 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5594 	if (ret < 0)
5595 		goto err;
5596 
5597 	while (1) {
5598 		struct dir_entry *entry;
5599 
5600 		leaf = path->nodes[0];
5601 		slot = path->slots[0];
5602 		if (slot >= btrfs_header_nritems(leaf)) {
5603 			ret = btrfs_next_leaf(root, path);
5604 			if (ret < 0)
5605 				goto err;
5606 			else if (ret > 0)
5607 				break;
5608 			continue;
5609 		}
5610 
5611 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
5612 
5613 		if (found_key.objectid != key.objectid)
5614 			break;
5615 		if (found_key.type != BTRFS_DIR_INDEX_KEY)
5616 			break;
5617 		if (found_key.offset < ctx->pos)
5618 			goto next;
5619 		if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5620 			goto next;
5621 		di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5622 		name_len = btrfs_dir_name_len(leaf, di);
5623 		if ((total_len + sizeof(struct dir_entry) + name_len) >=
5624 		    PAGE_SIZE) {
5625 			btrfs_release_path(path);
5626 			ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5627 			if (ret)
5628 				goto nopos;
5629 			addr = private->filldir_buf;
5630 			entries = 0;
5631 			total_len = 0;
5632 			goto again;
5633 		}
5634 
5635 		entry = addr;
5636 		put_unaligned(name_len, &entry->name_len);
5637 		name_ptr = (char *)(entry + 1);
5638 		read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5639 				   name_len);
5640 		put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5641 				&entry->type);
5642 		btrfs_dir_item_key_to_cpu(leaf, di, &location);
5643 		put_unaligned(location.objectid, &entry->ino);
5644 		put_unaligned(found_key.offset, &entry->offset);
5645 		entries++;
5646 		addr += sizeof(struct dir_entry) + name_len;
5647 		total_len += sizeof(struct dir_entry) + name_len;
5648 next:
5649 		path->slots[0]++;
5650 	}
5651 	btrfs_release_path(path);
5652 
5653 	ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5654 	if (ret)
5655 		goto nopos;
5656 
5657 	ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5658 	if (ret)
5659 		goto nopos;
5660 
5661 	/*
5662 	 * Stop new entries from being returned after we return the last
5663 	 * entry.
5664 	 *
5665 	 * New directory entries are assigned a strictly increasing
5666 	 * offset.  This means that new entries created during readdir
5667 	 * are *guaranteed* to be seen in the future by that readdir.
5668 	 * This has broken buggy programs which operate on names as
5669 	 * they're returned by readdir.  Until we re-use freed offsets
5670 	 * we have this hack to stop new entries from being returned
5671 	 * under the assumption that they'll never reach this huge
5672 	 * offset.
5673 	 *
5674 	 * This is being careful not to overflow 32bit loff_t unless the
5675 	 * last entry requires it because doing so has broken 32bit apps
5676 	 * in the past.
5677 	 */
5678 	if (ctx->pos >= INT_MAX)
5679 		ctx->pos = LLONG_MAX;
5680 	else
5681 		ctx->pos = INT_MAX;
5682 nopos:
5683 	ret = 0;
5684 err:
5685 	if (put)
5686 		btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5687 	btrfs_free_path(path);
5688 	return ret;
5689 }
5690 
5691 /*
5692  * This is somewhat expensive, updating the tree every time the
5693  * inode changes.  But, it is most likely to find the inode in cache.
5694  * FIXME, needs more benchmarking...there are no reasons other than performance
5695  * to keep or drop this code.
5696  */
5697 static int btrfs_dirty_inode(struct inode *inode)
5698 {
5699 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5700 	struct btrfs_root *root = BTRFS_I(inode)->root;
5701 	struct btrfs_trans_handle *trans;
5702 	int ret;
5703 
5704 	if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5705 		return 0;
5706 
5707 	trans = btrfs_join_transaction(root);
5708 	if (IS_ERR(trans))
5709 		return PTR_ERR(trans);
5710 
5711 	ret = btrfs_update_inode(trans, root, inode);
5712 	if (ret && ret == -ENOSPC) {
5713 		/* whoops, lets try again with the full transaction */
5714 		btrfs_end_transaction(trans);
5715 		trans = btrfs_start_transaction(root, 1);
5716 		if (IS_ERR(trans))
5717 			return PTR_ERR(trans);
5718 
5719 		ret = btrfs_update_inode(trans, root, inode);
5720 	}
5721 	btrfs_end_transaction(trans);
5722 	if (BTRFS_I(inode)->delayed_node)
5723 		btrfs_balance_delayed_items(fs_info);
5724 
5725 	return ret;
5726 }
5727 
5728 /*
5729  * This is a copy of file_update_time.  We need this so we can return error on
5730  * ENOSPC for updating the inode in the case of file write and mmap writes.
5731  */
5732 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
5733 			     int flags)
5734 {
5735 	struct btrfs_root *root = BTRFS_I(inode)->root;
5736 	bool dirty = flags & ~S_VERSION;
5737 
5738 	if (btrfs_root_readonly(root))
5739 		return -EROFS;
5740 
5741 	if (flags & S_VERSION)
5742 		dirty |= inode_maybe_inc_iversion(inode, dirty);
5743 	if (flags & S_CTIME)
5744 		inode->i_ctime = *now;
5745 	if (flags & S_MTIME)
5746 		inode->i_mtime = *now;
5747 	if (flags & S_ATIME)
5748 		inode->i_atime = *now;
5749 	return dirty ? btrfs_dirty_inode(inode) : 0;
5750 }
5751 
5752 /*
5753  * find the highest existing sequence number in a directory
5754  * and then set the in-memory index_cnt variable to reflect
5755  * free sequence numbers
5756  */
5757 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5758 {
5759 	struct btrfs_root *root = inode->root;
5760 	struct btrfs_key key, found_key;
5761 	struct btrfs_path *path;
5762 	struct extent_buffer *leaf;
5763 	int ret;
5764 
5765 	key.objectid = btrfs_ino(inode);
5766 	key.type = BTRFS_DIR_INDEX_KEY;
5767 	key.offset = (u64)-1;
5768 
5769 	path = btrfs_alloc_path();
5770 	if (!path)
5771 		return -ENOMEM;
5772 
5773 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5774 	if (ret < 0)
5775 		goto out;
5776 	/* FIXME: we should be able to handle this */
5777 	if (ret == 0)
5778 		goto out;
5779 	ret = 0;
5780 
5781 	/*
5782 	 * MAGIC NUMBER EXPLANATION:
5783 	 * since we search a directory based on f_pos we have to start at 2
5784 	 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5785 	 * else has to start at 2
5786 	 */
5787 	if (path->slots[0] == 0) {
5788 		inode->index_cnt = 2;
5789 		goto out;
5790 	}
5791 
5792 	path->slots[0]--;
5793 
5794 	leaf = path->nodes[0];
5795 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5796 
5797 	if (found_key.objectid != btrfs_ino(inode) ||
5798 	    found_key.type != BTRFS_DIR_INDEX_KEY) {
5799 		inode->index_cnt = 2;
5800 		goto out;
5801 	}
5802 
5803 	inode->index_cnt = found_key.offset + 1;
5804 out:
5805 	btrfs_free_path(path);
5806 	return ret;
5807 }
5808 
5809 /*
5810  * helper to find a free sequence number in a given directory.  This current
5811  * code is very simple, later versions will do smarter things in the btree
5812  */
5813 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
5814 {
5815 	int ret = 0;
5816 
5817 	if (dir->index_cnt == (u64)-1) {
5818 		ret = btrfs_inode_delayed_dir_index_count(dir);
5819 		if (ret) {
5820 			ret = btrfs_set_inode_index_count(dir);
5821 			if (ret)
5822 				return ret;
5823 		}
5824 	}
5825 
5826 	*index = dir->index_cnt;
5827 	dir->index_cnt++;
5828 
5829 	return ret;
5830 }
5831 
5832 static int btrfs_insert_inode_locked(struct inode *inode)
5833 {
5834 	struct btrfs_iget_args args;
5835 
5836 	args.ino = BTRFS_I(inode)->location.objectid;
5837 	args.root = BTRFS_I(inode)->root;
5838 
5839 	return insert_inode_locked4(inode,
5840 		   btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5841 		   btrfs_find_actor, &args);
5842 }
5843 
5844 /*
5845  * Inherit flags from the parent inode.
5846  *
5847  * Currently only the compression flags and the cow flags are inherited.
5848  */
5849 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
5850 {
5851 	unsigned int flags;
5852 
5853 	if (!dir)
5854 		return;
5855 
5856 	flags = BTRFS_I(dir)->flags;
5857 
5858 	if (flags & BTRFS_INODE_NOCOMPRESS) {
5859 		BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
5860 		BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
5861 	} else if (flags & BTRFS_INODE_COMPRESS) {
5862 		BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
5863 		BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
5864 	}
5865 
5866 	if (flags & BTRFS_INODE_NODATACOW) {
5867 		BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
5868 		if (S_ISREG(inode->i_mode))
5869 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5870 	}
5871 
5872 	btrfs_sync_inode_flags_to_i_flags(inode);
5873 }
5874 
5875 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5876 				     struct btrfs_root *root,
5877 				     struct inode *dir,
5878 				     const char *name, int name_len,
5879 				     u64 ref_objectid, u64 objectid,
5880 				     umode_t mode, u64 *index)
5881 {
5882 	struct btrfs_fs_info *fs_info = root->fs_info;
5883 	struct inode *inode;
5884 	struct btrfs_inode_item *inode_item;
5885 	struct btrfs_key *location;
5886 	struct btrfs_path *path;
5887 	struct btrfs_inode_ref *ref;
5888 	struct btrfs_key key[2];
5889 	u32 sizes[2];
5890 	int nitems = name ? 2 : 1;
5891 	unsigned long ptr;
5892 	unsigned int nofs_flag;
5893 	int ret;
5894 
5895 	path = btrfs_alloc_path();
5896 	if (!path)
5897 		return ERR_PTR(-ENOMEM);
5898 
5899 	nofs_flag = memalloc_nofs_save();
5900 	inode = new_inode(fs_info->sb);
5901 	memalloc_nofs_restore(nofs_flag);
5902 	if (!inode) {
5903 		btrfs_free_path(path);
5904 		return ERR_PTR(-ENOMEM);
5905 	}
5906 
5907 	/*
5908 	 * O_TMPFILE, set link count to 0, so that after this point,
5909 	 * we fill in an inode item with the correct link count.
5910 	 */
5911 	if (!name)
5912 		set_nlink(inode, 0);
5913 
5914 	/*
5915 	 * we have to initialize this early, so we can reclaim the inode
5916 	 * number if we fail afterwards in this function.
5917 	 */
5918 	inode->i_ino = objectid;
5919 
5920 	if (dir && name) {
5921 		trace_btrfs_inode_request(dir);
5922 
5923 		ret = btrfs_set_inode_index(BTRFS_I(dir), index);
5924 		if (ret) {
5925 			btrfs_free_path(path);
5926 			iput(inode);
5927 			return ERR_PTR(ret);
5928 		}
5929 	} else if (dir) {
5930 		*index = 0;
5931 	}
5932 	/*
5933 	 * index_cnt is ignored for everything but a dir,
5934 	 * btrfs_set_inode_index_count has an explanation for the magic
5935 	 * number
5936 	 */
5937 	BTRFS_I(inode)->index_cnt = 2;
5938 	BTRFS_I(inode)->dir_index = *index;
5939 	BTRFS_I(inode)->root = btrfs_grab_root(root);
5940 	BTRFS_I(inode)->generation = trans->transid;
5941 	inode->i_generation = BTRFS_I(inode)->generation;
5942 
5943 	/*
5944 	 * We could have gotten an inode number from somebody who was fsynced
5945 	 * and then removed in this same transaction, so let's just set full
5946 	 * sync since it will be a full sync anyway and this will blow away the
5947 	 * old info in the log.
5948 	 */
5949 	set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5950 
5951 	key[0].objectid = objectid;
5952 	key[0].type = BTRFS_INODE_ITEM_KEY;
5953 	key[0].offset = 0;
5954 
5955 	sizes[0] = sizeof(struct btrfs_inode_item);
5956 
5957 	if (name) {
5958 		/*
5959 		 * Start new inodes with an inode_ref. This is slightly more
5960 		 * efficient for small numbers of hard links since they will
5961 		 * be packed into one item. Extended refs will kick in if we
5962 		 * add more hard links than can fit in the ref item.
5963 		 */
5964 		key[1].objectid = objectid;
5965 		key[1].type = BTRFS_INODE_REF_KEY;
5966 		key[1].offset = ref_objectid;
5967 
5968 		sizes[1] = name_len + sizeof(*ref);
5969 	}
5970 
5971 	location = &BTRFS_I(inode)->location;
5972 	location->objectid = objectid;
5973 	location->offset = 0;
5974 	location->type = BTRFS_INODE_ITEM_KEY;
5975 
5976 	ret = btrfs_insert_inode_locked(inode);
5977 	if (ret < 0) {
5978 		iput(inode);
5979 		goto fail;
5980 	}
5981 
5982 	path->leave_spinning = 1;
5983 	ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5984 	if (ret != 0)
5985 		goto fail_unlock;
5986 
5987 	inode_init_owner(inode, dir, mode);
5988 	inode_set_bytes(inode, 0);
5989 
5990 	inode->i_mtime = current_time(inode);
5991 	inode->i_atime = inode->i_mtime;
5992 	inode->i_ctime = inode->i_mtime;
5993 	BTRFS_I(inode)->i_otime = inode->i_mtime;
5994 
5995 	inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5996 				  struct btrfs_inode_item);
5997 	memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
5998 			     sizeof(*inode_item));
5999 	fill_inode_item(trans, path->nodes[0], inode_item, inode);
6000 
6001 	if (name) {
6002 		ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6003 				     struct btrfs_inode_ref);
6004 		btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6005 		btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6006 		ptr = (unsigned long)(ref + 1);
6007 		write_extent_buffer(path->nodes[0], name, ptr, name_len);
6008 	}
6009 
6010 	btrfs_mark_buffer_dirty(path->nodes[0]);
6011 	btrfs_free_path(path);
6012 
6013 	btrfs_inherit_iflags(inode, dir);
6014 
6015 	if (S_ISREG(mode)) {
6016 		if (btrfs_test_opt(fs_info, NODATASUM))
6017 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6018 		if (btrfs_test_opt(fs_info, NODATACOW))
6019 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6020 				BTRFS_INODE_NODATASUM;
6021 	}
6022 
6023 	inode_tree_add(inode);
6024 
6025 	trace_btrfs_inode_new(inode);
6026 	btrfs_set_inode_last_trans(trans, inode);
6027 
6028 	btrfs_update_root_times(trans, root);
6029 
6030 	ret = btrfs_inode_inherit_props(trans, inode, dir);
6031 	if (ret)
6032 		btrfs_err(fs_info,
6033 			  "error inheriting props for ino %llu (root %llu): %d",
6034 			btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6035 
6036 	return inode;
6037 
6038 fail_unlock:
6039 	discard_new_inode(inode);
6040 fail:
6041 	if (dir && name)
6042 		BTRFS_I(dir)->index_cnt--;
6043 	btrfs_free_path(path);
6044 	return ERR_PTR(ret);
6045 }
6046 
6047 /*
6048  * utility function to add 'inode' into 'parent_inode' with
6049  * a give name and a given sequence number.
6050  * if 'add_backref' is true, also insert a backref from the
6051  * inode to the parent directory.
6052  */
6053 int btrfs_add_link(struct btrfs_trans_handle *trans,
6054 		   struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6055 		   const char *name, int name_len, int add_backref, u64 index)
6056 {
6057 	int ret = 0;
6058 	struct btrfs_key key;
6059 	struct btrfs_root *root = parent_inode->root;
6060 	u64 ino = btrfs_ino(inode);
6061 	u64 parent_ino = btrfs_ino(parent_inode);
6062 
6063 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6064 		memcpy(&key, &inode->root->root_key, sizeof(key));
6065 	} else {
6066 		key.objectid = ino;
6067 		key.type = BTRFS_INODE_ITEM_KEY;
6068 		key.offset = 0;
6069 	}
6070 
6071 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6072 		ret = btrfs_add_root_ref(trans, key.objectid,
6073 					 root->root_key.objectid, parent_ino,
6074 					 index, name, name_len);
6075 	} else if (add_backref) {
6076 		ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6077 					     parent_ino, index);
6078 	}
6079 
6080 	/* Nothing to clean up yet */
6081 	if (ret)
6082 		return ret;
6083 
6084 	ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6085 				    btrfs_inode_type(&inode->vfs_inode), index);
6086 	if (ret == -EEXIST || ret == -EOVERFLOW)
6087 		goto fail_dir_item;
6088 	else if (ret) {
6089 		btrfs_abort_transaction(trans, ret);
6090 		return ret;
6091 	}
6092 
6093 	btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6094 			   name_len * 2);
6095 	inode_inc_iversion(&parent_inode->vfs_inode);
6096 	/*
6097 	 * If we are replaying a log tree, we do not want to update the mtime
6098 	 * and ctime of the parent directory with the current time, since the
6099 	 * log replay procedure is responsible for setting them to their correct
6100 	 * values (the ones it had when the fsync was done).
6101 	 */
6102 	if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6103 		struct timespec64 now = current_time(&parent_inode->vfs_inode);
6104 
6105 		parent_inode->vfs_inode.i_mtime = now;
6106 		parent_inode->vfs_inode.i_ctime = now;
6107 	}
6108 	ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6109 	if (ret)
6110 		btrfs_abort_transaction(trans, ret);
6111 	return ret;
6112 
6113 fail_dir_item:
6114 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6115 		u64 local_index;
6116 		int err;
6117 		err = btrfs_del_root_ref(trans, key.objectid,
6118 					 root->root_key.objectid, parent_ino,
6119 					 &local_index, name, name_len);
6120 		if (err)
6121 			btrfs_abort_transaction(trans, err);
6122 	} else if (add_backref) {
6123 		u64 local_index;
6124 		int err;
6125 
6126 		err = btrfs_del_inode_ref(trans, root, name, name_len,
6127 					  ino, parent_ino, &local_index);
6128 		if (err)
6129 			btrfs_abort_transaction(trans, err);
6130 	}
6131 
6132 	/* Return the original error code */
6133 	return ret;
6134 }
6135 
6136 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6137 			    struct btrfs_inode *dir, struct dentry *dentry,
6138 			    struct btrfs_inode *inode, int backref, u64 index)
6139 {
6140 	int err = btrfs_add_link(trans, dir, inode,
6141 				 dentry->d_name.name, dentry->d_name.len,
6142 				 backref, index);
6143 	if (err > 0)
6144 		err = -EEXIST;
6145 	return err;
6146 }
6147 
6148 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6149 			umode_t mode, dev_t rdev)
6150 {
6151 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6152 	struct btrfs_trans_handle *trans;
6153 	struct btrfs_root *root = BTRFS_I(dir)->root;
6154 	struct inode *inode = NULL;
6155 	int err;
6156 	u64 objectid;
6157 	u64 index = 0;
6158 
6159 	/*
6160 	 * 2 for inode item and ref
6161 	 * 2 for dir items
6162 	 * 1 for xattr if selinux is on
6163 	 */
6164 	trans = btrfs_start_transaction(root, 5);
6165 	if (IS_ERR(trans))
6166 		return PTR_ERR(trans);
6167 
6168 	err = btrfs_find_free_ino(root, &objectid);
6169 	if (err)
6170 		goto out_unlock;
6171 
6172 	inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6173 			dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6174 			mode, &index);
6175 	if (IS_ERR(inode)) {
6176 		err = PTR_ERR(inode);
6177 		inode = NULL;
6178 		goto out_unlock;
6179 	}
6180 
6181 	/*
6182 	* If the active LSM wants to access the inode during
6183 	* d_instantiate it needs these. Smack checks to see
6184 	* if the filesystem supports xattrs by looking at the
6185 	* ops vector.
6186 	*/
6187 	inode->i_op = &btrfs_special_inode_operations;
6188 	init_special_inode(inode, inode->i_mode, rdev);
6189 
6190 	err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6191 	if (err)
6192 		goto out_unlock;
6193 
6194 	err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6195 			0, index);
6196 	if (err)
6197 		goto out_unlock;
6198 
6199 	btrfs_update_inode(trans, root, inode);
6200 	d_instantiate_new(dentry, inode);
6201 
6202 out_unlock:
6203 	btrfs_end_transaction(trans);
6204 	btrfs_btree_balance_dirty(fs_info);
6205 	if (err && inode) {
6206 		inode_dec_link_count(inode);
6207 		discard_new_inode(inode);
6208 	}
6209 	return err;
6210 }
6211 
6212 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6213 			umode_t mode, bool excl)
6214 {
6215 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6216 	struct btrfs_trans_handle *trans;
6217 	struct btrfs_root *root = BTRFS_I(dir)->root;
6218 	struct inode *inode = NULL;
6219 	int err;
6220 	u64 objectid;
6221 	u64 index = 0;
6222 
6223 	/*
6224 	 * 2 for inode item and ref
6225 	 * 2 for dir items
6226 	 * 1 for xattr if selinux is on
6227 	 */
6228 	trans = btrfs_start_transaction(root, 5);
6229 	if (IS_ERR(trans))
6230 		return PTR_ERR(trans);
6231 
6232 	err = btrfs_find_free_ino(root, &objectid);
6233 	if (err)
6234 		goto out_unlock;
6235 
6236 	inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6237 			dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6238 			mode, &index);
6239 	if (IS_ERR(inode)) {
6240 		err = PTR_ERR(inode);
6241 		inode = NULL;
6242 		goto out_unlock;
6243 	}
6244 	/*
6245 	* If the active LSM wants to access the inode during
6246 	* d_instantiate it needs these. Smack checks to see
6247 	* if the filesystem supports xattrs by looking at the
6248 	* ops vector.
6249 	*/
6250 	inode->i_fop = &btrfs_file_operations;
6251 	inode->i_op = &btrfs_file_inode_operations;
6252 	inode->i_mapping->a_ops = &btrfs_aops;
6253 
6254 	err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6255 	if (err)
6256 		goto out_unlock;
6257 
6258 	err = btrfs_update_inode(trans, root, inode);
6259 	if (err)
6260 		goto out_unlock;
6261 
6262 	err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6263 			0, index);
6264 	if (err)
6265 		goto out_unlock;
6266 
6267 	BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6268 	d_instantiate_new(dentry, inode);
6269 
6270 out_unlock:
6271 	btrfs_end_transaction(trans);
6272 	if (err && inode) {
6273 		inode_dec_link_count(inode);
6274 		discard_new_inode(inode);
6275 	}
6276 	btrfs_btree_balance_dirty(fs_info);
6277 	return err;
6278 }
6279 
6280 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6281 		      struct dentry *dentry)
6282 {
6283 	struct btrfs_trans_handle *trans = NULL;
6284 	struct btrfs_root *root = BTRFS_I(dir)->root;
6285 	struct inode *inode = d_inode(old_dentry);
6286 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6287 	u64 index;
6288 	int err;
6289 	int drop_inode = 0;
6290 
6291 	/* do not allow sys_link's with other subvols of the same device */
6292 	if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6293 		return -EXDEV;
6294 
6295 	if (inode->i_nlink >= BTRFS_LINK_MAX)
6296 		return -EMLINK;
6297 
6298 	err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6299 	if (err)
6300 		goto fail;
6301 
6302 	/*
6303 	 * 2 items for inode and inode ref
6304 	 * 2 items for dir items
6305 	 * 1 item for parent inode
6306 	 * 1 item for orphan item deletion if O_TMPFILE
6307 	 */
6308 	trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6309 	if (IS_ERR(trans)) {
6310 		err = PTR_ERR(trans);
6311 		trans = NULL;
6312 		goto fail;
6313 	}
6314 
6315 	/* There are several dir indexes for this inode, clear the cache. */
6316 	BTRFS_I(inode)->dir_index = 0ULL;
6317 	inc_nlink(inode);
6318 	inode_inc_iversion(inode);
6319 	inode->i_ctime = current_time(inode);
6320 	ihold(inode);
6321 	set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6322 
6323 	err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6324 			1, index);
6325 
6326 	if (err) {
6327 		drop_inode = 1;
6328 	} else {
6329 		struct dentry *parent = dentry->d_parent;
6330 		int ret;
6331 
6332 		err = btrfs_update_inode(trans, root, inode);
6333 		if (err)
6334 			goto fail;
6335 		if (inode->i_nlink == 1) {
6336 			/*
6337 			 * If new hard link count is 1, it's a file created
6338 			 * with open(2) O_TMPFILE flag.
6339 			 */
6340 			err = btrfs_orphan_del(trans, BTRFS_I(inode));
6341 			if (err)
6342 				goto fail;
6343 		}
6344 		d_instantiate(dentry, inode);
6345 		ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6346 					 true, NULL);
6347 		if (ret == BTRFS_NEED_TRANS_COMMIT) {
6348 			err = btrfs_commit_transaction(trans);
6349 			trans = NULL;
6350 		}
6351 	}
6352 
6353 fail:
6354 	if (trans)
6355 		btrfs_end_transaction(trans);
6356 	if (drop_inode) {
6357 		inode_dec_link_count(inode);
6358 		iput(inode);
6359 	}
6360 	btrfs_btree_balance_dirty(fs_info);
6361 	return err;
6362 }
6363 
6364 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6365 {
6366 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6367 	struct inode *inode = NULL;
6368 	struct btrfs_trans_handle *trans;
6369 	struct btrfs_root *root = BTRFS_I(dir)->root;
6370 	int err = 0;
6371 	u64 objectid = 0;
6372 	u64 index = 0;
6373 
6374 	/*
6375 	 * 2 items for inode and ref
6376 	 * 2 items for dir items
6377 	 * 1 for xattr if selinux is on
6378 	 */
6379 	trans = btrfs_start_transaction(root, 5);
6380 	if (IS_ERR(trans))
6381 		return PTR_ERR(trans);
6382 
6383 	err = btrfs_find_free_ino(root, &objectid);
6384 	if (err)
6385 		goto out_fail;
6386 
6387 	inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6388 			dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6389 			S_IFDIR | mode, &index);
6390 	if (IS_ERR(inode)) {
6391 		err = PTR_ERR(inode);
6392 		inode = NULL;
6393 		goto out_fail;
6394 	}
6395 
6396 	/* these must be set before we unlock the inode */
6397 	inode->i_op = &btrfs_dir_inode_operations;
6398 	inode->i_fop = &btrfs_dir_file_operations;
6399 
6400 	err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6401 	if (err)
6402 		goto out_fail;
6403 
6404 	btrfs_i_size_write(BTRFS_I(inode), 0);
6405 	err = btrfs_update_inode(trans, root, inode);
6406 	if (err)
6407 		goto out_fail;
6408 
6409 	err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6410 			dentry->d_name.name,
6411 			dentry->d_name.len, 0, index);
6412 	if (err)
6413 		goto out_fail;
6414 
6415 	d_instantiate_new(dentry, inode);
6416 
6417 out_fail:
6418 	btrfs_end_transaction(trans);
6419 	if (err && inode) {
6420 		inode_dec_link_count(inode);
6421 		discard_new_inode(inode);
6422 	}
6423 	btrfs_btree_balance_dirty(fs_info);
6424 	return err;
6425 }
6426 
6427 static noinline int uncompress_inline(struct btrfs_path *path,
6428 				      struct page *page,
6429 				      size_t pg_offset, u64 extent_offset,
6430 				      struct btrfs_file_extent_item *item)
6431 {
6432 	int ret;
6433 	struct extent_buffer *leaf = path->nodes[0];
6434 	char *tmp;
6435 	size_t max_size;
6436 	unsigned long inline_size;
6437 	unsigned long ptr;
6438 	int compress_type;
6439 
6440 	WARN_ON(pg_offset != 0);
6441 	compress_type = btrfs_file_extent_compression(leaf, item);
6442 	max_size = btrfs_file_extent_ram_bytes(leaf, item);
6443 	inline_size = btrfs_file_extent_inline_item_len(leaf,
6444 					btrfs_item_nr(path->slots[0]));
6445 	tmp = kmalloc(inline_size, GFP_NOFS);
6446 	if (!tmp)
6447 		return -ENOMEM;
6448 	ptr = btrfs_file_extent_inline_start(item);
6449 
6450 	read_extent_buffer(leaf, tmp, ptr, inline_size);
6451 
6452 	max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6453 	ret = btrfs_decompress(compress_type, tmp, page,
6454 			       extent_offset, inline_size, max_size);
6455 
6456 	/*
6457 	 * decompression code contains a memset to fill in any space between the end
6458 	 * of the uncompressed data and the end of max_size in case the decompressed
6459 	 * data ends up shorter than ram_bytes.  That doesn't cover the hole between
6460 	 * the end of an inline extent and the beginning of the next block, so we
6461 	 * cover that region here.
6462 	 */
6463 
6464 	if (max_size + pg_offset < PAGE_SIZE) {
6465 		char *map = kmap(page);
6466 		memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6467 		kunmap(page);
6468 	}
6469 	kfree(tmp);
6470 	return ret;
6471 }
6472 
6473 /**
6474  * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6475  * @inode:	file to search in
6476  * @page:	page to read extent data into if the extent is inline
6477  * @pg_offset:	offset into @page to copy to
6478  * @start:	file offset
6479  * @len:	length of range starting at @start
6480  *
6481  * This returns the first &struct extent_map which overlaps with the given
6482  * range, reading it from the B-tree and caching it if necessary. Note that
6483  * there may be more extents which overlap the given range after the returned
6484  * extent_map.
6485  *
6486  * If @page is not NULL and the extent is inline, this also reads the extent
6487  * data directly into the page and marks the extent up to date in the io_tree.
6488  *
6489  * Return: ERR_PTR on error, non-NULL extent_map on success.
6490  */
6491 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6492 				    struct page *page, size_t pg_offset,
6493 				    u64 start, u64 len)
6494 {
6495 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
6496 	int ret;
6497 	int err = 0;
6498 	u64 extent_start = 0;
6499 	u64 extent_end = 0;
6500 	u64 objectid = btrfs_ino(inode);
6501 	int extent_type = -1;
6502 	struct btrfs_path *path = NULL;
6503 	struct btrfs_root *root = inode->root;
6504 	struct btrfs_file_extent_item *item;
6505 	struct extent_buffer *leaf;
6506 	struct btrfs_key found_key;
6507 	struct extent_map *em = NULL;
6508 	struct extent_map_tree *em_tree = &inode->extent_tree;
6509 	struct extent_io_tree *io_tree = &inode->io_tree;
6510 
6511 	read_lock(&em_tree->lock);
6512 	em = lookup_extent_mapping(em_tree, start, len);
6513 	read_unlock(&em_tree->lock);
6514 
6515 	if (em) {
6516 		if (em->start > start || em->start + em->len <= start)
6517 			free_extent_map(em);
6518 		else if (em->block_start == EXTENT_MAP_INLINE && page)
6519 			free_extent_map(em);
6520 		else
6521 			goto out;
6522 	}
6523 	em = alloc_extent_map();
6524 	if (!em) {
6525 		err = -ENOMEM;
6526 		goto out;
6527 	}
6528 	em->start = EXTENT_MAP_HOLE;
6529 	em->orig_start = EXTENT_MAP_HOLE;
6530 	em->len = (u64)-1;
6531 	em->block_len = (u64)-1;
6532 
6533 	path = btrfs_alloc_path();
6534 	if (!path) {
6535 		err = -ENOMEM;
6536 		goto out;
6537 	}
6538 
6539 	/* Chances are we'll be called again, so go ahead and do readahead */
6540 	path->reada = READA_FORWARD;
6541 
6542 	/*
6543 	 * Unless we're going to uncompress the inline extent, no sleep would
6544 	 * happen.
6545 	 */
6546 	path->leave_spinning = 1;
6547 
6548 	ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6549 	if (ret < 0) {
6550 		err = ret;
6551 		goto out;
6552 	} else if (ret > 0) {
6553 		if (path->slots[0] == 0)
6554 			goto not_found;
6555 		path->slots[0]--;
6556 	}
6557 
6558 	leaf = path->nodes[0];
6559 	item = btrfs_item_ptr(leaf, path->slots[0],
6560 			      struct btrfs_file_extent_item);
6561 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6562 	if (found_key.objectid != objectid ||
6563 	    found_key.type != BTRFS_EXTENT_DATA_KEY) {
6564 		/*
6565 		 * If we backup past the first extent we want to move forward
6566 		 * and see if there is an extent in front of us, otherwise we'll
6567 		 * say there is a hole for our whole search range which can
6568 		 * cause problems.
6569 		 */
6570 		extent_end = start;
6571 		goto next;
6572 	}
6573 
6574 	extent_type = btrfs_file_extent_type(leaf, item);
6575 	extent_start = found_key.offset;
6576 	extent_end = btrfs_file_extent_end(path);
6577 	if (extent_type == BTRFS_FILE_EXTENT_REG ||
6578 	    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6579 		/* Only regular file could have regular/prealloc extent */
6580 		if (!S_ISREG(inode->vfs_inode.i_mode)) {
6581 			ret = -EUCLEAN;
6582 			btrfs_crit(fs_info,
6583 		"regular/prealloc extent found for non-regular inode %llu",
6584 				   btrfs_ino(inode));
6585 			goto out;
6586 		}
6587 		trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6588 						       extent_start);
6589 	} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6590 		trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6591 						      path->slots[0],
6592 						      extent_start);
6593 	}
6594 next:
6595 	if (start >= extent_end) {
6596 		path->slots[0]++;
6597 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6598 			ret = btrfs_next_leaf(root, path);
6599 			if (ret < 0) {
6600 				err = ret;
6601 				goto out;
6602 			} else if (ret > 0) {
6603 				goto not_found;
6604 			}
6605 			leaf = path->nodes[0];
6606 		}
6607 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6608 		if (found_key.objectid != objectid ||
6609 		    found_key.type != BTRFS_EXTENT_DATA_KEY)
6610 			goto not_found;
6611 		if (start + len <= found_key.offset)
6612 			goto not_found;
6613 		if (start > found_key.offset)
6614 			goto next;
6615 
6616 		/* New extent overlaps with existing one */
6617 		em->start = start;
6618 		em->orig_start = start;
6619 		em->len = found_key.offset - start;
6620 		em->block_start = EXTENT_MAP_HOLE;
6621 		goto insert;
6622 	}
6623 
6624 	btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6625 
6626 	if (extent_type == BTRFS_FILE_EXTENT_REG ||
6627 	    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6628 		goto insert;
6629 	} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6630 		unsigned long ptr;
6631 		char *map;
6632 		size_t size;
6633 		size_t extent_offset;
6634 		size_t copy_size;
6635 
6636 		if (!page)
6637 			goto out;
6638 
6639 		size = btrfs_file_extent_ram_bytes(leaf, item);
6640 		extent_offset = page_offset(page) + pg_offset - extent_start;
6641 		copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6642 				  size - extent_offset);
6643 		em->start = extent_start + extent_offset;
6644 		em->len = ALIGN(copy_size, fs_info->sectorsize);
6645 		em->orig_block_len = em->len;
6646 		em->orig_start = em->start;
6647 		ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6648 
6649 		btrfs_set_path_blocking(path);
6650 		if (!PageUptodate(page)) {
6651 			if (btrfs_file_extent_compression(leaf, item) !=
6652 			    BTRFS_COMPRESS_NONE) {
6653 				ret = uncompress_inline(path, page, pg_offset,
6654 							extent_offset, item);
6655 				if (ret) {
6656 					err = ret;
6657 					goto out;
6658 				}
6659 			} else {
6660 				map = kmap(page);
6661 				read_extent_buffer(leaf, map + pg_offset, ptr,
6662 						   copy_size);
6663 				if (pg_offset + copy_size < PAGE_SIZE) {
6664 					memset(map + pg_offset + copy_size, 0,
6665 					       PAGE_SIZE - pg_offset -
6666 					       copy_size);
6667 				}
6668 				kunmap(page);
6669 			}
6670 			flush_dcache_page(page);
6671 		}
6672 		set_extent_uptodate(io_tree, em->start,
6673 				    extent_map_end(em) - 1, NULL, GFP_NOFS);
6674 		goto insert;
6675 	}
6676 not_found:
6677 	em->start = start;
6678 	em->orig_start = start;
6679 	em->len = len;
6680 	em->block_start = EXTENT_MAP_HOLE;
6681 insert:
6682 	btrfs_release_path(path);
6683 	if (em->start > start || extent_map_end(em) <= start) {
6684 		btrfs_err(fs_info,
6685 			  "bad extent! em: [%llu %llu] passed [%llu %llu]",
6686 			  em->start, em->len, start, len);
6687 		err = -EIO;
6688 		goto out;
6689 	}
6690 
6691 	err = 0;
6692 	write_lock(&em_tree->lock);
6693 	err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6694 	write_unlock(&em_tree->lock);
6695 out:
6696 	btrfs_free_path(path);
6697 
6698 	trace_btrfs_get_extent(root, inode, em);
6699 
6700 	if (err) {
6701 		free_extent_map(em);
6702 		return ERR_PTR(err);
6703 	}
6704 	BUG_ON(!em); /* Error is always set */
6705 	return em;
6706 }
6707 
6708 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6709 					   u64 start, u64 len)
6710 {
6711 	struct extent_map *em;
6712 	struct extent_map *hole_em = NULL;
6713 	u64 delalloc_start = start;
6714 	u64 end;
6715 	u64 delalloc_len;
6716 	u64 delalloc_end;
6717 	int err = 0;
6718 
6719 	em = btrfs_get_extent(inode, NULL, 0, start, len);
6720 	if (IS_ERR(em))
6721 		return em;
6722 	/*
6723 	 * If our em maps to:
6724 	 * - a hole or
6725 	 * - a pre-alloc extent,
6726 	 * there might actually be delalloc bytes behind it.
6727 	 */
6728 	if (em->block_start != EXTENT_MAP_HOLE &&
6729 	    !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6730 		return em;
6731 	else
6732 		hole_em = em;
6733 
6734 	/* check to see if we've wrapped (len == -1 or similar) */
6735 	end = start + len;
6736 	if (end < start)
6737 		end = (u64)-1;
6738 	else
6739 		end -= 1;
6740 
6741 	em = NULL;
6742 
6743 	/* ok, we didn't find anything, lets look for delalloc */
6744 	delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
6745 				 end, len, EXTENT_DELALLOC, 1);
6746 	delalloc_end = delalloc_start + delalloc_len;
6747 	if (delalloc_end < delalloc_start)
6748 		delalloc_end = (u64)-1;
6749 
6750 	/*
6751 	 * We didn't find anything useful, return the original results from
6752 	 * get_extent()
6753 	 */
6754 	if (delalloc_start > end || delalloc_end <= start) {
6755 		em = hole_em;
6756 		hole_em = NULL;
6757 		goto out;
6758 	}
6759 
6760 	/*
6761 	 * Adjust the delalloc_start to make sure it doesn't go backwards from
6762 	 * the start they passed in
6763 	 */
6764 	delalloc_start = max(start, delalloc_start);
6765 	delalloc_len = delalloc_end - delalloc_start;
6766 
6767 	if (delalloc_len > 0) {
6768 		u64 hole_start;
6769 		u64 hole_len;
6770 		const u64 hole_end = extent_map_end(hole_em);
6771 
6772 		em = alloc_extent_map();
6773 		if (!em) {
6774 			err = -ENOMEM;
6775 			goto out;
6776 		}
6777 
6778 		ASSERT(hole_em);
6779 		/*
6780 		 * When btrfs_get_extent can't find anything it returns one
6781 		 * huge hole
6782 		 *
6783 		 * Make sure what it found really fits our range, and adjust to
6784 		 * make sure it is based on the start from the caller
6785 		 */
6786 		if (hole_end <= start || hole_em->start > end) {
6787 		       free_extent_map(hole_em);
6788 		       hole_em = NULL;
6789 		} else {
6790 		       hole_start = max(hole_em->start, start);
6791 		       hole_len = hole_end - hole_start;
6792 		}
6793 
6794 		if (hole_em && delalloc_start > hole_start) {
6795 			/*
6796 			 * Our hole starts before our delalloc, so we have to
6797 			 * return just the parts of the hole that go until the
6798 			 * delalloc starts
6799 			 */
6800 			em->len = min(hole_len, delalloc_start - hole_start);
6801 			em->start = hole_start;
6802 			em->orig_start = hole_start;
6803 			/*
6804 			 * Don't adjust block start at all, it is fixed at
6805 			 * EXTENT_MAP_HOLE
6806 			 */
6807 			em->block_start = hole_em->block_start;
6808 			em->block_len = hole_len;
6809 			if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6810 				set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6811 		} else {
6812 			/*
6813 			 * Hole is out of passed range or it starts after
6814 			 * delalloc range
6815 			 */
6816 			em->start = delalloc_start;
6817 			em->len = delalloc_len;
6818 			em->orig_start = delalloc_start;
6819 			em->block_start = EXTENT_MAP_DELALLOC;
6820 			em->block_len = delalloc_len;
6821 		}
6822 	} else {
6823 		return hole_em;
6824 	}
6825 out:
6826 
6827 	free_extent_map(hole_em);
6828 	if (err) {
6829 		free_extent_map(em);
6830 		return ERR_PTR(err);
6831 	}
6832 	return em;
6833 }
6834 
6835 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
6836 						  const u64 start,
6837 						  const u64 len,
6838 						  const u64 orig_start,
6839 						  const u64 block_start,
6840 						  const u64 block_len,
6841 						  const u64 orig_block_len,
6842 						  const u64 ram_bytes,
6843 						  const int type)
6844 {
6845 	struct extent_map *em = NULL;
6846 	int ret;
6847 
6848 	if (type != BTRFS_ORDERED_NOCOW) {
6849 		em = create_io_em(inode, start, len, orig_start,
6850 				  block_start, block_len, orig_block_len,
6851 				  ram_bytes,
6852 				  BTRFS_COMPRESS_NONE, /* compress_type */
6853 				  type);
6854 		if (IS_ERR(em))
6855 			goto out;
6856 	}
6857 	ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
6858 					   len, block_len, type);
6859 	if (ret) {
6860 		if (em) {
6861 			free_extent_map(em);
6862 			btrfs_drop_extent_cache(BTRFS_I(inode), start,
6863 						start + len - 1, 0);
6864 		}
6865 		em = ERR_PTR(ret);
6866 	}
6867  out:
6868 
6869 	return em;
6870 }
6871 
6872 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6873 						  u64 start, u64 len)
6874 {
6875 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6876 	struct btrfs_root *root = BTRFS_I(inode)->root;
6877 	struct extent_map *em;
6878 	struct btrfs_key ins;
6879 	u64 alloc_hint;
6880 	int ret;
6881 
6882 	alloc_hint = get_extent_allocation_hint(inode, start, len);
6883 	ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
6884 				   0, alloc_hint, &ins, 1, 1);
6885 	if (ret)
6886 		return ERR_PTR(ret);
6887 
6888 	em = btrfs_create_dio_extent(inode, start, ins.offset, start,
6889 				     ins.objectid, ins.offset, ins.offset,
6890 				     ins.offset, BTRFS_ORDERED_REGULAR);
6891 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
6892 	if (IS_ERR(em))
6893 		btrfs_free_reserved_extent(fs_info, ins.objectid,
6894 					   ins.offset, 1);
6895 
6896 	return em;
6897 }
6898 
6899 /*
6900  * returns 1 when the nocow is safe, < 1 on error, 0 if the
6901  * block must be cow'd
6902  */
6903 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6904 			      u64 *orig_start, u64 *orig_block_len,
6905 			      u64 *ram_bytes)
6906 {
6907 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6908 	struct btrfs_path *path;
6909 	int ret;
6910 	struct extent_buffer *leaf;
6911 	struct btrfs_root *root = BTRFS_I(inode)->root;
6912 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6913 	struct btrfs_file_extent_item *fi;
6914 	struct btrfs_key key;
6915 	u64 disk_bytenr;
6916 	u64 backref_offset;
6917 	u64 extent_end;
6918 	u64 num_bytes;
6919 	int slot;
6920 	int found_type;
6921 	bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6922 
6923 	path = btrfs_alloc_path();
6924 	if (!path)
6925 		return -ENOMEM;
6926 
6927 	ret = btrfs_lookup_file_extent(NULL, root, path,
6928 			btrfs_ino(BTRFS_I(inode)), offset, 0);
6929 	if (ret < 0)
6930 		goto out;
6931 
6932 	slot = path->slots[0];
6933 	if (ret == 1) {
6934 		if (slot == 0) {
6935 			/* can't find the item, must cow */
6936 			ret = 0;
6937 			goto out;
6938 		}
6939 		slot--;
6940 	}
6941 	ret = 0;
6942 	leaf = path->nodes[0];
6943 	btrfs_item_key_to_cpu(leaf, &key, slot);
6944 	if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
6945 	    key.type != BTRFS_EXTENT_DATA_KEY) {
6946 		/* not our file or wrong item type, must cow */
6947 		goto out;
6948 	}
6949 
6950 	if (key.offset > offset) {
6951 		/* Wrong offset, must cow */
6952 		goto out;
6953 	}
6954 
6955 	fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6956 	found_type = btrfs_file_extent_type(leaf, fi);
6957 	if (found_type != BTRFS_FILE_EXTENT_REG &&
6958 	    found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6959 		/* not a regular extent, must cow */
6960 		goto out;
6961 	}
6962 
6963 	if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6964 		goto out;
6965 
6966 	extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6967 	if (extent_end <= offset)
6968 		goto out;
6969 
6970 	disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6971 	if (disk_bytenr == 0)
6972 		goto out;
6973 
6974 	if (btrfs_file_extent_compression(leaf, fi) ||
6975 	    btrfs_file_extent_encryption(leaf, fi) ||
6976 	    btrfs_file_extent_other_encoding(leaf, fi))
6977 		goto out;
6978 
6979 	/*
6980 	 * Do the same check as in btrfs_cross_ref_exist but without the
6981 	 * unnecessary search.
6982 	 */
6983 	if (btrfs_file_extent_generation(leaf, fi) <=
6984 	    btrfs_root_last_snapshot(&root->root_item))
6985 		goto out;
6986 
6987 	backref_offset = btrfs_file_extent_offset(leaf, fi);
6988 
6989 	if (orig_start) {
6990 		*orig_start = key.offset - backref_offset;
6991 		*orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6992 		*ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6993 	}
6994 
6995 	if (btrfs_extent_readonly(fs_info, disk_bytenr))
6996 		goto out;
6997 
6998 	num_bytes = min(offset + *len, extent_end) - offset;
6999 	if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7000 		u64 range_end;
7001 
7002 		range_end = round_up(offset + num_bytes,
7003 				     root->fs_info->sectorsize) - 1;
7004 		ret = test_range_bit(io_tree, offset, range_end,
7005 				     EXTENT_DELALLOC, 0, NULL);
7006 		if (ret) {
7007 			ret = -EAGAIN;
7008 			goto out;
7009 		}
7010 	}
7011 
7012 	btrfs_release_path(path);
7013 
7014 	/*
7015 	 * look for other files referencing this extent, if we
7016 	 * find any we must cow
7017 	 */
7018 
7019 	ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7020 				    key.offset - backref_offset, disk_bytenr);
7021 	if (ret) {
7022 		ret = 0;
7023 		goto out;
7024 	}
7025 
7026 	/*
7027 	 * adjust disk_bytenr and num_bytes to cover just the bytes
7028 	 * in this extent we are about to write.  If there
7029 	 * are any csums in that range we have to cow in order
7030 	 * to keep the csums correct
7031 	 */
7032 	disk_bytenr += backref_offset;
7033 	disk_bytenr += offset - key.offset;
7034 	if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7035 		goto out;
7036 	/*
7037 	 * all of the above have passed, it is safe to overwrite this extent
7038 	 * without cow
7039 	 */
7040 	*len = num_bytes;
7041 	ret = 1;
7042 out:
7043 	btrfs_free_path(path);
7044 	return ret;
7045 }
7046 
7047 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7048 			      struct extent_state **cached_state, int writing)
7049 {
7050 	struct btrfs_ordered_extent *ordered;
7051 	int ret = 0;
7052 
7053 	while (1) {
7054 		lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7055 				 cached_state);
7056 		/*
7057 		 * We're concerned with the entire range that we're going to be
7058 		 * doing DIO to, so we need to make sure there's no ordered
7059 		 * extents in this range.
7060 		 */
7061 		ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7062 						     lockend - lockstart + 1);
7063 
7064 		/*
7065 		 * We need to make sure there are no buffered pages in this
7066 		 * range either, we could have raced between the invalidate in
7067 		 * generic_file_direct_write and locking the extent.  The
7068 		 * invalidate needs to happen so that reads after a write do not
7069 		 * get stale data.
7070 		 */
7071 		if (!ordered &&
7072 		    (!writing || !filemap_range_has_page(inode->i_mapping,
7073 							 lockstart, lockend)))
7074 			break;
7075 
7076 		unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7077 				     cached_state);
7078 
7079 		if (ordered) {
7080 			/*
7081 			 * If we are doing a DIO read and the ordered extent we
7082 			 * found is for a buffered write, we can not wait for it
7083 			 * to complete and retry, because if we do so we can
7084 			 * deadlock with concurrent buffered writes on page
7085 			 * locks. This happens only if our DIO read covers more
7086 			 * than one extent map, if at this point has already
7087 			 * created an ordered extent for a previous extent map
7088 			 * and locked its range in the inode's io tree, and a
7089 			 * concurrent write against that previous extent map's
7090 			 * range and this range started (we unlock the ranges
7091 			 * in the io tree only when the bios complete and
7092 			 * buffered writes always lock pages before attempting
7093 			 * to lock range in the io tree).
7094 			 */
7095 			if (writing ||
7096 			    test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7097 				btrfs_start_ordered_extent(inode, ordered, 1);
7098 			else
7099 				ret = -ENOTBLK;
7100 			btrfs_put_ordered_extent(ordered);
7101 		} else {
7102 			/*
7103 			 * We could trigger writeback for this range (and wait
7104 			 * for it to complete) and then invalidate the pages for
7105 			 * this range (through invalidate_inode_pages2_range()),
7106 			 * but that can lead us to a deadlock with a concurrent
7107 			 * call to readahead (a buffered read or a defrag call
7108 			 * triggered a readahead) on a page lock due to an
7109 			 * ordered dio extent we created before but did not have
7110 			 * yet a corresponding bio submitted (whence it can not
7111 			 * complete), which makes readahead wait for that
7112 			 * ordered extent to complete while holding a lock on
7113 			 * that page.
7114 			 */
7115 			ret = -ENOTBLK;
7116 		}
7117 
7118 		if (ret)
7119 			break;
7120 
7121 		cond_resched();
7122 	}
7123 
7124 	return ret;
7125 }
7126 
7127 /* The callers of this must take lock_extent() */
7128 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7129 				       u64 orig_start, u64 block_start,
7130 				       u64 block_len, u64 orig_block_len,
7131 				       u64 ram_bytes, int compress_type,
7132 				       int type)
7133 {
7134 	struct extent_map_tree *em_tree;
7135 	struct extent_map *em;
7136 	int ret;
7137 
7138 	ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7139 	       type == BTRFS_ORDERED_COMPRESSED ||
7140 	       type == BTRFS_ORDERED_NOCOW ||
7141 	       type == BTRFS_ORDERED_REGULAR);
7142 
7143 	em_tree = &BTRFS_I(inode)->extent_tree;
7144 	em = alloc_extent_map();
7145 	if (!em)
7146 		return ERR_PTR(-ENOMEM);
7147 
7148 	em->start = start;
7149 	em->orig_start = orig_start;
7150 	em->len = len;
7151 	em->block_len = block_len;
7152 	em->block_start = block_start;
7153 	em->orig_block_len = orig_block_len;
7154 	em->ram_bytes = ram_bytes;
7155 	em->generation = -1;
7156 	set_bit(EXTENT_FLAG_PINNED, &em->flags);
7157 	if (type == BTRFS_ORDERED_PREALLOC) {
7158 		set_bit(EXTENT_FLAG_FILLING, &em->flags);
7159 	} else if (type == BTRFS_ORDERED_COMPRESSED) {
7160 		set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7161 		em->compress_type = compress_type;
7162 	}
7163 
7164 	do {
7165 		btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7166 				em->start + em->len - 1, 0);
7167 		write_lock(&em_tree->lock);
7168 		ret = add_extent_mapping(em_tree, em, 1);
7169 		write_unlock(&em_tree->lock);
7170 		/*
7171 		 * The caller has taken lock_extent(), who could race with us
7172 		 * to add em?
7173 		 */
7174 	} while (ret == -EEXIST);
7175 
7176 	if (ret) {
7177 		free_extent_map(em);
7178 		return ERR_PTR(ret);
7179 	}
7180 
7181 	/* em got 2 refs now, callers needs to do free_extent_map once. */
7182 	return em;
7183 }
7184 
7185 
7186 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7187 					struct buffer_head *bh_result,
7188 					struct inode *inode,
7189 					u64 start, u64 len)
7190 {
7191 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7192 
7193 	if (em->block_start == EXTENT_MAP_HOLE ||
7194 			test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7195 		return -ENOENT;
7196 
7197 	len = min(len, em->len - (start - em->start));
7198 
7199 	bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7200 		inode->i_blkbits;
7201 	bh_result->b_size = len;
7202 	bh_result->b_bdev = fs_info->fs_devices->latest_bdev;
7203 	set_buffer_mapped(bh_result);
7204 
7205 	return 0;
7206 }
7207 
7208 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7209 					 struct buffer_head *bh_result,
7210 					 struct inode *inode,
7211 					 struct btrfs_dio_data *dio_data,
7212 					 u64 start, u64 len)
7213 {
7214 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7215 	struct extent_map *em = *map;
7216 	int ret = 0;
7217 
7218 	/*
7219 	 * We don't allocate a new extent in the following cases
7220 	 *
7221 	 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7222 	 * existing extent.
7223 	 * 2) The extent is marked as PREALLOC. We're good to go here and can
7224 	 * just use the extent.
7225 	 *
7226 	 */
7227 	if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7228 	    ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7229 	     em->block_start != EXTENT_MAP_HOLE)) {
7230 		int type;
7231 		u64 block_start, orig_start, orig_block_len, ram_bytes;
7232 
7233 		if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7234 			type = BTRFS_ORDERED_PREALLOC;
7235 		else
7236 			type = BTRFS_ORDERED_NOCOW;
7237 		len = min(len, em->len - (start - em->start));
7238 		block_start = em->block_start + (start - em->start);
7239 
7240 		if (can_nocow_extent(inode, start, &len, &orig_start,
7241 				     &orig_block_len, &ram_bytes) == 1 &&
7242 		    btrfs_inc_nocow_writers(fs_info, block_start)) {
7243 			struct extent_map *em2;
7244 
7245 			em2 = btrfs_create_dio_extent(inode, start, len,
7246 						      orig_start, block_start,
7247 						      len, orig_block_len,
7248 						      ram_bytes, type);
7249 			btrfs_dec_nocow_writers(fs_info, block_start);
7250 			if (type == BTRFS_ORDERED_PREALLOC) {
7251 				free_extent_map(em);
7252 				*map = em = em2;
7253 			}
7254 
7255 			if (em2 && IS_ERR(em2)) {
7256 				ret = PTR_ERR(em2);
7257 				goto out;
7258 			}
7259 			/*
7260 			 * For inode marked NODATACOW or extent marked PREALLOC,
7261 			 * use the existing or preallocated extent, so does not
7262 			 * need to adjust btrfs_space_info's bytes_may_use.
7263 			 */
7264 			btrfs_free_reserved_data_space_noquota(inode, start,
7265 							       len);
7266 			goto skip_cow;
7267 		}
7268 	}
7269 
7270 	/* this will cow the extent */
7271 	len = bh_result->b_size;
7272 	free_extent_map(em);
7273 	*map = em = btrfs_new_extent_direct(inode, start, len);
7274 	if (IS_ERR(em)) {
7275 		ret = PTR_ERR(em);
7276 		goto out;
7277 	}
7278 
7279 	len = min(len, em->len - (start - em->start));
7280 
7281 skip_cow:
7282 	bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7283 		inode->i_blkbits;
7284 	bh_result->b_size = len;
7285 	bh_result->b_bdev = fs_info->fs_devices->latest_bdev;
7286 	set_buffer_mapped(bh_result);
7287 
7288 	if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7289 		set_buffer_new(bh_result);
7290 
7291 	/*
7292 	 * Need to update the i_size under the extent lock so buffered
7293 	 * readers will get the updated i_size when we unlock.
7294 	 */
7295 	if (!dio_data->overwrite && start + len > i_size_read(inode))
7296 		i_size_write(inode, start + len);
7297 
7298 	WARN_ON(dio_data->reserve < len);
7299 	dio_data->reserve -= len;
7300 	dio_data->unsubmitted_oe_range_end = start + len;
7301 	current->journal_info = dio_data;
7302 out:
7303 	return ret;
7304 }
7305 
7306 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7307 				   struct buffer_head *bh_result, int create)
7308 {
7309 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7310 	struct extent_map *em;
7311 	struct extent_state *cached_state = NULL;
7312 	struct btrfs_dio_data *dio_data = NULL;
7313 	u64 start = iblock << inode->i_blkbits;
7314 	u64 lockstart, lockend;
7315 	u64 len = bh_result->b_size;
7316 	int ret = 0;
7317 
7318 	if (!create)
7319 		len = min_t(u64, len, fs_info->sectorsize);
7320 
7321 	lockstart = start;
7322 	lockend = start + len - 1;
7323 
7324 	if (current->journal_info) {
7325 		/*
7326 		 * Need to pull our outstanding extents and set journal_info to NULL so
7327 		 * that anything that needs to check if there's a transaction doesn't get
7328 		 * confused.
7329 		 */
7330 		dio_data = current->journal_info;
7331 		current->journal_info = NULL;
7332 	}
7333 
7334 	/*
7335 	 * If this errors out it's because we couldn't invalidate pagecache for
7336 	 * this range and we need to fallback to buffered.
7337 	 */
7338 	if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7339 			       create)) {
7340 		ret = -ENOTBLK;
7341 		goto err;
7342 	}
7343 
7344 	em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7345 	if (IS_ERR(em)) {
7346 		ret = PTR_ERR(em);
7347 		goto unlock_err;
7348 	}
7349 
7350 	/*
7351 	 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7352 	 * io.  INLINE is special, and we could probably kludge it in here, but
7353 	 * it's still buffered so for safety lets just fall back to the generic
7354 	 * buffered path.
7355 	 *
7356 	 * For COMPRESSED we _have_ to read the entire extent in so we can
7357 	 * decompress it, so there will be buffering required no matter what we
7358 	 * do, so go ahead and fallback to buffered.
7359 	 *
7360 	 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7361 	 * to buffered IO.  Don't blame me, this is the price we pay for using
7362 	 * the generic code.
7363 	 */
7364 	if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7365 	    em->block_start == EXTENT_MAP_INLINE) {
7366 		free_extent_map(em);
7367 		ret = -ENOTBLK;
7368 		goto unlock_err;
7369 	}
7370 
7371 	if (create) {
7372 		ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7373 						    dio_data, start, len);
7374 		if (ret < 0)
7375 			goto unlock_err;
7376 
7377 		unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
7378 				     lockend, &cached_state);
7379 	} else {
7380 		ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7381 						   start, len);
7382 		/* Can be negative only if we read from a hole */
7383 		if (ret < 0) {
7384 			ret = 0;
7385 			free_extent_map(em);
7386 			goto unlock_err;
7387 		}
7388 		/*
7389 		 * We need to unlock only the end area that we aren't using.
7390 		 * The rest is going to be unlocked by the endio routine.
7391 		 */
7392 		lockstart = start + bh_result->b_size;
7393 		if (lockstart < lockend) {
7394 			unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7395 					     lockstart, lockend, &cached_state);
7396 		} else {
7397 			free_extent_state(cached_state);
7398 		}
7399 	}
7400 
7401 	free_extent_map(em);
7402 
7403 	return 0;
7404 
7405 unlock_err:
7406 	unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7407 			     &cached_state);
7408 err:
7409 	if (dio_data)
7410 		current->journal_info = dio_data;
7411 	return ret;
7412 }
7413 
7414 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7415 {
7416 	/*
7417 	 * This implies a barrier so that stores to dio_bio->bi_status before
7418 	 * this and loads of dio_bio->bi_status after this are fully ordered.
7419 	 */
7420 	if (!refcount_dec_and_test(&dip->refs))
7421 		return;
7422 
7423 	if (bio_op(dip->dio_bio) == REQ_OP_WRITE) {
7424 		__endio_write_update_ordered(dip->inode, dip->logical_offset,
7425 					     dip->bytes,
7426 					     !dip->dio_bio->bi_status);
7427 	} else {
7428 		unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7429 			      dip->logical_offset,
7430 			      dip->logical_offset + dip->bytes - 1);
7431 	}
7432 
7433 	dio_end_io(dip->dio_bio);
7434 	kfree(dip);
7435 }
7436 
7437 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7438 					  int mirror_num,
7439 					  unsigned long bio_flags)
7440 {
7441 	struct btrfs_dio_private *dip = bio->bi_private;
7442 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7443 	blk_status_t ret;
7444 
7445 	BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7446 
7447 	ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7448 	if (ret)
7449 		return ret;
7450 
7451 	refcount_inc(&dip->refs);
7452 	ret = btrfs_map_bio(fs_info, bio, mirror_num);
7453 	if (ret)
7454 		refcount_dec(&dip->refs);
7455 	return ret;
7456 }
7457 
7458 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
7459 					     struct btrfs_io_bio *io_bio,
7460 					     const bool uptodate)
7461 {
7462 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7463 	const u32 sectorsize = fs_info->sectorsize;
7464 	struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7465 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7466 	const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7467 	struct bio_vec bvec;
7468 	struct bvec_iter iter;
7469 	u64 start = io_bio->logical;
7470 	int icsum = 0;
7471 	blk_status_t err = BLK_STS_OK;
7472 
7473 	__bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
7474 		unsigned int i, nr_sectors, pgoff;
7475 
7476 		nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7477 		pgoff = bvec.bv_offset;
7478 		for (i = 0; i < nr_sectors; i++) {
7479 			ASSERT(pgoff < PAGE_SIZE);
7480 			if (uptodate &&
7481 			    (!csum || !check_data_csum(inode, io_bio, icsum,
7482 						       bvec.bv_page, pgoff,
7483 						       start, sectorsize))) {
7484 				clean_io_failure(fs_info, failure_tree, io_tree,
7485 						 start, bvec.bv_page,
7486 						 btrfs_ino(BTRFS_I(inode)),
7487 						 pgoff);
7488 			} else {
7489 				blk_status_t status;
7490 
7491 				status = btrfs_submit_read_repair(inode,
7492 							&io_bio->bio,
7493 							start - io_bio->logical,
7494 							bvec.bv_page, pgoff,
7495 							start,
7496 							start + sectorsize - 1,
7497 							io_bio->mirror_num,
7498 							submit_dio_repair_bio);
7499 				if (status)
7500 					err = status;
7501 			}
7502 			start += sectorsize;
7503 			icsum++;
7504 			pgoff += sectorsize;
7505 		}
7506 	}
7507 	return err;
7508 }
7509 
7510 static void __endio_write_update_ordered(struct inode *inode,
7511 					 const u64 offset, const u64 bytes,
7512 					 const bool uptodate)
7513 {
7514 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7515 	struct btrfs_ordered_extent *ordered = NULL;
7516 	struct btrfs_workqueue *wq;
7517 	u64 ordered_offset = offset;
7518 	u64 ordered_bytes = bytes;
7519 	u64 last_offset;
7520 
7521 	if (btrfs_is_free_space_inode(BTRFS_I(inode)))
7522 		wq = fs_info->endio_freespace_worker;
7523 	else
7524 		wq = fs_info->endio_write_workers;
7525 
7526 	while (ordered_offset < offset + bytes) {
7527 		last_offset = ordered_offset;
7528 		if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7529 							   &ordered_offset,
7530 							   ordered_bytes,
7531 							   uptodate)) {
7532 			btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7533 					NULL);
7534 			btrfs_queue_work(wq, &ordered->work);
7535 		}
7536 		/*
7537 		 * If btrfs_dec_test_ordered_pending does not find any ordered
7538 		 * extent in the range, we can exit.
7539 		 */
7540 		if (ordered_offset == last_offset)
7541 			return;
7542 		/*
7543 		 * Our bio might span multiple ordered extents. In this case
7544 		 * we keep going until we have accounted the whole dio.
7545 		 */
7546 		if (ordered_offset < offset + bytes) {
7547 			ordered_bytes = offset + bytes - ordered_offset;
7548 			ordered = NULL;
7549 		}
7550 	}
7551 }
7552 
7553 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
7554 				    struct bio *bio, u64 offset)
7555 {
7556 	struct inode *inode = private_data;
7557 	blk_status_t ret;
7558 	ret = btrfs_csum_one_bio(inode, bio, offset, 1);
7559 	BUG_ON(ret); /* -ENOMEM */
7560 	return 0;
7561 }
7562 
7563 static void btrfs_end_dio_bio(struct bio *bio)
7564 {
7565 	struct btrfs_dio_private *dip = bio->bi_private;
7566 	blk_status_t err = bio->bi_status;
7567 
7568 	if (err)
7569 		btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7570 			   "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7571 			   btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7572 			   bio->bi_opf,
7573 			   (unsigned long long)bio->bi_iter.bi_sector,
7574 			   bio->bi_iter.bi_size, err);
7575 
7576 	if (bio_op(bio) == REQ_OP_READ) {
7577 		err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
7578 					       !err);
7579 	}
7580 
7581 	if (err)
7582 		dip->dio_bio->bi_status = err;
7583 
7584 	bio_put(bio);
7585 	btrfs_dio_private_put(dip);
7586 }
7587 
7588 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7589 		struct inode *inode, u64 file_offset, int async_submit)
7590 {
7591 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7592 	struct btrfs_dio_private *dip = bio->bi_private;
7593 	bool write = bio_op(bio) == REQ_OP_WRITE;
7594 	blk_status_t ret;
7595 
7596 	/* Check btrfs_submit_bio_hook() for rules about async submit. */
7597 	if (async_submit)
7598 		async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7599 
7600 	if (!write) {
7601 		ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7602 		if (ret)
7603 			goto err;
7604 	}
7605 
7606 	if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7607 		goto map;
7608 
7609 	if (write && async_submit) {
7610 		ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
7611 					  file_offset, inode,
7612 					  btrfs_submit_bio_start_direct_io);
7613 		goto err;
7614 	} else if (write) {
7615 		/*
7616 		 * If we aren't doing async submit, calculate the csum of the
7617 		 * bio now.
7618 		 */
7619 		ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
7620 		if (ret)
7621 			goto err;
7622 	} else {
7623 		u64 csum_offset;
7624 
7625 		csum_offset = file_offset - dip->logical_offset;
7626 		csum_offset >>= inode->i_sb->s_blocksize_bits;
7627 		csum_offset *= btrfs_super_csum_size(fs_info->super_copy);
7628 		btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
7629 	}
7630 map:
7631 	ret = btrfs_map_bio(fs_info, bio, 0);
7632 err:
7633 	return ret;
7634 }
7635 
7636 /*
7637  * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
7638  * or ordered extents whether or not we submit any bios.
7639  */
7640 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
7641 							  struct inode *inode,
7642 							  loff_t file_offset)
7643 {
7644 	const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7645 	const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7646 	size_t dip_size;
7647 	struct btrfs_dio_private *dip;
7648 
7649 	dip_size = sizeof(*dip);
7650 	if (!write && csum) {
7651 		struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7652 		const u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
7653 		size_t nblocks;
7654 
7655 		nblocks = dio_bio->bi_iter.bi_size >> inode->i_sb->s_blocksize_bits;
7656 		dip_size += csum_size * nblocks;
7657 	}
7658 
7659 	dip = kzalloc(dip_size, GFP_NOFS);
7660 	if (!dip)
7661 		return NULL;
7662 
7663 	dip->inode = inode;
7664 	dip->logical_offset = file_offset;
7665 	dip->bytes = dio_bio->bi_iter.bi_size;
7666 	dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7667 	dip->dio_bio = dio_bio;
7668 	refcount_set(&dip->refs, 1);
7669 
7670 	if (write) {
7671 		struct btrfs_dio_data *dio_data = current->journal_info;
7672 
7673 		/*
7674 		 * Setting range start and end to the same value means that
7675 		 * no cleanup will happen in btrfs_direct_IO
7676 		 */
7677 		dio_data->unsubmitted_oe_range_end = dip->logical_offset +
7678 			dip->bytes;
7679 		dio_data->unsubmitted_oe_range_start =
7680 			dio_data->unsubmitted_oe_range_end;
7681 	}
7682 	return dip;
7683 }
7684 
7685 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
7686 				loff_t file_offset)
7687 {
7688 	const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7689 	const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7690 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7691 	const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
7692 			     BTRFS_BLOCK_GROUP_RAID56_MASK);
7693 	struct btrfs_dio_private *dip;
7694 	struct bio *bio;
7695 	u64 start_sector;
7696 	int async_submit = 0;
7697 	u64 submit_len;
7698 	int clone_offset = 0;
7699 	int clone_len;
7700 	int ret;
7701 	blk_status_t status;
7702 	struct btrfs_io_geometry geom;
7703 
7704 	dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
7705 	if (!dip) {
7706 		if (!write) {
7707 			unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
7708 				file_offset + dio_bio->bi_iter.bi_size - 1);
7709 		}
7710 		dio_bio->bi_status = BLK_STS_RESOURCE;
7711 		dio_end_io(dio_bio);
7712 		return;
7713 	}
7714 
7715 	if (!write && csum) {
7716 		/*
7717 		 * Load the csums up front to reduce csum tree searches and
7718 		 * contention when submitting bios.
7719 		 */
7720 		status = btrfs_lookup_bio_sums(inode, dio_bio, file_offset,
7721 					       dip->csums);
7722 		if (status != BLK_STS_OK)
7723 			goto out_err;
7724 	}
7725 
7726 	start_sector = dio_bio->bi_iter.bi_sector;
7727 	submit_len = dio_bio->bi_iter.bi_size;
7728 
7729 	do {
7730 		ret = btrfs_get_io_geometry(fs_info, btrfs_op(dio_bio),
7731 					    start_sector << 9, submit_len,
7732 					    &geom);
7733 		if (ret) {
7734 			status = errno_to_blk_status(ret);
7735 			goto out_err;
7736 		}
7737 		ASSERT(geom.len <= INT_MAX);
7738 
7739 		clone_len = min_t(int, submit_len, geom.len);
7740 
7741 		/*
7742 		 * This will never fail as it's passing GPF_NOFS and
7743 		 * the allocation is backed by btrfs_bioset.
7744 		 */
7745 		bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
7746 		bio->bi_private = dip;
7747 		bio->bi_end_io = btrfs_end_dio_bio;
7748 		btrfs_io_bio(bio)->logical = file_offset;
7749 
7750 		ASSERT(submit_len >= clone_len);
7751 		submit_len -= clone_len;
7752 
7753 		/*
7754 		 * Increase the count before we submit the bio so we know
7755 		 * the end IO handler won't happen before we increase the
7756 		 * count. Otherwise, the dip might get freed before we're
7757 		 * done setting it up.
7758 		 *
7759 		 * We transfer the initial reference to the last bio, so we
7760 		 * don't need to increment the reference count for the last one.
7761 		 */
7762 		if (submit_len > 0) {
7763 			refcount_inc(&dip->refs);
7764 			/*
7765 			 * If we are submitting more than one bio, submit them
7766 			 * all asynchronously. The exception is RAID 5 or 6, as
7767 			 * asynchronous checksums make it difficult to collect
7768 			 * full stripe writes.
7769 			 */
7770 			if (!raid56)
7771 				async_submit = 1;
7772 		}
7773 
7774 		status = btrfs_submit_dio_bio(bio, inode, file_offset,
7775 						async_submit);
7776 		if (status) {
7777 			bio_put(bio);
7778 			if (submit_len > 0)
7779 				refcount_dec(&dip->refs);
7780 			goto out_err;
7781 		}
7782 
7783 		clone_offset += clone_len;
7784 		start_sector += clone_len >> 9;
7785 		file_offset += clone_len;
7786 	} while (submit_len > 0);
7787 	return;
7788 
7789 out_err:
7790 	dip->dio_bio->bi_status = status;
7791 	btrfs_dio_private_put(dip);
7792 }
7793 
7794 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
7795 			       const struct iov_iter *iter, loff_t offset)
7796 {
7797 	int seg;
7798 	int i;
7799 	unsigned int blocksize_mask = fs_info->sectorsize - 1;
7800 	ssize_t retval = -EINVAL;
7801 
7802 	if (offset & blocksize_mask)
7803 		goto out;
7804 
7805 	if (iov_iter_alignment(iter) & blocksize_mask)
7806 		goto out;
7807 
7808 	/* If this is a write we don't need to check anymore */
7809 	if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
7810 		return 0;
7811 	/*
7812 	 * Check to make sure we don't have duplicate iov_base's in this
7813 	 * iovec, if so return EINVAL, otherwise we'll get csum errors
7814 	 * when reading back.
7815 	 */
7816 	for (seg = 0; seg < iter->nr_segs; seg++) {
7817 		for (i = seg + 1; i < iter->nr_segs; i++) {
7818 			if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
7819 				goto out;
7820 		}
7821 	}
7822 	retval = 0;
7823 out:
7824 	return retval;
7825 }
7826 
7827 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
7828 {
7829 	struct file *file = iocb->ki_filp;
7830 	struct inode *inode = file->f_mapping->host;
7831 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7832 	struct btrfs_dio_data dio_data = { 0 };
7833 	struct extent_changeset *data_reserved = NULL;
7834 	loff_t offset = iocb->ki_pos;
7835 	size_t count = 0;
7836 	int flags = 0;
7837 	bool wakeup = true;
7838 	bool relock = false;
7839 	ssize_t ret;
7840 
7841 	if (check_direct_IO(fs_info, iter, offset))
7842 		return 0;
7843 
7844 	inode_dio_begin(inode);
7845 
7846 	/*
7847 	 * The generic stuff only does filemap_write_and_wait_range, which
7848 	 * isn't enough if we've written compressed pages to this area, so
7849 	 * we need to flush the dirty pages again to make absolutely sure
7850 	 * that any outstanding dirty pages are on disk.
7851 	 */
7852 	count = iov_iter_count(iter);
7853 	if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7854 		     &BTRFS_I(inode)->runtime_flags))
7855 		filemap_fdatawrite_range(inode->i_mapping, offset,
7856 					 offset + count - 1);
7857 
7858 	if (iov_iter_rw(iter) == WRITE) {
7859 		/*
7860 		 * If the write DIO is beyond the EOF, we need update
7861 		 * the isize, but it is protected by i_mutex. So we can
7862 		 * not unlock the i_mutex at this case.
7863 		 */
7864 		if (offset + count <= inode->i_size) {
7865 			dio_data.overwrite = 1;
7866 			inode_unlock(inode);
7867 			relock = true;
7868 		} else if (iocb->ki_flags & IOCB_NOWAIT) {
7869 			ret = -EAGAIN;
7870 			goto out;
7871 		}
7872 		ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
7873 						   offset, count);
7874 		if (ret)
7875 			goto out;
7876 
7877 		/*
7878 		 * We need to know how many extents we reserved so that we can
7879 		 * do the accounting properly if we go over the number we
7880 		 * originally calculated.  Abuse current->journal_info for this.
7881 		 */
7882 		dio_data.reserve = round_up(count,
7883 					    fs_info->sectorsize);
7884 		dio_data.unsubmitted_oe_range_start = (u64)offset;
7885 		dio_data.unsubmitted_oe_range_end = (u64)offset;
7886 		current->journal_info = &dio_data;
7887 		down_read(&BTRFS_I(inode)->dio_sem);
7888 	} else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7889 				     &BTRFS_I(inode)->runtime_flags)) {
7890 		inode_dio_end(inode);
7891 		flags = DIO_LOCKING | DIO_SKIP_HOLES;
7892 		wakeup = false;
7893 	}
7894 
7895 	ret = __blockdev_direct_IO(iocb, inode,
7896 				   fs_info->fs_devices->latest_bdev,
7897 				   iter, btrfs_get_blocks_direct, NULL,
7898 				   btrfs_submit_direct, flags);
7899 	if (iov_iter_rw(iter) == WRITE) {
7900 		up_read(&BTRFS_I(inode)->dio_sem);
7901 		current->journal_info = NULL;
7902 		if (ret < 0 && ret != -EIOCBQUEUED) {
7903 			if (dio_data.reserve)
7904 				btrfs_delalloc_release_space(inode, data_reserved,
7905 					offset, dio_data.reserve, true);
7906 			/*
7907 			 * On error we might have left some ordered extents
7908 			 * without submitting corresponding bios for them, so
7909 			 * cleanup them up to avoid other tasks getting them
7910 			 * and waiting for them to complete forever.
7911 			 */
7912 			if (dio_data.unsubmitted_oe_range_start <
7913 			    dio_data.unsubmitted_oe_range_end)
7914 				__endio_write_update_ordered(inode,
7915 					dio_data.unsubmitted_oe_range_start,
7916 					dio_data.unsubmitted_oe_range_end -
7917 					dio_data.unsubmitted_oe_range_start,
7918 					false);
7919 		} else if (ret >= 0 && (size_t)ret < count)
7920 			btrfs_delalloc_release_space(inode, data_reserved,
7921 					offset, count - (size_t)ret, true);
7922 		btrfs_delalloc_release_extents(BTRFS_I(inode), count);
7923 	}
7924 out:
7925 	if (wakeup)
7926 		inode_dio_end(inode);
7927 	if (relock)
7928 		inode_lock(inode);
7929 
7930 	extent_changeset_free(data_reserved);
7931 	return ret;
7932 }
7933 
7934 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7935 		__u64 start, __u64 len)
7936 {
7937 	int	ret;
7938 
7939 	ret = fiemap_prep(inode, fieinfo, start, &len, 0);
7940 	if (ret)
7941 		return ret;
7942 
7943 	return extent_fiemap(inode, fieinfo, start, len);
7944 }
7945 
7946 int btrfs_readpage(struct file *file, struct page *page)
7947 {
7948 	return extent_read_full_page(page, btrfs_get_extent, 0);
7949 }
7950 
7951 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7952 {
7953 	struct inode *inode = page->mapping->host;
7954 	int ret;
7955 
7956 	if (current->flags & PF_MEMALLOC) {
7957 		redirty_page_for_writepage(wbc, page);
7958 		unlock_page(page);
7959 		return 0;
7960 	}
7961 
7962 	/*
7963 	 * If we are under memory pressure we will call this directly from the
7964 	 * VM, we need to make sure we have the inode referenced for the ordered
7965 	 * extent.  If not just return like we didn't do anything.
7966 	 */
7967 	if (!igrab(inode)) {
7968 		redirty_page_for_writepage(wbc, page);
7969 		return AOP_WRITEPAGE_ACTIVATE;
7970 	}
7971 	ret = extent_write_full_page(page, wbc);
7972 	btrfs_add_delayed_iput(inode);
7973 	return ret;
7974 }
7975 
7976 static int btrfs_writepages(struct address_space *mapping,
7977 			    struct writeback_control *wbc)
7978 {
7979 	return extent_writepages(mapping, wbc);
7980 }
7981 
7982 static void btrfs_readahead(struct readahead_control *rac)
7983 {
7984 	extent_readahead(rac);
7985 }
7986 
7987 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7988 {
7989 	int ret = try_release_extent_mapping(page, gfp_flags);
7990 	if (ret == 1)
7991 		detach_page_private(page);
7992 	return ret;
7993 }
7994 
7995 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7996 {
7997 	if (PageWriteback(page) || PageDirty(page))
7998 		return 0;
7999 	return __btrfs_releasepage(page, gfp_flags);
8000 }
8001 
8002 #ifdef CONFIG_MIGRATION
8003 static int btrfs_migratepage(struct address_space *mapping,
8004 			     struct page *newpage, struct page *page,
8005 			     enum migrate_mode mode)
8006 {
8007 	int ret;
8008 
8009 	ret = migrate_page_move_mapping(mapping, newpage, page, 0);
8010 	if (ret != MIGRATEPAGE_SUCCESS)
8011 		return ret;
8012 
8013 	if (page_has_private(page))
8014 		attach_page_private(newpage, detach_page_private(page));
8015 
8016 	if (PagePrivate2(page)) {
8017 		ClearPagePrivate2(page);
8018 		SetPagePrivate2(newpage);
8019 	}
8020 
8021 	if (mode != MIGRATE_SYNC_NO_COPY)
8022 		migrate_page_copy(newpage, page);
8023 	else
8024 		migrate_page_states(newpage, page);
8025 	return MIGRATEPAGE_SUCCESS;
8026 }
8027 #endif
8028 
8029 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8030 				 unsigned int length)
8031 {
8032 	struct inode *inode = page->mapping->host;
8033 	struct extent_io_tree *tree;
8034 	struct btrfs_ordered_extent *ordered;
8035 	struct extent_state *cached_state = NULL;
8036 	u64 page_start = page_offset(page);
8037 	u64 page_end = page_start + PAGE_SIZE - 1;
8038 	u64 start;
8039 	u64 end;
8040 	int inode_evicting = inode->i_state & I_FREEING;
8041 
8042 	/*
8043 	 * we have the page locked, so new writeback can't start,
8044 	 * and the dirty bit won't be cleared while we are here.
8045 	 *
8046 	 * Wait for IO on this page so that we can safely clear
8047 	 * the PagePrivate2 bit and do ordered accounting
8048 	 */
8049 	wait_on_page_writeback(page);
8050 
8051 	tree = &BTRFS_I(inode)->io_tree;
8052 	if (offset) {
8053 		btrfs_releasepage(page, GFP_NOFS);
8054 		return;
8055 	}
8056 
8057 	if (!inode_evicting)
8058 		lock_extent_bits(tree, page_start, page_end, &cached_state);
8059 again:
8060 	start = page_start;
8061 	ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8062 					page_end - start + 1);
8063 	if (ordered) {
8064 		end = min(page_end,
8065 			  ordered->file_offset + ordered->num_bytes - 1);
8066 		/*
8067 		 * IO on this page will never be started, so we need
8068 		 * to account for any ordered extents now
8069 		 */
8070 		if (!inode_evicting)
8071 			clear_extent_bit(tree, start, end,
8072 					 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8073 					 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8074 					 EXTENT_DEFRAG, 1, 0, &cached_state);
8075 		/*
8076 		 * whoever cleared the private bit is responsible
8077 		 * for the finish_ordered_io
8078 		 */
8079 		if (TestClearPagePrivate2(page)) {
8080 			struct btrfs_ordered_inode_tree *tree;
8081 			u64 new_len;
8082 
8083 			tree = &BTRFS_I(inode)->ordered_tree;
8084 
8085 			spin_lock_irq(&tree->lock);
8086 			set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8087 			new_len = start - ordered->file_offset;
8088 			if (new_len < ordered->truncated_len)
8089 				ordered->truncated_len = new_len;
8090 			spin_unlock_irq(&tree->lock);
8091 
8092 			if (btrfs_dec_test_ordered_pending(inode, &ordered,
8093 							   start,
8094 							   end - start + 1, 1))
8095 				btrfs_finish_ordered_io(ordered);
8096 		}
8097 		btrfs_put_ordered_extent(ordered);
8098 		if (!inode_evicting) {
8099 			cached_state = NULL;
8100 			lock_extent_bits(tree, start, end,
8101 					 &cached_state);
8102 		}
8103 
8104 		start = end + 1;
8105 		if (start < page_end)
8106 			goto again;
8107 	}
8108 
8109 	/*
8110 	 * Qgroup reserved space handler
8111 	 * Page here will be either
8112 	 * 1) Already written to disk
8113 	 *    In this case, its reserved space is released from data rsv map
8114 	 *    and will be freed by delayed_ref handler finally.
8115 	 *    So even we call qgroup_free_data(), it won't decrease reserved
8116 	 *    space.
8117 	 * 2) Not written to disk
8118 	 *    This means the reserved space should be freed here. However,
8119 	 *    if a truncate invalidates the page (by clearing PageDirty)
8120 	 *    and the page is accounted for while allocating extent
8121 	 *    in btrfs_check_data_free_space() we let delayed_ref to
8122 	 *    free the entire extent.
8123 	 */
8124 	if (PageDirty(page))
8125 		btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8126 	if (!inode_evicting) {
8127 		clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8128 				 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8129 				 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8130 				 &cached_state);
8131 
8132 		__btrfs_releasepage(page, GFP_NOFS);
8133 	}
8134 
8135 	ClearPageChecked(page);
8136 	detach_page_private(page);
8137 }
8138 
8139 /*
8140  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8141  * called from a page fault handler when a page is first dirtied. Hence we must
8142  * be careful to check for EOF conditions here. We set the page up correctly
8143  * for a written page which means we get ENOSPC checking when writing into
8144  * holes and correct delalloc and unwritten extent mapping on filesystems that
8145  * support these features.
8146  *
8147  * We are not allowed to take the i_mutex here so we have to play games to
8148  * protect against truncate races as the page could now be beyond EOF.  Because
8149  * truncate_setsize() writes the inode size before removing pages, once we have
8150  * the page lock we can determine safely if the page is beyond EOF. If it is not
8151  * beyond EOF, then the page is guaranteed safe against truncation until we
8152  * unlock the page.
8153  */
8154 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8155 {
8156 	struct page *page = vmf->page;
8157 	struct inode *inode = file_inode(vmf->vma->vm_file);
8158 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8159 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8160 	struct btrfs_ordered_extent *ordered;
8161 	struct extent_state *cached_state = NULL;
8162 	struct extent_changeset *data_reserved = NULL;
8163 	char *kaddr;
8164 	unsigned long zero_start;
8165 	loff_t size;
8166 	vm_fault_t ret;
8167 	int ret2;
8168 	int reserved = 0;
8169 	u64 reserved_space;
8170 	u64 page_start;
8171 	u64 page_end;
8172 	u64 end;
8173 
8174 	reserved_space = PAGE_SIZE;
8175 
8176 	sb_start_pagefault(inode->i_sb);
8177 	page_start = page_offset(page);
8178 	page_end = page_start + PAGE_SIZE - 1;
8179 	end = page_end;
8180 
8181 	/*
8182 	 * Reserving delalloc space after obtaining the page lock can lead to
8183 	 * deadlock. For example, if a dirty page is locked by this function
8184 	 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8185 	 * dirty page write out, then the btrfs_writepage() function could
8186 	 * end up waiting indefinitely to get a lock on the page currently
8187 	 * being processed by btrfs_page_mkwrite() function.
8188 	 */
8189 	ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8190 					   reserved_space);
8191 	if (!ret2) {
8192 		ret2 = file_update_time(vmf->vma->vm_file);
8193 		reserved = 1;
8194 	}
8195 	if (ret2) {
8196 		ret = vmf_error(ret2);
8197 		if (reserved)
8198 			goto out;
8199 		goto out_noreserve;
8200 	}
8201 
8202 	ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8203 again:
8204 	lock_page(page);
8205 	size = i_size_read(inode);
8206 
8207 	if ((page->mapping != inode->i_mapping) ||
8208 	    (page_start >= size)) {
8209 		/* page got truncated out from underneath us */
8210 		goto out_unlock;
8211 	}
8212 	wait_on_page_writeback(page);
8213 
8214 	lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8215 	set_page_extent_mapped(page);
8216 
8217 	/*
8218 	 * we can't set the delalloc bits if there are pending ordered
8219 	 * extents.  Drop our locks and wait for them to finish
8220 	 */
8221 	ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8222 			PAGE_SIZE);
8223 	if (ordered) {
8224 		unlock_extent_cached(io_tree, page_start, page_end,
8225 				     &cached_state);
8226 		unlock_page(page);
8227 		btrfs_start_ordered_extent(inode, ordered, 1);
8228 		btrfs_put_ordered_extent(ordered);
8229 		goto again;
8230 	}
8231 
8232 	if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8233 		reserved_space = round_up(size - page_start,
8234 					  fs_info->sectorsize);
8235 		if (reserved_space < PAGE_SIZE) {
8236 			end = page_start + reserved_space - 1;
8237 			btrfs_delalloc_release_space(inode, data_reserved,
8238 					page_start, PAGE_SIZE - reserved_space,
8239 					true);
8240 		}
8241 	}
8242 
8243 	/*
8244 	 * page_mkwrite gets called when the page is firstly dirtied after it's
8245 	 * faulted in, but write(2) could also dirty a page and set delalloc
8246 	 * bits, thus in this case for space account reason, we still need to
8247 	 * clear any delalloc bits within this page range since we have to
8248 	 * reserve data&meta space before lock_page() (see above comments).
8249 	 */
8250 	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8251 			  EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8252 			  EXTENT_DEFRAG, 0, 0, &cached_state);
8253 
8254 	ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8255 					&cached_state);
8256 	if (ret2) {
8257 		unlock_extent_cached(io_tree, page_start, page_end,
8258 				     &cached_state);
8259 		ret = VM_FAULT_SIGBUS;
8260 		goto out_unlock;
8261 	}
8262 
8263 	/* page is wholly or partially inside EOF */
8264 	if (page_start + PAGE_SIZE > size)
8265 		zero_start = offset_in_page(size);
8266 	else
8267 		zero_start = PAGE_SIZE;
8268 
8269 	if (zero_start != PAGE_SIZE) {
8270 		kaddr = kmap(page);
8271 		memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8272 		flush_dcache_page(page);
8273 		kunmap(page);
8274 	}
8275 	ClearPageChecked(page);
8276 	set_page_dirty(page);
8277 	SetPageUptodate(page);
8278 
8279 	BTRFS_I(inode)->last_trans = fs_info->generation;
8280 	BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8281 	BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8282 
8283 	unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8284 
8285 	btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8286 	sb_end_pagefault(inode->i_sb);
8287 	extent_changeset_free(data_reserved);
8288 	return VM_FAULT_LOCKED;
8289 
8290 out_unlock:
8291 	unlock_page(page);
8292 out:
8293 	btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8294 	btrfs_delalloc_release_space(inode, data_reserved, page_start,
8295 				     reserved_space, (ret != 0));
8296 out_noreserve:
8297 	sb_end_pagefault(inode->i_sb);
8298 	extent_changeset_free(data_reserved);
8299 	return ret;
8300 }
8301 
8302 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8303 {
8304 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8305 	struct btrfs_root *root = BTRFS_I(inode)->root;
8306 	struct btrfs_block_rsv *rsv;
8307 	int ret;
8308 	struct btrfs_trans_handle *trans;
8309 	u64 mask = fs_info->sectorsize - 1;
8310 	u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8311 
8312 	if (!skip_writeback) {
8313 		ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8314 					       (u64)-1);
8315 		if (ret)
8316 			return ret;
8317 	}
8318 
8319 	/*
8320 	 * Yes ladies and gentlemen, this is indeed ugly.  We have a couple of
8321 	 * things going on here:
8322 	 *
8323 	 * 1) We need to reserve space to update our inode.
8324 	 *
8325 	 * 2) We need to have something to cache all the space that is going to
8326 	 * be free'd up by the truncate operation, but also have some slack
8327 	 * space reserved in case it uses space during the truncate (thank you
8328 	 * very much snapshotting).
8329 	 *
8330 	 * And we need these to be separate.  The fact is we can use a lot of
8331 	 * space doing the truncate, and we have no earthly idea how much space
8332 	 * we will use, so we need the truncate reservation to be separate so it
8333 	 * doesn't end up using space reserved for updating the inode.  We also
8334 	 * need to be able to stop the transaction and start a new one, which
8335 	 * means we need to be able to update the inode several times, and we
8336 	 * have no idea of knowing how many times that will be, so we can't just
8337 	 * reserve 1 item for the entirety of the operation, so that has to be
8338 	 * done separately as well.
8339 	 *
8340 	 * So that leaves us with
8341 	 *
8342 	 * 1) rsv - for the truncate reservation, which we will steal from the
8343 	 * transaction reservation.
8344 	 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8345 	 * updating the inode.
8346 	 */
8347 	rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8348 	if (!rsv)
8349 		return -ENOMEM;
8350 	rsv->size = min_size;
8351 	rsv->failfast = 1;
8352 
8353 	/*
8354 	 * 1 for the truncate slack space
8355 	 * 1 for updating the inode.
8356 	 */
8357 	trans = btrfs_start_transaction(root, 2);
8358 	if (IS_ERR(trans)) {
8359 		ret = PTR_ERR(trans);
8360 		goto out;
8361 	}
8362 
8363 	/* Migrate the slack space for the truncate to our reserve */
8364 	ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8365 				      min_size, false);
8366 	BUG_ON(ret);
8367 
8368 	/*
8369 	 * So if we truncate and then write and fsync we normally would just
8370 	 * write the extents that changed, which is a problem if we need to
8371 	 * first truncate that entire inode.  So set this flag so we write out
8372 	 * all of the extents in the inode to the sync log so we're completely
8373 	 * safe.
8374 	 */
8375 	set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8376 	trans->block_rsv = rsv;
8377 
8378 	while (1) {
8379 		ret = btrfs_truncate_inode_items(trans, root, inode,
8380 						 inode->i_size,
8381 						 BTRFS_EXTENT_DATA_KEY);
8382 		trans->block_rsv = &fs_info->trans_block_rsv;
8383 		if (ret != -ENOSPC && ret != -EAGAIN)
8384 			break;
8385 
8386 		ret = btrfs_update_inode(trans, root, inode);
8387 		if (ret)
8388 			break;
8389 
8390 		btrfs_end_transaction(trans);
8391 		btrfs_btree_balance_dirty(fs_info);
8392 
8393 		trans = btrfs_start_transaction(root, 2);
8394 		if (IS_ERR(trans)) {
8395 			ret = PTR_ERR(trans);
8396 			trans = NULL;
8397 			break;
8398 		}
8399 
8400 		btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8401 		ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8402 					      rsv, min_size, false);
8403 		BUG_ON(ret);	/* shouldn't happen */
8404 		trans->block_rsv = rsv;
8405 	}
8406 
8407 	/*
8408 	 * We can't call btrfs_truncate_block inside a trans handle as we could
8409 	 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8410 	 * we've truncated everything except the last little bit, and can do
8411 	 * btrfs_truncate_block and then update the disk_i_size.
8412 	 */
8413 	if (ret == NEED_TRUNCATE_BLOCK) {
8414 		btrfs_end_transaction(trans);
8415 		btrfs_btree_balance_dirty(fs_info);
8416 
8417 		ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
8418 		if (ret)
8419 			goto out;
8420 		trans = btrfs_start_transaction(root, 1);
8421 		if (IS_ERR(trans)) {
8422 			ret = PTR_ERR(trans);
8423 			goto out;
8424 		}
8425 		btrfs_inode_safe_disk_i_size_write(inode, 0);
8426 	}
8427 
8428 	if (trans) {
8429 		int ret2;
8430 
8431 		trans->block_rsv = &fs_info->trans_block_rsv;
8432 		ret2 = btrfs_update_inode(trans, root, inode);
8433 		if (ret2 && !ret)
8434 			ret = ret2;
8435 
8436 		ret2 = btrfs_end_transaction(trans);
8437 		if (ret2 && !ret)
8438 			ret = ret2;
8439 		btrfs_btree_balance_dirty(fs_info);
8440 	}
8441 out:
8442 	btrfs_free_block_rsv(fs_info, rsv);
8443 
8444 	return ret;
8445 }
8446 
8447 /*
8448  * create a new subvolume directory/inode (helper for the ioctl).
8449  */
8450 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8451 			     struct btrfs_root *new_root,
8452 			     struct btrfs_root *parent_root,
8453 			     u64 new_dirid)
8454 {
8455 	struct inode *inode;
8456 	int err;
8457 	u64 index = 0;
8458 
8459 	inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8460 				new_dirid, new_dirid,
8461 				S_IFDIR | (~current_umask() & S_IRWXUGO),
8462 				&index);
8463 	if (IS_ERR(inode))
8464 		return PTR_ERR(inode);
8465 	inode->i_op = &btrfs_dir_inode_operations;
8466 	inode->i_fop = &btrfs_dir_file_operations;
8467 
8468 	set_nlink(inode, 1);
8469 	btrfs_i_size_write(BTRFS_I(inode), 0);
8470 	unlock_new_inode(inode);
8471 
8472 	err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8473 	if (err)
8474 		btrfs_err(new_root->fs_info,
8475 			  "error inheriting subvolume %llu properties: %d",
8476 			  new_root->root_key.objectid, err);
8477 
8478 	err = btrfs_update_inode(trans, new_root, inode);
8479 
8480 	iput(inode);
8481 	return err;
8482 }
8483 
8484 struct inode *btrfs_alloc_inode(struct super_block *sb)
8485 {
8486 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8487 	struct btrfs_inode *ei;
8488 	struct inode *inode;
8489 
8490 	ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8491 	if (!ei)
8492 		return NULL;
8493 
8494 	ei->root = NULL;
8495 	ei->generation = 0;
8496 	ei->last_trans = 0;
8497 	ei->last_sub_trans = 0;
8498 	ei->logged_trans = 0;
8499 	ei->delalloc_bytes = 0;
8500 	ei->new_delalloc_bytes = 0;
8501 	ei->defrag_bytes = 0;
8502 	ei->disk_i_size = 0;
8503 	ei->flags = 0;
8504 	ei->csum_bytes = 0;
8505 	ei->index_cnt = (u64)-1;
8506 	ei->dir_index = 0;
8507 	ei->last_unlink_trans = 0;
8508 	ei->last_log_commit = 0;
8509 
8510 	spin_lock_init(&ei->lock);
8511 	ei->outstanding_extents = 0;
8512 	if (sb->s_magic != BTRFS_TEST_MAGIC)
8513 		btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8514 					      BTRFS_BLOCK_RSV_DELALLOC);
8515 	ei->runtime_flags = 0;
8516 	ei->prop_compress = BTRFS_COMPRESS_NONE;
8517 	ei->defrag_compress = BTRFS_COMPRESS_NONE;
8518 
8519 	ei->delayed_node = NULL;
8520 
8521 	ei->i_otime.tv_sec = 0;
8522 	ei->i_otime.tv_nsec = 0;
8523 
8524 	inode = &ei->vfs_inode;
8525 	extent_map_tree_init(&ei->extent_tree);
8526 	extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8527 	extent_io_tree_init(fs_info, &ei->io_failure_tree,
8528 			    IO_TREE_INODE_IO_FAILURE, inode);
8529 	extent_io_tree_init(fs_info, &ei->file_extent_tree,
8530 			    IO_TREE_INODE_FILE_EXTENT, inode);
8531 	ei->io_tree.track_uptodate = true;
8532 	ei->io_failure_tree.track_uptodate = true;
8533 	atomic_set(&ei->sync_writers, 0);
8534 	mutex_init(&ei->log_mutex);
8535 	btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8536 	INIT_LIST_HEAD(&ei->delalloc_inodes);
8537 	INIT_LIST_HEAD(&ei->delayed_iput);
8538 	RB_CLEAR_NODE(&ei->rb_node);
8539 	init_rwsem(&ei->dio_sem);
8540 
8541 	return inode;
8542 }
8543 
8544 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8545 void btrfs_test_destroy_inode(struct inode *inode)
8546 {
8547 	btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8548 	kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8549 }
8550 #endif
8551 
8552 void btrfs_free_inode(struct inode *inode)
8553 {
8554 	kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8555 }
8556 
8557 void btrfs_destroy_inode(struct inode *inode)
8558 {
8559 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8560 	struct btrfs_ordered_extent *ordered;
8561 	struct btrfs_root *root = BTRFS_I(inode)->root;
8562 
8563 	WARN_ON(!hlist_empty(&inode->i_dentry));
8564 	WARN_ON(inode->i_data.nrpages);
8565 	WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
8566 	WARN_ON(BTRFS_I(inode)->block_rsv.size);
8567 	WARN_ON(BTRFS_I(inode)->outstanding_extents);
8568 	WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8569 	WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
8570 	WARN_ON(BTRFS_I(inode)->csum_bytes);
8571 	WARN_ON(BTRFS_I(inode)->defrag_bytes);
8572 
8573 	/*
8574 	 * This can happen where we create an inode, but somebody else also
8575 	 * created the same inode and we need to destroy the one we already
8576 	 * created.
8577 	 */
8578 	if (!root)
8579 		return;
8580 
8581 	while (1) {
8582 		ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8583 		if (!ordered)
8584 			break;
8585 		else {
8586 			btrfs_err(fs_info,
8587 				  "found ordered extent %llu %llu on inode cleanup",
8588 				  ordered->file_offset, ordered->num_bytes);
8589 			btrfs_remove_ordered_extent(inode, ordered);
8590 			btrfs_put_ordered_extent(ordered);
8591 			btrfs_put_ordered_extent(ordered);
8592 		}
8593 	}
8594 	btrfs_qgroup_check_reserved_leak(inode);
8595 	inode_tree_del(inode);
8596 	btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8597 	btrfs_inode_clear_file_extent_range(BTRFS_I(inode), 0, (u64)-1);
8598 	btrfs_put_root(BTRFS_I(inode)->root);
8599 }
8600 
8601 int btrfs_drop_inode(struct inode *inode)
8602 {
8603 	struct btrfs_root *root = BTRFS_I(inode)->root;
8604 
8605 	if (root == NULL)
8606 		return 1;
8607 
8608 	/* the snap/subvol tree is on deleting */
8609 	if (btrfs_root_refs(&root->root_item) == 0)
8610 		return 1;
8611 	else
8612 		return generic_drop_inode(inode);
8613 }
8614 
8615 static void init_once(void *foo)
8616 {
8617 	struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8618 
8619 	inode_init_once(&ei->vfs_inode);
8620 }
8621 
8622 void __cold btrfs_destroy_cachep(void)
8623 {
8624 	/*
8625 	 * Make sure all delayed rcu free inodes are flushed before we
8626 	 * destroy cache.
8627 	 */
8628 	rcu_barrier();
8629 	kmem_cache_destroy(btrfs_inode_cachep);
8630 	kmem_cache_destroy(btrfs_trans_handle_cachep);
8631 	kmem_cache_destroy(btrfs_path_cachep);
8632 	kmem_cache_destroy(btrfs_free_space_cachep);
8633 	kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8634 }
8635 
8636 int __init btrfs_init_cachep(void)
8637 {
8638 	btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8639 			sizeof(struct btrfs_inode), 0,
8640 			SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8641 			init_once);
8642 	if (!btrfs_inode_cachep)
8643 		goto fail;
8644 
8645 	btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8646 			sizeof(struct btrfs_trans_handle), 0,
8647 			SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8648 	if (!btrfs_trans_handle_cachep)
8649 		goto fail;
8650 
8651 	btrfs_path_cachep = kmem_cache_create("btrfs_path",
8652 			sizeof(struct btrfs_path), 0,
8653 			SLAB_MEM_SPREAD, NULL);
8654 	if (!btrfs_path_cachep)
8655 		goto fail;
8656 
8657 	btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8658 			sizeof(struct btrfs_free_space), 0,
8659 			SLAB_MEM_SPREAD, NULL);
8660 	if (!btrfs_free_space_cachep)
8661 		goto fail;
8662 
8663 	btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8664 							PAGE_SIZE, PAGE_SIZE,
8665 							SLAB_RED_ZONE, NULL);
8666 	if (!btrfs_free_space_bitmap_cachep)
8667 		goto fail;
8668 
8669 	return 0;
8670 fail:
8671 	btrfs_destroy_cachep();
8672 	return -ENOMEM;
8673 }
8674 
8675 static int btrfs_getattr(const struct path *path, struct kstat *stat,
8676 			 u32 request_mask, unsigned int flags)
8677 {
8678 	u64 delalloc_bytes;
8679 	struct inode *inode = d_inode(path->dentry);
8680 	u32 blocksize = inode->i_sb->s_blocksize;
8681 	u32 bi_flags = BTRFS_I(inode)->flags;
8682 
8683 	stat->result_mask |= STATX_BTIME;
8684 	stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8685 	stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8686 	if (bi_flags & BTRFS_INODE_APPEND)
8687 		stat->attributes |= STATX_ATTR_APPEND;
8688 	if (bi_flags & BTRFS_INODE_COMPRESS)
8689 		stat->attributes |= STATX_ATTR_COMPRESSED;
8690 	if (bi_flags & BTRFS_INODE_IMMUTABLE)
8691 		stat->attributes |= STATX_ATTR_IMMUTABLE;
8692 	if (bi_flags & BTRFS_INODE_NODUMP)
8693 		stat->attributes |= STATX_ATTR_NODUMP;
8694 
8695 	stat->attributes_mask |= (STATX_ATTR_APPEND |
8696 				  STATX_ATTR_COMPRESSED |
8697 				  STATX_ATTR_IMMUTABLE |
8698 				  STATX_ATTR_NODUMP);
8699 
8700 	generic_fillattr(inode, stat);
8701 	stat->dev = BTRFS_I(inode)->root->anon_dev;
8702 
8703 	spin_lock(&BTRFS_I(inode)->lock);
8704 	delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8705 	spin_unlock(&BTRFS_I(inode)->lock);
8706 	stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8707 			ALIGN(delalloc_bytes, blocksize)) >> 9;
8708 	return 0;
8709 }
8710 
8711 static int btrfs_rename_exchange(struct inode *old_dir,
8712 			      struct dentry *old_dentry,
8713 			      struct inode *new_dir,
8714 			      struct dentry *new_dentry)
8715 {
8716 	struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8717 	struct btrfs_trans_handle *trans;
8718 	struct btrfs_root *root = BTRFS_I(old_dir)->root;
8719 	struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8720 	struct inode *new_inode = new_dentry->d_inode;
8721 	struct inode *old_inode = old_dentry->d_inode;
8722 	struct timespec64 ctime = current_time(old_inode);
8723 	struct dentry *parent;
8724 	u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8725 	u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8726 	u64 old_idx = 0;
8727 	u64 new_idx = 0;
8728 	int ret;
8729 	bool root_log_pinned = false;
8730 	bool dest_log_pinned = false;
8731 	struct btrfs_log_ctx ctx_root;
8732 	struct btrfs_log_ctx ctx_dest;
8733 	bool sync_log_root = false;
8734 	bool sync_log_dest = false;
8735 	bool commit_transaction = false;
8736 
8737 	/* we only allow rename subvolume link between subvolumes */
8738 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8739 		return -EXDEV;
8740 
8741 	btrfs_init_log_ctx(&ctx_root, old_inode);
8742 	btrfs_init_log_ctx(&ctx_dest, new_inode);
8743 
8744 	/* close the race window with snapshot create/destroy ioctl */
8745 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8746 	    new_ino == BTRFS_FIRST_FREE_OBJECTID)
8747 		down_read(&fs_info->subvol_sem);
8748 
8749 	/*
8750 	 * We want to reserve the absolute worst case amount of items.  So if
8751 	 * both inodes are subvols and we need to unlink them then that would
8752 	 * require 4 item modifications, but if they are both normal inodes it
8753 	 * would require 5 item modifications, so we'll assume their normal
8754 	 * inodes.  So 5 * 2 is 10, plus 2 for the new links, so 12 total items
8755 	 * should cover the worst case number of items we'll modify.
8756 	 */
8757 	trans = btrfs_start_transaction(root, 12);
8758 	if (IS_ERR(trans)) {
8759 		ret = PTR_ERR(trans);
8760 		goto out_notrans;
8761 	}
8762 
8763 	if (dest != root)
8764 		btrfs_record_root_in_trans(trans, dest);
8765 
8766 	/*
8767 	 * We need to find a free sequence number both in the source and
8768 	 * in the destination directory for the exchange.
8769 	 */
8770 	ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8771 	if (ret)
8772 		goto out_fail;
8773 	ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8774 	if (ret)
8775 		goto out_fail;
8776 
8777 	BTRFS_I(old_inode)->dir_index = 0ULL;
8778 	BTRFS_I(new_inode)->dir_index = 0ULL;
8779 
8780 	/* Reference for the source. */
8781 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8782 		/* force full log commit if subvolume involved. */
8783 		btrfs_set_log_full_commit(trans);
8784 	} else {
8785 		btrfs_pin_log_trans(root);
8786 		root_log_pinned = true;
8787 		ret = btrfs_insert_inode_ref(trans, dest,
8788 					     new_dentry->d_name.name,
8789 					     new_dentry->d_name.len,
8790 					     old_ino,
8791 					     btrfs_ino(BTRFS_I(new_dir)),
8792 					     old_idx);
8793 		if (ret)
8794 			goto out_fail;
8795 	}
8796 
8797 	/* And now for the dest. */
8798 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8799 		/* force full log commit if subvolume involved. */
8800 		btrfs_set_log_full_commit(trans);
8801 	} else {
8802 		btrfs_pin_log_trans(dest);
8803 		dest_log_pinned = true;
8804 		ret = btrfs_insert_inode_ref(trans, root,
8805 					     old_dentry->d_name.name,
8806 					     old_dentry->d_name.len,
8807 					     new_ino,
8808 					     btrfs_ino(BTRFS_I(old_dir)),
8809 					     new_idx);
8810 		if (ret)
8811 			goto out_fail;
8812 	}
8813 
8814 	/* Update inode version and ctime/mtime. */
8815 	inode_inc_iversion(old_dir);
8816 	inode_inc_iversion(new_dir);
8817 	inode_inc_iversion(old_inode);
8818 	inode_inc_iversion(new_inode);
8819 	old_dir->i_ctime = old_dir->i_mtime = ctime;
8820 	new_dir->i_ctime = new_dir->i_mtime = ctime;
8821 	old_inode->i_ctime = ctime;
8822 	new_inode->i_ctime = ctime;
8823 
8824 	if (old_dentry->d_parent != new_dentry->d_parent) {
8825 		btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8826 				BTRFS_I(old_inode), 1);
8827 		btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8828 				BTRFS_I(new_inode), 1);
8829 	}
8830 
8831 	/* src is a subvolume */
8832 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8833 		ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
8834 	} else { /* src is an inode */
8835 		ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
8836 					   BTRFS_I(old_dentry->d_inode),
8837 					   old_dentry->d_name.name,
8838 					   old_dentry->d_name.len);
8839 		if (!ret)
8840 			ret = btrfs_update_inode(trans, root, old_inode);
8841 	}
8842 	if (ret) {
8843 		btrfs_abort_transaction(trans, ret);
8844 		goto out_fail;
8845 	}
8846 
8847 	/* dest is a subvolume */
8848 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8849 		ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
8850 	} else { /* dest is an inode */
8851 		ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
8852 					   BTRFS_I(new_dentry->d_inode),
8853 					   new_dentry->d_name.name,
8854 					   new_dentry->d_name.len);
8855 		if (!ret)
8856 			ret = btrfs_update_inode(trans, dest, new_inode);
8857 	}
8858 	if (ret) {
8859 		btrfs_abort_transaction(trans, ret);
8860 		goto out_fail;
8861 	}
8862 
8863 	ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8864 			     new_dentry->d_name.name,
8865 			     new_dentry->d_name.len, 0, old_idx);
8866 	if (ret) {
8867 		btrfs_abort_transaction(trans, ret);
8868 		goto out_fail;
8869 	}
8870 
8871 	ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8872 			     old_dentry->d_name.name,
8873 			     old_dentry->d_name.len, 0, new_idx);
8874 	if (ret) {
8875 		btrfs_abort_transaction(trans, ret);
8876 		goto out_fail;
8877 	}
8878 
8879 	if (old_inode->i_nlink == 1)
8880 		BTRFS_I(old_inode)->dir_index = old_idx;
8881 	if (new_inode->i_nlink == 1)
8882 		BTRFS_I(new_inode)->dir_index = new_idx;
8883 
8884 	if (root_log_pinned) {
8885 		parent = new_dentry->d_parent;
8886 		ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
8887 					 BTRFS_I(old_dir), parent,
8888 					 false, &ctx_root);
8889 		if (ret == BTRFS_NEED_LOG_SYNC)
8890 			sync_log_root = true;
8891 		else if (ret == BTRFS_NEED_TRANS_COMMIT)
8892 			commit_transaction = true;
8893 		ret = 0;
8894 		btrfs_end_log_trans(root);
8895 		root_log_pinned = false;
8896 	}
8897 	if (dest_log_pinned) {
8898 		if (!commit_transaction) {
8899 			parent = old_dentry->d_parent;
8900 			ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
8901 						 BTRFS_I(new_dir), parent,
8902 						 false, &ctx_dest);
8903 			if (ret == BTRFS_NEED_LOG_SYNC)
8904 				sync_log_dest = true;
8905 			else if (ret == BTRFS_NEED_TRANS_COMMIT)
8906 				commit_transaction = true;
8907 			ret = 0;
8908 		}
8909 		btrfs_end_log_trans(dest);
8910 		dest_log_pinned = false;
8911 	}
8912 out_fail:
8913 	/*
8914 	 * If we have pinned a log and an error happened, we unpin tasks
8915 	 * trying to sync the log and force them to fallback to a transaction
8916 	 * commit if the log currently contains any of the inodes involved in
8917 	 * this rename operation (to ensure we do not persist a log with an
8918 	 * inconsistent state for any of these inodes or leading to any
8919 	 * inconsistencies when replayed). If the transaction was aborted, the
8920 	 * abortion reason is propagated to userspace when attempting to commit
8921 	 * the transaction. If the log does not contain any of these inodes, we
8922 	 * allow the tasks to sync it.
8923 	 */
8924 	if (ret && (root_log_pinned || dest_log_pinned)) {
8925 		if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
8926 		    btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
8927 		    btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
8928 		    (new_inode &&
8929 		     btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
8930 			btrfs_set_log_full_commit(trans);
8931 
8932 		if (root_log_pinned) {
8933 			btrfs_end_log_trans(root);
8934 			root_log_pinned = false;
8935 		}
8936 		if (dest_log_pinned) {
8937 			btrfs_end_log_trans(dest);
8938 			dest_log_pinned = false;
8939 		}
8940 	}
8941 	if (!ret && sync_log_root && !commit_transaction) {
8942 		ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
8943 				     &ctx_root);
8944 		if (ret)
8945 			commit_transaction = true;
8946 	}
8947 	if (!ret && sync_log_dest && !commit_transaction) {
8948 		ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
8949 				     &ctx_dest);
8950 		if (ret)
8951 			commit_transaction = true;
8952 	}
8953 	if (commit_transaction) {
8954 		/*
8955 		 * We may have set commit_transaction when logging the new name
8956 		 * in the destination root, in which case we left the source
8957 		 * root context in the list of log contextes. So make sure we
8958 		 * remove it to avoid invalid memory accesses, since the context
8959 		 * was allocated in our stack frame.
8960 		 */
8961 		if (sync_log_root) {
8962 			mutex_lock(&root->log_mutex);
8963 			list_del_init(&ctx_root.list);
8964 			mutex_unlock(&root->log_mutex);
8965 		}
8966 		ret = btrfs_commit_transaction(trans);
8967 	} else {
8968 		int ret2;
8969 
8970 		ret2 = btrfs_end_transaction(trans);
8971 		ret = ret ? ret : ret2;
8972 	}
8973 out_notrans:
8974 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8975 	    old_ino == BTRFS_FIRST_FREE_OBJECTID)
8976 		up_read(&fs_info->subvol_sem);
8977 
8978 	ASSERT(list_empty(&ctx_root.list));
8979 	ASSERT(list_empty(&ctx_dest.list));
8980 
8981 	return ret;
8982 }
8983 
8984 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
8985 				     struct btrfs_root *root,
8986 				     struct inode *dir,
8987 				     struct dentry *dentry)
8988 {
8989 	int ret;
8990 	struct inode *inode;
8991 	u64 objectid;
8992 	u64 index;
8993 
8994 	ret = btrfs_find_free_ino(root, &objectid);
8995 	if (ret)
8996 		return ret;
8997 
8998 	inode = btrfs_new_inode(trans, root, dir,
8999 				dentry->d_name.name,
9000 				dentry->d_name.len,
9001 				btrfs_ino(BTRFS_I(dir)),
9002 				objectid,
9003 				S_IFCHR | WHITEOUT_MODE,
9004 				&index);
9005 
9006 	if (IS_ERR(inode)) {
9007 		ret = PTR_ERR(inode);
9008 		return ret;
9009 	}
9010 
9011 	inode->i_op = &btrfs_special_inode_operations;
9012 	init_special_inode(inode, inode->i_mode,
9013 		WHITEOUT_DEV);
9014 
9015 	ret = btrfs_init_inode_security(trans, inode, dir,
9016 				&dentry->d_name);
9017 	if (ret)
9018 		goto out;
9019 
9020 	ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9021 				BTRFS_I(inode), 0, index);
9022 	if (ret)
9023 		goto out;
9024 
9025 	ret = btrfs_update_inode(trans, root, inode);
9026 out:
9027 	unlock_new_inode(inode);
9028 	if (ret)
9029 		inode_dec_link_count(inode);
9030 	iput(inode);
9031 
9032 	return ret;
9033 }
9034 
9035 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9036 			   struct inode *new_dir, struct dentry *new_dentry,
9037 			   unsigned int flags)
9038 {
9039 	struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9040 	struct btrfs_trans_handle *trans;
9041 	unsigned int trans_num_items;
9042 	struct btrfs_root *root = BTRFS_I(old_dir)->root;
9043 	struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9044 	struct inode *new_inode = d_inode(new_dentry);
9045 	struct inode *old_inode = d_inode(old_dentry);
9046 	u64 index = 0;
9047 	int ret;
9048 	u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9049 	bool log_pinned = false;
9050 	struct btrfs_log_ctx ctx;
9051 	bool sync_log = false;
9052 	bool commit_transaction = false;
9053 
9054 	if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9055 		return -EPERM;
9056 
9057 	/* we only allow rename subvolume link between subvolumes */
9058 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9059 		return -EXDEV;
9060 
9061 	if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9062 	    (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9063 		return -ENOTEMPTY;
9064 
9065 	if (S_ISDIR(old_inode->i_mode) && new_inode &&
9066 	    new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9067 		return -ENOTEMPTY;
9068 
9069 
9070 	/* check for collisions, even if the  name isn't there */
9071 	ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9072 			     new_dentry->d_name.name,
9073 			     new_dentry->d_name.len);
9074 
9075 	if (ret) {
9076 		if (ret == -EEXIST) {
9077 			/* we shouldn't get
9078 			 * eexist without a new_inode */
9079 			if (WARN_ON(!new_inode)) {
9080 				return ret;
9081 			}
9082 		} else {
9083 			/* maybe -EOVERFLOW */
9084 			return ret;
9085 		}
9086 	}
9087 	ret = 0;
9088 
9089 	/*
9090 	 * we're using rename to replace one file with another.  Start IO on it
9091 	 * now so  we don't add too much work to the end of the transaction
9092 	 */
9093 	if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9094 		filemap_flush(old_inode->i_mapping);
9095 
9096 	/* close the racy window with snapshot create/destroy ioctl */
9097 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9098 		down_read(&fs_info->subvol_sem);
9099 	/*
9100 	 * We want to reserve the absolute worst case amount of items.  So if
9101 	 * both inodes are subvols and we need to unlink them then that would
9102 	 * require 4 item modifications, but if they are both normal inodes it
9103 	 * would require 5 item modifications, so we'll assume they are normal
9104 	 * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9105 	 * should cover the worst case number of items we'll modify.
9106 	 * If our rename has the whiteout flag, we need more 5 units for the
9107 	 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9108 	 * when selinux is enabled).
9109 	 */
9110 	trans_num_items = 11;
9111 	if (flags & RENAME_WHITEOUT)
9112 		trans_num_items += 5;
9113 	trans = btrfs_start_transaction(root, trans_num_items);
9114 	if (IS_ERR(trans)) {
9115 		ret = PTR_ERR(trans);
9116 		goto out_notrans;
9117 	}
9118 
9119 	if (dest != root)
9120 		btrfs_record_root_in_trans(trans, dest);
9121 
9122 	ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9123 	if (ret)
9124 		goto out_fail;
9125 
9126 	BTRFS_I(old_inode)->dir_index = 0ULL;
9127 	if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9128 		/* force full log commit if subvolume involved. */
9129 		btrfs_set_log_full_commit(trans);
9130 	} else {
9131 		btrfs_pin_log_trans(root);
9132 		log_pinned = true;
9133 		ret = btrfs_insert_inode_ref(trans, dest,
9134 					     new_dentry->d_name.name,
9135 					     new_dentry->d_name.len,
9136 					     old_ino,
9137 					     btrfs_ino(BTRFS_I(new_dir)), index);
9138 		if (ret)
9139 			goto out_fail;
9140 	}
9141 
9142 	inode_inc_iversion(old_dir);
9143 	inode_inc_iversion(new_dir);
9144 	inode_inc_iversion(old_inode);
9145 	old_dir->i_ctime = old_dir->i_mtime =
9146 	new_dir->i_ctime = new_dir->i_mtime =
9147 	old_inode->i_ctime = current_time(old_dir);
9148 
9149 	if (old_dentry->d_parent != new_dentry->d_parent)
9150 		btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9151 				BTRFS_I(old_inode), 1);
9152 
9153 	if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9154 		ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9155 	} else {
9156 		ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9157 					BTRFS_I(d_inode(old_dentry)),
9158 					old_dentry->d_name.name,
9159 					old_dentry->d_name.len);
9160 		if (!ret)
9161 			ret = btrfs_update_inode(trans, root, old_inode);
9162 	}
9163 	if (ret) {
9164 		btrfs_abort_transaction(trans, ret);
9165 		goto out_fail;
9166 	}
9167 
9168 	if (new_inode) {
9169 		inode_inc_iversion(new_inode);
9170 		new_inode->i_ctime = current_time(new_inode);
9171 		if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9172 			     BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9173 			ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9174 			BUG_ON(new_inode->i_nlink == 0);
9175 		} else {
9176 			ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9177 						 BTRFS_I(d_inode(new_dentry)),
9178 						 new_dentry->d_name.name,
9179 						 new_dentry->d_name.len);
9180 		}
9181 		if (!ret && new_inode->i_nlink == 0)
9182 			ret = btrfs_orphan_add(trans,
9183 					BTRFS_I(d_inode(new_dentry)));
9184 		if (ret) {
9185 			btrfs_abort_transaction(trans, ret);
9186 			goto out_fail;
9187 		}
9188 	}
9189 
9190 	ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9191 			     new_dentry->d_name.name,
9192 			     new_dentry->d_name.len, 0, index);
9193 	if (ret) {
9194 		btrfs_abort_transaction(trans, ret);
9195 		goto out_fail;
9196 	}
9197 
9198 	if (old_inode->i_nlink == 1)
9199 		BTRFS_I(old_inode)->dir_index = index;
9200 
9201 	if (log_pinned) {
9202 		struct dentry *parent = new_dentry->d_parent;
9203 
9204 		btrfs_init_log_ctx(&ctx, old_inode);
9205 		ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9206 					 BTRFS_I(old_dir), parent,
9207 					 false, &ctx);
9208 		if (ret == BTRFS_NEED_LOG_SYNC)
9209 			sync_log = true;
9210 		else if (ret == BTRFS_NEED_TRANS_COMMIT)
9211 			commit_transaction = true;
9212 		ret = 0;
9213 		btrfs_end_log_trans(root);
9214 		log_pinned = false;
9215 	}
9216 
9217 	if (flags & RENAME_WHITEOUT) {
9218 		ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9219 						old_dentry);
9220 
9221 		if (ret) {
9222 			btrfs_abort_transaction(trans, ret);
9223 			goto out_fail;
9224 		}
9225 	}
9226 out_fail:
9227 	/*
9228 	 * If we have pinned the log and an error happened, we unpin tasks
9229 	 * trying to sync the log and force them to fallback to a transaction
9230 	 * commit if the log currently contains any of the inodes involved in
9231 	 * this rename operation (to ensure we do not persist a log with an
9232 	 * inconsistent state for any of these inodes or leading to any
9233 	 * inconsistencies when replayed). If the transaction was aborted, the
9234 	 * abortion reason is propagated to userspace when attempting to commit
9235 	 * the transaction. If the log does not contain any of these inodes, we
9236 	 * allow the tasks to sync it.
9237 	 */
9238 	if (ret && log_pinned) {
9239 		if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9240 		    btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9241 		    btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9242 		    (new_inode &&
9243 		     btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9244 			btrfs_set_log_full_commit(trans);
9245 
9246 		btrfs_end_log_trans(root);
9247 		log_pinned = false;
9248 	}
9249 	if (!ret && sync_log) {
9250 		ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9251 		if (ret)
9252 			commit_transaction = true;
9253 	} else if (sync_log) {
9254 		mutex_lock(&root->log_mutex);
9255 		list_del(&ctx.list);
9256 		mutex_unlock(&root->log_mutex);
9257 	}
9258 	if (commit_transaction) {
9259 		ret = btrfs_commit_transaction(trans);
9260 	} else {
9261 		int ret2;
9262 
9263 		ret2 = btrfs_end_transaction(trans);
9264 		ret = ret ? ret : ret2;
9265 	}
9266 out_notrans:
9267 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9268 		up_read(&fs_info->subvol_sem);
9269 
9270 	return ret;
9271 }
9272 
9273 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9274 			 struct inode *new_dir, struct dentry *new_dentry,
9275 			 unsigned int flags)
9276 {
9277 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9278 		return -EINVAL;
9279 
9280 	if (flags & RENAME_EXCHANGE)
9281 		return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9282 					  new_dentry);
9283 
9284 	return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9285 }
9286 
9287 struct btrfs_delalloc_work {
9288 	struct inode *inode;
9289 	struct completion completion;
9290 	struct list_head list;
9291 	struct btrfs_work work;
9292 };
9293 
9294 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9295 {
9296 	struct btrfs_delalloc_work *delalloc_work;
9297 	struct inode *inode;
9298 
9299 	delalloc_work = container_of(work, struct btrfs_delalloc_work,
9300 				     work);
9301 	inode = delalloc_work->inode;
9302 	filemap_flush(inode->i_mapping);
9303 	if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9304 				&BTRFS_I(inode)->runtime_flags))
9305 		filemap_flush(inode->i_mapping);
9306 
9307 	iput(inode);
9308 	complete(&delalloc_work->completion);
9309 }
9310 
9311 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9312 {
9313 	struct btrfs_delalloc_work *work;
9314 
9315 	work = kmalloc(sizeof(*work), GFP_NOFS);
9316 	if (!work)
9317 		return NULL;
9318 
9319 	init_completion(&work->completion);
9320 	INIT_LIST_HEAD(&work->list);
9321 	work->inode = inode;
9322 	btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9323 
9324 	return work;
9325 }
9326 
9327 /*
9328  * some fairly slow code that needs optimization. This walks the list
9329  * of all the inodes with pending delalloc and forces them to disk.
9330  */
9331 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
9332 {
9333 	struct btrfs_inode *binode;
9334 	struct inode *inode;
9335 	struct btrfs_delalloc_work *work, *next;
9336 	struct list_head works;
9337 	struct list_head splice;
9338 	int ret = 0;
9339 
9340 	INIT_LIST_HEAD(&works);
9341 	INIT_LIST_HEAD(&splice);
9342 
9343 	mutex_lock(&root->delalloc_mutex);
9344 	spin_lock(&root->delalloc_lock);
9345 	list_splice_init(&root->delalloc_inodes, &splice);
9346 	while (!list_empty(&splice)) {
9347 		binode = list_entry(splice.next, struct btrfs_inode,
9348 				    delalloc_inodes);
9349 
9350 		list_move_tail(&binode->delalloc_inodes,
9351 			       &root->delalloc_inodes);
9352 		inode = igrab(&binode->vfs_inode);
9353 		if (!inode) {
9354 			cond_resched_lock(&root->delalloc_lock);
9355 			continue;
9356 		}
9357 		spin_unlock(&root->delalloc_lock);
9358 
9359 		if (snapshot)
9360 			set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9361 				&binode->runtime_flags);
9362 		work = btrfs_alloc_delalloc_work(inode);
9363 		if (!work) {
9364 			iput(inode);
9365 			ret = -ENOMEM;
9366 			goto out;
9367 		}
9368 		list_add_tail(&work->list, &works);
9369 		btrfs_queue_work(root->fs_info->flush_workers,
9370 				 &work->work);
9371 		ret++;
9372 		if (nr != -1 && ret >= nr)
9373 			goto out;
9374 		cond_resched();
9375 		spin_lock(&root->delalloc_lock);
9376 	}
9377 	spin_unlock(&root->delalloc_lock);
9378 
9379 out:
9380 	list_for_each_entry_safe(work, next, &works, list) {
9381 		list_del_init(&work->list);
9382 		wait_for_completion(&work->completion);
9383 		kfree(work);
9384 	}
9385 
9386 	if (!list_empty(&splice)) {
9387 		spin_lock(&root->delalloc_lock);
9388 		list_splice_tail(&splice, &root->delalloc_inodes);
9389 		spin_unlock(&root->delalloc_lock);
9390 	}
9391 	mutex_unlock(&root->delalloc_mutex);
9392 	return ret;
9393 }
9394 
9395 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9396 {
9397 	struct btrfs_fs_info *fs_info = root->fs_info;
9398 	int ret;
9399 
9400 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9401 		return -EROFS;
9402 
9403 	ret = start_delalloc_inodes(root, -1, true);
9404 	if (ret > 0)
9405 		ret = 0;
9406 	return ret;
9407 }
9408 
9409 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
9410 {
9411 	struct btrfs_root *root;
9412 	struct list_head splice;
9413 	int ret;
9414 
9415 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9416 		return -EROFS;
9417 
9418 	INIT_LIST_HEAD(&splice);
9419 
9420 	mutex_lock(&fs_info->delalloc_root_mutex);
9421 	spin_lock(&fs_info->delalloc_root_lock);
9422 	list_splice_init(&fs_info->delalloc_roots, &splice);
9423 	while (!list_empty(&splice) && nr) {
9424 		root = list_first_entry(&splice, struct btrfs_root,
9425 					delalloc_root);
9426 		root = btrfs_grab_root(root);
9427 		BUG_ON(!root);
9428 		list_move_tail(&root->delalloc_root,
9429 			       &fs_info->delalloc_roots);
9430 		spin_unlock(&fs_info->delalloc_root_lock);
9431 
9432 		ret = start_delalloc_inodes(root, nr, false);
9433 		btrfs_put_root(root);
9434 		if (ret < 0)
9435 			goto out;
9436 
9437 		if (nr != -1) {
9438 			nr -= ret;
9439 			WARN_ON(nr < 0);
9440 		}
9441 		spin_lock(&fs_info->delalloc_root_lock);
9442 	}
9443 	spin_unlock(&fs_info->delalloc_root_lock);
9444 
9445 	ret = 0;
9446 out:
9447 	if (!list_empty(&splice)) {
9448 		spin_lock(&fs_info->delalloc_root_lock);
9449 		list_splice_tail(&splice, &fs_info->delalloc_roots);
9450 		spin_unlock(&fs_info->delalloc_root_lock);
9451 	}
9452 	mutex_unlock(&fs_info->delalloc_root_mutex);
9453 	return ret;
9454 }
9455 
9456 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9457 			 const char *symname)
9458 {
9459 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9460 	struct btrfs_trans_handle *trans;
9461 	struct btrfs_root *root = BTRFS_I(dir)->root;
9462 	struct btrfs_path *path;
9463 	struct btrfs_key key;
9464 	struct inode *inode = NULL;
9465 	int err;
9466 	u64 objectid;
9467 	u64 index = 0;
9468 	int name_len;
9469 	int datasize;
9470 	unsigned long ptr;
9471 	struct btrfs_file_extent_item *ei;
9472 	struct extent_buffer *leaf;
9473 
9474 	name_len = strlen(symname);
9475 	if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9476 		return -ENAMETOOLONG;
9477 
9478 	/*
9479 	 * 2 items for inode item and ref
9480 	 * 2 items for dir items
9481 	 * 1 item for updating parent inode item
9482 	 * 1 item for the inline extent item
9483 	 * 1 item for xattr if selinux is on
9484 	 */
9485 	trans = btrfs_start_transaction(root, 7);
9486 	if (IS_ERR(trans))
9487 		return PTR_ERR(trans);
9488 
9489 	err = btrfs_find_free_ino(root, &objectid);
9490 	if (err)
9491 		goto out_unlock;
9492 
9493 	inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9494 				dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9495 				objectid, S_IFLNK|S_IRWXUGO, &index);
9496 	if (IS_ERR(inode)) {
9497 		err = PTR_ERR(inode);
9498 		inode = NULL;
9499 		goto out_unlock;
9500 	}
9501 
9502 	/*
9503 	* If the active LSM wants to access the inode during
9504 	* d_instantiate it needs these. Smack checks to see
9505 	* if the filesystem supports xattrs by looking at the
9506 	* ops vector.
9507 	*/
9508 	inode->i_fop = &btrfs_file_operations;
9509 	inode->i_op = &btrfs_file_inode_operations;
9510 	inode->i_mapping->a_ops = &btrfs_aops;
9511 	BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9512 
9513 	err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9514 	if (err)
9515 		goto out_unlock;
9516 
9517 	path = btrfs_alloc_path();
9518 	if (!path) {
9519 		err = -ENOMEM;
9520 		goto out_unlock;
9521 	}
9522 	key.objectid = btrfs_ino(BTRFS_I(inode));
9523 	key.offset = 0;
9524 	key.type = BTRFS_EXTENT_DATA_KEY;
9525 	datasize = btrfs_file_extent_calc_inline_size(name_len);
9526 	err = btrfs_insert_empty_item(trans, root, path, &key,
9527 				      datasize);
9528 	if (err) {
9529 		btrfs_free_path(path);
9530 		goto out_unlock;
9531 	}
9532 	leaf = path->nodes[0];
9533 	ei = btrfs_item_ptr(leaf, path->slots[0],
9534 			    struct btrfs_file_extent_item);
9535 	btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9536 	btrfs_set_file_extent_type(leaf, ei,
9537 				   BTRFS_FILE_EXTENT_INLINE);
9538 	btrfs_set_file_extent_encryption(leaf, ei, 0);
9539 	btrfs_set_file_extent_compression(leaf, ei, 0);
9540 	btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9541 	btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9542 
9543 	ptr = btrfs_file_extent_inline_start(ei);
9544 	write_extent_buffer(leaf, symname, ptr, name_len);
9545 	btrfs_mark_buffer_dirty(leaf);
9546 	btrfs_free_path(path);
9547 
9548 	inode->i_op = &btrfs_symlink_inode_operations;
9549 	inode_nohighmem(inode);
9550 	inode_set_bytes(inode, name_len);
9551 	btrfs_i_size_write(BTRFS_I(inode), name_len);
9552 	err = btrfs_update_inode(trans, root, inode);
9553 	/*
9554 	 * Last step, add directory indexes for our symlink inode. This is the
9555 	 * last step to avoid extra cleanup of these indexes if an error happens
9556 	 * elsewhere above.
9557 	 */
9558 	if (!err)
9559 		err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9560 				BTRFS_I(inode), 0, index);
9561 	if (err)
9562 		goto out_unlock;
9563 
9564 	d_instantiate_new(dentry, inode);
9565 
9566 out_unlock:
9567 	btrfs_end_transaction(trans);
9568 	if (err && inode) {
9569 		inode_dec_link_count(inode);
9570 		discard_new_inode(inode);
9571 	}
9572 	btrfs_btree_balance_dirty(fs_info);
9573 	return err;
9574 }
9575 
9576 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9577 				       u64 start, u64 num_bytes, u64 min_size,
9578 				       loff_t actual_len, u64 *alloc_hint,
9579 				       struct btrfs_trans_handle *trans)
9580 {
9581 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9582 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9583 	struct extent_map *em;
9584 	struct btrfs_root *root = BTRFS_I(inode)->root;
9585 	struct btrfs_key ins;
9586 	u64 cur_offset = start;
9587 	u64 clear_offset = start;
9588 	u64 i_size;
9589 	u64 cur_bytes;
9590 	u64 last_alloc = (u64)-1;
9591 	int ret = 0;
9592 	bool own_trans = true;
9593 	u64 end = start + num_bytes - 1;
9594 
9595 	if (trans)
9596 		own_trans = false;
9597 	while (num_bytes > 0) {
9598 		if (own_trans) {
9599 			trans = btrfs_start_transaction(root, 3);
9600 			if (IS_ERR(trans)) {
9601 				ret = PTR_ERR(trans);
9602 				break;
9603 			}
9604 		}
9605 
9606 		cur_bytes = min_t(u64, num_bytes, SZ_256M);
9607 		cur_bytes = max(cur_bytes, min_size);
9608 		/*
9609 		 * If we are severely fragmented we could end up with really
9610 		 * small allocations, so if the allocator is returning small
9611 		 * chunks lets make its job easier by only searching for those
9612 		 * sized chunks.
9613 		 */
9614 		cur_bytes = min(cur_bytes, last_alloc);
9615 		ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9616 				min_size, 0, *alloc_hint, &ins, 1, 0);
9617 		if (ret) {
9618 			if (own_trans)
9619 				btrfs_end_transaction(trans);
9620 			break;
9621 		}
9622 
9623 		/*
9624 		 * We've reserved this space, and thus converted it from
9625 		 * ->bytes_may_use to ->bytes_reserved.  Any error that happens
9626 		 * from here on out we will only need to clear our reservation
9627 		 * for the remaining unreserved area, so advance our
9628 		 * clear_offset by our extent size.
9629 		 */
9630 		clear_offset += ins.offset;
9631 		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9632 
9633 		last_alloc = ins.offset;
9634 		ret = insert_reserved_file_extent(trans, inode,
9635 						  cur_offset, ins.objectid,
9636 						  ins.offset, ins.offset,
9637 						  ins.offset, 0, 0, 0,
9638 						  BTRFS_FILE_EXTENT_PREALLOC);
9639 		if (ret) {
9640 			btrfs_free_reserved_extent(fs_info, ins.objectid,
9641 						   ins.offset, 0);
9642 			btrfs_abort_transaction(trans, ret);
9643 			if (own_trans)
9644 				btrfs_end_transaction(trans);
9645 			break;
9646 		}
9647 
9648 		btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9649 					cur_offset + ins.offset -1, 0);
9650 
9651 		em = alloc_extent_map();
9652 		if (!em) {
9653 			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9654 				&BTRFS_I(inode)->runtime_flags);
9655 			goto next;
9656 		}
9657 
9658 		em->start = cur_offset;
9659 		em->orig_start = cur_offset;
9660 		em->len = ins.offset;
9661 		em->block_start = ins.objectid;
9662 		em->block_len = ins.offset;
9663 		em->orig_block_len = ins.offset;
9664 		em->ram_bytes = ins.offset;
9665 		set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9666 		em->generation = trans->transid;
9667 
9668 		while (1) {
9669 			write_lock(&em_tree->lock);
9670 			ret = add_extent_mapping(em_tree, em, 1);
9671 			write_unlock(&em_tree->lock);
9672 			if (ret != -EEXIST)
9673 				break;
9674 			btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9675 						cur_offset + ins.offset - 1,
9676 						0);
9677 		}
9678 		free_extent_map(em);
9679 next:
9680 		num_bytes -= ins.offset;
9681 		cur_offset += ins.offset;
9682 		*alloc_hint = ins.objectid + ins.offset;
9683 
9684 		inode_inc_iversion(inode);
9685 		inode->i_ctime = current_time(inode);
9686 		BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9687 		if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9688 		    (actual_len > inode->i_size) &&
9689 		    (cur_offset > inode->i_size)) {
9690 			if (cur_offset > actual_len)
9691 				i_size = actual_len;
9692 			else
9693 				i_size = cur_offset;
9694 			i_size_write(inode, i_size);
9695 			btrfs_inode_safe_disk_i_size_write(inode, 0);
9696 		}
9697 
9698 		ret = btrfs_update_inode(trans, root, inode);
9699 
9700 		if (ret) {
9701 			btrfs_abort_transaction(trans, ret);
9702 			if (own_trans)
9703 				btrfs_end_transaction(trans);
9704 			break;
9705 		}
9706 
9707 		if (own_trans)
9708 			btrfs_end_transaction(trans);
9709 	}
9710 	if (clear_offset < end)
9711 		btrfs_free_reserved_data_space(inode, NULL, clear_offset,
9712 			end - clear_offset + 1);
9713 	return ret;
9714 }
9715 
9716 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9717 			      u64 start, u64 num_bytes, u64 min_size,
9718 			      loff_t actual_len, u64 *alloc_hint)
9719 {
9720 	return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9721 					   min_size, actual_len, alloc_hint,
9722 					   NULL);
9723 }
9724 
9725 int btrfs_prealloc_file_range_trans(struct inode *inode,
9726 				    struct btrfs_trans_handle *trans, int mode,
9727 				    u64 start, u64 num_bytes, u64 min_size,
9728 				    loff_t actual_len, u64 *alloc_hint)
9729 {
9730 	return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9731 					   min_size, actual_len, alloc_hint, trans);
9732 }
9733 
9734 static int btrfs_set_page_dirty(struct page *page)
9735 {
9736 	return __set_page_dirty_nobuffers(page);
9737 }
9738 
9739 static int btrfs_permission(struct inode *inode, int mask)
9740 {
9741 	struct btrfs_root *root = BTRFS_I(inode)->root;
9742 	umode_t mode = inode->i_mode;
9743 
9744 	if (mask & MAY_WRITE &&
9745 	    (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9746 		if (btrfs_root_readonly(root))
9747 			return -EROFS;
9748 		if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9749 			return -EACCES;
9750 	}
9751 	return generic_permission(inode, mask);
9752 }
9753 
9754 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9755 {
9756 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9757 	struct btrfs_trans_handle *trans;
9758 	struct btrfs_root *root = BTRFS_I(dir)->root;
9759 	struct inode *inode = NULL;
9760 	u64 objectid;
9761 	u64 index;
9762 	int ret = 0;
9763 
9764 	/*
9765 	 * 5 units required for adding orphan entry
9766 	 */
9767 	trans = btrfs_start_transaction(root, 5);
9768 	if (IS_ERR(trans))
9769 		return PTR_ERR(trans);
9770 
9771 	ret = btrfs_find_free_ino(root, &objectid);
9772 	if (ret)
9773 		goto out;
9774 
9775 	inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9776 			btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
9777 	if (IS_ERR(inode)) {
9778 		ret = PTR_ERR(inode);
9779 		inode = NULL;
9780 		goto out;
9781 	}
9782 
9783 	inode->i_fop = &btrfs_file_operations;
9784 	inode->i_op = &btrfs_file_inode_operations;
9785 
9786 	inode->i_mapping->a_ops = &btrfs_aops;
9787 	BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9788 
9789 	ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9790 	if (ret)
9791 		goto out;
9792 
9793 	ret = btrfs_update_inode(trans, root, inode);
9794 	if (ret)
9795 		goto out;
9796 	ret = btrfs_orphan_add(trans, BTRFS_I(inode));
9797 	if (ret)
9798 		goto out;
9799 
9800 	/*
9801 	 * We set number of links to 0 in btrfs_new_inode(), and here we set
9802 	 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9803 	 * through:
9804 	 *
9805 	 *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9806 	 */
9807 	set_nlink(inode, 1);
9808 	d_tmpfile(dentry, inode);
9809 	unlock_new_inode(inode);
9810 	mark_inode_dirty(inode);
9811 out:
9812 	btrfs_end_transaction(trans);
9813 	if (ret && inode)
9814 		discard_new_inode(inode);
9815 	btrfs_btree_balance_dirty(fs_info);
9816 	return ret;
9817 }
9818 
9819 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
9820 {
9821 	struct inode *inode = tree->private_data;
9822 	unsigned long index = start >> PAGE_SHIFT;
9823 	unsigned long end_index = end >> PAGE_SHIFT;
9824 	struct page *page;
9825 
9826 	while (index <= end_index) {
9827 		page = find_get_page(inode->i_mapping, index);
9828 		ASSERT(page); /* Pages should be in the extent_io_tree */
9829 		set_page_writeback(page);
9830 		put_page(page);
9831 		index++;
9832 	}
9833 }
9834 
9835 #ifdef CONFIG_SWAP
9836 /*
9837  * Add an entry indicating a block group or device which is pinned by a
9838  * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
9839  * negative errno on failure.
9840  */
9841 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
9842 				  bool is_block_group)
9843 {
9844 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9845 	struct btrfs_swapfile_pin *sp, *entry;
9846 	struct rb_node **p;
9847 	struct rb_node *parent = NULL;
9848 
9849 	sp = kmalloc(sizeof(*sp), GFP_NOFS);
9850 	if (!sp)
9851 		return -ENOMEM;
9852 	sp->ptr = ptr;
9853 	sp->inode = inode;
9854 	sp->is_block_group = is_block_group;
9855 
9856 	spin_lock(&fs_info->swapfile_pins_lock);
9857 	p = &fs_info->swapfile_pins.rb_node;
9858 	while (*p) {
9859 		parent = *p;
9860 		entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
9861 		if (sp->ptr < entry->ptr ||
9862 		    (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
9863 			p = &(*p)->rb_left;
9864 		} else if (sp->ptr > entry->ptr ||
9865 			   (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
9866 			p = &(*p)->rb_right;
9867 		} else {
9868 			spin_unlock(&fs_info->swapfile_pins_lock);
9869 			kfree(sp);
9870 			return 1;
9871 		}
9872 	}
9873 	rb_link_node(&sp->node, parent, p);
9874 	rb_insert_color(&sp->node, &fs_info->swapfile_pins);
9875 	spin_unlock(&fs_info->swapfile_pins_lock);
9876 	return 0;
9877 }
9878 
9879 /* Free all of the entries pinned by this swapfile. */
9880 static void btrfs_free_swapfile_pins(struct inode *inode)
9881 {
9882 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9883 	struct btrfs_swapfile_pin *sp;
9884 	struct rb_node *node, *next;
9885 
9886 	spin_lock(&fs_info->swapfile_pins_lock);
9887 	node = rb_first(&fs_info->swapfile_pins);
9888 	while (node) {
9889 		next = rb_next(node);
9890 		sp = rb_entry(node, struct btrfs_swapfile_pin, node);
9891 		if (sp->inode == inode) {
9892 			rb_erase(&sp->node, &fs_info->swapfile_pins);
9893 			if (sp->is_block_group)
9894 				btrfs_put_block_group(sp->ptr);
9895 			kfree(sp);
9896 		}
9897 		node = next;
9898 	}
9899 	spin_unlock(&fs_info->swapfile_pins_lock);
9900 }
9901 
9902 struct btrfs_swap_info {
9903 	u64 start;
9904 	u64 block_start;
9905 	u64 block_len;
9906 	u64 lowest_ppage;
9907 	u64 highest_ppage;
9908 	unsigned long nr_pages;
9909 	int nr_extents;
9910 };
9911 
9912 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
9913 				 struct btrfs_swap_info *bsi)
9914 {
9915 	unsigned long nr_pages;
9916 	u64 first_ppage, first_ppage_reported, next_ppage;
9917 	int ret;
9918 
9919 	first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
9920 	next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
9921 				PAGE_SIZE) >> PAGE_SHIFT;
9922 
9923 	if (first_ppage >= next_ppage)
9924 		return 0;
9925 	nr_pages = next_ppage - first_ppage;
9926 
9927 	first_ppage_reported = first_ppage;
9928 	if (bsi->start == 0)
9929 		first_ppage_reported++;
9930 	if (bsi->lowest_ppage > first_ppage_reported)
9931 		bsi->lowest_ppage = first_ppage_reported;
9932 	if (bsi->highest_ppage < (next_ppage - 1))
9933 		bsi->highest_ppage = next_ppage - 1;
9934 
9935 	ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
9936 	if (ret < 0)
9937 		return ret;
9938 	bsi->nr_extents += ret;
9939 	bsi->nr_pages += nr_pages;
9940 	return 0;
9941 }
9942 
9943 static void btrfs_swap_deactivate(struct file *file)
9944 {
9945 	struct inode *inode = file_inode(file);
9946 
9947 	btrfs_free_swapfile_pins(inode);
9948 	atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
9949 }
9950 
9951 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
9952 			       sector_t *span)
9953 {
9954 	struct inode *inode = file_inode(file);
9955 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9956 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9957 	struct extent_state *cached_state = NULL;
9958 	struct extent_map *em = NULL;
9959 	struct btrfs_device *device = NULL;
9960 	struct btrfs_swap_info bsi = {
9961 		.lowest_ppage = (sector_t)-1ULL,
9962 	};
9963 	int ret = 0;
9964 	u64 isize;
9965 	u64 start;
9966 
9967 	/*
9968 	 * If the swap file was just created, make sure delalloc is done. If the
9969 	 * file changes again after this, the user is doing something stupid and
9970 	 * we don't really care.
9971 	 */
9972 	ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
9973 	if (ret)
9974 		return ret;
9975 
9976 	/*
9977 	 * The inode is locked, so these flags won't change after we check them.
9978 	 */
9979 	if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
9980 		btrfs_warn(fs_info, "swapfile must not be compressed");
9981 		return -EINVAL;
9982 	}
9983 	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
9984 		btrfs_warn(fs_info, "swapfile must not be copy-on-write");
9985 		return -EINVAL;
9986 	}
9987 	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
9988 		btrfs_warn(fs_info, "swapfile must not be checksummed");
9989 		return -EINVAL;
9990 	}
9991 
9992 	/*
9993 	 * Balance or device remove/replace/resize can move stuff around from
9994 	 * under us. The EXCL_OP flag makes sure they aren't running/won't run
9995 	 * concurrently while we are mapping the swap extents, and
9996 	 * fs_info->swapfile_pins prevents them from running while the swap file
9997 	 * is active and moving the extents. Note that this also prevents a
9998 	 * concurrent device add which isn't actually necessary, but it's not
9999 	 * really worth the trouble to allow it.
10000 	 */
10001 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10002 		btrfs_warn(fs_info,
10003 	   "cannot activate swapfile while exclusive operation is running");
10004 		return -EBUSY;
10005 	}
10006 	/*
10007 	 * Snapshots can create extents which require COW even if NODATACOW is
10008 	 * set. We use this counter to prevent snapshots. We must increment it
10009 	 * before walking the extents because we don't want a concurrent
10010 	 * snapshot to run after we've already checked the extents.
10011 	 */
10012 	atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10013 
10014 	isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10015 
10016 	lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10017 	start = 0;
10018 	while (start < isize) {
10019 		u64 logical_block_start, physical_block_start;
10020 		struct btrfs_block_group *bg;
10021 		u64 len = isize - start;
10022 
10023 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10024 		if (IS_ERR(em)) {
10025 			ret = PTR_ERR(em);
10026 			goto out;
10027 		}
10028 
10029 		if (em->block_start == EXTENT_MAP_HOLE) {
10030 			btrfs_warn(fs_info, "swapfile must not have holes");
10031 			ret = -EINVAL;
10032 			goto out;
10033 		}
10034 		if (em->block_start == EXTENT_MAP_INLINE) {
10035 			/*
10036 			 * It's unlikely we'll ever actually find ourselves
10037 			 * here, as a file small enough to fit inline won't be
10038 			 * big enough to store more than the swap header, but in
10039 			 * case something changes in the future, let's catch it
10040 			 * here rather than later.
10041 			 */
10042 			btrfs_warn(fs_info, "swapfile must not be inline");
10043 			ret = -EINVAL;
10044 			goto out;
10045 		}
10046 		if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10047 			btrfs_warn(fs_info, "swapfile must not be compressed");
10048 			ret = -EINVAL;
10049 			goto out;
10050 		}
10051 
10052 		logical_block_start = em->block_start + (start - em->start);
10053 		len = min(len, em->len - (start - em->start));
10054 		free_extent_map(em);
10055 		em = NULL;
10056 
10057 		ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10058 		if (ret < 0) {
10059 			goto out;
10060 		} else if (ret) {
10061 			ret = 0;
10062 		} else {
10063 			btrfs_warn(fs_info,
10064 				   "swapfile must not be copy-on-write");
10065 			ret = -EINVAL;
10066 			goto out;
10067 		}
10068 
10069 		em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10070 		if (IS_ERR(em)) {
10071 			ret = PTR_ERR(em);
10072 			goto out;
10073 		}
10074 
10075 		if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10076 			btrfs_warn(fs_info,
10077 				   "swapfile must have single data profile");
10078 			ret = -EINVAL;
10079 			goto out;
10080 		}
10081 
10082 		if (device == NULL) {
10083 			device = em->map_lookup->stripes[0].dev;
10084 			ret = btrfs_add_swapfile_pin(inode, device, false);
10085 			if (ret == 1)
10086 				ret = 0;
10087 			else if (ret)
10088 				goto out;
10089 		} else if (device != em->map_lookup->stripes[0].dev) {
10090 			btrfs_warn(fs_info, "swapfile must be on one device");
10091 			ret = -EINVAL;
10092 			goto out;
10093 		}
10094 
10095 		physical_block_start = (em->map_lookup->stripes[0].physical +
10096 					(logical_block_start - em->start));
10097 		len = min(len, em->len - (logical_block_start - em->start));
10098 		free_extent_map(em);
10099 		em = NULL;
10100 
10101 		bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10102 		if (!bg) {
10103 			btrfs_warn(fs_info,
10104 			   "could not find block group containing swapfile");
10105 			ret = -EINVAL;
10106 			goto out;
10107 		}
10108 
10109 		ret = btrfs_add_swapfile_pin(inode, bg, true);
10110 		if (ret) {
10111 			btrfs_put_block_group(bg);
10112 			if (ret == 1)
10113 				ret = 0;
10114 			else
10115 				goto out;
10116 		}
10117 
10118 		if (bsi.block_len &&
10119 		    bsi.block_start + bsi.block_len == physical_block_start) {
10120 			bsi.block_len += len;
10121 		} else {
10122 			if (bsi.block_len) {
10123 				ret = btrfs_add_swap_extent(sis, &bsi);
10124 				if (ret)
10125 					goto out;
10126 			}
10127 			bsi.start = start;
10128 			bsi.block_start = physical_block_start;
10129 			bsi.block_len = len;
10130 		}
10131 
10132 		start += len;
10133 	}
10134 
10135 	if (bsi.block_len)
10136 		ret = btrfs_add_swap_extent(sis, &bsi);
10137 
10138 out:
10139 	if (!IS_ERR_OR_NULL(em))
10140 		free_extent_map(em);
10141 
10142 	unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10143 
10144 	if (ret)
10145 		btrfs_swap_deactivate(file);
10146 
10147 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10148 
10149 	if (ret)
10150 		return ret;
10151 
10152 	if (device)
10153 		sis->bdev = device->bdev;
10154 	*span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10155 	sis->max = bsi.nr_pages;
10156 	sis->pages = bsi.nr_pages - 1;
10157 	sis->highest_bit = bsi.nr_pages - 1;
10158 	return bsi.nr_extents;
10159 }
10160 #else
10161 static void btrfs_swap_deactivate(struct file *file)
10162 {
10163 }
10164 
10165 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10166 			       sector_t *span)
10167 {
10168 	return -EOPNOTSUPP;
10169 }
10170 #endif
10171 
10172 static const struct inode_operations btrfs_dir_inode_operations = {
10173 	.getattr	= btrfs_getattr,
10174 	.lookup		= btrfs_lookup,
10175 	.create		= btrfs_create,
10176 	.unlink		= btrfs_unlink,
10177 	.link		= btrfs_link,
10178 	.mkdir		= btrfs_mkdir,
10179 	.rmdir		= btrfs_rmdir,
10180 	.rename		= btrfs_rename2,
10181 	.symlink	= btrfs_symlink,
10182 	.setattr	= btrfs_setattr,
10183 	.mknod		= btrfs_mknod,
10184 	.listxattr	= btrfs_listxattr,
10185 	.permission	= btrfs_permission,
10186 	.get_acl	= btrfs_get_acl,
10187 	.set_acl	= btrfs_set_acl,
10188 	.update_time	= btrfs_update_time,
10189 	.tmpfile        = btrfs_tmpfile,
10190 };
10191 
10192 static const struct file_operations btrfs_dir_file_operations = {
10193 	.llseek		= generic_file_llseek,
10194 	.read		= generic_read_dir,
10195 	.iterate_shared	= btrfs_real_readdir,
10196 	.open		= btrfs_opendir,
10197 	.unlocked_ioctl	= btrfs_ioctl,
10198 #ifdef CONFIG_COMPAT
10199 	.compat_ioctl	= btrfs_compat_ioctl,
10200 #endif
10201 	.release        = btrfs_release_file,
10202 	.fsync		= btrfs_sync_file,
10203 };
10204 
10205 static const struct extent_io_ops btrfs_extent_io_ops = {
10206 	/* mandatory callbacks */
10207 	.submit_bio_hook = btrfs_submit_bio_hook,
10208 	.readpage_end_io_hook = btrfs_readpage_end_io_hook,
10209 };
10210 
10211 /*
10212  * btrfs doesn't support the bmap operation because swapfiles
10213  * use bmap to make a mapping of extents in the file.  They assume
10214  * these extents won't change over the life of the file and they
10215  * use the bmap result to do IO directly to the drive.
10216  *
10217  * the btrfs bmap call would return logical addresses that aren't
10218  * suitable for IO and they also will change frequently as COW
10219  * operations happen.  So, swapfile + btrfs == corruption.
10220  *
10221  * For now we're avoiding this by dropping bmap.
10222  */
10223 static const struct address_space_operations btrfs_aops = {
10224 	.readpage	= btrfs_readpage,
10225 	.writepage	= btrfs_writepage,
10226 	.writepages	= btrfs_writepages,
10227 	.readahead	= btrfs_readahead,
10228 	.direct_IO	= btrfs_direct_IO,
10229 	.invalidatepage = btrfs_invalidatepage,
10230 	.releasepage	= btrfs_releasepage,
10231 #ifdef CONFIG_MIGRATION
10232 	.migratepage	= btrfs_migratepage,
10233 #endif
10234 	.set_page_dirty	= btrfs_set_page_dirty,
10235 	.error_remove_page = generic_error_remove_page,
10236 	.swap_activate	= btrfs_swap_activate,
10237 	.swap_deactivate = btrfs_swap_deactivate,
10238 };
10239 
10240 static const struct inode_operations btrfs_file_inode_operations = {
10241 	.getattr	= btrfs_getattr,
10242 	.setattr	= btrfs_setattr,
10243 	.listxattr      = btrfs_listxattr,
10244 	.permission	= btrfs_permission,
10245 	.fiemap		= btrfs_fiemap,
10246 	.get_acl	= btrfs_get_acl,
10247 	.set_acl	= btrfs_set_acl,
10248 	.update_time	= btrfs_update_time,
10249 };
10250 static const struct inode_operations btrfs_special_inode_operations = {
10251 	.getattr	= btrfs_getattr,
10252 	.setattr	= btrfs_setattr,
10253 	.permission	= btrfs_permission,
10254 	.listxattr	= btrfs_listxattr,
10255 	.get_acl	= btrfs_get_acl,
10256 	.set_acl	= btrfs_set_acl,
10257 	.update_time	= btrfs_update_time,
10258 };
10259 static const struct inode_operations btrfs_symlink_inode_operations = {
10260 	.get_link	= page_get_link,
10261 	.getattr	= btrfs_getattr,
10262 	.setattr	= btrfs_setattr,
10263 	.permission	= btrfs_permission,
10264 	.listxattr	= btrfs_listxattr,
10265 	.update_time	= btrfs_update_time,
10266 };
10267 
10268 const struct dentry_operations btrfs_dentry_operations = {
10269 	.d_delete	= btrfs_dentry_delete,
10270 };
10271