xref: /linux/fs/btrfs/delayed-inode.c (revision 68f715a820b02f965e2afc584a6cb542843cbc98)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2011 Fujitsu.  All rights reserved.
4  * Written by Miao Xie <miaox@cn.fujitsu.com>
5  */
6 
7 #include <linux/slab.h>
8 #include <linux/iversion.h>
9 #include "ctree.h"
10 #include "fs.h"
11 #include "messages.h"
12 #include "misc.h"
13 #include "delayed-inode.h"
14 #include "disk-io.h"
15 #include "transaction.h"
16 #include "qgroup.h"
17 #include "locking.h"
18 #include "inode-item.h"
19 #include "space-info.h"
20 #include "accessors.h"
21 #include "file-item.h"
22 
23 #define BTRFS_DELAYED_WRITEBACK		512
24 #define BTRFS_DELAYED_BACKGROUND	128
25 #define BTRFS_DELAYED_BATCH		16
26 
27 static struct kmem_cache *delayed_node_cache;
28 
29 int __init btrfs_delayed_inode_init(void)
30 {
31 	delayed_node_cache = kmem_cache_create("btrfs_delayed_node",
32 					sizeof(struct btrfs_delayed_node),
33 					0,
34 					SLAB_MEM_SPREAD,
35 					NULL);
36 	if (!delayed_node_cache)
37 		return -ENOMEM;
38 	return 0;
39 }
40 
41 void __cold btrfs_delayed_inode_exit(void)
42 {
43 	kmem_cache_destroy(delayed_node_cache);
44 }
45 
46 static inline void btrfs_init_delayed_node(
47 				struct btrfs_delayed_node *delayed_node,
48 				struct btrfs_root *root, u64 inode_id)
49 {
50 	delayed_node->root = root;
51 	delayed_node->inode_id = inode_id;
52 	refcount_set(&delayed_node->refs, 0);
53 	delayed_node->ins_root = RB_ROOT_CACHED;
54 	delayed_node->del_root = RB_ROOT_CACHED;
55 	mutex_init(&delayed_node->mutex);
56 	INIT_LIST_HEAD(&delayed_node->n_list);
57 	INIT_LIST_HEAD(&delayed_node->p_list);
58 }
59 
60 static struct btrfs_delayed_node *btrfs_get_delayed_node(
61 		struct btrfs_inode *btrfs_inode)
62 {
63 	struct btrfs_root *root = btrfs_inode->root;
64 	u64 ino = btrfs_ino(btrfs_inode);
65 	struct btrfs_delayed_node *node;
66 
67 	node = READ_ONCE(btrfs_inode->delayed_node);
68 	if (node) {
69 		refcount_inc(&node->refs);
70 		return node;
71 	}
72 
73 	spin_lock(&root->inode_lock);
74 	node = xa_load(&root->delayed_nodes, ino);
75 
76 	if (node) {
77 		if (btrfs_inode->delayed_node) {
78 			refcount_inc(&node->refs);	/* can be accessed */
79 			BUG_ON(btrfs_inode->delayed_node != node);
80 			spin_unlock(&root->inode_lock);
81 			return node;
82 		}
83 
84 		/*
85 		 * It's possible that we're racing into the middle of removing
86 		 * this node from the xarray.  In this case, the refcount
87 		 * was zero and it should never go back to one.  Just return
88 		 * NULL like it was never in the xarray at all; our release
89 		 * function is in the process of removing it.
90 		 *
91 		 * Some implementations of refcount_inc refuse to bump the
92 		 * refcount once it has hit zero.  If we don't do this dance
93 		 * here, refcount_inc() may decide to just WARN_ONCE() instead
94 		 * of actually bumping the refcount.
95 		 *
96 		 * If this node is properly in the xarray, we want to bump the
97 		 * refcount twice, once for the inode and once for this get
98 		 * operation.
99 		 */
100 		if (refcount_inc_not_zero(&node->refs)) {
101 			refcount_inc(&node->refs);
102 			btrfs_inode->delayed_node = node;
103 		} else {
104 			node = NULL;
105 		}
106 
107 		spin_unlock(&root->inode_lock);
108 		return node;
109 	}
110 	spin_unlock(&root->inode_lock);
111 
112 	return NULL;
113 }
114 
115 /* Will return either the node or PTR_ERR(-ENOMEM) */
116 static struct btrfs_delayed_node *btrfs_get_or_create_delayed_node(
117 		struct btrfs_inode *btrfs_inode)
118 {
119 	struct btrfs_delayed_node *node;
120 	struct btrfs_root *root = btrfs_inode->root;
121 	u64 ino = btrfs_ino(btrfs_inode);
122 	int ret;
123 	void *ptr;
124 
125 again:
126 	node = btrfs_get_delayed_node(btrfs_inode);
127 	if (node)
128 		return node;
129 
130 	node = kmem_cache_zalloc(delayed_node_cache, GFP_NOFS);
131 	if (!node)
132 		return ERR_PTR(-ENOMEM);
133 	btrfs_init_delayed_node(node, root, ino);
134 
135 	/* Cached in the inode and can be accessed. */
136 	refcount_set(&node->refs, 2);
137 
138 	/* Allocate and reserve the slot, from now it can return a NULL from xa_load(). */
139 	ret = xa_reserve(&root->delayed_nodes, ino, GFP_NOFS);
140 	if (ret == -ENOMEM) {
141 		kmem_cache_free(delayed_node_cache, node);
142 		return ERR_PTR(-ENOMEM);
143 	}
144 	spin_lock(&root->inode_lock);
145 	ptr = xa_load(&root->delayed_nodes, ino);
146 	if (ptr) {
147 		/* Somebody inserted it, go back and read it. */
148 		spin_unlock(&root->inode_lock);
149 		kmem_cache_free(delayed_node_cache, node);
150 		node = NULL;
151 		goto again;
152 	}
153 	ptr = xa_store(&root->delayed_nodes, ino, node, GFP_ATOMIC);
154 	ASSERT(xa_err(ptr) != -EINVAL);
155 	ASSERT(xa_err(ptr) != -ENOMEM);
156 	ASSERT(ptr == NULL);
157 	btrfs_inode->delayed_node = node;
158 	spin_unlock(&root->inode_lock);
159 
160 	return node;
161 }
162 
163 /*
164  * Call it when holding delayed_node->mutex
165  *
166  * If mod = 1, add this node into the prepared list.
167  */
168 static void btrfs_queue_delayed_node(struct btrfs_delayed_root *root,
169 				     struct btrfs_delayed_node *node,
170 				     int mod)
171 {
172 	spin_lock(&root->lock);
173 	if (test_bit(BTRFS_DELAYED_NODE_IN_LIST, &node->flags)) {
174 		if (!list_empty(&node->p_list))
175 			list_move_tail(&node->p_list, &root->prepare_list);
176 		else if (mod)
177 			list_add_tail(&node->p_list, &root->prepare_list);
178 	} else {
179 		list_add_tail(&node->n_list, &root->node_list);
180 		list_add_tail(&node->p_list, &root->prepare_list);
181 		refcount_inc(&node->refs);	/* inserted into list */
182 		root->nodes++;
183 		set_bit(BTRFS_DELAYED_NODE_IN_LIST, &node->flags);
184 	}
185 	spin_unlock(&root->lock);
186 }
187 
188 /* Call it when holding delayed_node->mutex */
189 static void btrfs_dequeue_delayed_node(struct btrfs_delayed_root *root,
190 				       struct btrfs_delayed_node *node)
191 {
192 	spin_lock(&root->lock);
193 	if (test_bit(BTRFS_DELAYED_NODE_IN_LIST, &node->flags)) {
194 		root->nodes--;
195 		refcount_dec(&node->refs);	/* not in the list */
196 		list_del_init(&node->n_list);
197 		if (!list_empty(&node->p_list))
198 			list_del_init(&node->p_list);
199 		clear_bit(BTRFS_DELAYED_NODE_IN_LIST, &node->flags);
200 	}
201 	spin_unlock(&root->lock);
202 }
203 
204 static struct btrfs_delayed_node *btrfs_first_delayed_node(
205 			struct btrfs_delayed_root *delayed_root)
206 {
207 	struct list_head *p;
208 	struct btrfs_delayed_node *node = NULL;
209 
210 	spin_lock(&delayed_root->lock);
211 	if (list_empty(&delayed_root->node_list))
212 		goto out;
213 
214 	p = delayed_root->node_list.next;
215 	node = list_entry(p, struct btrfs_delayed_node, n_list);
216 	refcount_inc(&node->refs);
217 out:
218 	spin_unlock(&delayed_root->lock);
219 
220 	return node;
221 }
222 
223 static struct btrfs_delayed_node *btrfs_next_delayed_node(
224 						struct btrfs_delayed_node *node)
225 {
226 	struct btrfs_delayed_root *delayed_root;
227 	struct list_head *p;
228 	struct btrfs_delayed_node *next = NULL;
229 
230 	delayed_root = node->root->fs_info->delayed_root;
231 	spin_lock(&delayed_root->lock);
232 	if (!test_bit(BTRFS_DELAYED_NODE_IN_LIST, &node->flags)) {
233 		/* not in the list */
234 		if (list_empty(&delayed_root->node_list))
235 			goto out;
236 		p = delayed_root->node_list.next;
237 	} else if (list_is_last(&node->n_list, &delayed_root->node_list))
238 		goto out;
239 	else
240 		p = node->n_list.next;
241 
242 	next = list_entry(p, struct btrfs_delayed_node, n_list);
243 	refcount_inc(&next->refs);
244 out:
245 	spin_unlock(&delayed_root->lock);
246 
247 	return next;
248 }
249 
250 static void __btrfs_release_delayed_node(
251 				struct btrfs_delayed_node *delayed_node,
252 				int mod)
253 {
254 	struct btrfs_delayed_root *delayed_root;
255 
256 	if (!delayed_node)
257 		return;
258 
259 	delayed_root = delayed_node->root->fs_info->delayed_root;
260 
261 	mutex_lock(&delayed_node->mutex);
262 	if (delayed_node->count)
263 		btrfs_queue_delayed_node(delayed_root, delayed_node, mod);
264 	else
265 		btrfs_dequeue_delayed_node(delayed_root, delayed_node);
266 	mutex_unlock(&delayed_node->mutex);
267 
268 	if (refcount_dec_and_test(&delayed_node->refs)) {
269 		struct btrfs_root *root = delayed_node->root;
270 
271 		spin_lock(&root->inode_lock);
272 		/*
273 		 * Once our refcount goes to zero, nobody is allowed to bump it
274 		 * back up.  We can delete it now.
275 		 */
276 		ASSERT(refcount_read(&delayed_node->refs) == 0);
277 		xa_erase(&root->delayed_nodes, delayed_node->inode_id);
278 		spin_unlock(&root->inode_lock);
279 		kmem_cache_free(delayed_node_cache, delayed_node);
280 	}
281 }
282 
283 static inline void btrfs_release_delayed_node(struct btrfs_delayed_node *node)
284 {
285 	__btrfs_release_delayed_node(node, 0);
286 }
287 
288 static struct btrfs_delayed_node *btrfs_first_prepared_delayed_node(
289 					struct btrfs_delayed_root *delayed_root)
290 {
291 	struct list_head *p;
292 	struct btrfs_delayed_node *node = NULL;
293 
294 	spin_lock(&delayed_root->lock);
295 	if (list_empty(&delayed_root->prepare_list))
296 		goto out;
297 
298 	p = delayed_root->prepare_list.next;
299 	list_del_init(p);
300 	node = list_entry(p, struct btrfs_delayed_node, p_list);
301 	refcount_inc(&node->refs);
302 out:
303 	spin_unlock(&delayed_root->lock);
304 
305 	return node;
306 }
307 
308 static inline void btrfs_release_prepared_delayed_node(
309 					struct btrfs_delayed_node *node)
310 {
311 	__btrfs_release_delayed_node(node, 1);
312 }
313 
314 static struct btrfs_delayed_item *btrfs_alloc_delayed_item(u16 data_len,
315 					   struct btrfs_delayed_node *node,
316 					   enum btrfs_delayed_item_type type)
317 {
318 	struct btrfs_delayed_item *item;
319 
320 	item = kmalloc(struct_size(item, data, data_len), GFP_NOFS);
321 	if (item) {
322 		item->data_len = data_len;
323 		item->type = type;
324 		item->bytes_reserved = 0;
325 		item->delayed_node = node;
326 		RB_CLEAR_NODE(&item->rb_node);
327 		INIT_LIST_HEAD(&item->log_list);
328 		item->logged = false;
329 		refcount_set(&item->refs, 1);
330 	}
331 	return item;
332 }
333 
334 /*
335  * Look up the delayed item by key.
336  *
337  * @delayed_node: pointer to the delayed node
338  * @index:	  the dir index value to lookup (offset of a dir index key)
339  *
340  * Note: if we don't find the right item, we will return the prev item and
341  * the next item.
342  */
343 static struct btrfs_delayed_item *__btrfs_lookup_delayed_item(
344 				struct rb_root *root,
345 				u64 index)
346 {
347 	struct rb_node *node = root->rb_node;
348 	struct btrfs_delayed_item *delayed_item = NULL;
349 
350 	while (node) {
351 		delayed_item = rb_entry(node, struct btrfs_delayed_item,
352 					rb_node);
353 		if (delayed_item->index < index)
354 			node = node->rb_right;
355 		else if (delayed_item->index > index)
356 			node = node->rb_left;
357 		else
358 			return delayed_item;
359 	}
360 
361 	return NULL;
362 }
363 
364 static int __btrfs_add_delayed_item(struct btrfs_delayed_node *delayed_node,
365 				    struct btrfs_delayed_item *ins)
366 {
367 	struct rb_node **p, *node;
368 	struct rb_node *parent_node = NULL;
369 	struct rb_root_cached *root;
370 	struct btrfs_delayed_item *item;
371 	bool leftmost = true;
372 
373 	if (ins->type == BTRFS_DELAYED_INSERTION_ITEM)
374 		root = &delayed_node->ins_root;
375 	else
376 		root = &delayed_node->del_root;
377 
378 	p = &root->rb_root.rb_node;
379 	node = &ins->rb_node;
380 
381 	while (*p) {
382 		parent_node = *p;
383 		item = rb_entry(parent_node, struct btrfs_delayed_item,
384 				 rb_node);
385 
386 		if (item->index < ins->index) {
387 			p = &(*p)->rb_right;
388 			leftmost = false;
389 		} else if (item->index > ins->index) {
390 			p = &(*p)->rb_left;
391 		} else {
392 			return -EEXIST;
393 		}
394 	}
395 
396 	rb_link_node(node, parent_node, p);
397 	rb_insert_color_cached(node, root, leftmost);
398 
399 	if (ins->type == BTRFS_DELAYED_INSERTION_ITEM &&
400 	    ins->index >= delayed_node->index_cnt)
401 		delayed_node->index_cnt = ins->index + 1;
402 
403 	delayed_node->count++;
404 	atomic_inc(&delayed_node->root->fs_info->delayed_root->items);
405 	return 0;
406 }
407 
408 static void finish_one_item(struct btrfs_delayed_root *delayed_root)
409 {
410 	int seq = atomic_inc_return(&delayed_root->items_seq);
411 
412 	/* atomic_dec_return implies a barrier */
413 	if ((atomic_dec_return(&delayed_root->items) <
414 	    BTRFS_DELAYED_BACKGROUND || seq % BTRFS_DELAYED_BATCH == 0))
415 		cond_wake_up_nomb(&delayed_root->wait);
416 }
417 
418 static void __btrfs_remove_delayed_item(struct btrfs_delayed_item *delayed_item)
419 {
420 	struct btrfs_delayed_node *delayed_node = delayed_item->delayed_node;
421 	struct rb_root_cached *root;
422 	struct btrfs_delayed_root *delayed_root;
423 
424 	/* Not inserted, ignore it. */
425 	if (RB_EMPTY_NODE(&delayed_item->rb_node))
426 		return;
427 
428 	/* If it's in a rbtree, then we need to have delayed node locked. */
429 	lockdep_assert_held(&delayed_node->mutex);
430 
431 	delayed_root = delayed_node->root->fs_info->delayed_root;
432 
433 	BUG_ON(!delayed_root);
434 
435 	if (delayed_item->type == BTRFS_DELAYED_INSERTION_ITEM)
436 		root = &delayed_node->ins_root;
437 	else
438 		root = &delayed_node->del_root;
439 
440 	rb_erase_cached(&delayed_item->rb_node, root);
441 	RB_CLEAR_NODE(&delayed_item->rb_node);
442 	delayed_node->count--;
443 
444 	finish_one_item(delayed_root);
445 }
446 
447 static void btrfs_release_delayed_item(struct btrfs_delayed_item *item)
448 {
449 	if (item) {
450 		__btrfs_remove_delayed_item(item);
451 		if (refcount_dec_and_test(&item->refs))
452 			kfree(item);
453 	}
454 }
455 
456 static struct btrfs_delayed_item *__btrfs_first_delayed_insertion_item(
457 					struct btrfs_delayed_node *delayed_node)
458 {
459 	struct rb_node *p;
460 	struct btrfs_delayed_item *item = NULL;
461 
462 	p = rb_first_cached(&delayed_node->ins_root);
463 	if (p)
464 		item = rb_entry(p, struct btrfs_delayed_item, rb_node);
465 
466 	return item;
467 }
468 
469 static struct btrfs_delayed_item *__btrfs_first_delayed_deletion_item(
470 					struct btrfs_delayed_node *delayed_node)
471 {
472 	struct rb_node *p;
473 	struct btrfs_delayed_item *item = NULL;
474 
475 	p = rb_first_cached(&delayed_node->del_root);
476 	if (p)
477 		item = rb_entry(p, struct btrfs_delayed_item, rb_node);
478 
479 	return item;
480 }
481 
482 static struct btrfs_delayed_item *__btrfs_next_delayed_item(
483 						struct btrfs_delayed_item *item)
484 {
485 	struct rb_node *p;
486 	struct btrfs_delayed_item *next = NULL;
487 
488 	p = rb_next(&item->rb_node);
489 	if (p)
490 		next = rb_entry(p, struct btrfs_delayed_item, rb_node);
491 
492 	return next;
493 }
494 
495 static int btrfs_delayed_item_reserve_metadata(struct btrfs_trans_handle *trans,
496 					       struct btrfs_delayed_item *item)
497 {
498 	struct btrfs_block_rsv *src_rsv;
499 	struct btrfs_block_rsv *dst_rsv;
500 	struct btrfs_fs_info *fs_info = trans->fs_info;
501 	u64 num_bytes;
502 	int ret;
503 
504 	if (!trans->bytes_reserved)
505 		return 0;
506 
507 	src_rsv = trans->block_rsv;
508 	dst_rsv = &fs_info->delayed_block_rsv;
509 
510 	num_bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
511 
512 	/*
513 	 * Here we migrate space rsv from transaction rsv, since have already
514 	 * reserved space when starting a transaction.  So no need to reserve
515 	 * qgroup space here.
516 	 */
517 	ret = btrfs_block_rsv_migrate(src_rsv, dst_rsv, num_bytes, true);
518 	if (!ret) {
519 		trace_btrfs_space_reservation(fs_info, "delayed_item",
520 					      item->delayed_node->inode_id,
521 					      num_bytes, 1);
522 		/*
523 		 * For insertions we track reserved metadata space by accounting
524 		 * for the number of leaves that will be used, based on the delayed
525 		 * node's curr_index_batch_size and index_item_leaves fields.
526 		 */
527 		if (item->type == BTRFS_DELAYED_DELETION_ITEM)
528 			item->bytes_reserved = num_bytes;
529 	}
530 
531 	return ret;
532 }
533 
534 static void btrfs_delayed_item_release_metadata(struct btrfs_root *root,
535 						struct btrfs_delayed_item *item)
536 {
537 	struct btrfs_block_rsv *rsv;
538 	struct btrfs_fs_info *fs_info = root->fs_info;
539 
540 	if (!item->bytes_reserved)
541 		return;
542 
543 	rsv = &fs_info->delayed_block_rsv;
544 	/*
545 	 * Check btrfs_delayed_item_reserve_metadata() to see why we don't need
546 	 * to release/reserve qgroup space.
547 	 */
548 	trace_btrfs_space_reservation(fs_info, "delayed_item",
549 				      item->delayed_node->inode_id,
550 				      item->bytes_reserved, 0);
551 	btrfs_block_rsv_release(fs_info, rsv, item->bytes_reserved, NULL);
552 }
553 
554 static void btrfs_delayed_item_release_leaves(struct btrfs_delayed_node *node,
555 					      unsigned int num_leaves)
556 {
557 	struct btrfs_fs_info *fs_info = node->root->fs_info;
558 	const u64 bytes = btrfs_calc_insert_metadata_size(fs_info, num_leaves);
559 
560 	/* There are no space reservations during log replay, bail out. */
561 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
562 		return;
563 
564 	trace_btrfs_space_reservation(fs_info, "delayed_item", node->inode_id,
565 				      bytes, 0);
566 	btrfs_block_rsv_release(fs_info, &fs_info->delayed_block_rsv, bytes, NULL);
567 }
568 
569 static int btrfs_delayed_inode_reserve_metadata(
570 					struct btrfs_trans_handle *trans,
571 					struct btrfs_root *root,
572 					struct btrfs_delayed_node *node)
573 {
574 	struct btrfs_fs_info *fs_info = root->fs_info;
575 	struct btrfs_block_rsv *src_rsv;
576 	struct btrfs_block_rsv *dst_rsv;
577 	u64 num_bytes;
578 	int ret;
579 
580 	src_rsv = trans->block_rsv;
581 	dst_rsv = &fs_info->delayed_block_rsv;
582 
583 	num_bytes = btrfs_calc_metadata_size(fs_info, 1);
584 
585 	/*
586 	 * btrfs_dirty_inode will update the inode under btrfs_join_transaction
587 	 * which doesn't reserve space for speed.  This is a problem since we
588 	 * still need to reserve space for this update, so try to reserve the
589 	 * space.
590 	 *
591 	 * Now if src_rsv == delalloc_block_rsv we'll let it just steal since
592 	 * we always reserve enough to update the inode item.
593 	 */
594 	if (!src_rsv || (!trans->bytes_reserved &&
595 			 src_rsv->type != BTRFS_BLOCK_RSV_DELALLOC)) {
596 		ret = btrfs_qgroup_reserve_meta(root, num_bytes,
597 					  BTRFS_QGROUP_RSV_META_PREALLOC, true);
598 		if (ret < 0)
599 			return ret;
600 		ret = btrfs_block_rsv_add(fs_info, dst_rsv, num_bytes,
601 					  BTRFS_RESERVE_NO_FLUSH);
602 		/* NO_FLUSH could only fail with -ENOSPC */
603 		ASSERT(ret == 0 || ret == -ENOSPC);
604 		if (ret)
605 			btrfs_qgroup_free_meta_prealloc(root, num_bytes);
606 	} else {
607 		ret = btrfs_block_rsv_migrate(src_rsv, dst_rsv, num_bytes, true);
608 	}
609 
610 	if (!ret) {
611 		trace_btrfs_space_reservation(fs_info, "delayed_inode",
612 					      node->inode_id, num_bytes, 1);
613 		node->bytes_reserved = num_bytes;
614 	}
615 
616 	return ret;
617 }
618 
619 static void btrfs_delayed_inode_release_metadata(struct btrfs_fs_info *fs_info,
620 						struct btrfs_delayed_node *node,
621 						bool qgroup_free)
622 {
623 	struct btrfs_block_rsv *rsv;
624 
625 	if (!node->bytes_reserved)
626 		return;
627 
628 	rsv = &fs_info->delayed_block_rsv;
629 	trace_btrfs_space_reservation(fs_info, "delayed_inode",
630 				      node->inode_id, node->bytes_reserved, 0);
631 	btrfs_block_rsv_release(fs_info, rsv, node->bytes_reserved, NULL);
632 	if (qgroup_free)
633 		btrfs_qgroup_free_meta_prealloc(node->root,
634 				node->bytes_reserved);
635 	else
636 		btrfs_qgroup_convert_reserved_meta(node->root,
637 				node->bytes_reserved);
638 	node->bytes_reserved = 0;
639 }
640 
641 /*
642  * Insert a single delayed item or a batch of delayed items, as many as possible
643  * that fit in a leaf. The delayed items (dir index keys) are sorted by their key
644  * in the rbtree, and if there's a gap between two consecutive dir index items,
645  * then it means at some point we had delayed dir indexes to add but they got
646  * removed (by btrfs_delete_delayed_dir_index()) before we attempted to flush them
647  * into the subvolume tree. Dir index keys also have their offsets coming from a
648  * monotonically increasing counter, so we can't get new keys with an offset that
649  * fits within a gap between delayed dir index items.
650  */
651 static int btrfs_insert_delayed_item(struct btrfs_trans_handle *trans,
652 				     struct btrfs_root *root,
653 				     struct btrfs_path *path,
654 				     struct btrfs_delayed_item *first_item)
655 {
656 	struct btrfs_fs_info *fs_info = root->fs_info;
657 	struct btrfs_delayed_node *node = first_item->delayed_node;
658 	LIST_HEAD(item_list);
659 	struct btrfs_delayed_item *curr;
660 	struct btrfs_delayed_item *next;
661 	const int max_size = BTRFS_LEAF_DATA_SIZE(fs_info);
662 	struct btrfs_item_batch batch;
663 	struct btrfs_key first_key;
664 	const u32 first_data_size = first_item->data_len;
665 	int total_size;
666 	char *ins_data = NULL;
667 	int ret;
668 	bool continuous_keys_only = false;
669 
670 	lockdep_assert_held(&node->mutex);
671 
672 	/*
673 	 * During normal operation the delayed index offset is continuously
674 	 * increasing, so we can batch insert all items as there will not be any
675 	 * overlapping keys in the tree.
676 	 *
677 	 * The exception to this is log replay, where we may have interleaved
678 	 * offsets in the tree, so our batch needs to be continuous keys only in
679 	 * order to ensure we do not end up with out of order items in our leaf.
680 	 */
681 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
682 		continuous_keys_only = true;
683 
684 	/*
685 	 * For delayed items to insert, we track reserved metadata bytes based
686 	 * on the number of leaves that we will use.
687 	 * See btrfs_insert_delayed_dir_index() and
688 	 * btrfs_delayed_item_reserve_metadata()).
689 	 */
690 	ASSERT(first_item->bytes_reserved == 0);
691 
692 	list_add_tail(&first_item->tree_list, &item_list);
693 	batch.total_data_size = first_data_size;
694 	batch.nr = 1;
695 	total_size = first_data_size + sizeof(struct btrfs_item);
696 	curr = first_item;
697 
698 	while (true) {
699 		int next_size;
700 
701 		next = __btrfs_next_delayed_item(curr);
702 		if (!next)
703 			break;
704 
705 		/*
706 		 * We cannot allow gaps in the key space if we're doing log
707 		 * replay.
708 		 */
709 		if (continuous_keys_only && (next->index != curr->index + 1))
710 			break;
711 
712 		ASSERT(next->bytes_reserved == 0);
713 
714 		next_size = next->data_len + sizeof(struct btrfs_item);
715 		if (total_size + next_size > max_size)
716 			break;
717 
718 		list_add_tail(&next->tree_list, &item_list);
719 		batch.nr++;
720 		total_size += next_size;
721 		batch.total_data_size += next->data_len;
722 		curr = next;
723 	}
724 
725 	if (batch.nr == 1) {
726 		first_key.objectid = node->inode_id;
727 		first_key.type = BTRFS_DIR_INDEX_KEY;
728 		first_key.offset = first_item->index;
729 		batch.keys = &first_key;
730 		batch.data_sizes = &first_data_size;
731 	} else {
732 		struct btrfs_key *ins_keys;
733 		u32 *ins_sizes;
734 		int i = 0;
735 
736 		ins_data = kmalloc(batch.nr * sizeof(u32) +
737 				   batch.nr * sizeof(struct btrfs_key), GFP_NOFS);
738 		if (!ins_data) {
739 			ret = -ENOMEM;
740 			goto out;
741 		}
742 		ins_sizes = (u32 *)ins_data;
743 		ins_keys = (struct btrfs_key *)(ins_data + batch.nr * sizeof(u32));
744 		batch.keys = ins_keys;
745 		batch.data_sizes = ins_sizes;
746 		list_for_each_entry(curr, &item_list, tree_list) {
747 			ins_keys[i].objectid = node->inode_id;
748 			ins_keys[i].type = BTRFS_DIR_INDEX_KEY;
749 			ins_keys[i].offset = curr->index;
750 			ins_sizes[i] = curr->data_len;
751 			i++;
752 		}
753 	}
754 
755 	ret = btrfs_insert_empty_items(trans, root, path, &batch);
756 	if (ret)
757 		goto out;
758 
759 	list_for_each_entry(curr, &item_list, tree_list) {
760 		char *data_ptr;
761 
762 		data_ptr = btrfs_item_ptr(path->nodes[0], path->slots[0], char);
763 		write_extent_buffer(path->nodes[0], &curr->data,
764 				    (unsigned long)data_ptr, curr->data_len);
765 		path->slots[0]++;
766 	}
767 
768 	/*
769 	 * Now release our path before releasing the delayed items and their
770 	 * metadata reservations, so that we don't block other tasks for more
771 	 * time than needed.
772 	 */
773 	btrfs_release_path(path);
774 
775 	ASSERT(node->index_item_leaves > 0);
776 
777 	/*
778 	 * For normal operations we will batch an entire leaf's worth of delayed
779 	 * items, so if there are more items to process we can decrement
780 	 * index_item_leaves by 1 as we inserted 1 leaf's worth of items.
781 	 *
782 	 * However for log replay we may not have inserted an entire leaf's
783 	 * worth of items, we may have not had continuous items, so decrementing
784 	 * here would mess up the index_item_leaves accounting.  For this case
785 	 * only clean up the accounting when there are no items left.
786 	 */
787 	if (next && !continuous_keys_only) {
788 		/*
789 		 * We inserted one batch of items into a leaf a there are more
790 		 * items to flush in a future batch, now release one unit of
791 		 * metadata space from the delayed block reserve, corresponding
792 		 * the leaf we just flushed to.
793 		 */
794 		btrfs_delayed_item_release_leaves(node, 1);
795 		node->index_item_leaves--;
796 	} else if (!next) {
797 		/*
798 		 * There are no more items to insert. We can have a number of
799 		 * reserved leaves > 1 here - this happens when many dir index
800 		 * items are added and then removed before they are flushed (file
801 		 * names with a very short life, never span a transaction). So
802 		 * release all remaining leaves.
803 		 */
804 		btrfs_delayed_item_release_leaves(node, node->index_item_leaves);
805 		node->index_item_leaves = 0;
806 	}
807 
808 	list_for_each_entry_safe(curr, next, &item_list, tree_list) {
809 		list_del(&curr->tree_list);
810 		btrfs_release_delayed_item(curr);
811 	}
812 out:
813 	kfree(ins_data);
814 	return ret;
815 }
816 
817 static int btrfs_insert_delayed_items(struct btrfs_trans_handle *trans,
818 				      struct btrfs_path *path,
819 				      struct btrfs_root *root,
820 				      struct btrfs_delayed_node *node)
821 {
822 	int ret = 0;
823 
824 	while (ret == 0) {
825 		struct btrfs_delayed_item *curr;
826 
827 		mutex_lock(&node->mutex);
828 		curr = __btrfs_first_delayed_insertion_item(node);
829 		if (!curr) {
830 			mutex_unlock(&node->mutex);
831 			break;
832 		}
833 		ret = btrfs_insert_delayed_item(trans, root, path, curr);
834 		mutex_unlock(&node->mutex);
835 	}
836 
837 	return ret;
838 }
839 
840 static int btrfs_batch_delete_items(struct btrfs_trans_handle *trans,
841 				    struct btrfs_root *root,
842 				    struct btrfs_path *path,
843 				    struct btrfs_delayed_item *item)
844 {
845 	const u64 ino = item->delayed_node->inode_id;
846 	struct btrfs_fs_info *fs_info = root->fs_info;
847 	struct btrfs_delayed_item *curr, *next;
848 	struct extent_buffer *leaf = path->nodes[0];
849 	LIST_HEAD(batch_list);
850 	int nitems, slot, last_slot;
851 	int ret;
852 	u64 total_reserved_size = item->bytes_reserved;
853 
854 	ASSERT(leaf != NULL);
855 
856 	slot = path->slots[0];
857 	last_slot = btrfs_header_nritems(leaf) - 1;
858 	/*
859 	 * Our caller always gives us a path pointing to an existing item, so
860 	 * this can not happen.
861 	 */
862 	ASSERT(slot <= last_slot);
863 	if (WARN_ON(slot > last_slot))
864 		return -ENOENT;
865 
866 	nitems = 1;
867 	curr = item;
868 	list_add_tail(&curr->tree_list, &batch_list);
869 
870 	/*
871 	 * Keep checking if the next delayed item matches the next item in the
872 	 * leaf - if so, we can add it to the batch of items to delete from the
873 	 * leaf.
874 	 */
875 	while (slot < last_slot) {
876 		struct btrfs_key key;
877 
878 		next = __btrfs_next_delayed_item(curr);
879 		if (!next)
880 			break;
881 
882 		slot++;
883 		btrfs_item_key_to_cpu(leaf, &key, slot);
884 		if (key.objectid != ino ||
885 		    key.type != BTRFS_DIR_INDEX_KEY ||
886 		    key.offset != next->index)
887 			break;
888 		nitems++;
889 		curr = next;
890 		list_add_tail(&curr->tree_list, &batch_list);
891 		total_reserved_size += curr->bytes_reserved;
892 	}
893 
894 	ret = btrfs_del_items(trans, root, path, path->slots[0], nitems);
895 	if (ret)
896 		return ret;
897 
898 	/* In case of BTRFS_FS_LOG_RECOVERING items won't have reserved space */
899 	if (total_reserved_size > 0) {
900 		/*
901 		 * Check btrfs_delayed_item_reserve_metadata() to see why we
902 		 * don't need to release/reserve qgroup space.
903 		 */
904 		trace_btrfs_space_reservation(fs_info, "delayed_item", ino,
905 					      total_reserved_size, 0);
906 		btrfs_block_rsv_release(fs_info, &fs_info->delayed_block_rsv,
907 					total_reserved_size, NULL);
908 	}
909 
910 	list_for_each_entry_safe(curr, next, &batch_list, tree_list) {
911 		list_del(&curr->tree_list);
912 		btrfs_release_delayed_item(curr);
913 	}
914 
915 	return 0;
916 }
917 
918 static int btrfs_delete_delayed_items(struct btrfs_trans_handle *trans,
919 				      struct btrfs_path *path,
920 				      struct btrfs_root *root,
921 				      struct btrfs_delayed_node *node)
922 {
923 	struct btrfs_key key;
924 	int ret = 0;
925 
926 	key.objectid = node->inode_id;
927 	key.type = BTRFS_DIR_INDEX_KEY;
928 
929 	while (ret == 0) {
930 		struct btrfs_delayed_item *item;
931 
932 		mutex_lock(&node->mutex);
933 		item = __btrfs_first_delayed_deletion_item(node);
934 		if (!item) {
935 			mutex_unlock(&node->mutex);
936 			break;
937 		}
938 
939 		key.offset = item->index;
940 		ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
941 		if (ret > 0) {
942 			/*
943 			 * There's no matching item in the leaf. This means we
944 			 * have already deleted this item in a past run of the
945 			 * delayed items. We ignore errors when running delayed
946 			 * items from an async context, through a work queue job
947 			 * running btrfs_async_run_delayed_root(), and don't
948 			 * release delayed items that failed to complete. This
949 			 * is because we will retry later, and at transaction
950 			 * commit time we always run delayed items and will
951 			 * then deal with errors if they fail to run again.
952 			 *
953 			 * So just release delayed items for which we can't find
954 			 * an item in the tree, and move to the next item.
955 			 */
956 			btrfs_release_path(path);
957 			btrfs_release_delayed_item(item);
958 			ret = 0;
959 		} else if (ret == 0) {
960 			ret = btrfs_batch_delete_items(trans, root, path, item);
961 			btrfs_release_path(path);
962 		}
963 
964 		/*
965 		 * We unlock and relock on each iteration, this is to prevent
966 		 * blocking other tasks for too long while we are being run from
967 		 * the async context (work queue job). Those tasks are typically
968 		 * running system calls like creat/mkdir/rename/unlink/etc which
969 		 * need to add delayed items to this delayed node.
970 		 */
971 		mutex_unlock(&node->mutex);
972 	}
973 
974 	return ret;
975 }
976 
977 static void btrfs_release_delayed_inode(struct btrfs_delayed_node *delayed_node)
978 {
979 	struct btrfs_delayed_root *delayed_root;
980 
981 	if (delayed_node &&
982 	    test_bit(BTRFS_DELAYED_NODE_INODE_DIRTY, &delayed_node->flags)) {
983 		BUG_ON(!delayed_node->root);
984 		clear_bit(BTRFS_DELAYED_NODE_INODE_DIRTY, &delayed_node->flags);
985 		delayed_node->count--;
986 
987 		delayed_root = delayed_node->root->fs_info->delayed_root;
988 		finish_one_item(delayed_root);
989 	}
990 }
991 
992 static void btrfs_release_delayed_iref(struct btrfs_delayed_node *delayed_node)
993 {
994 
995 	if (test_and_clear_bit(BTRFS_DELAYED_NODE_DEL_IREF, &delayed_node->flags)) {
996 		struct btrfs_delayed_root *delayed_root;
997 
998 		ASSERT(delayed_node->root);
999 		delayed_node->count--;
1000 
1001 		delayed_root = delayed_node->root->fs_info->delayed_root;
1002 		finish_one_item(delayed_root);
1003 	}
1004 }
1005 
1006 static int __btrfs_update_delayed_inode(struct btrfs_trans_handle *trans,
1007 					struct btrfs_root *root,
1008 					struct btrfs_path *path,
1009 					struct btrfs_delayed_node *node)
1010 {
1011 	struct btrfs_fs_info *fs_info = root->fs_info;
1012 	struct btrfs_key key;
1013 	struct btrfs_inode_item *inode_item;
1014 	struct extent_buffer *leaf;
1015 	int mod;
1016 	int ret;
1017 
1018 	key.objectid = node->inode_id;
1019 	key.type = BTRFS_INODE_ITEM_KEY;
1020 	key.offset = 0;
1021 
1022 	if (test_bit(BTRFS_DELAYED_NODE_DEL_IREF, &node->flags))
1023 		mod = -1;
1024 	else
1025 		mod = 1;
1026 
1027 	ret = btrfs_lookup_inode(trans, root, path, &key, mod);
1028 	if (ret > 0)
1029 		ret = -ENOENT;
1030 	if (ret < 0)
1031 		goto out;
1032 
1033 	leaf = path->nodes[0];
1034 	inode_item = btrfs_item_ptr(leaf, path->slots[0],
1035 				    struct btrfs_inode_item);
1036 	write_extent_buffer(leaf, &node->inode_item, (unsigned long)inode_item,
1037 			    sizeof(struct btrfs_inode_item));
1038 	btrfs_mark_buffer_dirty(trans, leaf);
1039 
1040 	if (!test_bit(BTRFS_DELAYED_NODE_DEL_IREF, &node->flags))
1041 		goto out;
1042 
1043 	/*
1044 	 * Now we're going to delete the INODE_REF/EXTREF, which should be the
1045 	 * only one ref left.  Check if the next item is an INODE_REF/EXTREF.
1046 	 *
1047 	 * But if we're the last item already, release and search for the last
1048 	 * INODE_REF/EXTREF.
1049 	 */
1050 	if (path->slots[0] + 1 >= btrfs_header_nritems(leaf)) {
1051 		key.objectid = node->inode_id;
1052 		key.type = BTRFS_INODE_EXTREF_KEY;
1053 		key.offset = (u64)-1;
1054 
1055 		btrfs_release_path(path);
1056 		ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1057 		if (ret < 0)
1058 			goto err_out;
1059 		ASSERT(ret > 0);
1060 		ASSERT(path->slots[0] > 0);
1061 		ret = 0;
1062 		path->slots[0]--;
1063 		leaf = path->nodes[0];
1064 	} else {
1065 		path->slots[0]++;
1066 	}
1067 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1068 	if (key.objectid != node->inode_id)
1069 		goto out;
1070 	if (key.type != BTRFS_INODE_REF_KEY &&
1071 	    key.type != BTRFS_INODE_EXTREF_KEY)
1072 		goto out;
1073 
1074 	/*
1075 	 * Delayed iref deletion is for the inode who has only one link,
1076 	 * so there is only one iref. The case that several irefs are
1077 	 * in the same item doesn't exist.
1078 	 */
1079 	ret = btrfs_del_item(trans, root, path);
1080 out:
1081 	btrfs_release_delayed_iref(node);
1082 	btrfs_release_path(path);
1083 err_out:
1084 	btrfs_delayed_inode_release_metadata(fs_info, node, (ret < 0));
1085 	btrfs_release_delayed_inode(node);
1086 
1087 	/*
1088 	 * If we fail to update the delayed inode we need to abort the
1089 	 * transaction, because we could leave the inode with the improper
1090 	 * counts behind.
1091 	 */
1092 	if (ret && ret != -ENOENT)
1093 		btrfs_abort_transaction(trans, ret);
1094 
1095 	return ret;
1096 }
1097 
1098 static inline int btrfs_update_delayed_inode(struct btrfs_trans_handle *trans,
1099 					     struct btrfs_root *root,
1100 					     struct btrfs_path *path,
1101 					     struct btrfs_delayed_node *node)
1102 {
1103 	int ret;
1104 
1105 	mutex_lock(&node->mutex);
1106 	if (!test_bit(BTRFS_DELAYED_NODE_INODE_DIRTY, &node->flags)) {
1107 		mutex_unlock(&node->mutex);
1108 		return 0;
1109 	}
1110 
1111 	ret = __btrfs_update_delayed_inode(trans, root, path, node);
1112 	mutex_unlock(&node->mutex);
1113 	return ret;
1114 }
1115 
1116 static inline int
1117 __btrfs_commit_inode_delayed_items(struct btrfs_trans_handle *trans,
1118 				   struct btrfs_path *path,
1119 				   struct btrfs_delayed_node *node)
1120 {
1121 	int ret;
1122 
1123 	ret = btrfs_insert_delayed_items(trans, path, node->root, node);
1124 	if (ret)
1125 		return ret;
1126 
1127 	ret = btrfs_delete_delayed_items(trans, path, node->root, node);
1128 	if (ret)
1129 		return ret;
1130 
1131 	ret = btrfs_update_delayed_inode(trans, node->root, path, node);
1132 	return ret;
1133 }
1134 
1135 /*
1136  * Called when committing the transaction.
1137  * Returns 0 on success.
1138  * Returns < 0 on error and returns with an aborted transaction with any
1139  * outstanding delayed items cleaned up.
1140  */
1141 static int __btrfs_run_delayed_items(struct btrfs_trans_handle *trans, int nr)
1142 {
1143 	struct btrfs_fs_info *fs_info = trans->fs_info;
1144 	struct btrfs_delayed_root *delayed_root;
1145 	struct btrfs_delayed_node *curr_node, *prev_node;
1146 	struct btrfs_path *path;
1147 	struct btrfs_block_rsv *block_rsv;
1148 	int ret = 0;
1149 	bool count = (nr > 0);
1150 
1151 	if (TRANS_ABORTED(trans))
1152 		return -EIO;
1153 
1154 	path = btrfs_alloc_path();
1155 	if (!path)
1156 		return -ENOMEM;
1157 
1158 	block_rsv = trans->block_rsv;
1159 	trans->block_rsv = &fs_info->delayed_block_rsv;
1160 
1161 	delayed_root = fs_info->delayed_root;
1162 
1163 	curr_node = btrfs_first_delayed_node(delayed_root);
1164 	while (curr_node && (!count || nr--)) {
1165 		ret = __btrfs_commit_inode_delayed_items(trans, path,
1166 							 curr_node);
1167 		if (ret) {
1168 			btrfs_abort_transaction(trans, ret);
1169 			break;
1170 		}
1171 
1172 		prev_node = curr_node;
1173 		curr_node = btrfs_next_delayed_node(curr_node);
1174 		/*
1175 		 * See the comment below about releasing path before releasing
1176 		 * node. If the commit of delayed items was successful the path
1177 		 * should always be released, but in case of an error, it may
1178 		 * point to locked extent buffers (a leaf at the very least).
1179 		 */
1180 		ASSERT(path->nodes[0] == NULL);
1181 		btrfs_release_delayed_node(prev_node);
1182 	}
1183 
1184 	/*
1185 	 * Release the path to avoid a potential deadlock and lockdep splat when
1186 	 * releasing the delayed node, as that requires taking the delayed node's
1187 	 * mutex. If another task starts running delayed items before we take
1188 	 * the mutex, it will first lock the mutex and then it may try to lock
1189 	 * the same btree path (leaf).
1190 	 */
1191 	btrfs_free_path(path);
1192 
1193 	if (curr_node)
1194 		btrfs_release_delayed_node(curr_node);
1195 	trans->block_rsv = block_rsv;
1196 
1197 	return ret;
1198 }
1199 
1200 int btrfs_run_delayed_items(struct btrfs_trans_handle *trans)
1201 {
1202 	return __btrfs_run_delayed_items(trans, -1);
1203 }
1204 
1205 int btrfs_run_delayed_items_nr(struct btrfs_trans_handle *trans, int nr)
1206 {
1207 	return __btrfs_run_delayed_items(trans, nr);
1208 }
1209 
1210 int btrfs_commit_inode_delayed_items(struct btrfs_trans_handle *trans,
1211 				     struct btrfs_inode *inode)
1212 {
1213 	struct btrfs_delayed_node *delayed_node = btrfs_get_delayed_node(inode);
1214 	struct btrfs_path *path;
1215 	struct btrfs_block_rsv *block_rsv;
1216 	int ret;
1217 
1218 	if (!delayed_node)
1219 		return 0;
1220 
1221 	mutex_lock(&delayed_node->mutex);
1222 	if (!delayed_node->count) {
1223 		mutex_unlock(&delayed_node->mutex);
1224 		btrfs_release_delayed_node(delayed_node);
1225 		return 0;
1226 	}
1227 	mutex_unlock(&delayed_node->mutex);
1228 
1229 	path = btrfs_alloc_path();
1230 	if (!path) {
1231 		btrfs_release_delayed_node(delayed_node);
1232 		return -ENOMEM;
1233 	}
1234 
1235 	block_rsv = trans->block_rsv;
1236 	trans->block_rsv = &delayed_node->root->fs_info->delayed_block_rsv;
1237 
1238 	ret = __btrfs_commit_inode_delayed_items(trans, path, delayed_node);
1239 
1240 	btrfs_release_delayed_node(delayed_node);
1241 	btrfs_free_path(path);
1242 	trans->block_rsv = block_rsv;
1243 
1244 	return ret;
1245 }
1246 
1247 int btrfs_commit_inode_delayed_inode(struct btrfs_inode *inode)
1248 {
1249 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1250 	struct btrfs_trans_handle *trans;
1251 	struct btrfs_delayed_node *delayed_node = btrfs_get_delayed_node(inode);
1252 	struct btrfs_path *path;
1253 	struct btrfs_block_rsv *block_rsv;
1254 	int ret;
1255 
1256 	if (!delayed_node)
1257 		return 0;
1258 
1259 	mutex_lock(&delayed_node->mutex);
1260 	if (!test_bit(BTRFS_DELAYED_NODE_INODE_DIRTY, &delayed_node->flags)) {
1261 		mutex_unlock(&delayed_node->mutex);
1262 		btrfs_release_delayed_node(delayed_node);
1263 		return 0;
1264 	}
1265 	mutex_unlock(&delayed_node->mutex);
1266 
1267 	trans = btrfs_join_transaction(delayed_node->root);
1268 	if (IS_ERR(trans)) {
1269 		ret = PTR_ERR(trans);
1270 		goto out;
1271 	}
1272 
1273 	path = btrfs_alloc_path();
1274 	if (!path) {
1275 		ret = -ENOMEM;
1276 		goto trans_out;
1277 	}
1278 
1279 	block_rsv = trans->block_rsv;
1280 	trans->block_rsv = &fs_info->delayed_block_rsv;
1281 
1282 	mutex_lock(&delayed_node->mutex);
1283 	if (test_bit(BTRFS_DELAYED_NODE_INODE_DIRTY, &delayed_node->flags))
1284 		ret = __btrfs_update_delayed_inode(trans, delayed_node->root,
1285 						   path, delayed_node);
1286 	else
1287 		ret = 0;
1288 	mutex_unlock(&delayed_node->mutex);
1289 
1290 	btrfs_free_path(path);
1291 	trans->block_rsv = block_rsv;
1292 trans_out:
1293 	btrfs_end_transaction(trans);
1294 	btrfs_btree_balance_dirty(fs_info);
1295 out:
1296 	btrfs_release_delayed_node(delayed_node);
1297 
1298 	return ret;
1299 }
1300 
1301 void btrfs_remove_delayed_node(struct btrfs_inode *inode)
1302 {
1303 	struct btrfs_delayed_node *delayed_node;
1304 
1305 	delayed_node = READ_ONCE(inode->delayed_node);
1306 	if (!delayed_node)
1307 		return;
1308 
1309 	inode->delayed_node = NULL;
1310 	btrfs_release_delayed_node(delayed_node);
1311 }
1312 
1313 struct btrfs_async_delayed_work {
1314 	struct btrfs_delayed_root *delayed_root;
1315 	int nr;
1316 	struct btrfs_work work;
1317 };
1318 
1319 static void btrfs_async_run_delayed_root(struct btrfs_work *work)
1320 {
1321 	struct btrfs_async_delayed_work *async_work;
1322 	struct btrfs_delayed_root *delayed_root;
1323 	struct btrfs_trans_handle *trans;
1324 	struct btrfs_path *path;
1325 	struct btrfs_delayed_node *delayed_node = NULL;
1326 	struct btrfs_root *root;
1327 	struct btrfs_block_rsv *block_rsv;
1328 	int total_done = 0;
1329 
1330 	async_work = container_of(work, struct btrfs_async_delayed_work, work);
1331 	delayed_root = async_work->delayed_root;
1332 
1333 	path = btrfs_alloc_path();
1334 	if (!path)
1335 		goto out;
1336 
1337 	do {
1338 		if (atomic_read(&delayed_root->items) <
1339 		    BTRFS_DELAYED_BACKGROUND / 2)
1340 			break;
1341 
1342 		delayed_node = btrfs_first_prepared_delayed_node(delayed_root);
1343 		if (!delayed_node)
1344 			break;
1345 
1346 		root = delayed_node->root;
1347 
1348 		trans = btrfs_join_transaction(root);
1349 		if (IS_ERR(trans)) {
1350 			btrfs_release_path(path);
1351 			btrfs_release_prepared_delayed_node(delayed_node);
1352 			total_done++;
1353 			continue;
1354 		}
1355 
1356 		block_rsv = trans->block_rsv;
1357 		trans->block_rsv = &root->fs_info->delayed_block_rsv;
1358 
1359 		__btrfs_commit_inode_delayed_items(trans, path, delayed_node);
1360 
1361 		trans->block_rsv = block_rsv;
1362 		btrfs_end_transaction(trans);
1363 		btrfs_btree_balance_dirty_nodelay(root->fs_info);
1364 
1365 		btrfs_release_path(path);
1366 		btrfs_release_prepared_delayed_node(delayed_node);
1367 		total_done++;
1368 
1369 	} while ((async_work->nr == 0 && total_done < BTRFS_DELAYED_WRITEBACK)
1370 		 || total_done < async_work->nr);
1371 
1372 	btrfs_free_path(path);
1373 out:
1374 	wake_up(&delayed_root->wait);
1375 	kfree(async_work);
1376 }
1377 
1378 
1379 static int btrfs_wq_run_delayed_node(struct btrfs_delayed_root *delayed_root,
1380 				     struct btrfs_fs_info *fs_info, int nr)
1381 {
1382 	struct btrfs_async_delayed_work *async_work;
1383 
1384 	async_work = kmalloc(sizeof(*async_work), GFP_NOFS);
1385 	if (!async_work)
1386 		return -ENOMEM;
1387 
1388 	async_work->delayed_root = delayed_root;
1389 	btrfs_init_work(&async_work->work, btrfs_async_run_delayed_root, NULL);
1390 	async_work->nr = nr;
1391 
1392 	btrfs_queue_work(fs_info->delayed_workers, &async_work->work);
1393 	return 0;
1394 }
1395 
1396 void btrfs_assert_delayed_root_empty(struct btrfs_fs_info *fs_info)
1397 {
1398 	WARN_ON(btrfs_first_delayed_node(fs_info->delayed_root));
1399 }
1400 
1401 static int could_end_wait(struct btrfs_delayed_root *delayed_root, int seq)
1402 {
1403 	int val = atomic_read(&delayed_root->items_seq);
1404 
1405 	if (val < seq || val >= seq + BTRFS_DELAYED_BATCH)
1406 		return 1;
1407 
1408 	if (atomic_read(&delayed_root->items) < BTRFS_DELAYED_BACKGROUND)
1409 		return 1;
1410 
1411 	return 0;
1412 }
1413 
1414 void btrfs_balance_delayed_items(struct btrfs_fs_info *fs_info)
1415 {
1416 	struct btrfs_delayed_root *delayed_root = fs_info->delayed_root;
1417 
1418 	if ((atomic_read(&delayed_root->items) < BTRFS_DELAYED_BACKGROUND) ||
1419 		btrfs_workqueue_normal_congested(fs_info->delayed_workers))
1420 		return;
1421 
1422 	if (atomic_read(&delayed_root->items) >= BTRFS_DELAYED_WRITEBACK) {
1423 		int seq;
1424 		int ret;
1425 
1426 		seq = atomic_read(&delayed_root->items_seq);
1427 
1428 		ret = btrfs_wq_run_delayed_node(delayed_root, fs_info, 0);
1429 		if (ret)
1430 			return;
1431 
1432 		wait_event_interruptible(delayed_root->wait,
1433 					 could_end_wait(delayed_root, seq));
1434 		return;
1435 	}
1436 
1437 	btrfs_wq_run_delayed_node(delayed_root, fs_info, BTRFS_DELAYED_BATCH);
1438 }
1439 
1440 static void btrfs_release_dir_index_item_space(struct btrfs_trans_handle *trans)
1441 {
1442 	struct btrfs_fs_info *fs_info = trans->fs_info;
1443 	const u64 bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
1444 
1445 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
1446 		return;
1447 
1448 	/*
1449 	 * Adding the new dir index item does not require touching another
1450 	 * leaf, so we can release 1 unit of metadata that was previously
1451 	 * reserved when starting the transaction. This applies only to
1452 	 * the case where we had a transaction start and excludes the
1453 	 * transaction join case (when replaying log trees).
1454 	 */
1455 	trace_btrfs_space_reservation(fs_info, "transaction",
1456 				      trans->transid, bytes, 0);
1457 	btrfs_block_rsv_release(fs_info, trans->block_rsv, bytes, NULL);
1458 	ASSERT(trans->bytes_reserved >= bytes);
1459 	trans->bytes_reserved -= bytes;
1460 }
1461 
1462 /* Will return 0, -ENOMEM or -EEXIST (index number collision, unexpected). */
1463 int btrfs_insert_delayed_dir_index(struct btrfs_trans_handle *trans,
1464 				   const char *name, int name_len,
1465 				   struct btrfs_inode *dir,
1466 				   struct btrfs_disk_key *disk_key, u8 flags,
1467 				   u64 index)
1468 {
1469 	struct btrfs_fs_info *fs_info = trans->fs_info;
1470 	const unsigned int leaf_data_size = BTRFS_LEAF_DATA_SIZE(fs_info);
1471 	struct btrfs_delayed_node *delayed_node;
1472 	struct btrfs_delayed_item *delayed_item;
1473 	struct btrfs_dir_item *dir_item;
1474 	bool reserve_leaf_space;
1475 	u32 data_len;
1476 	int ret;
1477 
1478 	delayed_node = btrfs_get_or_create_delayed_node(dir);
1479 	if (IS_ERR(delayed_node))
1480 		return PTR_ERR(delayed_node);
1481 
1482 	delayed_item = btrfs_alloc_delayed_item(sizeof(*dir_item) + name_len,
1483 						delayed_node,
1484 						BTRFS_DELAYED_INSERTION_ITEM);
1485 	if (!delayed_item) {
1486 		ret = -ENOMEM;
1487 		goto release_node;
1488 	}
1489 
1490 	delayed_item->index = index;
1491 
1492 	dir_item = (struct btrfs_dir_item *)delayed_item->data;
1493 	dir_item->location = *disk_key;
1494 	btrfs_set_stack_dir_transid(dir_item, trans->transid);
1495 	btrfs_set_stack_dir_data_len(dir_item, 0);
1496 	btrfs_set_stack_dir_name_len(dir_item, name_len);
1497 	btrfs_set_stack_dir_flags(dir_item, flags);
1498 	memcpy((char *)(dir_item + 1), name, name_len);
1499 
1500 	data_len = delayed_item->data_len + sizeof(struct btrfs_item);
1501 
1502 	mutex_lock(&delayed_node->mutex);
1503 
1504 	/*
1505 	 * First attempt to insert the delayed item. This is to make the error
1506 	 * handling path simpler in case we fail (-EEXIST). There's no risk of
1507 	 * any other task coming in and running the delayed item before we do
1508 	 * the metadata space reservation below, because we are holding the
1509 	 * delayed node's mutex and that mutex must also be locked before the
1510 	 * node's delayed items can be run.
1511 	 */
1512 	ret = __btrfs_add_delayed_item(delayed_node, delayed_item);
1513 	if (unlikely(ret)) {
1514 		btrfs_err(trans->fs_info,
1515 "error adding delayed dir index item, name: %.*s, index: %llu, root: %llu, dir: %llu, dir->index_cnt: %llu, delayed_node->index_cnt: %llu, error: %d",
1516 			  name_len, name, index, btrfs_root_id(delayed_node->root),
1517 			  delayed_node->inode_id, dir->index_cnt,
1518 			  delayed_node->index_cnt, ret);
1519 		btrfs_release_delayed_item(delayed_item);
1520 		btrfs_release_dir_index_item_space(trans);
1521 		mutex_unlock(&delayed_node->mutex);
1522 		goto release_node;
1523 	}
1524 
1525 	if (delayed_node->index_item_leaves == 0 ||
1526 	    delayed_node->curr_index_batch_size + data_len > leaf_data_size) {
1527 		delayed_node->curr_index_batch_size = data_len;
1528 		reserve_leaf_space = true;
1529 	} else {
1530 		delayed_node->curr_index_batch_size += data_len;
1531 		reserve_leaf_space = false;
1532 	}
1533 
1534 	if (reserve_leaf_space) {
1535 		ret = btrfs_delayed_item_reserve_metadata(trans, delayed_item);
1536 		/*
1537 		 * Space was reserved for a dir index item insertion when we
1538 		 * started the transaction, so getting a failure here should be
1539 		 * impossible.
1540 		 */
1541 		if (WARN_ON(ret)) {
1542 			btrfs_release_delayed_item(delayed_item);
1543 			mutex_unlock(&delayed_node->mutex);
1544 			goto release_node;
1545 		}
1546 
1547 		delayed_node->index_item_leaves++;
1548 	} else {
1549 		btrfs_release_dir_index_item_space(trans);
1550 	}
1551 	mutex_unlock(&delayed_node->mutex);
1552 
1553 release_node:
1554 	btrfs_release_delayed_node(delayed_node);
1555 	return ret;
1556 }
1557 
1558 static int btrfs_delete_delayed_insertion_item(struct btrfs_fs_info *fs_info,
1559 					       struct btrfs_delayed_node *node,
1560 					       u64 index)
1561 {
1562 	struct btrfs_delayed_item *item;
1563 
1564 	mutex_lock(&node->mutex);
1565 	item = __btrfs_lookup_delayed_item(&node->ins_root.rb_root, index);
1566 	if (!item) {
1567 		mutex_unlock(&node->mutex);
1568 		return 1;
1569 	}
1570 
1571 	/*
1572 	 * For delayed items to insert, we track reserved metadata bytes based
1573 	 * on the number of leaves that we will use.
1574 	 * See btrfs_insert_delayed_dir_index() and
1575 	 * btrfs_delayed_item_reserve_metadata()).
1576 	 */
1577 	ASSERT(item->bytes_reserved == 0);
1578 	ASSERT(node->index_item_leaves > 0);
1579 
1580 	/*
1581 	 * If there's only one leaf reserved, we can decrement this item from the
1582 	 * current batch, otherwise we can not because we don't know which leaf
1583 	 * it belongs to. With the current limit on delayed items, we rarely
1584 	 * accumulate enough dir index items to fill more than one leaf (even
1585 	 * when using a leaf size of 4K).
1586 	 */
1587 	if (node->index_item_leaves == 1) {
1588 		const u32 data_len = item->data_len + sizeof(struct btrfs_item);
1589 
1590 		ASSERT(node->curr_index_batch_size >= data_len);
1591 		node->curr_index_batch_size -= data_len;
1592 	}
1593 
1594 	btrfs_release_delayed_item(item);
1595 
1596 	/* If we now have no more dir index items, we can release all leaves. */
1597 	if (RB_EMPTY_ROOT(&node->ins_root.rb_root)) {
1598 		btrfs_delayed_item_release_leaves(node, node->index_item_leaves);
1599 		node->index_item_leaves = 0;
1600 	}
1601 
1602 	mutex_unlock(&node->mutex);
1603 	return 0;
1604 }
1605 
1606 int btrfs_delete_delayed_dir_index(struct btrfs_trans_handle *trans,
1607 				   struct btrfs_inode *dir, u64 index)
1608 {
1609 	struct btrfs_delayed_node *node;
1610 	struct btrfs_delayed_item *item;
1611 	int ret;
1612 
1613 	node = btrfs_get_or_create_delayed_node(dir);
1614 	if (IS_ERR(node))
1615 		return PTR_ERR(node);
1616 
1617 	ret = btrfs_delete_delayed_insertion_item(trans->fs_info, node, index);
1618 	if (!ret)
1619 		goto end;
1620 
1621 	item = btrfs_alloc_delayed_item(0, node, BTRFS_DELAYED_DELETION_ITEM);
1622 	if (!item) {
1623 		ret = -ENOMEM;
1624 		goto end;
1625 	}
1626 
1627 	item->index = index;
1628 
1629 	ret = btrfs_delayed_item_reserve_metadata(trans, item);
1630 	/*
1631 	 * we have reserved enough space when we start a new transaction,
1632 	 * so reserving metadata failure is impossible.
1633 	 */
1634 	if (ret < 0) {
1635 		btrfs_err(trans->fs_info,
1636 "metadata reservation failed for delayed dir item deltiona, should have been reserved");
1637 		btrfs_release_delayed_item(item);
1638 		goto end;
1639 	}
1640 
1641 	mutex_lock(&node->mutex);
1642 	ret = __btrfs_add_delayed_item(node, item);
1643 	if (unlikely(ret)) {
1644 		btrfs_err(trans->fs_info,
1645 			  "err add delayed dir index item(index: %llu) into the deletion tree of the delayed node(root id: %llu, inode id: %llu, errno: %d)",
1646 			  index, node->root->root_key.objectid,
1647 			  node->inode_id, ret);
1648 		btrfs_delayed_item_release_metadata(dir->root, item);
1649 		btrfs_release_delayed_item(item);
1650 	}
1651 	mutex_unlock(&node->mutex);
1652 end:
1653 	btrfs_release_delayed_node(node);
1654 	return ret;
1655 }
1656 
1657 int btrfs_inode_delayed_dir_index_count(struct btrfs_inode *inode)
1658 {
1659 	struct btrfs_delayed_node *delayed_node = btrfs_get_delayed_node(inode);
1660 
1661 	if (!delayed_node)
1662 		return -ENOENT;
1663 
1664 	/*
1665 	 * Since we have held i_mutex of this directory, it is impossible that
1666 	 * a new directory index is added into the delayed node and index_cnt
1667 	 * is updated now. So we needn't lock the delayed node.
1668 	 */
1669 	if (!delayed_node->index_cnt) {
1670 		btrfs_release_delayed_node(delayed_node);
1671 		return -EINVAL;
1672 	}
1673 
1674 	inode->index_cnt = delayed_node->index_cnt;
1675 	btrfs_release_delayed_node(delayed_node);
1676 	return 0;
1677 }
1678 
1679 bool btrfs_readdir_get_delayed_items(struct inode *inode,
1680 				     u64 last_index,
1681 				     struct list_head *ins_list,
1682 				     struct list_head *del_list)
1683 {
1684 	struct btrfs_delayed_node *delayed_node;
1685 	struct btrfs_delayed_item *item;
1686 
1687 	delayed_node = btrfs_get_delayed_node(BTRFS_I(inode));
1688 	if (!delayed_node)
1689 		return false;
1690 
1691 	/*
1692 	 * We can only do one readdir with delayed items at a time because of
1693 	 * item->readdir_list.
1694 	 */
1695 	btrfs_inode_unlock(BTRFS_I(inode), BTRFS_ILOCK_SHARED);
1696 	btrfs_inode_lock(BTRFS_I(inode), 0);
1697 
1698 	mutex_lock(&delayed_node->mutex);
1699 	item = __btrfs_first_delayed_insertion_item(delayed_node);
1700 	while (item && item->index <= last_index) {
1701 		refcount_inc(&item->refs);
1702 		list_add_tail(&item->readdir_list, ins_list);
1703 		item = __btrfs_next_delayed_item(item);
1704 	}
1705 
1706 	item = __btrfs_first_delayed_deletion_item(delayed_node);
1707 	while (item && item->index <= last_index) {
1708 		refcount_inc(&item->refs);
1709 		list_add_tail(&item->readdir_list, del_list);
1710 		item = __btrfs_next_delayed_item(item);
1711 	}
1712 	mutex_unlock(&delayed_node->mutex);
1713 	/*
1714 	 * This delayed node is still cached in the btrfs inode, so refs
1715 	 * must be > 1 now, and we needn't check it is going to be freed
1716 	 * or not.
1717 	 *
1718 	 * Besides that, this function is used to read dir, we do not
1719 	 * insert/delete delayed items in this period. So we also needn't
1720 	 * requeue or dequeue this delayed node.
1721 	 */
1722 	refcount_dec(&delayed_node->refs);
1723 
1724 	return true;
1725 }
1726 
1727 void btrfs_readdir_put_delayed_items(struct inode *inode,
1728 				     struct list_head *ins_list,
1729 				     struct list_head *del_list)
1730 {
1731 	struct btrfs_delayed_item *curr, *next;
1732 
1733 	list_for_each_entry_safe(curr, next, ins_list, readdir_list) {
1734 		list_del(&curr->readdir_list);
1735 		if (refcount_dec_and_test(&curr->refs))
1736 			kfree(curr);
1737 	}
1738 
1739 	list_for_each_entry_safe(curr, next, del_list, readdir_list) {
1740 		list_del(&curr->readdir_list);
1741 		if (refcount_dec_and_test(&curr->refs))
1742 			kfree(curr);
1743 	}
1744 
1745 	/*
1746 	 * The VFS is going to do up_read(), so we need to downgrade back to a
1747 	 * read lock.
1748 	 */
1749 	downgrade_write(&inode->i_rwsem);
1750 }
1751 
1752 int btrfs_should_delete_dir_index(struct list_head *del_list,
1753 				  u64 index)
1754 {
1755 	struct btrfs_delayed_item *curr;
1756 	int ret = 0;
1757 
1758 	list_for_each_entry(curr, del_list, readdir_list) {
1759 		if (curr->index > index)
1760 			break;
1761 		if (curr->index == index) {
1762 			ret = 1;
1763 			break;
1764 		}
1765 	}
1766 	return ret;
1767 }
1768 
1769 /*
1770  * Read dir info stored in the delayed tree.
1771  */
1772 int btrfs_readdir_delayed_dir_index(struct dir_context *ctx,
1773 				    struct list_head *ins_list)
1774 {
1775 	struct btrfs_dir_item *di;
1776 	struct btrfs_delayed_item *curr, *next;
1777 	struct btrfs_key location;
1778 	char *name;
1779 	int name_len;
1780 	int over = 0;
1781 	unsigned char d_type;
1782 
1783 	/*
1784 	 * Changing the data of the delayed item is impossible. So
1785 	 * we needn't lock them. And we have held i_mutex of the
1786 	 * directory, nobody can delete any directory indexes now.
1787 	 */
1788 	list_for_each_entry_safe(curr, next, ins_list, readdir_list) {
1789 		list_del(&curr->readdir_list);
1790 
1791 		if (curr->index < ctx->pos) {
1792 			if (refcount_dec_and_test(&curr->refs))
1793 				kfree(curr);
1794 			continue;
1795 		}
1796 
1797 		ctx->pos = curr->index;
1798 
1799 		di = (struct btrfs_dir_item *)curr->data;
1800 		name = (char *)(di + 1);
1801 		name_len = btrfs_stack_dir_name_len(di);
1802 
1803 		d_type = fs_ftype_to_dtype(btrfs_dir_flags_to_ftype(di->type));
1804 		btrfs_disk_key_to_cpu(&location, &di->location);
1805 
1806 		over = !dir_emit(ctx, name, name_len,
1807 			       location.objectid, d_type);
1808 
1809 		if (refcount_dec_and_test(&curr->refs))
1810 			kfree(curr);
1811 
1812 		if (over)
1813 			return 1;
1814 		ctx->pos++;
1815 	}
1816 	return 0;
1817 }
1818 
1819 static void fill_stack_inode_item(struct btrfs_trans_handle *trans,
1820 				  struct btrfs_inode_item *inode_item,
1821 				  struct inode *inode)
1822 {
1823 	u64 flags;
1824 
1825 	btrfs_set_stack_inode_uid(inode_item, i_uid_read(inode));
1826 	btrfs_set_stack_inode_gid(inode_item, i_gid_read(inode));
1827 	btrfs_set_stack_inode_size(inode_item, BTRFS_I(inode)->disk_i_size);
1828 	btrfs_set_stack_inode_mode(inode_item, inode->i_mode);
1829 	btrfs_set_stack_inode_nlink(inode_item, inode->i_nlink);
1830 	btrfs_set_stack_inode_nbytes(inode_item, inode_get_bytes(inode));
1831 	btrfs_set_stack_inode_generation(inode_item,
1832 					 BTRFS_I(inode)->generation);
1833 	btrfs_set_stack_inode_sequence(inode_item,
1834 				       inode_peek_iversion(inode));
1835 	btrfs_set_stack_inode_transid(inode_item, trans->transid);
1836 	btrfs_set_stack_inode_rdev(inode_item, inode->i_rdev);
1837 	flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
1838 					  BTRFS_I(inode)->ro_flags);
1839 	btrfs_set_stack_inode_flags(inode_item, flags);
1840 	btrfs_set_stack_inode_block_group(inode_item, 0);
1841 
1842 	btrfs_set_stack_timespec_sec(&inode_item->atime,
1843 				     inode_get_atime_sec(inode));
1844 	btrfs_set_stack_timespec_nsec(&inode_item->atime,
1845 				      inode_get_atime_nsec(inode));
1846 
1847 	btrfs_set_stack_timespec_sec(&inode_item->mtime,
1848 				     inode_get_mtime_sec(inode));
1849 	btrfs_set_stack_timespec_nsec(&inode_item->mtime,
1850 				      inode_get_mtime_nsec(inode));
1851 
1852 	btrfs_set_stack_timespec_sec(&inode_item->ctime,
1853 				     inode_get_ctime_sec(inode));
1854 	btrfs_set_stack_timespec_nsec(&inode_item->ctime,
1855 				      inode_get_ctime_nsec(inode));
1856 
1857 	btrfs_set_stack_timespec_sec(&inode_item->otime, BTRFS_I(inode)->i_otime_sec);
1858 	btrfs_set_stack_timespec_nsec(&inode_item->otime, BTRFS_I(inode)->i_otime_nsec);
1859 }
1860 
1861 int btrfs_fill_inode(struct inode *inode, u32 *rdev)
1862 {
1863 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
1864 	struct btrfs_delayed_node *delayed_node;
1865 	struct btrfs_inode_item *inode_item;
1866 
1867 	delayed_node = btrfs_get_delayed_node(BTRFS_I(inode));
1868 	if (!delayed_node)
1869 		return -ENOENT;
1870 
1871 	mutex_lock(&delayed_node->mutex);
1872 	if (!test_bit(BTRFS_DELAYED_NODE_INODE_DIRTY, &delayed_node->flags)) {
1873 		mutex_unlock(&delayed_node->mutex);
1874 		btrfs_release_delayed_node(delayed_node);
1875 		return -ENOENT;
1876 	}
1877 
1878 	inode_item = &delayed_node->inode_item;
1879 
1880 	i_uid_write(inode, btrfs_stack_inode_uid(inode_item));
1881 	i_gid_write(inode, btrfs_stack_inode_gid(inode_item));
1882 	btrfs_i_size_write(BTRFS_I(inode), btrfs_stack_inode_size(inode_item));
1883 	btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
1884 			round_up(i_size_read(inode), fs_info->sectorsize));
1885 	inode->i_mode = btrfs_stack_inode_mode(inode_item);
1886 	set_nlink(inode, btrfs_stack_inode_nlink(inode_item));
1887 	inode_set_bytes(inode, btrfs_stack_inode_nbytes(inode_item));
1888 	BTRFS_I(inode)->generation = btrfs_stack_inode_generation(inode_item);
1889         BTRFS_I(inode)->last_trans = btrfs_stack_inode_transid(inode_item);
1890 
1891 	inode_set_iversion_queried(inode,
1892 				   btrfs_stack_inode_sequence(inode_item));
1893 	inode->i_rdev = 0;
1894 	*rdev = btrfs_stack_inode_rdev(inode_item);
1895 	btrfs_inode_split_flags(btrfs_stack_inode_flags(inode_item),
1896 				&BTRFS_I(inode)->flags, &BTRFS_I(inode)->ro_flags);
1897 
1898 	inode_set_atime(inode, btrfs_stack_timespec_sec(&inode_item->atime),
1899 			btrfs_stack_timespec_nsec(&inode_item->atime));
1900 
1901 	inode_set_mtime(inode, btrfs_stack_timespec_sec(&inode_item->mtime),
1902 			btrfs_stack_timespec_nsec(&inode_item->mtime));
1903 
1904 	inode_set_ctime(inode, btrfs_stack_timespec_sec(&inode_item->ctime),
1905 			btrfs_stack_timespec_nsec(&inode_item->ctime));
1906 
1907 	BTRFS_I(inode)->i_otime_sec = btrfs_stack_timespec_sec(&inode_item->otime);
1908 	BTRFS_I(inode)->i_otime_nsec = btrfs_stack_timespec_nsec(&inode_item->otime);
1909 
1910 	inode->i_generation = BTRFS_I(inode)->generation;
1911 	BTRFS_I(inode)->index_cnt = (u64)-1;
1912 
1913 	mutex_unlock(&delayed_node->mutex);
1914 	btrfs_release_delayed_node(delayed_node);
1915 	return 0;
1916 }
1917 
1918 int btrfs_delayed_update_inode(struct btrfs_trans_handle *trans,
1919 			       struct btrfs_inode *inode)
1920 {
1921 	struct btrfs_root *root = inode->root;
1922 	struct btrfs_delayed_node *delayed_node;
1923 	int ret = 0;
1924 
1925 	delayed_node = btrfs_get_or_create_delayed_node(inode);
1926 	if (IS_ERR(delayed_node))
1927 		return PTR_ERR(delayed_node);
1928 
1929 	mutex_lock(&delayed_node->mutex);
1930 	if (test_bit(BTRFS_DELAYED_NODE_INODE_DIRTY, &delayed_node->flags)) {
1931 		fill_stack_inode_item(trans, &delayed_node->inode_item,
1932 				      &inode->vfs_inode);
1933 		goto release_node;
1934 	}
1935 
1936 	ret = btrfs_delayed_inode_reserve_metadata(trans, root, delayed_node);
1937 	if (ret)
1938 		goto release_node;
1939 
1940 	fill_stack_inode_item(trans, &delayed_node->inode_item, &inode->vfs_inode);
1941 	set_bit(BTRFS_DELAYED_NODE_INODE_DIRTY, &delayed_node->flags);
1942 	delayed_node->count++;
1943 	atomic_inc(&root->fs_info->delayed_root->items);
1944 release_node:
1945 	mutex_unlock(&delayed_node->mutex);
1946 	btrfs_release_delayed_node(delayed_node);
1947 	return ret;
1948 }
1949 
1950 int btrfs_delayed_delete_inode_ref(struct btrfs_inode *inode)
1951 {
1952 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1953 	struct btrfs_delayed_node *delayed_node;
1954 
1955 	/*
1956 	 * we don't do delayed inode updates during log recovery because it
1957 	 * leads to enospc problems.  This means we also can't do
1958 	 * delayed inode refs
1959 	 */
1960 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
1961 		return -EAGAIN;
1962 
1963 	delayed_node = btrfs_get_or_create_delayed_node(inode);
1964 	if (IS_ERR(delayed_node))
1965 		return PTR_ERR(delayed_node);
1966 
1967 	/*
1968 	 * We don't reserve space for inode ref deletion is because:
1969 	 * - We ONLY do async inode ref deletion for the inode who has only
1970 	 *   one link(i_nlink == 1), it means there is only one inode ref.
1971 	 *   And in most case, the inode ref and the inode item are in the
1972 	 *   same leaf, and we will deal with them at the same time.
1973 	 *   Since we are sure we will reserve the space for the inode item,
1974 	 *   it is unnecessary to reserve space for inode ref deletion.
1975 	 * - If the inode ref and the inode item are not in the same leaf,
1976 	 *   We also needn't worry about enospc problem, because we reserve
1977 	 *   much more space for the inode update than it needs.
1978 	 * - At the worst, we can steal some space from the global reservation.
1979 	 *   It is very rare.
1980 	 */
1981 	mutex_lock(&delayed_node->mutex);
1982 	if (test_bit(BTRFS_DELAYED_NODE_DEL_IREF, &delayed_node->flags))
1983 		goto release_node;
1984 
1985 	set_bit(BTRFS_DELAYED_NODE_DEL_IREF, &delayed_node->flags);
1986 	delayed_node->count++;
1987 	atomic_inc(&fs_info->delayed_root->items);
1988 release_node:
1989 	mutex_unlock(&delayed_node->mutex);
1990 	btrfs_release_delayed_node(delayed_node);
1991 	return 0;
1992 }
1993 
1994 static void __btrfs_kill_delayed_node(struct btrfs_delayed_node *delayed_node)
1995 {
1996 	struct btrfs_root *root = delayed_node->root;
1997 	struct btrfs_fs_info *fs_info = root->fs_info;
1998 	struct btrfs_delayed_item *curr_item, *prev_item;
1999 
2000 	mutex_lock(&delayed_node->mutex);
2001 	curr_item = __btrfs_first_delayed_insertion_item(delayed_node);
2002 	while (curr_item) {
2003 		prev_item = curr_item;
2004 		curr_item = __btrfs_next_delayed_item(prev_item);
2005 		btrfs_release_delayed_item(prev_item);
2006 	}
2007 
2008 	if (delayed_node->index_item_leaves > 0) {
2009 		btrfs_delayed_item_release_leaves(delayed_node,
2010 					  delayed_node->index_item_leaves);
2011 		delayed_node->index_item_leaves = 0;
2012 	}
2013 
2014 	curr_item = __btrfs_first_delayed_deletion_item(delayed_node);
2015 	while (curr_item) {
2016 		btrfs_delayed_item_release_metadata(root, curr_item);
2017 		prev_item = curr_item;
2018 		curr_item = __btrfs_next_delayed_item(prev_item);
2019 		btrfs_release_delayed_item(prev_item);
2020 	}
2021 
2022 	btrfs_release_delayed_iref(delayed_node);
2023 
2024 	if (test_bit(BTRFS_DELAYED_NODE_INODE_DIRTY, &delayed_node->flags)) {
2025 		btrfs_delayed_inode_release_metadata(fs_info, delayed_node, false);
2026 		btrfs_release_delayed_inode(delayed_node);
2027 	}
2028 	mutex_unlock(&delayed_node->mutex);
2029 }
2030 
2031 void btrfs_kill_delayed_inode_items(struct btrfs_inode *inode)
2032 {
2033 	struct btrfs_delayed_node *delayed_node;
2034 
2035 	delayed_node = btrfs_get_delayed_node(inode);
2036 	if (!delayed_node)
2037 		return;
2038 
2039 	__btrfs_kill_delayed_node(delayed_node);
2040 	btrfs_release_delayed_node(delayed_node);
2041 }
2042 
2043 void btrfs_kill_all_delayed_nodes(struct btrfs_root *root)
2044 {
2045 	unsigned long index = 0;
2046 	struct btrfs_delayed_node *delayed_nodes[8];
2047 
2048 	while (1) {
2049 		struct btrfs_delayed_node *node;
2050 		int count;
2051 
2052 		spin_lock(&root->inode_lock);
2053 		if (xa_empty(&root->delayed_nodes)) {
2054 			spin_unlock(&root->inode_lock);
2055 			return;
2056 		}
2057 
2058 		count = 0;
2059 		xa_for_each_start(&root->delayed_nodes, index, node, index) {
2060 			/*
2061 			 * Don't increase refs in case the node is dead and
2062 			 * about to be removed from the tree in the loop below
2063 			 */
2064 			if (refcount_inc_not_zero(&node->refs)) {
2065 				delayed_nodes[count] = node;
2066 				count++;
2067 			}
2068 			if (count >= ARRAY_SIZE(delayed_nodes))
2069 				break;
2070 		}
2071 		spin_unlock(&root->inode_lock);
2072 		index++;
2073 
2074 		for (int i = 0; i < count; i++) {
2075 			__btrfs_kill_delayed_node(delayed_nodes[i]);
2076 			btrfs_release_delayed_node(delayed_nodes[i]);
2077 		}
2078 	}
2079 }
2080 
2081 void btrfs_destroy_delayed_inodes(struct btrfs_fs_info *fs_info)
2082 {
2083 	struct btrfs_delayed_node *curr_node, *prev_node;
2084 
2085 	curr_node = btrfs_first_delayed_node(fs_info->delayed_root);
2086 	while (curr_node) {
2087 		__btrfs_kill_delayed_node(curr_node);
2088 
2089 		prev_node = curr_node;
2090 		curr_node = btrfs_next_delayed_node(curr_node);
2091 		btrfs_release_delayed_node(prev_node);
2092 	}
2093 }
2094 
2095 void btrfs_log_get_delayed_items(struct btrfs_inode *inode,
2096 				 struct list_head *ins_list,
2097 				 struct list_head *del_list)
2098 {
2099 	struct btrfs_delayed_node *node;
2100 	struct btrfs_delayed_item *item;
2101 
2102 	node = btrfs_get_delayed_node(inode);
2103 	if (!node)
2104 		return;
2105 
2106 	mutex_lock(&node->mutex);
2107 	item = __btrfs_first_delayed_insertion_item(node);
2108 	while (item) {
2109 		/*
2110 		 * It's possible that the item is already in a log list. This
2111 		 * can happen in case two tasks are trying to log the same
2112 		 * directory. For example if we have tasks A and task B:
2113 		 *
2114 		 * Task A collected the delayed items into a log list while
2115 		 * under the inode's log_mutex (at btrfs_log_inode()), but it
2116 		 * only releases the items after logging the inodes they point
2117 		 * to (if they are new inodes), which happens after unlocking
2118 		 * the log mutex;
2119 		 *
2120 		 * Task B enters btrfs_log_inode() and acquires the log_mutex
2121 		 * of the same directory inode, before task B releases the
2122 		 * delayed items. This can happen for example when logging some
2123 		 * inode we need to trigger logging of its parent directory, so
2124 		 * logging two files that have the same parent directory can
2125 		 * lead to this.
2126 		 *
2127 		 * If this happens, just ignore delayed items already in a log
2128 		 * list. All the tasks logging the directory are under a log
2129 		 * transaction and whichever finishes first can not sync the log
2130 		 * before the other completes and leaves the log transaction.
2131 		 */
2132 		if (!item->logged && list_empty(&item->log_list)) {
2133 			refcount_inc(&item->refs);
2134 			list_add_tail(&item->log_list, ins_list);
2135 		}
2136 		item = __btrfs_next_delayed_item(item);
2137 	}
2138 
2139 	item = __btrfs_first_delayed_deletion_item(node);
2140 	while (item) {
2141 		/* It may be non-empty, for the same reason mentioned above. */
2142 		if (!item->logged && list_empty(&item->log_list)) {
2143 			refcount_inc(&item->refs);
2144 			list_add_tail(&item->log_list, del_list);
2145 		}
2146 		item = __btrfs_next_delayed_item(item);
2147 	}
2148 	mutex_unlock(&node->mutex);
2149 
2150 	/*
2151 	 * We are called during inode logging, which means the inode is in use
2152 	 * and can not be evicted before we finish logging the inode. So we never
2153 	 * have the last reference on the delayed inode.
2154 	 * Also, we don't use btrfs_release_delayed_node() because that would
2155 	 * requeue the delayed inode (change its order in the list of prepared
2156 	 * nodes) and we don't want to do such change because we don't create or
2157 	 * delete delayed items.
2158 	 */
2159 	ASSERT(refcount_read(&node->refs) > 1);
2160 	refcount_dec(&node->refs);
2161 }
2162 
2163 void btrfs_log_put_delayed_items(struct btrfs_inode *inode,
2164 				 struct list_head *ins_list,
2165 				 struct list_head *del_list)
2166 {
2167 	struct btrfs_delayed_node *node;
2168 	struct btrfs_delayed_item *item;
2169 	struct btrfs_delayed_item *next;
2170 
2171 	node = btrfs_get_delayed_node(inode);
2172 	if (!node)
2173 		return;
2174 
2175 	mutex_lock(&node->mutex);
2176 
2177 	list_for_each_entry_safe(item, next, ins_list, log_list) {
2178 		item->logged = true;
2179 		list_del_init(&item->log_list);
2180 		if (refcount_dec_and_test(&item->refs))
2181 			kfree(item);
2182 	}
2183 
2184 	list_for_each_entry_safe(item, next, del_list, log_list) {
2185 		item->logged = true;
2186 		list_del_init(&item->log_list);
2187 		if (refcount_dec_and_test(&item->refs))
2188 			kfree(item);
2189 	}
2190 
2191 	mutex_unlock(&node->mutex);
2192 
2193 	/*
2194 	 * We are called during inode logging, which means the inode is in use
2195 	 * and can not be evicted before we finish logging the inode. So we never
2196 	 * have the last reference on the delayed inode.
2197 	 * Also, we don't use btrfs_release_delayed_node() because that would
2198 	 * requeue the delayed inode (change its order in the list of prepared
2199 	 * nodes) and we don't want to do such change because we don't create or
2200 	 * delete delayed items.
2201 	 */
2202 	ASSERT(refcount_read(&node->refs) > 1);
2203 	refcount_dec(&node->refs);
2204 }
2205