xref: /linux/fs/xfs/libxfs/xfs_btree.c (revision 8b83369ddcb3fb9cab5c1088987ce477565bb630)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2002,2005 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include "xfs.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_log_format.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_bit.h"
13 #include "xfs_mount.h"
14 #include "xfs_inode.h"
15 #include "xfs_trans.h"
16 #include "xfs_buf_item.h"
17 #include "xfs_btree.h"
18 #include "xfs_errortag.h"
19 #include "xfs_error.h"
20 #include "xfs_trace.h"
21 #include "xfs_alloc.h"
22 #include "xfs_log.h"
23 #include "xfs_btree_staging.h"
24 
25 /*
26  * Cursor allocation zone.
27  */
28 kmem_zone_t	*xfs_btree_cur_zone;
29 
30 /*
31  * Btree magic numbers.
32  */
33 static const uint32_t xfs_magics[2][XFS_BTNUM_MAX] = {
34 	{ XFS_ABTB_MAGIC, XFS_ABTC_MAGIC, 0, XFS_BMAP_MAGIC, XFS_IBT_MAGIC,
35 	  XFS_FIBT_MAGIC, 0 },
36 	{ XFS_ABTB_CRC_MAGIC, XFS_ABTC_CRC_MAGIC, XFS_RMAP_CRC_MAGIC,
37 	  XFS_BMAP_CRC_MAGIC, XFS_IBT_CRC_MAGIC, XFS_FIBT_CRC_MAGIC,
38 	  XFS_REFC_CRC_MAGIC }
39 };
40 
41 uint32_t
42 xfs_btree_magic(
43 	int			crc,
44 	xfs_btnum_t		btnum)
45 {
46 	uint32_t		magic = xfs_magics[crc][btnum];
47 
48 	/* Ensure we asked for crc for crc-only magics. */
49 	ASSERT(magic != 0);
50 	return magic;
51 }
52 
53 /*
54  * Check a long btree block header.  Return the address of the failing check,
55  * or NULL if everything is ok.
56  */
57 xfs_failaddr_t
58 __xfs_btree_check_lblock(
59 	struct xfs_btree_cur	*cur,
60 	struct xfs_btree_block	*block,
61 	int			level,
62 	struct xfs_buf		*bp)
63 {
64 	struct xfs_mount	*mp = cur->bc_mp;
65 	xfs_btnum_t		btnum = cur->bc_btnum;
66 	int			crc = xfs_sb_version_hascrc(&mp->m_sb);
67 
68 	if (crc) {
69 		if (!uuid_equal(&block->bb_u.l.bb_uuid, &mp->m_sb.sb_meta_uuid))
70 			return __this_address;
71 		if (block->bb_u.l.bb_blkno !=
72 		    cpu_to_be64(bp ? bp->b_bn : XFS_BUF_DADDR_NULL))
73 			return __this_address;
74 		if (block->bb_u.l.bb_pad != cpu_to_be32(0))
75 			return __this_address;
76 	}
77 
78 	if (be32_to_cpu(block->bb_magic) != xfs_btree_magic(crc, btnum))
79 		return __this_address;
80 	if (be16_to_cpu(block->bb_level) != level)
81 		return __this_address;
82 	if (be16_to_cpu(block->bb_numrecs) >
83 	    cur->bc_ops->get_maxrecs(cur, level))
84 		return __this_address;
85 	if (block->bb_u.l.bb_leftsib != cpu_to_be64(NULLFSBLOCK) &&
86 	    !xfs_btree_check_lptr(cur, be64_to_cpu(block->bb_u.l.bb_leftsib),
87 			level + 1))
88 		return __this_address;
89 	if (block->bb_u.l.bb_rightsib != cpu_to_be64(NULLFSBLOCK) &&
90 	    !xfs_btree_check_lptr(cur, be64_to_cpu(block->bb_u.l.bb_rightsib),
91 			level + 1))
92 		return __this_address;
93 
94 	return NULL;
95 }
96 
97 /* Check a long btree block header. */
98 static int
99 xfs_btree_check_lblock(
100 	struct xfs_btree_cur	*cur,
101 	struct xfs_btree_block	*block,
102 	int			level,
103 	struct xfs_buf		*bp)
104 {
105 	struct xfs_mount	*mp = cur->bc_mp;
106 	xfs_failaddr_t		fa;
107 
108 	fa = __xfs_btree_check_lblock(cur, block, level, bp);
109 	if (XFS_IS_CORRUPT(mp, fa != NULL) ||
110 	    XFS_TEST_ERROR(false, mp, XFS_ERRTAG_BTREE_CHECK_LBLOCK)) {
111 		if (bp)
112 			trace_xfs_btree_corrupt(bp, _RET_IP_);
113 		return -EFSCORRUPTED;
114 	}
115 	return 0;
116 }
117 
118 /*
119  * Check a short btree block header.  Return the address of the failing check,
120  * or NULL if everything is ok.
121  */
122 xfs_failaddr_t
123 __xfs_btree_check_sblock(
124 	struct xfs_btree_cur	*cur,
125 	struct xfs_btree_block	*block,
126 	int			level,
127 	struct xfs_buf		*bp)
128 {
129 	struct xfs_mount	*mp = cur->bc_mp;
130 	xfs_btnum_t		btnum = cur->bc_btnum;
131 	int			crc = xfs_sb_version_hascrc(&mp->m_sb);
132 
133 	if (crc) {
134 		if (!uuid_equal(&block->bb_u.s.bb_uuid, &mp->m_sb.sb_meta_uuid))
135 			return __this_address;
136 		if (block->bb_u.s.bb_blkno !=
137 		    cpu_to_be64(bp ? bp->b_bn : XFS_BUF_DADDR_NULL))
138 			return __this_address;
139 	}
140 
141 	if (be32_to_cpu(block->bb_magic) != xfs_btree_magic(crc, btnum))
142 		return __this_address;
143 	if (be16_to_cpu(block->bb_level) != level)
144 		return __this_address;
145 	if (be16_to_cpu(block->bb_numrecs) >
146 	    cur->bc_ops->get_maxrecs(cur, level))
147 		return __this_address;
148 	if (block->bb_u.s.bb_leftsib != cpu_to_be32(NULLAGBLOCK) &&
149 	    !xfs_btree_check_sptr(cur, be32_to_cpu(block->bb_u.s.bb_leftsib),
150 			level + 1))
151 		return __this_address;
152 	if (block->bb_u.s.bb_rightsib != cpu_to_be32(NULLAGBLOCK) &&
153 	    !xfs_btree_check_sptr(cur, be32_to_cpu(block->bb_u.s.bb_rightsib),
154 			level + 1))
155 		return __this_address;
156 
157 	return NULL;
158 }
159 
160 /* Check a short btree block header. */
161 STATIC int
162 xfs_btree_check_sblock(
163 	struct xfs_btree_cur	*cur,
164 	struct xfs_btree_block	*block,
165 	int			level,
166 	struct xfs_buf		*bp)
167 {
168 	struct xfs_mount	*mp = cur->bc_mp;
169 	xfs_failaddr_t		fa;
170 
171 	fa = __xfs_btree_check_sblock(cur, block, level, bp);
172 	if (XFS_IS_CORRUPT(mp, fa != NULL) ||
173 	    XFS_TEST_ERROR(false, mp, XFS_ERRTAG_BTREE_CHECK_SBLOCK)) {
174 		if (bp)
175 			trace_xfs_btree_corrupt(bp, _RET_IP_);
176 		return -EFSCORRUPTED;
177 	}
178 	return 0;
179 }
180 
181 /*
182  * Debug routine: check that block header is ok.
183  */
184 int
185 xfs_btree_check_block(
186 	struct xfs_btree_cur	*cur,	/* btree cursor */
187 	struct xfs_btree_block	*block,	/* generic btree block pointer */
188 	int			level,	/* level of the btree block */
189 	struct xfs_buf		*bp)	/* buffer containing block, if any */
190 {
191 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
192 		return xfs_btree_check_lblock(cur, block, level, bp);
193 	else
194 		return xfs_btree_check_sblock(cur, block, level, bp);
195 }
196 
197 /* Check that this long pointer is valid and points within the fs. */
198 bool
199 xfs_btree_check_lptr(
200 	struct xfs_btree_cur	*cur,
201 	xfs_fsblock_t		fsbno,
202 	int			level)
203 {
204 	if (level <= 0)
205 		return false;
206 	return xfs_verify_fsbno(cur->bc_mp, fsbno);
207 }
208 
209 /* Check that this short pointer is valid and points within the AG. */
210 bool
211 xfs_btree_check_sptr(
212 	struct xfs_btree_cur	*cur,
213 	xfs_agblock_t		agbno,
214 	int			level)
215 {
216 	if (level <= 0)
217 		return false;
218 	return xfs_verify_agbno(cur->bc_mp, cur->bc_ag.agno, agbno);
219 }
220 
221 /*
222  * Check that a given (indexed) btree pointer at a certain level of a
223  * btree is valid and doesn't point past where it should.
224  */
225 static int
226 xfs_btree_check_ptr(
227 	struct xfs_btree_cur	*cur,
228 	union xfs_btree_ptr	*ptr,
229 	int			index,
230 	int			level)
231 {
232 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
233 		if (xfs_btree_check_lptr(cur, be64_to_cpu((&ptr->l)[index]),
234 				level))
235 			return 0;
236 		xfs_err(cur->bc_mp,
237 "Inode %llu fork %d: Corrupt btree %d pointer at level %d index %d.",
238 				cur->bc_ino.ip->i_ino,
239 				cur->bc_ino.whichfork, cur->bc_btnum,
240 				level, index);
241 	} else {
242 		if (xfs_btree_check_sptr(cur, be32_to_cpu((&ptr->s)[index]),
243 				level))
244 			return 0;
245 		xfs_err(cur->bc_mp,
246 "AG %u: Corrupt btree %d pointer at level %d index %d.",
247 				cur->bc_ag.agno, cur->bc_btnum,
248 				level, index);
249 	}
250 
251 	return -EFSCORRUPTED;
252 }
253 
254 #ifdef DEBUG
255 # define xfs_btree_debug_check_ptr	xfs_btree_check_ptr
256 #else
257 # define xfs_btree_debug_check_ptr(...)	(0)
258 #endif
259 
260 /*
261  * Calculate CRC on the whole btree block and stuff it into the
262  * long-form btree header.
263  *
264  * Prior to calculting the CRC, pull the LSN out of the buffer log item and put
265  * it into the buffer so recovery knows what the last modification was that made
266  * it to disk.
267  */
268 void
269 xfs_btree_lblock_calc_crc(
270 	struct xfs_buf		*bp)
271 {
272 	struct xfs_btree_block	*block = XFS_BUF_TO_BLOCK(bp);
273 	struct xfs_buf_log_item	*bip = bp->b_log_item;
274 
275 	if (!xfs_sb_version_hascrc(&bp->b_mount->m_sb))
276 		return;
277 	if (bip)
278 		block->bb_u.l.bb_lsn = cpu_to_be64(bip->bli_item.li_lsn);
279 	xfs_buf_update_cksum(bp, XFS_BTREE_LBLOCK_CRC_OFF);
280 }
281 
282 bool
283 xfs_btree_lblock_verify_crc(
284 	struct xfs_buf		*bp)
285 {
286 	struct xfs_btree_block	*block = XFS_BUF_TO_BLOCK(bp);
287 	struct xfs_mount	*mp = bp->b_mount;
288 
289 	if (xfs_sb_version_hascrc(&mp->m_sb)) {
290 		if (!xfs_log_check_lsn(mp, be64_to_cpu(block->bb_u.l.bb_lsn)))
291 			return false;
292 		return xfs_buf_verify_cksum(bp, XFS_BTREE_LBLOCK_CRC_OFF);
293 	}
294 
295 	return true;
296 }
297 
298 /*
299  * Calculate CRC on the whole btree block and stuff it into the
300  * short-form btree header.
301  *
302  * Prior to calculting the CRC, pull the LSN out of the buffer log item and put
303  * it into the buffer so recovery knows what the last modification was that made
304  * it to disk.
305  */
306 void
307 xfs_btree_sblock_calc_crc(
308 	struct xfs_buf		*bp)
309 {
310 	struct xfs_btree_block	*block = XFS_BUF_TO_BLOCK(bp);
311 	struct xfs_buf_log_item	*bip = bp->b_log_item;
312 
313 	if (!xfs_sb_version_hascrc(&bp->b_mount->m_sb))
314 		return;
315 	if (bip)
316 		block->bb_u.s.bb_lsn = cpu_to_be64(bip->bli_item.li_lsn);
317 	xfs_buf_update_cksum(bp, XFS_BTREE_SBLOCK_CRC_OFF);
318 }
319 
320 bool
321 xfs_btree_sblock_verify_crc(
322 	struct xfs_buf		*bp)
323 {
324 	struct xfs_btree_block  *block = XFS_BUF_TO_BLOCK(bp);
325 	struct xfs_mount	*mp = bp->b_mount;
326 
327 	if (xfs_sb_version_hascrc(&mp->m_sb)) {
328 		if (!xfs_log_check_lsn(mp, be64_to_cpu(block->bb_u.s.bb_lsn)))
329 			return false;
330 		return xfs_buf_verify_cksum(bp, XFS_BTREE_SBLOCK_CRC_OFF);
331 	}
332 
333 	return true;
334 }
335 
336 static int
337 xfs_btree_free_block(
338 	struct xfs_btree_cur	*cur,
339 	struct xfs_buf		*bp)
340 {
341 	int			error;
342 
343 	error = cur->bc_ops->free_block(cur, bp);
344 	if (!error) {
345 		xfs_trans_binval(cur->bc_tp, bp);
346 		XFS_BTREE_STATS_INC(cur, free);
347 	}
348 	return error;
349 }
350 
351 /*
352  * Delete the btree cursor.
353  */
354 void
355 xfs_btree_del_cursor(
356 	struct xfs_btree_cur	*cur,		/* btree cursor */
357 	int			error)		/* del because of error */
358 {
359 	int			i;		/* btree level */
360 
361 	/*
362 	 * Clear the buffer pointers and release the buffers. If we're doing
363 	 * this because of an error, inspect all of the entries in the bc_bufs
364 	 * array for buffers to be unlocked. This is because some of the btree
365 	 * code works from level n down to 0, and if we get an error along the
366 	 * way we won't have initialized all the entries down to 0.
367 	 */
368 	for (i = 0; i < cur->bc_nlevels; i++) {
369 		if (cur->bc_bufs[i])
370 			xfs_trans_brelse(cur->bc_tp, cur->bc_bufs[i]);
371 		else if (!error)
372 			break;
373 	}
374 
375 	ASSERT(cur->bc_btnum != XFS_BTNUM_BMAP || cur->bc_ino.allocated == 0 ||
376 	       XFS_FORCED_SHUTDOWN(cur->bc_mp));
377 	if (unlikely(cur->bc_flags & XFS_BTREE_STAGING))
378 		kmem_free(cur->bc_ops);
379 	kmem_cache_free(xfs_btree_cur_zone, cur);
380 }
381 
382 /*
383  * Duplicate the btree cursor.
384  * Allocate a new one, copy the record, re-get the buffers.
385  */
386 int					/* error */
387 xfs_btree_dup_cursor(
388 	xfs_btree_cur_t	*cur,		/* input cursor */
389 	xfs_btree_cur_t	**ncur)		/* output cursor */
390 {
391 	struct xfs_buf	*bp;		/* btree block's buffer pointer */
392 	int		error;		/* error return value */
393 	int		i;		/* level number of btree block */
394 	xfs_mount_t	*mp;		/* mount structure for filesystem */
395 	xfs_btree_cur_t	*new;		/* new cursor value */
396 	xfs_trans_t	*tp;		/* transaction pointer, can be NULL */
397 
398 	tp = cur->bc_tp;
399 	mp = cur->bc_mp;
400 
401 	/*
402 	 * Allocate a new cursor like the old one.
403 	 */
404 	new = cur->bc_ops->dup_cursor(cur);
405 
406 	/*
407 	 * Copy the record currently in the cursor.
408 	 */
409 	new->bc_rec = cur->bc_rec;
410 
411 	/*
412 	 * For each level current, re-get the buffer and copy the ptr value.
413 	 */
414 	for (i = 0; i < new->bc_nlevels; i++) {
415 		new->bc_ptrs[i] = cur->bc_ptrs[i];
416 		new->bc_ra[i] = cur->bc_ra[i];
417 		bp = cur->bc_bufs[i];
418 		if (bp) {
419 			error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp,
420 						   XFS_BUF_ADDR(bp), mp->m_bsize,
421 						   0, &bp,
422 						   cur->bc_ops->buf_ops);
423 			if (error) {
424 				xfs_btree_del_cursor(new, error);
425 				*ncur = NULL;
426 				return error;
427 			}
428 		}
429 		new->bc_bufs[i] = bp;
430 	}
431 	*ncur = new;
432 	return 0;
433 }
434 
435 /*
436  * XFS btree block layout and addressing:
437  *
438  * There are two types of blocks in the btree: leaf and non-leaf blocks.
439  *
440  * The leaf record start with a header then followed by records containing
441  * the values.  A non-leaf block also starts with the same header, and
442  * then first contains lookup keys followed by an equal number of pointers
443  * to the btree blocks at the previous level.
444  *
445  *		+--------+-------+-------+-------+-------+-------+-------+
446  * Leaf:	| header | rec 1 | rec 2 | rec 3 | rec 4 | rec 5 | rec N |
447  *		+--------+-------+-------+-------+-------+-------+-------+
448  *
449  *		+--------+-------+-------+-------+-------+-------+-------+
450  * Non-Leaf:	| header | key 1 | key 2 | key N | ptr 1 | ptr 2 | ptr N |
451  *		+--------+-------+-------+-------+-------+-------+-------+
452  *
453  * The header is called struct xfs_btree_block for reasons better left unknown
454  * and comes in different versions for short (32bit) and long (64bit) block
455  * pointers.  The record and key structures are defined by the btree instances
456  * and opaque to the btree core.  The block pointers are simple disk endian
457  * integers, available in a short (32bit) and long (64bit) variant.
458  *
459  * The helpers below calculate the offset of a given record, key or pointer
460  * into a btree block (xfs_btree_*_offset) or return a pointer to the given
461  * record, key or pointer (xfs_btree_*_addr).  Note that all addressing
462  * inside the btree block is done using indices starting at one, not zero!
463  *
464  * If XFS_BTREE_OVERLAPPING is set, then this btree supports keys containing
465  * overlapping intervals.  In such a tree, records are still sorted lowest to
466  * highest and indexed by the smallest key value that refers to the record.
467  * However, nodes are different: each pointer has two associated keys -- one
468  * indexing the lowest key available in the block(s) below (the same behavior
469  * as the key in a regular btree) and another indexing the highest key
470  * available in the block(s) below.  Because records are /not/ sorted by the
471  * highest key, all leaf block updates require us to compute the highest key
472  * that matches any record in the leaf and to recursively update the high keys
473  * in the nodes going further up in the tree, if necessary.  Nodes look like
474  * this:
475  *
476  *		+--------+-----+-----+-----+-----+-----+-------+-------+-----+
477  * Non-Leaf:	| header | lo1 | hi1 | lo2 | hi2 | ... | ptr 1 | ptr 2 | ... |
478  *		+--------+-----+-----+-----+-----+-----+-------+-------+-----+
479  *
480  * To perform an interval query on an overlapped tree, perform the usual
481  * depth-first search and use the low and high keys to decide if we can skip
482  * that particular node.  If a leaf node is reached, return the records that
483  * intersect the interval.  Note that an interval query may return numerous
484  * entries.  For a non-overlapped tree, simply search for the record associated
485  * with the lowest key and iterate forward until a non-matching record is
486  * found.  Section 14.3 ("Interval Trees") of _Introduction to Algorithms_ by
487  * Cormen, Leiserson, Rivest, and Stein (2nd or 3rd ed. only) discuss this in
488  * more detail.
489  *
490  * Why do we care about overlapping intervals?  Let's say you have a bunch of
491  * reverse mapping records on a reflink filesystem:
492  *
493  * 1: +- file A startblock B offset C length D -----------+
494  * 2:      +- file E startblock F offset G length H --------------+
495  * 3:      +- file I startblock F offset J length K --+
496  * 4:                                                        +- file L... --+
497  *
498  * Now say we want to map block (B+D) into file A at offset (C+D).  Ideally,
499  * we'd simply increment the length of record 1.  But how do we find the record
500  * that ends at (B+D-1) (i.e. record 1)?  A LE lookup of (B+D-1) would return
501  * record 3 because the keys are ordered first by startblock.  An interval
502  * query would return records 1 and 2 because they both overlap (B+D-1), and
503  * from that we can pick out record 1 as the appropriate left neighbor.
504  *
505  * In the non-overlapped case you can do a LE lookup and decrement the cursor
506  * because a record's interval must end before the next record.
507  */
508 
509 /*
510  * Return size of the btree block header for this btree instance.
511  */
512 static inline size_t xfs_btree_block_len(struct xfs_btree_cur *cur)
513 {
514 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
515 		if (cur->bc_flags & XFS_BTREE_CRC_BLOCKS)
516 			return XFS_BTREE_LBLOCK_CRC_LEN;
517 		return XFS_BTREE_LBLOCK_LEN;
518 	}
519 	if (cur->bc_flags & XFS_BTREE_CRC_BLOCKS)
520 		return XFS_BTREE_SBLOCK_CRC_LEN;
521 	return XFS_BTREE_SBLOCK_LEN;
522 }
523 
524 /*
525  * Return size of btree block pointers for this btree instance.
526  */
527 static inline size_t xfs_btree_ptr_len(struct xfs_btree_cur *cur)
528 {
529 	return (cur->bc_flags & XFS_BTREE_LONG_PTRS) ?
530 		sizeof(__be64) : sizeof(__be32);
531 }
532 
533 /*
534  * Calculate offset of the n-th record in a btree block.
535  */
536 STATIC size_t
537 xfs_btree_rec_offset(
538 	struct xfs_btree_cur	*cur,
539 	int			n)
540 {
541 	return xfs_btree_block_len(cur) +
542 		(n - 1) * cur->bc_ops->rec_len;
543 }
544 
545 /*
546  * Calculate offset of the n-th key in a btree block.
547  */
548 STATIC size_t
549 xfs_btree_key_offset(
550 	struct xfs_btree_cur	*cur,
551 	int			n)
552 {
553 	return xfs_btree_block_len(cur) +
554 		(n - 1) * cur->bc_ops->key_len;
555 }
556 
557 /*
558  * Calculate offset of the n-th high key in a btree block.
559  */
560 STATIC size_t
561 xfs_btree_high_key_offset(
562 	struct xfs_btree_cur	*cur,
563 	int			n)
564 {
565 	return xfs_btree_block_len(cur) +
566 		(n - 1) * cur->bc_ops->key_len + (cur->bc_ops->key_len / 2);
567 }
568 
569 /*
570  * Calculate offset of the n-th block pointer in a btree block.
571  */
572 STATIC size_t
573 xfs_btree_ptr_offset(
574 	struct xfs_btree_cur	*cur,
575 	int			n,
576 	int			level)
577 {
578 	return xfs_btree_block_len(cur) +
579 		cur->bc_ops->get_maxrecs(cur, level) * cur->bc_ops->key_len +
580 		(n - 1) * xfs_btree_ptr_len(cur);
581 }
582 
583 /*
584  * Return a pointer to the n-th record in the btree block.
585  */
586 union xfs_btree_rec *
587 xfs_btree_rec_addr(
588 	struct xfs_btree_cur	*cur,
589 	int			n,
590 	struct xfs_btree_block	*block)
591 {
592 	return (union xfs_btree_rec *)
593 		((char *)block + xfs_btree_rec_offset(cur, n));
594 }
595 
596 /*
597  * Return a pointer to the n-th key in the btree block.
598  */
599 union xfs_btree_key *
600 xfs_btree_key_addr(
601 	struct xfs_btree_cur	*cur,
602 	int			n,
603 	struct xfs_btree_block	*block)
604 {
605 	return (union xfs_btree_key *)
606 		((char *)block + xfs_btree_key_offset(cur, n));
607 }
608 
609 /*
610  * Return a pointer to the n-th high key in the btree block.
611  */
612 union xfs_btree_key *
613 xfs_btree_high_key_addr(
614 	struct xfs_btree_cur	*cur,
615 	int			n,
616 	struct xfs_btree_block	*block)
617 {
618 	return (union xfs_btree_key *)
619 		((char *)block + xfs_btree_high_key_offset(cur, n));
620 }
621 
622 /*
623  * Return a pointer to the n-th block pointer in the btree block.
624  */
625 union xfs_btree_ptr *
626 xfs_btree_ptr_addr(
627 	struct xfs_btree_cur	*cur,
628 	int			n,
629 	struct xfs_btree_block	*block)
630 {
631 	int			level = xfs_btree_get_level(block);
632 
633 	ASSERT(block->bb_level != 0);
634 
635 	return (union xfs_btree_ptr *)
636 		((char *)block + xfs_btree_ptr_offset(cur, n, level));
637 }
638 
639 struct xfs_ifork *
640 xfs_btree_ifork_ptr(
641 	struct xfs_btree_cur	*cur)
642 {
643 	ASSERT(cur->bc_flags & XFS_BTREE_ROOT_IN_INODE);
644 
645 	if (cur->bc_flags & XFS_BTREE_STAGING)
646 		return cur->bc_ino.ifake->if_fork;
647 	return XFS_IFORK_PTR(cur->bc_ino.ip, cur->bc_ino.whichfork);
648 }
649 
650 /*
651  * Get the root block which is stored in the inode.
652  *
653  * For now this btree implementation assumes the btree root is always
654  * stored in the if_broot field of an inode fork.
655  */
656 STATIC struct xfs_btree_block *
657 xfs_btree_get_iroot(
658 	struct xfs_btree_cur	*cur)
659 {
660 	struct xfs_ifork	*ifp = xfs_btree_ifork_ptr(cur);
661 
662 	return (struct xfs_btree_block *)ifp->if_broot;
663 }
664 
665 /*
666  * Retrieve the block pointer from the cursor at the given level.
667  * This may be an inode btree root or from a buffer.
668  */
669 struct xfs_btree_block *		/* generic btree block pointer */
670 xfs_btree_get_block(
671 	struct xfs_btree_cur	*cur,	/* btree cursor */
672 	int			level,	/* level in btree */
673 	struct xfs_buf		**bpp)	/* buffer containing the block */
674 {
675 	if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
676 	    (level == cur->bc_nlevels - 1)) {
677 		*bpp = NULL;
678 		return xfs_btree_get_iroot(cur);
679 	}
680 
681 	*bpp = cur->bc_bufs[level];
682 	return XFS_BUF_TO_BLOCK(*bpp);
683 }
684 
685 /*
686  * Change the cursor to point to the first record at the given level.
687  * Other levels are unaffected.
688  */
689 STATIC int				/* success=1, failure=0 */
690 xfs_btree_firstrec(
691 	xfs_btree_cur_t		*cur,	/* btree cursor */
692 	int			level)	/* level to change */
693 {
694 	struct xfs_btree_block	*block;	/* generic btree block pointer */
695 	struct xfs_buf		*bp;	/* buffer containing block */
696 
697 	/*
698 	 * Get the block pointer for this level.
699 	 */
700 	block = xfs_btree_get_block(cur, level, &bp);
701 	if (xfs_btree_check_block(cur, block, level, bp))
702 		return 0;
703 	/*
704 	 * It's empty, there is no such record.
705 	 */
706 	if (!block->bb_numrecs)
707 		return 0;
708 	/*
709 	 * Set the ptr value to 1, that's the first record/key.
710 	 */
711 	cur->bc_ptrs[level] = 1;
712 	return 1;
713 }
714 
715 /*
716  * Change the cursor to point to the last record in the current block
717  * at the given level.  Other levels are unaffected.
718  */
719 STATIC int				/* success=1, failure=0 */
720 xfs_btree_lastrec(
721 	xfs_btree_cur_t		*cur,	/* btree cursor */
722 	int			level)	/* level to change */
723 {
724 	struct xfs_btree_block	*block;	/* generic btree block pointer */
725 	struct xfs_buf		*bp;	/* buffer containing block */
726 
727 	/*
728 	 * Get the block pointer for this level.
729 	 */
730 	block = xfs_btree_get_block(cur, level, &bp);
731 	if (xfs_btree_check_block(cur, block, level, bp))
732 		return 0;
733 	/*
734 	 * It's empty, there is no such record.
735 	 */
736 	if (!block->bb_numrecs)
737 		return 0;
738 	/*
739 	 * Set the ptr value to numrecs, that's the last record/key.
740 	 */
741 	cur->bc_ptrs[level] = be16_to_cpu(block->bb_numrecs);
742 	return 1;
743 }
744 
745 /*
746  * Compute first and last byte offsets for the fields given.
747  * Interprets the offsets table, which contains struct field offsets.
748  */
749 void
750 xfs_btree_offsets(
751 	int64_t		fields,		/* bitmask of fields */
752 	const short	*offsets,	/* table of field offsets */
753 	int		nbits,		/* number of bits to inspect */
754 	int		*first,		/* output: first byte offset */
755 	int		*last)		/* output: last byte offset */
756 {
757 	int		i;		/* current bit number */
758 	int64_t		imask;		/* mask for current bit number */
759 
760 	ASSERT(fields != 0);
761 	/*
762 	 * Find the lowest bit, so the first byte offset.
763 	 */
764 	for (i = 0, imask = 1LL; ; i++, imask <<= 1) {
765 		if (imask & fields) {
766 			*first = offsets[i];
767 			break;
768 		}
769 	}
770 	/*
771 	 * Find the highest bit, so the last byte offset.
772 	 */
773 	for (i = nbits - 1, imask = 1LL << i; ; i--, imask >>= 1) {
774 		if (imask & fields) {
775 			*last = offsets[i + 1] - 1;
776 			break;
777 		}
778 	}
779 }
780 
781 /*
782  * Get a buffer for the block, return it read in.
783  * Long-form addressing.
784  */
785 int
786 xfs_btree_read_bufl(
787 	struct xfs_mount	*mp,		/* file system mount point */
788 	struct xfs_trans	*tp,		/* transaction pointer */
789 	xfs_fsblock_t		fsbno,		/* file system block number */
790 	struct xfs_buf		**bpp,		/* buffer for fsbno */
791 	int			refval,		/* ref count value for buffer */
792 	const struct xfs_buf_ops *ops)
793 {
794 	struct xfs_buf		*bp;		/* return value */
795 	xfs_daddr_t		d;		/* real disk block address */
796 	int			error;
797 
798 	if (!xfs_verify_fsbno(mp, fsbno))
799 		return -EFSCORRUPTED;
800 	d = XFS_FSB_TO_DADDR(mp, fsbno);
801 	error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp, d,
802 				   mp->m_bsize, 0, &bp, ops);
803 	if (error)
804 		return error;
805 	if (bp)
806 		xfs_buf_set_ref(bp, refval);
807 	*bpp = bp;
808 	return 0;
809 }
810 
811 /*
812  * Read-ahead the block, don't wait for it, don't return a buffer.
813  * Long-form addressing.
814  */
815 /* ARGSUSED */
816 void
817 xfs_btree_reada_bufl(
818 	struct xfs_mount	*mp,		/* file system mount point */
819 	xfs_fsblock_t		fsbno,		/* file system block number */
820 	xfs_extlen_t		count,		/* count of filesystem blocks */
821 	const struct xfs_buf_ops *ops)
822 {
823 	xfs_daddr_t		d;
824 
825 	ASSERT(fsbno != NULLFSBLOCK);
826 	d = XFS_FSB_TO_DADDR(mp, fsbno);
827 	xfs_buf_readahead(mp->m_ddev_targp, d, mp->m_bsize * count, ops);
828 }
829 
830 /*
831  * Read-ahead the block, don't wait for it, don't return a buffer.
832  * Short-form addressing.
833  */
834 /* ARGSUSED */
835 void
836 xfs_btree_reada_bufs(
837 	struct xfs_mount	*mp,		/* file system mount point */
838 	xfs_agnumber_t		agno,		/* allocation group number */
839 	xfs_agblock_t		agbno,		/* allocation group block number */
840 	xfs_extlen_t		count,		/* count of filesystem blocks */
841 	const struct xfs_buf_ops *ops)
842 {
843 	xfs_daddr_t		d;
844 
845 	ASSERT(agno != NULLAGNUMBER);
846 	ASSERT(agbno != NULLAGBLOCK);
847 	d = XFS_AGB_TO_DADDR(mp, agno, agbno);
848 	xfs_buf_readahead(mp->m_ddev_targp, d, mp->m_bsize * count, ops);
849 }
850 
851 STATIC int
852 xfs_btree_readahead_lblock(
853 	struct xfs_btree_cur	*cur,
854 	int			lr,
855 	struct xfs_btree_block	*block)
856 {
857 	int			rval = 0;
858 	xfs_fsblock_t		left = be64_to_cpu(block->bb_u.l.bb_leftsib);
859 	xfs_fsblock_t		right = be64_to_cpu(block->bb_u.l.bb_rightsib);
860 
861 	if ((lr & XFS_BTCUR_LEFTRA) && left != NULLFSBLOCK) {
862 		xfs_btree_reada_bufl(cur->bc_mp, left, 1,
863 				     cur->bc_ops->buf_ops);
864 		rval++;
865 	}
866 
867 	if ((lr & XFS_BTCUR_RIGHTRA) && right != NULLFSBLOCK) {
868 		xfs_btree_reada_bufl(cur->bc_mp, right, 1,
869 				     cur->bc_ops->buf_ops);
870 		rval++;
871 	}
872 
873 	return rval;
874 }
875 
876 STATIC int
877 xfs_btree_readahead_sblock(
878 	struct xfs_btree_cur	*cur,
879 	int			lr,
880 	struct xfs_btree_block *block)
881 {
882 	int			rval = 0;
883 	xfs_agblock_t		left = be32_to_cpu(block->bb_u.s.bb_leftsib);
884 	xfs_agblock_t		right = be32_to_cpu(block->bb_u.s.bb_rightsib);
885 
886 
887 	if ((lr & XFS_BTCUR_LEFTRA) && left != NULLAGBLOCK) {
888 		xfs_btree_reada_bufs(cur->bc_mp, cur->bc_ag.agno,
889 				     left, 1, cur->bc_ops->buf_ops);
890 		rval++;
891 	}
892 
893 	if ((lr & XFS_BTCUR_RIGHTRA) && right != NULLAGBLOCK) {
894 		xfs_btree_reada_bufs(cur->bc_mp, cur->bc_ag.agno,
895 				     right, 1, cur->bc_ops->buf_ops);
896 		rval++;
897 	}
898 
899 	return rval;
900 }
901 
902 /*
903  * Read-ahead btree blocks, at the given level.
904  * Bits in lr are set from XFS_BTCUR_{LEFT,RIGHT}RA.
905  */
906 STATIC int
907 xfs_btree_readahead(
908 	struct xfs_btree_cur	*cur,		/* btree cursor */
909 	int			lev,		/* level in btree */
910 	int			lr)		/* left/right bits */
911 {
912 	struct xfs_btree_block	*block;
913 
914 	/*
915 	 * No readahead needed if we are at the root level and the
916 	 * btree root is stored in the inode.
917 	 */
918 	if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
919 	    (lev == cur->bc_nlevels - 1))
920 		return 0;
921 
922 	if ((cur->bc_ra[lev] | lr) == cur->bc_ra[lev])
923 		return 0;
924 
925 	cur->bc_ra[lev] |= lr;
926 	block = XFS_BUF_TO_BLOCK(cur->bc_bufs[lev]);
927 
928 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
929 		return xfs_btree_readahead_lblock(cur, lr, block);
930 	return xfs_btree_readahead_sblock(cur, lr, block);
931 }
932 
933 STATIC int
934 xfs_btree_ptr_to_daddr(
935 	struct xfs_btree_cur	*cur,
936 	union xfs_btree_ptr	*ptr,
937 	xfs_daddr_t		*daddr)
938 {
939 	xfs_fsblock_t		fsbno;
940 	xfs_agblock_t		agbno;
941 	int			error;
942 
943 	error = xfs_btree_check_ptr(cur, ptr, 0, 1);
944 	if (error)
945 		return error;
946 
947 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
948 		fsbno = be64_to_cpu(ptr->l);
949 		*daddr = XFS_FSB_TO_DADDR(cur->bc_mp, fsbno);
950 	} else {
951 		agbno = be32_to_cpu(ptr->s);
952 		*daddr = XFS_AGB_TO_DADDR(cur->bc_mp, cur->bc_ag.agno,
953 				agbno);
954 	}
955 
956 	return 0;
957 }
958 
959 /*
960  * Readahead @count btree blocks at the given @ptr location.
961  *
962  * We don't need to care about long or short form btrees here as we have a
963  * method of converting the ptr directly to a daddr available to us.
964  */
965 STATIC void
966 xfs_btree_readahead_ptr(
967 	struct xfs_btree_cur	*cur,
968 	union xfs_btree_ptr	*ptr,
969 	xfs_extlen_t		count)
970 {
971 	xfs_daddr_t		daddr;
972 
973 	if (xfs_btree_ptr_to_daddr(cur, ptr, &daddr))
974 		return;
975 	xfs_buf_readahead(cur->bc_mp->m_ddev_targp, daddr,
976 			  cur->bc_mp->m_bsize * count, cur->bc_ops->buf_ops);
977 }
978 
979 /*
980  * Set the buffer for level "lev" in the cursor to bp, releasing
981  * any previous buffer.
982  */
983 STATIC void
984 xfs_btree_setbuf(
985 	xfs_btree_cur_t		*cur,	/* btree cursor */
986 	int			lev,	/* level in btree */
987 	struct xfs_buf		*bp)	/* new buffer to set */
988 {
989 	struct xfs_btree_block	*b;	/* btree block */
990 
991 	if (cur->bc_bufs[lev])
992 		xfs_trans_brelse(cur->bc_tp, cur->bc_bufs[lev]);
993 	cur->bc_bufs[lev] = bp;
994 	cur->bc_ra[lev] = 0;
995 
996 	b = XFS_BUF_TO_BLOCK(bp);
997 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
998 		if (b->bb_u.l.bb_leftsib == cpu_to_be64(NULLFSBLOCK))
999 			cur->bc_ra[lev] |= XFS_BTCUR_LEFTRA;
1000 		if (b->bb_u.l.bb_rightsib == cpu_to_be64(NULLFSBLOCK))
1001 			cur->bc_ra[lev] |= XFS_BTCUR_RIGHTRA;
1002 	} else {
1003 		if (b->bb_u.s.bb_leftsib == cpu_to_be32(NULLAGBLOCK))
1004 			cur->bc_ra[lev] |= XFS_BTCUR_LEFTRA;
1005 		if (b->bb_u.s.bb_rightsib == cpu_to_be32(NULLAGBLOCK))
1006 			cur->bc_ra[lev] |= XFS_BTCUR_RIGHTRA;
1007 	}
1008 }
1009 
1010 bool
1011 xfs_btree_ptr_is_null(
1012 	struct xfs_btree_cur	*cur,
1013 	union xfs_btree_ptr	*ptr)
1014 {
1015 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
1016 		return ptr->l == cpu_to_be64(NULLFSBLOCK);
1017 	else
1018 		return ptr->s == cpu_to_be32(NULLAGBLOCK);
1019 }
1020 
1021 void
1022 xfs_btree_set_ptr_null(
1023 	struct xfs_btree_cur	*cur,
1024 	union xfs_btree_ptr	*ptr)
1025 {
1026 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
1027 		ptr->l = cpu_to_be64(NULLFSBLOCK);
1028 	else
1029 		ptr->s = cpu_to_be32(NULLAGBLOCK);
1030 }
1031 
1032 /*
1033  * Get/set/init sibling pointers
1034  */
1035 void
1036 xfs_btree_get_sibling(
1037 	struct xfs_btree_cur	*cur,
1038 	struct xfs_btree_block	*block,
1039 	union xfs_btree_ptr	*ptr,
1040 	int			lr)
1041 {
1042 	ASSERT(lr == XFS_BB_LEFTSIB || lr == XFS_BB_RIGHTSIB);
1043 
1044 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
1045 		if (lr == XFS_BB_RIGHTSIB)
1046 			ptr->l = block->bb_u.l.bb_rightsib;
1047 		else
1048 			ptr->l = block->bb_u.l.bb_leftsib;
1049 	} else {
1050 		if (lr == XFS_BB_RIGHTSIB)
1051 			ptr->s = block->bb_u.s.bb_rightsib;
1052 		else
1053 			ptr->s = block->bb_u.s.bb_leftsib;
1054 	}
1055 }
1056 
1057 void
1058 xfs_btree_set_sibling(
1059 	struct xfs_btree_cur	*cur,
1060 	struct xfs_btree_block	*block,
1061 	union xfs_btree_ptr	*ptr,
1062 	int			lr)
1063 {
1064 	ASSERT(lr == XFS_BB_LEFTSIB || lr == XFS_BB_RIGHTSIB);
1065 
1066 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
1067 		if (lr == XFS_BB_RIGHTSIB)
1068 			block->bb_u.l.bb_rightsib = ptr->l;
1069 		else
1070 			block->bb_u.l.bb_leftsib = ptr->l;
1071 	} else {
1072 		if (lr == XFS_BB_RIGHTSIB)
1073 			block->bb_u.s.bb_rightsib = ptr->s;
1074 		else
1075 			block->bb_u.s.bb_leftsib = ptr->s;
1076 	}
1077 }
1078 
1079 void
1080 xfs_btree_init_block_int(
1081 	struct xfs_mount	*mp,
1082 	struct xfs_btree_block	*buf,
1083 	xfs_daddr_t		blkno,
1084 	xfs_btnum_t		btnum,
1085 	__u16			level,
1086 	__u16			numrecs,
1087 	__u64			owner,
1088 	unsigned int		flags)
1089 {
1090 	int			crc = xfs_sb_version_hascrc(&mp->m_sb);
1091 	__u32			magic = xfs_btree_magic(crc, btnum);
1092 
1093 	buf->bb_magic = cpu_to_be32(magic);
1094 	buf->bb_level = cpu_to_be16(level);
1095 	buf->bb_numrecs = cpu_to_be16(numrecs);
1096 
1097 	if (flags & XFS_BTREE_LONG_PTRS) {
1098 		buf->bb_u.l.bb_leftsib = cpu_to_be64(NULLFSBLOCK);
1099 		buf->bb_u.l.bb_rightsib = cpu_to_be64(NULLFSBLOCK);
1100 		if (crc) {
1101 			buf->bb_u.l.bb_blkno = cpu_to_be64(blkno);
1102 			buf->bb_u.l.bb_owner = cpu_to_be64(owner);
1103 			uuid_copy(&buf->bb_u.l.bb_uuid, &mp->m_sb.sb_meta_uuid);
1104 			buf->bb_u.l.bb_pad = 0;
1105 			buf->bb_u.l.bb_lsn = 0;
1106 		}
1107 	} else {
1108 		/* owner is a 32 bit value on short blocks */
1109 		__u32 __owner = (__u32)owner;
1110 
1111 		buf->bb_u.s.bb_leftsib = cpu_to_be32(NULLAGBLOCK);
1112 		buf->bb_u.s.bb_rightsib = cpu_to_be32(NULLAGBLOCK);
1113 		if (crc) {
1114 			buf->bb_u.s.bb_blkno = cpu_to_be64(blkno);
1115 			buf->bb_u.s.bb_owner = cpu_to_be32(__owner);
1116 			uuid_copy(&buf->bb_u.s.bb_uuid, &mp->m_sb.sb_meta_uuid);
1117 			buf->bb_u.s.bb_lsn = 0;
1118 		}
1119 	}
1120 }
1121 
1122 void
1123 xfs_btree_init_block(
1124 	struct xfs_mount *mp,
1125 	struct xfs_buf	*bp,
1126 	xfs_btnum_t	btnum,
1127 	__u16		level,
1128 	__u16		numrecs,
1129 	__u64		owner)
1130 {
1131 	xfs_btree_init_block_int(mp, XFS_BUF_TO_BLOCK(bp), bp->b_bn,
1132 				 btnum, level, numrecs, owner, 0);
1133 }
1134 
1135 void
1136 xfs_btree_init_block_cur(
1137 	struct xfs_btree_cur	*cur,
1138 	struct xfs_buf		*bp,
1139 	int			level,
1140 	int			numrecs)
1141 {
1142 	__u64			owner;
1143 
1144 	/*
1145 	 * we can pull the owner from the cursor right now as the different
1146 	 * owners align directly with the pointer size of the btree. This may
1147 	 * change in future, but is safe for current users of the generic btree
1148 	 * code.
1149 	 */
1150 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
1151 		owner = cur->bc_ino.ip->i_ino;
1152 	else
1153 		owner = cur->bc_ag.agno;
1154 
1155 	xfs_btree_init_block_int(cur->bc_mp, XFS_BUF_TO_BLOCK(bp), bp->b_bn,
1156 				 cur->bc_btnum, level, numrecs,
1157 				 owner, cur->bc_flags);
1158 }
1159 
1160 /*
1161  * Return true if ptr is the last record in the btree and
1162  * we need to track updates to this record.  The decision
1163  * will be further refined in the update_lastrec method.
1164  */
1165 STATIC int
1166 xfs_btree_is_lastrec(
1167 	struct xfs_btree_cur	*cur,
1168 	struct xfs_btree_block	*block,
1169 	int			level)
1170 {
1171 	union xfs_btree_ptr	ptr;
1172 
1173 	if (level > 0)
1174 		return 0;
1175 	if (!(cur->bc_flags & XFS_BTREE_LASTREC_UPDATE))
1176 		return 0;
1177 
1178 	xfs_btree_get_sibling(cur, block, &ptr, XFS_BB_RIGHTSIB);
1179 	if (!xfs_btree_ptr_is_null(cur, &ptr))
1180 		return 0;
1181 	return 1;
1182 }
1183 
1184 STATIC void
1185 xfs_btree_buf_to_ptr(
1186 	struct xfs_btree_cur	*cur,
1187 	struct xfs_buf		*bp,
1188 	union xfs_btree_ptr	*ptr)
1189 {
1190 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
1191 		ptr->l = cpu_to_be64(XFS_DADDR_TO_FSB(cur->bc_mp,
1192 					XFS_BUF_ADDR(bp)));
1193 	else {
1194 		ptr->s = cpu_to_be32(xfs_daddr_to_agbno(cur->bc_mp,
1195 					XFS_BUF_ADDR(bp)));
1196 	}
1197 }
1198 
1199 STATIC void
1200 xfs_btree_set_refs(
1201 	struct xfs_btree_cur	*cur,
1202 	struct xfs_buf		*bp)
1203 {
1204 	switch (cur->bc_btnum) {
1205 	case XFS_BTNUM_BNO:
1206 	case XFS_BTNUM_CNT:
1207 		xfs_buf_set_ref(bp, XFS_ALLOC_BTREE_REF);
1208 		break;
1209 	case XFS_BTNUM_INO:
1210 	case XFS_BTNUM_FINO:
1211 		xfs_buf_set_ref(bp, XFS_INO_BTREE_REF);
1212 		break;
1213 	case XFS_BTNUM_BMAP:
1214 		xfs_buf_set_ref(bp, XFS_BMAP_BTREE_REF);
1215 		break;
1216 	case XFS_BTNUM_RMAP:
1217 		xfs_buf_set_ref(bp, XFS_RMAP_BTREE_REF);
1218 		break;
1219 	case XFS_BTNUM_REFC:
1220 		xfs_buf_set_ref(bp, XFS_REFC_BTREE_REF);
1221 		break;
1222 	default:
1223 		ASSERT(0);
1224 	}
1225 }
1226 
1227 int
1228 xfs_btree_get_buf_block(
1229 	struct xfs_btree_cur	*cur,
1230 	union xfs_btree_ptr	*ptr,
1231 	struct xfs_btree_block	**block,
1232 	struct xfs_buf		**bpp)
1233 {
1234 	struct xfs_mount	*mp = cur->bc_mp;
1235 	xfs_daddr_t		d;
1236 	int			error;
1237 
1238 	error = xfs_btree_ptr_to_daddr(cur, ptr, &d);
1239 	if (error)
1240 		return error;
1241 	error = xfs_trans_get_buf(cur->bc_tp, mp->m_ddev_targp, d, mp->m_bsize,
1242 			0, bpp);
1243 	if (error)
1244 		return error;
1245 
1246 	(*bpp)->b_ops = cur->bc_ops->buf_ops;
1247 	*block = XFS_BUF_TO_BLOCK(*bpp);
1248 	return 0;
1249 }
1250 
1251 /*
1252  * Read in the buffer at the given ptr and return the buffer and
1253  * the block pointer within the buffer.
1254  */
1255 STATIC int
1256 xfs_btree_read_buf_block(
1257 	struct xfs_btree_cur	*cur,
1258 	union xfs_btree_ptr	*ptr,
1259 	int			flags,
1260 	struct xfs_btree_block	**block,
1261 	struct xfs_buf		**bpp)
1262 {
1263 	struct xfs_mount	*mp = cur->bc_mp;
1264 	xfs_daddr_t		d;
1265 	int			error;
1266 
1267 	/* need to sort out how callers deal with failures first */
1268 	ASSERT(!(flags & XBF_TRYLOCK));
1269 
1270 	error = xfs_btree_ptr_to_daddr(cur, ptr, &d);
1271 	if (error)
1272 		return error;
1273 	error = xfs_trans_read_buf(mp, cur->bc_tp, mp->m_ddev_targp, d,
1274 				   mp->m_bsize, flags, bpp,
1275 				   cur->bc_ops->buf_ops);
1276 	if (error)
1277 		return error;
1278 
1279 	xfs_btree_set_refs(cur, *bpp);
1280 	*block = XFS_BUF_TO_BLOCK(*bpp);
1281 	return 0;
1282 }
1283 
1284 /*
1285  * Copy keys from one btree block to another.
1286  */
1287 void
1288 xfs_btree_copy_keys(
1289 	struct xfs_btree_cur	*cur,
1290 	union xfs_btree_key	*dst_key,
1291 	union xfs_btree_key	*src_key,
1292 	int			numkeys)
1293 {
1294 	ASSERT(numkeys >= 0);
1295 	memcpy(dst_key, src_key, numkeys * cur->bc_ops->key_len);
1296 }
1297 
1298 /*
1299  * Copy records from one btree block to another.
1300  */
1301 STATIC void
1302 xfs_btree_copy_recs(
1303 	struct xfs_btree_cur	*cur,
1304 	union xfs_btree_rec	*dst_rec,
1305 	union xfs_btree_rec	*src_rec,
1306 	int			numrecs)
1307 {
1308 	ASSERT(numrecs >= 0);
1309 	memcpy(dst_rec, src_rec, numrecs * cur->bc_ops->rec_len);
1310 }
1311 
1312 /*
1313  * Copy block pointers from one btree block to another.
1314  */
1315 void
1316 xfs_btree_copy_ptrs(
1317 	struct xfs_btree_cur	*cur,
1318 	union xfs_btree_ptr	*dst_ptr,
1319 	const union xfs_btree_ptr *src_ptr,
1320 	int			numptrs)
1321 {
1322 	ASSERT(numptrs >= 0);
1323 	memcpy(dst_ptr, src_ptr, numptrs * xfs_btree_ptr_len(cur));
1324 }
1325 
1326 /*
1327  * Shift keys one index left/right inside a single btree block.
1328  */
1329 STATIC void
1330 xfs_btree_shift_keys(
1331 	struct xfs_btree_cur	*cur,
1332 	union xfs_btree_key	*key,
1333 	int			dir,
1334 	int			numkeys)
1335 {
1336 	char			*dst_key;
1337 
1338 	ASSERT(numkeys >= 0);
1339 	ASSERT(dir == 1 || dir == -1);
1340 
1341 	dst_key = (char *)key + (dir * cur->bc_ops->key_len);
1342 	memmove(dst_key, key, numkeys * cur->bc_ops->key_len);
1343 }
1344 
1345 /*
1346  * Shift records one index left/right inside a single btree block.
1347  */
1348 STATIC void
1349 xfs_btree_shift_recs(
1350 	struct xfs_btree_cur	*cur,
1351 	union xfs_btree_rec	*rec,
1352 	int			dir,
1353 	int			numrecs)
1354 {
1355 	char			*dst_rec;
1356 
1357 	ASSERT(numrecs >= 0);
1358 	ASSERT(dir == 1 || dir == -1);
1359 
1360 	dst_rec = (char *)rec + (dir * cur->bc_ops->rec_len);
1361 	memmove(dst_rec, rec, numrecs * cur->bc_ops->rec_len);
1362 }
1363 
1364 /*
1365  * Shift block pointers one index left/right inside a single btree block.
1366  */
1367 STATIC void
1368 xfs_btree_shift_ptrs(
1369 	struct xfs_btree_cur	*cur,
1370 	union xfs_btree_ptr	*ptr,
1371 	int			dir,
1372 	int			numptrs)
1373 {
1374 	char			*dst_ptr;
1375 
1376 	ASSERT(numptrs >= 0);
1377 	ASSERT(dir == 1 || dir == -1);
1378 
1379 	dst_ptr = (char *)ptr + (dir * xfs_btree_ptr_len(cur));
1380 	memmove(dst_ptr, ptr, numptrs * xfs_btree_ptr_len(cur));
1381 }
1382 
1383 /*
1384  * Log key values from the btree block.
1385  */
1386 STATIC void
1387 xfs_btree_log_keys(
1388 	struct xfs_btree_cur	*cur,
1389 	struct xfs_buf		*bp,
1390 	int			first,
1391 	int			last)
1392 {
1393 
1394 	if (bp) {
1395 		xfs_trans_buf_set_type(cur->bc_tp, bp, XFS_BLFT_BTREE_BUF);
1396 		xfs_trans_log_buf(cur->bc_tp, bp,
1397 				  xfs_btree_key_offset(cur, first),
1398 				  xfs_btree_key_offset(cur, last + 1) - 1);
1399 	} else {
1400 		xfs_trans_log_inode(cur->bc_tp, cur->bc_ino.ip,
1401 				xfs_ilog_fbroot(cur->bc_ino.whichfork));
1402 	}
1403 }
1404 
1405 /*
1406  * Log record values from the btree block.
1407  */
1408 void
1409 xfs_btree_log_recs(
1410 	struct xfs_btree_cur	*cur,
1411 	struct xfs_buf		*bp,
1412 	int			first,
1413 	int			last)
1414 {
1415 
1416 	xfs_trans_buf_set_type(cur->bc_tp, bp, XFS_BLFT_BTREE_BUF);
1417 	xfs_trans_log_buf(cur->bc_tp, bp,
1418 			  xfs_btree_rec_offset(cur, first),
1419 			  xfs_btree_rec_offset(cur, last + 1) - 1);
1420 
1421 }
1422 
1423 /*
1424  * Log block pointer fields from a btree block (nonleaf).
1425  */
1426 STATIC void
1427 xfs_btree_log_ptrs(
1428 	struct xfs_btree_cur	*cur,	/* btree cursor */
1429 	struct xfs_buf		*bp,	/* buffer containing btree block */
1430 	int			first,	/* index of first pointer to log */
1431 	int			last)	/* index of last pointer to log */
1432 {
1433 
1434 	if (bp) {
1435 		struct xfs_btree_block	*block = XFS_BUF_TO_BLOCK(bp);
1436 		int			level = xfs_btree_get_level(block);
1437 
1438 		xfs_trans_buf_set_type(cur->bc_tp, bp, XFS_BLFT_BTREE_BUF);
1439 		xfs_trans_log_buf(cur->bc_tp, bp,
1440 				xfs_btree_ptr_offset(cur, first, level),
1441 				xfs_btree_ptr_offset(cur, last + 1, level) - 1);
1442 	} else {
1443 		xfs_trans_log_inode(cur->bc_tp, cur->bc_ino.ip,
1444 			xfs_ilog_fbroot(cur->bc_ino.whichfork));
1445 	}
1446 
1447 }
1448 
1449 /*
1450  * Log fields from a btree block header.
1451  */
1452 void
1453 xfs_btree_log_block(
1454 	struct xfs_btree_cur	*cur,	/* btree cursor */
1455 	struct xfs_buf		*bp,	/* buffer containing btree block */
1456 	int			fields)	/* mask of fields: XFS_BB_... */
1457 {
1458 	int			first;	/* first byte offset logged */
1459 	int			last;	/* last byte offset logged */
1460 	static const short	soffsets[] = {	/* table of offsets (short) */
1461 		offsetof(struct xfs_btree_block, bb_magic),
1462 		offsetof(struct xfs_btree_block, bb_level),
1463 		offsetof(struct xfs_btree_block, bb_numrecs),
1464 		offsetof(struct xfs_btree_block, bb_u.s.bb_leftsib),
1465 		offsetof(struct xfs_btree_block, bb_u.s.bb_rightsib),
1466 		offsetof(struct xfs_btree_block, bb_u.s.bb_blkno),
1467 		offsetof(struct xfs_btree_block, bb_u.s.bb_lsn),
1468 		offsetof(struct xfs_btree_block, bb_u.s.bb_uuid),
1469 		offsetof(struct xfs_btree_block, bb_u.s.bb_owner),
1470 		offsetof(struct xfs_btree_block, bb_u.s.bb_crc),
1471 		XFS_BTREE_SBLOCK_CRC_LEN
1472 	};
1473 	static const short	loffsets[] = {	/* table of offsets (long) */
1474 		offsetof(struct xfs_btree_block, bb_magic),
1475 		offsetof(struct xfs_btree_block, bb_level),
1476 		offsetof(struct xfs_btree_block, bb_numrecs),
1477 		offsetof(struct xfs_btree_block, bb_u.l.bb_leftsib),
1478 		offsetof(struct xfs_btree_block, bb_u.l.bb_rightsib),
1479 		offsetof(struct xfs_btree_block, bb_u.l.bb_blkno),
1480 		offsetof(struct xfs_btree_block, bb_u.l.bb_lsn),
1481 		offsetof(struct xfs_btree_block, bb_u.l.bb_uuid),
1482 		offsetof(struct xfs_btree_block, bb_u.l.bb_owner),
1483 		offsetof(struct xfs_btree_block, bb_u.l.bb_crc),
1484 		offsetof(struct xfs_btree_block, bb_u.l.bb_pad),
1485 		XFS_BTREE_LBLOCK_CRC_LEN
1486 	};
1487 
1488 	if (bp) {
1489 		int nbits;
1490 
1491 		if (cur->bc_flags & XFS_BTREE_CRC_BLOCKS) {
1492 			/*
1493 			 * We don't log the CRC when updating a btree
1494 			 * block but instead recreate it during log
1495 			 * recovery.  As the log buffers have checksums
1496 			 * of their own this is safe and avoids logging a crc
1497 			 * update in a lot of places.
1498 			 */
1499 			if (fields == XFS_BB_ALL_BITS)
1500 				fields = XFS_BB_ALL_BITS_CRC;
1501 			nbits = XFS_BB_NUM_BITS_CRC;
1502 		} else {
1503 			nbits = XFS_BB_NUM_BITS;
1504 		}
1505 		xfs_btree_offsets(fields,
1506 				  (cur->bc_flags & XFS_BTREE_LONG_PTRS) ?
1507 					loffsets : soffsets,
1508 				  nbits, &first, &last);
1509 		xfs_trans_buf_set_type(cur->bc_tp, bp, XFS_BLFT_BTREE_BUF);
1510 		xfs_trans_log_buf(cur->bc_tp, bp, first, last);
1511 	} else {
1512 		xfs_trans_log_inode(cur->bc_tp, cur->bc_ino.ip,
1513 			xfs_ilog_fbroot(cur->bc_ino.whichfork));
1514 	}
1515 }
1516 
1517 /*
1518  * Increment cursor by one record at the level.
1519  * For nonzero levels the leaf-ward information is untouched.
1520  */
1521 int						/* error */
1522 xfs_btree_increment(
1523 	struct xfs_btree_cur	*cur,
1524 	int			level,
1525 	int			*stat)		/* success/failure */
1526 {
1527 	struct xfs_btree_block	*block;
1528 	union xfs_btree_ptr	ptr;
1529 	struct xfs_buf		*bp;
1530 	int			error;		/* error return value */
1531 	int			lev;
1532 
1533 	ASSERT(level < cur->bc_nlevels);
1534 
1535 	/* Read-ahead to the right at this level. */
1536 	xfs_btree_readahead(cur, level, XFS_BTCUR_RIGHTRA);
1537 
1538 	/* Get a pointer to the btree block. */
1539 	block = xfs_btree_get_block(cur, level, &bp);
1540 
1541 #ifdef DEBUG
1542 	error = xfs_btree_check_block(cur, block, level, bp);
1543 	if (error)
1544 		goto error0;
1545 #endif
1546 
1547 	/* We're done if we remain in the block after the increment. */
1548 	if (++cur->bc_ptrs[level] <= xfs_btree_get_numrecs(block))
1549 		goto out1;
1550 
1551 	/* Fail if we just went off the right edge of the tree. */
1552 	xfs_btree_get_sibling(cur, block, &ptr, XFS_BB_RIGHTSIB);
1553 	if (xfs_btree_ptr_is_null(cur, &ptr))
1554 		goto out0;
1555 
1556 	XFS_BTREE_STATS_INC(cur, increment);
1557 
1558 	/*
1559 	 * March up the tree incrementing pointers.
1560 	 * Stop when we don't go off the right edge of a block.
1561 	 */
1562 	for (lev = level + 1; lev < cur->bc_nlevels; lev++) {
1563 		block = xfs_btree_get_block(cur, lev, &bp);
1564 
1565 #ifdef DEBUG
1566 		error = xfs_btree_check_block(cur, block, lev, bp);
1567 		if (error)
1568 			goto error0;
1569 #endif
1570 
1571 		if (++cur->bc_ptrs[lev] <= xfs_btree_get_numrecs(block))
1572 			break;
1573 
1574 		/* Read-ahead the right block for the next loop. */
1575 		xfs_btree_readahead(cur, lev, XFS_BTCUR_RIGHTRA);
1576 	}
1577 
1578 	/*
1579 	 * If we went off the root then we are either seriously
1580 	 * confused or have the tree root in an inode.
1581 	 */
1582 	if (lev == cur->bc_nlevels) {
1583 		if (cur->bc_flags & XFS_BTREE_ROOT_IN_INODE)
1584 			goto out0;
1585 		ASSERT(0);
1586 		error = -EFSCORRUPTED;
1587 		goto error0;
1588 	}
1589 	ASSERT(lev < cur->bc_nlevels);
1590 
1591 	/*
1592 	 * Now walk back down the tree, fixing up the cursor's buffer
1593 	 * pointers and key numbers.
1594 	 */
1595 	for (block = xfs_btree_get_block(cur, lev, &bp); lev > level; ) {
1596 		union xfs_btree_ptr	*ptrp;
1597 
1598 		ptrp = xfs_btree_ptr_addr(cur, cur->bc_ptrs[lev], block);
1599 		--lev;
1600 		error = xfs_btree_read_buf_block(cur, ptrp, 0, &block, &bp);
1601 		if (error)
1602 			goto error0;
1603 
1604 		xfs_btree_setbuf(cur, lev, bp);
1605 		cur->bc_ptrs[lev] = 1;
1606 	}
1607 out1:
1608 	*stat = 1;
1609 	return 0;
1610 
1611 out0:
1612 	*stat = 0;
1613 	return 0;
1614 
1615 error0:
1616 	return error;
1617 }
1618 
1619 /*
1620  * Decrement cursor by one record at the level.
1621  * For nonzero levels the leaf-ward information is untouched.
1622  */
1623 int						/* error */
1624 xfs_btree_decrement(
1625 	struct xfs_btree_cur	*cur,
1626 	int			level,
1627 	int			*stat)		/* success/failure */
1628 {
1629 	struct xfs_btree_block	*block;
1630 	struct xfs_buf		*bp;
1631 	int			error;		/* error return value */
1632 	int			lev;
1633 	union xfs_btree_ptr	ptr;
1634 
1635 	ASSERT(level < cur->bc_nlevels);
1636 
1637 	/* Read-ahead to the left at this level. */
1638 	xfs_btree_readahead(cur, level, XFS_BTCUR_LEFTRA);
1639 
1640 	/* We're done if we remain in the block after the decrement. */
1641 	if (--cur->bc_ptrs[level] > 0)
1642 		goto out1;
1643 
1644 	/* Get a pointer to the btree block. */
1645 	block = xfs_btree_get_block(cur, level, &bp);
1646 
1647 #ifdef DEBUG
1648 	error = xfs_btree_check_block(cur, block, level, bp);
1649 	if (error)
1650 		goto error0;
1651 #endif
1652 
1653 	/* Fail if we just went off the left edge of the tree. */
1654 	xfs_btree_get_sibling(cur, block, &ptr, XFS_BB_LEFTSIB);
1655 	if (xfs_btree_ptr_is_null(cur, &ptr))
1656 		goto out0;
1657 
1658 	XFS_BTREE_STATS_INC(cur, decrement);
1659 
1660 	/*
1661 	 * March up the tree decrementing pointers.
1662 	 * Stop when we don't go off the left edge of a block.
1663 	 */
1664 	for (lev = level + 1; lev < cur->bc_nlevels; lev++) {
1665 		if (--cur->bc_ptrs[lev] > 0)
1666 			break;
1667 		/* Read-ahead the left block for the next loop. */
1668 		xfs_btree_readahead(cur, lev, XFS_BTCUR_LEFTRA);
1669 	}
1670 
1671 	/*
1672 	 * If we went off the root then we are seriously confused.
1673 	 * or the root of the tree is in an inode.
1674 	 */
1675 	if (lev == cur->bc_nlevels) {
1676 		if (cur->bc_flags & XFS_BTREE_ROOT_IN_INODE)
1677 			goto out0;
1678 		ASSERT(0);
1679 		error = -EFSCORRUPTED;
1680 		goto error0;
1681 	}
1682 	ASSERT(lev < cur->bc_nlevels);
1683 
1684 	/*
1685 	 * Now walk back down the tree, fixing up the cursor's buffer
1686 	 * pointers and key numbers.
1687 	 */
1688 	for (block = xfs_btree_get_block(cur, lev, &bp); lev > level; ) {
1689 		union xfs_btree_ptr	*ptrp;
1690 
1691 		ptrp = xfs_btree_ptr_addr(cur, cur->bc_ptrs[lev], block);
1692 		--lev;
1693 		error = xfs_btree_read_buf_block(cur, ptrp, 0, &block, &bp);
1694 		if (error)
1695 			goto error0;
1696 		xfs_btree_setbuf(cur, lev, bp);
1697 		cur->bc_ptrs[lev] = xfs_btree_get_numrecs(block);
1698 	}
1699 out1:
1700 	*stat = 1;
1701 	return 0;
1702 
1703 out0:
1704 	*stat = 0;
1705 	return 0;
1706 
1707 error0:
1708 	return error;
1709 }
1710 
1711 int
1712 xfs_btree_lookup_get_block(
1713 	struct xfs_btree_cur	*cur,	/* btree cursor */
1714 	int			level,	/* level in the btree */
1715 	union xfs_btree_ptr	*pp,	/* ptr to btree block */
1716 	struct xfs_btree_block	**blkp) /* return btree block */
1717 {
1718 	struct xfs_buf		*bp;	/* buffer pointer for btree block */
1719 	xfs_daddr_t		daddr;
1720 	int			error = 0;
1721 
1722 	/* special case the root block if in an inode */
1723 	if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
1724 	    (level == cur->bc_nlevels - 1)) {
1725 		*blkp = xfs_btree_get_iroot(cur);
1726 		return 0;
1727 	}
1728 
1729 	/*
1730 	 * If the old buffer at this level for the disk address we are
1731 	 * looking for re-use it.
1732 	 *
1733 	 * Otherwise throw it away and get a new one.
1734 	 */
1735 	bp = cur->bc_bufs[level];
1736 	error = xfs_btree_ptr_to_daddr(cur, pp, &daddr);
1737 	if (error)
1738 		return error;
1739 	if (bp && XFS_BUF_ADDR(bp) == daddr) {
1740 		*blkp = XFS_BUF_TO_BLOCK(bp);
1741 		return 0;
1742 	}
1743 
1744 	error = xfs_btree_read_buf_block(cur, pp, 0, blkp, &bp);
1745 	if (error)
1746 		return error;
1747 
1748 	/* Check the inode owner since the verifiers don't. */
1749 	if (xfs_sb_version_hascrc(&cur->bc_mp->m_sb) &&
1750 	    !(cur->bc_ino.flags & XFS_BTCUR_BMBT_INVALID_OWNER) &&
1751 	    (cur->bc_flags & XFS_BTREE_LONG_PTRS) &&
1752 	    be64_to_cpu((*blkp)->bb_u.l.bb_owner) !=
1753 			cur->bc_ino.ip->i_ino)
1754 		goto out_bad;
1755 
1756 	/* Did we get the level we were looking for? */
1757 	if (be16_to_cpu((*blkp)->bb_level) != level)
1758 		goto out_bad;
1759 
1760 	/* Check that internal nodes have at least one record. */
1761 	if (level != 0 && be16_to_cpu((*blkp)->bb_numrecs) == 0)
1762 		goto out_bad;
1763 
1764 	xfs_btree_setbuf(cur, level, bp);
1765 	return 0;
1766 
1767 out_bad:
1768 	*blkp = NULL;
1769 	xfs_buf_mark_corrupt(bp);
1770 	xfs_trans_brelse(cur->bc_tp, bp);
1771 	return -EFSCORRUPTED;
1772 }
1773 
1774 /*
1775  * Get current search key.  For level 0 we don't actually have a key
1776  * structure so we make one up from the record.  For all other levels
1777  * we just return the right key.
1778  */
1779 STATIC union xfs_btree_key *
1780 xfs_lookup_get_search_key(
1781 	struct xfs_btree_cur	*cur,
1782 	int			level,
1783 	int			keyno,
1784 	struct xfs_btree_block	*block,
1785 	union xfs_btree_key	*kp)
1786 {
1787 	if (level == 0) {
1788 		cur->bc_ops->init_key_from_rec(kp,
1789 				xfs_btree_rec_addr(cur, keyno, block));
1790 		return kp;
1791 	}
1792 
1793 	return xfs_btree_key_addr(cur, keyno, block);
1794 }
1795 
1796 /*
1797  * Lookup the record.  The cursor is made to point to it, based on dir.
1798  * stat is set to 0 if can't find any such record, 1 for success.
1799  */
1800 int					/* error */
1801 xfs_btree_lookup(
1802 	struct xfs_btree_cur	*cur,	/* btree cursor */
1803 	xfs_lookup_t		dir,	/* <=, ==, or >= */
1804 	int			*stat)	/* success/failure */
1805 {
1806 	struct xfs_btree_block	*block;	/* current btree block */
1807 	int64_t			diff;	/* difference for the current key */
1808 	int			error;	/* error return value */
1809 	int			keyno;	/* current key number */
1810 	int			level;	/* level in the btree */
1811 	union xfs_btree_ptr	*pp;	/* ptr to btree block */
1812 	union xfs_btree_ptr	ptr;	/* ptr to btree block */
1813 
1814 	XFS_BTREE_STATS_INC(cur, lookup);
1815 
1816 	/* No such thing as a zero-level tree. */
1817 	if (XFS_IS_CORRUPT(cur->bc_mp, cur->bc_nlevels == 0))
1818 		return -EFSCORRUPTED;
1819 
1820 	block = NULL;
1821 	keyno = 0;
1822 
1823 	/* initialise start pointer from cursor */
1824 	cur->bc_ops->init_ptr_from_cur(cur, &ptr);
1825 	pp = &ptr;
1826 
1827 	/*
1828 	 * Iterate over each level in the btree, starting at the root.
1829 	 * For each level above the leaves, find the key we need, based
1830 	 * on the lookup record, then follow the corresponding block
1831 	 * pointer down to the next level.
1832 	 */
1833 	for (level = cur->bc_nlevels - 1, diff = 1; level >= 0; level--) {
1834 		/* Get the block we need to do the lookup on. */
1835 		error = xfs_btree_lookup_get_block(cur, level, pp, &block);
1836 		if (error)
1837 			goto error0;
1838 
1839 		if (diff == 0) {
1840 			/*
1841 			 * If we already had a key match at a higher level, we
1842 			 * know we need to use the first entry in this block.
1843 			 */
1844 			keyno = 1;
1845 		} else {
1846 			/* Otherwise search this block. Do a binary search. */
1847 
1848 			int	high;	/* high entry number */
1849 			int	low;	/* low entry number */
1850 
1851 			/* Set low and high entry numbers, 1-based. */
1852 			low = 1;
1853 			high = xfs_btree_get_numrecs(block);
1854 			if (!high) {
1855 				/* Block is empty, must be an empty leaf. */
1856 				if (level != 0 || cur->bc_nlevels != 1) {
1857 					XFS_CORRUPTION_ERROR(__func__,
1858 							XFS_ERRLEVEL_LOW,
1859 							cur->bc_mp, block,
1860 							sizeof(*block));
1861 					return -EFSCORRUPTED;
1862 				}
1863 
1864 				cur->bc_ptrs[0] = dir != XFS_LOOKUP_LE;
1865 				*stat = 0;
1866 				return 0;
1867 			}
1868 
1869 			/* Binary search the block. */
1870 			while (low <= high) {
1871 				union xfs_btree_key	key;
1872 				union xfs_btree_key	*kp;
1873 
1874 				XFS_BTREE_STATS_INC(cur, compare);
1875 
1876 				/* keyno is average of low and high. */
1877 				keyno = (low + high) >> 1;
1878 
1879 				/* Get current search key */
1880 				kp = xfs_lookup_get_search_key(cur, level,
1881 						keyno, block, &key);
1882 
1883 				/*
1884 				 * Compute difference to get next direction:
1885 				 *  - less than, move right
1886 				 *  - greater than, move left
1887 				 *  - equal, we're done
1888 				 */
1889 				diff = cur->bc_ops->key_diff(cur, kp);
1890 				if (diff < 0)
1891 					low = keyno + 1;
1892 				else if (diff > 0)
1893 					high = keyno - 1;
1894 				else
1895 					break;
1896 			}
1897 		}
1898 
1899 		/*
1900 		 * If there are more levels, set up for the next level
1901 		 * by getting the block number and filling in the cursor.
1902 		 */
1903 		if (level > 0) {
1904 			/*
1905 			 * If we moved left, need the previous key number,
1906 			 * unless there isn't one.
1907 			 */
1908 			if (diff > 0 && --keyno < 1)
1909 				keyno = 1;
1910 			pp = xfs_btree_ptr_addr(cur, keyno, block);
1911 
1912 			error = xfs_btree_debug_check_ptr(cur, pp, 0, level);
1913 			if (error)
1914 				goto error0;
1915 
1916 			cur->bc_ptrs[level] = keyno;
1917 		}
1918 	}
1919 
1920 	/* Done with the search. See if we need to adjust the results. */
1921 	if (dir != XFS_LOOKUP_LE && diff < 0) {
1922 		keyno++;
1923 		/*
1924 		 * If ge search and we went off the end of the block, but it's
1925 		 * not the last block, we're in the wrong block.
1926 		 */
1927 		xfs_btree_get_sibling(cur, block, &ptr, XFS_BB_RIGHTSIB);
1928 		if (dir == XFS_LOOKUP_GE &&
1929 		    keyno > xfs_btree_get_numrecs(block) &&
1930 		    !xfs_btree_ptr_is_null(cur, &ptr)) {
1931 			int	i;
1932 
1933 			cur->bc_ptrs[0] = keyno;
1934 			error = xfs_btree_increment(cur, 0, &i);
1935 			if (error)
1936 				goto error0;
1937 			if (XFS_IS_CORRUPT(cur->bc_mp, i != 1))
1938 				return -EFSCORRUPTED;
1939 			*stat = 1;
1940 			return 0;
1941 		}
1942 	} else if (dir == XFS_LOOKUP_LE && diff > 0)
1943 		keyno--;
1944 	cur->bc_ptrs[0] = keyno;
1945 
1946 	/* Return if we succeeded or not. */
1947 	if (keyno == 0 || keyno > xfs_btree_get_numrecs(block))
1948 		*stat = 0;
1949 	else if (dir != XFS_LOOKUP_EQ || diff == 0)
1950 		*stat = 1;
1951 	else
1952 		*stat = 0;
1953 	return 0;
1954 
1955 error0:
1956 	return error;
1957 }
1958 
1959 /* Find the high key storage area from a regular key. */
1960 union xfs_btree_key *
1961 xfs_btree_high_key_from_key(
1962 	struct xfs_btree_cur	*cur,
1963 	union xfs_btree_key	*key)
1964 {
1965 	ASSERT(cur->bc_flags & XFS_BTREE_OVERLAPPING);
1966 	return (union xfs_btree_key *)((char *)key +
1967 			(cur->bc_ops->key_len / 2));
1968 }
1969 
1970 /* Determine the low (and high if overlapped) keys of a leaf block */
1971 STATIC void
1972 xfs_btree_get_leaf_keys(
1973 	struct xfs_btree_cur	*cur,
1974 	struct xfs_btree_block	*block,
1975 	union xfs_btree_key	*key)
1976 {
1977 	union xfs_btree_key	max_hkey;
1978 	union xfs_btree_key	hkey;
1979 	union xfs_btree_rec	*rec;
1980 	union xfs_btree_key	*high;
1981 	int			n;
1982 
1983 	rec = xfs_btree_rec_addr(cur, 1, block);
1984 	cur->bc_ops->init_key_from_rec(key, rec);
1985 
1986 	if (cur->bc_flags & XFS_BTREE_OVERLAPPING) {
1987 
1988 		cur->bc_ops->init_high_key_from_rec(&max_hkey, rec);
1989 		for (n = 2; n <= xfs_btree_get_numrecs(block); n++) {
1990 			rec = xfs_btree_rec_addr(cur, n, block);
1991 			cur->bc_ops->init_high_key_from_rec(&hkey, rec);
1992 			if (cur->bc_ops->diff_two_keys(cur, &hkey, &max_hkey)
1993 					> 0)
1994 				max_hkey = hkey;
1995 		}
1996 
1997 		high = xfs_btree_high_key_from_key(cur, key);
1998 		memcpy(high, &max_hkey, cur->bc_ops->key_len / 2);
1999 	}
2000 }
2001 
2002 /* Determine the low (and high if overlapped) keys of a node block */
2003 STATIC void
2004 xfs_btree_get_node_keys(
2005 	struct xfs_btree_cur	*cur,
2006 	struct xfs_btree_block	*block,
2007 	union xfs_btree_key	*key)
2008 {
2009 	union xfs_btree_key	*hkey;
2010 	union xfs_btree_key	*max_hkey;
2011 	union xfs_btree_key	*high;
2012 	int			n;
2013 
2014 	if (cur->bc_flags & XFS_BTREE_OVERLAPPING) {
2015 		memcpy(key, xfs_btree_key_addr(cur, 1, block),
2016 				cur->bc_ops->key_len / 2);
2017 
2018 		max_hkey = xfs_btree_high_key_addr(cur, 1, block);
2019 		for (n = 2; n <= xfs_btree_get_numrecs(block); n++) {
2020 			hkey = xfs_btree_high_key_addr(cur, n, block);
2021 			if (cur->bc_ops->diff_two_keys(cur, hkey, max_hkey) > 0)
2022 				max_hkey = hkey;
2023 		}
2024 
2025 		high = xfs_btree_high_key_from_key(cur, key);
2026 		memcpy(high, max_hkey, cur->bc_ops->key_len / 2);
2027 	} else {
2028 		memcpy(key, xfs_btree_key_addr(cur, 1, block),
2029 				cur->bc_ops->key_len);
2030 	}
2031 }
2032 
2033 /* Derive the keys for any btree block. */
2034 void
2035 xfs_btree_get_keys(
2036 	struct xfs_btree_cur	*cur,
2037 	struct xfs_btree_block	*block,
2038 	union xfs_btree_key	*key)
2039 {
2040 	if (be16_to_cpu(block->bb_level) == 0)
2041 		xfs_btree_get_leaf_keys(cur, block, key);
2042 	else
2043 		xfs_btree_get_node_keys(cur, block, key);
2044 }
2045 
2046 /*
2047  * Decide if we need to update the parent keys of a btree block.  For
2048  * a standard btree this is only necessary if we're updating the first
2049  * record/key.  For an overlapping btree, we must always update the
2050  * keys because the highest key can be in any of the records or keys
2051  * in the block.
2052  */
2053 static inline bool
2054 xfs_btree_needs_key_update(
2055 	struct xfs_btree_cur	*cur,
2056 	int			ptr)
2057 {
2058 	return (cur->bc_flags & XFS_BTREE_OVERLAPPING) || ptr == 1;
2059 }
2060 
2061 /*
2062  * Update the low and high parent keys of the given level, progressing
2063  * towards the root.  If force_all is false, stop if the keys for a given
2064  * level do not need updating.
2065  */
2066 STATIC int
2067 __xfs_btree_updkeys(
2068 	struct xfs_btree_cur	*cur,
2069 	int			level,
2070 	struct xfs_btree_block	*block,
2071 	struct xfs_buf		*bp0,
2072 	bool			force_all)
2073 {
2074 	union xfs_btree_key	key;	/* keys from current level */
2075 	union xfs_btree_key	*lkey;	/* keys from the next level up */
2076 	union xfs_btree_key	*hkey;
2077 	union xfs_btree_key	*nlkey;	/* keys from the next level up */
2078 	union xfs_btree_key	*nhkey;
2079 	struct xfs_buf		*bp;
2080 	int			ptr;
2081 
2082 	ASSERT(cur->bc_flags & XFS_BTREE_OVERLAPPING);
2083 
2084 	/* Exit if there aren't any parent levels to update. */
2085 	if (level + 1 >= cur->bc_nlevels)
2086 		return 0;
2087 
2088 	trace_xfs_btree_updkeys(cur, level, bp0);
2089 
2090 	lkey = &key;
2091 	hkey = xfs_btree_high_key_from_key(cur, lkey);
2092 	xfs_btree_get_keys(cur, block, lkey);
2093 	for (level++; level < cur->bc_nlevels; level++) {
2094 #ifdef DEBUG
2095 		int		error;
2096 #endif
2097 		block = xfs_btree_get_block(cur, level, &bp);
2098 		trace_xfs_btree_updkeys(cur, level, bp);
2099 #ifdef DEBUG
2100 		error = xfs_btree_check_block(cur, block, level, bp);
2101 		if (error)
2102 			return error;
2103 #endif
2104 		ptr = cur->bc_ptrs[level];
2105 		nlkey = xfs_btree_key_addr(cur, ptr, block);
2106 		nhkey = xfs_btree_high_key_addr(cur, ptr, block);
2107 		if (!force_all &&
2108 		    !(cur->bc_ops->diff_two_keys(cur, nlkey, lkey) != 0 ||
2109 		      cur->bc_ops->diff_two_keys(cur, nhkey, hkey) != 0))
2110 			break;
2111 		xfs_btree_copy_keys(cur, nlkey, lkey, 1);
2112 		xfs_btree_log_keys(cur, bp, ptr, ptr);
2113 		if (level + 1 >= cur->bc_nlevels)
2114 			break;
2115 		xfs_btree_get_node_keys(cur, block, lkey);
2116 	}
2117 
2118 	return 0;
2119 }
2120 
2121 /* Update all the keys from some level in cursor back to the root. */
2122 STATIC int
2123 xfs_btree_updkeys_force(
2124 	struct xfs_btree_cur	*cur,
2125 	int			level)
2126 {
2127 	struct xfs_buf		*bp;
2128 	struct xfs_btree_block	*block;
2129 
2130 	block = xfs_btree_get_block(cur, level, &bp);
2131 	return __xfs_btree_updkeys(cur, level, block, bp, true);
2132 }
2133 
2134 /*
2135  * Update the parent keys of the given level, progressing towards the root.
2136  */
2137 STATIC int
2138 xfs_btree_update_keys(
2139 	struct xfs_btree_cur	*cur,
2140 	int			level)
2141 {
2142 	struct xfs_btree_block	*block;
2143 	struct xfs_buf		*bp;
2144 	union xfs_btree_key	*kp;
2145 	union xfs_btree_key	key;
2146 	int			ptr;
2147 
2148 	ASSERT(level >= 0);
2149 
2150 	block = xfs_btree_get_block(cur, level, &bp);
2151 	if (cur->bc_flags & XFS_BTREE_OVERLAPPING)
2152 		return __xfs_btree_updkeys(cur, level, block, bp, false);
2153 
2154 	/*
2155 	 * Go up the tree from this level toward the root.
2156 	 * At each level, update the key value to the value input.
2157 	 * Stop when we reach a level where the cursor isn't pointing
2158 	 * at the first entry in the block.
2159 	 */
2160 	xfs_btree_get_keys(cur, block, &key);
2161 	for (level++, ptr = 1; ptr == 1 && level < cur->bc_nlevels; level++) {
2162 #ifdef DEBUG
2163 		int		error;
2164 #endif
2165 		block = xfs_btree_get_block(cur, level, &bp);
2166 #ifdef DEBUG
2167 		error = xfs_btree_check_block(cur, block, level, bp);
2168 		if (error)
2169 			return error;
2170 #endif
2171 		ptr = cur->bc_ptrs[level];
2172 		kp = xfs_btree_key_addr(cur, ptr, block);
2173 		xfs_btree_copy_keys(cur, kp, &key, 1);
2174 		xfs_btree_log_keys(cur, bp, ptr, ptr);
2175 	}
2176 
2177 	return 0;
2178 }
2179 
2180 /*
2181  * Update the record referred to by cur to the value in the
2182  * given record. This either works (return 0) or gets an
2183  * EFSCORRUPTED error.
2184  */
2185 int
2186 xfs_btree_update(
2187 	struct xfs_btree_cur	*cur,
2188 	union xfs_btree_rec	*rec)
2189 {
2190 	struct xfs_btree_block	*block;
2191 	struct xfs_buf		*bp;
2192 	int			error;
2193 	int			ptr;
2194 	union xfs_btree_rec	*rp;
2195 
2196 	/* Pick up the current block. */
2197 	block = xfs_btree_get_block(cur, 0, &bp);
2198 
2199 #ifdef DEBUG
2200 	error = xfs_btree_check_block(cur, block, 0, bp);
2201 	if (error)
2202 		goto error0;
2203 #endif
2204 	/* Get the address of the rec to be updated. */
2205 	ptr = cur->bc_ptrs[0];
2206 	rp = xfs_btree_rec_addr(cur, ptr, block);
2207 
2208 	/* Fill in the new contents and log them. */
2209 	xfs_btree_copy_recs(cur, rp, rec, 1);
2210 	xfs_btree_log_recs(cur, bp, ptr, ptr);
2211 
2212 	/*
2213 	 * If we are tracking the last record in the tree and
2214 	 * we are at the far right edge of the tree, update it.
2215 	 */
2216 	if (xfs_btree_is_lastrec(cur, block, 0)) {
2217 		cur->bc_ops->update_lastrec(cur, block, rec,
2218 					    ptr, LASTREC_UPDATE);
2219 	}
2220 
2221 	/* Pass new key value up to our parent. */
2222 	if (xfs_btree_needs_key_update(cur, ptr)) {
2223 		error = xfs_btree_update_keys(cur, 0);
2224 		if (error)
2225 			goto error0;
2226 	}
2227 
2228 	return 0;
2229 
2230 error0:
2231 	return error;
2232 }
2233 
2234 /*
2235  * Move 1 record left from cur/level if possible.
2236  * Update cur to reflect the new path.
2237  */
2238 STATIC int					/* error */
2239 xfs_btree_lshift(
2240 	struct xfs_btree_cur	*cur,
2241 	int			level,
2242 	int			*stat)		/* success/failure */
2243 {
2244 	struct xfs_buf		*lbp;		/* left buffer pointer */
2245 	struct xfs_btree_block	*left;		/* left btree block */
2246 	int			lrecs;		/* left record count */
2247 	struct xfs_buf		*rbp;		/* right buffer pointer */
2248 	struct xfs_btree_block	*right;		/* right btree block */
2249 	struct xfs_btree_cur	*tcur;		/* temporary btree cursor */
2250 	int			rrecs;		/* right record count */
2251 	union xfs_btree_ptr	lptr;		/* left btree pointer */
2252 	union xfs_btree_key	*rkp = NULL;	/* right btree key */
2253 	union xfs_btree_ptr	*rpp = NULL;	/* right address pointer */
2254 	union xfs_btree_rec	*rrp = NULL;	/* right record pointer */
2255 	int			error;		/* error return value */
2256 	int			i;
2257 
2258 	if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
2259 	    level == cur->bc_nlevels - 1)
2260 		goto out0;
2261 
2262 	/* Set up variables for this block as "right". */
2263 	right = xfs_btree_get_block(cur, level, &rbp);
2264 
2265 #ifdef DEBUG
2266 	error = xfs_btree_check_block(cur, right, level, rbp);
2267 	if (error)
2268 		goto error0;
2269 #endif
2270 
2271 	/* If we've got no left sibling then we can't shift an entry left. */
2272 	xfs_btree_get_sibling(cur, right, &lptr, XFS_BB_LEFTSIB);
2273 	if (xfs_btree_ptr_is_null(cur, &lptr))
2274 		goto out0;
2275 
2276 	/*
2277 	 * If the cursor entry is the one that would be moved, don't
2278 	 * do it... it's too complicated.
2279 	 */
2280 	if (cur->bc_ptrs[level] <= 1)
2281 		goto out0;
2282 
2283 	/* Set up the left neighbor as "left". */
2284 	error = xfs_btree_read_buf_block(cur, &lptr, 0, &left, &lbp);
2285 	if (error)
2286 		goto error0;
2287 
2288 	/* If it's full, it can't take another entry. */
2289 	lrecs = xfs_btree_get_numrecs(left);
2290 	if (lrecs == cur->bc_ops->get_maxrecs(cur, level))
2291 		goto out0;
2292 
2293 	rrecs = xfs_btree_get_numrecs(right);
2294 
2295 	/*
2296 	 * We add one entry to the left side and remove one for the right side.
2297 	 * Account for it here, the changes will be updated on disk and logged
2298 	 * later.
2299 	 */
2300 	lrecs++;
2301 	rrecs--;
2302 
2303 	XFS_BTREE_STATS_INC(cur, lshift);
2304 	XFS_BTREE_STATS_ADD(cur, moves, 1);
2305 
2306 	/*
2307 	 * If non-leaf, copy a key and a ptr to the left block.
2308 	 * Log the changes to the left block.
2309 	 */
2310 	if (level > 0) {
2311 		/* It's a non-leaf.  Move keys and pointers. */
2312 		union xfs_btree_key	*lkp;	/* left btree key */
2313 		union xfs_btree_ptr	*lpp;	/* left address pointer */
2314 
2315 		lkp = xfs_btree_key_addr(cur, lrecs, left);
2316 		rkp = xfs_btree_key_addr(cur, 1, right);
2317 
2318 		lpp = xfs_btree_ptr_addr(cur, lrecs, left);
2319 		rpp = xfs_btree_ptr_addr(cur, 1, right);
2320 
2321 		error = xfs_btree_debug_check_ptr(cur, rpp, 0, level);
2322 		if (error)
2323 			goto error0;
2324 
2325 		xfs_btree_copy_keys(cur, lkp, rkp, 1);
2326 		xfs_btree_copy_ptrs(cur, lpp, rpp, 1);
2327 
2328 		xfs_btree_log_keys(cur, lbp, lrecs, lrecs);
2329 		xfs_btree_log_ptrs(cur, lbp, lrecs, lrecs);
2330 
2331 		ASSERT(cur->bc_ops->keys_inorder(cur,
2332 			xfs_btree_key_addr(cur, lrecs - 1, left), lkp));
2333 	} else {
2334 		/* It's a leaf.  Move records.  */
2335 		union xfs_btree_rec	*lrp;	/* left record pointer */
2336 
2337 		lrp = xfs_btree_rec_addr(cur, lrecs, left);
2338 		rrp = xfs_btree_rec_addr(cur, 1, right);
2339 
2340 		xfs_btree_copy_recs(cur, lrp, rrp, 1);
2341 		xfs_btree_log_recs(cur, lbp, lrecs, lrecs);
2342 
2343 		ASSERT(cur->bc_ops->recs_inorder(cur,
2344 			xfs_btree_rec_addr(cur, lrecs - 1, left), lrp));
2345 	}
2346 
2347 	xfs_btree_set_numrecs(left, lrecs);
2348 	xfs_btree_log_block(cur, lbp, XFS_BB_NUMRECS);
2349 
2350 	xfs_btree_set_numrecs(right, rrecs);
2351 	xfs_btree_log_block(cur, rbp, XFS_BB_NUMRECS);
2352 
2353 	/*
2354 	 * Slide the contents of right down one entry.
2355 	 */
2356 	XFS_BTREE_STATS_ADD(cur, moves, rrecs - 1);
2357 	if (level > 0) {
2358 		/* It's a nonleaf. operate on keys and ptrs */
2359 		for (i = 0; i < rrecs; i++) {
2360 			error = xfs_btree_debug_check_ptr(cur, rpp, i + 1, level);
2361 			if (error)
2362 				goto error0;
2363 		}
2364 
2365 		xfs_btree_shift_keys(cur,
2366 				xfs_btree_key_addr(cur, 2, right),
2367 				-1, rrecs);
2368 		xfs_btree_shift_ptrs(cur,
2369 				xfs_btree_ptr_addr(cur, 2, right),
2370 				-1, rrecs);
2371 
2372 		xfs_btree_log_keys(cur, rbp, 1, rrecs);
2373 		xfs_btree_log_ptrs(cur, rbp, 1, rrecs);
2374 	} else {
2375 		/* It's a leaf. operate on records */
2376 		xfs_btree_shift_recs(cur,
2377 			xfs_btree_rec_addr(cur, 2, right),
2378 			-1, rrecs);
2379 		xfs_btree_log_recs(cur, rbp, 1, rrecs);
2380 	}
2381 
2382 	/*
2383 	 * Using a temporary cursor, update the parent key values of the
2384 	 * block on the left.
2385 	 */
2386 	if (cur->bc_flags & XFS_BTREE_OVERLAPPING) {
2387 		error = xfs_btree_dup_cursor(cur, &tcur);
2388 		if (error)
2389 			goto error0;
2390 		i = xfs_btree_firstrec(tcur, level);
2391 		if (XFS_IS_CORRUPT(tcur->bc_mp, i != 1)) {
2392 			error = -EFSCORRUPTED;
2393 			goto error0;
2394 		}
2395 
2396 		error = xfs_btree_decrement(tcur, level, &i);
2397 		if (error)
2398 			goto error1;
2399 
2400 		/* Update the parent high keys of the left block, if needed. */
2401 		error = xfs_btree_update_keys(tcur, level);
2402 		if (error)
2403 			goto error1;
2404 
2405 		xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
2406 	}
2407 
2408 	/* Update the parent keys of the right block. */
2409 	error = xfs_btree_update_keys(cur, level);
2410 	if (error)
2411 		goto error0;
2412 
2413 	/* Slide the cursor value left one. */
2414 	cur->bc_ptrs[level]--;
2415 
2416 	*stat = 1;
2417 	return 0;
2418 
2419 out0:
2420 	*stat = 0;
2421 	return 0;
2422 
2423 error0:
2424 	return error;
2425 
2426 error1:
2427 	xfs_btree_del_cursor(tcur, XFS_BTREE_ERROR);
2428 	return error;
2429 }
2430 
2431 /*
2432  * Move 1 record right from cur/level if possible.
2433  * Update cur to reflect the new path.
2434  */
2435 STATIC int					/* error */
2436 xfs_btree_rshift(
2437 	struct xfs_btree_cur	*cur,
2438 	int			level,
2439 	int			*stat)		/* success/failure */
2440 {
2441 	struct xfs_buf		*lbp;		/* left buffer pointer */
2442 	struct xfs_btree_block	*left;		/* left btree block */
2443 	struct xfs_buf		*rbp;		/* right buffer pointer */
2444 	struct xfs_btree_block	*right;		/* right btree block */
2445 	struct xfs_btree_cur	*tcur;		/* temporary btree cursor */
2446 	union xfs_btree_ptr	rptr;		/* right block pointer */
2447 	union xfs_btree_key	*rkp;		/* right btree key */
2448 	int			rrecs;		/* right record count */
2449 	int			lrecs;		/* left record count */
2450 	int			error;		/* error return value */
2451 	int			i;		/* loop counter */
2452 
2453 	if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
2454 	    (level == cur->bc_nlevels - 1))
2455 		goto out0;
2456 
2457 	/* Set up variables for this block as "left". */
2458 	left = xfs_btree_get_block(cur, level, &lbp);
2459 
2460 #ifdef DEBUG
2461 	error = xfs_btree_check_block(cur, left, level, lbp);
2462 	if (error)
2463 		goto error0;
2464 #endif
2465 
2466 	/* If we've got no right sibling then we can't shift an entry right. */
2467 	xfs_btree_get_sibling(cur, left, &rptr, XFS_BB_RIGHTSIB);
2468 	if (xfs_btree_ptr_is_null(cur, &rptr))
2469 		goto out0;
2470 
2471 	/*
2472 	 * If the cursor entry is the one that would be moved, don't
2473 	 * do it... it's too complicated.
2474 	 */
2475 	lrecs = xfs_btree_get_numrecs(left);
2476 	if (cur->bc_ptrs[level] >= lrecs)
2477 		goto out0;
2478 
2479 	/* Set up the right neighbor as "right". */
2480 	error = xfs_btree_read_buf_block(cur, &rptr, 0, &right, &rbp);
2481 	if (error)
2482 		goto error0;
2483 
2484 	/* If it's full, it can't take another entry. */
2485 	rrecs = xfs_btree_get_numrecs(right);
2486 	if (rrecs == cur->bc_ops->get_maxrecs(cur, level))
2487 		goto out0;
2488 
2489 	XFS_BTREE_STATS_INC(cur, rshift);
2490 	XFS_BTREE_STATS_ADD(cur, moves, rrecs);
2491 
2492 	/*
2493 	 * Make a hole at the start of the right neighbor block, then
2494 	 * copy the last left block entry to the hole.
2495 	 */
2496 	if (level > 0) {
2497 		/* It's a nonleaf. make a hole in the keys and ptrs */
2498 		union xfs_btree_key	*lkp;
2499 		union xfs_btree_ptr	*lpp;
2500 		union xfs_btree_ptr	*rpp;
2501 
2502 		lkp = xfs_btree_key_addr(cur, lrecs, left);
2503 		lpp = xfs_btree_ptr_addr(cur, lrecs, left);
2504 		rkp = xfs_btree_key_addr(cur, 1, right);
2505 		rpp = xfs_btree_ptr_addr(cur, 1, right);
2506 
2507 		for (i = rrecs - 1; i >= 0; i--) {
2508 			error = xfs_btree_debug_check_ptr(cur, rpp, i, level);
2509 			if (error)
2510 				goto error0;
2511 		}
2512 
2513 		xfs_btree_shift_keys(cur, rkp, 1, rrecs);
2514 		xfs_btree_shift_ptrs(cur, rpp, 1, rrecs);
2515 
2516 		error = xfs_btree_debug_check_ptr(cur, lpp, 0, level);
2517 		if (error)
2518 			goto error0;
2519 
2520 		/* Now put the new data in, and log it. */
2521 		xfs_btree_copy_keys(cur, rkp, lkp, 1);
2522 		xfs_btree_copy_ptrs(cur, rpp, lpp, 1);
2523 
2524 		xfs_btree_log_keys(cur, rbp, 1, rrecs + 1);
2525 		xfs_btree_log_ptrs(cur, rbp, 1, rrecs + 1);
2526 
2527 		ASSERT(cur->bc_ops->keys_inorder(cur, rkp,
2528 			xfs_btree_key_addr(cur, 2, right)));
2529 	} else {
2530 		/* It's a leaf. make a hole in the records */
2531 		union xfs_btree_rec	*lrp;
2532 		union xfs_btree_rec	*rrp;
2533 
2534 		lrp = xfs_btree_rec_addr(cur, lrecs, left);
2535 		rrp = xfs_btree_rec_addr(cur, 1, right);
2536 
2537 		xfs_btree_shift_recs(cur, rrp, 1, rrecs);
2538 
2539 		/* Now put the new data in, and log it. */
2540 		xfs_btree_copy_recs(cur, rrp, lrp, 1);
2541 		xfs_btree_log_recs(cur, rbp, 1, rrecs + 1);
2542 	}
2543 
2544 	/*
2545 	 * Decrement and log left's numrecs, bump and log right's numrecs.
2546 	 */
2547 	xfs_btree_set_numrecs(left, --lrecs);
2548 	xfs_btree_log_block(cur, lbp, XFS_BB_NUMRECS);
2549 
2550 	xfs_btree_set_numrecs(right, ++rrecs);
2551 	xfs_btree_log_block(cur, rbp, XFS_BB_NUMRECS);
2552 
2553 	/*
2554 	 * Using a temporary cursor, update the parent key values of the
2555 	 * block on the right.
2556 	 */
2557 	error = xfs_btree_dup_cursor(cur, &tcur);
2558 	if (error)
2559 		goto error0;
2560 	i = xfs_btree_lastrec(tcur, level);
2561 	if (XFS_IS_CORRUPT(tcur->bc_mp, i != 1)) {
2562 		error = -EFSCORRUPTED;
2563 		goto error0;
2564 	}
2565 
2566 	error = xfs_btree_increment(tcur, level, &i);
2567 	if (error)
2568 		goto error1;
2569 
2570 	/* Update the parent high keys of the left block, if needed. */
2571 	if (cur->bc_flags & XFS_BTREE_OVERLAPPING) {
2572 		error = xfs_btree_update_keys(cur, level);
2573 		if (error)
2574 			goto error1;
2575 	}
2576 
2577 	/* Update the parent keys of the right block. */
2578 	error = xfs_btree_update_keys(tcur, level);
2579 	if (error)
2580 		goto error1;
2581 
2582 	xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
2583 
2584 	*stat = 1;
2585 	return 0;
2586 
2587 out0:
2588 	*stat = 0;
2589 	return 0;
2590 
2591 error0:
2592 	return error;
2593 
2594 error1:
2595 	xfs_btree_del_cursor(tcur, XFS_BTREE_ERROR);
2596 	return error;
2597 }
2598 
2599 /*
2600  * Split cur/level block in half.
2601  * Return new block number and the key to its first
2602  * record (to be inserted into parent).
2603  */
2604 STATIC int					/* error */
2605 __xfs_btree_split(
2606 	struct xfs_btree_cur	*cur,
2607 	int			level,
2608 	union xfs_btree_ptr	*ptrp,
2609 	union xfs_btree_key	*key,
2610 	struct xfs_btree_cur	**curp,
2611 	int			*stat)		/* success/failure */
2612 {
2613 	union xfs_btree_ptr	lptr;		/* left sibling block ptr */
2614 	struct xfs_buf		*lbp;		/* left buffer pointer */
2615 	struct xfs_btree_block	*left;		/* left btree block */
2616 	union xfs_btree_ptr	rptr;		/* right sibling block ptr */
2617 	struct xfs_buf		*rbp;		/* right buffer pointer */
2618 	struct xfs_btree_block	*right;		/* right btree block */
2619 	union xfs_btree_ptr	rrptr;		/* right-right sibling ptr */
2620 	struct xfs_buf		*rrbp;		/* right-right buffer pointer */
2621 	struct xfs_btree_block	*rrblock;	/* right-right btree block */
2622 	int			lrecs;
2623 	int			rrecs;
2624 	int			src_index;
2625 	int			error;		/* error return value */
2626 	int			i;
2627 
2628 	XFS_BTREE_STATS_INC(cur, split);
2629 
2630 	/* Set up left block (current one). */
2631 	left = xfs_btree_get_block(cur, level, &lbp);
2632 
2633 #ifdef DEBUG
2634 	error = xfs_btree_check_block(cur, left, level, lbp);
2635 	if (error)
2636 		goto error0;
2637 #endif
2638 
2639 	xfs_btree_buf_to_ptr(cur, lbp, &lptr);
2640 
2641 	/* Allocate the new block. If we can't do it, we're toast. Give up. */
2642 	error = cur->bc_ops->alloc_block(cur, &lptr, &rptr, stat);
2643 	if (error)
2644 		goto error0;
2645 	if (*stat == 0)
2646 		goto out0;
2647 	XFS_BTREE_STATS_INC(cur, alloc);
2648 
2649 	/* Set up the new block as "right". */
2650 	error = xfs_btree_get_buf_block(cur, &rptr, &right, &rbp);
2651 	if (error)
2652 		goto error0;
2653 
2654 	/* Fill in the btree header for the new right block. */
2655 	xfs_btree_init_block_cur(cur, rbp, xfs_btree_get_level(left), 0);
2656 
2657 	/*
2658 	 * Split the entries between the old and the new block evenly.
2659 	 * Make sure that if there's an odd number of entries now, that
2660 	 * each new block will have the same number of entries.
2661 	 */
2662 	lrecs = xfs_btree_get_numrecs(left);
2663 	rrecs = lrecs / 2;
2664 	if ((lrecs & 1) && cur->bc_ptrs[level] <= rrecs + 1)
2665 		rrecs++;
2666 	src_index = (lrecs - rrecs + 1);
2667 
2668 	XFS_BTREE_STATS_ADD(cur, moves, rrecs);
2669 
2670 	/* Adjust numrecs for the later get_*_keys() calls. */
2671 	lrecs -= rrecs;
2672 	xfs_btree_set_numrecs(left, lrecs);
2673 	xfs_btree_set_numrecs(right, xfs_btree_get_numrecs(right) + rrecs);
2674 
2675 	/*
2676 	 * Copy btree block entries from the left block over to the
2677 	 * new block, the right. Update the right block and log the
2678 	 * changes.
2679 	 */
2680 	if (level > 0) {
2681 		/* It's a non-leaf.  Move keys and pointers. */
2682 		union xfs_btree_key	*lkp;	/* left btree key */
2683 		union xfs_btree_ptr	*lpp;	/* left address pointer */
2684 		union xfs_btree_key	*rkp;	/* right btree key */
2685 		union xfs_btree_ptr	*rpp;	/* right address pointer */
2686 
2687 		lkp = xfs_btree_key_addr(cur, src_index, left);
2688 		lpp = xfs_btree_ptr_addr(cur, src_index, left);
2689 		rkp = xfs_btree_key_addr(cur, 1, right);
2690 		rpp = xfs_btree_ptr_addr(cur, 1, right);
2691 
2692 		for (i = src_index; i < rrecs; i++) {
2693 			error = xfs_btree_debug_check_ptr(cur, lpp, i, level);
2694 			if (error)
2695 				goto error0;
2696 		}
2697 
2698 		/* Copy the keys & pointers to the new block. */
2699 		xfs_btree_copy_keys(cur, rkp, lkp, rrecs);
2700 		xfs_btree_copy_ptrs(cur, rpp, lpp, rrecs);
2701 
2702 		xfs_btree_log_keys(cur, rbp, 1, rrecs);
2703 		xfs_btree_log_ptrs(cur, rbp, 1, rrecs);
2704 
2705 		/* Stash the keys of the new block for later insertion. */
2706 		xfs_btree_get_node_keys(cur, right, key);
2707 	} else {
2708 		/* It's a leaf.  Move records.  */
2709 		union xfs_btree_rec	*lrp;	/* left record pointer */
2710 		union xfs_btree_rec	*rrp;	/* right record pointer */
2711 
2712 		lrp = xfs_btree_rec_addr(cur, src_index, left);
2713 		rrp = xfs_btree_rec_addr(cur, 1, right);
2714 
2715 		/* Copy records to the new block. */
2716 		xfs_btree_copy_recs(cur, rrp, lrp, rrecs);
2717 		xfs_btree_log_recs(cur, rbp, 1, rrecs);
2718 
2719 		/* Stash the keys of the new block for later insertion. */
2720 		xfs_btree_get_leaf_keys(cur, right, key);
2721 	}
2722 
2723 	/*
2724 	 * Find the left block number by looking in the buffer.
2725 	 * Adjust sibling pointers.
2726 	 */
2727 	xfs_btree_get_sibling(cur, left, &rrptr, XFS_BB_RIGHTSIB);
2728 	xfs_btree_set_sibling(cur, right, &rrptr, XFS_BB_RIGHTSIB);
2729 	xfs_btree_set_sibling(cur, right, &lptr, XFS_BB_LEFTSIB);
2730 	xfs_btree_set_sibling(cur, left, &rptr, XFS_BB_RIGHTSIB);
2731 
2732 	xfs_btree_log_block(cur, rbp, XFS_BB_ALL_BITS);
2733 	xfs_btree_log_block(cur, lbp, XFS_BB_NUMRECS | XFS_BB_RIGHTSIB);
2734 
2735 	/*
2736 	 * If there's a block to the new block's right, make that block
2737 	 * point back to right instead of to left.
2738 	 */
2739 	if (!xfs_btree_ptr_is_null(cur, &rrptr)) {
2740 		error = xfs_btree_read_buf_block(cur, &rrptr,
2741 							0, &rrblock, &rrbp);
2742 		if (error)
2743 			goto error0;
2744 		xfs_btree_set_sibling(cur, rrblock, &rptr, XFS_BB_LEFTSIB);
2745 		xfs_btree_log_block(cur, rrbp, XFS_BB_LEFTSIB);
2746 	}
2747 
2748 	/* Update the parent high keys of the left block, if needed. */
2749 	if (cur->bc_flags & XFS_BTREE_OVERLAPPING) {
2750 		error = xfs_btree_update_keys(cur, level);
2751 		if (error)
2752 			goto error0;
2753 	}
2754 
2755 	/*
2756 	 * If the cursor is really in the right block, move it there.
2757 	 * If it's just pointing past the last entry in left, then we'll
2758 	 * insert there, so don't change anything in that case.
2759 	 */
2760 	if (cur->bc_ptrs[level] > lrecs + 1) {
2761 		xfs_btree_setbuf(cur, level, rbp);
2762 		cur->bc_ptrs[level] -= lrecs;
2763 	}
2764 	/*
2765 	 * If there are more levels, we'll need another cursor which refers
2766 	 * the right block, no matter where this cursor was.
2767 	 */
2768 	if (level + 1 < cur->bc_nlevels) {
2769 		error = xfs_btree_dup_cursor(cur, curp);
2770 		if (error)
2771 			goto error0;
2772 		(*curp)->bc_ptrs[level + 1]++;
2773 	}
2774 	*ptrp = rptr;
2775 	*stat = 1;
2776 	return 0;
2777 out0:
2778 	*stat = 0;
2779 	return 0;
2780 
2781 error0:
2782 	return error;
2783 }
2784 
2785 struct xfs_btree_split_args {
2786 	struct xfs_btree_cur	*cur;
2787 	int			level;
2788 	union xfs_btree_ptr	*ptrp;
2789 	union xfs_btree_key	*key;
2790 	struct xfs_btree_cur	**curp;
2791 	int			*stat;		/* success/failure */
2792 	int			result;
2793 	bool			kswapd;	/* allocation in kswapd context */
2794 	struct completion	*done;
2795 	struct work_struct	work;
2796 };
2797 
2798 /*
2799  * Stack switching interfaces for allocation
2800  */
2801 static void
2802 xfs_btree_split_worker(
2803 	struct work_struct	*work)
2804 {
2805 	struct xfs_btree_split_args	*args = container_of(work,
2806 						struct xfs_btree_split_args, work);
2807 	unsigned long		pflags;
2808 	unsigned long		new_pflags = PF_MEMALLOC_NOFS;
2809 
2810 	/*
2811 	 * we are in a transaction context here, but may also be doing work
2812 	 * in kswapd context, and hence we may need to inherit that state
2813 	 * temporarily to ensure that we don't block waiting for memory reclaim
2814 	 * in any way.
2815 	 */
2816 	if (args->kswapd)
2817 		new_pflags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
2818 
2819 	current_set_flags_nested(&pflags, new_pflags);
2820 
2821 	args->result = __xfs_btree_split(args->cur, args->level, args->ptrp,
2822 					 args->key, args->curp, args->stat);
2823 	complete(args->done);
2824 
2825 	current_restore_flags_nested(&pflags, new_pflags);
2826 }
2827 
2828 /*
2829  * BMBT split requests often come in with little stack to work on. Push
2830  * them off to a worker thread so there is lots of stack to use. For the other
2831  * btree types, just call directly to avoid the context switch overhead here.
2832  */
2833 STATIC int					/* error */
2834 xfs_btree_split(
2835 	struct xfs_btree_cur	*cur,
2836 	int			level,
2837 	union xfs_btree_ptr	*ptrp,
2838 	union xfs_btree_key	*key,
2839 	struct xfs_btree_cur	**curp,
2840 	int			*stat)		/* success/failure */
2841 {
2842 	struct xfs_btree_split_args	args;
2843 	DECLARE_COMPLETION_ONSTACK(done);
2844 
2845 	if (cur->bc_btnum != XFS_BTNUM_BMAP)
2846 		return __xfs_btree_split(cur, level, ptrp, key, curp, stat);
2847 
2848 	args.cur = cur;
2849 	args.level = level;
2850 	args.ptrp = ptrp;
2851 	args.key = key;
2852 	args.curp = curp;
2853 	args.stat = stat;
2854 	args.done = &done;
2855 	args.kswapd = current_is_kswapd();
2856 	INIT_WORK_ONSTACK(&args.work, xfs_btree_split_worker);
2857 	queue_work(xfs_alloc_wq, &args.work);
2858 	wait_for_completion(&done);
2859 	destroy_work_on_stack(&args.work);
2860 	return args.result;
2861 }
2862 
2863 
2864 /*
2865  * Copy the old inode root contents into a real block and make the
2866  * broot point to it.
2867  */
2868 int						/* error */
2869 xfs_btree_new_iroot(
2870 	struct xfs_btree_cur	*cur,		/* btree cursor */
2871 	int			*logflags,	/* logging flags for inode */
2872 	int			*stat)		/* return status - 0 fail */
2873 {
2874 	struct xfs_buf		*cbp;		/* buffer for cblock */
2875 	struct xfs_btree_block	*block;		/* btree block */
2876 	struct xfs_btree_block	*cblock;	/* child btree block */
2877 	union xfs_btree_key	*ckp;		/* child key pointer */
2878 	union xfs_btree_ptr	*cpp;		/* child ptr pointer */
2879 	union xfs_btree_key	*kp;		/* pointer to btree key */
2880 	union xfs_btree_ptr	*pp;		/* pointer to block addr */
2881 	union xfs_btree_ptr	nptr;		/* new block addr */
2882 	int			level;		/* btree level */
2883 	int			error;		/* error return code */
2884 	int			i;		/* loop counter */
2885 
2886 	XFS_BTREE_STATS_INC(cur, newroot);
2887 
2888 	ASSERT(cur->bc_flags & XFS_BTREE_ROOT_IN_INODE);
2889 
2890 	level = cur->bc_nlevels - 1;
2891 
2892 	block = xfs_btree_get_iroot(cur);
2893 	pp = xfs_btree_ptr_addr(cur, 1, block);
2894 
2895 	/* Allocate the new block. If we can't do it, we're toast. Give up. */
2896 	error = cur->bc_ops->alloc_block(cur, pp, &nptr, stat);
2897 	if (error)
2898 		goto error0;
2899 	if (*stat == 0)
2900 		return 0;
2901 
2902 	XFS_BTREE_STATS_INC(cur, alloc);
2903 
2904 	/* Copy the root into a real block. */
2905 	error = xfs_btree_get_buf_block(cur, &nptr, &cblock, &cbp);
2906 	if (error)
2907 		goto error0;
2908 
2909 	/*
2910 	 * we can't just memcpy() the root in for CRC enabled btree blocks.
2911 	 * In that case have to also ensure the blkno remains correct
2912 	 */
2913 	memcpy(cblock, block, xfs_btree_block_len(cur));
2914 	if (cur->bc_flags & XFS_BTREE_CRC_BLOCKS) {
2915 		if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
2916 			cblock->bb_u.l.bb_blkno = cpu_to_be64(cbp->b_bn);
2917 		else
2918 			cblock->bb_u.s.bb_blkno = cpu_to_be64(cbp->b_bn);
2919 	}
2920 
2921 	be16_add_cpu(&block->bb_level, 1);
2922 	xfs_btree_set_numrecs(block, 1);
2923 	cur->bc_nlevels++;
2924 	cur->bc_ptrs[level + 1] = 1;
2925 
2926 	kp = xfs_btree_key_addr(cur, 1, block);
2927 	ckp = xfs_btree_key_addr(cur, 1, cblock);
2928 	xfs_btree_copy_keys(cur, ckp, kp, xfs_btree_get_numrecs(cblock));
2929 
2930 	cpp = xfs_btree_ptr_addr(cur, 1, cblock);
2931 	for (i = 0; i < be16_to_cpu(cblock->bb_numrecs); i++) {
2932 		error = xfs_btree_debug_check_ptr(cur, pp, i, level);
2933 		if (error)
2934 			goto error0;
2935 	}
2936 
2937 	xfs_btree_copy_ptrs(cur, cpp, pp, xfs_btree_get_numrecs(cblock));
2938 
2939 	error = xfs_btree_debug_check_ptr(cur, &nptr, 0, level);
2940 	if (error)
2941 		goto error0;
2942 
2943 	xfs_btree_copy_ptrs(cur, pp, &nptr, 1);
2944 
2945 	xfs_iroot_realloc(cur->bc_ino.ip,
2946 			  1 - xfs_btree_get_numrecs(cblock),
2947 			  cur->bc_ino.whichfork);
2948 
2949 	xfs_btree_setbuf(cur, level, cbp);
2950 
2951 	/*
2952 	 * Do all this logging at the end so that
2953 	 * the root is at the right level.
2954 	 */
2955 	xfs_btree_log_block(cur, cbp, XFS_BB_ALL_BITS);
2956 	xfs_btree_log_keys(cur, cbp, 1, be16_to_cpu(cblock->bb_numrecs));
2957 	xfs_btree_log_ptrs(cur, cbp, 1, be16_to_cpu(cblock->bb_numrecs));
2958 
2959 	*logflags |=
2960 		XFS_ILOG_CORE | xfs_ilog_fbroot(cur->bc_ino.whichfork);
2961 	*stat = 1;
2962 	return 0;
2963 error0:
2964 	return error;
2965 }
2966 
2967 /*
2968  * Allocate a new root block, fill it in.
2969  */
2970 STATIC int				/* error */
2971 xfs_btree_new_root(
2972 	struct xfs_btree_cur	*cur,	/* btree cursor */
2973 	int			*stat)	/* success/failure */
2974 {
2975 	struct xfs_btree_block	*block;	/* one half of the old root block */
2976 	struct xfs_buf		*bp;	/* buffer containing block */
2977 	int			error;	/* error return value */
2978 	struct xfs_buf		*lbp;	/* left buffer pointer */
2979 	struct xfs_btree_block	*left;	/* left btree block */
2980 	struct xfs_buf		*nbp;	/* new (root) buffer */
2981 	struct xfs_btree_block	*new;	/* new (root) btree block */
2982 	int			nptr;	/* new value for key index, 1 or 2 */
2983 	struct xfs_buf		*rbp;	/* right buffer pointer */
2984 	struct xfs_btree_block	*right;	/* right btree block */
2985 	union xfs_btree_ptr	rptr;
2986 	union xfs_btree_ptr	lptr;
2987 
2988 	XFS_BTREE_STATS_INC(cur, newroot);
2989 
2990 	/* initialise our start point from the cursor */
2991 	cur->bc_ops->init_ptr_from_cur(cur, &rptr);
2992 
2993 	/* Allocate the new block. If we can't do it, we're toast. Give up. */
2994 	error = cur->bc_ops->alloc_block(cur, &rptr, &lptr, stat);
2995 	if (error)
2996 		goto error0;
2997 	if (*stat == 0)
2998 		goto out0;
2999 	XFS_BTREE_STATS_INC(cur, alloc);
3000 
3001 	/* Set up the new block. */
3002 	error = xfs_btree_get_buf_block(cur, &lptr, &new, &nbp);
3003 	if (error)
3004 		goto error0;
3005 
3006 	/* Set the root in the holding structure  increasing the level by 1. */
3007 	cur->bc_ops->set_root(cur, &lptr, 1);
3008 
3009 	/*
3010 	 * At the previous root level there are now two blocks: the old root,
3011 	 * and the new block generated when it was split.  We don't know which
3012 	 * one the cursor is pointing at, so we set up variables "left" and
3013 	 * "right" for each case.
3014 	 */
3015 	block = xfs_btree_get_block(cur, cur->bc_nlevels - 1, &bp);
3016 
3017 #ifdef DEBUG
3018 	error = xfs_btree_check_block(cur, block, cur->bc_nlevels - 1, bp);
3019 	if (error)
3020 		goto error0;
3021 #endif
3022 
3023 	xfs_btree_get_sibling(cur, block, &rptr, XFS_BB_RIGHTSIB);
3024 	if (!xfs_btree_ptr_is_null(cur, &rptr)) {
3025 		/* Our block is left, pick up the right block. */
3026 		lbp = bp;
3027 		xfs_btree_buf_to_ptr(cur, lbp, &lptr);
3028 		left = block;
3029 		error = xfs_btree_read_buf_block(cur, &rptr, 0, &right, &rbp);
3030 		if (error)
3031 			goto error0;
3032 		bp = rbp;
3033 		nptr = 1;
3034 	} else {
3035 		/* Our block is right, pick up the left block. */
3036 		rbp = bp;
3037 		xfs_btree_buf_to_ptr(cur, rbp, &rptr);
3038 		right = block;
3039 		xfs_btree_get_sibling(cur, right, &lptr, XFS_BB_LEFTSIB);
3040 		error = xfs_btree_read_buf_block(cur, &lptr, 0, &left, &lbp);
3041 		if (error)
3042 			goto error0;
3043 		bp = lbp;
3044 		nptr = 2;
3045 	}
3046 
3047 	/* Fill in the new block's btree header and log it. */
3048 	xfs_btree_init_block_cur(cur, nbp, cur->bc_nlevels, 2);
3049 	xfs_btree_log_block(cur, nbp, XFS_BB_ALL_BITS);
3050 	ASSERT(!xfs_btree_ptr_is_null(cur, &lptr) &&
3051 			!xfs_btree_ptr_is_null(cur, &rptr));
3052 
3053 	/* Fill in the key data in the new root. */
3054 	if (xfs_btree_get_level(left) > 0) {
3055 		/*
3056 		 * Get the keys for the left block's keys and put them directly
3057 		 * in the parent block.  Do the same for the right block.
3058 		 */
3059 		xfs_btree_get_node_keys(cur, left,
3060 				xfs_btree_key_addr(cur, 1, new));
3061 		xfs_btree_get_node_keys(cur, right,
3062 				xfs_btree_key_addr(cur, 2, new));
3063 	} else {
3064 		/*
3065 		 * Get the keys for the left block's records and put them
3066 		 * directly in the parent block.  Do the same for the right
3067 		 * block.
3068 		 */
3069 		xfs_btree_get_leaf_keys(cur, left,
3070 			xfs_btree_key_addr(cur, 1, new));
3071 		xfs_btree_get_leaf_keys(cur, right,
3072 			xfs_btree_key_addr(cur, 2, new));
3073 	}
3074 	xfs_btree_log_keys(cur, nbp, 1, 2);
3075 
3076 	/* Fill in the pointer data in the new root. */
3077 	xfs_btree_copy_ptrs(cur,
3078 		xfs_btree_ptr_addr(cur, 1, new), &lptr, 1);
3079 	xfs_btree_copy_ptrs(cur,
3080 		xfs_btree_ptr_addr(cur, 2, new), &rptr, 1);
3081 	xfs_btree_log_ptrs(cur, nbp, 1, 2);
3082 
3083 	/* Fix up the cursor. */
3084 	xfs_btree_setbuf(cur, cur->bc_nlevels, nbp);
3085 	cur->bc_ptrs[cur->bc_nlevels] = nptr;
3086 	cur->bc_nlevels++;
3087 	*stat = 1;
3088 	return 0;
3089 error0:
3090 	return error;
3091 out0:
3092 	*stat = 0;
3093 	return 0;
3094 }
3095 
3096 STATIC int
3097 xfs_btree_make_block_unfull(
3098 	struct xfs_btree_cur	*cur,	/* btree cursor */
3099 	int			level,	/* btree level */
3100 	int			numrecs,/* # of recs in block */
3101 	int			*oindex,/* old tree index */
3102 	int			*index,	/* new tree index */
3103 	union xfs_btree_ptr	*nptr,	/* new btree ptr */
3104 	struct xfs_btree_cur	**ncur,	/* new btree cursor */
3105 	union xfs_btree_key	*key,	/* key of new block */
3106 	int			*stat)
3107 {
3108 	int			error = 0;
3109 
3110 	if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
3111 	    level == cur->bc_nlevels - 1) {
3112 		struct xfs_inode *ip = cur->bc_ino.ip;
3113 
3114 		if (numrecs < cur->bc_ops->get_dmaxrecs(cur, level)) {
3115 			/* A root block that can be made bigger. */
3116 			xfs_iroot_realloc(ip, 1, cur->bc_ino.whichfork);
3117 			*stat = 1;
3118 		} else {
3119 			/* A root block that needs replacing */
3120 			int	logflags = 0;
3121 
3122 			error = xfs_btree_new_iroot(cur, &logflags, stat);
3123 			if (error || *stat == 0)
3124 				return error;
3125 
3126 			xfs_trans_log_inode(cur->bc_tp, ip, logflags);
3127 		}
3128 
3129 		return 0;
3130 	}
3131 
3132 	/* First, try shifting an entry to the right neighbor. */
3133 	error = xfs_btree_rshift(cur, level, stat);
3134 	if (error || *stat)
3135 		return error;
3136 
3137 	/* Next, try shifting an entry to the left neighbor. */
3138 	error = xfs_btree_lshift(cur, level, stat);
3139 	if (error)
3140 		return error;
3141 
3142 	if (*stat) {
3143 		*oindex = *index = cur->bc_ptrs[level];
3144 		return 0;
3145 	}
3146 
3147 	/*
3148 	 * Next, try splitting the current block in half.
3149 	 *
3150 	 * If this works we have to re-set our variables because we
3151 	 * could be in a different block now.
3152 	 */
3153 	error = xfs_btree_split(cur, level, nptr, key, ncur, stat);
3154 	if (error || *stat == 0)
3155 		return error;
3156 
3157 
3158 	*index = cur->bc_ptrs[level];
3159 	return 0;
3160 }
3161 
3162 /*
3163  * Insert one record/level.  Return information to the caller
3164  * allowing the next level up to proceed if necessary.
3165  */
3166 STATIC int
3167 xfs_btree_insrec(
3168 	struct xfs_btree_cur	*cur,	/* btree cursor */
3169 	int			level,	/* level to insert record at */
3170 	union xfs_btree_ptr	*ptrp,	/* i/o: block number inserted */
3171 	union xfs_btree_rec	*rec,	/* record to insert */
3172 	union xfs_btree_key	*key,	/* i/o: block key for ptrp */
3173 	struct xfs_btree_cur	**curp,	/* output: new cursor replacing cur */
3174 	int			*stat)	/* success/failure */
3175 {
3176 	struct xfs_btree_block	*block;	/* btree block */
3177 	struct xfs_buf		*bp;	/* buffer for block */
3178 	union xfs_btree_ptr	nptr;	/* new block ptr */
3179 	struct xfs_btree_cur	*ncur;	/* new btree cursor */
3180 	union xfs_btree_key	nkey;	/* new block key */
3181 	union xfs_btree_key	*lkey;
3182 	int			optr;	/* old key/record index */
3183 	int			ptr;	/* key/record index */
3184 	int			numrecs;/* number of records */
3185 	int			error;	/* error return value */
3186 	int			i;
3187 	xfs_daddr_t		old_bn;
3188 
3189 	ncur = NULL;
3190 	lkey = &nkey;
3191 
3192 	/*
3193 	 * If we have an external root pointer, and we've made it to the
3194 	 * root level, allocate a new root block and we're done.
3195 	 */
3196 	if (!(cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
3197 	    (level >= cur->bc_nlevels)) {
3198 		error = xfs_btree_new_root(cur, stat);
3199 		xfs_btree_set_ptr_null(cur, ptrp);
3200 
3201 		return error;
3202 	}
3203 
3204 	/* If we're off the left edge, return failure. */
3205 	ptr = cur->bc_ptrs[level];
3206 	if (ptr == 0) {
3207 		*stat = 0;
3208 		return 0;
3209 	}
3210 
3211 	optr = ptr;
3212 
3213 	XFS_BTREE_STATS_INC(cur, insrec);
3214 
3215 	/* Get pointers to the btree buffer and block. */
3216 	block = xfs_btree_get_block(cur, level, &bp);
3217 	old_bn = bp ? bp->b_bn : XFS_BUF_DADDR_NULL;
3218 	numrecs = xfs_btree_get_numrecs(block);
3219 
3220 #ifdef DEBUG
3221 	error = xfs_btree_check_block(cur, block, level, bp);
3222 	if (error)
3223 		goto error0;
3224 
3225 	/* Check that the new entry is being inserted in the right place. */
3226 	if (ptr <= numrecs) {
3227 		if (level == 0) {
3228 			ASSERT(cur->bc_ops->recs_inorder(cur, rec,
3229 				xfs_btree_rec_addr(cur, ptr, block)));
3230 		} else {
3231 			ASSERT(cur->bc_ops->keys_inorder(cur, key,
3232 				xfs_btree_key_addr(cur, ptr, block)));
3233 		}
3234 	}
3235 #endif
3236 
3237 	/*
3238 	 * If the block is full, we can't insert the new entry until we
3239 	 * make the block un-full.
3240 	 */
3241 	xfs_btree_set_ptr_null(cur, &nptr);
3242 	if (numrecs == cur->bc_ops->get_maxrecs(cur, level)) {
3243 		error = xfs_btree_make_block_unfull(cur, level, numrecs,
3244 					&optr, &ptr, &nptr, &ncur, lkey, stat);
3245 		if (error || *stat == 0)
3246 			goto error0;
3247 	}
3248 
3249 	/*
3250 	 * The current block may have changed if the block was
3251 	 * previously full and we have just made space in it.
3252 	 */
3253 	block = xfs_btree_get_block(cur, level, &bp);
3254 	numrecs = xfs_btree_get_numrecs(block);
3255 
3256 #ifdef DEBUG
3257 	error = xfs_btree_check_block(cur, block, level, bp);
3258 	if (error)
3259 		return error;
3260 #endif
3261 
3262 	/*
3263 	 * At this point we know there's room for our new entry in the block
3264 	 * we're pointing at.
3265 	 */
3266 	XFS_BTREE_STATS_ADD(cur, moves, numrecs - ptr + 1);
3267 
3268 	if (level > 0) {
3269 		/* It's a nonleaf. make a hole in the keys and ptrs */
3270 		union xfs_btree_key	*kp;
3271 		union xfs_btree_ptr	*pp;
3272 
3273 		kp = xfs_btree_key_addr(cur, ptr, block);
3274 		pp = xfs_btree_ptr_addr(cur, ptr, block);
3275 
3276 		for (i = numrecs - ptr; i >= 0; i--) {
3277 			error = xfs_btree_debug_check_ptr(cur, pp, i, level);
3278 			if (error)
3279 				return error;
3280 		}
3281 
3282 		xfs_btree_shift_keys(cur, kp, 1, numrecs - ptr + 1);
3283 		xfs_btree_shift_ptrs(cur, pp, 1, numrecs - ptr + 1);
3284 
3285 		error = xfs_btree_debug_check_ptr(cur, ptrp, 0, level);
3286 		if (error)
3287 			goto error0;
3288 
3289 		/* Now put the new data in, bump numrecs and log it. */
3290 		xfs_btree_copy_keys(cur, kp, key, 1);
3291 		xfs_btree_copy_ptrs(cur, pp, ptrp, 1);
3292 		numrecs++;
3293 		xfs_btree_set_numrecs(block, numrecs);
3294 		xfs_btree_log_ptrs(cur, bp, ptr, numrecs);
3295 		xfs_btree_log_keys(cur, bp, ptr, numrecs);
3296 #ifdef DEBUG
3297 		if (ptr < numrecs) {
3298 			ASSERT(cur->bc_ops->keys_inorder(cur, kp,
3299 				xfs_btree_key_addr(cur, ptr + 1, block)));
3300 		}
3301 #endif
3302 	} else {
3303 		/* It's a leaf. make a hole in the records */
3304 		union xfs_btree_rec             *rp;
3305 
3306 		rp = xfs_btree_rec_addr(cur, ptr, block);
3307 
3308 		xfs_btree_shift_recs(cur, rp, 1, numrecs - ptr + 1);
3309 
3310 		/* Now put the new data in, bump numrecs and log it. */
3311 		xfs_btree_copy_recs(cur, rp, rec, 1);
3312 		xfs_btree_set_numrecs(block, ++numrecs);
3313 		xfs_btree_log_recs(cur, bp, ptr, numrecs);
3314 #ifdef DEBUG
3315 		if (ptr < numrecs) {
3316 			ASSERT(cur->bc_ops->recs_inorder(cur, rp,
3317 				xfs_btree_rec_addr(cur, ptr + 1, block)));
3318 		}
3319 #endif
3320 	}
3321 
3322 	/* Log the new number of records in the btree header. */
3323 	xfs_btree_log_block(cur, bp, XFS_BB_NUMRECS);
3324 
3325 	/*
3326 	 * If we just inserted into a new tree block, we have to
3327 	 * recalculate nkey here because nkey is out of date.
3328 	 *
3329 	 * Otherwise we're just updating an existing block (having shoved
3330 	 * some records into the new tree block), so use the regular key
3331 	 * update mechanism.
3332 	 */
3333 	if (bp && bp->b_bn != old_bn) {
3334 		xfs_btree_get_keys(cur, block, lkey);
3335 	} else if (xfs_btree_needs_key_update(cur, optr)) {
3336 		error = xfs_btree_update_keys(cur, level);
3337 		if (error)
3338 			goto error0;
3339 	}
3340 
3341 	/*
3342 	 * If we are tracking the last record in the tree and
3343 	 * we are at the far right edge of the tree, update it.
3344 	 */
3345 	if (xfs_btree_is_lastrec(cur, block, level)) {
3346 		cur->bc_ops->update_lastrec(cur, block, rec,
3347 					    ptr, LASTREC_INSREC);
3348 	}
3349 
3350 	/*
3351 	 * Return the new block number, if any.
3352 	 * If there is one, give back a record value and a cursor too.
3353 	 */
3354 	*ptrp = nptr;
3355 	if (!xfs_btree_ptr_is_null(cur, &nptr)) {
3356 		xfs_btree_copy_keys(cur, key, lkey, 1);
3357 		*curp = ncur;
3358 	}
3359 
3360 	*stat = 1;
3361 	return 0;
3362 
3363 error0:
3364 	return error;
3365 }
3366 
3367 /*
3368  * Insert the record at the point referenced by cur.
3369  *
3370  * A multi-level split of the tree on insert will invalidate the original
3371  * cursor.  All callers of this function should assume that the cursor is
3372  * no longer valid and revalidate it.
3373  */
3374 int
3375 xfs_btree_insert(
3376 	struct xfs_btree_cur	*cur,
3377 	int			*stat)
3378 {
3379 	int			error;	/* error return value */
3380 	int			i;	/* result value, 0 for failure */
3381 	int			level;	/* current level number in btree */
3382 	union xfs_btree_ptr	nptr;	/* new block number (split result) */
3383 	struct xfs_btree_cur	*ncur;	/* new cursor (split result) */
3384 	struct xfs_btree_cur	*pcur;	/* previous level's cursor */
3385 	union xfs_btree_key	bkey;	/* key of block to insert */
3386 	union xfs_btree_key	*key;
3387 	union xfs_btree_rec	rec;	/* record to insert */
3388 
3389 	level = 0;
3390 	ncur = NULL;
3391 	pcur = cur;
3392 	key = &bkey;
3393 
3394 	xfs_btree_set_ptr_null(cur, &nptr);
3395 
3396 	/* Make a key out of the record data to be inserted, and save it. */
3397 	cur->bc_ops->init_rec_from_cur(cur, &rec);
3398 	cur->bc_ops->init_key_from_rec(key, &rec);
3399 
3400 	/*
3401 	 * Loop going up the tree, starting at the leaf level.
3402 	 * Stop when we don't get a split block, that must mean that
3403 	 * the insert is finished with this level.
3404 	 */
3405 	do {
3406 		/*
3407 		 * Insert nrec/nptr into this level of the tree.
3408 		 * Note if we fail, nptr will be null.
3409 		 */
3410 		error = xfs_btree_insrec(pcur, level, &nptr, &rec, key,
3411 				&ncur, &i);
3412 		if (error) {
3413 			if (pcur != cur)
3414 				xfs_btree_del_cursor(pcur, XFS_BTREE_ERROR);
3415 			goto error0;
3416 		}
3417 
3418 		if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
3419 			error = -EFSCORRUPTED;
3420 			goto error0;
3421 		}
3422 		level++;
3423 
3424 		/*
3425 		 * See if the cursor we just used is trash.
3426 		 * Can't trash the caller's cursor, but otherwise we should
3427 		 * if ncur is a new cursor or we're about to be done.
3428 		 */
3429 		if (pcur != cur &&
3430 		    (ncur || xfs_btree_ptr_is_null(cur, &nptr))) {
3431 			/* Save the state from the cursor before we trash it */
3432 			if (cur->bc_ops->update_cursor)
3433 				cur->bc_ops->update_cursor(pcur, cur);
3434 			cur->bc_nlevels = pcur->bc_nlevels;
3435 			xfs_btree_del_cursor(pcur, XFS_BTREE_NOERROR);
3436 		}
3437 		/* If we got a new cursor, switch to it. */
3438 		if (ncur) {
3439 			pcur = ncur;
3440 			ncur = NULL;
3441 		}
3442 	} while (!xfs_btree_ptr_is_null(cur, &nptr));
3443 
3444 	*stat = i;
3445 	return 0;
3446 error0:
3447 	return error;
3448 }
3449 
3450 /*
3451  * Try to merge a non-leaf block back into the inode root.
3452  *
3453  * Note: the killroot names comes from the fact that we're effectively
3454  * killing the old root block.  But because we can't just delete the
3455  * inode we have to copy the single block it was pointing to into the
3456  * inode.
3457  */
3458 STATIC int
3459 xfs_btree_kill_iroot(
3460 	struct xfs_btree_cur	*cur)
3461 {
3462 	int			whichfork = cur->bc_ino.whichfork;
3463 	struct xfs_inode	*ip = cur->bc_ino.ip;
3464 	struct xfs_ifork	*ifp = XFS_IFORK_PTR(ip, whichfork);
3465 	struct xfs_btree_block	*block;
3466 	struct xfs_btree_block	*cblock;
3467 	union xfs_btree_key	*kp;
3468 	union xfs_btree_key	*ckp;
3469 	union xfs_btree_ptr	*pp;
3470 	union xfs_btree_ptr	*cpp;
3471 	struct xfs_buf		*cbp;
3472 	int			level;
3473 	int			index;
3474 	int			numrecs;
3475 	int			error;
3476 #ifdef DEBUG
3477 	union xfs_btree_ptr	ptr;
3478 #endif
3479 	int			i;
3480 
3481 	ASSERT(cur->bc_flags & XFS_BTREE_ROOT_IN_INODE);
3482 	ASSERT(cur->bc_nlevels > 1);
3483 
3484 	/*
3485 	 * Don't deal with the root block needs to be a leaf case.
3486 	 * We're just going to turn the thing back into extents anyway.
3487 	 */
3488 	level = cur->bc_nlevels - 1;
3489 	if (level == 1)
3490 		goto out0;
3491 
3492 	/*
3493 	 * Give up if the root has multiple children.
3494 	 */
3495 	block = xfs_btree_get_iroot(cur);
3496 	if (xfs_btree_get_numrecs(block) != 1)
3497 		goto out0;
3498 
3499 	cblock = xfs_btree_get_block(cur, level - 1, &cbp);
3500 	numrecs = xfs_btree_get_numrecs(cblock);
3501 
3502 	/*
3503 	 * Only do this if the next level will fit.
3504 	 * Then the data must be copied up to the inode,
3505 	 * instead of freeing the root you free the next level.
3506 	 */
3507 	if (numrecs > cur->bc_ops->get_dmaxrecs(cur, level))
3508 		goto out0;
3509 
3510 	XFS_BTREE_STATS_INC(cur, killroot);
3511 
3512 #ifdef DEBUG
3513 	xfs_btree_get_sibling(cur, block, &ptr, XFS_BB_LEFTSIB);
3514 	ASSERT(xfs_btree_ptr_is_null(cur, &ptr));
3515 	xfs_btree_get_sibling(cur, block, &ptr, XFS_BB_RIGHTSIB);
3516 	ASSERT(xfs_btree_ptr_is_null(cur, &ptr));
3517 #endif
3518 
3519 	index = numrecs - cur->bc_ops->get_maxrecs(cur, level);
3520 	if (index) {
3521 		xfs_iroot_realloc(cur->bc_ino.ip, index,
3522 				  cur->bc_ino.whichfork);
3523 		block = ifp->if_broot;
3524 	}
3525 
3526 	be16_add_cpu(&block->bb_numrecs, index);
3527 	ASSERT(block->bb_numrecs == cblock->bb_numrecs);
3528 
3529 	kp = xfs_btree_key_addr(cur, 1, block);
3530 	ckp = xfs_btree_key_addr(cur, 1, cblock);
3531 	xfs_btree_copy_keys(cur, kp, ckp, numrecs);
3532 
3533 	pp = xfs_btree_ptr_addr(cur, 1, block);
3534 	cpp = xfs_btree_ptr_addr(cur, 1, cblock);
3535 
3536 	for (i = 0; i < numrecs; i++) {
3537 		error = xfs_btree_debug_check_ptr(cur, cpp, i, level - 1);
3538 		if (error)
3539 			return error;
3540 	}
3541 
3542 	xfs_btree_copy_ptrs(cur, pp, cpp, numrecs);
3543 
3544 	error = xfs_btree_free_block(cur, cbp);
3545 	if (error)
3546 		return error;
3547 
3548 	cur->bc_bufs[level - 1] = NULL;
3549 	be16_add_cpu(&block->bb_level, -1);
3550 	xfs_trans_log_inode(cur->bc_tp, ip,
3551 		XFS_ILOG_CORE | xfs_ilog_fbroot(cur->bc_ino.whichfork));
3552 	cur->bc_nlevels--;
3553 out0:
3554 	return 0;
3555 }
3556 
3557 /*
3558  * Kill the current root node, and replace it with it's only child node.
3559  */
3560 STATIC int
3561 xfs_btree_kill_root(
3562 	struct xfs_btree_cur	*cur,
3563 	struct xfs_buf		*bp,
3564 	int			level,
3565 	union xfs_btree_ptr	*newroot)
3566 {
3567 	int			error;
3568 
3569 	XFS_BTREE_STATS_INC(cur, killroot);
3570 
3571 	/*
3572 	 * Update the root pointer, decreasing the level by 1 and then
3573 	 * free the old root.
3574 	 */
3575 	cur->bc_ops->set_root(cur, newroot, -1);
3576 
3577 	error = xfs_btree_free_block(cur, bp);
3578 	if (error)
3579 		return error;
3580 
3581 	cur->bc_bufs[level] = NULL;
3582 	cur->bc_ra[level] = 0;
3583 	cur->bc_nlevels--;
3584 
3585 	return 0;
3586 }
3587 
3588 STATIC int
3589 xfs_btree_dec_cursor(
3590 	struct xfs_btree_cur	*cur,
3591 	int			level,
3592 	int			*stat)
3593 {
3594 	int			error;
3595 	int			i;
3596 
3597 	if (level > 0) {
3598 		error = xfs_btree_decrement(cur, level, &i);
3599 		if (error)
3600 			return error;
3601 	}
3602 
3603 	*stat = 1;
3604 	return 0;
3605 }
3606 
3607 /*
3608  * Single level of the btree record deletion routine.
3609  * Delete record pointed to by cur/level.
3610  * Remove the record from its block then rebalance the tree.
3611  * Return 0 for error, 1 for done, 2 to go on to the next level.
3612  */
3613 STATIC int					/* error */
3614 xfs_btree_delrec(
3615 	struct xfs_btree_cur	*cur,		/* btree cursor */
3616 	int			level,		/* level removing record from */
3617 	int			*stat)		/* fail/done/go-on */
3618 {
3619 	struct xfs_btree_block	*block;		/* btree block */
3620 	union xfs_btree_ptr	cptr;		/* current block ptr */
3621 	struct xfs_buf		*bp;		/* buffer for block */
3622 	int			error;		/* error return value */
3623 	int			i;		/* loop counter */
3624 	union xfs_btree_ptr	lptr;		/* left sibling block ptr */
3625 	struct xfs_buf		*lbp;		/* left buffer pointer */
3626 	struct xfs_btree_block	*left;		/* left btree block */
3627 	int			lrecs = 0;	/* left record count */
3628 	int			ptr;		/* key/record index */
3629 	union xfs_btree_ptr	rptr;		/* right sibling block ptr */
3630 	struct xfs_buf		*rbp;		/* right buffer pointer */
3631 	struct xfs_btree_block	*right;		/* right btree block */
3632 	struct xfs_btree_block	*rrblock;	/* right-right btree block */
3633 	struct xfs_buf		*rrbp;		/* right-right buffer pointer */
3634 	int			rrecs = 0;	/* right record count */
3635 	struct xfs_btree_cur	*tcur;		/* temporary btree cursor */
3636 	int			numrecs;	/* temporary numrec count */
3637 
3638 	tcur = NULL;
3639 
3640 	/* Get the index of the entry being deleted, check for nothing there. */
3641 	ptr = cur->bc_ptrs[level];
3642 	if (ptr == 0) {
3643 		*stat = 0;
3644 		return 0;
3645 	}
3646 
3647 	/* Get the buffer & block containing the record or key/ptr. */
3648 	block = xfs_btree_get_block(cur, level, &bp);
3649 	numrecs = xfs_btree_get_numrecs(block);
3650 
3651 #ifdef DEBUG
3652 	error = xfs_btree_check_block(cur, block, level, bp);
3653 	if (error)
3654 		goto error0;
3655 #endif
3656 
3657 	/* Fail if we're off the end of the block. */
3658 	if (ptr > numrecs) {
3659 		*stat = 0;
3660 		return 0;
3661 	}
3662 
3663 	XFS_BTREE_STATS_INC(cur, delrec);
3664 	XFS_BTREE_STATS_ADD(cur, moves, numrecs - ptr);
3665 
3666 	/* Excise the entries being deleted. */
3667 	if (level > 0) {
3668 		/* It's a nonleaf. operate on keys and ptrs */
3669 		union xfs_btree_key	*lkp;
3670 		union xfs_btree_ptr	*lpp;
3671 
3672 		lkp = xfs_btree_key_addr(cur, ptr + 1, block);
3673 		lpp = xfs_btree_ptr_addr(cur, ptr + 1, block);
3674 
3675 		for (i = 0; i < numrecs - ptr; i++) {
3676 			error = xfs_btree_debug_check_ptr(cur, lpp, i, level);
3677 			if (error)
3678 				goto error0;
3679 		}
3680 
3681 		if (ptr < numrecs) {
3682 			xfs_btree_shift_keys(cur, lkp, -1, numrecs - ptr);
3683 			xfs_btree_shift_ptrs(cur, lpp, -1, numrecs - ptr);
3684 			xfs_btree_log_keys(cur, bp, ptr, numrecs - 1);
3685 			xfs_btree_log_ptrs(cur, bp, ptr, numrecs - 1);
3686 		}
3687 	} else {
3688 		/* It's a leaf. operate on records */
3689 		if (ptr < numrecs) {
3690 			xfs_btree_shift_recs(cur,
3691 				xfs_btree_rec_addr(cur, ptr + 1, block),
3692 				-1, numrecs - ptr);
3693 			xfs_btree_log_recs(cur, bp, ptr, numrecs - 1);
3694 		}
3695 	}
3696 
3697 	/*
3698 	 * Decrement and log the number of entries in the block.
3699 	 */
3700 	xfs_btree_set_numrecs(block, --numrecs);
3701 	xfs_btree_log_block(cur, bp, XFS_BB_NUMRECS);
3702 
3703 	/*
3704 	 * If we are tracking the last record in the tree and
3705 	 * we are at the far right edge of the tree, update it.
3706 	 */
3707 	if (xfs_btree_is_lastrec(cur, block, level)) {
3708 		cur->bc_ops->update_lastrec(cur, block, NULL,
3709 					    ptr, LASTREC_DELREC);
3710 	}
3711 
3712 	/*
3713 	 * We're at the root level.  First, shrink the root block in-memory.
3714 	 * Try to get rid of the next level down.  If we can't then there's
3715 	 * nothing left to do.
3716 	 */
3717 	if (level == cur->bc_nlevels - 1) {
3718 		if (cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) {
3719 			xfs_iroot_realloc(cur->bc_ino.ip, -1,
3720 					  cur->bc_ino.whichfork);
3721 
3722 			error = xfs_btree_kill_iroot(cur);
3723 			if (error)
3724 				goto error0;
3725 
3726 			error = xfs_btree_dec_cursor(cur, level, stat);
3727 			if (error)
3728 				goto error0;
3729 			*stat = 1;
3730 			return 0;
3731 		}
3732 
3733 		/*
3734 		 * If this is the root level, and there's only one entry left,
3735 		 * and it's NOT the leaf level, then we can get rid of this
3736 		 * level.
3737 		 */
3738 		if (numrecs == 1 && level > 0) {
3739 			union xfs_btree_ptr	*pp;
3740 			/*
3741 			 * pp is still set to the first pointer in the block.
3742 			 * Make it the new root of the btree.
3743 			 */
3744 			pp = xfs_btree_ptr_addr(cur, 1, block);
3745 			error = xfs_btree_kill_root(cur, bp, level, pp);
3746 			if (error)
3747 				goto error0;
3748 		} else if (level > 0) {
3749 			error = xfs_btree_dec_cursor(cur, level, stat);
3750 			if (error)
3751 				goto error0;
3752 		}
3753 		*stat = 1;
3754 		return 0;
3755 	}
3756 
3757 	/*
3758 	 * If we deleted the leftmost entry in the block, update the
3759 	 * key values above us in the tree.
3760 	 */
3761 	if (xfs_btree_needs_key_update(cur, ptr)) {
3762 		error = xfs_btree_update_keys(cur, level);
3763 		if (error)
3764 			goto error0;
3765 	}
3766 
3767 	/*
3768 	 * If the number of records remaining in the block is at least
3769 	 * the minimum, we're done.
3770 	 */
3771 	if (numrecs >= cur->bc_ops->get_minrecs(cur, level)) {
3772 		error = xfs_btree_dec_cursor(cur, level, stat);
3773 		if (error)
3774 			goto error0;
3775 		return 0;
3776 	}
3777 
3778 	/*
3779 	 * Otherwise, we have to move some records around to keep the
3780 	 * tree balanced.  Look at the left and right sibling blocks to
3781 	 * see if we can re-balance by moving only one record.
3782 	 */
3783 	xfs_btree_get_sibling(cur, block, &rptr, XFS_BB_RIGHTSIB);
3784 	xfs_btree_get_sibling(cur, block, &lptr, XFS_BB_LEFTSIB);
3785 
3786 	if (cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) {
3787 		/*
3788 		 * One child of root, need to get a chance to copy its contents
3789 		 * into the root and delete it. Can't go up to next level,
3790 		 * there's nothing to delete there.
3791 		 */
3792 		if (xfs_btree_ptr_is_null(cur, &rptr) &&
3793 		    xfs_btree_ptr_is_null(cur, &lptr) &&
3794 		    level == cur->bc_nlevels - 2) {
3795 			error = xfs_btree_kill_iroot(cur);
3796 			if (!error)
3797 				error = xfs_btree_dec_cursor(cur, level, stat);
3798 			if (error)
3799 				goto error0;
3800 			return 0;
3801 		}
3802 	}
3803 
3804 	ASSERT(!xfs_btree_ptr_is_null(cur, &rptr) ||
3805 	       !xfs_btree_ptr_is_null(cur, &lptr));
3806 
3807 	/*
3808 	 * Duplicate the cursor so our btree manipulations here won't
3809 	 * disrupt the next level up.
3810 	 */
3811 	error = xfs_btree_dup_cursor(cur, &tcur);
3812 	if (error)
3813 		goto error0;
3814 
3815 	/*
3816 	 * If there's a right sibling, see if it's ok to shift an entry
3817 	 * out of it.
3818 	 */
3819 	if (!xfs_btree_ptr_is_null(cur, &rptr)) {
3820 		/*
3821 		 * Move the temp cursor to the last entry in the next block.
3822 		 * Actually any entry but the first would suffice.
3823 		 */
3824 		i = xfs_btree_lastrec(tcur, level);
3825 		if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
3826 			error = -EFSCORRUPTED;
3827 			goto error0;
3828 		}
3829 
3830 		error = xfs_btree_increment(tcur, level, &i);
3831 		if (error)
3832 			goto error0;
3833 		if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
3834 			error = -EFSCORRUPTED;
3835 			goto error0;
3836 		}
3837 
3838 		i = xfs_btree_lastrec(tcur, level);
3839 		if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
3840 			error = -EFSCORRUPTED;
3841 			goto error0;
3842 		}
3843 
3844 		/* Grab a pointer to the block. */
3845 		right = xfs_btree_get_block(tcur, level, &rbp);
3846 #ifdef DEBUG
3847 		error = xfs_btree_check_block(tcur, right, level, rbp);
3848 		if (error)
3849 			goto error0;
3850 #endif
3851 		/* Grab the current block number, for future use. */
3852 		xfs_btree_get_sibling(tcur, right, &cptr, XFS_BB_LEFTSIB);
3853 
3854 		/*
3855 		 * If right block is full enough so that removing one entry
3856 		 * won't make it too empty, and left-shifting an entry out
3857 		 * of right to us works, we're done.
3858 		 */
3859 		if (xfs_btree_get_numrecs(right) - 1 >=
3860 		    cur->bc_ops->get_minrecs(tcur, level)) {
3861 			error = xfs_btree_lshift(tcur, level, &i);
3862 			if (error)
3863 				goto error0;
3864 			if (i) {
3865 				ASSERT(xfs_btree_get_numrecs(block) >=
3866 				       cur->bc_ops->get_minrecs(tcur, level));
3867 
3868 				xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
3869 				tcur = NULL;
3870 
3871 				error = xfs_btree_dec_cursor(cur, level, stat);
3872 				if (error)
3873 					goto error0;
3874 				return 0;
3875 			}
3876 		}
3877 
3878 		/*
3879 		 * Otherwise, grab the number of records in right for
3880 		 * future reference, and fix up the temp cursor to point
3881 		 * to our block again (last record).
3882 		 */
3883 		rrecs = xfs_btree_get_numrecs(right);
3884 		if (!xfs_btree_ptr_is_null(cur, &lptr)) {
3885 			i = xfs_btree_firstrec(tcur, level);
3886 			if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
3887 				error = -EFSCORRUPTED;
3888 				goto error0;
3889 			}
3890 
3891 			error = xfs_btree_decrement(tcur, level, &i);
3892 			if (error)
3893 				goto error0;
3894 			if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
3895 				error = -EFSCORRUPTED;
3896 				goto error0;
3897 			}
3898 		}
3899 	}
3900 
3901 	/*
3902 	 * If there's a left sibling, see if it's ok to shift an entry
3903 	 * out of it.
3904 	 */
3905 	if (!xfs_btree_ptr_is_null(cur, &lptr)) {
3906 		/*
3907 		 * Move the temp cursor to the first entry in the
3908 		 * previous block.
3909 		 */
3910 		i = xfs_btree_firstrec(tcur, level);
3911 		if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
3912 			error = -EFSCORRUPTED;
3913 			goto error0;
3914 		}
3915 
3916 		error = xfs_btree_decrement(tcur, level, &i);
3917 		if (error)
3918 			goto error0;
3919 		i = xfs_btree_firstrec(tcur, level);
3920 		if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
3921 			error = -EFSCORRUPTED;
3922 			goto error0;
3923 		}
3924 
3925 		/* Grab a pointer to the block. */
3926 		left = xfs_btree_get_block(tcur, level, &lbp);
3927 #ifdef DEBUG
3928 		error = xfs_btree_check_block(cur, left, level, lbp);
3929 		if (error)
3930 			goto error0;
3931 #endif
3932 		/* Grab the current block number, for future use. */
3933 		xfs_btree_get_sibling(tcur, left, &cptr, XFS_BB_RIGHTSIB);
3934 
3935 		/*
3936 		 * If left block is full enough so that removing one entry
3937 		 * won't make it too empty, and right-shifting an entry out
3938 		 * of left to us works, we're done.
3939 		 */
3940 		if (xfs_btree_get_numrecs(left) - 1 >=
3941 		    cur->bc_ops->get_minrecs(tcur, level)) {
3942 			error = xfs_btree_rshift(tcur, level, &i);
3943 			if (error)
3944 				goto error0;
3945 			if (i) {
3946 				ASSERT(xfs_btree_get_numrecs(block) >=
3947 				       cur->bc_ops->get_minrecs(tcur, level));
3948 				xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
3949 				tcur = NULL;
3950 				if (level == 0)
3951 					cur->bc_ptrs[0]++;
3952 
3953 				*stat = 1;
3954 				return 0;
3955 			}
3956 		}
3957 
3958 		/*
3959 		 * Otherwise, grab the number of records in right for
3960 		 * future reference.
3961 		 */
3962 		lrecs = xfs_btree_get_numrecs(left);
3963 	}
3964 
3965 	/* Delete the temp cursor, we're done with it. */
3966 	xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
3967 	tcur = NULL;
3968 
3969 	/* If here, we need to do a join to keep the tree balanced. */
3970 	ASSERT(!xfs_btree_ptr_is_null(cur, &cptr));
3971 
3972 	if (!xfs_btree_ptr_is_null(cur, &lptr) &&
3973 	    lrecs + xfs_btree_get_numrecs(block) <=
3974 			cur->bc_ops->get_maxrecs(cur, level)) {
3975 		/*
3976 		 * Set "right" to be the starting block,
3977 		 * "left" to be the left neighbor.
3978 		 */
3979 		rptr = cptr;
3980 		right = block;
3981 		rbp = bp;
3982 		error = xfs_btree_read_buf_block(cur, &lptr, 0, &left, &lbp);
3983 		if (error)
3984 			goto error0;
3985 
3986 	/*
3987 	 * If that won't work, see if we can join with the right neighbor block.
3988 	 */
3989 	} else if (!xfs_btree_ptr_is_null(cur, &rptr) &&
3990 		   rrecs + xfs_btree_get_numrecs(block) <=
3991 			cur->bc_ops->get_maxrecs(cur, level)) {
3992 		/*
3993 		 * Set "left" to be the starting block,
3994 		 * "right" to be the right neighbor.
3995 		 */
3996 		lptr = cptr;
3997 		left = block;
3998 		lbp = bp;
3999 		error = xfs_btree_read_buf_block(cur, &rptr, 0, &right, &rbp);
4000 		if (error)
4001 			goto error0;
4002 
4003 	/*
4004 	 * Otherwise, we can't fix the imbalance.
4005 	 * Just return.  This is probably a logic error, but it's not fatal.
4006 	 */
4007 	} else {
4008 		error = xfs_btree_dec_cursor(cur, level, stat);
4009 		if (error)
4010 			goto error0;
4011 		return 0;
4012 	}
4013 
4014 	rrecs = xfs_btree_get_numrecs(right);
4015 	lrecs = xfs_btree_get_numrecs(left);
4016 
4017 	/*
4018 	 * We're now going to join "left" and "right" by moving all the stuff
4019 	 * in "right" to "left" and deleting "right".
4020 	 */
4021 	XFS_BTREE_STATS_ADD(cur, moves, rrecs);
4022 	if (level > 0) {
4023 		/* It's a non-leaf.  Move keys and pointers. */
4024 		union xfs_btree_key	*lkp;	/* left btree key */
4025 		union xfs_btree_ptr	*lpp;	/* left address pointer */
4026 		union xfs_btree_key	*rkp;	/* right btree key */
4027 		union xfs_btree_ptr	*rpp;	/* right address pointer */
4028 
4029 		lkp = xfs_btree_key_addr(cur, lrecs + 1, left);
4030 		lpp = xfs_btree_ptr_addr(cur, lrecs + 1, left);
4031 		rkp = xfs_btree_key_addr(cur, 1, right);
4032 		rpp = xfs_btree_ptr_addr(cur, 1, right);
4033 
4034 		for (i = 1; i < rrecs; i++) {
4035 			error = xfs_btree_debug_check_ptr(cur, rpp, i, level);
4036 			if (error)
4037 				goto error0;
4038 		}
4039 
4040 		xfs_btree_copy_keys(cur, lkp, rkp, rrecs);
4041 		xfs_btree_copy_ptrs(cur, lpp, rpp, rrecs);
4042 
4043 		xfs_btree_log_keys(cur, lbp, lrecs + 1, lrecs + rrecs);
4044 		xfs_btree_log_ptrs(cur, lbp, lrecs + 1, lrecs + rrecs);
4045 	} else {
4046 		/* It's a leaf.  Move records.  */
4047 		union xfs_btree_rec	*lrp;	/* left record pointer */
4048 		union xfs_btree_rec	*rrp;	/* right record pointer */
4049 
4050 		lrp = xfs_btree_rec_addr(cur, lrecs + 1, left);
4051 		rrp = xfs_btree_rec_addr(cur, 1, right);
4052 
4053 		xfs_btree_copy_recs(cur, lrp, rrp, rrecs);
4054 		xfs_btree_log_recs(cur, lbp, lrecs + 1, lrecs + rrecs);
4055 	}
4056 
4057 	XFS_BTREE_STATS_INC(cur, join);
4058 
4059 	/*
4060 	 * Fix up the number of records and right block pointer in the
4061 	 * surviving block, and log it.
4062 	 */
4063 	xfs_btree_set_numrecs(left, lrecs + rrecs);
4064 	xfs_btree_get_sibling(cur, right, &cptr, XFS_BB_RIGHTSIB);
4065 	xfs_btree_set_sibling(cur, left, &cptr, XFS_BB_RIGHTSIB);
4066 	xfs_btree_log_block(cur, lbp, XFS_BB_NUMRECS | XFS_BB_RIGHTSIB);
4067 
4068 	/* If there is a right sibling, point it to the remaining block. */
4069 	xfs_btree_get_sibling(cur, left, &cptr, XFS_BB_RIGHTSIB);
4070 	if (!xfs_btree_ptr_is_null(cur, &cptr)) {
4071 		error = xfs_btree_read_buf_block(cur, &cptr, 0, &rrblock, &rrbp);
4072 		if (error)
4073 			goto error0;
4074 		xfs_btree_set_sibling(cur, rrblock, &lptr, XFS_BB_LEFTSIB);
4075 		xfs_btree_log_block(cur, rrbp, XFS_BB_LEFTSIB);
4076 	}
4077 
4078 	/* Free the deleted block. */
4079 	error = xfs_btree_free_block(cur, rbp);
4080 	if (error)
4081 		goto error0;
4082 
4083 	/*
4084 	 * If we joined with the left neighbor, set the buffer in the
4085 	 * cursor to the left block, and fix up the index.
4086 	 */
4087 	if (bp != lbp) {
4088 		cur->bc_bufs[level] = lbp;
4089 		cur->bc_ptrs[level] += lrecs;
4090 		cur->bc_ra[level] = 0;
4091 	}
4092 	/*
4093 	 * If we joined with the right neighbor and there's a level above
4094 	 * us, increment the cursor at that level.
4095 	 */
4096 	else if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) ||
4097 		   (level + 1 < cur->bc_nlevels)) {
4098 		error = xfs_btree_increment(cur, level + 1, &i);
4099 		if (error)
4100 			goto error0;
4101 	}
4102 
4103 	/*
4104 	 * Readjust the ptr at this level if it's not a leaf, since it's
4105 	 * still pointing at the deletion point, which makes the cursor
4106 	 * inconsistent.  If this makes the ptr 0, the caller fixes it up.
4107 	 * We can't use decrement because it would change the next level up.
4108 	 */
4109 	if (level > 0)
4110 		cur->bc_ptrs[level]--;
4111 
4112 	/*
4113 	 * We combined blocks, so we have to update the parent keys if the
4114 	 * btree supports overlapped intervals.  However, bc_ptrs[level + 1]
4115 	 * points to the old block so that the caller knows which record to
4116 	 * delete.  Therefore, the caller must be savvy enough to call updkeys
4117 	 * for us if we return stat == 2.  The other exit points from this
4118 	 * function don't require deletions further up the tree, so they can
4119 	 * call updkeys directly.
4120 	 */
4121 
4122 	/* Return value means the next level up has something to do. */
4123 	*stat = 2;
4124 	return 0;
4125 
4126 error0:
4127 	if (tcur)
4128 		xfs_btree_del_cursor(tcur, XFS_BTREE_ERROR);
4129 	return error;
4130 }
4131 
4132 /*
4133  * Delete the record pointed to by cur.
4134  * The cursor refers to the place where the record was (could be inserted)
4135  * when the operation returns.
4136  */
4137 int					/* error */
4138 xfs_btree_delete(
4139 	struct xfs_btree_cur	*cur,
4140 	int			*stat)	/* success/failure */
4141 {
4142 	int			error;	/* error return value */
4143 	int			level;
4144 	int			i;
4145 	bool			joined = false;
4146 
4147 	/*
4148 	 * Go up the tree, starting at leaf level.
4149 	 *
4150 	 * If 2 is returned then a join was done; go to the next level.
4151 	 * Otherwise we are done.
4152 	 */
4153 	for (level = 0, i = 2; i == 2; level++) {
4154 		error = xfs_btree_delrec(cur, level, &i);
4155 		if (error)
4156 			goto error0;
4157 		if (i == 2)
4158 			joined = true;
4159 	}
4160 
4161 	/*
4162 	 * If we combined blocks as part of deleting the record, delrec won't
4163 	 * have updated the parent high keys so we have to do that here.
4164 	 */
4165 	if (joined && (cur->bc_flags & XFS_BTREE_OVERLAPPING)) {
4166 		error = xfs_btree_updkeys_force(cur, 0);
4167 		if (error)
4168 			goto error0;
4169 	}
4170 
4171 	if (i == 0) {
4172 		for (level = 1; level < cur->bc_nlevels; level++) {
4173 			if (cur->bc_ptrs[level] == 0) {
4174 				error = xfs_btree_decrement(cur, level, &i);
4175 				if (error)
4176 					goto error0;
4177 				break;
4178 			}
4179 		}
4180 	}
4181 
4182 	*stat = i;
4183 	return 0;
4184 error0:
4185 	return error;
4186 }
4187 
4188 /*
4189  * Get the data from the pointed-to record.
4190  */
4191 int					/* error */
4192 xfs_btree_get_rec(
4193 	struct xfs_btree_cur	*cur,	/* btree cursor */
4194 	union xfs_btree_rec	**recp,	/* output: btree record */
4195 	int			*stat)	/* output: success/failure */
4196 {
4197 	struct xfs_btree_block	*block;	/* btree block */
4198 	struct xfs_buf		*bp;	/* buffer pointer */
4199 	int			ptr;	/* record number */
4200 #ifdef DEBUG
4201 	int			error;	/* error return value */
4202 #endif
4203 
4204 	ptr = cur->bc_ptrs[0];
4205 	block = xfs_btree_get_block(cur, 0, &bp);
4206 
4207 #ifdef DEBUG
4208 	error = xfs_btree_check_block(cur, block, 0, bp);
4209 	if (error)
4210 		return error;
4211 #endif
4212 
4213 	/*
4214 	 * Off the right end or left end, return failure.
4215 	 */
4216 	if (ptr > xfs_btree_get_numrecs(block) || ptr <= 0) {
4217 		*stat = 0;
4218 		return 0;
4219 	}
4220 
4221 	/*
4222 	 * Point to the record and extract its data.
4223 	 */
4224 	*recp = xfs_btree_rec_addr(cur, ptr, block);
4225 	*stat = 1;
4226 	return 0;
4227 }
4228 
4229 /* Visit a block in a btree. */
4230 STATIC int
4231 xfs_btree_visit_block(
4232 	struct xfs_btree_cur		*cur,
4233 	int				level,
4234 	xfs_btree_visit_blocks_fn	fn,
4235 	void				*data)
4236 {
4237 	struct xfs_btree_block		*block;
4238 	struct xfs_buf			*bp;
4239 	union xfs_btree_ptr		rptr;
4240 	int				error;
4241 
4242 	/* do right sibling readahead */
4243 	xfs_btree_readahead(cur, level, XFS_BTCUR_RIGHTRA);
4244 	block = xfs_btree_get_block(cur, level, &bp);
4245 
4246 	/* process the block */
4247 	error = fn(cur, level, data);
4248 	if (error)
4249 		return error;
4250 
4251 	/* now read rh sibling block for next iteration */
4252 	xfs_btree_get_sibling(cur, block, &rptr, XFS_BB_RIGHTSIB);
4253 	if (xfs_btree_ptr_is_null(cur, &rptr))
4254 		return -ENOENT;
4255 
4256 	return xfs_btree_lookup_get_block(cur, level, &rptr, &block);
4257 }
4258 
4259 
4260 /* Visit every block in a btree. */
4261 int
4262 xfs_btree_visit_blocks(
4263 	struct xfs_btree_cur		*cur,
4264 	xfs_btree_visit_blocks_fn	fn,
4265 	unsigned int			flags,
4266 	void				*data)
4267 {
4268 	union xfs_btree_ptr		lptr;
4269 	int				level;
4270 	struct xfs_btree_block		*block = NULL;
4271 	int				error = 0;
4272 
4273 	cur->bc_ops->init_ptr_from_cur(cur, &lptr);
4274 
4275 	/* for each level */
4276 	for (level = cur->bc_nlevels - 1; level >= 0; level--) {
4277 		/* grab the left hand block */
4278 		error = xfs_btree_lookup_get_block(cur, level, &lptr, &block);
4279 		if (error)
4280 			return error;
4281 
4282 		/* readahead the left most block for the next level down */
4283 		if (level > 0) {
4284 			union xfs_btree_ptr     *ptr;
4285 
4286 			ptr = xfs_btree_ptr_addr(cur, 1, block);
4287 			xfs_btree_readahead_ptr(cur, ptr, 1);
4288 
4289 			/* save for the next iteration of the loop */
4290 			xfs_btree_copy_ptrs(cur, &lptr, ptr, 1);
4291 
4292 			if (!(flags & XFS_BTREE_VISIT_LEAVES))
4293 				continue;
4294 		} else if (!(flags & XFS_BTREE_VISIT_RECORDS)) {
4295 			continue;
4296 		}
4297 
4298 		/* for each buffer in the level */
4299 		do {
4300 			error = xfs_btree_visit_block(cur, level, fn, data);
4301 		} while (!error);
4302 
4303 		if (error != -ENOENT)
4304 			return error;
4305 	}
4306 
4307 	return 0;
4308 }
4309 
4310 /*
4311  * Change the owner of a btree.
4312  *
4313  * The mechanism we use here is ordered buffer logging. Because we don't know
4314  * how many buffers were are going to need to modify, we don't really want to
4315  * have to make transaction reservations for the worst case of every buffer in a
4316  * full size btree as that may be more space that we can fit in the log....
4317  *
4318  * We do the btree walk in the most optimal manner possible - we have sibling
4319  * pointers so we can just walk all the blocks on each level from left to right
4320  * in a single pass, and then move to the next level and do the same. We can
4321  * also do readahead on the sibling pointers to get IO moving more quickly,
4322  * though for slow disks this is unlikely to make much difference to performance
4323  * as the amount of CPU work we have to do before moving to the next block is
4324  * relatively small.
4325  *
4326  * For each btree block that we load, modify the owner appropriately, set the
4327  * buffer as an ordered buffer and log it appropriately. We need to ensure that
4328  * we mark the region we change dirty so that if the buffer is relogged in
4329  * a subsequent transaction the changes we make here as an ordered buffer are
4330  * correctly relogged in that transaction.  If we are in recovery context, then
4331  * just queue the modified buffer as delayed write buffer so the transaction
4332  * recovery completion writes the changes to disk.
4333  */
4334 struct xfs_btree_block_change_owner_info {
4335 	uint64_t		new_owner;
4336 	struct list_head	*buffer_list;
4337 };
4338 
4339 static int
4340 xfs_btree_block_change_owner(
4341 	struct xfs_btree_cur	*cur,
4342 	int			level,
4343 	void			*data)
4344 {
4345 	struct xfs_btree_block_change_owner_info	*bbcoi = data;
4346 	struct xfs_btree_block	*block;
4347 	struct xfs_buf		*bp;
4348 
4349 	/* modify the owner */
4350 	block = xfs_btree_get_block(cur, level, &bp);
4351 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
4352 		if (block->bb_u.l.bb_owner == cpu_to_be64(bbcoi->new_owner))
4353 			return 0;
4354 		block->bb_u.l.bb_owner = cpu_to_be64(bbcoi->new_owner);
4355 	} else {
4356 		if (block->bb_u.s.bb_owner == cpu_to_be32(bbcoi->new_owner))
4357 			return 0;
4358 		block->bb_u.s.bb_owner = cpu_to_be32(bbcoi->new_owner);
4359 	}
4360 
4361 	/*
4362 	 * If the block is a root block hosted in an inode, we might not have a
4363 	 * buffer pointer here and we shouldn't attempt to log the change as the
4364 	 * information is already held in the inode and discarded when the root
4365 	 * block is formatted into the on-disk inode fork. We still change it,
4366 	 * though, so everything is consistent in memory.
4367 	 */
4368 	if (!bp) {
4369 		ASSERT(cur->bc_flags & XFS_BTREE_ROOT_IN_INODE);
4370 		ASSERT(level == cur->bc_nlevels - 1);
4371 		return 0;
4372 	}
4373 
4374 	if (cur->bc_tp) {
4375 		if (!xfs_trans_ordered_buf(cur->bc_tp, bp)) {
4376 			xfs_btree_log_block(cur, bp, XFS_BB_OWNER);
4377 			return -EAGAIN;
4378 		}
4379 	} else {
4380 		xfs_buf_delwri_queue(bp, bbcoi->buffer_list);
4381 	}
4382 
4383 	return 0;
4384 }
4385 
4386 int
4387 xfs_btree_change_owner(
4388 	struct xfs_btree_cur	*cur,
4389 	uint64_t		new_owner,
4390 	struct list_head	*buffer_list)
4391 {
4392 	struct xfs_btree_block_change_owner_info	bbcoi;
4393 
4394 	bbcoi.new_owner = new_owner;
4395 	bbcoi.buffer_list = buffer_list;
4396 
4397 	return xfs_btree_visit_blocks(cur, xfs_btree_block_change_owner,
4398 			XFS_BTREE_VISIT_ALL, &bbcoi);
4399 }
4400 
4401 /* Verify the v5 fields of a long-format btree block. */
4402 xfs_failaddr_t
4403 xfs_btree_lblock_v5hdr_verify(
4404 	struct xfs_buf		*bp,
4405 	uint64_t		owner)
4406 {
4407 	struct xfs_mount	*mp = bp->b_mount;
4408 	struct xfs_btree_block	*block = XFS_BUF_TO_BLOCK(bp);
4409 
4410 	if (!xfs_sb_version_hascrc(&mp->m_sb))
4411 		return __this_address;
4412 	if (!uuid_equal(&block->bb_u.l.bb_uuid, &mp->m_sb.sb_meta_uuid))
4413 		return __this_address;
4414 	if (block->bb_u.l.bb_blkno != cpu_to_be64(bp->b_bn))
4415 		return __this_address;
4416 	if (owner != XFS_RMAP_OWN_UNKNOWN &&
4417 	    be64_to_cpu(block->bb_u.l.bb_owner) != owner)
4418 		return __this_address;
4419 	return NULL;
4420 }
4421 
4422 /* Verify a long-format btree block. */
4423 xfs_failaddr_t
4424 xfs_btree_lblock_verify(
4425 	struct xfs_buf		*bp,
4426 	unsigned int		max_recs)
4427 {
4428 	struct xfs_mount	*mp = bp->b_mount;
4429 	struct xfs_btree_block	*block = XFS_BUF_TO_BLOCK(bp);
4430 
4431 	/* numrecs verification */
4432 	if (be16_to_cpu(block->bb_numrecs) > max_recs)
4433 		return __this_address;
4434 
4435 	/* sibling pointer verification */
4436 	if (block->bb_u.l.bb_leftsib != cpu_to_be64(NULLFSBLOCK) &&
4437 	    !xfs_verify_fsbno(mp, be64_to_cpu(block->bb_u.l.bb_leftsib)))
4438 		return __this_address;
4439 	if (block->bb_u.l.bb_rightsib != cpu_to_be64(NULLFSBLOCK) &&
4440 	    !xfs_verify_fsbno(mp, be64_to_cpu(block->bb_u.l.bb_rightsib)))
4441 		return __this_address;
4442 
4443 	return NULL;
4444 }
4445 
4446 /**
4447  * xfs_btree_sblock_v5hdr_verify() -- verify the v5 fields of a short-format
4448  *				      btree block
4449  *
4450  * @bp: buffer containing the btree block
4451  */
4452 xfs_failaddr_t
4453 xfs_btree_sblock_v5hdr_verify(
4454 	struct xfs_buf		*bp)
4455 {
4456 	struct xfs_mount	*mp = bp->b_mount;
4457 	struct xfs_btree_block	*block = XFS_BUF_TO_BLOCK(bp);
4458 	struct xfs_perag	*pag = bp->b_pag;
4459 
4460 	if (!xfs_sb_version_hascrc(&mp->m_sb))
4461 		return __this_address;
4462 	if (!uuid_equal(&block->bb_u.s.bb_uuid, &mp->m_sb.sb_meta_uuid))
4463 		return __this_address;
4464 	if (block->bb_u.s.bb_blkno != cpu_to_be64(bp->b_bn))
4465 		return __this_address;
4466 	if (pag && be32_to_cpu(block->bb_u.s.bb_owner) != pag->pag_agno)
4467 		return __this_address;
4468 	return NULL;
4469 }
4470 
4471 /**
4472  * xfs_btree_sblock_verify() -- verify a short-format btree block
4473  *
4474  * @bp: buffer containing the btree block
4475  * @max_recs: maximum records allowed in this btree node
4476  */
4477 xfs_failaddr_t
4478 xfs_btree_sblock_verify(
4479 	struct xfs_buf		*bp,
4480 	unsigned int		max_recs)
4481 {
4482 	struct xfs_mount	*mp = bp->b_mount;
4483 	struct xfs_btree_block	*block = XFS_BUF_TO_BLOCK(bp);
4484 	xfs_agblock_t		agno;
4485 
4486 	/* numrecs verification */
4487 	if (be16_to_cpu(block->bb_numrecs) > max_recs)
4488 		return __this_address;
4489 
4490 	/* sibling pointer verification */
4491 	agno = xfs_daddr_to_agno(mp, XFS_BUF_ADDR(bp));
4492 	if (block->bb_u.s.bb_leftsib != cpu_to_be32(NULLAGBLOCK) &&
4493 	    !xfs_verify_agbno(mp, agno, be32_to_cpu(block->bb_u.s.bb_leftsib)))
4494 		return __this_address;
4495 	if (block->bb_u.s.bb_rightsib != cpu_to_be32(NULLAGBLOCK) &&
4496 	    !xfs_verify_agbno(mp, agno, be32_to_cpu(block->bb_u.s.bb_rightsib)))
4497 		return __this_address;
4498 
4499 	return NULL;
4500 }
4501 
4502 /*
4503  * Calculate the number of btree levels needed to store a given number of
4504  * records in a short-format btree.
4505  */
4506 uint
4507 xfs_btree_compute_maxlevels(
4508 	uint			*limits,
4509 	unsigned long		len)
4510 {
4511 	uint			level;
4512 	unsigned long		maxblocks;
4513 
4514 	maxblocks = (len + limits[0] - 1) / limits[0];
4515 	for (level = 1; maxblocks > 1; level++)
4516 		maxblocks = (maxblocks + limits[1] - 1) / limits[1];
4517 	return level;
4518 }
4519 
4520 /*
4521  * Query a regular btree for all records overlapping a given interval.
4522  * Start with a LE lookup of the key of low_rec and return all records
4523  * until we find a record with a key greater than the key of high_rec.
4524  */
4525 STATIC int
4526 xfs_btree_simple_query_range(
4527 	struct xfs_btree_cur		*cur,
4528 	union xfs_btree_key		*low_key,
4529 	union xfs_btree_key		*high_key,
4530 	xfs_btree_query_range_fn	fn,
4531 	void				*priv)
4532 {
4533 	union xfs_btree_rec		*recp;
4534 	union xfs_btree_key		rec_key;
4535 	int64_t				diff;
4536 	int				stat;
4537 	bool				firstrec = true;
4538 	int				error;
4539 
4540 	ASSERT(cur->bc_ops->init_high_key_from_rec);
4541 	ASSERT(cur->bc_ops->diff_two_keys);
4542 
4543 	/*
4544 	 * Find the leftmost record.  The btree cursor must be set
4545 	 * to the low record used to generate low_key.
4546 	 */
4547 	stat = 0;
4548 	error = xfs_btree_lookup(cur, XFS_LOOKUP_LE, &stat);
4549 	if (error)
4550 		goto out;
4551 
4552 	/* Nothing?  See if there's anything to the right. */
4553 	if (!stat) {
4554 		error = xfs_btree_increment(cur, 0, &stat);
4555 		if (error)
4556 			goto out;
4557 	}
4558 
4559 	while (stat) {
4560 		/* Find the record. */
4561 		error = xfs_btree_get_rec(cur, &recp, &stat);
4562 		if (error || !stat)
4563 			break;
4564 
4565 		/* Skip if high_key(rec) < low_key. */
4566 		if (firstrec) {
4567 			cur->bc_ops->init_high_key_from_rec(&rec_key, recp);
4568 			firstrec = false;
4569 			diff = cur->bc_ops->diff_two_keys(cur, low_key,
4570 					&rec_key);
4571 			if (diff > 0)
4572 				goto advloop;
4573 		}
4574 
4575 		/* Stop if high_key < low_key(rec). */
4576 		cur->bc_ops->init_key_from_rec(&rec_key, recp);
4577 		diff = cur->bc_ops->diff_two_keys(cur, &rec_key, high_key);
4578 		if (diff > 0)
4579 			break;
4580 
4581 		/* Callback */
4582 		error = fn(cur, recp, priv);
4583 		if (error)
4584 			break;
4585 
4586 advloop:
4587 		/* Move on to the next record. */
4588 		error = xfs_btree_increment(cur, 0, &stat);
4589 		if (error)
4590 			break;
4591 	}
4592 
4593 out:
4594 	return error;
4595 }
4596 
4597 /*
4598  * Query an overlapped interval btree for all records overlapping a given
4599  * interval.  This function roughly follows the algorithm given in
4600  * "Interval Trees" of _Introduction to Algorithms_, which is section
4601  * 14.3 in the 2nd and 3rd editions.
4602  *
4603  * First, generate keys for the low and high records passed in.
4604  *
4605  * For any leaf node, generate the high and low keys for the record.
4606  * If the record keys overlap with the query low/high keys, pass the
4607  * record to the function iterator.
4608  *
4609  * For any internal node, compare the low and high keys of each
4610  * pointer against the query low/high keys.  If there's an overlap,
4611  * follow the pointer.
4612  *
4613  * As an optimization, we stop scanning a block when we find a low key
4614  * that is greater than the query's high key.
4615  */
4616 STATIC int
4617 xfs_btree_overlapped_query_range(
4618 	struct xfs_btree_cur		*cur,
4619 	union xfs_btree_key		*low_key,
4620 	union xfs_btree_key		*high_key,
4621 	xfs_btree_query_range_fn	fn,
4622 	void				*priv)
4623 {
4624 	union xfs_btree_ptr		ptr;
4625 	union xfs_btree_ptr		*pp;
4626 	union xfs_btree_key		rec_key;
4627 	union xfs_btree_key		rec_hkey;
4628 	union xfs_btree_key		*lkp;
4629 	union xfs_btree_key		*hkp;
4630 	union xfs_btree_rec		*recp;
4631 	struct xfs_btree_block		*block;
4632 	int64_t				ldiff;
4633 	int64_t				hdiff;
4634 	int				level;
4635 	struct xfs_buf			*bp;
4636 	int				i;
4637 	int				error;
4638 
4639 	/* Load the root of the btree. */
4640 	level = cur->bc_nlevels - 1;
4641 	cur->bc_ops->init_ptr_from_cur(cur, &ptr);
4642 	error = xfs_btree_lookup_get_block(cur, level, &ptr, &block);
4643 	if (error)
4644 		return error;
4645 	xfs_btree_get_block(cur, level, &bp);
4646 	trace_xfs_btree_overlapped_query_range(cur, level, bp);
4647 #ifdef DEBUG
4648 	error = xfs_btree_check_block(cur, block, level, bp);
4649 	if (error)
4650 		goto out;
4651 #endif
4652 	cur->bc_ptrs[level] = 1;
4653 
4654 	while (level < cur->bc_nlevels) {
4655 		block = xfs_btree_get_block(cur, level, &bp);
4656 
4657 		/* End of node, pop back towards the root. */
4658 		if (cur->bc_ptrs[level] > be16_to_cpu(block->bb_numrecs)) {
4659 pop_up:
4660 			if (level < cur->bc_nlevels - 1)
4661 				cur->bc_ptrs[level + 1]++;
4662 			level++;
4663 			continue;
4664 		}
4665 
4666 		if (level == 0) {
4667 			/* Handle a leaf node. */
4668 			recp = xfs_btree_rec_addr(cur, cur->bc_ptrs[0], block);
4669 
4670 			cur->bc_ops->init_high_key_from_rec(&rec_hkey, recp);
4671 			ldiff = cur->bc_ops->diff_two_keys(cur, &rec_hkey,
4672 					low_key);
4673 
4674 			cur->bc_ops->init_key_from_rec(&rec_key, recp);
4675 			hdiff = cur->bc_ops->diff_two_keys(cur, high_key,
4676 					&rec_key);
4677 
4678 			/*
4679 			 * If (record's high key >= query's low key) and
4680 			 *    (query's high key >= record's low key), then
4681 			 * this record overlaps the query range; callback.
4682 			 */
4683 			if (ldiff >= 0 && hdiff >= 0) {
4684 				error = fn(cur, recp, priv);
4685 				if (error)
4686 					break;
4687 			} else if (hdiff < 0) {
4688 				/* Record is larger than high key; pop. */
4689 				goto pop_up;
4690 			}
4691 			cur->bc_ptrs[level]++;
4692 			continue;
4693 		}
4694 
4695 		/* Handle an internal node. */
4696 		lkp = xfs_btree_key_addr(cur, cur->bc_ptrs[level], block);
4697 		hkp = xfs_btree_high_key_addr(cur, cur->bc_ptrs[level], block);
4698 		pp = xfs_btree_ptr_addr(cur, cur->bc_ptrs[level], block);
4699 
4700 		ldiff = cur->bc_ops->diff_two_keys(cur, hkp, low_key);
4701 		hdiff = cur->bc_ops->diff_two_keys(cur, high_key, lkp);
4702 
4703 		/*
4704 		 * If (pointer's high key >= query's low key) and
4705 		 *    (query's high key >= pointer's low key), then
4706 		 * this record overlaps the query range; follow pointer.
4707 		 */
4708 		if (ldiff >= 0 && hdiff >= 0) {
4709 			level--;
4710 			error = xfs_btree_lookup_get_block(cur, level, pp,
4711 					&block);
4712 			if (error)
4713 				goto out;
4714 			xfs_btree_get_block(cur, level, &bp);
4715 			trace_xfs_btree_overlapped_query_range(cur, level, bp);
4716 #ifdef DEBUG
4717 			error = xfs_btree_check_block(cur, block, level, bp);
4718 			if (error)
4719 				goto out;
4720 #endif
4721 			cur->bc_ptrs[level] = 1;
4722 			continue;
4723 		} else if (hdiff < 0) {
4724 			/* The low key is larger than the upper range; pop. */
4725 			goto pop_up;
4726 		}
4727 		cur->bc_ptrs[level]++;
4728 	}
4729 
4730 out:
4731 	/*
4732 	 * If we don't end this function with the cursor pointing at a record
4733 	 * block, a subsequent non-error cursor deletion will not release
4734 	 * node-level buffers, causing a buffer leak.  This is quite possible
4735 	 * with a zero-results range query, so release the buffers if we
4736 	 * failed to return any results.
4737 	 */
4738 	if (cur->bc_bufs[0] == NULL) {
4739 		for (i = 0; i < cur->bc_nlevels; i++) {
4740 			if (cur->bc_bufs[i]) {
4741 				xfs_trans_brelse(cur->bc_tp, cur->bc_bufs[i]);
4742 				cur->bc_bufs[i] = NULL;
4743 				cur->bc_ptrs[i] = 0;
4744 				cur->bc_ra[i] = 0;
4745 			}
4746 		}
4747 	}
4748 
4749 	return error;
4750 }
4751 
4752 /*
4753  * Query a btree for all records overlapping a given interval of keys.  The
4754  * supplied function will be called with each record found; return one of the
4755  * XFS_BTREE_QUERY_RANGE_{CONTINUE,ABORT} values or the usual negative error
4756  * code.  This function returns -ECANCELED, zero, or a negative error code.
4757  */
4758 int
4759 xfs_btree_query_range(
4760 	struct xfs_btree_cur		*cur,
4761 	union xfs_btree_irec		*low_rec,
4762 	union xfs_btree_irec		*high_rec,
4763 	xfs_btree_query_range_fn	fn,
4764 	void				*priv)
4765 {
4766 	union xfs_btree_rec		rec;
4767 	union xfs_btree_key		low_key;
4768 	union xfs_btree_key		high_key;
4769 
4770 	/* Find the keys of both ends of the interval. */
4771 	cur->bc_rec = *high_rec;
4772 	cur->bc_ops->init_rec_from_cur(cur, &rec);
4773 	cur->bc_ops->init_key_from_rec(&high_key, &rec);
4774 
4775 	cur->bc_rec = *low_rec;
4776 	cur->bc_ops->init_rec_from_cur(cur, &rec);
4777 	cur->bc_ops->init_key_from_rec(&low_key, &rec);
4778 
4779 	/* Enforce low key < high key. */
4780 	if (cur->bc_ops->diff_two_keys(cur, &low_key, &high_key) > 0)
4781 		return -EINVAL;
4782 
4783 	if (!(cur->bc_flags & XFS_BTREE_OVERLAPPING))
4784 		return xfs_btree_simple_query_range(cur, &low_key,
4785 				&high_key, fn, priv);
4786 	return xfs_btree_overlapped_query_range(cur, &low_key, &high_key,
4787 			fn, priv);
4788 }
4789 
4790 /* Query a btree for all records. */
4791 int
4792 xfs_btree_query_all(
4793 	struct xfs_btree_cur		*cur,
4794 	xfs_btree_query_range_fn	fn,
4795 	void				*priv)
4796 {
4797 	union xfs_btree_key		low_key;
4798 	union xfs_btree_key		high_key;
4799 
4800 	memset(&cur->bc_rec, 0, sizeof(cur->bc_rec));
4801 	memset(&low_key, 0, sizeof(low_key));
4802 	memset(&high_key, 0xFF, sizeof(high_key));
4803 
4804 	return xfs_btree_simple_query_range(cur, &low_key, &high_key, fn, priv);
4805 }
4806 
4807 /*
4808  * Calculate the number of blocks needed to store a given number of records
4809  * in a short-format (per-AG metadata) btree.
4810  */
4811 unsigned long long
4812 xfs_btree_calc_size(
4813 	uint			*limits,
4814 	unsigned long long	len)
4815 {
4816 	int			level;
4817 	int			maxrecs;
4818 	unsigned long long	rval;
4819 
4820 	maxrecs = limits[0];
4821 	for (level = 0, rval = 0; len > 1; level++) {
4822 		len += maxrecs - 1;
4823 		do_div(len, maxrecs);
4824 		maxrecs = limits[1];
4825 		rval += len;
4826 	}
4827 	return rval;
4828 }
4829 
4830 static int
4831 xfs_btree_count_blocks_helper(
4832 	struct xfs_btree_cur	*cur,
4833 	int			level,
4834 	void			*data)
4835 {
4836 	xfs_extlen_t		*blocks = data;
4837 	(*blocks)++;
4838 
4839 	return 0;
4840 }
4841 
4842 /* Count the blocks in a btree and return the result in *blocks. */
4843 int
4844 xfs_btree_count_blocks(
4845 	struct xfs_btree_cur	*cur,
4846 	xfs_extlen_t		*blocks)
4847 {
4848 	*blocks = 0;
4849 	return xfs_btree_visit_blocks(cur, xfs_btree_count_blocks_helper,
4850 			XFS_BTREE_VISIT_ALL, blocks);
4851 }
4852 
4853 /* Compare two btree pointers. */
4854 int64_t
4855 xfs_btree_diff_two_ptrs(
4856 	struct xfs_btree_cur		*cur,
4857 	const union xfs_btree_ptr	*a,
4858 	const union xfs_btree_ptr	*b)
4859 {
4860 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
4861 		return (int64_t)be64_to_cpu(a->l) - be64_to_cpu(b->l);
4862 	return (int64_t)be32_to_cpu(a->s) - be32_to_cpu(b->s);
4863 }
4864 
4865 /* If there's an extent, we're done. */
4866 STATIC int
4867 xfs_btree_has_record_helper(
4868 	struct xfs_btree_cur		*cur,
4869 	union xfs_btree_rec		*rec,
4870 	void				*priv)
4871 {
4872 	return -ECANCELED;
4873 }
4874 
4875 /* Is there a record covering a given range of keys? */
4876 int
4877 xfs_btree_has_record(
4878 	struct xfs_btree_cur	*cur,
4879 	union xfs_btree_irec	*low,
4880 	union xfs_btree_irec	*high,
4881 	bool			*exists)
4882 {
4883 	int			error;
4884 
4885 	error = xfs_btree_query_range(cur, low, high,
4886 			&xfs_btree_has_record_helper, NULL);
4887 	if (error == -ECANCELED) {
4888 		*exists = true;
4889 		return 0;
4890 	}
4891 	*exists = false;
4892 	return error;
4893 }
4894 
4895 /* Are there more records in this btree? */
4896 bool
4897 xfs_btree_has_more_records(
4898 	struct xfs_btree_cur	*cur)
4899 {
4900 	struct xfs_btree_block	*block;
4901 	struct xfs_buf		*bp;
4902 
4903 	block = xfs_btree_get_block(cur, 0, &bp);
4904 
4905 	/* There are still records in this block. */
4906 	if (cur->bc_ptrs[0] < xfs_btree_get_numrecs(block))
4907 		return true;
4908 
4909 	/* There are more record blocks. */
4910 	if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
4911 		return block->bb_u.l.bb_rightsib != cpu_to_be64(NULLFSBLOCK);
4912 	else
4913 		return block->bb_u.s.bb_rightsib != cpu_to_be32(NULLAGBLOCK);
4914 }
4915