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