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