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