xref: /linux/fs/xfs/libxfs/xfs_da_btree.c (revision e47e2e0ba9103df7b3d25356421e6832c4d0e7be)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
4  * Copyright (c) 2013 Red Hat, Inc.
5  * All Rights Reserved.
6  */
7 #include "xfs.h"
8 #include "xfs_fs.h"
9 #include "xfs_shared.h"
10 #include "xfs_format.h"
11 #include "xfs_log_format.h"
12 #include "xfs_trans_resv.h"
13 #include "xfs_bit.h"
14 #include "xfs_mount.h"
15 #include "xfs_inode.h"
16 #include "xfs_dir2.h"
17 #include "xfs_dir2_priv.h"
18 #include "xfs_trans.h"
19 #include "xfs_bmap.h"
20 #include "xfs_attr_leaf.h"
21 #include "xfs_error.h"
22 #include "xfs_trace.h"
23 #include "xfs_buf_item.h"
24 #include "xfs_log.h"
25 #include "xfs_errortag.h"
26 
27 /*
28  * xfs_da_btree.c
29  *
30  * Routines to implement directories as Btrees of hashed names.
31  */
32 
33 /*========================================================================
34  * Function prototypes for the kernel.
35  *========================================================================*/
36 
37 /*
38  * Routines used for growing the Btree.
39  */
40 STATIC int xfs_da3_root_split(xfs_da_state_t *state,
41 					    xfs_da_state_blk_t *existing_root,
42 					    xfs_da_state_blk_t *new_child);
43 STATIC int xfs_da3_node_split(xfs_da_state_t *state,
44 					    xfs_da_state_blk_t *existing_blk,
45 					    xfs_da_state_blk_t *split_blk,
46 					    xfs_da_state_blk_t *blk_to_add,
47 					    int treelevel,
48 					    int *result);
49 STATIC void xfs_da3_node_rebalance(xfs_da_state_t *state,
50 					 xfs_da_state_blk_t *node_blk_1,
51 					 xfs_da_state_blk_t *node_blk_2);
52 STATIC void xfs_da3_node_add(xfs_da_state_t *state,
53 				   xfs_da_state_blk_t *old_node_blk,
54 				   xfs_da_state_blk_t *new_node_blk);
55 
56 /*
57  * Routines used for shrinking the Btree.
58  */
59 STATIC int xfs_da3_root_join(xfs_da_state_t *state,
60 					   xfs_da_state_blk_t *root_blk);
61 STATIC int xfs_da3_node_toosmall(xfs_da_state_t *state, int *retval);
62 STATIC void xfs_da3_node_remove(xfs_da_state_t *state,
63 					      xfs_da_state_blk_t *drop_blk);
64 STATIC void xfs_da3_node_unbalance(xfs_da_state_t *state,
65 					 xfs_da_state_blk_t *src_node_blk,
66 					 xfs_da_state_blk_t *dst_node_blk);
67 
68 /*
69  * Utility routines.
70  */
71 STATIC int	xfs_da3_blk_unlink(xfs_da_state_t *state,
72 				  xfs_da_state_blk_t *drop_blk,
73 				  xfs_da_state_blk_t *save_blk);
74 
75 
76 struct kmem_cache	*xfs_da_state_cache;	/* anchor for dir/attr state */
77 
78 /*
79  * Allocate a dir-state structure.
80  * We don't put them on the stack since they're large.
81  */
82 struct xfs_da_state *
83 xfs_da_state_alloc(
84 	struct xfs_da_args	*args)
85 {
86 	struct xfs_da_state	*state;
87 
88 	state = kmem_cache_zalloc(xfs_da_state_cache,
89 			GFP_KERNEL | __GFP_NOLOCKDEP | __GFP_NOFAIL);
90 	state->args = args;
91 	state->mp = args->dp->i_mount;
92 	return state;
93 }
94 
95 /*
96  * Kill the altpath contents of a da-state structure.
97  */
98 STATIC void
99 xfs_da_state_kill_altpath(xfs_da_state_t *state)
100 {
101 	int	i;
102 
103 	for (i = 0; i < state->altpath.active; i++)
104 		state->altpath.blk[i].bp = NULL;
105 	state->altpath.active = 0;
106 }
107 
108 /*
109  * Free a da-state structure.
110  */
111 void
112 xfs_da_state_free(xfs_da_state_t *state)
113 {
114 	xfs_da_state_kill_altpath(state);
115 #ifdef DEBUG
116 	memset((char *)state, 0, sizeof(*state));
117 #endif /* DEBUG */
118 	kmem_cache_free(xfs_da_state_cache, state);
119 }
120 
121 void
122 xfs_da_state_reset(
123 	struct xfs_da_state	*state,
124 	struct xfs_da_args	*args)
125 {
126 	xfs_da_state_kill_altpath(state);
127 	memset(state, 0, sizeof(struct xfs_da_state));
128 	state->args = args;
129 	state->mp = state->args->dp->i_mount;
130 }
131 
132 static inline int xfs_dabuf_nfsb(struct xfs_mount *mp, int whichfork)
133 {
134 	if (whichfork == XFS_DATA_FORK)
135 		return mp->m_dir_geo->fsbcount;
136 	return mp->m_attr_geo->fsbcount;
137 }
138 
139 void
140 xfs_da3_node_hdr_from_disk(
141 	struct xfs_mount		*mp,
142 	struct xfs_da3_icnode_hdr	*to,
143 	struct xfs_da_intnode		*from)
144 {
145 	if (xfs_has_crc(mp)) {
146 		struct xfs_da3_intnode	*from3 = (struct xfs_da3_intnode *)from;
147 
148 		to->forw = be32_to_cpu(from3->hdr.info.hdr.forw);
149 		to->back = be32_to_cpu(from3->hdr.info.hdr.back);
150 		to->magic = be16_to_cpu(from3->hdr.info.hdr.magic);
151 		to->count = be16_to_cpu(from3->hdr.__count);
152 		to->level = be16_to_cpu(from3->hdr.__level);
153 		to->btree = from3->__btree;
154 		ASSERT(to->magic == XFS_DA3_NODE_MAGIC);
155 	} else {
156 		to->forw = be32_to_cpu(from->hdr.info.forw);
157 		to->back = be32_to_cpu(from->hdr.info.back);
158 		to->magic = be16_to_cpu(from->hdr.info.magic);
159 		to->count = be16_to_cpu(from->hdr.__count);
160 		to->level = be16_to_cpu(from->hdr.__level);
161 		to->btree = from->__btree;
162 		ASSERT(to->magic == XFS_DA_NODE_MAGIC);
163 	}
164 }
165 
166 void
167 xfs_da3_node_hdr_to_disk(
168 	struct xfs_mount		*mp,
169 	struct xfs_da_intnode		*to,
170 	struct xfs_da3_icnode_hdr	*from)
171 {
172 	if (xfs_has_crc(mp)) {
173 		struct xfs_da3_intnode	*to3 = (struct xfs_da3_intnode *)to;
174 
175 		ASSERT(from->magic == XFS_DA3_NODE_MAGIC);
176 		to3->hdr.info.hdr.forw = cpu_to_be32(from->forw);
177 		to3->hdr.info.hdr.back = cpu_to_be32(from->back);
178 		to3->hdr.info.hdr.magic = cpu_to_be16(from->magic);
179 		to3->hdr.__count = cpu_to_be16(from->count);
180 		to3->hdr.__level = cpu_to_be16(from->level);
181 	} else {
182 		ASSERT(from->magic == XFS_DA_NODE_MAGIC);
183 		to->hdr.info.forw = cpu_to_be32(from->forw);
184 		to->hdr.info.back = cpu_to_be32(from->back);
185 		to->hdr.info.magic = cpu_to_be16(from->magic);
186 		to->hdr.__count = cpu_to_be16(from->count);
187 		to->hdr.__level = cpu_to_be16(from->level);
188 	}
189 }
190 
191 /*
192  * Verify an xfs_da3_blkinfo structure. Note that the da3 fields are only
193  * accessible on v5 filesystems. This header format is common across da node,
194  * attr leaf and dir leaf blocks.
195  */
196 xfs_failaddr_t
197 xfs_da3_blkinfo_verify(
198 	struct xfs_buf		*bp,
199 	struct xfs_da3_blkinfo	*hdr3)
200 {
201 	struct xfs_mount	*mp = bp->b_mount;
202 	struct xfs_da_blkinfo	*hdr = &hdr3->hdr;
203 
204 	if (!xfs_verify_magic16(bp, hdr->magic))
205 		return __this_address;
206 
207 	if (xfs_has_crc(mp)) {
208 		if (!uuid_equal(&hdr3->uuid, &mp->m_sb.sb_meta_uuid))
209 			return __this_address;
210 		if (be64_to_cpu(hdr3->blkno) != xfs_buf_daddr(bp))
211 			return __this_address;
212 		if (!xfs_log_check_lsn(mp, be64_to_cpu(hdr3->lsn)))
213 			return __this_address;
214 	}
215 
216 	return NULL;
217 }
218 
219 static xfs_failaddr_t
220 xfs_da3_node_verify(
221 	struct xfs_buf		*bp)
222 {
223 	struct xfs_mount	*mp = bp->b_mount;
224 	struct xfs_da_intnode	*hdr = bp->b_addr;
225 	struct xfs_da3_icnode_hdr ichdr;
226 	xfs_failaddr_t		fa;
227 
228 	xfs_da3_node_hdr_from_disk(mp, &ichdr, hdr);
229 
230 	fa = xfs_da3_blkinfo_verify(bp, bp->b_addr);
231 	if (fa)
232 		return fa;
233 
234 	if (ichdr.level == 0)
235 		return __this_address;
236 	if (ichdr.level > XFS_DA_NODE_MAXDEPTH)
237 		return __this_address;
238 	if (ichdr.count == 0)
239 		return __this_address;
240 
241 	/*
242 	 * we don't know if the node is for and attribute or directory tree,
243 	 * so only fail if the count is outside both bounds
244 	 */
245 	if (ichdr.count > mp->m_dir_geo->node_ents &&
246 	    ichdr.count > mp->m_attr_geo->node_ents)
247 		return __this_address;
248 
249 	/* XXX: hash order check? */
250 
251 	return NULL;
252 }
253 
254 static void
255 xfs_da3_node_write_verify(
256 	struct xfs_buf	*bp)
257 {
258 	struct xfs_mount	*mp = bp->b_mount;
259 	struct xfs_buf_log_item	*bip = bp->b_log_item;
260 	struct xfs_da3_node_hdr *hdr3 = bp->b_addr;
261 	xfs_failaddr_t		fa;
262 
263 	fa = xfs_da3_node_verify(bp);
264 	if (fa) {
265 		xfs_verifier_error(bp, -EFSCORRUPTED, fa);
266 		return;
267 	}
268 
269 	if (!xfs_has_crc(mp))
270 		return;
271 
272 	if (bip)
273 		hdr3->info.lsn = cpu_to_be64(bip->bli_item.li_lsn);
274 
275 	xfs_buf_update_cksum(bp, XFS_DA3_NODE_CRC_OFF);
276 }
277 
278 /*
279  * leaf/node format detection on trees is sketchy, so a node read can be done on
280  * leaf level blocks when detection identifies the tree as a node format tree
281  * incorrectly. In this case, we need to swap the verifier to match the correct
282  * format of the block being read.
283  */
284 static void
285 xfs_da3_node_read_verify(
286 	struct xfs_buf		*bp)
287 {
288 	struct xfs_da_blkinfo	*info = bp->b_addr;
289 	xfs_failaddr_t		fa;
290 
291 	switch (be16_to_cpu(info->magic)) {
292 		case XFS_DA3_NODE_MAGIC:
293 			if (!xfs_buf_verify_cksum(bp, XFS_DA3_NODE_CRC_OFF)) {
294 				xfs_verifier_error(bp, -EFSBADCRC,
295 						__this_address);
296 				break;
297 			}
298 			fallthrough;
299 		case XFS_DA_NODE_MAGIC:
300 			fa = xfs_da3_node_verify(bp);
301 			if (fa)
302 				xfs_verifier_error(bp, -EFSCORRUPTED, fa);
303 			return;
304 		case XFS_ATTR_LEAF_MAGIC:
305 		case XFS_ATTR3_LEAF_MAGIC:
306 			bp->b_ops = &xfs_attr3_leaf_buf_ops;
307 			bp->b_ops->verify_read(bp);
308 			return;
309 		case XFS_DIR2_LEAFN_MAGIC:
310 		case XFS_DIR3_LEAFN_MAGIC:
311 			bp->b_ops = &xfs_dir3_leafn_buf_ops;
312 			bp->b_ops->verify_read(bp);
313 			return;
314 		default:
315 			xfs_verifier_error(bp, -EFSCORRUPTED, __this_address);
316 			break;
317 	}
318 }
319 
320 /* Verify the structure of a da3 block. */
321 static xfs_failaddr_t
322 xfs_da3_node_verify_struct(
323 	struct xfs_buf		*bp)
324 {
325 	struct xfs_da_blkinfo	*info = bp->b_addr;
326 
327 	switch (be16_to_cpu(info->magic)) {
328 	case XFS_DA3_NODE_MAGIC:
329 	case XFS_DA_NODE_MAGIC:
330 		return xfs_da3_node_verify(bp);
331 	case XFS_ATTR_LEAF_MAGIC:
332 	case XFS_ATTR3_LEAF_MAGIC:
333 		bp->b_ops = &xfs_attr3_leaf_buf_ops;
334 		return bp->b_ops->verify_struct(bp);
335 	case XFS_DIR2_LEAFN_MAGIC:
336 	case XFS_DIR3_LEAFN_MAGIC:
337 		bp->b_ops = &xfs_dir3_leafn_buf_ops;
338 		return bp->b_ops->verify_struct(bp);
339 	default:
340 		return __this_address;
341 	}
342 }
343 
344 const struct xfs_buf_ops xfs_da3_node_buf_ops = {
345 	.name = "xfs_da3_node",
346 	.magic16 = { cpu_to_be16(XFS_DA_NODE_MAGIC),
347 		     cpu_to_be16(XFS_DA3_NODE_MAGIC) },
348 	.verify_read = xfs_da3_node_read_verify,
349 	.verify_write = xfs_da3_node_write_verify,
350 	.verify_struct = xfs_da3_node_verify_struct,
351 };
352 
353 static int
354 xfs_da3_node_set_type(
355 	struct xfs_trans	*tp,
356 	struct xfs_buf		*bp)
357 {
358 	struct xfs_da_blkinfo	*info = bp->b_addr;
359 
360 	switch (be16_to_cpu(info->magic)) {
361 	case XFS_DA_NODE_MAGIC:
362 	case XFS_DA3_NODE_MAGIC:
363 		xfs_trans_buf_set_type(tp, bp, XFS_BLFT_DA_NODE_BUF);
364 		return 0;
365 	case XFS_ATTR_LEAF_MAGIC:
366 	case XFS_ATTR3_LEAF_MAGIC:
367 		xfs_trans_buf_set_type(tp, bp, XFS_BLFT_ATTR_LEAF_BUF);
368 		return 0;
369 	case XFS_DIR2_LEAFN_MAGIC:
370 	case XFS_DIR3_LEAFN_MAGIC:
371 		xfs_trans_buf_set_type(tp, bp, XFS_BLFT_DIR_LEAFN_BUF);
372 		return 0;
373 	default:
374 		XFS_CORRUPTION_ERROR(__func__, XFS_ERRLEVEL_LOW, tp->t_mountp,
375 				info, sizeof(*info));
376 		xfs_trans_brelse(tp, bp);
377 		return -EFSCORRUPTED;
378 	}
379 }
380 
381 int
382 xfs_da3_node_read(
383 	struct xfs_trans	*tp,
384 	struct xfs_inode	*dp,
385 	xfs_dablk_t		bno,
386 	struct xfs_buf		**bpp,
387 	int			whichfork)
388 {
389 	int			error;
390 
391 	error = xfs_da_read_buf(tp, dp, bno, 0, bpp, whichfork,
392 			&xfs_da3_node_buf_ops);
393 	if (error || !*bpp || !tp)
394 		return error;
395 	return xfs_da3_node_set_type(tp, *bpp);
396 }
397 
398 int
399 xfs_da3_node_read_mapped(
400 	struct xfs_trans	*tp,
401 	struct xfs_inode	*dp,
402 	xfs_daddr_t		mappedbno,
403 	struct xfs_buf		**bpp,
404 	int			whichfork)
405 {
406 	struct xfs_mount	*mp = dp->i_mount;
407 	int			error;
408 
409 	error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp, mappedbno,
410 			XFS_FSB_TO_BB(mp, xfs_dabuf_nfsb(mp, whichfork)), 0,
411 			bpp, &xfs_da3_node_buf_ops);
412 	if (error || !*bpp)
413 		return error;
414 
415 	if (whichfork == XFS_ATTR_FORK)
416 		xfs_buf_set_ref(*bpp, XFS_ATTR_BTREE_REF);
417 	else
418 		xfs_buf_set_ref(*bpp, XFS_DIR_BTREE_REF);
419 
420 	if (!tp)
421 		return 0;
422 	return xfs_da3_node_set_type(tp, *bpp);
423 }
424 
425 /*
426  * Copy src directory/attr leaf/node buffer to the dst.
427  * For v5 file systems make sure the right blkno is stamped in.
428  */
429 void
430 xfs_da_buf_copy(
431 	struct xfs_buf *dst,
432 	struct xfs_buf *src,
433 	size_t size)
434 {
435 	struct xfs_da3_blkinfo *da3 = dst->b_addr;
436 
437 	memcpy(dst->b_addr, src->b_addr, size);
438 	dst->b_ops = src->b_ops;
439 	xfs_trans_buf_copy_type(dst, src);
440 	if (xfs_has_crc(dst->b_mount))
441 		da3->blkno = cpu_to_be64(xfs_buf_daddr(dst));
442 }
443 
444 /*========================================================================
445  * Routines used for growing the Btree.
446  *========================================================================*/
447 
448 /*
449  * Create the initial contents of an intermediate node.
450  */
451 int
452 xfs_da3_node_create(
453 	struct xfs_da_args	*args,
454 	xfs_dablk_t		blkno,
455 	int			level,
456 	struct xfs_buf		**bpp,
457 	int			whichfork)
458 {
459 	struct xfs_da_intnode	*node;
460 	struct xfs_trans	*tp = args->trans;
461 	struct xfs_mount	*mp = tp->t_mountp;
462 	struct xfs_da3_icnode_hdr ichdr = {0};
463 	struct xfs_buf		*bp;
464 	int			error;
465 	struct xfs_inode	*dp = args->dp;
466 
467 	trace_xfs_da_node_create(args);
468 	ASSERT(level <= XFS_DA_NODE_MAXDEPTH);
469 
470 	error = xfs_da_get_buf(tp, dp, blkno, &bp, whichfork);
471 	if (error)
472 		return error;
473 	bp->b_ops = &xfs_da3_node_buf_ops;
474 	xfs_trans_buf_set_type(tp, bp, XFS_BLFT_DA_NODE_BUF);
475 	node = bp->b_addr;
476 
477 	if (xfs_has_crc(mp)) {
478 		struct xfs_da3_node_hdr *hdr3 = bp->b_addr;
479 
480 		memset(hdr3, 0, sizeof(struct xfs_da3_node_hdr));
481 		ichdr.magic = XFS_DA3_NODE_MAGIC;
482 		hdr3->info.blkno = cpu_to_be64(xfs_buf_daddr(bp));
483 		hdr3->info.owner = cpu_to_be64(args->dp->i_ino);
484 		uuid_copy(&hdr3->info.uuid, &mp->m_sb.sb_meta_uuid);
485 	} else {
486 		ichdr.magic = XFS_DA_NODE_MAGIC;
487 	}
488 	ichdr.level = level;
489 
490 	xfs_da3_node_hdr_to_disk(dp->i_mount, node, &ichdr);
491 	xfs_trans_log_buf(tp, bp,
492 		XFS_DA_LOGRANGE(node, &node->hdr, args->geo->node_hdr_size));
493 
494 	*bpp = bp;
495 	return 0;
496 }
497 
498 /*
499  * Split a leaf node, rebalance, then possibly split
500  * intermediate nodes, rebalance, etc.
501  */
502 int							/* error */
503 xfs_da3_split(
504 	struct xfs_da_state	*state)
505 {
506 	struct xfs_da_state_blk	*oldblk;
507 	struct xfs_da_state_blk	*newblk;
508 	struct xfs_da_state_blk	*addblk;
509 	struct xfs_da_intnode	*node;
510 	int			max;
511 	int			action = 0;
512 	int			error;
513 	int			i;
514 
515 	trace_xfs_da_split(state->args);
516 
517 	if (XFS_TEST_ERROR(false, state->mp, XFS_ERRTAG_DA_LEAF_SPLIT))
518 		return -EIO;
519 
520 	/*
521 	 * Walk back up the tree splitting/inserting/adjusting as necessary.
522 	 * If we need to insert and there isn't room, split the node, then
523 	 * decide which fragment to insert the new block from below into.
524 	 * Note that we may split the root this way, but we need more fixup.
525 	 */
526 	max = state->path.active - 1;
527 	ASSERT((max >= 0) && (max < XFS_DA_NODE_MAXDEPTH));
528 	ASSERT(state->path.blk[max].magic == XFS_ATTR_LEAF_MAGIC ||
529 	       state->path.blk[max].magic == XFS_DIR2_LEAFN_MAGIC);
530 
531 	addblk = &state->path.blk[max];		/* initial dummy value */
532 	for (i = max; (i >= 0) && addblk; state->path.active--, i--) {
533 		oldblk = &state->path.blk[i];
534 		newblk = &state->altpath.blk[i];
535 
536 		/*
537 		 * If a leaf node then
538 		 *     Allocate a new leaf node, then rebalance across them.
539 		 * else if an intermediate node then
540 		 *     We split on the last layer, must we split the node?
541 		 */
542 		switch (oldblk->magic) {
543 		case XFS_ATTR_LEAF_MAGIC:
544 			error = xfs_attr3_leaf_split(state, oldblk, newblk);
545 			if ((error != 0) && (error != -ENOSPC)) {
546 				return error;	/* GROT: attr is inconsistent */
547 			}
548 			if (!error) {
549 				addblk = newblk;
550 				break;
551 			}
552 			/*
553 			 * Entry wouldn't fit, split the leaf again. The new
554 			 * extrablk will be consumed by xfs_da3_node_split if
555 			 * the node is split.
556 			 */
557 			state->extravalid = 1;
558 			if (state->inleaf) {
559 				state->extraafter = 0;	/* before newblk */
560 				trace_xfs_attr_leaf_split_before(state->args);
561 				error = xfs_attr3_leaf_split(state, oldblk,
562 							    &state->extrablk);
563 			} else {
564 				state->extraafter = 1;	/* after newblk */
565 				trace_xfs_attr_leaf_split_after(state->args);
566 				error = xfs_attr3_leaf_split(state, newblk,
567 							    &state->extrablk);
568 			}
569 			if (error)
570 				return error;	/* GROT: attr inconsistent */
571 			addblk = newblk;
572 			break;
573 		case XFS_DIR2_LEAFN_MAGIC:
574 			error = xfs_dir2_leafn_split(state, oldblk, newblk);
575 			if (error)
576 				return error;
577 			addblk = newblk;
578 			break;
579 		case XFS_DA_NODE_MAGIC:
580 			error = xfs_da3_node_split(state, oldblk, newblk, addblk,
581 							 max - i, &action);
582 			addblk->bp = NULL;
583 			if (error)
584 				return error;	/* GROT: dir is inconsistent */
585 			/*
586 			 * Record the newly split block for the next time thru?
587 			 */
588 			if (action)
589 				addblk = newblk;
590 			else
591 				addblk = NULL;
592 			break;
593 		}
594 
595 		/*
596 		 * Update the btree to show the new hashval for this child.
597 		 */
598 		xfs_da3_fixhashpath(state, &state->path);
599 	}
600 	if (!addblk)
601 		return 0;
602 
603 	/*
604 	 * xfs_da3_node_split() should have consumed any extra blocks we added
605 	 * during a double leaf split in the attr fork. This is guaranteed as
606 	 * we can't be here if the attr fork only has a single leaf block.
607 	 */
608 	ASSERT(state->extravalid == 0 ||
609 	       state->path.blk[max].magic == XFS_DIR2_LEAFN_MAGIC);
610 
611 	/*
612 	 * Split the root node.
613 	 */
614 	ASSERT(state->path.active == 0);
615 	oldblk = &state->path.blk[0];
616 	error = xfs_da3_root_split(state, oldblk, addblk);
617 	if (error)
618 		goto out;
619 
620 	/*
621 	 * Update pointers to the node which used to be block 0 and just got
622 	 * bumped because of the addition of a new root node.  Note that the
623 	 * original block 0 could be at any position in the list of blocks in
624 	 * the tree.
625 	 *
626 	 * Note: the magic numbers and sibling pointers are in the same physical
627 	 * place for both v2 and v3 headers (by design). Hence it doesn't matter
628 	 * which version of the xfs_da_intnode structure we use here as the
629 	 * result will be the same using either structure.
630 	 */
631 	node = oldblk->bp->b_addr;
632 	if (node->hdr.info.forw) {
633 		if (be32_to_cpu(node->hdr.info.forw) != addblk->blkno) {
634 			xfs_buf_mark_corrupt(oldblk->bp);
635 			error = -EFSCORRUPTED;
636 			goto out;
637 		}
638 		node = addblk->bp->b_addr;
639 		node->hdr.info.back = cpu_to_be32(oldblk->blkno);
640 		xfs_trans_log_buf(state->args->trans, addblk->bp,
641 				  XFS_DA_LOGRANGE(node, &node->hdr.info,
642 				  sizeof(node->hdr.info)));
643 	}
644 	node = oldblk->bp->b_addr;
645 	if (node->hdr.info.back) {
646 		if (be32_to_cpu(node->hdr.info.back) != addblk->blkno) {
647 			xfs_buf_mark_corrupt(oldblk->bp);
648 			error = -EFSCORRUPTED;
649 			goto out;
650 		}
651 		node = addblk->bp->b_addr;
652 		node->hdr.info.forw = cpu_to_be32(oldblk->blkno);
653 		xfs_trans_log_buf(state->args->trans, addblk->bp,
654 				  XFS_DA_LOGRANGE(node, &node->hdr.info,
655 				  sizeof(node->hdr.info)));
656 	}
657 out:
658 	addblk->bp = NULL;
659 	return error;
660 }
661 
662 /*
663  * Split the root.  We have to create a new root and point to the two
664  * parts (the split old root) that we just created.  Copy block zero to
665  * the EOF, extending the inode in process.
666  */
667 STATIC int						/* error */
668 xfs_da3_root_split(
669 	struct xfs_da_state	*state,
670 	struct xfs_da_state_blk	*blk1,
671 	struct xfs_da_state_blk	*blk2)
672 {
673 	struct xfs_da_intnode	*node;
674 	struct xfs_da_intnode	*oldroot;
675 	struct xfs_da_node_entry *btree;
676 	struct xfs_da3_icnode_hdr nodehdr;
677 	struct xfs_da_args	*args;
678 	struct xfs_buf		*bp;
679 	struct xfs_inode	*dp;
680 	struct xfs_trans	*tp;
681 	struct xfs_dir2_leaf	*leaf;
682 	xfs_dablk_t		blkno;
683 	int			level;
684 	int			error;
685 	int			size;
686 
687 	trace_xfs_da_root_split(state->args);
688 
689 	/*
690 	 * Copy the existing (incorrect) block from the root node position
691 	 * to a free space somewhere.
692 	 */
693 	args = state->args;
694 	error = xfs_da_grow_inode(args, &blkno);
695 	if (error)
696 		return error;
697 
698 	dp = args->dp;
699 	tp = args->trans;
700 	error = xfs_da_get_buf(tp, dp, blkno, &bp, args->whichfork);
701 	if (error)
702 		return error;
703 	node = bp->b_addr;
704 	oldroot = blk1->bp->b_addr;
705 	if (oldroot->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC) ||
706 	    oldroot->hdr.info.magic == cpu_to_be16(XFS_DA3_NODE_MAGIC)) {
707 		struct xfs_da3_icnode_hdr icnodehdr;
708 
709 		xfs_da3_node_hdr_from_disk(dp->i_mount, &icnodehdr, oldroot);
710 		btree = icnodehdr.btree;
711 		size = (int)((char *)&btree[icnodehdr.count] - (char *)oldroot);
712 		level = icnodehdr.level;
713 	} else {
714 		struct xfs_dir3_icleaf_hdr leafhdr;
715 
716 		leaf = (xfs_dir2_leaf_t *)oldroot;
717 		xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
718 
719 		ASSERT(leafhdr.magic == XFS_DIR2_LEAFN_MAGIC ||
720 		       leafhdr.magic == XFS_DIR3_LEAFN_MAGIC);
721 		size = (int)((char *)&leafhdr.ents[leafhdr.count] -
722 			(char *)leaf);
723 		level = 0;
724 	}
725 
726 	/*
727 	 * Copy old root to new buffer and log it.
728 	 */
729 	xfs_da_buf_copy(bp, blk1->bp, size);
730 	xfs_trans_log_buf(tp, bp, 0, size - 1);
731 
732 	/*
733 	 * Update blk1 to point to new buffer.
734 	 */
735 	blk1->bp = bp;
736 	blk1->blkno = blkno;
737 
738 	/*
739 	 * Set up the new root node.
740 	 */
741 	error = xfs_da3_node_create(args,
742 		(args->whichfork == XFS_DATA_FORK) ? args->geo->leafblk : 0,
743 		level + 1, &bp, args->whichfork);
744 	if (error)
745 		return error;
746 
747 	node = bp->b_addr;
748 	xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr, node);
749 	btree = nodehdr.btree;
750 	btree[0].hashval = cpu_to_be32(blk1->hashval);
751 	btree[0].before = cpu_to_be32(blk1->blkno);
752 	btree[1].hashval = cpu_to_be32(blk2->hashval);
753 	btree[1].before = cpu_to_be32(blk2->blkno);
754 	nodehdr.count = 2;
755 	xfs_da3_node_hdr_to_disk(dp->i_mount, node, &nodehdr);
756 
757 #ifdef DEBUG
758 	if (oldroot->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC) ||
759 	    oldroot->hdr.info.magic == cpu_to_be16(XFS_DIR3_LEAFN_MAGIC)) {
760 		ASSERT(blk1->blkno >= args->geo->leafblk &&
761 		       blk1->blkno < args->geo->freeblk);
762 		ASSERT(blk2->blkno >= args->geo->leafblk &&
763 		       blk2->blkno < args->geo->freeblk);
764 	}
765 #endif
766 
767 	/* Header is already logged by xfs_da_node_create */
768 	xfs_trans_log_buf(tp, bp,
769 		XFS_DA_LOGRANGE(node, btree, sizeof(xfs_da_node_entry_t) * 2));
770 
771 	return 0;
772 }
773 
774 /*
775  * Split the node, rebalance, then add the new entry.
776  */
777 STATIC int						/* error */
778 xfs_da3_node_split(
779 	struct xfs_da_state	*state,
780 	struct xfs_da_state_blk	*oldblk,
781 	struct xfs_da_state_blk	*newblk,
782 	struct xfs_da_state_blk	*addblk,
783 	int			treelevel,
784 	int			*result)
785 {
786 	struct xfs_da_intnode	*node;
787 	struct xfs_da3_icnode_hdr nodehdr;
788 	xfs_dablk_t		blkno;
789 	int			newcount;
790 	int			error;
791 	int			useextra;
792 	struct xfs_inode	*dp = state->args->dp;
793 
794 	trace_xfs_da_node_split(state->args);
795 
796 	node = oldblk->bp->b_addr;
797 	xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr, node);
798 
799 	/*
800 	 * With V2 dirs the extra block is data or freespace.
801 	 */
802 	useextra = state->extravalid && state->args->whichfork == XFS_ATTR_FORK;
803 	newcount = 1 + useextra;
804 	/*
805 	 * Do we have to split the node?
806 	 */
807 	if (nodehdr.count + newcount > state->args->geo->node_ents) {
808 		/*
809 		 * Allocate a new node, add to the doubly linked chain of
810 		 * nodes, then move some of our excess entries into it.
811 		 */
812 		error = xfs_da_grow_inode(state->args, &blkno);
813 		if (error)
814 			return error;	/* GROT: dir is inconsistent */
815 
816 		error = xfs_da3_node_create(state->args, blkno, treelevel,
817 					   &newblk->bp, state->args->whichfork);
818 		if (error)
819 			return error;	/* GROT: dir is inconsistent */
820 		newblk->blkno = blkno;
821 		newblk->magic = XFS_DA_NODE_MAGIC;
822 		xfs_da3_node_rebalance(state, oldblk, newblk);
823 		error = xfs_da3_blk_link(state, oldblk, newblk);
824 		if (error)
825 			return error;
826 		*result = 1;
827 	} else {
828 		*result = 0;
829 	}
830 
831 	/*
832 	 * Insert the new entry(s) into the correct block
833 	 * (updating last hashval in the process).
834 	 *
835 	 * xfs_da3_node_add() inserts BEFORE the given index,
836 	 * and as a result of using node_lookup_int() we always
837 	 * point to a valid entry (not after one), but a split
838 	 * operation always results in a new block whose hashvals
839 	 * FOLLOW the current block.
840 	 *
841 	 * If we had double-split op below us, then add the extra block too.
842 	 */
843 	node = oldblk->bp->b_addr;
844 	xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr, node);
845 	if (oldblk->index <= nodehdr.count) {
846 		oldblk->index++;
847 		xfs_da3_node_add(state, oldblk, addblk);
848 		if (useextra) {
849 			if (state->extraafter)
850 				oldblk->index++;
851 			xfs_da3_node_add(state, oldblk, &state->extrablk);
852 			state->extravalid = 0;
853 		}
854 	} else {
855 		newblk->index++;
856 		xfs_da3_node_add(state, newblk, addblk);
857 		if (useextra) {
858 			if (state->extraafter)
859 				newblk->index++;
860 			xfs_da3_node_add(state, newblk, &state->extrablk);
861 			state->extravalid = 0;
862 		}
863 	}
864 
865 	return 0;
866 }
867 
868 /*
869  * Balance the btree elements between two intermediate nodes,
870  * usually one full and one empty.
871  *
872  * NOTE: if blk2 is empty, then it will get the upper half of blk1.
873  */
874 STATIC void
875 xfs_da3_node_rebalance(
876 	struct xfs_da_state	*state,
877 	struct xfs_da_state_blk	*blk1,
878 	struct xfs_da_state_blk	*blk2)
879 {
880 	struct xfs_da_intnode	*node1;
881 	struct xfs_da_intnode	*node2;
882 	struct xfs_da_node_entry *btree1;
883 	struct xfs_da_node_entry *btree2;
884 	struct xfs_da_node_entry *btree_s;
885 	struct xfs_da_node_entry *btree_d;
886 	struct xfs_da3_icnode_hdr nodehdr1;
887 	struct xfs_da3_icnode_hdr nodehdr2;
888 	struct xfs_trans	*tp;
889 	int			count;
890 	int			tmp;
891 	int			swap = 0;
892 	struct xfs_inode	*dp = state->args->dp;
893 
894 	trace_xfs_da_node_rebalance(state->args);
895 
896 	node1 = blk1->bp->b_addr;
897 	node2 = blk2->bp->b_addr;
898 	xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr1, node1);
899 	xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr2, node2);
900 	btree1 = nodehdr1.btree;
901 	btree2 = nodehdr2.btree;
902 
903 	/*
904 	 * Figure out how many entries need to move, and in which direction.
905 	 * Swap the nodes around if that makes it simpler.
906 	 */
907 	if (nodehdr1.count > 0 && nodehdr2.count > 0 &&
908 	    ((be32_to_cpu(btree2[0].hashval) < be32_to_cpu(btree1[0].hashval)) ||
909 	     (be32_to_cpu(btree2[nodehdr2.count - 1].hashval) <
910 			be32_to_cpu(btree1[nodehdr1.count - 1].hashval)))) {
911 		swap(node1, node2);
912 		xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr1, node1);
913 		xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr2, node2);
914 		btree1 = nodehdr1.btree;
915 		btree2 = nodehdr2.btree;
916 		swap = 1;
917 	}
918 
919 	count = (nodehdr1.count - nodehdr2.count) / 2;
920 	if (count == 0)
921 		return;
922 	tp = state->args->trans;
923 	/*
924 	 * Two cases: high-to-low and low-to-high.
925 	 */
926 	if (count > 0) {
927 		/*
928 		 * Move elements in node2 up to make a hole.
929 		 */
930 		tmp = nodehdr2.count;
931 		if (tmp > 0) {
932 			tmp *= (uint)sizeof(xfs_da_node_entry_t);
933 			btree_s = &btree2[0];
934 			btree_d = &btree2[count];
935 			memmove(btree_d, btree_s, tmp);
936 		}
937 
938 		/*
939 		 * Move the req'd B-tree elements from high in node1 to
940 		 * low in node2.
941 		 */
942 		nodehdr2.count += count;
943 		tmp = count * (uint)sizeof(xfs_da_node_entry_t);
944 		btree_s = &btree1[nodehdr1.count - count];
945 		btree_d = &btree2[0];
946 		memcpy(btree_d, btree_s, tmp);
947 		nodehdr1.count -= count;
948 	} else {
949 		/*
950 		 * Move the req'd B-tree elements from low in node2 to
951 		 * high in node1.
952 		 */
953 		count = -count;
954 		tmp = count * (uint)sizeof(xfs_da_node_entry_t);
955 		btree_s = &btree2[0];
956 		btree_d = &btree1[nodehdr1.count];
957 		memcpy(btree_d, btree_s, tmp);
958 		nodehdr1.count += count;
959 
960 		xfs_trans_log_buf(tp, blk1->bp,
961 			XFS_DA_LOGRANGE(node1, btree_d, tmp));
962 
963 		/*
964 		 * Move elements in node2 down to fill the hole.
965 		 */
966 		tmp  = nodehdr2.count - count;
967 		tmp *= (uint)sizeof(xfs_da_node_entry_t);
968 		btree_s = &btree2[count];
969 		btree_d = &btree2[0];
970 		memmove(btree_d, btree_s, tmp);
971 		nodehdr2.count -= count;
972 	}
973 
974 	/*
975 	 * Log header of node 1 and all current bits of node 2.
976 	 */
977 	xfs_da3_node_hdr_to_disk(dp->i_mount, node1, &nodehdr1);
978 	xfs_trans_log_buf(tp, blk1->bp,
979 		XFS_DA_LOGRANGE(node1, &node1->hdr,
980 				state->args->geo->node_hdr_size));
981 
982 	xfs_da3_node_hdr_to_disk(dp->i_mount, node2, &nodehdr2);
983 	xfs_trans_log_buf(tp, blk2->bp,
984 		XFS_DA_LOGRANGE(node2, &node2->hdr,
985 				state->args->geo->node_hdr_size +
986 				(sizeof(btree2[0]) * nodehdr2.count)));
987 
988 	/*
989 	 * Record the last hashval from each block for upward propagation.
990 	 * (note: don't use the swapped node pointers)
991 	 */
992 	if (swap) {
993 		node1 = blk1->bp->b_addr;
994 		node2 = blk2->bp->b_addr;
995 		xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr1, node1);
996 		xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr2, node2);
997 		btree1 = nodehdr1.btree;
998 		btree2 = nodehdr2.btree;
999 	}
1000 	blk1->hashval = be32_to_cpu(btree1[nodehdr1.count - 1].hashval);
1001 	blk2->hashval = be32_to_cpu(btree2[nodehdr2.count - 1].hashval);
1002 
1003 	/*
1004 	 * Adjust the expected index for insertion.
1005 	 */
1006 	if (blk1->index >= nodehdr1.count) {
1007 		blk2->index = blk1->index - nodehdr1.count;
1008 		blk1->index = nodehdr1.count + 1;	/* make it invalid */
1009 	}
1010 }
1011 
1012 /*
1013  * Add a new entry to an intermediate node.
1014  */
1015 STATIC void
1016 xfs_da3_node_add(
1017 	struct xfs_da_state	*state,
1018 	struct xfs_da_state_blk	*oldblk,
1019 	struct xfs_da_state_blk	*newblk)
1020 {
1021 	struct xfs_da_intnode	*node;
1022 	struct xfs_da3_icnode_hdr nodehdr;
1023 	struct xfs_da_node_entry *btree;
1024 	int			tmp;
1025 	struct xfs_inode	*dp = state->args->dp;
1026 
1027 	trace_xfs_da_node_add(state->args);
1028 
1029 	node = oldblk->bp->b_addr;
1030 	xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr, node);
1031 	btree = nodehdr.btree;
1032 
1033 	ASSERT(oldblk->index >= 0 && oldblk->index <= nodehdr.count);
1034 	ASSERT(newblk->blkno != 0);
1035 	if (state->args->whichfork == XFS_DATA_FORK)
1036 		ASSERT(newblk->blkno >= state->args->geo->leafblk &&
1037 		       newblk->blkno < state->args->geo->freeblk);
1038 
1039 	/*
1040 	 * We may need to make some room before we insert the new node.
1041 	 */
1042 	tmp = 0;
1043 	if (oldblk->index < nodehdr.count) {
1044 		tmp = (nodehdr.count - oldblk->index) * (uint)sizeof(*btree);
1045 		memmove(&btree[oldblk->index + 1], &btree[oldblk->index], tmp);
1046 	}
1047 	btree[oldblk->index].hashval = cpu_to_be32(newblk->hashval);
1048 	btree[oldblk->index].before = cpu_to_be32(newblk->blkno);
1049 	xfs_trans_log_buf(state->args->trans, oldblk->bp,
1050 		XFS_DA_LOGRANGE(node, &btree[oldblk->index],
1051 				tmp + sizeof(*btree)));
1052 
1053 	nodehdr.count += 1;
1054 	xfs_da3_node_hdr_to_disk(dp->i_mount, node, &nodehdr);
1055 	xfs_trans_log_buf(state->args->trans, oldblk->bp,
1056 		XFS_DA_LOGRANGE(node, &node->hdr,
1057 				state->args->geo->node_hdr_size));
1058 
1059 	/*
1060 	 * Copy the last hash value from the oldblk to propagate upwards.
1061 	 */
1062 	oldblk->hashval = be32_to_cpu(btree[nodehdr.count - 1].hashval);
1063 }
1064 
1065 /*========================================================================
1066  * Routines used for shrinking the Btree.
1067  *========================================================================*/
1068 
1069 /*
1070  * Deallocate an empty leaf node, remove it from its parent,
1071  * possibly deallocating that block, etc...
1072  */
1073 int
1074 xfs_da3_join(
1075 	struct xfs_da_state	*state)
1076 {
1077 	struct xfs_da_state_blk	*drop_blk;
1078 	struct xfs_da_state_blk	*save_blk;
1079 	int			action = 0;
1080 	int			error;
1081 
1082 	trace_xfs_da_join(state->args);
1083 
1084 	drop_blk = &state->path.blk[ state->path.active-1 ];
1085 	save_blk = &state->altpath.blk[ state->path.active-1 ];
1086 	ASSERT(state->path.blk[0].magic == XFS_DA_NODE_MAGIC);
1087 	ASSERT(drop_blk->magic == XFS_ATTR_LEAF_MAGIC ||
1088 	       drop_blk->magic == XFS_DIR2_LEAFN_MAGIC);
1089 
1090 	/*
1091 	 * Walk back up the tree joining/deallocating as necessary.
1092 	 * When we stop dropping blocks, break out.
1093 	 */
1094 	for (  ; state->path.active >= 2; drop_blk--, save_blk--,
1095 		 state->path.active--) {
1096 		/*
1097 		 * See if we can combine the block with a neighbor.
1098 		 *   (action == 0) => no options, just leave
1099 		 *   (action == 1) => coalesce, then unlink
1100 		 *   (action == 2) => block empty, unlink it
1101 		 */
1102 		switch (drop_blk->magic) {
1103 		case XFS_ATTR_LEAF_MAGIC:
1104 			error = xfs_attr3_leaf_toosmall(state, &action);
1105 			if (error)
1106 				return error;
1107 			if (action == 0)
1108 				return 0;
1109 			xfs_attr3_leaf_unbalance(state, drop_blk, save_blk);
1110 			break;
1111 		case XFS_DIR2_LEAFN_MAGIC:
1112 			error = xfs_dir2_leafn_toosmall(state, &action);
1113 			if (error)
1114 				return error;
1115 			if (action == 0)
1116 				return 0;
1117 			xfs_dir2_leafn_unbalance(state, drop_blk, save_blk);
1118 			break;
1119 		case XFS_DA_NODE_MAGIC:
1120 			/*
1121 			 * Remove the offending node, fixup hashvals,
1122 			 * check for a toosmall neighbor.
1123 			 */
1124 			xfs_da3_node_remove(state, drop_blk);
1125 			xfs_da3_fixhashpath(state, &state->path);
1126 			error = xfs_da3_node_toosmall(state, &action);
1127 			if (error)
1128 				return error;
1129 			if (action == 0)
1130 				return 0;
1131 			xfs_da3_node_unbalance(state, drop_blk, save_blk);
1132 			break;
1133 		}
1134 		xfs_da3_fixhashpath(state, &state->altpath);
1135 		error = xfs_da3_blk_unlink(state, drop_blk, save_blk);
1136 		xfs_da_state_kill_altpath(state);
1137 		if (error)
1138 			return error;
1139 		error = xfs_da_shrink_inode(state->args, drop_blk->blkno,
1140 							 drop_blk->bp);
1141 		drop_blk->bp = NULL;
1142 		if (error)
1143 			return error;
1144 	}
1145 	/*
1146 	 * We joined all the way to the top.  If it turns out that
1147 	 * we only have one entry in the root, make the child block
1148 	 * the new root.
1149 	 */
1150 	xfs_da3_node_remove(state, drop_blk);
1151 	xfs_da3_fixhashpath(state, &state->path);
1152 	error = xfs_da3_root_join(state, &state->path.blk[0]);
1153 	return error;
1154 }
1155 
1156 #ifdef	DEBUG
1157 static void
1158 xfs_da_blkinfo_onlychild_validate(struct xfs_da_blkinfo *blkinfo, __u16 level)
1159 {
1160 	__be16	magic = blkinfo->magic;
1161 
1162 	if (level == 1) {
1163 		ASSERT(magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC) ||
1164 		       magic == cpu_to_be16(XFS_DIR3_LEAFN_MAGIC) ||
1165 		       magic == cpu_to_be16(XFS_ATTR_LEAF_MAGIC) ||
1166 		       magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC));
1167 	} else {
1168 		ASSERT(magic == cpu_to_be16(XFS_DA_NODE_MAGIC) ||
1169 		       magic == cpu_to_be16(XFS_DA3_NODE_MAGIC));
1170 	}
1171 	ASSERT(!blkinfo->forw);
1172 	ASSERT(!blkinfo->back);
1173 }
1174 #else	/* !DEBUG */
1175 #define	xfs_da_blkinfo_onlychild_validate(blkinfo, level)
1176 #endif	/* !DEBUG */
1177 
1178 /*
1179  * We have only one entry in the root.  Copy the only remaining child of
1180  * the old root to block 0 as the new root node.
1181  */
1182 STATIC int
1183 xfs_da3_root_join(
1184 	struct xfs_da_state	*state,
1185 	struct xfs_da_state_blk	*root_blk)
1186 {
1187 	struct xfs_da_intnode	*oldroot;
1188 	struct xfs_da_args	*args;
1189 	xfs_dablk_t		child;
1190 	struct xfs_buf		*bp;
1191 	struct xfs_da3_icnode_hdr oldroothdr;
1192 	int			error;
1193 	struct xfs_inode	*dp = state->args->dp;
1194 
1195 	trace_xfs_da_root_join(state->args);
1196 
1197 	ASSERT(root_blk->magic == XFS_DA_NODE_MAGIC);
1198 
1199 	args = state->args;
1200 	oldroot = root_blk->bp->b_addr;
1201 	xfs_da3_node_hdr_from_disk(dp->i_mount, &oldroothdr, oldroot);
1202 	ASSERT(oldroothdr.forw == 0);
1203 	ASSERT(oldroothdr.back == 0);
1204 
1205 	/*
1206 	 * If the root has more than one child, then don't do anything.
1207 	 */
1208 	if (oldroothdr.count > 1)
1209 		return 0;
1210 
1211 	/*
1212 	 * Read in the (only) child block, then copy those bytes into
1213 	 * the root block's buffer and free the original child block.
1214 	 */
1215 	child = be32_to_cpu(oldroothdr.btree[0].before);
1216 	ASSERT(child != 0);
1217 	error = xfs_da3_node_read(args->trans, dp, child, &bp, args->whichfork);
1218 	if (error)
1219 		return error;
1220 	xfs_da_blkinfo_onlychild_validate(bp->b_addr, oldroothdr.level);
1221 
1222 	/*
1223 	 * Copy child to root buffer and log it.
1224 	 */
1225 	xfs_da_buf_copy(root_blk->bp, bp, args->geo->blksize);
1226 	xfs_trans_log_buf(args->trans, root_blk->bp, 0,
1227 			  args->geo->blksize - 1);
1228 	/*
1229 	 * Now we can drop the child buffer.
1230 	 */
1231 	error = xfs_da_shrink_inode(args, child, bp);
1232 	return error;
1233 }
1234 
1235 /*
1236  * Check a node block and its neighbors to see if the block should be
1237  * collapsed into one or the other neighbor.  Always keep the block
1238  * with the smaller block number.
1239  * If the current block is over 50% full, don't try to join it, return 0.
1240  * If the block is empty, fill in the state structure and return 2.
1241  * If it can be collapsed, fill in the state structure and return 1.
1242  * If nothing can be done, return 0.
1243  */
1244 STATIC int
1245 xfs_da3_node_toosmall(
1246 	struct xfs_da_state	*state,
1247 	int			*action)
1248 {
1249 	struct xfs_da_intnode	*node;
1250 	struct xfs_da_state_blk	*blk;
1251 	struct xfs_da_blkinfo	*info;
1252 	xfs_dablk_t		blkno;
1253 	struct xfs_buf		*bp;
1254 	struct xfs_da3_icnode_hdr nodehdr;
1255 	int			count;
1256 	int			forward;
1257 	int			error;
1258 	int			retval;
1259 	int			i;
1260 	struct xfs_inode	*dp = state->args->dp;
1261 
1262 	trace_xfs_da_node_toosmall(state->args);
1263 
1264 	/*
1265 	 * Check for the degenerate case of the block being over 50% full.
1266 	 * If so, it's not worth even looking to see if we might be able
1267 	 * to coalesce with a sibling.
1268 	 */
1269 	blk = &state->path.blk[ state->path.active-1 ];
1270 	info = blk->bp->b_addr;
1271 	node = (xfs_da_intnode_t *)info;
1272 	xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr, node);
1273 	if (nodehdr.count > (state->args->geo->node_ents >> 1)) {
1274 		*action = 0;	/* blk over 50%, don't try to join */
1275 		return 0;	/* blk over 50%, don't try to join */
1276 	}
1277 
1278 	/*
1279 	 * Check for the degenerate case of the block being empty.
1280 	 * If the block is empty, we'll simply delete it, no need to
1281 	 * coalesce it with a sibling block.  We choose (arbitrarily)
1282 	 * to merge with the forward block unless it is NULL.
1283 	 */
1284 	if (nodehdr.count == 0) {
1285 		/*
1286 		 * Make altpath point to the block we want to keep and
1287 		 * path point to the block we want to drop (this one).
1288 		 */
1289 		forward = (info->forw != 0);
1290 		memcpy(&state->altpath, &state->path, sizeof(state->path));
1291 		error = xfs_da3_path_shift(state, &state->altpath, forward,
1292 						 0, &retval);
1293 		if (error)
1294 			return error;
1295 		if (retval) {
1296 			*action = 0;
1297 		} else {
1298 			*action = 2;
1299 		}
1300 		return 0;
1301 	}
1302 
1303 	/*
1304 	 * Examine each sibling block to see if we can coalesce with
1305 	 * at least 25% free space to spare.  We need to figure out
1306 	 * whether to merge with the forward or the backward block.
1307 	 * We prefer coalescing with the lower numbered sibling so as
1308 	 * to shrink a directory over time.
1309 	 */
1310 	count  = state->args->geo->node_ents;
1311 	count -= state->args->geo->node_ents >> 2;
1312 	count -= nodehdr.count;
1313 
1314 	/* start with smaller blk num */
1315 	forward = nodehdr.forw < nodehdr.back;
1316 	for (i = 0; i < 2; forward = !forward, i++) {
1317 		struct xfs_da3_icnode_hdr thdr;
1318 		if (forward)
1319 			blkno = nodehdr.forw;
1320 		else
1321 			blkno = nodehdr.back;
1322 		if (blkno == 0)
1323 			continue;
1324 		error = xfs_da3_node_read(state->args->trans, dp, blkno, &bp,
1325 				state->args->whichfork);
1326 		if (error)
1327 			return error;
1328 
1329 		node = bp->b_addr;
1330 		xfs_da3_node_hdr_from_disk(dp->i_mount, &thdr, node);
1331 		xfs_trans_brelse(state->args->trans, bp);
1332 
1333 		if (count - thdr.count >= 0)
1334 			break;	/* fits with at least 25% to spare */
1335 	}
1336 	if (i >= 2) {
1337 		*action = 0;
1338 		return 0;
1339 	}
1340 
1341 	/*
1342 	 * Make altpath point to the block we want to keep (the lower
1343 	 * numbered block) and path point to the block we want to drop.
1344 	 */
1345 	memcpy(&state->altpath, &state->path, sizeof(state->path));
1346 	if (blkno < blk->blkno) {
1347 		error = xfs_da3_path_shift(state, &state->altpath, forward,
1348 						 0, &retval);
1349 	} else {
1350 		error = xfs_da3_path_shift(state, &state->path, forward,
1351 						 0, &retval);
1352 	}
1353 	if (error)
1354 		return error;
1355 	if (retval) {
1356 		*action = 0;
1357 		return 0;
1358 	}
1359 	*action = 1;
1360 	return 0;
1361 }
1362 
1363 /*
1364  * Pick up the last hashvalue from an intermediate node.
1365  */
1366 STATIC uint
1367 xfs_da3_node_lasthash(
1368 	struct xfs_inode	*dp,
1369 	struct xfs_buf		*bp,
1370 	int			*count)
1371 {
1372 	struct xfs_da3_icnode_hdr nodehdr;
1373 
1374 	xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr, bp->b_addr);
1375 	if (count)
1376 		*count = nodehdr.count;
1377 	if (!nodehdr.count)
1378 		return 0;
1379 	return be32_to_cpu(nodehdr.btree[nodehdr.count - 1].hashval);
1380 }
1381 
1382 /*
1383  * Walk back up the tree adjusting hash values as necessary,
1384  * when we stop making changes, return.
1385  */
1386 void
1387 xfs_da3_fixhashpath(
1388 	struct xfs_da_state	*state,
1389 	struct xfs_da_state_path *path)
1390 {
1391 	struct xfs_da_state_blk	*blk;
1392 	struct xfs_da_intnode	*node;
1393 	struct xfs_da_node_entry *btree;
1394 	xfs_dahash_t		lasthash=0;
1395 	int			level;
1396 	int			count;
1397 	struct xfs_inode	*dp = state->args->dp;
1398 
1399 	trace_xfs_da_fixhashpath(state->args);
1400 
1401 	level = path->active-1;
1402 	blk = &path->blk[ level ];
1403 	switch (blk->magic) {
1404 	case XFS_ATTR_LEAF_MAGIC:
1405 		lasthash = xfs_attr_leaf_lasthash(blk->bp, &count);
1406 		if (count == 0)
1407 			return;
1408 		break;
1409 	case XFS_DIR2_LEAFN_MAGIC:
1410 		lasthash = xfs_dir2_leaf_lasthash(dp, blk->bp, &count);
1411 		if (count == 0)
1412 			return;
1413 		break;
1414 	case XFS_DA_NODE_MAGIC:
1415 		lasthash = xfs_da3_node_lasthash(dp, blk->bp, &count);
1416 		if (count == 0)
1417 			return;
1418 		break;
1419 	}
1420 	for (blk--, level--; level >= 0; blk--, level--) {
1421 		struct xfs_da3_icnode_hdr nodehdr;
1422 
1423 		node = blk->bp->b_addr;
1424 		xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr, node);
1425 		btree = nodehdr.btree;
1426 		if (be32_to_cpu(btree[blk->index].hashval) == lasthash)
1427 			break;
1428 		blk->hashval = lasthash;
1429 		btree[blk->index].hashval = cpu_to_be32(lasthash);
1430 		xfs_trans_log_buf(state->args->trans, blk->bp,
1431 				  XFS_DA_LOGRANGE(node, &btree[blk->index],
1432 						  sizeof(*btree)));
1433 
1434 		lasthash = be32_to_cpu(btree[nodehdr.count - 1].hashval);
1435 	}
1436 }
1437 
1438 /*
1439  * Remove an entry from an intermediate node.
1440  */
1441 STATIC void
1442 xfs_da3_node_remove(
1443 	struct xfs_da_state	*state,
1444 	struct xfs_da_state_blk	*drop_blk)
1445 {
1446 	struct xfs_da_intnode	*node;
1447 	struct xfs_da3_icnode_hdr nodehdr;
1448 	struct xfs_da_node_entry *btree;
1449 	int			index;
1450 	int			tmp;
1451 	struct xfs_inode	*dp = state->args->dp;
1452 
1453 	trace_xfs_da_node_remove(state->args);
1454 
1455 	node = drop_blk->bp->b_addr;
1456 	xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr, node);
1457 	ASSERT(drop_blk->index < nodehdr.count);
1458 	ASSERT(drop_blk->index >= 0);
1459 
1460 	/*
1461 	 * Copy over the offending entry, or just zero it out.
1462 	 */
1463 	index = drop_blk->index;
1464 	btree = nodehdr.btree;
1465 	if (index < nodehdr.count - 1) {
1466 		tmp  = nodehdr.count - index - 1;
1467 		tmp *= (uint)sizeof(xfs_da_node_entry_t);
1468 		memmove(&btree[index], &btree[index + 1], tmp);
1469 		xfs_trans_log_buf(state->args->trans, drop_blk->bp,
1470 		    XFS_DA_LOGRANGE(node, &btree[index], tmp));
1471 		index = nodehdr.count - 1;
1472 	}
1473 	memset(&btree[index], 0, sizeof(xfs_da_node_entry_t));
1474 	xfs_trans_log_buf(state->args->trans, drop_blk->bp,
1475 	    XFS_DA_LOGRANGE(node, &btree[index], sizeof(btree[index])));
1476 	nodehdr.count -= 1;
1477 	xfs_da3_node_hdr_to_disk(dp->i_mount, node, &nodehdr);
1478 	xfs_trans_log_buf(state->args->trans, drop_blk->bp,
1479 	    XFS_DA_LOGRANGE(node, &node->hdr, state->args->geo->node_hdr_size));
1480 
1481 	/*
1482 	 * Copy the last hash value from the block to propagate upwards.
1483 	 */
1484 	drop_blk->hashval = be32_to_cpu(btree[index - 1].hashval);
1485 }
1486 
1487 /*
1488  * Unbalance the elements between two intermediate nodes,
1489  * move all Btree elements from one node into another.
1490  */
1491 STATIC void
1492 xfs_da3_node_unbalance(
1493 	struct xfs_da_state	*state,
1494 	struct xfs_da_state_blk	*drop_blk,
1495 	struct xfs_da_state_blk	*save_blk)
1496 {
1497 	struct xfs_da_intnode	*drop_node;
1498 	struct xfs_da_intnode	*save_node;
1499 	struct xfs_da_node_entry *drop_btree;
1500 	struct xfs_da_node_entry *save_btree;
1501 	struct xfs_da3_icnode_hdr drop_hdr;
1502 	struct xfs_da3_icnode_hdr save_hdr;
1503 	struct xfs_trans	*tp;
1504 	int			sindex;
1505 	int			tmp;
1506 	struct xfs_inode	*dp = state->args->dp;
1507 
1508 	trace_xfs_da_node_unbalance(state->args);
1509 
1510 	drop_node = drop_blk->bp->b_addr;
1511 	save_node = save_blk->bp->b_addr;
1512 	xfs_da3_node_hdr_from_disk(dp->i_mount, &drop_hdr, drop_node);
1513 	xfs_da3_node_hdr_from_disk(dp->i_mount, &save_hdr, save_node);
1514 	drop_btree = drop_hdr.btree;
1515 	save_btree = save_hdr.btree;
1516 	tp = state->args->trans;
1517 
1518 	/*
1519 	 * If the dying block has lower hashvals, then move all the
1520 	 * elements in the remaining block up to make a hole.
1521 	 */
1522 	if ((be32_to_cpu(drop_btree[0].hashval) <
1523 			be32_to_cpu(save_btree[0].hashval)) ||
1524 	    (be32_to_cpu(drop_btree[drop_hdr.count - 1].hashval) <
1525 			be32_to_cpu(save_btree[save_hdr.count - 1].hashval))) {
1526 		/* XXX: check this - is memmove dst correct? */
1527 		tmp = save_hdr.count * sizeof(xfs_da_node_entry_t);
1528 		memmove(&save_btree[drop_hdr.count], &save_btree[0], tmp);
1529 
1530 		sindex = 0;
1531 		xfs_trans_log_buf(tp, save_blk->bp,
1532 			XFS_DA_LOGRANGE(save_node, &save_btree[0],
1533 				(save_hdr.count + drop_hdr.count) *
1534 						sizeof(xfs_da_node_entry_t)));
1535 	} else {
1536 		sindex = save_hdr.count;
1537 		xfs_trans_log_buf(tp, save_blk->bp,
1538 			XFS_DA_LOGRANGE(save_node, &save_btree[sindex],
1539 				drop_hdr.count * sizeof(xfs_da_node_entry_t)));
1540 	}
1541 
1542 	/*
1543 	 * Move all the B-tree elements from drop_blk to save_blk.
1544 	 */
1545 	tmp = drop_hdr.count * (uint)sizeof(xfs_da_node_entry_t);
1546 	memcpy(&save_btree[sindex], &drop_btree[0], tmp);
1547 	save_hdr.count += drop_hdr.count;
1548 
1549 	xfs_da3_node_hdr_to_disk(dp->i_mount, save_node, &save_hdr);
1550 	xfs_trans_log_buf(tp, save_blk->bp,
1551 		XFS_DA_LOGRANGE(save_node, &save_node->hdr,
1552 				state->args->geo->node_hdr_size));
1553 
1554 	/*
1555 	 * Save the last hashval in the remaining block for upward propagation.
1556 	 */
1557 	save_blk->hashval = be32_to_cpu(save_btree[save_hdr.count - 1].hashval);
1558 }
1559 
1560 /*========================================================================
1561  * Routines used for finding things in the Btree.
1562  *========================================================================*/
1563 
1564 /*
1565  * Walk down the Btree looking for a particular filename, filling
1566  * in the state structure as we go.
1567  *
1568  * We will set the state structure to point to each of the elements
1569  * in each of the nodes where either the hashval is or should be.
1570  *
1571  * We support duplicate hashval's so for each entry in the current
1572  * node that could contain the desired hashval, descend.  This is a
1573  * pruned depth-first tree search.
1574  */
1575 int							/* error */
1576 xfs_da3_node_lookup_int(
1577 	struct xfs_da_state	*state,
1578 	int			*result)
1579 {
1580 	struct xfs_da_state_blk	*blk;
1581 	struct xfs_da_blkinfo	*curr;
1582 	struct xfs_da_intnode	*node;
1583 	struct xfs_da_node_entry *btree;
1584 	struct xfs_da3_icnode_hdr nodehdr;
1585 	struct xfs_da_args	*args;
1586 	xfs_dablk_t		blkno;
1587 	xfs_dahash_t		hashval;
1588 	xfs_dahash_t		btreehashval;
1589 	int			probe;
1590 	int			span;
1591 	int			max;
1592 	int			error;
1593 	int			retval;
1594 	unsigned int		expected_level = 0;
1595 	uint16_t		magic;
1596 	struct xfs_inode	*dp = state->args->dp;
1597 
1598 	args = state->args;
1599 
1600 	/*
1601 	 * Descend thru the B-tree searching each level for the right
1602 	 * node to use, until the right hashval is found.
1603 	 */
1604 	blkno = args->geo->leafblk;
1605 	for (blk = &state->path.blk[0], state->path.active = 1;
1606 			 state->path.active <= XFS_DA_NODE_MAXDEPTH;
1607 			 blk++, state->path.active++) {
1608 		/*
1609 		 * Read the next node down in the tree.
1610 		 */
1611 		blk->blkno = blkno;
1612 		error = xfs_da3_node_read(args->trans, args->dp, blkno,
1613 					&blk->bp, args->whichfork);
1614 		if (error) {
1615 			blk->blkno = 0;
1616 			state->path.active--;
1617 			return error;
1618 		}
1619 		curr = blk->bp->b_addr;
1620 		magic = be16_to_cpu(curr->magic);
1621 
1622 		if (magic == XFS_ATTR_LEAF_MAGIC ||
1623 		    magic == XFS_ATTR3_LEAF_MAGIC) {
1624 			blk->magic = XFS_ATTR_LEAF_MAGIC;
1625 			blk->hashval = xfs_attr_leaf_lasthash(blk->bp, NULL);
1626 			break;
1627 		}
1628 
1629 		if (magic == XFS_DIR2_LEAFN_MAGIC ||
1630 		    magic == XFS_DIR3_LEAFN_MAGIC) {
1631 			blk->magic = XFS_DIR2_LEAFN_MAGIC;
1632 			blk->hashval = xfs_dir2_leaf_lasthash(args->dp,
1633 							      blk->bp, NULL);
1634 			break;
1635 		}
1636 
1637 		if (magic != XFS_DA_NODE_MAGIC && magic != XFS_DA3_NODE_MAGIC) {
1638 			xfs_buf_mark_corrupt(blk->bp);
1639 			return -EFSCORRUPTED;
1640 		}
1641 
1642 		blk->magic = XFS_DA_NODE_MAGIC;
1643 
1644 		/*
1645 		 * Search an intermediate node for a match.
1646 		 */
1647 		node = blk->bp->b_addr;
1648 		xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr, node);
1649 		btree = nodehdr.btree;
1650 
1651 		/* Tree taller than we can handle; bail out! */
1652 		if (nodehdr.level >= XFS_DA_NODE_MAXDEPTH) {
1653 			xfs_buf_mark_corrupt(blk->bp);
1654 			return -EFSCORRUPTED;
1655 		}
1656 
1657 		/* Check the level from the root. */
1658 		if (blkno == args->geo->leafblk)
1659 			expected_level = nodehdr.level - 1;
1660 		else if (expected_level != nodehdr.level) {
1661 			xfs_buf_mark_corrupt(blk->bp);
1662 			return -EFSCORRUPTED;
1663 		} else
1664 			expected_level--;
1665 
1666 		max = nodehdr.count;
1667 		blk->hashval = be32_to_cpu(btree[max - 1].hashval);
1668 
1669 		/*
1670 		 * Binary search.  (note: small blocks will skip loop)
1671 		 */
1672 		probe = span = max / 2;
1673 		hashval = args->hashval;
1674 		while (span > 4) {
1675 			span /= 2;
1676 			btreehashval = be32_to_cpu(btree[probe].hashval);
1677 			if (btreehashval < hashval)
1678 				probe += span;
1679 			else if (btreehashval > hashval)
1680 				probe -= span;
1681 			else
1682 				break;
1683 		}
1684 		ASSERT((probe >= 0) && (probe < max));
1685 		ASSERT((span <= 4) ||
1686 			(be32_to_cpu(btree[probe].hashval) == hashval));
1687 
1688 		/*
1689 		 * Since we may have duplicate hashval's, find the first
1690 		 * matching hashval in the node.
1691 		 */
1692 		while (probe > 0 &&
1693 		       be32_to_cpu(btree[probe].hashval) >= hashval) {
1694 			probe--;
1695 		}
1696 		while (probe < max &&
1697 		       be32_to_cpu(btree[probe].hashval) < hashval) {
1698 			probe++;
1699 		}
1700 
1701 		/*
1702 		 * Pick the right block to descend on.
1703 		 */
1704 		if (probe == max) {
1705 			blk->index = max - 1;
1706 			blkno = be32_to_cpu(btree[max - 1].before);
1707 		} else {
1708 			blk->index = probe;
1709 			blkno = be32_to_cpu(btree[probe].before);
1710 		}
1711 
1712 		/* We can't point back to the root. */
1713 		if (XFS_IS_CORRUPT(dp->i_mount, blkno == args->geo->leafblk))
1714 			return -EFSCORRUPTED;
1715 	}
1716 
1717 	if (XFS_IS_CORRUPT(dp->i_mount, expected_level != 0))
1718 		return -EFSCORRUPTED;
1719 
1720 	/*
1721 	 * A leaf block that ends in the hashval that we are interested in
1722 	 * (final hashval == search hashval) means that the next block may
1723 	 * contain more entries with the same hashval, shift upward to the
1724 	 * next leaf and keep searching.
1725 	 */
1726 	for (;;) {
1727 		if (blk->magic == XFS_DIR2_LEAFN_MAGIC) {
1728 			retval = xfs_dir2_leafn_lookup_int(blk->bp, args,
1729 							&blk->index, state);
1730 		} else if (blk->magic == XFS_ATTR_LEAF_MAGIC) {
1731 			retval = xfs_attr3_leaf_lookup_int(blk->bp, args);
1732 			blk->index = args->index;
1733 			args->blkno = blk->blkno;
1734 		} else {
1735 			ASSERT(0);
1736 			return -EFSCORRUPTED;
1737 		}
1738 		if (((retval == -ENOENT) || (retval == -ENOATTR)) &&
1739 		    (blk->hashval == args->hashval)) {
1740 			error = xfs_da3_path_shift(state, &state->path, 1, 1,
1741 							 &retval);
1742 			if (error)
1743 				return error;
1744 			if (retval == 0) {
1745 				continue;
1746 			} else if (blk->magic == XFS_ATTR_LEAF_MAGIC) {
1747 				/* path_shift() gives ENOENT */
1748 				retval = -ENOATTR;
1749 			}
1750 		}
1751 		break;
1752 	}
1753 	*result = retval;
1754 	return 0;
1755 }
1756 
1757 /*========================================================================
1758  * Utility routines.
1759  *========================================================================*/
1760 
1761 /*
1762  * Compare two intermediate nodes for "order".
1763  */
1764 STATIC int
1765 xfs_da3_node_order(
1766 	struct xfs_inode *dp,
1767 	struct xfs_buf	*node1_bp,
1768 	struct xfs_buf	*node2_bp)
1769 {
1770 	struct xfs_da_intnode	*node1;
1771 	struct xfs_da_intnode	*node2;
1772 	struct xfs_da_node_entry *btree1;
1773 	struct xfs_da_node_entry *btree2;
1774 	struct xfs_da3_icnode_hdr node1hdr;
1775 	struct xfs_da3_icnode_hdr node2hdr;
1776 
1777 	node1 = node1_bp->b_addr;
1778 	node2 = node2_bp->b_addr;
1779 	xfs_da3_node_hdr_from_disk(dp->i_mount, &node1hdr, node1);
1780 	xfs_da3_node_hdr_from_disk(dp->i_mount, &node2hdr, node2);
1781 	btree1 = node1hdr.btree;
1782 	btree2 = node2hdr.btree;
1783 
1784 	if (node1hdr.count > 0 && node2hdr.count > 0 &&
1785 	    ((be32_to_cpu(btree2[0].hashval) < be32_to_cpu(btree1[0].hashval)) ||
1786 	     (be32_to_cpu(btree2[node2hdr.count - 1].hashval) <
1787 	      be32_to_cpu(btree1[node1hdr.count - 1].hashval)))) {
1788 		return 1;
1789 	}
1790 	return 0;
1791 }
1792 
1793 /*
1794  * Link a new block into a doubly linked list of blocks (of whatever type).
1795  */
1796 int							/* error */
1797 xfs_da3_blk_link(
1798 	struct xfs_da_state	*state,
1799 	struct xfs_da_state_blk	*old_blk,
1800 	struct xfs_da_state_blk	*new_blk)
1801 {
1802 	struct xfs_da_blkinfo	*old_info;
1803 	struct xfs_da_blkinfo	*new_info;
1804 	struct xfs_da_blkinfo	*tmp_info;
1805 	struct xfs_da_args	*args;
1806 	struct xfs_buf		*bp;
1807 	int			before = 0;
1808 	int			error;
1809 	struct xfs_inode	*dp = state->args->dp;
1810 
1811 	/*
1812 	 * Set up environment.
1813 	 */
1814 	args = state->args;
1815 	ASSERT(args != NULL);
1816 	old_info = old_blk->bp->b_addr;
1817 	new_info = new_blk->bp->b_addr;
1818 	ASSERT(old_blk->magic == XFS_DA_NODE_MAGIC ||
1819 	       old_blk->magic == XFS_DIR2_LEAFN_MAGIC ||
1820 	       old_blk->magic == XFS_ATTR_LEAF_MAGIC);
1821 
1822 	switch (old_blk->magic) {
1823 	case XFS_ATTR_LEAF_MAGIC:
1824 		before = xfs_attr_leaf_order(old_blk->bp, new_blk->bp);
1825 		break;
1826 	case XFS_DIR2_LEAFN_MAGIC:
1827 		before = xfs_dir2_leafn_order(dp, old_blk->bp, new_blk->bp);
1828 		break;
1829 	case XFS_DA_NODE_MAGIC:
1830 		before = xfs_da3_node_order(dp, old_blk->bp, new_blk->bp);
1831 		break;
1832 	}
1833 
1834 	/*
1835 	 * Link blocks in appropriate order.
1836 	 */
1837 	if (before) {
1838 		/*
1839 		 * Link new block in before existing block.
1840 		 */
1841 		trace_xfs_da_link_before(args);
1842 		new_info->forw = cpu_to_be32(old_blk->blkno);
1843 		new_info->back = old_info->back;
1844 		if (old_info->back) {
1845 			error = xfs_da3_node_read(args->trans, dp,
1846 						be32_to_cpu(old_info->back),
1847 						&bp, args->whichfork);
1848 			if (error)
1849 				return error;
1850 			ASSERT(bp != NULL);
1851 			tmp_info = bp->b_addr;
1852 			ASSERT(tmp_info->magic == old_info->magic);
1853 			ASSERT(be32_to_cpu(tmp_info->forw) == old_blk->blkno);
1854 			tmp_info->forw = cpu_to_be32(new_blk->blkno);
1855 			xfs_trans_log_buf(args->trans, bp, 0, sizeof(*tmp_info)-1);
1856 		}
1857 		old_info->back = cpu_to_be32(new_blk->blkno);
1858 	} else {
1859 		/*
1860 		 * Link new block in after existing block.
1861 		 */
1862 		trace_xfs_da_link_after(args);
1863 		new_info->forw = old_info->forw;
1864 		new_info->back = cpu_to_be32(old_blk->blkno);
1865 		if (old_info->forw) {
1866 			error = xfs_da3_node_read(args->trans, dp,
1867 						be32_to_cpu(old_info->forw),
1868 						&bp, args->whichfork);
1869 			if (error)
1870 				return error;
1871 			ASSERT(bp != NULL);
1872 			tmp_info = bp->b_addr;
1873 			ASSERT(tmp_info->magic == old_info->magic);
1874 			ASSERT(be32_to_cpu(tmp_info->back) == old_blk->blkno);
1875 			tmp_info->back = cpu_to_be32(new_blk->blkno);
1876 			xfs_trans_log_buf(args->trans, bp, 0, sizeof(*tmp_info)-1);
1877 		}
1878 		old_info->forw = cpu_to_be32(new_blk->blkno);
1879 	}
1880 
1881 	xfs_trans_log_buf(args->trans, old_blk->bp, 0, sizeof(*tmp_info) - 1);
1882 	xfs_trans_log_buf(args->trans, new_blk->bp, 0, sizeof(*tmp_info) - 1);
1883 	return 0;
1884 }
1885 
1886 /*
1887  * Unlink a block from a doubly linked list of blocks.
1888  */
1889 STATIC int						/* error */
1890 xfs_da3_blk_unlink(
1891 	struct xfs_da_state	*state,
1892 	struct xfs_da_state_blk	*drop_blk,
1893 	struct xfs_da_state_blk	*save_blk)
1894 {
1895 	struct xfs_da_blkinfo	*drop_info;
1896 	struct xfs_da_blkinfo	*save_info;
1897 	struct xfs_da_blkinfo	*tmp_info;
1898 	struct xfs_da_args	*args;
1899 	struct xfs_buf		*bp;
1900 	int			error;
1901 
1902 	/*
1903 	 * Set up environment.
1904 	 */
1905 	args = state->args;
1906 	ASSERT(args != NULL);
1907 	save_info = save_blk->bp->b_addr;
1908 	drop_info = drop_blk->bp->b_addr;
1909 	ASSERT(save_blk->magic == XFS_DA_NODE_MAGIC ||
1910 	       save_blk->magic == XFS_DIR2_LEAFN_MAGIC ||
1911 	       save_blk->magic == XFS_ATTR_LEAF_MAGIC);
1912 	ASSERT(save_blk->magic == drop_blk->magic);
1913 	ASSERT((be32_to_cpu(save_info->forw) == drop_blk->blkno) ||
1914 	       (be32_to_cpu(save_info->back) == drop_blk->blkno));
1915 	ASSERT((be32_to_cpu(drop_info->forw) == save_blk->blkno) ||
1916 	       (be32_to_cpu(drop_info->back) == save_blk->blkno));
1917 
1918 	/*
1919 	 * Unlink the leaf block from the doubly linked chain of leaves.
1920 	 */
1921 	if (be32_to_cpu(save_info->back) == drop_blk->blkno) {
1922 		trace_xfs_da_unlink_back(args);
1923 		save_info->back = drop_info->back;
1924 		if (drop_info->back) {
1925 			error = xfs_da3_node_read(args->trans, args->dp,
1926 						be32_to_cpu(drop_info->back),
1927 						&bp, args->whichfork);
1928 			if (error)
1929 				return error;
1930 			ASSERT(bp != NULL);
1931 			tmp_info = bp->b_addr;
1932 			ASSERT(tmp_info->magic == save_info->magic);
1933 			ASSERT(be32_to_cpu(tmp_info->forw) == drop_blk->blkno);
1934 			tmp_info->forw = cpu_to_be32(save_blk->blkno);
1935 			xfs_trans_log_buf(args->trans, bp, 0,
1936 						    sizeof(*tmp_info) - 1);
1937 		}
1938 	} else {
1939 		trace_xfs_da_unlink_forward(args);
1940 		save_info->forw = drop_info->forw;
1941 		if (drop_info->forw) {
1942 			error = xfs_da3_node_read(args->trans, args->dp,
1943 						be32_to_cpu(drop_info->forw),
1944 						&bp, args->whichfork);
1945 			if (error)
1946 				return error;
1947 			ASSERT(bp != NULL);
1948 			tmp_info = bp->b_addr;
1949 			ASSERT(tmp_info->magic == save_info->magic);
1950 			ASSERT(be32_to_cpu(tmp_info->back) == drop_blk->blkno);
1951 			tmp_info->back = cpu_to_be32(save_blk->blkno);
1952 			xfs_trans_log_buf(args->trans, bp, 0,
1953 						    sizeof(*tmp_info) - 1);
1954 		}
1955 	}
1956 
1957 	xfs_trans_log_buf(args->trans, save_blk->bp, 0, sizeof(*save_info) - 1);
1958 	return 0;
1959 }
1960 
1961 /*
1962  * Move a path "forward" or "!forward" one block at the current level.
1963  *
1964  * This routine will adjust a "path" to point to the next block
1965  * "forward" (higher hashvalues) or "!forward" (lower hashvals) in the
1966  * Btree, including updating pointers to the intermediate nodes between
1967  * the new bottom and the root.
1968  */
1969 int							/* error */
1970 xfs_da3_path_shift(
1971 	struct xfs_da_state	*state,
1972 	struct xfs_da_state_path *path,
1973 	int			forward,
1974 	int			release,
1975 	int			*result)
1976 {
1977 	struct xfs_da_state_blk	*blk;
1978 	struct xfs_da_blkinfo	*info;
1979 	struct xfs_da_args	*args;
1980 	struct xfs_da_node_entry *btree;
1981 	struct xfs_da3_icnode_hdr nodehdr;
1982 	struct xfs_buf		*bp;
1983 	xfs_dablk_t		blkno = 0;
1984 	int			level;
1985 	int			error;
1986 	struct xfs_inode	*dp = state->args->dp;
1987 
1988 	trace_xfs_da_path_shift(state->args);
1989 
1990 	/*
1991 	 * Roll up the Btree looking for the first block where our
1992 	 * current index is not at the edge of the block.  Note that
1993 	 * we skip the bottom layer because we want the sibling block.
1994 	 */
1995 	args = state->args;
1996 	ASSERT(args != NULL);
1997 	ASSERT(path != NULL);
1998 	ASSERT((path->active > 0) && (path->active < XFS_DA_NODE_MAXDEPTH));
1999 	level = (path->active-1) - 1;	/* skip bottom layer in path */
2000 	for (; level >= 0; level--) {
2001 		blk = &path->blk[level];
2002 		xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr,
2003 					   blk->bp->b_addr);
2004 
2005 		if (forward && (blk->index < nodehdr.count - 1)) {
2006 			blk->index++;
2007 			blkno = be32_to_cpu(nodehdr.btree[blk->index].before);
2008 			break;
2009 		} else if (!forward && (blk->index > 0)) {
2010 			blk->index--;
2011 			blkno = be32_to_cpu(nodehdr.btree[blk->index].before);
2012 			break;
2013 		}
2014 	}
2015 	if (level < 0) {
2016 		*result = -ENOENT;	/* we're out of our tree */
2017 		ASSERT(args->op_flags & XFS_DA_OP_OKNOENT);
2018 		return 0;
2019 	}
2020 
2021 	/*
2022 	 * Roll down the edge of the subtree until we reach the
2023 	 * same depth we were at originally.
2024 	 */
2025 	for (blk++, level++; level < path->active; blk++, level++) {
2026 		/*
2027 		 * Read the next child block into a local buffer.
2028 		 */
2029 		error = xfs_da3_node_read(args->trans, dp, blkno, &bp,
2030 					  args->whichfork);
2031 		if (error)
2032 			return error;
2033 
2034 		/*
2035 		 * Release the old block (if it's dirty, the trans doesn't
2036 		 * actually let go) and swap the local buffer into the path
2037 		 * structure. This ensures failure of the above read doesn't set
2038 		 * a NULL buffer in an active slot in the path.
2039 		 */
2040 		if (release)
2041 			xfs_trans_brelse(args->trans, blk->bp);
2042 		blk->blkno = blkno;
2043 		blk->bp = bp;
2044 
2045 		info = blk->bp->b_addr;
2046 		ASSERT(info->magic == cpu_to_be16(XFS_DA_NODE_MAGIC) ||
2047 		       info->magic == cpu_to_be16(XFS_DA3_NODE_MAGIC) ||
2048 		       info->magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC) ||
2049 		       info->magic == cpu_to_be16(XFS_DIR3_LEAFN_MAGIC) ||
2050 		       info->magic == cpu_to_be16(XFS_ATTR_LEAF_MAGIC) ||
2051 		       info->magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC));
2052 
2053 
2054 		/*
2055 		 * Note: we flatten the magic number to a single type so we
2056 		 * don't have to compare against crc/non-crc types elsewhere.
2057 		 */
2058 		switch (be16_to_cpu(info->magic)) {
2059 		case XFS_DA_NODE_MAGIC:
2060 		case XFS_DA3_NODE_MAGIC:
2061 			blk->magic = XFS_DA_NODE_MAGIC;
2062 			xfs_da3_node_hdr_from_disk(dp->i_mount, &nodehdr,
2063 						   bp->b_addr);
2064 			btree = nodehdr.btree;
2065 			blk->hashval = be32_to_cpu(btree[nodehdr.count - 1].hashval);
2066 			if (forward)
2067 				blk->index = 0;
2068 			else
2069 				blk->index = nodehdr.count - 1;
2070 			blkno = be32_to_cpu(btree[blk->index].before);
2071 			break;
2072 		case XFS_ATTR_LEAF_MAGIC:
2073 		case XFS_ATTR3_LEAF_MAGIC:
2074 			blk->magic = XFS_ATTR_LEAF_MAGIC;
2075 			ASSERT(level == path->active-1);
2076 			blk->index = 0;
2077 			blk->hashval = xfs_attr_leaf_lasthash(blk->bp, NULL);
2078 			break;
2079 		case XFS_DIR2_LEAFN_MAGIC:
2080 		case XFS_DIR3_LEAFN_MAGIC:
2081 			blk->magic = XFS_DIR2_LEAFN_MAGIC;
2082 			ASSERT(level == path->active-1);
2083 			blk->index = 0;
2084 			blk->hashval = xfs_dir2_leaf_lasthash(args->dp,
2085 							      blk->bp, NULL);
2086 			break;
2087 		default:
2088 			ASSERT(0);
2089 			break;
2090 		}
2091 	}
2092 	*result = 0;
2093 	return 0;
2094 }
2095 
2096 
2097 /*========================================================================
2098  * Utility routines.
2099  *========================================================================*/
2100 
2101 /*
2102  * Implement a simple hash on a character string.
2103  * Rotate the hash value by 7 bits, then XOR each character in.
2104  * This is implemented with some source-level loop unrolling.
2105  */
2106 xfs_dahash_t
2107 xfs_da_hashname(const uint8_t *name, int namelen)
2108 {
2109 	xfs_dahash_t hash;
2110 
2111 	/*
2112 	 * Do four characters at a time as long as we can.
2113 	 */
2114 	for (hash = 0; namelen >= 4; namelen -= 4, name += 4)
2115 		hash = (name[0] << 21) ^ (name[1] << 14) ^ (name[2] << 7) ^
2116 		       (name[3] << 0) ^ rol32(hash, 7 * 4);
2117 
2118 	/*
2119 	 * Now do the rest of the characters.
2120 	 */
2121 	switch (namelen) {
2122 	case 3:
2123 		return (name[0] << 14) ^ (name[1] << 7) ^ (name[2] << 0) ^
2124 		       rol32(hash, 7 * 3);
2125 	case 2:
2126 		return (name[0] << 7) ^ (name[1] << 0) ^ rol32(hash, 7 * 2);
2127 	case 1:
2128 		return (name[0] << 0) ^ rol32(hash, 7 * 1);
2129 	default: /* case 0: */
2130 		return hash;
2131 	}
2132 }
2133 
2134 enum xfs_dacmp
2135 xfs_da_compname(
2136 	struct xfs_da_args *args,
2137 	const unsigned char *name,
2138 	int		len)
2139 {
2140 	return (args->namelen == len && memcmp(args->name, name, len) == 0) ?
2141 					XFS_CMP_EXACT : XFS_CMP_DIFFERENT;
2142 }
2143 
2144 int
2145 xfs_da_grow_inode_int(
2146 	struct xfs_da_args	*args,
2147 	xfs_fileoff_t		*bno,
2148 	int			count)
2149 {
2150 	struct xfs_trans	*tp = args->trans;
2151 	struct xfs_inode	*dp = args->dp;
2152 	int			w = args->whichfork;
2153 	xfs_rfsblock_t		nblks = dp->i_nblocks;
2154 	struct xfs_bmbt_irec	map, *mapp;
2155 	int			nmap, error, got, i, mapi;
2156 
2157 	/*
2158 	 * Find a spot in the file space to put the new block.
2159 	 */
2160 	error = xfs_bmap_first_unused(tp, dp, count, bno, w);
2161 	if (error)
2162 		return error;
2163 
2164 	/*
2165 	 * Try mapping it in one filesystem block.
2166 	 */
2167 	nmap = 1;
2168 	error = xfs_bmapi_write(tp, dp, *bno, count,
2169 			xfs_bmapi_aflag(w)|XFS_BMAPI_METADATA|XFS_BMAPI_CONTIG,
2170 			args->total, &map, &nmap);
2171 	if (error)
2172 		return error;
2173 
2174 	ASSERT(nmap <= 1);
2175 	if (nmap == 1) {
2176 		mapp = &map;
2177 		mapi = 1;
2178 	} else if (nmap == 0 && count > 1) {
2179 		xfs_fileoff_t		b;
2180 		int			c;
2181 
2182 		/*
2183 		 * If we didn't get it and the block might work if fragmented,
2184 		 * try without the CONTIG flag.  Loop until we get it all.
2185 		 */
2186 		mapp = kmalloc(sizeof(*mapp) * count,
2187 				GFP_KERNEL | __GFP_NOFAIL);
2188 		for (b = *bno, mapi = 0; b < *bno + count; ) {
2189 			c = (int)(*bno + count - b);
2190 			nmap = min(XFS_BMAP_MAX_NMAP, c);
2191 			error = xfs_bmapi_write(tp, dp, b, c,
2192 					xfs_bmapi_aflag(w)|XFS_BMAPI_METADATA,
2193 					args->total, &mapp[mapi], &nmap);
2194 			if (error)
2195 				goto out_free_map;
2196 			if (nmap < 1)
2197 				break;
2198 			mapi += nmap;
2199 			b = mapp[mapi - 1].br_startoff +
2200 			    mapp[mapi - 1].br_blockcount;
2201 		}
2202 	} else {
2203 		mapi = 0;
2204 		mapp = NULL;
2205 	}
2206 
2207 	/*
2208 	 * Count the blocks we got, make sure it matches the total.
2209 	 */
2210 	for (i = 0, got = 0; i < mapi; i++)
2211 		got += mapp[i].br_blockcount;
2212 	if (got != count || mapp[0].br_startoff != *bno ||
2213 	    mapp[mapi - 1].br_startoff + mapp[mapi - 1].br_blockcount !=
2214 	    *bno + count) {
2215 		error = -ENOSPC;
2216 		goto out_free_map;
2217 	}
2218 
2219 	/* account for newly allocated blocks in reserved blocks total */
2220 	args->total -= dp->i_nblocks - nblks;
2221 
2222 out_free_map:
2223 	if (mapp != &map)
2224 		kfree(mapp);
2225 	return error;
2226 }
2227 
2228 /*
2229  * Add a block to the btree ahead of the file.
2230  * Return the new block number to the caller.
2231  */
2232 int
2233 xfs_da_grow_inode(
2234 	struct xfs_da_args	*args,
2235 	xfs_dablk_t		*new_blkno)
2236 {
2237 	xfs_fileoff_t		bno;
2238 	int			error;
2239 
2240 	trace_xfs_da_grow_inode(args);
2241 
2242 	bno = args->geo->leafblk;
2243 	error = xfs_da_grow_inode_int(args, &bno, args->geo->fsbcount);
2244 	if (!error)
2245 		*new_blkno = (xfs_dablk_t)bno;
2246 	return error;
2247 }
2248 
2249 /*
2250  * Ick.  We need to always be able to remove a btree block, even
2251  * if there's no space reservation because the filesystem is full.
2252  * This is called if xfs_bunmapi on a btree block fails due to ENOSPC.
2253  * It swaps the target block with the last block in the file.  The
2254  * last block in the file can always be removed since it can't cause
2255  * a bmap btree split to do that.
2256  */
2257 STATIC int
2258 xfs_da3_swap_lastblock(
2259 	struct xfs_da_args	*args,
2260 	xfs_dablk_t		*dead_blknop,
2261 	struct xfs_buf		**dead_bufp)
2262 {
2263 	struct xfs_da_blkinfo	*dead_info;
2264 	struct xfs_da_blkinfo	*sib_info;
2265 	struct xfs_da_intnode	*par_node;
2266 	struct xfs_da_intnode	*dead_node;
2267 	struct xfs_dir2_leaf	*dead_leaf2;
2268 	struct xfs_da_node_entry *btree;
2269 	struct xfs_da3_icnode_hdr par_hdr;
2270 	struct xfs_inode	*dp;
2271 	struct xfs_trans	*tp;
2272 	struct xfs_mount	*mp;
2273 	struct xfs_buf		*dead_buf;
2274 	struct xfs_buf		*last_buf;
2275 	struct xfs_buf		*sib_buf;
2276 	struct xfs_buf		*par_buf;
2277 	xfs_dahash_t		dead_hash;
2278 	xfs_fileoff_t		lastoff;
2279 	xfs_dablk_t		dead_blkno;
2280 	xfs_dablk_t		last_blkno;
2281 	xfs_dablk_t		sib_blkno;
2282 	xfs_dablk_t		par_blkno;
2283 	int			error;
2284 	int			w;
2285 	int			entno;
2286 	int			level;
2287 	int			dead_level;
2288 
2289 	trace_xfs_da_swap_lastblock(args);
2290 
2291 	dead_buf = *dead_bufp;
2292 	dead_blkno = *dead_blknop;
2293 	tp = args->trans;
2294 	dp = args->dp;
2295 	w = args->whichfork;
2296 	ASSERT(w == XFS_DATA_FORK);
2297 	mp = dp->i_mount;
2298 	lastoff = args->geo->freeblk;
2299 	error = xfs_bmap_last_before(tp, dp, &lastoff, w);
2300 	if (error)
2301 		return error;
2302 	if (XFS_IS_CORRUPT(mp, lastoff == 0))
2303 		return -EFSCORRUPTED;
2304 	/*
2305 	 * Read the last block in the btree space.
2306 	 */
2307 	last_blkno = (xfs_dablk_t)lastoff - args->geo->fsbcount;
2308 	error = xfs_da3_node_read(tp, dp, last_blkno, &last_buf, w);
2309 	if (error)
2310 		return error;
2311 	/*
2312 	 * Copy the last block into the dead buffer and log it.
2313 	 */
2314 	xfs_da_buf_copy(dead_buf, last_buf, args->geo->blksize);
2315 	xfs_trans_log_buf(tp, dead_buf, 0, args->geo->blksize - 1);
2316 	dead_info = dead_buf->b_addr;
2317 
2318 	/*
2319 	 * Get values from the moved block.
2320 	 */
2321 	if (dead_info->magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC) ||
2322 	    dead_info->magic == cpu_to_be16(XFS_DIR3_LEAFN_MAGIC)) {
2323 		struct xfs_dir3_icleaf_hdr leafhdr;
2324 		struct xfs_dir2_leaf_entry *ents;
2325 
2326 		dead_leaf2 = (xfs_dir2_leaf_t *)dead_info;
2327 		xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr,
2328 					    dead_leaf2);
2329 		ents = leafhdr.ents;
2330 		dead_level = 0;
2331 		dead_hash = be32_to_cpu(ents[leafhdr.count - 1].hashval);
2332 	} else {
2333 		struct xfs_da3_icnode_hdr deadhdr;
2334 
2335 		dead_node = (xfs_da_intnode_t *)dead_info;
2336 		xfs_da3_node_hdr_from_disk(dp->i_mount, &deadhdr, dead_node);
2337 		btree = deadhdr.btree;
2338 		dead_level = deadhdr.level;
2339 		dead_hash = be32_to_cpu(btree[deadhdr.count - 1].hashval);
2340 	}
2341 	sib_buf = par_buf = NULL;
2342 	/*
2343 	 * If the moved block has a left sibling, fix up the pointers.
2344 	 */
2345 	if ((sib_blkno = be32_to_cpu(dead_info->back))) {
2346 		error = xfs_da3_node_read(tp, dp, sib_blkno, &sib_buf, w);
2347 		if (error)
2348 			goto done;
2349 		sib_info = sib_buf->b_addr;
2350 		if (XFS_IS_CORRUPT(mp,
2351 				   be32_to_cpu(sib_info->forw) != last_blkno ||
2352 				   sib_info->magic != dead_info->magic)) {
2353 			error = -EFSCORRUPTED;
2354 			goto done;
2355 		}
2356 		sib_info->forw = cpu_to_be32(dead_blkno);
2357 		xfs_trans_log_buf(tp, sib_buf,
2358 			XFS_DA_LOGRANGE(sib_info, &sib_info->forw,
2359 					sizeof(sib_info->forw)));
2360 		sib_buf = NULL;
2361 	}
2362 	/*
2363 	 * If the moved block has a right sibling, fix up the pointers.
2364 	 */
2365 	if ((sib_blkno = be32_to_cpu(dead_info->forw))) {
2366 		error = xfs_da3_node_read(tp, dp, sib_blkno, &sib_buf, w);
2367 		if (error)
2368 			goto done;
2369 		sib_info = sib_buf->b_addr;
2370 		if (XFS_IS_CORRUPT(mp,
2371 				   be32_to_cpu(sib_info->back) != last_blkno ||
2372 				   sib_info->magic != dead_info->magic)) {
2373 			error = -EFSCORRUPTED;
2374 			goto done;
2375 		}
2376 		sib_info->back = cpu_to_be32(dead_blkno);
2377 		xfs_trans_log_buf(tp, sib_buf,
2378 			XFS_DA_LOGRANGE(sib_info, &sib_info->back,
2379 					sizeof(sib_info->back)));
2380 		sib_buf = NULL;
2381 	}
2382 	par_blkno = args->geo->leafblk;
2383 	level = -1;
2384 	/*
2385 	 * Walk down the tree looking for the parent of the moved block.
2386 	 */
2387 	for (;;) {
2388 		error = xfs_da3_node_read(tp, dp, par_blkno, &par_buf, w);
2389 		if (error)
2390 			goto done;
2391 		par_node = par_buf->b_addr;
2392 		xfs_da3_node_hdr_from_disk(dp->i_mount, &par_hdr, par_node);
2393 		if (XFS_IS_CORRUPT(mp,
2394 				   level >= 0 && level != par_hdr.level + 1)) {
2395 			error = -EFSCORRUPTED;
2396 			goto done;
2397 		}
2398 		level = par_hdr.level;
2399 		btree = par_hdr.btree;
2400 		for (entno = 0;
2401 		     entno < par_hdr.count &&
2402 		     be32_to_cpu(btree[entno].hashval) < dead_hash;
2403 		     entno++)
2404 			continue;
2405 		if (XFS_IS_CORRUPT(mp, entno == par_hdr.count)) {
2406 			error = -EFSCORRUPTED;
2407 			goto done;
2408 		}
2409 		par_blkno = be32_to_cpu(btree[entno].before);
2410 		if (level == dead_level + 1)
2411 			break;
2412 		xfs_trans_brelse(tp, par_buf);
2413 		par_buf = NULL;
2414 	}
2415 	/*
2416 	 * We're in the right parent block.
2417 	 * Look for the right entry.
2418 	 */
2419 	for (;;) {
2420 		for (;
2421 		     entno < par_hdr.count &&
2422 		     be32_to_cpu(btree[entno].before) != last_blkno;
2423 		     entno++)
2424 			continue;
2425 		if (entno < par_hdr.count)
2426 			break;
2427 		par_blkno = par_hdr.forw;
2428 		xfs_trans_brelse(tp, par_buf);
2429 		par_buf = NULL;
2430 		if (XFS_IS_CORRUPT(mp, par_blkno == 0)) {
2431 			error = -EFSCORRUPTED;
2432 			goto done;
2433 		}
2434 		error = xfs_da3_node_read(tp, dp, par_blkno, &par_buf, w);
2435 		if (error)
2436 			goto done;
2437 		par_node = par_buf->b_addr;
2438 		xfs_da3_node_hdr_from_disk(dp->i_mount, &par_hdr, par_node);
2439 		if (XFS_IS_CORRUPT(mp, par_hdr.level != level)) {
2440 			error = -EFSCORRUPTED;
2441 			goto done;
2442 		}
2443 		btree = par_hdr.btree;
2444 		entno = 0;
2445 	}
2446 	/*
2447 	 * Update the parent entry pointing to the moved block.
2448 	 */
2449 	btree[entno].before = cpu_to_be32(dead_blkno);
2450 	xfs_trans_log_buf(tp, par_buf,
2451 		XFS_DA_LOGRANGE(par_node, &btree[entno].before,
2452 				sizeof(btree[entno].before)));
2453 	*dead_blknop = last_blkno;
2454 	*dead_bufp = last_buf;
2455 	return 0;
2456 done:
2457 	if (par_buf)
2458 		xfs_trans_brelse(tp, par_buf);
2459 	if (sib_buf)
2460 		xfs_trans_brelse(tp, sib_buf);
2461 	xfs_trans_brelse(tp, last_buf);
2462 	return error;
2463 }
2464 
2465 /*
2466  * Remove a btree block from a directory or attribute.
2467  */
2468 int
2469 xfs_da_shrink_inode(
2470 	struct xfs_da_args	*args,
2471 	xfs_dablk_t		dead_blkno,
2472 	struct xfs_buf		*dead_buf)
2473 {
2474 	struct xfs_inode	*dp;
2475 	int			done, error, w, count;
2476 	struct xfs_trans	*tp;
2477 
2478 	trace_xfs_da_shrink_inode(args);
2479 
2480 	dp = args->dp;
2481 	w = args->whichfork;
2482 	tp = args->trans;
2483 	count = args->geo->fsbcount;
2484 	for (;;) {
2485 		/*
2486 		 * Remove extents.  If we get ENOSPC for a dir we have to move
2487 		 * the last block to the place we want to kill.
2488 		 */
2489 		error = xfs_bunmapi(tp, dp, dead_blkno, count,
2490 				    xfs_bmapi_aflag(w), 0, &done);
2491 		if (error == -ENOSPC) {
2492 			if (w != XFS_DATA_FORK)
2493 				break;
2494 			error = xfs_da3_swap_lastblock(args, &dead_blkno,
2495 						      &dead_buf);
2496 			if (error)
2497 				break;
2498 		} else {
2499 			break;
2500 		}
2501 	}
2502 	xfs_trans_binval(tp, dead_buf);
2503 	return error;
2504 }
2505 
2506 static int
2507 xfs_dabuf_map(
2508 	struct xfs_inode	*dp,
2509 	xfs_dablk_t		bno,
2510 	unsigned int		flags,
2511 	int			whichfork,
2512 	struct xfs_buf_map	**mapp,
2513 	int			*nmaps)
2514 {
2515 	struct xfs_mount	*mp = dp->i_mount;
2516 	int			nfsb = xfs_dabuf_nfsb(mp, whichfork);
2517 	struct xfs_bmbt_irec	irec, *irecs = &irec;
2518 	struct xfs_buf_map	*map = *mapp;
2519 	xfs_fileoff_t		off = bno;
2520 	int			error = 0, nirecs, i;
2521 
2522 	if (nfsb > 1)
2523 		irecs = kzalloc(sizeof(irec) * nfsb,
2524 				GFP_KERNEL | __GFP_NOLOCKDEP | __GFP_NOFAIL);
2525 
2526 	nirecs = nfsb;
2527 	error = xfs_bmapi_read(dp, bno, nfsb, irecs, &nirecs,
2528 			xfs_bmapi_aflag(whichfork));
2529 	if (error)
2530 		goto out_free_irecs;
2531 
2532 	/*
2533 	 * Use the caller provided map for the single map case, else allocate a
2534 	 * larger one that needs to be free by the caller.
2535 	 */
2536 	if (nirecs > 1) {
2537 		map = kzalloc(nirecs * sizeof(struct xfs_buf_map),
2538 				GFP_KERNEL | __GFP_NOLOCKDEP | __GFP_NOFAIL);
2539 		if (!map) {
2540 			error = -ENOMEM;
2541 			goto out_free_irecs;
2542 		}
2543 		*mapp = map;
2544 	}
2545 
2546 	for (i = 0; i < nirecs; i++) {
2547 		if (irecs[i].br_startblock == HOLESTARTBLOCK ||
2548 		    irecs[i].br_startblock == DELAYSTARTBLOCK)
2549 			goto invalid_mapping;
2550 		if (off != irecs[i].br_startoff)
2551 			goto invalid_mapping;
2552 
2553 		map[i].bm_bn = XFS_FSB_TO_DADDR(mp, irecs[i].br_startblock);
2554 		map[i].bm_len = XFS_FSB_TO_BB(mp, irecs[i].br_blockcount);
2555 		off += irecs[i].br_blockcount;
2556 	}
2557 
2558 	if (off != bno + nfsb)
2559 		goto invalid_mapping;
2560 
2561 	*nmaps = nirecs;
2562 out_free_irecs:
2563 	if (irecs != &irec)
2564 		kfree(irecs);
2565 	return error;
2566 
2567 invalid_mapping:
2568 	/* Caller ok with no mapping. */
2569 	if (XFS_IS_CORRUPT(mp, !(flags & XFS_DABUF_MAP_HOLE_OK))) {
2570 		error = -EFSCORRUPTED;
2571 		if (xfs_error_level >= XFS_ERRLEVEL_LOW) {
2572 			xfs_alert(mp, "%s: bno %u inode %llu",
2573 					__func__, bno, dp->i_ino);
2574 
2575 			for (i = 0; i < nirecs; i++) {
2576 				xfs_alert(mp,
2577 "[%02d] br_startoff %lld br_startblock %lld br_blockcount %lld br_state %d",
2578 					i, irecs[i].br_startoff,
2579 					irecs[i].br_startblock,
2580 					irecs[i].br_blockcount,
2581 					irecs[i].br_state);
2582 			}
2583 		}
2584 	} else {
2585 		*nmaps = 0;
2586 	}
2587 	goto out_free_irecs;
2588 }
2589 
2590 /*
2591  * Get a buffer for the dir/attr block.
2592  */
2593 int
2594 xfs_da_get_buf(
2595 	struct xfs_trans	*tp,
2596 	struct xfs_inode	*dp,
2597 	xfs_dablk_t		bno,
2598 	struct xfs_buf		**bpp,
2599 	int			whichfork)
2600 {
2601 	struct xfs_mount	*mp = dp->i_mount;
2602 	struct xfs_buf		*bp;
2603 	struct xfs_buf_map	map, *mapp = &map;
2604 	int			nmap = 1;
2605 	int			error;
2606 
2607 	*bpp = NULL;
2608 	error = xfs_dabuf_map(dp, bno, 0, whichfork, &mapp, &nmap);
2609 	if (error || nmap == 0)
2610 		goto out_free;
2611 
2612 	error = xfs_trans_get_buf_map(tp, mp->m_ddev_targp, mapp, nmap, 0, &bp);
2613 	if (error)
2614 		goto out_free;
2615 
2616 	*bpp = bp;
2617 
2618 out_free:
2619 	if (mapp != &map)
2620 		kfree(mapp);
2621 
2622 	return error;
2623 }
2624 
2625 /*
2626  * Get a buffer for the dir/attr block, fill in the contents.
2627  */
2628 int
2629 xfs_da_read_buf(
2630 	struct xfs_trans	*tp,
2631 	struct xfs_inode	*dp,
2632 	xfs_dablk_t		bno,
2633 	unsigned int		flags,
2634 	struct xfs_buf		**bpp,
2635 	int			whichfork,
2636 	const struct xfs_buf_ops *ops)
2637 {
2638 	struct xfs_mount	*mp = dp->i_mount;
2639 	struct xfs_buf		*bp;
2640 	struct xfs_buf_map	map, *mapp = &map;
2641 	int			nmap = 1;
2642 	int			error;
2643 
2644 	*bpp = NULL;
2645 	error = xfs_dabuf_map(dp, bno, flags, whichfork, &mapp, &nmap);
2646 	if (error || !nmap)
2647 		goto out_free;
2648 
2649 	error = xfs_trans_read_buf_map(mp, tp, mp->m_ddev_targp, mapp, nmap, 0,
2650 			&bp, ops);
2651 	if (error)
2652 		goto out_free;
2653 
2654 	if (whichfork == XFS_ATTR_FORK)
2655 		xfs_buf_set_ref(bp, XFS_ATTR_BTREE_REF);
2656 	else
2657 		xfs_buf_set_ref(bp, XFS_DIR_BTREE_REF);
2658 	*bpp = bp;
2659 out_free:
2660 	if (mapp != &map)
2661 		kfree(mapp);
2662 
2663 	return error;
2664 }
2665 
2666 /*
2667  * Readahead the dir/attr block.
2668  */
2669 int
2670 xfs_da_reada_buf(
2671 	struct xfs_inode	*dp,
2672 	xfs_dablk_t		bno,
2673 	unsigned int		flags,
2674 	int			whichfork,
2675 	const struct xfs_buf_ops *ops)
2676 {
2677 	struct xfs_buf_map	map;
2678 	struct xfs_buf_map	*mapp;
2679 	int			nmap;
2680 	int			error;
2681 
2682 	mapp = &map;
2683 	nmap = 1;
2684 	error = xfs_dabuf_map(dp, bno, flags, whichfork, &mapp, &nmap);
2685 	if (error || !nmap)
2686 		goto out_free;
2687 
2688 	xfs_buf_readahead_map(dp->i_mount->m_ddev_targp, mapp, nmap, ops);
2689 
2690 out_free:
2691 	if (mapp != &map)
2692 		kfree(mapp);
2693 
2694 	return error;
2695 }
2696