xref: /linux/fs/btrfs/file-item.c (revision fab183d632628381b466a41479489541ac0e29a0)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/bio.h>
7 #include <linux/slab.h>
8 #include <linux/pagemap.h>
9 #include <linux/highmem.h>
10 #include <linux/sched/mm.h>
11 #include "messages.h"
12 #include "ctree.h"
13 #include "disk-io.h"
14 #include "transaction.h"
15 #include "bio.h"
16 #include "compression.h"
17 #include "fs.h"
18 #include "accessors.h"
19 #include "file-item.h"
20 #include "volumes.h"
21 
22 #define __MAX_CSUM_ITEMS(r, size) ((unsigned long)(((BTRFS_LEAF_DATA_SIZE(r) - \
23 				   sizeof(struct btrfs_item) * 2) / \
24 				  size) - 1))
25 
26 #define MAX_CSUM_ITEMS(r, size) (min_t(u32, __MAX_CSUM_ITEMS(r, size), \
27 				       PAGE_SIZE))
28 
29 /*
30  * Set inode's size according to filesystem options.
31  *
32  * @inode:      inode we want to update the disk_i_size for
33  * @new_i_size: i_size we want to set to, 0 if we use i_size
34  *
35  * With NO_HOLES set this simply sets the disk_is_size to whatever i_size_read()
36  * returns as it is perfectly fine with a file that has holes without hole file
37  * extent items.
38  *
39  * However without NO_HOLES we need to only return the area that is contiguous
40  * from the 0 offset of the file.  Otherwise we could end up adjust i_size up
41  * to an extent that has a gap in between.
42  *
43  * Finally new_i_size should only be set in the case of truncate where we're not
44  * ready to use i_size_read() as the limiter yet.
45  */
btrfs_inode_safe_disk_i_size_write(struct btrfs_inode * inode,u64 new_i_size)46 void btrfs_inode_safe_disk_i_size_write(struct btrfs_inode *inode, u64 new_i_size)
47 {
48 	u64 start, end, i_size;
49 	bool found;
50 
51 	spin_lock(&inode->lock);
52 	i_size = new_i_size ?: i_size_read(&inode->vfs_inode);
53 	if (!inode->file_extent_tree) {
54 		inode->disk_i_size = i_size;
55 		goto out_unlock;
56 	}
57 
58 	found = btrfs_find_contiguous_extent_bit(inode->file_extent_tree, 0, &start,
59 						 &end, EXTENT_DIRTY);
60 	if (found && start == 0)
61 		i_size = min(i_size, end + 1);
62 	else
63 		i_size = 0;
64 	inode->disk_i_size = i_size;
65 out_unlock:
66 	spin_unlock(&inode->lock);
67 }
68 
69 /*
70  * Mark range within a file as having a new extent inserted.
71  *
72  * @inode: inode being modified
73  * @start: start file offset of the file extent we've inserted
74  * @len:   logical length of the file extent item
75  *
76  * Call when we are inserting a new file extent where there was none before.
77  * Does not need to call this in the case where we're replacing an existing file
78  * extent, however if not sure it's fine to call this multiple times.
79  *
80  * The start and len must match the file extent item, so thus must be sectorsize
81  * aligned.
82  */
btrfs_inode_set_file_extent_range(struct btrfs_inode * inode,u64 start,u64 len)83 int btrfs_inode_set_file_extent_range(struct btrfs_inode *inode, u64 start,
84 				      u64 len)
85 {
86 	if (!inode->file_extent_tree)
87 		return 0;
88 
89 	if (len == 0)
90 		return 0;
91 
92 	ASSERT(IS_ALIGNED(start + len, inode->root->fs_info->sectorsize));
93 
94 	return btrfs_set_extent_bit(inode->file_extent_tree, start, start + len - 1,
95 				    EXTENT_DIRTY, NULL);
96 }
97 
98 /*
99  * Mark an inode range as not having a backing extent.
100  *
101  * @inode: inode being modified
102  * @start: start file offset of the file extent we've inserted
103  * @len:   logical length of the file extent item
104  *
105  * Called when we drop a file extent, for example when we truncate.  Doesn't
106  * need to be called for cases where we're replacing a file extent, like when
107  * we've COWed a file extent.
108  *
109  * The start and len must match the file extent item, so thus must be sectorsize
110  * aligned.
111  */
btrfs_inode_clear_file_extent_range(struct btrfs_inode * inode,u64 start,u64 len)112 int btrfs_inode_clear_file_extent_range(struct btrfs_inode *inode, u64 start,
113 					u64 len)
114 {
115 	if (!inode->file_extent_tree)
116 		return 0;
117 
118 	if (len == 0)
119 		return 0;
120 
121 	ASSERT(IS_ALIGNED(start + len, inode->root->fs_info->sectorsize) ||
122 	       len == (u64)-1);
123 
124 	return btrfs_clear_extent_bit(inode->file_extent_tree, start,
125 				      start + len - 1, EXTENT_DIRTY, NULL);
126 }
127 
bytes_to_csum_size(const struct btrfs_fs_info * fs_info,u32 bytes)128 static size_t bytes_to_csum_size(const struct btrfs_fs_info *fs_info, u32 bytes)
129 {
130 	ASSERT(IS_ALIGNED(bytes, fs_info->sectorsize));
131 
132 	return (bytes >> fs_info->sectorsize_bits) * fs_info->csum_size;
133 }
134 
csum_size_to_bytes(const struct btrfs_fs_info * fs_info,u32 csum_size)135 static size_t csum_size_to_bytes(const struct btrfs_fs_info *fs_info, u32 csum_size)
136 {
137 	ASSERT(IS_ALIGNED(csum_size, fs_info->csum_size));
138 
139 	return (csum_size / fs_info->csum_size) << fs_info->sectorsize_bits;
140 }
141 
max_ordered_sum_bytes(const struct btrfs_fs_info * fs_info)142 static inline u32 max_ordered_sum_bytes(const struct btrfs_fs_info *fs_info)
143 {
144 	u32 max_csum_size = round_down(PAGE_SIZE - sizeof(struct btrfs_ordered_sum),
145 				       fs_info->csum_size);
146 
147 	return csum_size_to_bytes(fs_info, max_csum_size);
148 }
149 
150 /*
151  * Calculate the total size needed to allocate for an ordered sum structure
152  * spanning @bytes in the file.
153  */
btrfs_ordered_sum_size(const struct btrfs_fs_info * fs_info,unsigned long bytes)154 static int btrfs_ordered_sum_size(const struct btrfs_fs_info *fs_info, unsigned long bytes)
155 {
156 	return sizeof(struct btrfs_ordered_sum) + bytes_to_csum_size(fs_info, bytes);
157 }
158 
btrfs_insert_hole_extent(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 objectid,u64 pos,u64 num_bytes)159 int btrfs_insert_hole_extent(struct btrfs_trans_handle *trans,
160 			     struct btrfs_root *root,
161 			     u64 objectid, u64 pos, u64 num_bytes)
162 {
163 	int ret = 0;
164 	struct btrfs_file_extent_item *item;
165 	struct btrfs_key file_key;
166 	BTRFS_PATH_AUTO_FREE(path);
167 	struct extent_buffer *leaf;
168 
169 	path = btrfs_alloc_path();
170 	if (!path)
171 		return -ENOMEM;
172 
173 	file_key.objectid = objectid;
174 	file_key.type = BTRFS_EXTENT_DATA_KEY;
175 	file_key.offset = pos;
176 
177 	ret = btrfs_insert_empty_item(trans, root, path, &file_key,
178 				      sizeof(*item));
179 	if (ret < 0)
180 		return ret;
181 	leaf = path->nodes[0];
182 	item = btrfs_item_ptr(leaf, path->slots[0],
183 			      struct btrfs_file_extent_item);
184 	btrfs_set_file_extent_disk_bytenr(leaf, item, 0);
185 	btrfs_set_file_extent_disk_num_bytes(leaf, item, 0);
186 	btrfs_set_file_extent_offset(leaf, item, 0);
187 	btrfs_set_file_extent_num_bytes(leaf, item, num_bytes);
188 	btrfs_set_file_extent_ram_bytes(leaf, item, num_bytes);
189 	btrfs_set_file_extent_generation(leaf, item, trans->transid);
190 	btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
191 	btrfs_set_file_extent_compression(leaf, item, 0);
192 	btrfs_set_file_extent_encryption(leaf, item, 0);
193 	btrfs_set_file_extent_other_encoding(leaf, item, 0);
194 
195 	return ret;
196 }
197 
198 static struct btrfs_csum_item *
btrfs_lookup_csum(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,u64 bytenr,int cow)199 btrfs_lookup_csum(struct btrfs_trans_handle *trans,
200 		  struct btrfs_root *root,
201 		  struct btrfs_path *path,
202 		  u64 bytenr, int cow)
203 {
204 	struct btrfs_fs_info *fs_info = root->fs_info;
205 	int ret;
206 	struct btrfs_key file_key;
207 	struct btrfs_key found_key;
208 	struct btrfs_csum_item *item;
209 	struct extent_buffer *leaf;
210 	u64 csum_offset = 0;
211 	const u32 csum_size = fs_info->csum_size;
212 	int csums_in_item;
213 
214 	file_key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
215 	file_key.type = BTRFS_EXTENT_CSUM_KEY;
216 	file_key.offset = bytenr;
217 	ret = btrfs_search_slot(trans, root, &file_key, path, 0, cow);
218 	if (ret < 0)
219 		goto fail;
220 	leaf = path->nodes[0];
221 	if (ret > 0) {
222 		ret = 1;
223 		if (path->slots[0] == 0)
224 			goto fail;
225 		path->slots[0]--;
226 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
227 		if (found_key.type != BTRFS_EXTENT_CSUM_KEY)
228 			goto fail;
229 
230 		csum_offset = (bytenr - found_key.offset) >>
231 				fs_info->sectorsize_bits;
232 		csums_in_item = btrfs_item_size(leaf, path->slots[0]);
233 		csums_in_item /= csum_size;
234 
235 		if (csum_offset == csums_in_item) {
236 			ret = -EFBIG;
237 			goto fail;
238 		} else if (csum_offset > csums_in_item) {
239 			goto fail;
240 		}
241 	}
242 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_csum_item);
243 	item = (struct btrfs_csum_item *)((unsigned char *)item +
244 					  csum_offset * csum_size);
245 	return item;
246 fail:
247 	if (ret > 0)
248 		ret = -ENOENT;
249 	return ERR_PTR(ret);
250 }
251 
btrfs_lookup_file_extent(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,u64 objectid,u64 offset,int mod)252 int btrfs_lookup_file_extent(struct btrfs_trans_handle *trans,
253 			     struct btrfs_root *root,
254 			     struct btrfs_path *path, u64 objectid,
255 			     u64 offset, int mod)
256 {
257 	struct btrfs_key file_key;
258 	int ins_len = mod < 0 ? -1 : 0;
259 	int cow = mod != 0;
260 
261 	file_key.objectid = objectid;
262 	file_key.type = BTRFS_EXTENT_DATA_KEY;
263 	file_key.offset = offset;
264 
265 	return btrfs_search_slot(trans, root, &file_key, path, ins_len, cow);
266 }
267 
268 /*
269  * Find checksums for logical bytenr range [disk_bytenr, disk_bytenr + len) and
270  * store the result to @dst.
271  *
272  * Return >0 for the number of sectors we found.
273  * Return 0 for the range [disk_bytenr, disk_bytenr + sectorsize) has no csum
274  * for it. Caller may want to try next sector until one range is hit.
275  * Return <0 for fatal error.
276  */
search_csum_tree(struct btrfs_fs_info * fs_info,struct btrfs_path * path,u64 disk_bytenr,u64 len,u8 * dst)277 static int search_csum_tree(struct btrfs_fs_info *fs_info,
278 			    struct btrfs_path *path, u64 disk_bytenr,
279 			    u64 len, u8 *dst)
280 {
281 	struct btrfs_root *csum_root;
282 	struct btrfs_csum_item *item = NULL;
283 	struct btrfs_key key;
284 	const u32 sectorsize = fs_info->sectorsize;
285 	const u32 csum_size = fs_info->csum_size;
286 	u32 itemsize;
287 	int ret;
288 	u64 csum_start;
289 	u64 csum_len;
290 
291 	ASSERT(IS_ALIGNED(disk_bytenr, sectorsize) &&
292 	       IS_ALIGNED(len, sectorsize));
293 
294 	/* Check if the current csum item covers disk_bytenr */
295 	if (path->nodes[0]) {
296 		item = btrfs_item_ptr(path->nodes[0], path->slots[0],
297 				      struct btrfs_csum_item);
298 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
299 		itemsize = btrfs_item_size(path->nodes[0], path->slots[0]);
300 
301 		csum_start = key.offset;
302 		csum_len = (itemsize / csum_size) * sectorsize;
303 
304 		if (in_range(disk_bytenr, csum_start, csum_len))
305 			goto found;
306 	}
307 
308 	/* Current item doesn't contain the desired range, search again */
309 	btrfs_release_path(path);
310 	csum_root = btrfs_csum_root(fs_info, disk_bytenr);
311 	if (unlikely(!csum_root)) {
312 		btrfs_err(fs_info,
313 			  "missing csum root for extent at bytenr %llu",
314 			  disk_bytenr);
315 		return -EUCLEAN;
316 	}
317 
318 	item = btrfs_lookup_csum(NULL, csum_root, path, disk_bytenr, 0);
319 	if (IS_ERR(item)) {
320 		ret = PTR_ERR(item);
321 		goto out;
322 	}
323 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
324 	itemsize = btrfs_item_size(path->nodes[0], path->slots[0]);
325 
326 	csum_start = key.offset;
327 	csum_len = (itemsize / csum_size) * sectorsize;
328 	ASSERT(in_range(disk_bytenr, csum_start, csum_len),
329 	       "disk_bytenr=%llu csum_start=%llu csum_len=%llu",
330 	       disk_bytenr, csum_start, csum_len);
331 
332 found:
333 	ret = (min(csum_start + csum_len, disk_bytenr + len) -
334 		   disk_bytenr) >> fs_info->sectorsize_bits;
335 	read_extent_buffer(path->nodes[0], dst, (unsigned long)item,
336 			ret * csum_size);
337 out:
338 	if (ret == -ENOENT || ret == -EFBIG)
339 		ret = 0;
340 	return ret;
341 }
342 
343 /*
344  * Lookup the checksum for the read bio in csum tree.
345  *
346  * Return: BLK_STS_RESOURCE if allocating memory fails, BLK_STS_OK otherwise.
347  */
btrfs_lookup_bio_sums(struct btrfs_bio * bbio)348 int btrfs_lookup_bio_sums(struct btrfs_bio *bbio)
349 {
350 	struct btrfs_inode *inode = bbio->inode;
351 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
352 	struct bio *bio = &bbio->bio;
353 	BTRFS_PATH_AUTO_FREE(path);
354 	const u32 sectorsize = fs_info->sectorsize;
355 	const u32 csum_size = fs_info->csum_size;
356 	u32 orig_len = bio->bi_iter.bi_size;
357 	u64 orig_disk_bytenr = bio->bi_iter.bi_sector << SECTOR_SHIFT;
358 	const unsigned int nblocks = orig_len >> fs_info->sectorsize_bits;
359 	int ret = 0;
360 	u32 bio_offset = 0;
361 	bool using_commit_root = false;
362 
363 	if ((inode->flags & BTRFS_INODE_NODATASUM) ||
364 	    test_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state))
365 		return 0;
366 
367 	/*
368 	 * This function is only called for read bio.
369 	 *
370 	 * This means two things:
371 	 * - All our csums should only be in csum tree
372 	 *   No ordered extents csums, as ordered extents are only for write
373 	 *   path.
374 	 * - No need to bother any other info from bvec
375 	 *   Since we're looking up csums, the only important info is the
376 	 *   disk_bytenr and the length, which can be extracted from bi_iter
377 	 *   directly.
378 	 */
379 	ASSERT(bio_op(bio) == REQ_OP_READ);
380 	path = btrfs_alloc_path();
381 	if (!path)
382 		return -ENOMEM;
383 
384 	if (nblocks * csum_size > BTRFS_BIO_INLINE_CSUM_SIZE) {
385 		bbio->csum = kvcalloc(nblocks, csum_size, GFP_NOFS);
386 		if (!bbio->csum)
387 			return -ENOMEM;
388 	} else {
389 		bbio->csum = bbio->csum_inline;
390 	}
391 
392 	/*
393 	 * If requested number of sectors is larger than one leaf can contain,
394 	 * kick the readahead for csum tree.
395 	 */
396 	if (nblocks > fs_info->csums_per_leaf)
397 		path->reada = READA_FORWARD;
398 
399 	/*
400 	 * the free space stuff is only read when it hasn't been
401 	 * updated in the current transaction.  So, we can safely
402 	 * read from the commit root and sidestep a nasty deadlock
403 	 * between reading the free space cache and updating the csum tree.
404 	 */
405 	if (btrfs_is_free_space_inode(inode)) {
406 		path->search_commit_root = true;
407 		path->skip_locking = true;
408 	}
409 
410 	/*
411 	 * If we are searching for a csum of an extent from a past
412 	 * transaction, we can search in the commit root and reduce
413 	 * lock contention on the csum tree extent buffers.
414 	 *
415 	 * This is important because that lock is an rwsem which gets
416 	 * pretty heavy write load under memory pressure and sustained
417 	 * csum overwrites, unlike the commit_root_sem. (Memory pressure
418 	 * makes us writeback the nodes multiple times per transaction,
419 	 * which makes us cow them each time, taking the write lock.)
420 	 *
421 	 * Due to how rwsem is implemented, there is a possible
422 	 * priority inversion where the readers holding the lock don't
423 	 * get scheduled (say they're in a cgroup stuck in heavy reclaim)
424 	 * which then blocks writers, including transaction commit. By
425 	 * using a semaphore with fewer writers (only a commit switching
426 	 * the roots), we make this issue less likely.
427 	 *
428 	 * Note that we don't rely on btrfs_search_slot to lock the
429 	 * commit root csum. We call search_slot multiple times, which would
430 	 * create a potential race where a commit comes in between searches
431 	 * while we are not holding the commit_root_sem, and we get csums
432 	 * from across transactions.
433 	 */
434 	if (bbio->csum_search_commit_root) {
435 		using_commit_root = true;
436 		path->search_commit_root = true;
437 		path->skip_locking = true;
438 		down_read(&fs_info->commit_root_sem);
439 	}
440 
441 	while (bio_offset < orig_len) {
442 		int count;
443 		u64 cur_disk_bytenr = orig_disk_bytenr + bio_offset;
444 		u8 *csum_dst = bbio->csum +
445 			(bio_offset >> fs_info->sectorsize_bits) * csum_size;
446 
447 		count = search_csum_tree(fs_info, path, cur_disk_bytenr,
448 					 orig_len - bio_offset, csum_dst);
449 		if (count < 0) {
450 			ret = count;
451 			if (bbio->csum != bbio->csum_inline)
452 				kvfree(bbio->csum);
453 			bbio->csum = NULL;
454 			break;
455 		}
456 
457 		/*
458 		 * We didn't find a csum for this range.  We need to make sure
459 		 * we complain loudly about this, because we are not NODATASUM.
460 		 *
461 		 * However for the DATA_RELOC inode we could potentially be
462 		 * relocating data extents for a NODATASUM inode, so the inode
463 		 * itself won't be marked with NODATASUM, but the extent we're
464 		 * copying is in fact NODATASUM.  If we don't find a csum we
465 		 * assume this is the case.
466 		 */
467 		if (count == 0) {
468 			/*
469 			 * If an extent is relocated in the current transaction
470 			 * then relocation writes a new csum without updating
471 			 * the extent map generation. Until the next commit, we
472 			 * will see a hole in that case, so we need to fallback
473 			 * to searching the transaction csum root.
474 			 *
475 			 * Note that a commit root lookup of a referenced extent can
476 			 * only miss, not return a stale csum. A freed extent's csum
477 			 * is deleted in the same transaction and its bytenr is not
478 			 * reusable until that transaction has committed and the
479 			 * extent is unpinned.
480 			 */
481 			if (using_commit_root) {
482 				up_read(&fs_info->commit_root_sem);
483 				using_commit_root = false;
484 				path->search_commit_root = false;
485 				path->skip_locking = false;
486 				btrfs_release_path(path);
487 				continue;
488 			}
489 
490 			memset(csum_dst, 0, csum_size);
491 			count = 1;
492 
493 			if (btrfs_is_data_reloc_root(inode->root)) {
494 				u64 file_offset = bbio->file_offset + bio_offset;
495 
496 				btrfs_set_extent_bit(&inode->io_tree, file_offset,
497 						     file_offset + sectorsize - 1,
498 						     EXTENT_NODATASUM, NULL);
499 			} else {
500 				btrfs_warn_rl(fs_info,
501 			"csum hole found for disk bytenr range [%llu, %llu)",
502 				cur_disk_bytenr, cur_disk_bytenr + sectorsize);
503 			}
504 		}
505 		bio_offset += count * sectorsize;
506 	}
507 
508 	if (using_commit_root)
509 		up_read(&fs_info->commit_root_sem);
510 	return ret;
511 }
512 
513 /*
514  * Search for checksums for a given logical range.
515  *
516  * @root:		The root where to look for checksums.
517  * @start:		Logical address of target checksum range.
518  * @end:		End offset (inclusive) of the target checksum range.
519  * @list:		List for adding each checksum that was found.
520  *			Can be NULL in case the caller only wants to check if
521  *			there any checksums for the range.
522  * @nowait:		Indicate if the search must be non-blocking or not.
523  *
524  * Return < 0 on error, 0 if no checksums were found, or 1 if checksums were
525  * found.
526  */
btrfs_lookup_csums_list(struct btrfs_root * root,u64 start,u64 end,struct list_head * list,bool nowait)527 int btrfs_lookup_csums_list(struct btrfs_root *root, u64 start, u64 end,
528 			    struct list_head *list, bool nowait)
529 {
530 	struct btrfs_fs_info *fs_info = root->fs_info;
531 	struct btrfs_key key;
532 	struct btrfs_path *path;
533 	struct extent_buffer *leaf;
534 	struct btrfs_ordered_sum *sums;
535 	struct btrfs_csum_item *item;
536 	int ret;
537 	bool found_csums = false;
538 
539 	ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
540 	       IS_ALIGNED(end + 1, fs_info->sectorsize));
541 
542 	path = btrfs_alloc_path();
543 	if (!path)
544 		return -ENOMEM;
545 
546 	path->nowait = nowait;
547 
548 	key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
549 	key.type = BTRFS_EXTENT_CSUM_KEY;
550 	key.offset = start;
551 
552 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
553 	if (ret < 0)
554 		goto out;
555 	if (ret > 0 && path->slots[0] > 0) {
556 		leaf = path->nodes[0];
557 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
558 
559 		/*
560 		 * There are two cases we can hit here for the previous csum
561 		 * item:
562 		 *
563 		 *		|<- search range ->|
564 		 *	|<- csum item ->|
565 		 *
566 		 * Or
567 		 *				|<- search range ->|
568 		 *	|<- csum item ->|
569 		 *
570 		 * Check if the previous csum item covers the leading part of
571 		 * the search range.  If so we have to start from previous csum
572 		 * item.
573 		 */
574 		if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
575 		    key.type == BTRFS_EXTENT_CSUM_KEY) {
576 			if (bytes_to_csum_size(fs_info, start - key.offset) <
577 			    btrfs_item_size(leaf, path->slots[0] - 1))
578 				path->slots[0]--;
579 		}
580 	}
581 
582 	while (start <= end) {
583 		u64 csum_end;
584 
585 		leaf = path->nodes[0];
586 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
587 			ret = btrfs_next_leaf(root, path);
588 			if (ret < 0)
589 				goto out;
590 			if (ret > 0)
591 				break;
592 			leaf = path->nodes[0];
593 		}
594 
595 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
596 		if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
597 		    key.type != BTRFS_EXTENT_CSUM_KEY ||
598 		    key.offset > end)
599 			break;
600 
601 		if (key.offset > start)
602 			start = key.offset;
603 
604 		csum_end = key.offset + csum_size_to_bytes(fs_info,
605 					btrfs_item_size(leaf, path->slots[0]));
606 		if (csum_end <= start) {
607 			path->slots[0]++;
608 			continue;
609 		}
610 
611 		found_csums = true;
612 		if (!list)
613 			goto out;
614 
615 		csum_end = min(csum_end, end + 1);
616 		item = btrfs_item_ptr(path->nodes[0], path->slots[0],
617 				      struct btrfs_csum_item);
618 		while (start < csum_end) {
619 			unsigned long offset;
620 			size_t size;
621 
622 			size = min_t(size_t, csum_end - start,
623 				     max_ordered_sum_bytes(fs_info));
624 			sums = kzalloc(btrfs_ordered_sum_size(fs_info, size),
625 				       GFP_NOFS);
626 			if (!sums) {
627 				ret = -ENOMEM;
628 				goto out;
629 			}
630 
631 			sums->logical = start;
632 			sums->len = size;
633 
634 			offset = bytes_to_csum_size(fs_info, start - key.offset);
635 
636 			read_extent_buffer(path->nodes[0],
637 					   sums->sums,
638 					   ((unsigned long)item) + offset,
639 					   bytes_to_csum_size(fs_info, size));
640 
641 			start += size;
642 			list_add_tail(&sums->list, list);
643 		}
644 		path->slots[0]++;
645 	}
646 out:
647 	btrfs_free_path(path);
648 	if (ret < 0) {
649 		if (list) {
650 			struct btrfs_ordered_sum *tmp_sums;
651 
652 			list_for_each_entry_safe(sums, tmp_sums, list, list)
653 				kfree(sums);
654 		}
655 
656 		return ret;
657 	}
658 
659 	return found_csums ? 1 : 0;
660 }
661 
662 /*
663  * Do the same work as btrfs_lookup_csums_list(), the difference is in how
664  * we return the result.
665  *
666  * This version will set the corresponding bits in @csum_bitmap to represent
667  * that there is a csum found.
668  * Each bit represents a sector. Thus caller should ensure @csum_buf passed
669  * in is large enough to contain all csums.
670  */
btrfs_lookup_csums_bitmap(struct btrfs_root * root,struct btrfs_path * path,u64 start,u64 end,u8 * csum_buf,unsigned long * csum_bitmap)671 int btrfs_lookup_csums_bitmap(struct btrfs_root *root, struct btrfs_path *path,
672 			      u64 start, u64 end, u8 *csum_buf,
673 			      unsigned long *csum_bitmap)
674 {
675 	struct btrfs_fs_info *fs_info = root->fs_info;
676 	struct btrfs_key key;
677 	struct extent_buffer *leaf;
678 	struct btrfs_csum_item *item;
679 	const u64 orig_start = start;
680 	bool free_path = false;
681 	int ret;
682 
683 	ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
684 	       IS_ALIGNED(end + 1, fs_info->sectorsize));
685 
686 	if (!path) {
687 		path = btrfs_alloc_path();
688 		if (!path)
689 			return -ENOMEM;
690 		free_path = true;
691 	}
692 
693 	/* Check if we can reuse the previous path. */
694 	if (path->nodes[0]) {
695 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
696 
697 		if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
698 		    key.type == BTRFS_EXTENT_CSUM_KEY &&
699 		    key.offset <= start)
700 			goto search_forward;
701 		btrfs_release_path(path);
702 	}
703 
704 	key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
705 	key.type = BTRFS_EXTENT_CSUM_KEY;
706 	key.offset = start;
707 
708 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
709 	if (ret < 0)
710 		goto fail;
711 	if (ret > 0 && path->slots[0] > 0) {
712 		leaf = path->nodes[0];
713 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
714 
715 		/*
716 		 * There are two cases we can hit here for the previous csum
717 		 * item:
718 		 *
719 		 *		|<- search range ->|
720 		 *	|<- csum item ->|
721 		 *
722 		 * Or
723 		 *				|<- search range ->|
724 		 *	|<- csum item ->|
725 		 *
726 		 * Check if the previous csum item covers the leading part of
727 		 * the search range.  If so we have to start from previous csum
728 		 * item.
729 		 */
730 		if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
731 		    key.type == BTRFS_EXTENT_CSUM_KEY) {
732 			if (bytes_to_csum_size(fs_info, start - key.offset) <
733 			    btrfs_item_size(leaf, path->slots[0] - 1))
734 				path->slots[0]--;
735 		}
736 	}
737 
738 search_forward:
739 	while (start <= end) {
740 		u64 csum_end;
741 
742 		leaf = path->nodes[0];
743 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
744 			ret = btrfs_next_leaf(root, path);
745 			if (ret < 0)
746 				goto fail;
747 			if (ret > 0)
748 				break;
749 			leaf = path->nodes[0];
750 		}
751 
752 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
753 		if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
754 		    key.type != BTRFS_EXTENT_CSUM_KEY ||
755 		    key.offset > end)
756 			break;
757 
758 		if (key.offset > start)
759 			start = key.offset;
760 
761 		csum_end = key.offset + csum_size_to_bytes(fs_info,
762 					btrfs_item_size(leaf, path->slots[0]));
763 		if (csum_end <= start) {
764 			path->slots[0]++;
765 			continue;
766 		}
767 
768 		csum_end = min(csum_end, end + 1);
769 		item = btrfs_item_ptr(path->nodes[0], path->slots[0],
770 				      struct btrfs_csum_item);
771 		while (start < csum_end) {
772 			unsigned long offset;
773 			size_t size;
774 			u8 *csum_dest = csum_buf + bytes_to_csum_size(fs_info,
775 						start - orig_start);
776 
777 			size = min_t(size_t, csum_end - start, end + 1 - start);
778 
779 			offset = bytes_to_csum_size(fs_info, start - key.offset);
780 
781 			read_extent_buffer(path->nodes[0], csum_dest,
782 					   ((unsigned long)item) + offset,
783 					   bytes_to_csum_size(fs_info, size));
784 
785 			bitmap_set(csum_bitmap,
786 				(start - orig_start) >> fs_info->sectorsize_bits,
787 				size >> fs_info->sectorsize_bits);
788 
789 			start += size;
790 		}
791 		path->slots[0]++;
792 	}
793 	ret = 0;
794 fail:
795 	if (free_path)
796 		btrfs_free_path(path);
797 	return ret;
798 }
799 
csum_one_bio(struct btrfs_bio * bbio,struct bvec_iter * src)800 static void csum_one_bio(struct btrfs_bio *bbio, struct bvec_iter *src)
801 {
802 	struct btrfs_inode *inode = bbio->inode;
803 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
804 	struct bio *bio = &bbio->bio;
805 	struct btrfs_ordered_sum *sums = bbio->sums;
806 	struct bvec_iter iter = *src;
807 	phys_addr_t paddr;
808 	const u32 blocksize = fs_info->sectorsize;
809 	const u32 step = min(blocksize, PAGE_SIZE);
810 	const u32 nr_steps = blocksize / step;
811 	phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE];
812 	u32 offset = 0;
813 	int index = 0;
814 
815 	btrfs_bio_for_each_block(paddr, bio, &iter, step) {
816 		paddrs[(offset / step) % nr_steps] = paddr;
817 		offset += step;
818 
819 		if (IS_ALIGNED(offset, blocksize)) {
820 			btrfs_calculate_block_csum_pages(fs_info, paddrs, sums->sums + index);
821 			index += fs_info->csum_size;
822 		}
823 	}
824 }
825 
csum_one_bio_work(struct work_struct * work)826 static void csum_one_bio_work(struct work_struct *work)
827 {
828 	struct btrfs_bio *bbio = container_of(work, struct btrfs_bio, csum_work);
829 
830 	ASSERT(btrfs_op(&bbio->bio) == BTRFS_MAP_WRITE);
831 	ASSERT(bbio->async_csum == true);
832 	csum_one_bio(bbio, &bbio->csum_saved_iter);
833 	complete(&bbio->csum_done);
834 }
835 
836 /*
837  * Calculate checksums of the data contained inside a bio.
838  */
btrfs_csum_one_bio(struct btrfs_bio * bbio,bool async)839 int btrfs_csum_one_bio(struct btrfs_bio *bbio, bool async)
840 {
841 	struct btrfs_ordered_extent *ordered = bbio->ordered;
842 	struct btrfs_inode *inode = bbio->inode;
843 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
844 	struct bio *bio = &bbio->bio;
845 	struct btrfs_ordered_sum *sums;
846 	unsigned nofs_flag;
847 
848 	nofs_flag = memalloc_nofs_save();
849 	sums = kvzalloc(btrfs_ordered_sum_size(fs_info, bio->bi_iter.bi_size),
850 		       GFP_KERNEL);
851 	memalloc_nofs_restore(nofs_flag);
852 
853 	if (!sums)
854 		return -ENOMEM;
855 
856 	sums->logical = bbio->orig_logical;
857 	sums->len = bio->bi_iter.bi_size;
858 	INIT_LIST_HEAD(&sums->list);
859 	bbio->sums = sums;
860 	btrfs_add_ordered_sum(ordered, sums);
861 
862 	if (!async) {
863 		csum_one_bio(bbio, &bbio->bio.bi_iter);
864 		return 0;
865 	}
866 	init_completion(&bbio->csum_done);
867 	bbio->async_csum = true;
868 	bbio->csum_saved_iter = bbio->bio.bi_iter;
869 	INIT_WORK(&bbio->csum_work, csum_one_bio_work);
870 	schedule_work(&bbio->csum_work);
871 	return 0;
872 }
873 
874 /*
875  * Nodatasum I/O on zoned file systems still requires an btrfs_ordered_sum to
876  * record the updated logical address on Zone Append completion.
877  * Allocate just the structure with an empty sums array here for that case.
878  */
btrfs_alloc_dummy_sum(struct btrfs_bio * bbio)879 int btrfs_alloc_dummy_sum(struct btrfs_bio *bbio)
880 {
881 	bbio->sums = kmalloc_obj(*bbio->sums, GFP_NOFS);
882 	if (!bbio->sums)
883 		return -ENOMEM;
884 	bbio->sums->len = bbio->bio.bi_iter.bi_size;
885 	bbio->sums->logical = bbio->bio.bi_iter.bi_sector << SECTOR_SHIFT;
886 	btrfs_add_ordered_sum(bbio->ordered, bbio->sums);
887 	return 0;
888 }
889 
890 /*
891  * Remove one checksum overlapping a range.
892  *
893  * This expects the key to describe the csum pointed to by the path, and it
894  * expects the csum to overlap the range [bytenr, len]
895  *
896  * The csum should not be entirely contained in the range and the range should
897  * not be entirely contained in the csum.
898  *
899  * This calls btrfs_truncate_item with the correct args based on the overlap,
900  * and fixes up the key as required.
901  */
truncate_one_csum(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_key * key,u64 bytenr,u64 len)902 static noinline void truncate_one_csum(struct btrfs_trans_handle *trans,
903 				       struct btrfs_path *path,
904 				       struct btrfs_key *key,
905 				       u64 bytenr, u64 len)
906 {
907 	struct btrfs_fs_info *fs_info = trans->fs_info;
908 	struct extent_buffer *leaf;
909 	const u32 csum_size = fs_info->csum_size;
910 	u64 csum_end;
911 	u64 end_byte = bytenr + len;
912 	u32 blocksize_bits = fs_info->sectorsize_bits;
913 
914 	leaf = path->nodes[0];
915 	csum_end = btrfs_item_size(leaf, path->slots[0]) / csum_size;
916 	csum_end <<= blocksize_bits;
917 	csum_end += key->offset;
918 
919 	if (key->offset < bytenr && csum_end <= end_byte) {
920 		/*
921 		 *         [ bytenr - len ]
922 		 *         [   ]
923 		 *   [csum     ]
924 		 *   A simple truncate off the end of the item
925 		 */
926 		u32 new_size = (bytenr - key->offset) >> blocksize_bits;
927 		new_size *= csum_size;
928 		btrfs_truncate_item(trans, path, new_size, 1);
929 	} else if (key->offset >= bytenr && csum_end > end_byte &&
930 		   end_byte > key->offset) {
931 		/*
932 		 *         [ bytenr - len ]
933 		 *                 [ ]
934 		 *                 [csum     ]
935 		 * we need to truncate from the beginning of the csum
936 		 */
937 		u32 new_size = (csum_end - end_byte) >> blocksize_bits;
938 		new_size *= csum_size;
939 
940 		btrfs_truncate_item(trans, path, new_size, 0);
941 
942 		key->offset = end_byte;
943 		btrfs_set_item_key_safe(trans, path, key);
944 	} else {
945 		BUG();
946 	}
947 }
948 
949 /*
950  * Delete the csum items from the csum tree for a given range of bytes.
951  */
btrfs_del_csums(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 bytenr,u64 len)952 int btrfs_del_csums(struct btrfs_trans_handle *trans,
953 		    struct btrfs_root *root, u64 bytenr, u64 len)
954 {
955 	struct btrfs_fs_info *fs_info = trans->fs_info;
956 	BTRFS_PATH_AUTO_FREE(path);
957 	struct btrfs_key key;
958 	u64 end_byte = bytenr + len;
959 	u64 csum_end;
960 	struct extent_buffer *leaf;
961 	int ret = 0;
962 	const u32 csum_size = fs_info->csum_size;
963 	u32 blocksize_bits = fs_info->sectorsize_bits;
964 
965 	ASSERT(btrfs_root_id(root) == BTRFS_CSUM_TREE_OBJECTID ||
966 	       btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
967 
968 	path = btrfs_alloc_path();
969 	if (!path)
970 		return -ENOMEM;
971 
972 	while (1) {
973 		key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
974 		key.type = BTRFS_EXTENT_CSUM_KEY;
975 		key.offset = end_byte - 1;
976 
977 		ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
978 		if (ret > 0) {
979 			ret = 0;
980 			if (path->slots[0] == 0)
981 				break;
982 			path->slots[0]--;
983 		} else if (ret < 0) {
984 			break;
985 		}
986 
987 		leaf = path->nodes[0];
988 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
989 
990 		if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
991 		    key.type != BTRFS_EXTENT_CSUM_KEY) {
992 			break;
993 		}
994 
995 		if (key.offset >= end_byte)
996 			break;
997 
998 		csum_end = btrfs_item_size(leaf, path->slots[0]) / csum_size;
999 		csum_end <<= blocksize_bits;
1000 		csum_end += key.offset;
1001 
1002 		/* this csum ends before we start, we're done */
1003 		if (csum_end <= bytenr)
1004 			break;
1005 
1006 		/* delete the entire item, it is inside our range */
1007 		if (key.offset >= bytenr && csum_end <= end_byte) {
1008 			int del_nr = 1;
1009 
1010 			/*
1011 			 * Check how many csum items preceding this one in this
1012 			 * leaf correspond to our range and then delete them all
1013 			 * at once.
1014 			 */
1015 			if (key.offset > bytenr && path->slots[0] > 0) {
1016 				int slot = path->slots[0] - 1;
1017 
1018 				while (slot >= 0) {
1019 					struct btrfs_key pk;
1020 
1021 					btrfs_item_key_to_cpu(leaf, &pk, slot);
1022 					if (pk.offset < bytenr ||
1023 					    pk.type != BTRFS_EXTENT_CSUM_KEY ||
1024 					    pk.objectid !=
1025 					    BTRFS_EXTENT_CSUM_OBJECTID)
1026 						break;
1027 					path->slots[0] = slot;
1028 					del_nr++;
1029 					key.offset = pk.offset;
1030 					slot--;
1031 				}
1032 			}
1033 			ret = btrfs_del_items(trans, root, path,
1034 					      path->slots[0], del_nr);
1035 			if (ret)
1036 				break;
1037 			if (key.offset == bytenr)
1038 				break;
1039 		} else if (key.offset < bytenr && csum_end > end_byte) {
1040 			unsigned long offset;
1041 			unsigned long shift_len;
1042 			unsigned long item_offset;
1043 			/*
1044 			 *        [ bytenr - len ]
1045 			 *     [csum                ]
1046 			 *
1047 			 * Our bytes are in the middle of the csum,
1048 			 * we need to split this item and insert a new one.
1049 			 *
1050 			 * But we can't drop the path because the
1051 			 * csum could change, get removed, extended etc.
1052 			 *
1053 			 * The trick here is the max size of a csum item leaves
1054 			 * enough room in the tree block for a single
1055 			 * item header.  So, we split the item in place,
1056 			 * adding a new header pointing to the existing
1057 			 * bytes.  Then we loop around again and we have
1058 			 * a nicely formed csum item that we can neatly
1059 			 * truncate.
1060 			 */
1061 			offset = (bytenr - key.offset) >> blocksize_bits;
1062 			offset *= csum_size;
1063 
1064 			shift_len = (len >> blocksize_bits) * csum_size;
1065 
1066 			item_offset = btrfs_item_ptr_offset(leaf,
1067 							    path->slots[0]);
1068 
1069 			memzero_extent_buffer(leaf, item_offset + offset,
1070 					     shift_len);
1071 			key.offset = bytenr;
1072 
1073 			/*
1074 			 * btrfs_split_item returns -EAGAIN when the
1075 			 * item changed size or key
1076 			 */
1077 			ret = btrfs_split_item(trans, root, path, &key, offset);
1078 			if (unlikely(ret && ret != -EAGAIN)) {
1079 				btrfs_abort_transaction(trans, ret);
1080 				break;
1081 			}
1082 			ret = 0;
1083 
1084 			key.offset = end_byte - 1;
1085 		} else {
1086 			truncate_one_csum(trans, path, &key, bytenr, len);
1087 			if (key.offset < bytenr)
1088 				break;
1089 		}
1090 		btrfs_release_path(path);
1091 	}
1092 	return ret;
1093 }
1094 
find_next_csum_offset(struct btrfs_root * root,struct btrfs_path * path,u64 * next_offset)1095 static int find_next_csum_offset(struct btrfs_root *root,
1096 				 struct btrfs_path *path,
1097 				 u64 *next_offset)
1098 {
1099 	const u32 nritems = btrfs_header_nritems(path->nodes[0]);
1100 	struct btrfs_key found_key;
1101 	int slot = path->slots[0] + 1;
1102 	int ret;
1103 
1104 	if (nritems == 0 || slot >= nritems) {
1105 		ret = btrfs_next_leaf(root, path);
1106 		if (ret < 0) {
1107 			return ret;
1108 		} else if (ret > 0) {
1109 			*next_offset = (u64)-1;
1110 			return 0;
1111 		}
1112 		slot = path->slots[0];
1113 	}
1114 
1115 	btrfs_item_key_to_cpu(path->nodes[0], &found_key, slot);
1116 
1117 	if (found_key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1118 	    found_key.type != BTRFS_EXTENT_CSUM_KEY)
1119 		*next_offset = (u64)-1;
1120 	else
1121 		*next_offset = found_key.offset;
1122 
1123 	return 0;
1124 }
1125 
btrfs_insert_data_csums(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_ordered_sum * sums)1126 int btrfs_insert_data_csums(struct btrfs_trans_handle *trans,
1127 			    struct btrfs_root *root,
1128 			    struct btrfs_ordered_sum *sums)
1129 {
1130 	struct btrfs_fs_info *fs_info = root->fs_info;
1131 	struct btrfs_key file_key;
1132 	struct btrfs_key found_key;
1133 	BTRFS_PATH_AUTO_FREE(path);
1134 	struct btrfs_csum_item *item;
1135 	struct btrfs_csum_item *item_end;
1136 	struct extent_buffer *leaf = NULL;
1137 	u64 next_offset;
1138 	u64 total_bytes = 0;
1139 	u64 csum_offset;
1140 	u64 bytenr;
1141 	u32 ins_size;
1142 	int index = 0;
1143 	int found_next;
1144 	int ret;
1145 	const u32 csum_size = fs_info->csum_size;
1146 
1147 	path = btrfs_alloc_path();
1148 	if (!path)
1149 		return -ENOMEM;
1150 again:
1151 	next_offset = (u64)-1;
1152 	found_next = 0;
1153 	bytenr = sums->logical + total_bytes;
1154 	file_key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1155 	file_key.type = BTRFS_EXTENT_CSUM_KEY;
1156 	file_key.offset = bytenr;
1157 
1158 	item = btrfs_lookup_csum(trans, root, path, bytenr, 1);
1159 	if (!IS_ERR(item)) {
1160 		ret = 0;
1161 		leaf = path->nodes[0];
1162 		item_end = btrfs_item_ptr(leaf, path->slots[0],
1163 					  struct btrfs_csum_item);
1164 		item_end = (struct btrfs_csum_item *)((char *)item_end +
1165 			   btrfs_item_size(leaf, path->slots[0]));
1166 		goto found;
1167 	}
1168 	ret = PTR_ERR(item);
1169 	if (ret != -EFBIG && ret != -ENOENT)
1170 		return ret;
1171 
1172 	if (ret == -EFBIG) {
1173 		u32 item_size;
1174 		/* we found one, but it isn't big enough yet */
1175 		leaf = path->nodes[0];
1176 		item_size = btrfs_item_size(leaf, path->slots[0]);
1177 		if ((item_size / csum_size) >=
1178 		    MAX_CSUM_ITEMS(fs_info, csum_size)) {
1179 			/* already at max size, make a new one */
1180 			goto insert;
1181 		}
1182 	} else {
1183 		/* We didn't find a csum item, insert one. */
1184 		ret = find_next_csum_offset(root, path, &next_offset);
1185 		if (ret < 0)
1186 			return ret;
1187 		found_next = 1;
1188 		goto insert;
1189 	}
1190 
1191 	/*
1192 	 * At this point, we know the tree has a checksum item that ends at an
1193 	 * offset matching the start of the checksum range we want to insert.
1194 	 * We try to extend that item as much as possible and then add as many
1195 	 * checksums to it as they fit.
1196 	 *
1197 	 * First check if the leaf has enough free space for at least one
1198 	 * checksum. If it has go directly to the item extension code, otherwise
1199 	 * release the path and do a search for insertion before the extension.
1200 	 */
1201 	if (btrfs_leaf_free_space(leaf) >= csum_size) {
1202 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1203 		csum_offset = (bytenr - found_key.offset) >>
1204 			fs_info->sectorsize_bits;
1205 		goto extend_csum;
1206 	}
1207 
1208 	btrfs_release_path(path);
1209 	path->search_for_extension = true;
1210 	ret = btrfs_search_slot(trans, root, &file_key, path,
1211 				csum_size, 1);
1212 	path->search_for_extension = false;
1213 	if (ret < 0)
1214 		return ret;
1215 
1216 	if (ret > 0) {
1217 		if (path->slots[0] == 0)
1218 			goto insert;
1219 		path->slots[0]--;
1220 	}
1221 
1222 	leaf = path->nodes[0];
1223 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1224 	csum_offset = (bytenr - found_key.offset) >> fs_info->sectorsize_bits;
1225 
1226 	if (found_key.type != BTRFS_EXTENT_CSUM_KEY ||
1227 	    found_key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1228 	    csum_offset >= MAX_CSUM_ITEMS(fs_info, csum_size)) {
1229 		goto insert;
1230 	}
1231 
1232 extend_csum:
1233 	if (csum_offset == btrfs_item_size(leaf, path->slots[0]) /
1234 	    csum_size) {
1235 		int extend_nr;
1236 		u64 tmp;
1237 		u32 diff;
1238 
1239 		tmp = sums->len - total_bytes;
1240 		tmp >>= fs_info->sectorsize_bits;
1241 		WARN_ON(tmp < 1);
1242 		extend_nr = max_t(int, 1, tmp);
1243 
1244 		/*
1245 		 * A log tree can already have checksum items with a subset of
1246 		 * the checksums we are trying to log. This can happen after
1247 		 * doing a sequence of partial writes into prealloc extents and
1248 		 * fsyncs in between, with a full fsync logging a larger subrange
1249 		 * of an extent for which a previous fast fsync logged a smaller
1250 		 * subrange. And this happens in particular due to merging file
1251 		 * extent items when we complete an ordered extent for a range
1252 		 * covered by a prealloc extent - this is done at
1253 		 * btrfs_mark_extent_written().
1254 		 *
1255 		 * So if we try to extend the previous checksum item, which has
1256 		 * a range that ends at the start of the range we want to insert,
1257 		 * make sure we don't extend beyond the start offset of the next
1258 		 * checksum item. If we are at the last item in the leaf, then
1259 		 * forget the optimization of extending and add a new checksum
1260 		 * item - it is not worth the complexity of releasing the path,
1261 		 * getting the first key for the next leaf, repeat the btree
1262 		 * search, etc, because log trees are temporary anyway and it
1263 		 * would only save a few bytes of leaf space.
1264 		 */
1265 		if (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID) {
1266 			if (path->slots[0] + 1 >=
1267 			    btrfs_header_nritems(path->nodes[0])) {
1268 				ret = find_next_csum_offset(root, path, &next_offset);
1269 				if (ret < 0)
1270 					return ret;
1271 				found_next = 1;
1272 				goto insert;
1273 			}
1274 
1275 			ret = find_next_csum_offset(root, path, &next_offset);
1276 			if (ret < 0)
1277 				return ret;
1278 
1279 			tmp = (next_offset - bytenr) >> fs_info->sectorsize_bits;
1280 			if (tmp <= INT_MAX)
1281 				extend_nr = min_t(int, extend_nr, tmp);
1282 		}
1283 
1284 		diff = (csum_offset + extend_nr) * csum_size;
1285 		diff = min(diff,
1286 			   MAX_CSUM_ITEMS(fs_info, csum_size) * csum_size);
1287 
1288 		diff = diff - btrfs_item_size(leaf, path->slots[0]);
1289 		diff = min_t(u32, btrfs_leaf_free_space(leaf), diff);
1290 		diff /= csum_size;
1291 		diff *= csum_size;
1292 
1293 		btrfs_extend_item(trans, path, diff);
1294 		ret = 0;
1295 		goto csum;
1296 	}
1297 
1298 insert:
1299 	btrfs_release_path(path);
1300 	csum_offset = 0;
1301 	if (found_next) {
1302 		u64 tmp;
1303 
1304 		tmp = sums->len - total_bytes;
1305 		tmp >>= fs_info->sectorsize_bits;
1306 		tmp = min(tmp, (next_offset - file_key.offset) >>
1307 					 fs_info->sectorsize_bits);
1308 
1309 		tmp = max_t(u64, 1, tmp);
1310 		tmp = min_t(u64, tmp, MAX_CSUM_ITEMS(fs_info, csum_size));
1311 		ins_size = csum_size * tmp;
1312 	} else {
1313 		ins_size = csum_size;
1314 	}
1315 	ret = btrfs_insert_empty_item(trans, root, path, &file_key,
1316 				      ins_size);
1317 	if (ret < 0)
1318 		return ret;
1319 	leaf = path->nodes[0];
1320 csum:
1321 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_csum_item);
1322 	item_end = (struct btrfs_csum_item *)((unsigned char *)item +
1323 				      btrfs_item_size(leaf, path->slots[0]));
1324 	item = (struct btrfs_csum_item *)((unsigned char *)item +
1325 					  csum_offset * csum_size);
1326 found:
1327 	ins_size = (u32)(sums->len - total_bytes) >> fs_info->sectorsize_bits;
1328 	ins_size *= csum_size;
1329 	ins_size = min_t(u32, (unsigned long)item_end - (unsigned long)item,
1330 			      ins_size);
1331 	write_extent_buffer(leaf, sums->sums + index, (unsigned long)item,
1332 			    ins_size);
1333 
1334 	index += ins_size;
1335 	ins_size /= csum_size;
1336 	total_bytes += (ins_size << fs_info->sectorsize_bits);
1337 
1338 	if (total_bytes < sums->len) {
1339 		btrfs_release_path(path);
1340 		cond_resched();
1341 		goto again;
1342 	}
1343 
1344 	return 0;
1345 }
1346 
btrfs_extent_item_to_extent_map(struct btrfs_inode * inode,const struct btrfs_path * path,const struct btrfs_file_extent_item * fi,struct extent_map * em)1347 void btrfs_extent_item_to_extent_map(struct btrfs_inode *inode,
1348 				     const struct btrfs_path *path,
1349 				     const struct btrfs_file_extent_item *fi,
1350 				     struct extent_map *em)
1351 {
1352 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1353 	struct btrfs_root *root = inode->root;
1354 	struct extent_buffer *leaf = path->nodes[0];
1355 	const int slot = path->slots[0];
1356 	struct btrfs_key key;
1357 	u64 extent_start;
1358 	u8 type = btrfs_file_extent_type(leaf, fi);
1359 	int compress_type = btrfs_file_extent_compression(leaf, fi);
1360 
1361 	btrfs_item_key_to_cpu(leaf, &key, slot);
1362 	extent_start = key.offset;
1363 	em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1364 	em->generation = btrfs_file_extent_generation(leaf, fi);
1365 	if (type == BTRFS_FILE_EXTENT_REG ||
1366 	    type == BTRFS_FILE_EXTENT_PREALLOC) {
1367 		const u64 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1368 
1369 		em->start = extent_start;
1370 		em->len = btrfs_file_extent_end(path) - extent_start;
1371 		if (disk_bytenr == 0) {
1372 			em->disk_bytenr = EXTENT_MAP_HOLE;
1373 			em->disk_num_bytes = 0;
1374 			em->offset = 0;
1375 			return;
1376 		}
1377 		em->disk_bytenr = disk_bytenr;
1378 		em->disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1379 		em->offset = btrfs_file_extent_offset(leaf, fi);
1380 		if (compress_type != BTRFS_COMPRESS_NONE) {
1381 			btrfs_extent_map_set_compression(em, compress_type);
1382 		} else {
1383 			/*
1384 			 * Older kernels can create regular non-hole data
1385 			 * extents with ram_bytes smaller than disk_num_bytes.
1386 			 * Not a big deal, just always use disk_num_bytes
1387 			 * for ram_bytes.
1388 			 */
1389 			em->ram_bytes = em->disk_num_bytes;
1390 			if (type == BTRFS_FILE_EXTENT_PREALLOC)
1391 				em->flags |= EXTENT_FLAG_PREALLOC;
1392 		}
1393 	} else if (type == BTRFS_FILE_EXTENT_INLINE) {
1394 		/* Tree-checker has ensured this. */
1395 		ASSERT(extent_start == 0);
1396 
1397 		em->disk_bytenr = EXTENT_MAP_INLINE;
1398 		em->start = 0;
1399 		em->len = fs_info->sectorsize;
1400 		em->offset = 0;
1401 		btrfs_extent_map_set_compression(em, compress_type);
1402 	} else {
1403 		btrfs_err(fs_info,
1404 			  "unknown file extent item type %d, inode %llu, offset %llu, "
1405 			  "root %llu", type, btrfs_ino(inode), extent_start,
1406 			  btrfs_root_id(root));
1407 	}
1408 }
1409 
1410 /*
1411  * Returns the end offset (non inclusive) of the file extent item the given path
1412  * points to. If it points to an inline extent, the returned offset is rounded
1413  * up to the sector size.
1414  */
btrfs_file_extent_end(const struct btrfs_path * path)1415 u64 btrfs_file_extent_end(const struct btrfs_path *path)
1416 {
1417 	const struct extent_buffer *leaf = path->nodes[0];
1418 	const int slot = path->slots[0];
1419 	struct btrfs_file_extent_item *fi;
1420 	struct btrfs_key key;
1421 	u64 end;
1422 
1423 	btrfs_item_key_to_cpu(leaf, &key, slot);
1424 	ASSERT(key.type == BTRFS_EXTENT_DATA_KEY);
1425 	fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
1426 
1427 	if (btrfs_file_extent_type(leaf, fi) == BTRFS_FILE_EXTENT_INLINE)
1428 		end = leaf->fs_info->sectorsize;
1429 	else
1430 		end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
1431 
1432 	return end;
1433 }
1434