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