Linux Audio

Check our new training course

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