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