Linux Audio

Check our new training course

Loading...
v6.9.4
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * Copyright (c) 2000-2005 Silicon Graphics, Inc.
   4 * Copyright (c) 2013 Red Hat, Inc.
   5 * All Rights Reserved.
   6 */
   7#include "xfs.h"
   8#include "xfs_fs.h"
   9#include "xfs_shared.h"
  10#include "xfs_format.h"
  11#include "xfs_log_format.h"
  12#include "xfs_trans_resv.h"
  13#include "xfs_mount.h"
  14#include "xfs_inode.h"
  15#include "xfs_bmap.h"
  16#include "xfs_dir2.h"
  17#include "xfs_dir2_priv.h"
  18#include "xfs_error.h"
  19#include "xfs_trace.h"
  20#include "xfs_trans.h"
  21#include "xfs_buf_item.h"
  22#include "xfs_log.h"
  23#include "xfs_health.h"
  24
  25/*
  26 * Function declarations.
  27 */
  28static int xfs_dir2_leafn_add(struct xfs_buf *bp, xfs_da_args_t *args,
  29			      int index);
  30static void xfs_dir2_leafn_rebalance(xfs_da_state_t *state,
  31				     xfs_da_state_blk_t *blk1,
  32				     xfs_da_state_blk_t *blk2);
  33static int xfs_dir2_leafn_remove(xfs_da_args_t *args, struct xfs_buf *bp,
  34				 int index, xfs_da_state_blk_t *dblk,
  35				 int *rval);
  36
  37/*
  38 * Convert data space db to the corresponding free db.
  39 */
  40static xfs_dir2_db_t
  41xfs_dir2_db_to_fdb(struct xfs_da_geometry *geo, xfs_dir2_db_t db)
  42{
  43	return xfs_dir2_byte_to_db(geo, XFS_DIR2_FREE_OFFSET) +
  44			(db / geo->free_max_bests);
  45}
  46
  47/*
  48 * Convert data space db to the corresponding index in a free db.
  49 */
  50static int
  51xfs_dir2_db_to_fdindex(struct xfs_da_geometry *geo, xfs_dir2_db_t db)
  52{
  53	return db % geo->free_max_bests;
  54}
  55
  56/*
  57 * Check internal consistency of a leafn block.
  58 */
  59#ifdef DEBUG
  60static xfs_failaddr_t
  61xfs_dir3_leafn_check(
  62	struct xfs_inode	*dp,
  63	struct xfs_buf		*bp)
  64{
  65	struct xfs_dir2_leaf	*leaf = bp->b_addr;
  66	struct xfs_dir3_icleaf_hdr leafhdr;
  67
  68	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
  69
  70	if (leafhdr.magic == XFS_DIR3_LEAFN_MAGIC) {
  71		struct xfs_dir3_leaf_hdr *leaf3 = bp->b_addr;
  72		if (be64_to_cpu(leaf3->info.blkno) != xfs_buf_daddr(bp))
  73			return __this_address;
  74	} else if (leafhdr.magic != XFS_DIR2_LEAFN_MAGIC)
  75		return __this_address;
  76
  77	return xfs_dir3_leaf_check_int(dp->i_mount, &leafhdr, leaf, false);
  78}
  79
  80static inline void
  81xfs_dir3_leaf_check(
  82	struct xfs_inode	*dp,
  83	struct xfs_buf		*bp)
  84{
  85	xfs_failaddr_t		fa;
  86
  87	fa = xfs_dir3_leafn_check(dp, bp);
  88	if (!fa)
  89		return;
  90	xfs_corruption_error(__func__, XFS_ERRLEVEL_LOW, dp->i_mount,
  91			bp->b_addr, BBTOB(bp->b_length), __FILE__, __LINE__,
  92			fa);
  93	ASSERT(0);
  94}
  95#else
  96#define	xfs_dir3_leaf_check(dp, bp)
  97#endif
  98
  99static xfs_failaddr_t
 100xfs_dir3_free_verify(
 101	struct xfs_buf		*bp)
 102{
 103	struct xfs_mount	*mp = bp->b_mount;
 104	struct xfs_dir2_free_hdr *hdr = bp->b_addr;
 105
 106	if (!xfs_verify_magic(bp, hdr->magic))
 107		return __this_address;
 108
 109	if (xfs_has_crc(mp)) {
 110		struct xfs_dir3_blk_hdr *hdr3 = bp->b_addr;
 111
 112		if (!uuid_equal(&hdr3->uuid, &mp->m_sb.sb_meta_uuid))
 113			return __this_address;
 114		if (be64_to_cpu(hdr3->blkno) != xfs_buf_daddr(bp))
 115			return __this_address;
 116		if (!xfs_log_check_lsn(mp, be64_to_cpu(hdr3->lsn)))
 117			return __this_address;
 118	}
 119
 120	/* XXX: should bounds check the xfs_dir3_icfree_hdr here */
 121
 122	return NULL;
 123}
 124
 125static void
 126xfs_dir3_free_read_verify(
 127	struct xfs_buf	*bp)
 128{
 129	struct xfs_mount	*mp = bp->b_mount;
 130	xfs_failaddr_t		fa;
 131
 132	if (xfs_has_crc(mp) &&
 133	    !xfs_buf_verify_cksum(bp, XFS_DIR3_FREE_CRC_OFF))
 134		xfs_verifier_error(bp, -EFSBADCRC, __this_address);
 135	else {
 136		fa = xfs_dir3_free_verify(bp);
 137		if (fa)
 138			xfs_verifier_error(bp, -EFSCORRUPTED, fa);
 139	}
 140}
 141
 142static void
 143xfs_dir3_free_write_verify(
 144	struct xfs_buf	*bp)
 145{
 146	struct xfs_mount	*mp = bp->b_mount;
 147	struct xfs_buf_log_item	*bip = bp->b_log_item;
 148	struct xfs_dir3_blk_hdr	*hdr3 = bp->b_addr;
 149	xfs_failaddr_t		fa;
 150
 151	fa = xfs_dir3_free_verify(bp);
 152	if (fa) {
 153		xfs_verifier_error(bp, -EFSCORRUPTED, fa);
 154		return;
 155	}
 156
 157	if (!xfs_has_crc(mp))
 158		return;
 159
 160	if (bip)
 161		hdr3->lsn = cpu_to_be64(bip->bli_item.li_lsn);
 162
 163	xfs_buf_update_cksum(bp, XFS_DIR3_FREE_CRC_OFF);
 164}
 165
 166const struct xfs_buf_ops xfs_dir3_free_buf_ops = {
 167	.name = "xfs_dir3_free",
 168	.magic = { cpu_to_be32(XFS_DIR2_FREE_MAGIC),
 169		   cpu_to_be32(XFS_DIR3_FREE_MAGIC) },
 170	.verify_read = xfs_dir3_free_read_verify,
 171	.verify_write = xfs_dir3_free_write_verify,
 172	.verify_struct = xfs_dir3_free_verify,
 173};
 174
 175/* Everything ok in the free block header? */
 176static xfs_failaddr_t
 177xfs_dir3_free_header_check(
 178	struct xfs_inode	*dp,
 179	xfs_dablk_t		fbno,
 180	struct xfs_buf		*bp)
 181{
 182	struct xfs_mount	*mp = dp->i_mount;
 183	int			maxbests = mp->m_dir_geo->free_max_bests;
 184	unsigned int		firstdb;
 185
 186	firstdb = (xfs_dir2_da_to_db(mp->m_dir_geo, fbno) -
 187		   xfs_dir2_byte_to_db(mp->m_dir_geo, XFS_DIR2_FREE_OFFSET)) *
 188			maxbests;
 189	if (xfs_has_crc(mp)) {
 190		struct xfs_dir3_free_hdr *hdr3 = bp->b_addr;
 191
 192		if (be32_to_cpu(hdr3->firstdb) != firstdb)
 193			return __this_address;
 194		if (be32_to_cpu(hdr3->nvalid) > maxbests)
 195			return __this_address;
 196		if (be32_to_cpu(hdr3->nvalid) < be32_to_cpu(hdr3->nused))
 197			return __this_address;
 198		if (be64_to_cpu(hdr3->hdr.owner) != dp->i_ino)
 199			return __this_address;
 200	} else {
 201		struct xfs_dir2_free_hdr *hdr = bp->b_addr;
 202
 203		if (be32_to_cpu(hdr->firstdb) != firstdb)
 204			return __this_address;
 205		if (be32_to_cpu(hdr->nvalid) > maxbests)
 206			return __this_address;
 207		if (be32_to_cpu(hdr->nvalid) < be32_to_cpu(hdr->nused))
 208			return __this_address;
 209	}
 210	return NULL;
 211}
 212
 213static int
 214__xfs_dir3_free_read(
 215	struct xfs_trans	*tp,
 216	struct xfs_inode	*dp,
 217	xfs_dablk_t		fbno,
 218	unsigned int		flags,
 219	struct xfs_buf		**bpp)
 220{
 221	xfs_failaddr_t		fa;
 222	int			err;
 223
 224	err = xfs_da_read_buf(tp, dp, fbno, flags, bpp, XFS_DATA_FORK,
 225			&xfs_dir3_free_buf_ops);
 226	if (err || !*bpp)
 227		return err;
 228
 229	/* Check things that we can't do in the verifier. */
 230	fa = xfs_dir3_free_header_check(dp, fbno, *bpp);
 231	if (fa) {
 232		__xfs_buf_mark_corrupt(*bpp, fa);
 233		xfs_trans_brelse(tp, *bpp);
 234		*bpp = NULL;
 235		xfs_dirattr_mark_sick(dp, XFS_DATA_FORK);
 236		return -EFSCORRUPTED;
 237	}
 238
 239	/* try read returns without an error or *bpp if it lands in a hole */
 240	if (tp)
 241		xfs_trans_buf_set_type(tp, *bpp, XFS_BLFT_DIR_FREE_BUF);
 242
 243	return 0;
 244}
 245
 246void
 247xfs_dir2_free_hdr_from_disk(
 248	struct xfs_mount		*mp,
 249	struct xfs_dir3_icfree_hdr	*to,
 250	struct xfs_dir2_free		*from)
 251{
 252	if (xfs_has_crc(mp)) {
 253		struct xfs_dir3_free	*from3 = (struct xfs_dir3_free *)from;
 254
 255		to->magic = be32_to_cpu(from3->hdr.hdr.magic);
 256		to->firstdb = be32_to_cpu(from3->hdr.firstdb);
 257		to->nvalid = be32_to_cpu(from3->hdr.nvalid);
 258		to->nused = be32_to_cpu(from3->hdr.nused);
 259		to->bests = from3->bests;
 260
 261		ASSERT(to->magic == XFS_DIR3_FREE_MAGIC);
 262	} else {
 263		to->magic = be32_to_cpu(from->hdr.magic);
 264		to->firstdb = be32_to_cpu(from->hdr.firstdb);
 265		to->nvalid = be32_to_cpu(from->hdr.nvalid);
 266		to->nused = be32_to_cpu(from->hdr.nused);
 267		to->bests = from->bests;
 268
 269		ASSERT(to->magic == XFS_DIR2_FREE_MAGIC);
 270	}
 271}
 272
 273static void
 274xfs_dir2_free_hdr_to_disk(
 275	struct xfs_mount		*mp,
 276	struct xfs_dir2_free		*to,
 277	struct xfs_dir3_icfree_hdr	*from)
 278{
 279	if (xfs_has_crc(mp)) {
 280		struct xfs_dir3_free	*to3 = (struct xfs_dir3_free *)to;
 281
 282		ASSERT(from->magic == XFS_DIR3_FREE_MAGIC);
 283
 284		to3->hdr.hdr.magic = cpu_to_be32(from->magic);
 285		to3->hdr.firstdb = cpu_to_be32(from->firstdb);
 286		to3->hdr.nvalid = cpu_to_be32(from->nvalid);
 287		to3->hdr.nused = cpu_to_be32(from->nused);
 288	} else {
 289		ASSERT(from->magic == XFS_DIR2_FREE_MAGIC);
 290
 291		to->hdr.magic = cpu_to_be32(from->magic);
 292		to->hdr.firstdb = cpu_to_be32(from->firstdb);
 293		to->hdr.nvalid = cpu_to_be32(from->nvalid);
 294		to->hdr.nused = cpu_to_be32(from->nused);
 295	}
 296}
 297
 298int
 299xfs_dir2_free_read(
 300	struct xfs_trans	*tp,
 301	struct xfs_inode	*dp,
 302	xfs_dablk_t		fbno,
 303	struct xfs_buf		**bpp)
 304{
 305	return __xfs_dir3_free_read(tp, dp, fbno, 0, bpp);
 306}
 307
 308static int
 309xfs_dir2_free_try_read(
 310	struct xfs_trans	*tp,
 311	struct xfs_inode	*dp,
 312	xfs_dablk_t		fbno,
 313	struct xfs_buf		**bpp)
 314{
 315	return __xfs_dir3_free_read(tp, dp, fbno, XFS_DABUF_MAP_HOLE_OK, bpp);
 316}
 317
 318static int
 319xfs_dir3_free_get_buf(
 320	xfs_da_args_t		*args,
 321	xfs_dir2_db_t		fbno,
 322	struct xfs_buf		**bpp)
 323{
 324	struct xfs_trans	*tp = args->trans;
 325	struct xfs_inode	*dp = args->dp;
 326	struct xfs_mount	*mp = dp->i_mount;
 327	struct xfs_buf		*bp;
 328	int			error;
 329	struct xfs_dir3_icfree_hdr hdr;
 330
 331	error = xfs_da_get_buf(tp, dp, xfs_dir2_db_to_da(args->geo, fbno),
 332			&bp, XFS_DATA_FORK);
 333	if (error)
 334		return error;
 335
 336	xfs_trans_buf_set_type(tp, bp, XFS_BLFT_DIR_FREE_BUF);
 337	bp->b_ops = &xfs_dir3_free_buf_ops;
 338
 339	/*
 340	 * Initialize the new block to be empty, and remember
 341	 * its first slot as our empty slot.
 342	 */
 343	memset(bp->b_addr, 0, sizeof(struct xfs_dir3_free_hdr));
 344	memset(&hdr, 0, sizeof(hdr));
 345
 346	if (xfs_has_crc(mp)) {
 347		struct xfs_dir3_free_hdr *hdr3 = bp->b_addr;
 348
 349		hdr.magic = XFS_DIR3_FREE_MAGIC;
 350
 351		hdr3->hdr.blkno = cpu_to_be64(xfs_buf_daddr(bp));
 352		hdr3->hdr.owner = cpu_to_be64(dp->i_ino);
 353		uuid_copy(&hdr3->hdr.uuid, &mp->m_sb.sb_meta_uuid);
 354	} else
 355		hdr.magic = XFS_DIR2_FREE_MAGIC;
 356	xfs_dir2_free_hdr_to_disk(mp, bp->b_addr, &hdr);
 357	*bpp = bp;
 358	return 0;
 359}
 360
 361/*
 362 * Log entries from a freespace block.
 363 */
 364STATIC void
 365xfs_dir2_free_log_bests(
 366	struct xfs_da_args	*args,
 367	struct xfs_dir3_icfree_hdr *hdr,
 368	struct xfs_buf		*bp,
 369	int			first,		/* first entry to log */
 370	int			last)		/* last entry to log */
 371{
 372	struct xfs_dir2_free	*free = bp->b_addr;
 373
 374	ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
 375	       free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
 376	xfs_trans_log_buf(args->trans, bp,
 377			  (char *)&hdr->bests[first] - (char *)free,
 378			  (char *)&hdr->bests[last] - (char *)free +
 379			   sizeof(hdr->bests[0]) - 1);
 380}
 381
 382/*
 383 * Log header from a freespace block.
 384 */
 385static void
 386xfs_dir2_free_log_header(
 387	struct xfs_da_args	*args,
 388	struct xfs_buf		*bp)
 389{
 390#ifdef DEBUG
 391	xfs_dir2_free_t		*free;		/* freespace structure */
 392
 393	free = bp->b_addr;
 394	ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
 395	       free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
 396#endif
 397	xfs_trans_log_buf(args->trans, bp, 0,
 398			  args->geo->free_hdr_size - 1);
 399}
 400
 401/*
 402 * Convert a leaf-format directory to a node-format directory.
 403 * We need to change the magic number of the leaf block, and copy
 404 * the freespace table out of the leaf block into its own block.
 405 */
 406int						/* error */
 407xfs_dir2_leaf_to_node(
 408	xfs_da_args_t		*args,		/* operation arguments */
 409	struct xfs_buf		*lbp)		/* leaf buffer */
 410{
 411	xfs_inode_t		*dp;		/* incore directory inode */
 412	int			error;		/* error return value */
 413	struct xfs_buf		*fbp;		/* freespace buffer */
 414	xfs_dir2_db_t		fdb;		/* freespace block number */
 415	__be16			*from;		/* pointer to freespace entry */
 416	int			i;		/* leaf freespace index */
 417	xfs_dir2_leaf_t		*leaf;		/* leaf structure */
 418	xfs_dir2_leaf_tail_t	*ltp;		/* leaf tail structure */
 419	int			n;		/* count of live freespc ents */
 420	xfs_dir2_data_off_t	off;		/* freespace entry value */
 421	xfs_trans_t		*tp;		/* transaction pointer */
 422	struct xfs_dir3_icfree_hdr freehdr;
 423
 424	trace_xfs_dir2_leaf_to_node(args);
 425
 426	dp = args->dp;
 427	tp = args->trans;
 428	/*
 429	 * Add a freespace block to the directory.
 430	 */
 431	if ((error = xfs_dir2_grow_inode(args, XFS_DIR2_FREE_SPACE, &fdb))) {
 432		return error;
 433	}
 434	ASSERT(fdb == xfs_dir2_byte_to_db(args->geo, XFS_DIR2_FREE_OFFSET));
 435	/*
 436	 * Get the buffer for the new freespace block.
 437	 */
 438	error = xfs_dir3_free_get_buf(args, fdb, &fbp);
 439	if (error)
 440		return error;
 441
 442	xfs_dir2_free_hdr_from_disk(dp->i_mount, &freehdr, fbp->b_addr);
 443	leaf = lbp->b_addr;
 444	ltp = xfs_dir2_leaf_tail_p(args->geo, leaf);
 445	if (be32_to_cpu(ltp->bestcount) >
 446				(uint)dp->i_disk_size / args->geo->blksize) {
 447		xfs_buf_mark_corrupt(lbp);
 448		xfs_da_mark_sick(args);
 449		return -EFSCORRUPTED;
 450	}
 451
 452	/*
 453	 * Copy freespace entries from the leaf block to the new block.
 454	 * Count active entries.
 455	 */
 456	from = xfs_dir2_leaf_bests_p(ltp);
 457	for (i = n = 0; i < be32_to_cpu(ltp->bestcount); i++, from++) {
 458		off = be16_to_cpu(*from);
 459		if (off != NULLDATAOFF)
 460			n++;
 461		freehdr.bests[i] = cpu_to_be16(off);
 462	}
 463
 464	/*
 465	 * Now initialize the freespace block header.
 466	 */
 467	freehdr.nused = n;
 468	freehdr.nvalid = be32_to_cpu(ltp->bestcount);
 469
 470	xfs_dir2_free_hdr_to_disk(dp->i_mount, fbp->b_addr, &freehdr);
 471	xfs_dir2_free_log_bests(args, &freehdr, fbp, 0, freehdr.nvalid - 1);
 472	xfs_dir2_free_log_header(args, fbp);
 473
 474	/*
 475	 * Converting the leaf to a leafnode is just a matter of changing the
 476	 * magic number and the ops. Do the change directly to the buffer as
 477	 * it's less work (and less code) than decoding the header to host
 478	 * format and back again.
 479	 */
 480	if (leaf->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAF1_MAGIC))
 481		leaf->hdr.info.magic = cpu_to_be16(XFS_DIR2_LEAFN_MAGIC);
 482	else
 483		leaf->hdr.info.magic = cpu_to_be16(XFS_DIR3_LEAFN_MAGIC);
 484	lbp->b_ops = &xfs_dir3_leafn_buf_ops;
 485	xfs_trans_buf_set_type(tp, lbp, XFS_BLFT_DIR_LEAFN_BUF);
 486	xfs_dir3_leaf_log_header(args, lbp);
 487	xfs_dir3_leaf_check(dp, lbp);
 488	return 0;
 489}
 490
 491/*
 492 * Add a leaf entry to a leaf block in a node-form directory.
 493 * The other work necessary is done from the caller.
 494 */
 495static int					/* error */
 496xfs_dir2_leafn_add(
 497	struct xfs_buf		*bp,		/* leaf buffer */
 498	struct xfs_da_args	*args,		/* operation arguments */
 499	int			index)		/* insertion pt for new entry */
 500{
 501	struct xfs_dir3_icleaf_hdr leafhdr;
 502	struct xfs_inode	*dp = args->dp;
 503	struct xfs_dir2_leaf	*leaf = bp->b_addr;
 504	struct xfs_dir2_leaf_entry *lep;
 505	struct xfs_dir2_leaf_entry *ents;
 506	int			compact;	/* compacting stale leaves */
 507	int			highstale = 0;	/* next stale entry */
 508	int			lfloghigh;	/* high leaf entry logging */
 509	int			lfloglow;	/* low leaf entry logging */
 510	int			lowstale = 0;	/* previous stale entry */
 511
 512	trace_xfs_dir2_leafn_add(args, index);
 513
 514	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
 515	ents = leafhdr.ents;
 516
 517	/*
 518	 * Quick check just to make sure we are not going to index
 519	 * into other peoples memory
 520	 */
 521	if (index < 0) {
 522		xfs_buf_mark_corrupt(bp);
 523		xfs_da_mark_sick(args);
 524		return -EFSCORRUPTED;
 525	}
 526
 527	/*
 528	 * If there are already the maximum number of leaf entries in
 529	 * the block, if there are no stale entries it won't fit.
 530	 * Caller will do a split.  If there are stale entries we'll do
 531	 * a compact.
 532	 */
 533
 534	if (leafhdr.count == args->geo->leaf_max_ents) {
 535		if (!leafhdr.stale)
 536			return -ENOSPC;
 537		compact = leafhdr.stale > 1;
 538	} else
 539		compact = 0;
 540	ASSERT(index == 0 || be32_to_cpu(ents[index - 1].hashval) <= args->hashval);
 541	ASSERT(index == leafhdr.count ||
 542	       be32_to_cpu(ents[index].hashval) >= args->hashval);
 543
 544	if (args->op_flags & XFS_DA_OP_JUSTCHECK)
 545		return 0;
 546
 547	/*
 548	 * Compact out all but one stale leaf entry.  Leaves behind
 549	 * the entry closest to index.
 550	 */
 551	if (compact)
 552		xfs_dir3_leaf_compact_x1(&leafhdr, ents, &index, &lowstale,
 553					 &highstale, &lfloglow, &lfloghigh);
 554	else if (leafhdr.stale) {
 555		/*
 556		 * Set impossible logging indices for this case.
 557		 */
 558		lfloglow = leafhdr.count;
 559		lfloghigh = -1;
 560	}
 561
 562	/*
 563	 * Insert the new entry, log everything.
 564	 */
 565	lep = xfs_dir3_leaf_find_entry(&leafhdr, ents, index, compact, lowstale,
 566				       highstale, &lfloglow, &lfloghigh);
 567
 568	lep->hashval = cpu_to_be32(args->hashval);
 569	lep->address = cpu_to_be32(xfs_dir2_db_off_to_dataptr(args->geo,
 570				args->blkno, args->index));
 571
 572	xfs_dir2_leaf_hdr_to_disk(dp->i_mount, leaf, &leafhdr);
 573	xfs_dir3_leaf_log_header(args, bp);
 574	xfs_dir3_leaf_log_ents(args, &leafhdr, bp, lfloglow, lfloghigh);
 575	xfs_dir3_leaf_check(dp, bp);
 576	return 0;
 577}
 578
 579#ifdef DEBUG
 580static void
 581xfs_dir2_free_hdr_check(
 582	struct xfs_inode *dp,
 583	struct xfs_buf	*bp,
 584	xfs_dir2_db_t	db)
 585{
 586	struct xfs_dir3_icfree_hdr hdr;
 587
 588	xfs_dir2_free_hdr_from_disk(dp->i_mount, &hdr, bp->b_addr);
 589
 590	ASSERT((hdr.firstdb % dp->i_mount->m_dir_geo->free_max_bests) == 0);
 591	ASSERT(hdr.firstdb <= db);
 592	ASSERT(db < hdr.firstdb + hdr.nvalid);
 593}
 594#else
 595#define xfs_dir2_free_hdr_check(dp, bp, db)
 596#endif	/* DEBUG */
 597
 598/*
 599 * Return the last hash value in the leaf.
 600 * Stale entries are ok.
 601 */
 602xfs_dahash_t					/* hash value */
 603xfs_dir2_leaf_lasthash(
 604	struct xfs_inode *dp,
 605	struct xfs_buf	*bp,			/* leaf buffer */
 606	int		*count)			/* count of entries in leaf */
 607{
 608	struct xfs_dir3_icleaf_hdr leafhdr;
 609
 610	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, bp->b_addr);
 611
 612	ASSERT(leafhdr.magic == XFS_DIR2_LEAFN_MAGIC ||
 613	       leafhdr.magic == XFS_DIR3_LEAFN_MAGIC ||
 614	       leafhdr.magic == XFS_DIR2_LEAF1_MAGIC ||
 615	       leafhdr.magic == XFS_DIR3_LEAF1_MAGIC);
 616
 617	if (count)
 618		*count = leafhdr.count;
 619	if (!leafhdr.count)
 620		return 0;
 621	return be32_to_cpu(leafhdr.ents[leafhdr.count - 1].hashval);
 622}
 623
 624/*
 625 * Look up a leaf entry for space to add a name in a node-format leaf block.
 626 * The extrablk in state is a freespace block.
 627 */
 628STATIC int
 629xfs_dir2_leafn_lookup_for_addname(
 630	struct xfs_buf		*bp,		/* leaf buffer */
 631	xfs_da_args_t		*args,		/* operation arguments */
 632	int			*indexp,	/* out: leaf entry index */
 633	xfs_da_state_t		*state)		/* state to fill in */
 634{
 635	struct xfs_buf		*curbp = NULL;	/* current data/free buffer */
 636	xfs_dir2_db_t		curdb = -1;	/* current data block number */
 637	xfs_dir2_db_t		curfdb = -1;	/* current free block number */
 638	xfs_inode_t		*dp;		/* incore directory inode */
 639	int			error;		/* error return value */
 640	int			fi;		/* free entry index */
 641	xfs_dir2_free_t		*free = NULL;	/* free block structure */
 642	int			index;		/* leaf entry index */
 643	xfs_dir2_leaf_t		*leaf;		/* leaf structure */
 644	int			length;		/* length of new data entry */
 645	xfs_dir2_leaf_entry_t	*lep;		/* leaf entry */
 646	xfs_mount_t		*mp;		/* filesystem mount point */
 647	xfs_dir2_db_t		newdb;		/* new data block number */
 648	xfs_dir2_db_t		newfdb;		/* new free block number */
 649	xfs_trans_t		*tp;		/* transaction pointer */
 650	struct xfs_dir3_icleaf_hdr leafhdr;
 651
 652	dp = args->dp;
 653	tp = args->trans;
 654	mp = dp->i_mount;
 655	leaf = bp->b_addr;
 656	xfs_dir2_leaf_hdr_from_disk(mp, &leafhdr, leaf);
 657
 658	xfs_dir3_leaf_check(dp, bp);
 659	ASSERT(leafhdr.count > 0);
 660
 661	/*
 662	 * Look up the hash value in the leaf entries.
 663	 */
 664	index = xfs_dir2_leaf_search_hash(args, bp);
 665	/*
 666	 * Do we have a buffer coming in?
 667	 */
 668	if (state->extravalid) {
 669		/* If so, it's a free block buffer, get the block number. */
 670		curbp = state->extrablk.bp;
 671		curfdb = state->extrablk.blkno;
 672		free = curbp->b_addr;
 673		ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
 674		       free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
 675	}
 676	length = xfs_dir2_data_entsize(mp, args->namelen);
 677	/*
 678	 * Loop over leaf entries with the right hash value.
 679	 */
 680	for (lep = &leafhdr.ents[index];
 681	     index < leafhdr.count && be32_to_cpu(lep->hashval) == args->hashval;
 682	     lep++, index++) {
 683		/*
 684		 * Skip stale leaf entries.
 685		 */
 686		if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR)
 687			continue;
 688		/*
 689		 * Pull the data block number from the entry.
 690		 */
 691		newdb = xfs_dir2_dataptr_to_db(args->geo,
 692					       be32_to_cpu(lep->address));
 693		/*
 694		 * For addname, we're looking for a place to put the new entry.
 695		 * We want to use a data block with an entry of equal
 696		 * hash value to ours if there is one with room.
 697		 *
 698		 * If this block isn't the data block we already have
 699		 * in hand, take a look at it.
 700		 */
 701		if (newdb != curdb) {
 702			struct xfs_dir3_icfree_hdr freehdr;
 703
 704			curdb = newdb;
 705			/*
 706			 * Convert the data block to the free block
 707			 * holding its freespace information.
 708			 */
 709			newfdb = xfs_dir2_db_to_fdb(args->geo, newdb);
 710			/*
 711			 * If it's not the one we have in hand, read it in.
 712			 */
 713			if (newfdb != curfdb) {
 714				/*
 715				 * If we had one before, drop it.
 716				 */
 717				if (curbp)
 718					xfs_trans_brelse(tp, curbp);
 719
 720				error = xfs_dir2_free_read(tp, dp,
 721						xfs_dir2_db_to_da(args->geo,
 722								  newfdb),
 723						&curbp);
 724				if (error)
 725					return error;
 726				free = curbp->b_addr;
 727
 728				xfs_dir2_free_hdr_check(dp, curbp, curdb);
 729			}
 730			/*
 731			 * Get the index for our entry.
 732			 */
 733			fi = xfs_dir2_db_to_fdindex(args->geo, curdb);
 734			/*
 735			 * If it has room, return it.
 736			 */
 737			xfs_dir2_free_hdr_from_disk(mp, &freehdr, free);
 738			if (XFS_IS_CORRUPT(mp,
 739					   freehdr.bests[fi] ==
 740					   cpu_to_be16(NULLDATAOFF))) {
 741				if (curfdb != newfdb)
 742					xfs_trans_brelse(tp, curbp);
 743				xfs_da_mark_sick(args);
 744				return -EFSCORRUPTED;
 745			}
 746			curfdb = newfdb;
 747			if (be16_to_cpu(freehdr.bests[fi]) >= length)
 748				goto out;
 749		}
 750	}
 751	/* Didn't find any space */
 752	fi = -1;
 753out:
 754	ASSERT(args->op_flags & XFS_DA_OP_OKNOENT);
 755	if (curbp) {
 756		/* Giving back a free block. */
 757		state->extravalid = 1;
 758		state->extrablk.bp = curbp;
 759		state->extrablk.index = fi;
 760		state->extrablk.blkno = curfdb;
 761
 762		/*
 763		 * Important: this magic number is not in the buffer - it's for
 764		 * buffer type information and therefore only the free/data type
 765		 * matters here, not whether CRCs are enabled or not.
 766		 */
 767		state->extrablk.magic = XFS_DIR2_FREE_MAGIC;
 768	} else {
 769		state->extravalid = 0;
 770	}
 771	/*
 772	 * Return the index, that will be the insertion point.
 773	 */
 774	*indexp = index;
 775	return -ENOENT;
 776}
 777
 778/*
 779 * Look up a leaf entry in a node-format leaf block.
 780 * The extrablk in state a data block.
 781 */
 782STATIC int
 783xfs_dir2_leafn_lookup_for_entry(
 784	struct xfs_buf		*bp,		/* leaf buffer */
 785	xfs_da_args_t		*args,		/* operation arguments */
 786	int			*indexp,	/* out: leaf entry index */
 787	xfs_da_state_t		*state)		/* state to fill in */
 788{
 789	struct xfs_buf		*curbp = NULL;	/* current data/free buffer */
 790	xfs_dir2_db_t		curdb = -1;	/* current data block number */
 791	xfs_dir2_data_entry_t	*dep;		/* data block entry */
 792	xfs_inode_t		*dp;		/* incore directory inode */
 793	int			error;		/* error return value */
 794	int			index;		/* leaf entry index */
 795	xfs_dir2_leaf_t		*leaf;		/* leaf structure */
 796	xfs_dir2_leaf_entry_t	*lep;		/* leaf entry */
 797	xfs_mount_t		*mp;		/* filesystem mount point */
 798	xfs_dir2_db_t		newdb;		/* new data block number */
 799	xfs_trans_t		*tp;		/* transaction pointer */
 800	enum xfs_dacmp		cmp;		/* comparison result */
 801	struct xfs_dir3_icleaf_hdr leafhdr;
 802
 803	dp = args->dp;
 804	tp = args->trans;
 805	mp = dp->i_mount;
 806	leaf = bp->b_addr;
 807	xfs_dir2_leaf_hdr_from_disk(mp, &leafhdr, leaf);
 808
 809	xfs_dir3_leaf_check(dp, bp);
 810	if (leafhdr.count <= 0) {
 811		xfs_buf_mark_corrupt(bp);
 812		xfs_da_mark_sick(args);
 813		return -EFSCORRUPTED;
 814	}
 815
 816	/*
 817	 * Look up the hash value in the leaf entries.
 818	 */
 819	index = xfs_dir2_leaf_search_hash(args, bp);
 820	/*
 821	 * Do we have a buffer coming in?
 822	 */
 823	if (state->extravalid) {
 824		curbp = state->extrablk.bp;
 825		curdb = state->extrablk.blkno;
 826	}
 827	/*
 828	 * Loop over leaf entries with the right hash value.
 829	 */
 830	for (lep = &leafhdr.ents[index];
 831	     index < leafhdr.count && be32_to_cpu(lep->hashval) == args->hashval;
 832	     lep++, index++) {
 833		/*
 834		 * Skip stale leaf entries.
 835		 */
 836		if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR)
 837			continue;
 838		/*
 839		 * Pull the data block number from the entry.
 840		 */
 841		newdb = xfs_dir2_dataptr_to_db(args->geo,
 842					       be32_to_cpu(lep->address));
 843		/*
 844		 * Not adding a new entry, so we really want to find
 845		 * the name given to us.
 846		 *
 847		 * If it's a different data block, go get it.
 848		 */
 849		if (newdb != curdb) {
 850			/*
 851			 * If we had a block before that we aren't saving
 852			 * for a CI name, drop it
 853			 */
 854			if (curbp && (args->cmpresult == XFS_CMP_DIFFERENT ||
 855						curdb != state->extrablk.blkno))
 856				xfs_trans_brelse(tp, curbp);
 857			/*
 858			 * If needing the block that is saved with a CI match,
 859			 * use it otherwise read in the new data block.
 860			 */
 861			if (args->cmpresult != XFS_CMP_DIFFERENT &&
 862					newdb == state->extrablk.blkno) {
 863				ASSERT(state->extravalid);
 864				curbp = state->extrablk.bp;
 865			} else {
 866				error = xfs_dir3_data_read(tp, dp,
 867						xfs_dir2_db_to_da(args->geo,
 868								  newdb),
 869						0, &curbp);
 870				if (error)
 871					return error;
 872			}
 873			xfs_dir3_data_check(dp, curbp);
 874			curdb = newdb;
 875		}
 876		/*
 877		 * Point to the data entry.
 878		 */
 879		dep = (xfs_dir2_data_entry_t *)((char *)curbp->b_addr +
 880			xfs_dir2_dataptr_to_off(args->geo,
 881						be32_to_cpu(lep->address)));
 882		/*
 883		 * Compare the entry and if it's an exact match, return
 884		 * EEXIST immediately. If it's the first case-insensitive
 885		 * match, store the block & inode number and continue looking.
 886		 */
 887		cmp = xfs_dir2_compname(args, dep->name, dep->namelen);
 888		if (cmp != XFS_CMP_DIFFERENT && cmp != args->cmpresult) {
 889			/* If there is a CI match block, drop it */
 890			if (args->cmpresult != XFS_CMP_DIFFERENT &&
 891						curdb != state->extrablk.blkno)
 892				xfs_trans_brelse(tp, state->extrablk.bp);
 893			args->cmpresult = cmp;
 894			args->inumber = be64_to_cpu(dep->inumber);
 895			args->filetype = xfs_dir2_data_get_ftype(mp, dep);
 896			*indexp = index;
 897			state->extravalid = 1;
 898			state->extrablk.bp = curbp;
 899			state->extrablk.blkno = curdb;
 900			state->extrablk.index = (int)((char *)dep -
 901							(char *)curbp->b_addr);
 902			state->extrablk.magic = XFS_DIR2_DATA_MAGIC;
 903			curbp->b_ops = &xfs_dir3_data_buf_ops;
 904			xfs_trans_buf_set_type(tp, curbp, XFS_BLFT_DIR_DATA_BUF);
 905			if (cmp == XFS_CMP_EXACT)
 906				return -EEXIST;
 907		}
 908	}
 909	ASSERT(index == leafhdr.count || (args->op_flags & XFS_DA_OP_OKNOENT));
 910	if (curbp) {
 911		if (args->cmpresult == XFS_CMP_DIFFERENT) {
 912			/* Giving back last used data block. */
 913			state->extravalid = 1;
 914			state->extrablk.bp = curbp;
 915			state->extrablk.index = -1;
 916			state->extrablk.blkno = curdb;
 917			state->extrablk.magic = XFS_DIR2_DATA_MAGIC;
 918			curbp->b_ops = &xfs_dir3_data_buf_ops;
 919			xfs_trans_buf_set_type(tp, curbp, XFS_BLFT_DIR_DATA_BUF);
 920		} else {
 921			/* If the curbp is not the CI match block, drop it */
 922			if (state->extrablk.bp != curbp)
 923				xfs_trans_brelse(tp, curbp);
 924		}
 925	} else {
 926		state->extravalid = 0;
 927	}
 928	*indexp = index;
 929	return -ENOENT;
 930}
 931
 932/*
 933 * Look up a leaf entry in a node-format leaf block.
 934 * If this is an addname then the extrablk in state is a freespace block,
 935 * otherwise it's a data block.
 936 */
 937int
 938xfs_dir2_leafn_lookup_int(
 939	struct xfs_buf		*bp,		/* leaf buffer */
 940	xfs_da_args_t		*args,		/* operation arguments */
 941	int			*indexp,	/* out: leaf entry index */
 942	xfs_da_state_t		*state)		/* state to fill in */
 943{
 944	if (args->op_flags & XFS_DA_OP_ADDNAME)
 945		return xfs_dir2_leafn_lookup_for_addname(bp, args, indexp,
 946							state);
 947	return xfs_dir2_leafn_lookup_for_entry(bp, args, indexp, state);
 948}
 949
 950/*
 951 * Move count leaf entries from source to destination leaf.
 952 * Log entries and headers.  Stale entries are preserved.
 953 */
 954static void
 955xfs_dir3_leafn_moveents(
 956	xfs_da_args_t			*args,	/* operation arguments */
 957	struct xfs_buf			*bp_s,	/* source */
 958	struct xfs_dir3_icleaf_hdr	*shdr,
 959	struct xfs_dir2_leaf_entry	*sents,
 960	int				start_s,/* source leaf index */
 961	struct xfs_buf			*bp_d,	/* destination */
 962	struct xfs_dir3_icleaf_hdr	*dhdr,
 963	struct xfs_dir2_leaf_entry	*dents,
 964	int				start_d,/* destination leaf index */
 965	int				count)	/* count of leaves to copy */
 966{
 967	int				stale;	/* count stale leaves copied */
 968
 969	trace_xfs_dir2_leafn_moveents(args, start_s, start_d, count);
 970
 971	/*
 972	 * Silently return if nothing to do.
 973	 */
 974	if (count == 0)
 975		return;
 976
 977	/*
 978	 * If the destination index is not the end of the current
 979	 * destination leaf entries, open up a hole in the destination
 980	 * to hold the new entries.
 981	 */
 982	if (start_d < dhdr->count) {
 983		memmove(&dents[start_d + count], &dents[start_d],
 984			(dhdr->count - start_d) * sizeof(xfs_dir2_leaf_entry_t));
 985		xfs_dir3_leaf_log_ents(args, dhdr, bp_d, start_d + count,
 986				       count + dhdr->count - 1);
 987	}
 988	/*
 989	 * If the source has stale leaves, count the ones in the copy range
 990	 * so we can update the header correctly.
 991	 */
 992	if (shdr->stale) {
 993		int	i;			/* temp leaf index */
 994
 995		for (i = start_s, stale = 0; i < start_s + count; i++) {
 996			if (sents[i].address ==
 997					cpu_to_be32(XFS_DIR2_NULL_DATAPTR))
 998				stale++;
 999		}
1000	} else
1001		stale = 0;
1002	/*
1003	 * Copy the leaf entries from source to destination.
1004	 */
1005	memcpy(&dents[start_d], &sents[start_s],
1006		count * sizeof(xfs_dir2_leaf_entry_t));
1007	xfs_dir3_leaf_log_ents(args, dhdr, bp_d, start_d, start_d + count - 1);
1008
1009	/*
1010	 * If there are source entries after the ones we copied,
1011	 * delete the ones we copied by sliding the next ones down.
1012	 */
1013	if (start_s + count < shdr->count) {
1014		memmove(&sents[start_s], &sents[start_s + count],
1015			count * sizeof(xfs_dir2_leaf_entry_t));
1016		xfs_dir3_leaf_log_ents(args, shdr, bp_s, start_s,
1017				       start_s + count - 1);
1018	}
1019
1020	/*
1021	 * Update the headers and log them.
1022	 */
1023	shdr->count -= count;
1024	shdr->stale -= stale;
1025	dhdr->count += count;
1026	dhdr->stale += stale;
1027}
1028
1029/*
1030 * Determine the sort order of two leaf blocks.
1031 * Returns 1 if both are valid and leaf2 should be before leaf1, else 0.
1032 */
1033int						/* sort order */
1034xfs_dir2_leafn_order(
1035	struct xfs_inode	*dp,
1036	struct xfs_buf		*leaf1_bp,		/* leaf1 buffer */
1037	struct xfs_buf		*leaf2_bp)		/* leaf2 buffer */
1038{
1039	struct xfs_dir2_leaf	*leaf1 = leaf1_bp->b_addr;
1040	struct xfs_dir2_leaf	*leaf2 = leaf2_bp->b_addr;
1041	struct xfs_dir2_leaf_entry *ents1;
1042	struct xfs_dir2_leaf_entry *ents2;
1043	struct xfs_dir3_icleaf_hdr hdr1;
1044	struct xfs_dir3_icleaf_hdr hdr2;
1045
1046	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr1, leaf1);
1047	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr2, leaf2);
1048	ents1 = hdr1.ents;
1049	ents2 = hdr2.ents;
1050
1051	if (hdr1.count > 0 && hdr2.count > 0 &&
1052	    (be32_to_cpu(ents2[0].hashval) < be32_to_cpu(ents1[0].hashval) ||
1053	     be32_to_cpu(ents2[hdr2.count - 1].hashval) <
1054				be32_to_cpu(ents1[hdr1.count - 1].hashval)))
1055		return 1;
1056	return 0;
1057}
1058
1059/*
1060 * Rebalance leaf entries between two leaf blocks.
1061 * This is actually only called when the second block is new,
1062 * though the code deals with the general case.
1063 * A new entry will be inserted in one of the blocks, and that
1064 * entry is taken into account when balancing.
1065 */
1066static void
1067xfs_dir2_leafn_rebalance(
1068	xfs_da_state_t		*state,		/* btree cursor */
1069	xfs_da_state_blk_t	*blk1,		/* first btree block */
1070	xfs_da_state_blk_t	*blk2)		/* second btree block */
1071{
1072	xfs_da_args_t		*args;		/* operation arguments */
1073	int			count;		/* count (& direction) leaves */
1074	int			isleft;		/* new goes in left leaf */
1075	xfs_dir2_leaf_t		*leaf1;		/* first leaf structure */
1076	xfs_dir2_leaf_t		*leaf2;		/* second leaf structure */
1077	int			mid;		/* midpoint leaf index */
1078#if defined(DEBUG) || defined(XFS_WARN)
1079	int			oldstale;	/* old count of stale leaves */
1080#endif
1081	int			oldsum;		/* old total leaf count */
1082	int			swap_blocks;	/* swapped leaf blocks */
1083	struct xfs_dir2_leaf_entry *ents1;
1084	struct xfs_dir2_leaf_entry *ents2;
1085	struct xfs_dir3_icleaf_hdr hdr1;
1086	struct xfs_dir3_icleaf_hdr hdr2;
1087	struct xfs_inode	*dp = state->args->dp;
1088
1089	args = state->args;
1090	/*
1091	 * If the block order is wrong, swap the arguments.
1092	 */
1093	swap_blocks = xfs_dir2_leafn_order(dp, blk1->bp, blk2->bp);
1094	if (swap_blocks)
1095		swap(blk1, blk2);
1096
1097	leaf1 = blk1->bp->b_addr;
1098	leaf2 = blk2->bp->b_addr;
1099	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr1, leaf1);
1100	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr2, leaf2);
1101	ents1 = hdr1.ents;
1102	ents2 = hdr2.ents;
1103
1104	oldsum = hdr1.count + hdr2.count;
1105#if defined(DEBUG) || defined(XFS_WARN)
1106	oldstale = hdr1.stale + hdr2.stale;
1107#endif
1108	mid = oldsum >> 1;
1109
1110	/*
1111	 * If the old leaf count was odd then the new one will be even,
1112	 * so we need to divide the new count evenly.
1113	 */
1114	if (oldsum & 1) {
1115		xfs_dahash_t	midhash;	/* middle entry hash value */
1116
1117		if (mid >= hdr1.count)
1118			midhash = be32_to_cpu(ents2[mid - hdr1.count].hashval);
1119		else
1120			midhash = be32_to_cpu(ents1[mid].hashval);
1121		isleft = args->hashval <= midhash;
1122	}
1123	/*
1124	 * If the old count is even then the new count is odd, so there's
1125	 * no preferred side for the new entry.
1126	 * Pick the left one.
1127	 */
1128	else
1129		isleft = 1;
1130	/*
1131	 * Calculate moved entry count.  Positive means left-to-right,
1132	 * negative means right-to-left.  Then move the entries.
1133	 */
1134	count = hdr1.count - mid + (isleft == 0);
1135	if (count > 0)
1136		xfs_dir3_leafn_moveents(args, blk1->bp, &hdr1, ents1,
1137					hdr1.count - count, blk2->bp,
1138					&hdr2, ents2, 0, count);
1139	else if (count < 0)
1140		xfs_dir3_leafn_moveents(args, blk2->bp, &hdr2, ents2, 0,
1141					blk1->bp, &hdr1, ents1,
1142					hdr1.count, count);
1143
1144	ASSERT(hdr1.count + hdr2.count == oldsum);
1145	ASSERT(hdr1.stale + hdr2.stale == oldstale);
1146
1147	/* log the changes made when moving the entries */
1148	xfs_dir2_leaf_hdr_to_disk(dp->i_mount, leaf1, &hdr1);
1149	xfs_dir2_leaf_hdr_to_disk(dp->i_mount, leaf2, &hdr2);
1150	xfs_dir3_leaf_log_header(args, blk1->bp);
1151	xfs_dir3_leaf_log_header(args, blk2->bp);
1152
1153	xfs_dir3_leaf_check(dp, blk1->bp);
1154	xfs_dir3_leaf_check(dp, blk2->bp);
1155
1156	/*
1157	 * Mark whether we're inserting into the old or new leaf.
1158	 */
1159	if (hdr1.count < hdr2.count)
1160		state->inleaf = swap_blocks;
1161	else if (hdr1.count > hdr2.count)
1162		state->inleaf = !swap_blocks;
1163	else
1164		state->inleaf = swap_blocks ^ (blk1->index <= hdr1.count);
1165	/*
1166	 * Adjust the expected index for insertion.
1167	 */
1168	if (!state->inleaf)
1169		blk2->index = blk1->index - hdr1.count;
1170
1171	/*
1172	 * Finally sanity check just to make sure we are not returning a
1173	 * negative index
1174	 */
1175	if (blk2->index < 0) {
1176		state->inleaf = 1;
1177		blk2->index = 0;
1178		xfs_alert(dp->i_mount,
1179	"%s: picked the wrong leaf? reverting original leaf: blk1->index %d",
1180			__func__, blk1->index);
1181	}
1182}
1183
1184static int
1185xfs_dir3_data_block_free(
1186	xfs_da_args_t		*args,
1187	struct xfs_dir2_data_hdr *hdr,
1188	struct xfs_dir2_free	*free,
1189	xfs_dir2_db_t		fdb,
1190	int			findex,
1191	struct xfs_buf		*fbp,
1192	int			longest)
1193{
1194	int			logfree = 0;
1195	struct xfs_dir3_icfree_hdr freehdr;
1196	struct xfs_inode	*dp = args->dp;
1197
1198	xfs_dir2_free_hdr_from_disk(dp->i_mount, &freehdr, free);
1199	if (hdr) {
1200		/*
1201		 * Data block is not empty, just set the free entry to the new
1202		 * value.
1203		 */
1204		freehdr.bests[findex] = cpu_to_be16(longest);
1205		xfs_dir2_free_log_bests(args, &freehdr, fbp, findex, findex);
1206		return 0;
1207	}
1208
1209	/* One less used entry in the free table. */
1210	freehdr.nused--;
1211
1212	/*
1213	 * If this was the last entry in the table, we can trim the table size
1214	 * back.  There might be other entries at the end referring to
1215	 * non-existent data blocks, get those too.
1216	 */
1217	if (findex == freehdr.nvalid - 1) {
1218		int	i;		/* free entry index */
1219
1220		for (i = findex - 1; i >= 0; i--) {
1221			if (freehdr.bests[i] != cpu_to_be16(NULLDATAOFF))
1222				break;
1223		}
1224		freehdr.nvalid = i + 1;
1225		logfree = 0;
1226	} else {
1227		/* Not the last entry, just punch it out.  */
1228		freehdr.bests[findex] = cpu_to_be16(NULLDATAOFF);
1229		logfree = 1;
1230	}
1231
1232	xfs_dir2_free_hdr_to_disk(dp->i_mount, free, &freehdr);
1233	xfs_dir2_free_log_header(args, fbp);
1234
1235	/*
1236	 * If there are no useful entries left in the block, get rid of the
1237	 * block if we can.
1238	 */
1239	if (!freehdr.nused) {
1240		int error;
1241
1242		error = xfs_dir2_shrink_inode(args, fdb, fbp);
1243		if (error == 0) {
1244			fbp = NULL;
1245			logfree = 0;
1246		} else if (error != -ENOSPC || args->total != 0)
1247			return error;
1248		/*
1249		 * It's possible to get ENOSPC if there is no
1250		 * space reservation.  In this case some one
1251		 * else will eventually get rid of this block.
1252		 */
1253	}
1254
1255	/* Log the free entry that changed, unless we got rid of it.  */
1256	if (logfree)
1257		xfs_dir2_free_log_bests(args, &freehdr, fbp, findex, findex);
1258	return 0;
1259}
1260
1261/*
1262 * Remove an entry from a node directory.
1263 * This removes the leaf entry and the data entry,
1264 * and updates the free block if necessary.
1265 */
1266static int					/* error */
1267xfs_dir2_leafn_remove(
1268	xfs_da_args_t		*args,		/* operation arguments */
1269	struct xfs_buf		*bp,		/* leaf buffer */
1270	int			index,		/* leaf entry index */
1271	xfs_da_state_blk_t	*dblk,		/* data block */
1272	int			*rval)		/* resulting block needs join */
1273{
1274	struct xfs_da_geometry	*geo = args->geo;
1275	xfs_dir2_data_hdr_t	*hdr;		/* data block header */
1276	xfs_dir2_db_t		db;		/* data block number */
1277	struct xfs_buf		*dbp;		/* data block buffer */
1278	xfs_dir2_data_entry_t	*dep;		/* data block entry */
1279	xfs_inode_t		*dp;		/* incore directory inode */
1280	xfs_dir2_leaf_t		*leaf;		/* leaf structure */
1281	xfs_dir2_leaf_entry_t	*lep;		/* leaf entry */
1282	int			longest;	/* longest data free entry */
1283	int			off;		/* data block entry offset */
1284	int			needlog;	/* need to log data header */
1285	int			needscan;	/* need to rescan data frees */
1286	xfs_trans_t		*tp;		/* transaction pointer */
1287	struct xfs_dir2_data_free *bf;		/* bestfree table */
1288	struct xfs_dir3_icleaf_hdr leafhdr;
1289
1290	trace_xfs_dir2_leafn_remove(args, index);
1291
1292	dp = args->dp;
1293	tp = args->trans;
1294	leaf = bp->b_addr;
1295	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
1296
1297	/*
1298	 * Point to the entry we're removing.
1299	 */
1300	lep = &leafhdr.ents[index];
1301
1302	/*
1303	 * Extract the data block and offset from the entry.
1304	 */
1305	db = xfs_dir2_dataptr_to_db(geo, be32_to_cpu(lep->address));
1306	ASSERT(dblk->blkno == db);
1307	off = xfs_dir2_dataptr_to_off(geo, be32_to_cpu(lep->address));
1308	ASSERT(dblk->index == off);
1309
1310	/*
1311	 * Kill the leaf entry by marking it stale.
1312	 * Log the leaf block changes.
1313	 */
1314	leafhdr.stale++;
1315	xfs_dir2_leaf_hdr_to_disk(dp->i_mount, leaf, &leafhdr);
1316	xfs_dir3_leaf_log_header(args, bp);
1317
1318	lep->address = cpu_to_be32(XFS_DIR2_NULL_DATAPTR);
1319	xfs_dir3_leaf_log_ents(args, &leafhdr, bp, index, index);
1320
1321	/*
1322	 * Make the data entry free.  Keep track of the longest freespace
1323	 * in the data block in case it changes.
1324	 */
1325	dbp = dblk->bp;
1326	hdr = dbp->b_addr;
1327	dep = (xfs_dir2_data_entry_t *)((char *)hdr + off);
1328	bf = xfs_dir2_data_bestfree_p(dp->i_mount, hdr);
1329	longest = be16_to_cpu(bf[0].length);
1330	needlog = needscan = 0;
1331	xfs_dir2_data_make_free(args, dbp, off,
1332		xfs_dir2_data_entsize(dp->i_mount, dep->namelen), &needlog,
1333		&needscan);
1334	/*
1335	 * Rescan the data block freespaces for bestfree.
1336	 * Log the data block header if needed.
1337	 */
1338	if (needscan)
1339		xfs_dir2_data_freescan(dp->i_mount, hdr, &needlog);
1340	if (needlog)
1341		xfs_dir2_data_log_header(args, dbp);
1342	xfs_dir3_data_check(dp, dbp);
1343	/*
1344	 * If the longest data block freespace changes, need to update
1345	 * the corresponding freeblock entry.
1346	 */
1347	if (longest < be16_to_cpu(bf[0].length)) {
1348		int		error;		/* error return value */
1349		struct xfs_buf	*fbp;		/* freeblock buffer */
1350		xfs_dir2_db_t	fdb;		/* freeblock block number */
1351		int		findex;		/* index in freeblock entries */
1352		xfs_dir2_free_t	*free;		/* freeblock structure */
1353
1354		/*
1355		 * Convert the data block number to a free block,
1356		 * read in the free block.
1357		 */
1358		fdb = xfs_dir2_db_to_fdb(geo, db);
1359		error = xfs_dir2_free_read(tp, dp, xfs_dir2_db_to_da(geo, fdb),
1360					   &fbp);
1361		if (error)
1362			return error;
1363		free = fbp->b_addr;
1364#ifdef DEBUG
1365	{
1366		struct xfs_dir3_icfree_hdr freehdr;
1367
1368		xfs_dir2_free_hdr_from_disk(dp->i_mount, &freehdr, free);
1369		ASSERT(freehdr.firstdb == geo->free_max_bests *
1370			(fdb - xfs_dir2_byte_to_db(geo, XFS_DIR2_FREE_OFFSET)));
1371	}
1372#endif
1373		/*
1374		 * Calculate which entry we need to fix.
1375		 */
1376		findex = xfs_dir2_db_to_fdindex(geo, db);
1377		longest = be16_to_cpu(bf[0].length);
1378		/*
1379		 * If the data block is now empty we can get rid of it
1380		 * (usually).
1381		 */
1382		if (longest == geo->blksize - geo->data_entry_offset) {
1383			/*
1384			 * Try to punch out the data block.
1385			 */
1386			error = xfs_dir2_shrink_inode(args, db, dbp);
1387			if (error == 0) {
1388				dblk->bp = NULL;
1389				hdr = NULL;
1390			}
1391			/*
1392			 * We can get ENOSPC if there's no space reservation.
1393			 * In this case just drop the buffer and some one else
1394			 * will eventually get rid of the empty block.
1395			 */
1396			else if (!(error == -ENOSPC && args->total == 0))
1397				return error;
1398		}
1399		/*
1400		 * If we got rid of the data block, we can eliminate that entry
1401		 * in the free block.
1402		 */
1403		error = xfs_dir3_data_block_free(args, hdr, free,
1404						 fdb, findex, fbp, longest);
1405		if (error)
1406			return error;
1407	}
1408
1409	xfs_dir3_leaf_check(dp, bp);
1410	/*
1411	 * Return indication of whether this leaf block is empty enough
1412	 * to justify trying to join it with a neighbor.
1413	 */
1414	*rval = (geo->leaf_hdr_size +
1415		 (uint)sizeof(leafhdr.ents) * (leafhdr.count - leafhdr.stale)) <
1416		geo->magicpct;
1417	return 0;
1418}
1419
1420/*
1421 * Split the leaf entries in the old block into old and new blocks.
1422 */
1423int						/* error */
1424xfs_dir2_leafn_split(
1425	xfs_da_state_t		*state,		/* btree cursor */
1426	xfs_da_state_blk_t	*oldblk,	/* original block */
1427	xfs_da_state_blk_t	*newblk)	/* newly created block */
1428{
1429	xfs_da_args_t		*args;		/* operation arguments */
1430	xfs_dablk_t		blkno;		/* new leaf block number */
1431	int			error;		/* error return value */
1432	struct xfs_inode	*dp;
1433
1434	/*
1435	 * Allocate space for a new leaf node.
1436	 */
1437	args = state->args;
1438	dp = args->dp;
1439	ASSERT(oldblk->magic == XFS_DIR2_LEAFN_MAGIC);
1440	error = xfs_da_grow_inode(args, &blkno);
1441	if (error) {
1442		return error;
1443	}
1444	/*
1445	 * Initialize the new leaf block.
1446	 */
1447	error = xfs_dir3_leaf_get_buf(args, xfs_dir2_da_to_db(args->geo, blkno),
1448				      &newblk->bp, XFS_DIR2_LEAFN_MAGIC);
1449	if (error)
1450		return error;
1451
1452	newblk->blkno = blkno;
1453	newblk->magic = XFS_DIR2_LEAFN_MAGIC;
1454	/*
1455	 * Rebalance the entries across the two leaves, link the new
1456	 * block into the leaves.
1457	 */
1458	xfs_dir2_leafn_rebalance(state, oldblk, newblk);
1459	error = xfs_da3_blk_link(state, oldblk, newblk);
1460	if (error) {
1461		return error;
1462	}
1463	/*
1464	 * Insert the new entry in the correct block.
1465	 */
1466	if (state->inleaf)
1467		error = xfs_dir2_leafn_add(oldblk->bp, args, oldblk->index);
1468	else
1469		error = xfs_dir2_leafn_add(newblk->bp, args, newblk->index);
1470	/*
1471	 * Update last hashval in each block since we added the name.
1472	 */
1473	oldblk->hashval = xfs_dir2_leaf_lasthash(dp, oldblk->bp, NULL);
1474	newblk->hashval = xfs_dir2_leaf_lasthash(dp, newblk->bp, NULL);
1475	xfs_dir3_leaf_check(dp, oldblk->bp);
1476	xfs_dir3_leaf_check(dp, newblk->bp);
1477	return error;
1478}
1479
1480/*
1481 * Check a leaf block and its neighbors to see if the block should be
1482 * collapsed into one or the other neighbor.  Always keep the block
1483 * with the smaller block number.
1484 * If the current block is over 50% full, don't try to join it, return 0.
1485 * If the block is empty, fill in the state structure and return 2.
1486 * If it can be collapsed, fill in the state structure and return 1.
1487 * If nothing can be done, return 0.
1488 */
1489int						/* error */
1490xfs_dir2_leafn_toosmall(
1491	xfs_da_state_t		*state,		/* btree cursor */
1492	int			*action)	/* resulting action to take */
1493{
1494	xfs_da_state_blk_t	*blk;		/* leaf block */
1495	xfs_dablk_t		blkno;		/* leaf block number */
1496	struct xfs_buf		*bp;		/* leaf buffer */
1497	int			bytes;		/* bytes in use */
1498	int			count;		/* leaf live entry count */
1499	int			error;		/* error return value */
1500	int			forward;	/* sibling block direction */
1501	int			i;		/* sibling counter */
1502	xfs_dir2_leaf_t		*leaf;		/* leaf structure */
1503	int			rval;		/* result from path_shift */
1504	struct xfs_dir3_icleaf_hdr leafhdr;
1505	struct xfs_dir2_leaf_entry *ents;
1506	struct xfs_inode	*dp = state->args->dp;
1507
1508	/*
1509	 * Check for the degenerate case of the block being over 50% full.
1510	 * If so, it's not worth even looking to see if we might be able
1511	 * to coalesce with a sibling.
1512	 */
1513	blk = &state->path.blk[state->path.active - 1];
1514	leaf = blk->bp->b_addr;
1515	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
1516	ents = leafhdr.ents;
1517	xfs_dir3_leaf_check(dp, blk->bp);
1518
1519	count = leafhdr.count - leafhdr.stale;
1520	bytes = state->args->geo->leaf_hdr_size + count * sizeof(ents[0]);
1521	if (bytes > (state->args->geo->blksize >> 1)) {
1522		/*
1523		 * Blk over 50%, don't try to join.
1524		 */
1525		*action = 0;
1526		return 0;
1527	}
1528	/*
1529	 * Check for the degenerate case of the block being empty.
1530	 * If the block is empty, we'll simply delete it, no need to
1531	 * coalesce it with a sibling block.  We choose (arbitrarily)
1532	 * to merge with the forward block unless it is NULL.
1533	 */
1534	if (count == 0) {
1535		/*
1536		 * Make altpath point to the block we want to keep and
1537		 * path point to the block we want to drop (this one).
1538		 */
1539		forward = (leafhdr.forw != 0);
1540		memcpy(&state->altpath, &state->path, sizeof(state->path));
1541		error = xfs_da3_path_shift(state, &state->altpath, forward, 0,
1542			&rval);
1543		if (error)
1544			return error;
1545		*action = rval ? 2 : 0;
1546		return 0;
1547	}
1548	/*
1549	 * Examine each sibling block to see if we can coalesce with
1550	 * at least 25% free space to spare.  We need to figure out
1551	 * whether to merge with the forward or the backward block.
1552	 * We prefer coalescing with the lower numbered sibling so as
1553	 * to shrink a directory over time.
1554	 */
1555	forward = leafhdr.forw < leafhdr.back;
1556	for (i = 0, bp = NULL; i < 2; forward = !forward, i++) {
1557		struct xfs_dir3_icleaf_hdr hdr2;
1558
1559		blkno = forward ? leafhdr.forw : leafhdr.back;
1560		if (blkno == 0)
1561			continue;
1562		/*
1563		 * Read the sibling leaf block.
1564		 */
1565		error = xfs_dir3_leafn_read(state->args->trans, dp, blkno, &bp);
1566		if (error)
1567			return error;
1568
1569		/*
1570		 * Count bytes in the two blocks combined.
1571		 */
1572		count = leafhdr.count - leafhdr.stale;
1573		bytes = state->args->geo->blksize -
1574			(state->args->geo->blksize >> 2);
1575
1576		leaf = bp->b_addr;
1577		xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr2, leaf);
1578		ents = hdr2.ents;
1579		count += hdr2.count - hdr2.stale;
1580		bytes -= count * sizeof(ents[0]);
1581
1582		/*
1583		 * Fits with at least 25% to spare.
1584		 */
1585		if (bytes >= 0)
1586			break;
1587		xfs_trans_brelse(state->args->trans, bp);
1588	}
1589	/*
1590	 * Didn't like either block, give up.
1591	 */
1592	if (i >= 2) {
1593		*action = 0;
1594		return 0;
1595	}
1596
1597	/*
1598	 * Make altpath point to the block we want to keep (the lower
1599	 * numbered block) and path point to the block we want to drop.
1600	 */
1601	memcpy(&state->altpath, &state->path, sizeof(state->path));
1602	if (blkno < blk->blkno)
1603		error = xfs_da3_path_shift(state, &state->altpath, forward, 0,
1604			&rval);
1605	else
1606		error = xfs_da3_path_shift(state, &state->path, forward, 0,
1607			&rval);
1608	if (error) {
1609		return error;
1610	}
1611	*action = rval ? 0 : 1;
1612	return 0;
1613}
1614
1615/*
1616 * Move all the leaf entries from drop_blk to save_blk.
1617 * This is done as part of a join operation.
1618 */
1619void
1620xfs_dir2_leafn_unbalance(
1621	xfs_da_state_t		*state,		/* cursor */
1622	xfs_da_state_blk_t	*drop_blk,	/* dead block */
1623	xfs_da_state_blk_t	*save_blk)	/* surviving block */
1624{
1625	xfs_da_args_t		*args;		/* operation arguments */
1626	xfs_dir2_leaf_t		*drop_leaf;	/* dead leaf structure */
1627	xfs_dir2_leaf_t		*save_leaf;	/* surviving leaf structure */
1628	struct xfs_dir3_icleaf_hdr savehdr;
1629	struct xfs_dir3_icleaf_hdr drophdr;
1630	struct xfs_dir2_leaf_entry *sents;
1631	struct xfs_dir2_leaf_entry *dents;
1632	struct xfs_inode	*dp = state->args->dp;
1633
1634	args = state->args;
1635	ASSERT(drop_blk->magic == XFS_DIR2_LEAFN_MAGIC);
1636	ASSERT(save_blk->magic == XFS_DIR2_LEAFN_MAGIC);
1637	drop_leaf = drop_blk->bp->b_addr;
1638	save_leaf = save_blk->bp->b_addr;
1639
1640	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &savehdr, save_leaf);
1641	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &drophdr, drop_leaf);
1642	sents = savehdr.ents;
1643	dents = drophdr.ents;
1644
1645	/*
1646	 * If there are any stale leaf entries, take this opportunity
1647	 * to purge them.
1648	 */
1649	if (drophdr.stale)
1650		xfs_dir3_leaf_compact(args, &drophdr, drop_blk->bp);
1651	if (savehdr.stale)
1652		xfs_dir3_leaf_compact(args, &savehdr, save_blk->bp);
1653
1654	/*
1655	 * Move the entries from drop to the appropriate end of save.
1656	 */
1657	drop_blk->hashval = be32_to_cpu(dents[drophdr.count - 1].hashval);
1658	if (xfs_dir2_leafn_order(dp, save_blk->bp, drop_blk->bp))
1659		xfs_dir3_leafn_moveents(args, drop_blk->bp, &drophdr, dents, 0,
1660					save_blk->bp, &savehdr, sents, 0,
1661					drophdr.count);
1662	else
1663		xfs_dir3_leafn_moveents(args, drop_blk->bp, &drophdr, dents, 0,
1664					save_blk->bp, &savehdr, sents,
1665					savehdr.count, drophdr.count);
1666	save_blk->hashval = be32_to_cpu(sents[savehdr.count - 1].hashval);
1667
1668	/* log the changes made when moving the entries */
1669	xfs_dir2_leaf_hdr_to_disk(dp->i_mount, save_leaf, &savehdr);
1670	xfs_dir2_leaf_hdr_to_disk(dp->i_mount, drop_leaf, &drophdr);
1671	xfs_dir3_leaf_log_header(args, save_blk->bp);
1672	xfs_dir3_leaf_log_header(args, drop_blk->bp);
1673
1674	xfs_dir3_leaf_check(dp, save_blk->bp);
1675	xfs_dir3_leaf_check(dp, drop_blk->bp);
1676}
1677
1678/*
1679 * Add a new data block to the directory at the free space index that the caller
1680 * has specified.
1681 */
1682static int
1683xfs_dir2_node_add_datablk(
1684	struct xfs_da_args	*args,
1685	struct xfs_da_state_blk	*fblk,
1686	xfs_dir2_db_t		*dbno,
1687	struct xfs_buf		**dbpp,
1688	struct xfs_buf		**fbpp,
1689	struct xfs_dir3_icfree_hdr *hdr,
1690	int			*findex)
1691{
1692	struct xfs_inode	*dp = args->dp;
1693	struct xfs_trans	*tp = args->trans;
1694	struct xfs_mount	*mp = dp->i_mount;
1695	struct xfs_dir2_data_free *bf;
1696	xfs_dir2_db_t		fbno;
1697	struct xfs_buf		*fbp;
1698	struct xfs_buf		*dbp;
1699	int			error;
1700
1701	/* Not allowed to allocate, return failure. */
1702	if (args->total == 0)
1703		return -ENOSPC;
1704
1705	/* Allocate and initialize the new data block.  */
1706	error = xfs_dir2_grow_inode(args, XFS_DIR2_DATA_SPACE, dbno);
1707	if (error)
1708		return error;
1709	error = xfs_dir3_data_init(args, *dbno, &dbp);
1710	if (error)
1711		return error;
1712
1713	/*
1714	 * Get the freespace block corresponding to the data block
1715	 * that was just allocated.
1716	 */
1717	fbno = xfs_dir2_db_to_fdb(args->geo, *dbno);
1718	error = xfs_dir2_free_try_read(tp, dp,
1719			       xfs_dir2_db_to_da(args->geo, fbno), &fbp);
1720	if (error)
1721		return error;
1722
1723	/*
1724	 * If there wasn't a freespace block, the read will
1725	 * return a NULL fbp.  Allocate and initialize a new one.
1726	 */
1727	if (!fbp) {
1728		error = xfs_dir2_grow_inode(args, XFS_DIR2_FREE_SPACE, &fbno);
1729		if (error)
1730			return error;
1731
1732		if (XFS_IS_CORRUPT(mp,
1733				   xfs_dir2_db_to_fdb(args->geo, *dbno) !=
1734				   fbno)) {
1735			xfs_alert(mp,
1736"%s: dir ino %llu needed freesp block %lld for data block %lld, got %lld",
1737				__func__, (unsigned long long)dp->i_ino,
1738				(long long)xfs_dir2_db_to_fdb(args->geo, *dbno),
1739				(long long)*dbno, (long long)fbno);
1740			if (fblk) {
1741				xfs_alert(mp,
1742			" fblk "PTR_FMT" blkno %llu index %d magic 0x%x",
1743					fblk, (unsigned long long)fblk->blkno,
1744					fblk->index, fblk->magic);
1745			} else {
1746				xfs_alert(mp, " ... fblk is NULL");
1747			}
1748			xfs_da_mark_sick(args);
1749			return -EFSCORRUPTED;
1750		}
1751
1752		/* Get a buffer for the new block. */
1753		error = xfs_dir3_free_get_buf(args, fbno, &fbp);
1754		if (error)
1755			return error;
1756		xfs_dir2_free_hdr_from_disk(mp, hdr, fbp->b_addr);
1757
1758		/* Remember the first slot as our empty slot. */
1759		hdr->firstdb = (fbno - xfs_dir2_byte_to_db(args->geo,
1760							XFS_DIR2_FREE_OFFSET)) *
1761				args->geo->free_max_bests;
1762	} else {
1763		xfs_dir2_free_hdr_from_disk(mp, hdr, fbp->b_addr);
1764	}
1765
1766	/* Set the freespace block index from the data block number. */
1767	*findex = xfs_dir2_db_to_fdindex(args->geo, *dbno);
1768
1769	/* Extend the freespace table if the new data block is off the end. */
1770	if (*findex >= hdr->nvalid) {
1771		ASSERT(*findex < args->geo->free_max_bests);
1772		hdr->nvalid = *findex + 1;
1773		hdr->bests[*findex] = cpu_to_be16(NULLDATAOFF);
1774	}
1775
1776	/*
1777	 * If this entry was for an empty data block (this should always be
1778	 * true) then update the header.
1779	 */
1780	if (hdr->bests[*findex] == cpu_to_be16(NULLDATAOFF)) {
1781		hdr->nused++;
1782		xfs_dir2_free_hdr_to_disk(mp, fbp->b_addr, hdr);
1783		xfs_dir2_free_log_header(args, fbp);
1784	}
1785
1786	/* Update the freespace value for the new block in the table. */
1787	bf = xfs_dir2_data_bestfree_p(mp, dbp->b_addr);
1788	hdr->bests[*findex] = bf[0].length;
1789
1790	*dbpp = dbp;
1791	*fbpp = fbp;
1792	return 0;
1793}
1794
1795static int
1796xfs_dir2_node_find_freeblk(
1797	struct xfs_da_args	*args,
1798	struct xfs_da_state_blk	*fblk,
1799	xfs_dir2_db_t		*dbnop,
1800	struct xfs_buf		**fbpp,
1801	struct xfs_dir3_icfree_hdr *hdr,
1802	int			*findexp,
1803	int			length)
1804{
1805	struct xfs_inode	*dp = args->dp;
1806	struct xfs_trans	*tp = args->trans;
1807	struct xfs_buf		*fbp = NULL;
1808	xfs_dir2_db_t		firstfbno;
1809	xfs_dir2_db_t		lastfbno;
1810	xfs_dir2_db_t		ifbno = -1;
1811	xfs_dir2_db_t		dbno = -1;
1812	xfs_dir2_db_t		fbno;
1813	xfs_fileoff_t		fo;
1814	int			findex = 0;
1815	int			error;
1816
1817	/*
1818	 * If we came in with a freespace block that means that lookup
1819	 * found an entry with our hash value.  This is the freespace
1820	 * block for that data entry.
1821	 */
1822	if (fblk) {
1823		fbp = fblk->bp;
1824		findex = fblk->index;
1825		xfs_dir2_free_hdr_from_disk(dp->i_mount, hdr, fbp->b_addr);
1826		if (findex >= 0) {
1827			/* caller already found the freespace for us. */
1828			ASSERT(findex < hdr->nvalid);
1829			ASSERT(be16_to_cpu(hdr->bests[findex]) != NULLDATAOFF);
1830			ASSERT(be16_to_cpu(hdr->bests[findex]) >= length);
1831			dbno = hdr->firstdb + findex;
1832			goto found_block;
1833		}
1834
1835		/*
1836		 * The data block looked at didn't have enough room.
1837		 * We'll start at the beginning of the freespace entries.
1838		 */
1839		ifbno = fblk->blkno;
1840		xfs_trans_brelse(tp, fbp);
1841		fbp = NULL;
1842		fblk->bp = NULL;
1843	}
1844
1845	/*
1846	 * If we don't have a data block yet, we're going to scan the freespace
1847	 * data for a data block with enough free space in it.
1848	 */
1849	error = xfs_bmap_last_offset(dp, &fo, XFS_DATA_FORK);
1850	if (error)
1851		return error;
1852	lastfbno = xfs_dir2_da_to_db(args->geo, (xfs_dablk_t)fo);
1853	firstfbno = xfs_dir2_byte_to_db(args->geo, XFS_DIR2_FREE_OFFSET);
1854
1855	for (fbno = lastfbno - 1; fbno >= firstfbno; fbno--) {
1856		/* If it's ifbno we already looked at it. */
1857		if (fbno == ifbno)
1858			continue;
1859
1860		/*
1861		 * Read the block.  There can be holes in the freespace blocks,
1862		 * so this might not succeed.  This should be really rare, so
1863		 * there's no reason to avoid it.
1864		 */
1865		error = xfs_dir2_free_try_read(tp, dp,
1866				xfs_dir2_db_to_da(args->geo, fbno),
1867				&fbp);
1868		if (error)
1869			return error;
1870		if (!fbp)
1871			continue;
1872
1873		xfs_dir2_free_hdr_from_disk(dp->i_mount, hdr, fbp->b_addr);
1874
1875		/* Scan the free entry array for a large enough free space. */
1876		for (findex = hdr->nvalid - 1; findex >= 0; findex--) {
1877			if (be16_to_cpu(hdr->bests[findex]) != NULLDATAOFF &&
1878			    be16_to_cpu(hdr->bests[findex]) >= length) {
1879				dbno = hdr->firstdb + findex;
1880				goto found_block;
1881			}
1882		}
1883
1884		/* Didn't find free space, go on to next free block */
1885		xfs_trans_brelse(tp, fbp);
1886	}
1887
1888found_block:
1889	*dbnop = dbno;
1890	*fbpp = fbp;
1891	*findexp = findex;
1892	return 0;
1893}
1894
1895/*
1896 * Add the data entry for a node-format directory name addition.
1897 * The leaf entry is added in xfs_dir2_leafn_add.
1898 * We may enter with a freespace block that the lookup found.
1899 */
1900static int
1901xfs_dir2_node_addname_int(
1902	struct xfs_da_args	*args,		/* operation arguments */
1903	struct xfs_da_state_blk	*fblk)		/* optional freespace block */
1904{
1905	struct xfs_dir2_data_unused *dup;	/* data unused entry pointer */
1906	struct xfs_dir2_data_entry *dep;	/* data entry pointer */
1907	struct xfs_dir2_data_hdr *hdr;		/* data block header */
1908	struct xfs_dir2_data_free *bf;
1909	struct xfs_trans	*tp = args->trans;
1910	struct xfs_inode	*dp = args->dp;
1911	struct xfs_dir3_icfree_hdr freehdr;
1912	struct xfs_buf		*dbp;		/* data block buffer */
1913	struct xfs_buf		*fbp;		/* freespace buffer */
1914	xfs_dir2_data_aoff_t	aoff;
1915	xfs_dir2_db_t		dbno;		/* data block number */
1916	int			error;		/* error return value */
1917	int			findex;		/* freespace entry index */
1918	int			length;		/* length of the new entry */
1919	int			logfree = 0;	/* need to log free entry */
1920	int			needlog = 0;	/* need to log data header */
1921	int			needscan = 0;	/* need to rescan data frees */
1922	__be16			*tagp;		/* data entry tag pointer */
1923
1924	length = xfs_dir2_data_entsize(dp->i_mount, args->namelen);
1925	error = xfs_dir2_node_find_freeblk(args, fblk, &dbno, &fbp, &freehdr,
1926					   &findex, length);
1927	if (error)
1928		return error;
1929
1930	/*
1931	 * Now we know if we must allocate blocks, so if we are checking whether
1932	 * we can insert without allocation then we can return now.
1933	 */
1934	if (args->op_flags & XFS_DA_OP_JUSTCHECK) {
1935		if (dbno == -1)
1936			return -ENOSPC;
1937		return 0;
1938	}
1939
1940	/*
1941	 * If we don't have a data block, we need to allocate one and make
1942	 * the freespace entries refer to it.
1943	 */
1944	if (dbno == -1) {
1945		/* we're going to have to log the free block index later */
1946		logfree = 1;
1947		error = xfs_dir2_node_add_datablk(args, fblk, &dbno, &dbp, &fbp,
1948						  &freehdr, &findex);
1949	} else {
1950		/* Read the data block in. */
1951		error = xfs_dir3_data_read(tp, dp,
1952					   xfs_dir2_db_to_da(args->geo, dbno),
1953					   0, &dbp);
1954	}
1955	if (error)
1956		return error;
1957
1958	/* setup for data block up now */
1959	hdr = dbp->b_addr;
1960	bf = xfs_dir2_data_bestfree_p(dp->i_mount, hdr);
1961	ASSERT(be16_to_cpu(bf[0].length) >= length);
1962
1963	/* Point to the existing unused space. */
1964	dup = (xfs_dir2_data_unused_t *)
1965	      ((char *)hdr + be16_to_cpu(bf[0].offset));
1966
1967	/* Mark the first part of the unused space, inuse for us. */
1968	aoff = (xfs_dir2_data_aoff_t)((char *)dup - (char *)hdr);
1969	error = xfs_dir2_data_use_free(args, dbp, dup, aoff, length,
1970			&needlog, &needscan);
1971	if (error) {
1972		xfs_trans_brelse(tp, dbp);
1973		return error;
1974	}
1975
1976	/* Fill in the new entry and log it. */
1977	dep = (xfs_dir2_data_entry_t *)dup;
1978	dep->inumber = cpu_to_be64(args->inumber);
1979	dep->namelen = args->namelen;
1980	memcpy(dep->name, args->name, dep->namelen);
1981	xfs_dir2_data_put_ftype(dp->i_mount, dep, args->filetype);
1982	tagp = xfs_dir2_data_entry_tag_p(dp->i_mount, dep);
1983	*tagp = cpu_to_be16((char *)dep - (char *)hdr);
1984	xfs_dir2_data_log_entry(args, dbp, dep);
1985
1986	/* Rescan the freespace and log the data block if needed. */
1987	if (needscan)
1988		xfs_dir2_data_freescan(dp->i_mount, hdr, &needlog);
1989	if (needlog)
1990		xfs_dir2_data_log_header(args, dbp);
1991
1992	/* If the freespace block entry is now wrong, update it. */
1993	if (freehdr.bests[findex] != bf[0].length) {
1994		freehdr.bests[findex] = bf[0].length;
1995		logfree = 1;
1996	}
1997
1998	/* Log the freespace entry if needed. */
1999	if (logfree)
2000		xfs_dir2_free_log_bests(args, &freehdr, fbp, findex, findex);
2001
2002	/* Return the data block and offset in args. */
2003	args->blkno = (xfs_dablk_t)dbno;
2004	args->index = be16_to_cpu(*tagp);
2005	return 0;
2006}
2007
2008/*
2009 * Top-level node form directory addname routine.
2010 */
2011int						/* error */
2012xfs_dir2_node_addname(
2013	xfs_da_args_t		*args)		/* operation arguments */
2014{
2015	xfs_da_state_blk_t	*blk;		/* leaf block for insert */
2016	int			error;		/* error return value */
2017	int			rval;		/* sub-return value */
2018	xfs_da_state_t		*state;		/* btree cursor */
2019
2020	trace_xfs_dir2_node_addname(args);
2021
2022	/*
2023	 * Allocate and initialize the state (btree cursor).
2024	 */
2025	state = xfs_da_state_alloc(args);
2026	/*
2027	 * Look up the name.  We're not supposed to find it, but
2028	 * this gives us the insertion point.
2029	 */
2030	error = xfs_da3_node_lookup_int(state, &rval);
2031	if (error)
2032		rval = error;
2033	if (rval != -ENOENT) {
2034		goto done;
2035	}
2036	/*
2037	 * Add the data entry to a data block.
2038	 * Extravalid is set to a freeblock found by lookup.
2039	 */
2040	rval = xfs_dir2_node_addname_int(args,
2041		state->extravalid ? &state->extrablk : NULL);
2042	if (rval) {
2043		goto done;
2044	}
2045	blk = &state->path.blk[state->path.active - 1];
2046	ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2047	/*
2048	 * Add the new leaf entry.
2049	 */
2050	rval = xfs_dir2_leafn_add(blk->bp, args, blk->index);
2051	if (rval == 0) {
2052		/*
2053		 * It worked, fix the hash values up the btree.
2054		 */
2055		if (!(args->op_flags & XFS_DA_OP_JUSTCHECK))
2056			xfs_da3_fixhashpath(state, &state->path);
2057	} else {
2058		/*
2059		 * It didn't work, we need to split the leaf block.
2060		 */
2061		if (args->total == 0) {
2062			ASSERT(rval == -ENOSPC);
2063			goto done;
2064		}
2065		/*
2066		 * Split the leaf block and insert the new entry.
2067		 */
2068		rval = xfs_da3_split(state);
2069	}
2070done:
2071	xfs_da_state_free(state);
2072	return rval;
2073}
2074
2075/*
2076 * Lookup an entry in a node-format directory.
2077 * All the real work happens in xfs_da3_node_lookup_int.
2078 * The only real output is the inode number of the entry.
2079 */
2080int						/* error */
2081xfs_dir2_node_lookup(
2082	xfs_da_args_t	*args)			/* operation arguments */
2083{
2084	int		error;			/* error return value */
2085	int		i;			/* btree level */
2086	int		rval;			/* operation return value */
2087	xfs_da_state_t	*state;			/* btree cursor */
2088
2089	trace_xfs_dir2_node_lookup(args);
2090
2091	/*
2092	 * Allocate and initialize the btree cursor.
2093	 */
2094	state = xfs_da_state_alloc(args);
2095
2096	/*
2097	 * Fill in the path to the entry in the cursor.
2098	 */
2099	error = xfs_da3_node_lookup_int(state, &rval);
2100	if (error)
2101		rval = error;
2102	else if (rval == -ENOENT && args->cmpresult == XFS_CMP_CASE) {
2103		/* If a CI match, dup the actual name and return -EEXIST */
2104		xfs_dir2_data_entry_t	*dep;
2105
2106		dep = (xfs_dir2_data_entry_t *)
2107			((char *)state->extrablk.bp->b_addr +
2108						 state->extrablk.index);
2109		rval = xfs_dir_cilookup_result(args, dep->name, dep->namelen);
2110	}
2111	/*
2112	 * Release the btree blocks and leaf block.
2113	 */
2114	for (i = 0; i < state->path.active; i++) {
2115		xfs_trans_brelse(args->trans, state->path.blk[i].bp);
2116		state->path.blk[i].bp = NULL;
2117	}
2118	/*
2119	 * Release the data block if we have it.
2120	 */
2121	if (state->extravalid && state->extrablk.bp) {
2122		xfs_trans_brelse(args->trans, state->extrablk.bp);
2123		state->extrablk.bp = NULL;
2124	}
2125	xfs_da_state_free(state);
2126	return rval;
2127}
2128
2129/*
2130 * Remove an entry from a node-format directory.
2131 */
2132int						/* error */
2133xfs_dir2_node_removename(
2134	struct xfs_da_args	*args)		/* operation arguments */
2135{
2136	struct xfs_da_state_blk	*blk;		/* leaf block */
2137	int			error;		/* error return value */
2138	int			rval;		/* operation return value */
2139	struct xfs_da_state	*state;		/* btree cursor */
2140
2141	trace_xfs_dir2_node_removename(args);
2142
2143	/*
2144	 * Allocate and initialize the btree cursor.
2145	 */
2146	state = xfs_da_state_alloc(args);
2147
2148	/* Look up the entry we're deleting, set up the cursor. */
2149	error = xfs_da3_node_lookup_int(state, &rval);
2150	if (error)
2151		goto out_free;
2152
2153	/* Didn't find it, upper layer screwed up. */
2154	if (rval != -EEXIST) {
2155		error = rval;
2156		goto out_free;
2157	}
2158
2159	blk = &state->path.blk[state->path.active - 1];
2160	ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2161	ASSERT(state->extravalid);
2162	/*
2163	 * Remove the leaf and data entries.
2164	 * Extrablk refers to the data block.
2165	 */
2166	error = xfs_dir2_leafn_remove(args, blk->bp, blk->index,
2167		&state->extrablk, &rval);
2168	if (error)
2169		goto out_free;
2170	/*
2171	 * Fix the hash values up the btree.
2172	 */
2173	xfs_da3_fixhashpath(state, &state->path);
2174	/*
2175	 * If we need to join leaf blocks, do it.
2176	 */
2177	if (rval && state->path.active > 1)
2178		error = xfs_da3_join(state);
2179	/*
2180	 * If no errors so far, try conversion to leaf format.
2181	 */
2182	if (!error)
2183		error = xfs_dir2_node_to_leaf(state);
2184out_free:
2185	xfs_da_state_free(state);
2186	return error;
2187}
2188
2189/*
2190 * Replace an entry's inode number in a node-format directory.
2191 */
2192int						/* error */
2193xfs_dir2_node_replace(
2194	xfs_da_args_t		*args)		/* operation arguments */
2195{
2196	xfs_da_state_blk_t	*blk;		/* leaf block */
2197	xfs_dir2_data_hdr_t	*hdr;		/* data block header */
2198	xfs_dir2_data_entry_t	*dep;		/* data entry changed */
2199	int			error;		/* error return value */
2200	int			i;		/* btree level */
2201	xfs_ino_t		inum;		/* new inode number */
2202	int			ftype;		/* new file type */
2203	int			rval;		/* internal return value */
2204	xfs_da_state_t		*state;		/* btree cursor */
2205
2206	trace_xfs_dir2_node_replace(args);
2207
2208	/*
2209	 * Allocate and initialize the btree cursor.
2210	 */
2211	state = xfs_da_state_alloc(args);
2212
2213	/*
2214	 * We have to save new inode number and ftype since
2215	 * xfs_da3_node_lookup_int() is going to overwrite them
2216	 */
2217	inum = args->inumber;
2218	ftype = args->filetype;
2219
2220	/*
2221	 * Lookup the entry to change in the btree.
2222	 */
2223	error = xfs_da3_node_lookup_int(state, &rval);
2224	if (error) {
2225		rval = error;
2226	}
2227	/*
2228	 * It should be found, since the vnodeops layer has looked it up
2229	 * and locked it.  But paranoia is good.
2230	 */
2231	if (rval == -EEXIST) {
2232		struct xfs_dir3_icleaf_hdr	leafhdr;
2233
2234		/*
2235		 * Find the leaf entry.
2236		 */
2237		blk = &state->path.blk[state->path.active - 1];
2238		ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2239		ASSERT(state->extravalid);
2240
2241		xfs_dir2_leaf_hdr_from_disk(state->mp, &leafhdr,
2242					    blk->bp->b_addr);
2243		/*
2244		 * Point to the data entry.
2245		 */
2246		hdr = state->extrablk.bp->b_addr;
2247		ASSERT(hdr->magic == cpu_to_be32(XFS_DIR2_DATA_MAGIC) ||
2248		       hdr->magic == cpu_to_be32(XFS_DIR3_DATA_MAGIC));
2249		dep = (xfs_dir2_data_entry_t *)
2250		      ((char *)hdr +
2251		       xfs_dir2_dataptr_to_off(args->geo,
2252				be32_to_cpu(leafhdr.ents[blk->index].address)));
2253		ASSERT(inum != be64_to_cpu(dep->inumber));
2254		/*
2255		 * Fill in the new inode number and log the entry.
2256		 */
2257		dep->inumber = cpu_to_be64(inum);
2258		xfs_dir2_data_put_ftype(state->mp, dep, ftype);
2259		xfs_dir2_data_log_entry(args, state->extrablk.bp, dep);
2260		rval = 0;
2261	}
2262	/*
2263	 * Didn't find it, and we're holding a data block.  Drop it.
2264	 */
2265	else if (state->extravalid) {
2266		xfs_trans_brelse(args->trans, state->extrablk.bp);
2267		state->extrablk.bp = NULL;
2268	}
2269	/*
2270	 * Release all the buffers in the cursor.
2271	 */
2272	for (i = 0; i < state->path.active; i++) {
2273		xfs_trans_brelse(args->trans, state->path.blk[i].bp);
2274		state->path.blk[i].bp = NULL;
2275	}
2276	xfs_da_state_free(state);
2277	return rval;
2278}
2279
2280/*
2281 * Trim off a trailing empty freespace block.
2282 * Return (in rvalp) 1 if we did it, 0 if not.
2283 */
2284int						/* error */
2285xfs_dir2_node_trim_free(
2286	xfs_da_args_t		*args,		/* operation arguments */
2287	xfs_fileoff_t		fo,		/* free block number */
2288	int			*rvalp)		/* out: did something */
2289{
2290	struct xfs_buf		*bp;		/* freespace buffer */
2291	xfs_inode_t		*dp;		/* incore directory inode */
2292	int			error;		/* error return code */
2293	xfs_dir2_free_t		*free;		/* freespace structure */
2294	xfs_trans_t		*tp;		/* transaction pointer */
2295	struct xfs_dir3_icfree_hdr freehdr;
2296
2297	dp = args->dp;
2298	tp = args->trans;
2299
2300	*rvalp = 0;
2301
2302	/*
2303	 * Read the freespace block.
2304	 */
2305	error = xfs_dir2_free_try_read(tp, dp, fo, &bp);
2306	if (error)
2307		return error;
2308	/*
2309	 * There can be holes in freespace.  If fo is a hole, there's
2310	 * nothing to do.
2311	 */
2312	if (!bp)
2313		return 0;
2314	free = bp->b_addr;
2315	xfs_dir2_free_hdr_from_disk(dp->i_mount, &freehdr, free);
2316
2317	/*
2318	 * If there are used entries, there's nothing to do.
2319	 */
2320	if (freehdr.nused > 0) {
2321		xfs_trans_brelse(tp, bp);
2322		return 0;
2323	}
2324	/*
2325	 * Blow the block away.
2326	 */
2327	error = xfs_dir2_shrink_inode(args,
2328			xfs_dir2_da_to_db(args->geo, (xfs_dablk_t)fo), bp);
2329	if (error) {
2330		/*
2331		 * Can't fail with ENOSPC since that only happens with no
2332		 * space reservation, when breaking up an extent into two
2333		 * pieces.  This is the last block of an extent.
2334		 */
2335		ASSERT(error != -ENOSPC);
2336		xfs_trans_brelse(tp, bp);
2337		return error;
2338	}
2339	/*
2340	 * Return that we succeeded.
2341	 */
2342	*rvalp = 1;
2343	return 0;
2344}
v5.14.15
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * Copyright (c) 2000-2005 Silicon Graphics, Inc.
   4 * Copyright (c) 2013 Red Hat, Inc.
   5 * All Rights Reserved.
   6 */
   7#include "xfs.h"
   8#include "xfs_fs.h"
   9#include "xfs_shared.h"
  10#include "xfs_format.h"
  11#include "xfs_log_format.h"
  12#include "xfs_trans_resv.h"
  13#include "xfs_mount.h"
  14#include "xfs_inode.h"
  15#include "xfs_bmap.h"
  16#include "xfs_dir2.h"
  17#include "xfs_dir2_priv.h"
  18#include "xfs_error.h"
  19#include "xfs_trace.h"
  20#include "xfs_trans.h"
  21#include "xfs_buf_item.h"
  22#include "xfs_log.h"
 
  23
  24/*
  25 * Function declarations.
  26 */
  27static int xfs_dir2_leafn_add(struct xfs_buf *bp, xfs_da_args_t *args,
  28			      int index);
  29static void xfs_dir2_leafn_rebalance(xfs_da_state_t *state,
  30				     xfs_da_state_blk_t *blk1,
  31				     xfs_da_state_blk_t *blk2);
  32static int xfs_dir2_leafn_remove(xfs_da_args_t *args, struct xfs_buf *bp,
  33				 int index, xfs_da_state_blk_t *dblk,
  34				 int *rval);
  35
  36/*
  37 * Convert data space db to the corresponding free db.
  38 */
  39static xfs_dir2_db_t
  40xfs_dir2_db_to_fdb(struct xfs_da_geometry *geo, xfs_dir2_db_t db)
  41{
  42	return xfs_dir2_byte_to_db(geo, XFS_DIR2_FREE_OFFSET) +
  43			(db / geo->free_max_bests);
  44}
  45
  46/*
  47 * Convert data space db to the corresponding index in a free db.
  48 */
  49static int
  50xfs_dir2_db_to_fdindex(struct xfs_da_geometry *geo, xfs_dir2_db_t db)
  51{
  52	return db % geo->free_max_bests;
  53}
  54
  55/*
  56 * Check internal consistency of a leafn block.
  57 */
  58#ifdef DEBUG
  59static xfs_failaddr_t
  60xfs_dir3_leafn_check(
  61	struct xfs_inode	*dp,
  62	struct xfs_buf		*bp)
  63{
  64	struct xfs_dir2_leaf	*leaf = bp->b_addr;
  65	struct xfs_dir3_icleaf_hdr leafhdr;
  66
  67	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
  68
  69	if (leafhdr.magic == XFS_DIR3_LEAFN_MAGIC) {
  70		struct xfs_dir3_leaf_hdr *leaf3 = bp->b_addr;
  71		if (be64_to_cpu(leaf3->info.blkno) != bp->b_bn)
  72			return __this_address;
  73	} else if (leafhdr.magic != XFS_DIR2_LEAFN_MAGIC)
  74		return __this_address;
  75
  76	return xfs_dir3_leaf_check_int(dp->i_mount, &leafhdr, leaf, false);
  77}
  78
  79static inline void
  80xfs_dir3_leaf_check(
  81	struct xfs_inode	*dp,
  82	struct xfs_buf		*bp)
  83{
  84	xfs_failaddr_t		fa;
  85
  86	fa = xfs_dir3_leafn_check(dp, bp);
  87	if (!fa)
  88		return;
  89	xfs_corruption_error(__func__, XFS_ERRLEVEL_LOW, dp->i_mount,
  90			bp->b_addr, BBTOB(bp->b_length), __FILE__, __LINE__,
  91			fa);
  92	ASSERT(0);
  93}
  94#else
  95#define	xfs_dir3_leaf_check(dp, bp)
  96#endif
  97
  98static xfs_failaddr_t
  99xfs_dir3_free_verify(
 100	struct xfs_buf		*bp)
 101{
 102	struct xfs_mount	*mp = bp->b_mount;
 103	struct xfs_dir2_free_hdr *hdr = bp->b_addr;
 104
 105	if (!xfs_verify_magic(bp, hdr->magic))
 106		return __this_address;
 107
 108	if (xfs_sb_version_hascrc(&mp->m_sb)) {
 109		struct xfs_dir3_blk_hdr *hdr3 = bp->b_addr;
 110
 111		if (!uuid_equal(&hdr3->uuid, &mp->m_sb.sb_meta_uuid))
 112			return __this_address;
 113		if (be64_to_cpu(hdr3->blkno) != bp->b_bn)
 114			return __this_address;
 115		if (!xfs_log_check_lsn(mp, be64_to_cpu(hdr3->lsn)))
 116			return __this_address;
 117	}
 118
 119	/* XXX: should bounds check the xfs_dir3_icfree_hdr here */
 120
 121	return NULL;
 122}
 123
 124static void
 125xfs_dir3_free_read_verify(
 126	struct xfs_buf	*bp)
 127{
 128	struct xfs_mount	*mp = bp->b_mount;
 129	xfs_failaddr_t		fa;
 130
 131	if (xfs_sb_version_hascrc(&mp->m_sb) &&
 132	    !xfs_buf_verify_cksum(bp, XFS_DIR3_FREE_CRC_OFF))
 133		xfs_verifier_error(bp, -EFSBADCRC, __this_address);
 134	else {
 135		fa = xfs_dir3_free_verify(bp);
 136		if (fa)
 137			xfs_verifier_error(bp, -EFSCORRUPTED, fa);
 138	}
 139}
 140
 141static void
 142xfs_dir3_free_write_verify(
 143	struct xfs_buf	*bp)
 144{
 145	struct xfs_mount	*mp = bp->b_mount;
 146	struct xfs_buf_log_item	*bip = bp->b_log_item;
 147	struct xfs_dir3_blk_hdr	*hdr3 = bp->b_addr;
 148	xfs_failaddr_t		fa;
 149
 150	fa = xfs_dir3_free_verify(bp);
 151	if (fa) {
 152		xfs_verifier_error(bp, -EFSCORRUPTED, fa);
 153		return;
 154	}
 155
 156	if (!xfs_sb_version_hascrc(&mp->m_sb))
 157		return;
 158
 159	if (bip)
 160		hdr3->lsn = cpu_to_be64(bip->bli_item.li_lsn);
 161
 162	xfs_buf_update_cksum(bp, XFS_DIR3_FREE_CRC_OFF);
 163}
 164
 165const struct xfs_buf_ops xfs_dir3_free_buf_ops = {
 166	.name = "xfs_dir3_free",
 167	.magic = { cpu_to_be32(XFS_DIR2_FREE_MAGIC),
 168		   cpu_to_be32(XFS_DIR3_FREE_MAGIC) },
 169	.verify_read = xfs_dir3_free_read_verify,
 170	.verify_write = xfs_dir3_free_write_verify,
 171	.verify_struct = xfs_dir3_free_verify,
 172};
 173
 174/* Everything ok in the free block header? */
 175static xfs_failaddr_t
 176xfs_dir3_free_header_check(
 177	struct xfs_inode	*dp,
 178	xfs_dablk_t		fbno,
 179	struct xfs_buf		*bp)
 180{
 181	struct xfs_mount	*mp = dp->i_mount;
 182	int			maxbests = mp->m_dir_geo->free_max_bests;
 183	unsigned int		firstdb;
 184
 185	firstdb = (xfs_dir2_da_to_db(mp->m_dir_geo, fbno) -
 186		   xfs_dir2_byte_to_db(mp->m_dir_geo, XFS_DIR2_FREE_OFFSET)) *
 187			maxbests;
 188	if (xfs_sb_version_hascrc(&mp->m_sb)) {
 189		struct xfs_dir3_free_hdr *hdr3 = bp->b_addr;
 190
 191		if (be32_to_cpu(hdr3->firstdb) != firstdb)
 192			return __this_address;
 193		if (be32_to_cpu(hdr3->nvalid) > maxbests)
 194			return __this_address;
 195		if (be32_to_cpu(hdr3->nvalid) < be32_to_cpu(hdr3->nused))
 196			return __this_address;
 197		if (be64_to_cpu(hdr3->hdr.owner) != dp->i_ino)
 198			return __this_address;
 199	} else {
 200		struct xfs_dir2_free_hdr *hdr = bp->b_addr;
 201
 202		if (be32_to_cpu(hdr->firstdb) != firstdb)
 203			return __this_address;
 204		if (be32_to_cpu(hdr->nvalid) > maxbests)
 205			return __this_address;
 206		if (be32_to_cpu(hdr->nvalid) < be32_to_cpu(hdr->nused))
 207			return __this_address;
 208	}
 209	return NULL;
 210}
 211
 212static int
 213__xfs_dir3_free_read(
 214	struct xfs_trans	*tp,
 215	struct xfs_inode	*dp,
 216	xfs_dablk_t		fbno,
 217	unsigned int		flags,
 218	struct xfs_buf		**bpp)
 219{
 220	xfs_failaddr_t		fa;
 221	int			err;
 222
 223	err = xfs_da_read_buf(tp, dp, fbno, flags, bpp, XFS_DATA_FORK,
 224			&xfs_dir3_free_buf_ops);
 225	if (err || !*bpp)
 226		return err;
 227
 228	/* Check things that we can't do in the verifier. */
 229	fa = xfs_dir3_free_header_check(dp, fbno, *bpp);
 230	if (fa) {
 231		__xfs_buf_mark_corrupt(*bpp, fa);
 232		xfs_trans_brelse(tp, *bpp);
 233		*bpp = NULL;
 
 234		return -EFSCORRUPTED;
 235	}
 236
 237	/* try read returns without an error or *bpp if it lands in a hole */
 238	if (tp)
 239		xfs_trans_buf_set_type(tp, *bpp, XFS_BLFT_DIR_FREE_BUF);
 240
 241	return 0;
 242}
 243
 244void
 245xfs_dir2_free_hdr_from_disk(
 246	struct xfs_mount		*mp,
 247	struct xfs_dir3_icfree_hdr	*to,
 248	struct xfs_dir2_free		*from)
 249{
 250	if (xfs_sb_version_hascrc(&mp->m_sb)) {
 251		struct xfs_dir3_free	*from3 = (struct xfs_dir3_free *)from;
 252
 253		to->magic = be32_to_cpu(from3->hdr.hdr.magic);
 254		to->firstdb = be32_to_cpu(from3->hdr.firstdb);
 255		to->nvalid = be32_to_cpu(from3->hdr.nvalid);
 256		to->nused = be32_to_cpu(from3->hdr.nused);
 257		to->bests = from3->bests;
 258
 259		ASSERT(to->magic == XFS_DIR3_FREE_MAGIC);
 260	} else {
 261		to->magic = be32_to_cpu(from->hdr.magic);
 262		to->firstdb = be32_to_cpu(from->hdr.firstdb);
 263		to->nvalid = be32_to_cpu(from->hdr.nvalid);
 264		to->nused = be32_to_cpu(from->hdr.nused);
 265		to->bests = from->bests;
 266
 267		ASSERT(to->magic == XFS_DIR2_FREE_MAGIC);
 268	}
 269}
 270
 271static void
 272xfs_dir2_free_hdr_to_disk(
 273	struct xfs_mount		*mp,
 274	struct xfs_dir2_free		*to,
 275	struct xfs_dir3_icfree_hdr	*from)
 276{
 277	if (xfs_sb_version_hascrc(&mp->m_sb)) {
 278		struct xfs_dir3_free	*to3 = (struct xfs_dir3_free *)to;
 279
 280		ASSERT(from->magic == XFS_DIR3_FREE_MAGIC);
 281
 282		to3->hdr.hdr.magic = cpu_to_be32(from->magic);
 283		to3->hdr.firstdb = cpu_to_be32(from->firstdb);
 284		to3->hdr.nvalid = cpu_to_be32(from->nvalid);
 285		to3->hdr.nused = cpu_to_be32(from->nused);
 286	} else {
 287		ASSERT(from->magic == XFS_DIR2_FREE_MAGIC);
 288
 289		to->hdr.magic = cpu_to_be32(from->magic);
 290		to->hdr.firstdb = cpu_to_be32(from->firstdb);
 291		to->hdr.nvalid = cpu_to_be32(from->nvalid);
 292		to->hdr.nused = cpu_to_be32(from->nused);
 293	}
 294}
 295
 296int
 297xfs_dir2_free_read(
 298	struct xfs_trans	*tp,
 299	struct xfs_inode	*dp,
 300	xfs_dablk_t		fbno,
 301	struct xfs_buf		**bpp)
 302{
 303	return __xfs_dir3_free_read(tp, dp, fbno, 0, bpp);
 304}
 305
 306static int
 307xfs_dir2_free_try_read(
 308	struct xfs_trans	*tp,
 309	struct xfs_inode	*dp,
 310	xfs_dablk_t		fbno,
 311	struct xfs_buf		**bpp)
 312{
 313	return __xfs_dir3_free_read(tp, dp, fbno, XFS_DABUF_MAP_HOLE_OK, bpp);
 314}
 315
 316static int
 317xfs_dir3_free_get_buf(
 318	xfs_da_args_t		*args,
 319	xfs_dir2_db_t		fbno,
 320	struct xfs_buf		**bpp)
 321{
 322	struct xfs_trans	*tp = args->trans;
 323	struct xfs_inode	*dp = args->dp;
 324	struct xfs_mount	*mp = dp->i_mount;
 325	struct xfs_buf		*bp;
 326	int			error;
 327	struct xfs_dir3_icfree_hdr hdr;
 328
 329	error = xfs_da_get_buf(tp, dp, xfs_dir2_db_to_da(args->geo, fbno),
 330			&bp, XFS_DATA_FORK);
 331	if (error)
 332		return error;
 333
 334	xfs_trans_buf_set_type(tp, bp, XFS_BLFT_DIR_FREE_BUF);
 335	bp->b_ops = &xfs_dir3_free_buf_ops;
 336
 337	/*
 338	 * Initialize the new block to be empty, and remember
 339	 * its first slot as our empty slot.
 340	 */
 341	memset(bp->b_addr, 0, sizeof(struct xfs_dir3_free_hdr));
 342	memset(&hdr, 0, sizeof(hdr));
 343
 344	if (xfs_sb_version_hascrc(&mp->m_sb)) {
 345		struct xfs_dir3_free_hdr *hdr3 = bp->b_addr;
 346
 347		hdr.magic = XFS_DIR3_FREE_MAGIC;
 348
 349		hdr3->hdr.blkno = cpu_to_be64(bp->b_bn);
 350		hdr3->hdr.owner = cpu_to_be64(dp->i_ino);
 351		uuid_copy(&hdr3->hdr.uuid, &mp->m_sb.sb_meta_uuid);
 352	} else
 353		hdr.magic = XFS_DIR2_FREE_MAGIC;
 354	xfs_dir2_free_hdr_to_disk(mp, bp->b_addr, &hdr);
 355	*bpp = bp;
 356	return 0;
 357}
 358
 359/*
 360 * Log entries from a freespace block.
 361 */
 362STATIC void
 363xfs_dir2_free_log_bests(
 364	struct xfs_da_args	*args,
 365	struct xfs_dir3_icfree_hdr *hdr,
 366	struct xfs_buf		*bp,
 367	int			first,		/* first entry to log */
 368	int			last)		/* last entry to log */
 369{
 370	struct xfs_dir2_free	*free = bp->b_addr;
 371
 372	ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
 373	       free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
 374	xfs_trans_log_buf(args->trans, bp,
 375			  (char *)&hdr->bests[first] - (char *)free,
 376			  (char *)&hdr->bests[last] - (char *)free +
 377			   sizeof(hdr->bests[0]) - 1);
 378}
 379
 380/*
 381 * Log header from a freespace block.
 382 */
 383static void
 384xfs_dir2_free_log_header(
 385	struct xfs_da_args	*args,
 386	struct xfs_buf		*bp)
 387{
 388#ifdef DEBUG
 389	xfs_dir2_free_t		*free;		/* freespace structure */
 390
 391	free = bp->b_addr;
 392	ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
 393	       free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
 394#endif
 395	xfs_trans_log_buf(args->trans, bp, 0,
 396			  args->geo->free_hdr_size - 1);
 397}
 398
 399/*
 400 * Convert a leaf-format directory to a node-format directory.
 401 * We need to change the magic number of the leaf block, and copy
 402 * the freespace table out of the leaf block into its own block.
 403 */
 404int						/* error */
 405xfs_dir2_leaf_to_node(
 406	xfs_da_args_t		*args,		/* operation arguments */
 407	struct xfs_buf		*lbp)		/* leaf buffer */
 408{
 409	xfs_inode_t		*dp;		/* incore directory inode */
 410	int			error;		/* error return value */
 411	struct xfs_buf		*fbp;		/* freespace buffer */
 412	xfs_dir2_db_t		fdb;		/* freespace block number */
 413	__be16			*from;		/* pointer to freespace entry */
 414	int			i;		/* leaf freespace index */
 415	xfs_dir2_leaf_t		*leaf;		/* leaf structure */
 416	xfs_dir2_leaf_tail_t	*ltp;		/* leaf tail structure */
 417	int			n;		/* count of live freespc ents */
 418	xfs_dir2_data_off_t	off;		/* freespace entry value */
 419	xfs_trans_t		*tp;		/* transaction pointer */
 420	struct xfs_dir3_icfree_hdr freehdr;
 421
 422	trace_xfs_dir2_leaf_to_node(args);
 423
 424	dp = args->dp;
 425	tp = args->trans;
 426	/*
 427	 * Add a freespace block to the directory.
 428	 */
 429	if ((error = xfs_dir2_grow_inode(args, XFS_DIR2_FREE_SPACE, &fdb))) {
 430		return error;
 431	}
 432	ASSERT(fdb == xfs_dir2_byte_to_db(args->geo, XFS_DIR2_FREE_OFFSET));
 433	/*
 434	 * Get the buffer for the new freespace block.
 435	 */
 436	error = xfs_dir3_free_get_buf(args, fdb, &fbp);
 437	if (error)
 438		return error;
 439
 440	xfs_dir2_free_hdr_from_disk(dp->i_mount, &freehdr, fbp->b_addr);
 441	leaf = lbp->b_addr;
 442	ltp = xfs_dir2_leaf_tail_p(args->geo, leaf);
 443	if (be32_to_cpu(ltp->bestcount) >
 444				(uint)dp->i_disk_size / args->geo->blksize) {
 445		xfs_buf_mark_corrupt(lbp);
 
 446		return -EFSCORRUPTED;
 447	}
 448
 449	/*
 450	 * Copy freespace entries from the leaf block to the new block.
 451	 * Count active entries.
 452	 */
 453	from = xfs_dir2_leaf_bests_p(ltp);
 454	for (i = n = 0; i < be32_to_cpu(ltp->bestcount); i++, from++) {
 455		off = be16_to_cpu(*from);
 456		if (off != NULLDATAOFF)
 457			n++;
 458		freehdr.bests[i] = cpu_to_be16(off);
 459	}
 460
 461	/*
 462	 * Now initialize the freespace block header.
 463	 */
 464	freehdr.nused = n;
 465	freehdr.nvalid = be32_to_cpu(ltp->bestcount);
 466
 467	xfs_dir2_free_hdr_to_disk(dp->i_mount, fbp->b_addr, &freehdr);
 468	xfs_dir2_free_log_bests(args, &freehdr, fbp, 0, freehdr.nvalid - 1);
 469	xfs_dir2_free_log_header(args, fbp);
 470
 471	/*
 472	 * Converting the leaf to a leafnode is just a matter of changing the
 473	 * magic number and the ops. Do the change directly to the buffer as
 474	 * it's less work (and less code) than decoding the header to host
 475	 * format and back again.
 476	 */
 477	if (leaf->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAF1_MAGIC))
 478		leaf->hdr.info.magic = cpu_to_be16(XFS_DIR2_LEAFN_MAGIC);
 479	else
 480		leaf->hdr.info.magic = cpu_to_be16(XFS_DIR3_LEAFN_MAGIC);
 481	lbp->b_ops = &xfs_dir3_leafn_buf_ops;
 482	xfs_trans_buf_set_type(tp, lbp, XFS_BLFT_DIR_LEAFN_BUF);
 483	xfs_dir3_leaf_log_header(args, lbp);
 484	xfs_dir3_leaf_check(dp, lbp);
 485	return 0;
 486}
 487
 488/*
 489 * Add a leaf entry to a leaf block in a node-form directory.
 490 * The other work necessary is done from the caller.
 491 */
 492static int					/* error */
 493xfs_dir2_leafn_add(
 494	struct xfs_buf		*bp,		/* leaf buffer */
 495	struct xfs_da_args	*args,		/* operation arguments */
 496	int			index)		/* insertion pt for new entry */
 497{
 498	struct xfs_dir3_icleaf_hdr leafhdr;
 499	struct xfs_inode	*dp = args->dp;
 500	struct xfs_dir2_leaf	*leaf = bp->b_addr;
 501	struct xfs_dir2_leaf_entry *lep;
 502	struct xfs_dir2_leaf_entry *ents;
 503	int			compact;	/* compacting stale leaves */
 504	int			highstale = 0;	/* next stale entry */
 505	int			lfloghigh;	/* high leaf entry logging */
 506	int			lfloglow;	/* low leaf entry logging */
 507	int			lowstale = 0;	/* previous stale entry */
 508
 509	trace_xfs_dir2_leafn_add(args, index);
 510
 511	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
 512	ents = leafhdr.ents;
 513
 514	/*
 515	 * Quick check just to make sure we are not going to index
 516	 * into other peoples memory
 517	 */
 518	if (index < 0) {
 519		xfs_buf_mark_corrupt(bp);
 
 520		return -EFSCORRUPTED;
 521	}
 522
 523	/*
 524	 * If there are already the maximum number of leaf entries in
 525	 * the block, if there are no stale entries it won't fit.
 526	 * Caller will do a split.  If there are stale entries we'll do
 527	 * a compact.
 528	 */
 529
 530	if (leafhdr.count == args->geo->leaf_max_ents) {
 531		if (!leafhdr.stale)
 532			return -ENOSPC;
 533		compact = leafhdr.stale > 1;
 534	} else
 535		compact = 0;
 536	ASSERT(index == 0 || be32_to_cpu(ents[index - 1].hashval) <= args->hashval);
 537	ASSERT(index == leafhdr.count ||
 538	       be32_to_cpu(ents[index].hashval) >= args->hashval);
 539
 540	if (args->op_flags & XFS_DA_OP_JUSTCHECK)
 541		return 0;
 542
 543	/*
 544	 * Compact out all but one stale leaf entry.  Leaves behind
 545	 * the entry closest to index.
 546	 */
 547	if (compact)
 548		xfs_dir3_leaf_compact_x1(&leafhdr, ents, &index, &lowstale,
 549					 &highstale, &lfloglow, &lfloghigh);
 550	else if (leafhdr.stale) {
 551		/*
 552		 * Set impossible logging indices for this case.
 553		 */
 554		lfloglow = leafhdr.count;
 555		lfloghigh = -1;
 556	}
 557
 558	/*
 559	 * Insert the new entry, log everything.
 560	 */
 561	lep = xfs_dir3_leaf_find_entry(&leafhdr, ents, index, compact, lowstale,
 562				       highstale, &lfloglow, &lfloghigh);
 563
 564	lep->hashval = cpu_to_be32(args->hashval);
 565	lep->address = cpu_to_be32(xfs_dir2_db_off_to_dataptr(args->geo,
 566				args->blkno, args->index));
 567
 568	xfs_dir2_leaf_hdr_to_disk(dp->i_mount, leaf, &leafhdr);
 569	xfs_dir3_leaf_log_header(args, bp);
 570	xfs_dir3_leaf_log_ents(args, &leafhdr, bp, lfloglow, lfloghigh);
 571	xfs_dir3_leaf_check(dp, bp);
 572	return 0;
 573}
 574
 575#ifdef DEBUG
 576static void
 577xfs_dir2_free_hdr_check(
 578	struct xfs_inode *dp,
 579	struct xfs_buf	*bp,
 580	xfs_dir2_db_t	db)
 581{
 582	struct xfs_dir3_icfree_hdr hdr;
 583
 584	xfs_dir2_free_hdr_from_disk(dp->i_mount, &hdr, bp->b_addr);
 585
 586	ASSERT((hdr.firstdb % dp->i_mount->m_dir_geo->free_max_bests) == 0);
 587	ASSERT(hdr.firstdb <= db);
 588	ASSERT(db < hdr.firstdb + hdr.nvalid);
 589}
 590#else
 591#define xfs_dir2_free_hdr_check(dp, bp, db)
 592#endif	/* DEBUG */
 593
 594/*
 595 * Return the last hash value in the leaf.
 596 * Stale entries are ok.
 597 */
 598xfs_dahash_t					/* hash value */
 599xfs_dir2_leaf_lasthash(
 600	struct xfs_inode *dp,
 601	struct xfs_buf	*bp,			/* leaf buffer */
 602	int		*count)			/* count of entries in leaf */
 603{
 604	struct xfs_dir3_icleaf_hdr leafhdr;
 605
 606	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, bp->b_addr);
 607
 608	ASSERT(leafhdr.magic == XFS_DIR2_LEAFN_MAGIC ||
 609	       leafhdr.magic == XFS_DIR3_LEAFN_MAGIC ||
 610	       leafhdr.magic == XFS_DIR2_LEAF1_MAGIC ||
 611	       leafhdr.magic == XFS_DIR3_LEAF1_MAGIC);
 612
 613	if (count)
 614		*count = leafhdr.count;
 615	if (!leafhdr.count)
 616		return 0;
 617	return be32_to_cpu(leafhdr.ents[leafhdr.count - 1].hashval);
 618}
 619
 620/*
 621 * Look up a leaf entry for space to add a name in a node-format leaf block.
 622 * The extrablk in state is a freespace block.
 623 */
 624STATIC int
 625xfs_dir2_leafn_lookup_for_addname(
 626	struct xfs_buf		*bp,		/* leaf buffer */
 627	xfs_da_args_t		*args,		/* operation arguments */
 628	int			*indexp,	/* out: leaf entry index */
 629	xfs_da_state_t		*state)		/* state to fill in */
 630{
 631	struct xfs_buf		*curbp = NULL;	/* current data/free buffer */
 632	xfs_dir2_db_t		curdb = -1;	/* current data block number */
 633	xfs_dir2_db_t		curfdb = -1;	/* current free block number */
 634	xfs_inode_t		*dp;		/* incore directory inode */
 635	int			error;		/* error return value */
 636	int			fi;		/* free entry index */
 637	xfs_dir2_free_t		*free = NULL;	/* free block structure */
 638	int			index;		/* leaf entry index */
 639	xfs_dir2_leaf_t		*leaf;		/* leaf structure */
 640	int			length;		/* length of new data entry */
 641	xfs_dir2_leaf_entry_t	*lep;		/* leaf entry */
 642	xfs_mount_t		*mp;		/* filesystem mount point */
 643	xfs_dir2_db_t		newdb;		/* new data block number */
 644	xfs_dir2_db_t		newfdb;		/* new free block number */
 645	xfs_trans_t		*tp;		/* transaction pointer */
 646	struct xfs_dir3_icleaf_hdr leafhdr;
 647
 648	dp = args->dp;
 649	tp = args->trans;
 650	mp = dp->i_mount;
 651	leaf = bp->b_addr;
 652	xfs_dir2_leaf_hdr_from_disk(mp, &leafhdr, leaf);
 653
 654	xfs_dir3_leaf_check(dp, bp);
 655	ASSERT(leafhdr.count > 0);
 656
 657	/*
 658	 * Look up the hash value in the leaf entries.
 659	 */
 660	index = xfs_dir2_leaf_search_hash(args, bp);
 661	/*
 662	 * Do we have a buffer coming in?
 663	 */
 664	if (state->extravalid) {
 665		/* If so, it's a free block buffer, get the block number. */
 666		curbp = state->extrablk.bp;
 667		curfdb = state->extrablk.blkno;
 668		free = curbp->b_addr;
 669		ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
 670		       free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
 671	}
 672	length = xfs_dir2_data_entsize(mp, args->namelen);
 673	/*
 674	 * Loop over leaf entries with the right hash value.
 675	 */
 676	for (lep = &leafhdr.ents[index];
 677	     index < leafhdr.count && be32_to_cpu(lep->hashval) == args->hashval;
 678	     lep++, index++) {
 679		/*
 680		 * Skip stale leaf entries.
 681		 */
 682		if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR)
 683			continue;
 684		/*
 685		 * Pull the data block number from the entry.
 686		 */
 687		newdb = xfs_dir2_dataptr_to_db(args->geo,
 688					       be32_to_cpu(lep->address));
 689		/*
 690		 * For addname, we're looking for a place to put the new entry.
 691		 * We want to use a data block with an entry of equal
 692		 * hash value to ours if there is one with room.
 693		 *
 694		 * If this block isn't the data block we already have
 695		 * in hand, take a look at it.
 696		 */
 697		if (newdb != curdb) {
 698			struct xfs_dir3_icfree_hdr freehdr;
 699
 700			curdb = newdb;
 701			/*
 702			 * Convert the data block to the free block
 703			 * holding its freespace information.
 704			 */
 705			newfdb = xfs_dir2_db_to_fdb(args->geo, newdb);
 706			/*
 707			 * If it's not the one we have in hand, read it in.
 708			 */
 709			if (newfdb != curfdb) {
 710				/*
 711				 * If we had one before, drop it.
 712				 */
 713				if (curbp)
 714					xfs_trans_brelse(tp, curbp);
 715
 716				error = xfs_dir2_free_read(tp, dp,
 717						xfs_dir2_db_to_da(args->geo,
 718								  newfdb),
 719						&curbp);
 720				if (error)
 721					return error;
 722				free = curbp->b_addr;
 723
 724				xfs_dir2_free_hdr_check(dp, curbp, curdb);
 725			}
 726			/*
 727			 * Get the index for our entry.
 728			 */
 729			fi = xfs_dir2_db_to_fdindex(args->geo, curdb);
 730			/*
 731			 * If it has room, return it.
 732			 */
 733			xfs_dir2_free_hdr_from_disk(mp, &freehdr, free);
 734			if (XFS_IS_CORRUPT(mp,
 735					   freehdr.bests[fi] ==
 736					   cpu_to_be16(NULLDATAOFF))) {
 737				if (curfdb != newfdb)
 738					xfs_trans_brelse(tp, curbp);
 
 739				return -EFSCORRUPTED;
 740			}
 741			curfdb = newfdb;
 742			if (be16_to_cpu(freehdr.bests[fi]) >= length)
 743				goto out;
 744		}
 745	}
 746	/* Didn't find any space */
 747	fi = -1;
 748out:
 749	ASSERT(args->op_flags & XFS_DA_OP_OKNOENT);
 750	if (curbp) {
 751		/* Giving back a free block. */
 752		state->extravalid = 1;
 753		state->extrablk.bp = curbp;
 754		state->extrablk.index = fi;
 755		state->extrablk.blkno = curfdb;
 756
 757		/*
 758		 * Important: this magic number is not in the buffer - it's for
 759		 * buffer type information and therefore only the free/data type
 760		 * matters here, not whether CRCs are enabled or not.
 761		 */
 762		state->extrablk.magic = XFS_DIR2_FREE_MAGIC;
 763	} else {
 764		state->extravalid = 0;
 765	}
 766	/*
 767	 * Return the index, that will be the insertion point.
 768	 */
 769	*indexp = index;
 770	return -ENOENT;
 771}
 772
 773/*
 774 * Look up a leaf entry in a node-format leaf block.
 775 * The extrablk in state a data block.
 776 */
 777STATIC int
 778xfs_dir2_leafn_lookup_for_entry(
 779	struct xfs_buf		*bp,		/* leaf buffer */
 780	xfs_da_args_t		*args,		/* operation arguments */
 781	int			*indexp,	/* out: leaf entry index */
 782	xfs_da_state_t		*state)		/* state to fill in */
 783{
 784	struct xfs_buf		*curbp = NULL;	/* current data/free buffer */
 785	xfs_dir2_db_t		curdb = -1;	/* current data block number */
 786	xfs_dir2_data_entry_t	*dep;		/* data block entry */
 787	xfs_inode_t		*dp;		/* incore directory inode */
 788	int			error;		/* error return value */
 789	int			index;		/* leaf entry index */
 790	xfs_dir2_leaf_t		*leaf;		/* leaf structure */
 791	xfs_dir2_leaf_entry_t	*lep;		/* leaf entry */
 792	xfs_mount_t		*mp;		/* filesystem mount point */
 793	xfs_dir2_db_t		newdb;		/* new data block number */
 794	xfs_trans_t		*tp;		/* transaction pointer */
 795	enum xfs_dacmp		cmp;		/* comparison result */
 796	struct xfs_dir3_icleaf_hdr leafhdr;
 797
 798	dp = args->dp;
 799	tp = args->trans;
 800	mp = dp->i_mount;
 801	leaf = bp->b_addr;
 802	xfs_dir2_leaf_hdr_from_disk(mp, &leafhdr, leaf);
 803
 804	xfs_dir3_leaf_check(dp, bp);
 805	if (leafhdr.count <= 0) {
 806		xfs_buf_mark_corrupt(bp);
 
 807		return -EFSCORRUPTED;
 808	}
 809
 810	/*
 811	 * Look up the hash value in the leaf entries.
 812	 */
 813	index = xfs_dir2_leaf_search_hash(args, bp);
 814	/*
 815	 * Do we have a buffer coming in?
 816	 */
 817	if (state->extravalid) {
 818		curbp = state->extrablk.bp;
 819		curdb = state->extrablk.blkno;
 820	}
 821	/*
 822	 * Loop over leaf entries with the right hash value.
 823	 */
 824	for (lep = &leafhdr.ents[index];
 825	     index < leafhdr.count && be32_to_cpu(lep->hashval) == args->hashval;
 826	     lep++, index++) {
 827		/*
 828		 * Skip stale leaf entries.
 829		 */
 830		if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR)
 831			continue;
 832		/*
 833		 * Pull the data block number from the entry.
 834		 */
 835		newdb = xfs_dir2_dataptr_to_db(args->geo,
 836					       be32_to_cpu(lep->address));
 837		/*
 838		 * Not adding a new entry, so we really want to find
 839		 * the name given to us.
 840		 *
 841		 * If it's a different data block, go get it.
 842		 */
 843		if (newdb != curdb) {
 844			/*
 845			 * If we had a block before that we aren't saving
 846			 * for a CI name, drop it
 847			 */
 848			if (curbp && (args->cmpresult == XFS_CMP_DIFFERENT ||
 849						curdb != state->extrablk.blkno))
 850				xfs_trans_brelse(tp, curbp);
 851			/*
 852			 * If needing the block that is saved with a CI match,
 853			 * use it otherwise read in the new data block.
 854			 */
 855			if (args->cmpresult != XFS_CMP_DIFFERENT &&
 856					newdb == state->extrablk.blkno) {
 857				ASSERT(state->extravalid);
 858				curbp = state->extrablk.bp;
 859			} else {
 860				error = xfs_dir3_data_read(tp, dp,
 861						xfs_dir2_db_to_da(args->geo,
 862								  newdb),
 863						0, &curbp);
 864				if (error)
 865					return error;
 866			}
 867			xfs_dir3_data_check(dp, curbp);
 868			curdb = newdb;
 869		}
 870		/*
 871		 * Point to the data entry.
 872		 */
 873		dep = (xfs_dir2_data_entry_t *)((char *)curbp->b_addr +
 874			xfs_dir2_dataptr_to_off(args->geo,
 875						be32_to_cpu(lep->address)));
 876		/*
 877		 * Compare the entry and if it's an exact match, return
 878		 * EEXIST immediately. If it's the first case-insensitive
 879		 * match, store the block & inode number and continue looking.
 880		 */
 881		cmp = xfs_dir2_compname(args, dep->name, dep->namelen);
 882		if (cmp != XFS_CMP_DIFFERENT && cmp != args->cmpresult) {
 883			/* If there is a CI match block, drop it */
 884			if (args->cmpresult != XFS_CMP_DIFFERENT &&
 885						curdb != state->extrablk.blkno)
 886				xfs_trans_brelse(tp, state->extrablk.bp);
 887			args->cmpresult = cmp;
 888			args->inumber = be64_to_cpu(dep->inumber);
 889			args->filetype = xfs_dir2_data_get_ftype(mp, dep);
 890			*indexp = index;
 891			state->extravalid = 1;
 892			state->extrablk.bp = curbp;
 893			state->extrablk.blkno = curdb;
 894			state->extrablk.index = (int)((char *)dep -
 895							(char *)curbp->b_addr);
 896			state->extrablk.magic = XFS_DIR2_DATA_MAGIC;
 897			curbp->b_ops = &xfs_dir3_data_buf_ops;
 898			xfs_trans_buf_set_type(tp, curbp, XFS_BLFT_DIR_DATA_BUF);
 899			if (cmp == XFS_CMP_EXACT)
 900				return -EEXIST;
 901		}
 902	}
 903	ASSERT(index == leafhdr.count || (args->op_flags & XFS_DA_OP_OKNOENT));
 904	if (curbp) {
 905		if (args->cmpresult == XFS_CMP_DIFFERENT) {
 906			/* Giving back last used data block. */
 907			state->extravalid = 1;
 908			state->extrablk.bp = curbp;
 909			state->extrablk.index = -1;
 910			state->extrablk.blkno = curdb;
 911			state->extrablk.magic = XFS_DIR2_DATA_MAGIC;
 912			curbp->b_ops = &xfs_dir3_data_buf_ops;
 913			xfs_trans_buf_set_type(tp, curbp, XFS_BLFT_DIR_DATA_BUF);
 914		} else {
 915			/* If the curbp is not the CI match block, drop it */
 916			if (state->extrablk.bp != curbp)
 917				xfs_trans_brelse(tp, curbp);
 918		}
 919	} else {
 920		state->extravalid = 0;
 921	}
 922	*indexp = index;
 923	return -ENOENT;
 924}
 925
 926/*
 927 * Look up a leaf entry in a node-format leaf block.
 928 * If this is an addname then the extrablk in state is a freespace block,
 929 * otherwise it's a data block.
 930 */
 931int
 932xfs_dir2_leafn_lookup_int(
 933	struct xfs_buf		*bp,		/* leaf buffer */
 934	xfs_da_args_t		*args,		/* operation arguments */
 935	int			*indexp,	/* out: leaf entry index */
 936	xfs_da_state_t		*state)		/* state to fill in */
 937{
 938	if (args->op_flags & XFS_DA_OP_ADDNAME)
 939		return xfs_dir2_leafn_lookup_for_addname(bp, args, indexp,
 940							state);
 941	return xfs_dir2_leafn_lookup_for_entry(bp, args, indexp, state);
 942}
 943
 944/*
 945 * Move count leaf entries from source to destination leaf.
 946 * Log entries and headers.  Stale entries are preserved.
 947 */
 948static void
 949xfs_dir3_leafn_moveents(
 950	xfs_da_args_t			*args,	/* operation arguments */
 951	struct xfs_buf			*bp_s,	/* source */
 952	struct xfs_dir3_icleaf_hdr	*shdr,
 953	struct xfs_dir2_leaf_entry	*sents,
 954	int				start_s,/* source leaf index */
 955	struct xfs_buf			*bp_d,	/* destination */
 956	struct xfs_dir3_icleaf_hdr	*dhdr,
 957	struct xfs_dir2_leaf_entry	*dents,
 958	int				start_d,/* destination leaf index */
 959	int				count)	/* count of leaves to copy */
 960{
 961	int				stale;	/* count stale leaves copied */
 962
 963	trace_xfs_dir2_leafn_moveents(args, start_s, start_d, count);
 964
 965	/*
 966	 * Silently return if nothing to do.
 967	 */
 968	if (count == 0)
 969		return;
 970
 971	/*
 972	 * If the destination index is not the end of the current
 973	 * destination leaf entries, open up a hole in the destination
 974	 * to hold the new entries.
 975	 */
 976	if (start_d < dhdr->count) {
 977		memmove(&dents[start_d + count], &dents[start_d],
 978			(dhdr->count - start_d) * sizeof(xfs_dir2_leaf_entry_t));
 979		xfs_dir3_leaf_log_ents(args, dhdr, bp_d, start_d + count,
 980				       count + dhdr->count - 1);
 981	}
 982	/*
 983	 * If the source has stale leaves, count the ones in the copy range
 984	 * so we can update the header correctly.
 985	 */
 986	if (shdr->stale) {
 987		int	i;			/* temp leaf index */
 988
 989		for (i = start_s, stale = 0; i < start_s + count; i++) {
 990			if (sents[i].address ==
 991					cpu_to_be32(XFS_DIR2_NULL_DATAPTR))
 992				stale++;
 993		}
 994	} else
 995		stale = 0;
 996	/*
 997	 * Copy the leaf entries from source to destination.
 998	 */
 999	memcpy(&dents[start_d], &sents[start_s],
1000		count * sizeof(xfs_dir2_leaf_entry_t));
1001	xfs_dir3_leaf_log_ents(args, dhdr, bp_d, start_d, start_d + count - 1);
1002
1003	/*
1004	 * If there are source entries after the ones we copied,
1005	 * delete the ones we copied by sliding the next ones down.
1006	 */
1007	if (start_s + count < shdr->count) {
1008		memmove(&sents[start_s], &sents[start_s + count],
1009			count * sizeof(xfs_dir2_leaf_entry_t));
1010		xfs_dir3_leaf_log_ents(args, shdr, bp_s, start_s,
1011				       start_s + count - 1);
1012	}
1013
1014	/*
1015	 * Update the headers and log them.
1016	 */
1017	shdr->count -= count;
1018	shdr->stale -= stale;
1019	dhdr->count += count;
1020	dhdr->stale += stale;
1021}
1022
1023/*
1024 * Determine the sort order of two leaf blocks.
1025 * Returns 1 if both are valid and leaf2 should be before leaf1, else 0.
1026 */
1027int						/* sort order */
1028xfs_dir2_leafn_order(
1029	struct xfs_inode	*dp,
1030	struct xfs_buf		*leaf1_bp,		/* leaf1 buffer */
1031	struct xfs_buf		*leaf2_bp)		/* leaf2 buffer */
1032{
1033	struct xfs_dir2_leaf	*leaf1 = leaf1_bp->b_addr;
1034	struct xfs_dir2_leaf	*leaf2 = leaf2_bp->b_addr;
1035	struct xfs_dir2_leaf_entry *ents1;
1036	struct xfs_dir2_leaf_entry *ents2;
1037	struct xfs_dir3_icleaf_hdr hdr1;
1038	struct xfs_dir3_icleaf_hdr hdr2;
1039
1040	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr1, leaf1);
1041	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr2, leaf2);
1042	ents1 = hdr1.ents;
1043	ents2 = hdr2.ents;
1044
1045	if (hdr1.count > 0 && hdr2.count > 0 &&
1046	    (be32_to_cpu(ents2[0].hashval) < be32_to_cpu(ents1[0].hashval) ||
1047	     be32_to_cpu(ents2[hdr2.count - 1].hashval) <
1048				be32_to_cpu(ents1[hdr1.count - 1].hashval)))
1049		return 1;
1050	return 0;
1051}
1052
1053/*
1054 * Rebalance leaf entries between two leaf blocks.
1055 * This is actually only called when the second block is new,
1056 * though the code deals with the general case.
1057 * A new entry will be inserted in one of the blocks, and that
1058 * entry is taken into account when balancing.
1059 */
1060static void
1061xfs_dir2_leafn_rebalance(
1062	xfs_da_state_t		*state,		/* btree cursor */
1063	xfs_da_state_blk_t	*blk1,		/* first btree block */
1064	xfs_da_state_blk_t	*blk2)		/* second btree block */
1065{
1066	xfs_da_args_t		*args;		/* operation arguments */
1067	int			count;		/* count (& direction) leaves */
1068	int			isleft;		/* new goes in left leaf */
1069	xfs_dir2_leaf_t		*leaf1;		/* first leaf structure */
1070	xfs_dir2_leaf_t		*leaf2;		/* second leaf structure */
1071	int			mid;		/* midpoint leaf index */
1072#if defined(DEBUG) || defined(XFS_WARN)
1073	int			oldstale;	/* old count of stale leaves */
1074#endif
1075	int			oldsum;		/* old total leaf count */
1076	int			swap_blocks;	/* swapped leaf blocks */
1077	struct xfs_dir2_leaf_entry *ents1;
1078	struct xfs_dir2_leaf_entry *ents2;
1079	struct xfs_dir3_icleaf_hdr hdr1;
1080	struct xfs_dir3_icleaf_hdr hdr2;
1081	struct xfs_inode	*dp = state->args->dp;
1082
1083	args = state->args;
1084	/*
1085	 * If the block order is wrong, swap the arguments.
1086	 */
1087	swap_blocks = xfs_dir2_leafn_order(dp, blk1->bp, blk2->bp);
1088	if (swap_blocks)
1089		swap(blk1, blk2);
1090
1091	leaf1 = blk1->bp->b_addr;
1092	leaf2 = blk2->bp->b_addr;
1093	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr1, leaf1);
1094	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr2, leaf2);
1095	ents1 = hdr1.ents;
1096	ents2 = hdr2.ents;
1097
1098	oldsum = hdr1.count + hdr2.count;
1099#if defined(DEBUG) || defined(XFS_WARN)
1100	oldstale = hdr1.stale + hdr2.stale;
1101#endif
1102	mid = oldsum >> 1;
1103
1104	/*
1105	 * If the old leaf count was odd then the new one will be even,
1106	 * so we need to divide the new count evenly.
1107	 */
1108	if (oldsum & 1) {
1109		xfs_dahash_t	midhash;	/* middle entry hash value */
1110
1111		if (mid >= hdr1.count)
1112			midhash = be32_to_cpu(ents2[mid - hdr1.count].hashval);
1113		else
1114			midhash = be32_to_cpu(ents1[mid].hashval);
1115		isleft = args->hashval <= midhash;
1116	}
1117	/*
1118	 * If the old count is even then the new count is odd, so there's
1119	 * no preferred side for the new entry.
1120	 * Pick the left one.
1121	 */
1122	else
1123		isleft = 1;
1124	/*
1125	 * Calculate moved entry count.  Positive means left-to-right,
1126	 * negative means right-to-left.  Then move the entries.
1127	 */
1128	count = hdr1.count - mid + (isleft == 0);
1129	if (count > 0)
1130		xfs_dir3_leafn_moveents(args, blk1->bp, &hdr1, ents1,
1131					hdr1.count - count, blk2->bp,
1132					&hdr2, ents2, 0, count);
1133	else if (count < 0)
1134		xfs_dir3_leafn_moveents(args, blk2->bp, &hdr2, ents2, 0,
1135					blk1->bp, &hdr1, ents1,
1136					hdr1.count, count);
1137
1138	ASSERT(hdr1.count + hdr2.count == oldsum);
1139	ASSERT(hdr1.stale + hdr2.stale == oldstale);
1140
1141	/* log the changes made when moving the entries */
1142	xfs_dir2_leaf_hdr_to_disk(dp->i_mount, leaf1, &hdr1);
1143	xfs_dir2_leaf_hdr_to_disk(dp->i_mount, leaf2, &hdr2);
1144	xfs_dir3_leaf_log_header(args, blk1->bp);
1145	xfs_dir3_leaf_log_header(args, blk2->bp);
1146
1147	xfs_dir3_leaf_check(dp, blk1->bp);
1148	xfs_dir3_leaf_check(dp, blk2->bp);
1149
1150	/*
1151	 * Mark whether we're inserting into the old or new leaf.
1152	 */
1153	if (hdr1.count < hdr2.count)
1154		state->inleaf = swap_blocks;
1155	else if (hdr1.count > hdr2.count)
1156		state->inleaf = !swap_blocks;
1157	else
1158		state->inleaf = swap_blocks ^ (blk1->index <= hdr1.count);
1159	/*
1160	 * Adjust the expected index for insertion.
1161	 */
1162	if (!state->inleaf)
1163		blk2->index = blk1->index - hdr1.count;
1164
1165	/*
1166	 * Finally sanity check just to make sure we are not returning a
1167	 * negative index
1168	 */
1169	if (blk2->index < 0) {
1170		state->inleaf = 1;
1171		blk2->index = 0;
1172		xfs_alert(dp->i_mount,
1173	"%s: picked the wrong leaf? reverting original leaf: blk1->index %d",
1174			__func__, blk1->index);
1175	}
1176}
1177
1178static int
1179xfs_dir3_data_block_free(
1180	xfs_da_args_t		*args,
1181	struct xfs_dir2_data_hdr *hdr,
1182	struct xfs_dir2_free	*free,
1183	xfs_dir2_db_t		fdb,
1184	int			findex,
1185	struct xfs_buf		*fbp,
1186	int			longest)
1187{
1188	int			logfree = 0;
1189	struct xfs_dir3_icfree_hdr freehdr;
1190	struct xfs_inode	*dp = args->dp;
1191
1192	xfs_dir2_free_hdr_from_disk(dp->i_mount, &freehdr, free);
1193	if (hdr) {
1194		/*
1195		 * Data block is not empty, just set the free entry to the new
1196		 * value.
1197		 */
1198		freehdr.bests[findex] = cpu_to_be16(longest);
1199		xfs_dir2_free_log_bests(args, &freehdr, fbp, findex, findex);
1200		return 0;
1201	}
1202
1203	/* One less used entry in the free table. */
1204	freehdr.nused--;
1205
1206	/*
1207	 * If this was the last entry in the table, we can trim the table size
1208	 * back.  There might be other entries at the end referring to
1209	 * non-existent data blocks, get those too.
1210	 */
1211	if (findex == freehdr.nvalid - 1) {
1212		int	i;		/* free entry index */
1213
1214		for (i = findex - 1; i >= 0; i--) {
1215			if (freehdr.bests[i] != cpu_to_be16(NULLDATAOFF))
1216				break;
1217		}
1218		freehdr.nvalid = i + 1;
1219		logfree = 0;
1220	} else {
1221		/* Not the last entry, just punch it out.  */
1222		freehdr.bests[findex] = cpu_to_be16(NULLDATAOFF);
1223		logfree = 1;
1224	}
1225
1226	xfs_dir2_free_hdr_to_disk(dp->i_mount, free, &freehdr);
1227	xfs_dir2_free_log_header(args, fbp);
1228
1229	/*
1230	 * If there are no useful entries left in the block, get rid of the
1231	 * block if we can.
1232	 */
1233	if (!freehdr.nused) {
1234		int error;
1235
1236		error = xfs_dir2_shrink_inode(args, fdb, fbp);
1237		if (error == 0) {
1238			fbp = NULL;
1239			logfree = 0;
1240		} else if (error != -ENOSPC || args->total != 0)
1241			return error;
1242		/*
1243		 * It's possible to get ENOSPC if there is no
1244		 * space reservation.  In this case some one
1245		 * else will eventually get rid of this block.
1246		 */
1247	}
1248
1249	/* Log the free entry that changed, unless we got rid of it.  */
1250	if (logfree)
1251		xfs_dir2_free_log_bests(args, &freehdr, fbp, findex, findex);
1252	return 0;
1253}
1254
1255/*
1256 * Remove an entry from a node directory.
1257 * This removes the leaf entry and the data entry,
1258 * and updates the free block if necessary.
1259 */
1260static int					/* error */
1261xfs_dir2_leafn_remove(
1262	xfs_da_args_t		*args,		/* operation arguments */
1263	struct xfs_buf		*bp,		/* leaf buffer */
1264	int			index,		/* leaf entry index */
1265	xfs_da_state_blk_t	*dblk,		/* data block */
1266	int			*rval)		/* resulting block needs join */
1267{
1268	struct xfs_da_geometry	*geo = args->geo;
1269	xfs_dir2_data_hdr_t	*hdr;		/* data block header */
1270	xfs_dir2_db_t		db;		/* data block number */
1271	struct xfs_buf		*dbp;		/* data block buffer */
1272	xfs_dir2_data_entry_t	*dep;		/* data block entry */
1273	xfs_inode_t		*dp;		/* incore directory inode */
1274	xfs_dir2_leaf_t		*leaf;		/* leaf structure */
1275	xfs_dir2_leaf_entry_t	*lep;		/* leaf entry */
1276	int			longest;	/* longest data free entry */
1277	int			off;		/* data block entry offset */
1278	int			needlog;	/* need to log data header */
1279	int			needscan;	/* need to rescan data frees */
1280	xfs_trans_t		*tp;		/* transaction pointer */
1281	struct xfs_dir2_data_free *bf;		/* bestfree table */
1282	struct xfs_dir3_icleaf_hdr leafhdr;
1283
1284	trace_xfs_dir2_leafn_remove(args, index);
1285
1286	dp = args->dp;
1287	tp = args->trans;
1288	leaf = bp->b_addr;
1289	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
1290
1291	/*
1292	 * Point to the entry we're removing.
1293	 */
1294	lep = &leafhdr.ents[index];
1295
1296	/*
1297	 * Extract the data block and offset from the entry.
1298	 */
1299	db = xfs_dir2_dataptr_to_db(geo, be32_to_cpu(lep->address));
1300	ASSERT(dblk->blkno == db);
1301	off = xfs_dir2_dataptr_to_off(geo, be32_to_cpu(lep->address));
1302	ASSERT(dblk->index == off);
1303
1304	/*
1305	 * Kill the leaf entry by marking it stale.
1306	 * Log the leaf block changes.
1307	 */
1308	leafhdr.stale++;
1309	xfs_dir2_leaf_hdr_to_disk(dp->i_mount, leaf, &leafhdr);
1310	xfs_dir3_leaf_log_header(args, bp);
1311
1312	lep->address = cpu_to_be32(XFS_DIR2_NULL_DATAPTR);
1313	xfs_dir3_leaf_log_ents(args, &leafhdr, bp, index, index);
1314
1315	/*
1316	 * Make the data entry free.  Keep track of the longest freespace
1317	 * in the data block in case it changes.
1318	 */
1319	dbp = dblk->bp;
1320	hdr = dbp->b_addr;
1321	dep = (xfs_dir2_data_entry_t *)((char *)hdr + off);
1322	bf = xfs_dir2_data_bestfree_p(dp->i_mount, hdr);
1323	longest = be16_to_cpu(bf[0].length);
1324	needlog = needscan = 0;
1325	xfs_dir2_data_make_free(args, dbp, off,
1326		xfs_dir2_data_entsize(dp->i_mount, dep->namelen), &needlog,
1327		&needscan);
1328	/*
1329	 * Rescan the data block freespaces for bestfree.
1330	 * Log the data block header if needed.
1331	 */
1332	if (needscan)
1333		xfs_dir2_data_freescan(dp->i_mount, hdr, &needlog);
1334	if (needlog)
1335		xfs_dir2_data_log_header(args, dbp);
1336	xfs_dir3_data_check(dp, dbp);
1337	/*
1338	 * If the longest data block freespace changes, need to update
1339	 * the corresponding freeblock entry.
1340	 */
1341	if (longest < be16_to_cpu(bf[0].length)) {
1342		int		error;		/* error return value */
1343		struct xfs_buf	*fbp;		/* freeblock buffer */
1344		xfs_dir2_db_t	fdb;		/* freeblock block number */
1345		int		findex;		/* index in freeblock entries */
1346		xfs_dir2_free_t	*free;		/* freeblock structure */
1347
1348		/*
1349		 * Convert the data block number to a free block,
1350		 * read in the free block.
1351		 */
1352		fdb = xfs_dir2_db_to_fdb(geo, db);
1353		error = xfs_dir2_free_read(tp, dp, xfs_dir2_db_to_da(geo, fdb),
1354					   &fbp);
1355		if (error)
1356			return error;
1357		free = fbp->b_addr;
1358#ifdef DEBUG
1359	{
1360		struct xfs_dir3_icfree_hdr freehdr;
1361
1362		xfs_dir2_free_hdr_from_disk(dp->i_mount, &freehdr, free);
1363		ASSERT(freehdr.firstdb == geo->free_max_bests *
1364			(fdb - xfs_dir2_byte_to_db(geo, XFS_DIR2_FREE_OFFSET)));
1365	}
1366#endif
1367		/*
1368		 * Calculate which entry we need to fix.
1369		 */
1370		findex = xfs_dir2_db_to_fdindex(geo, db);
1371		longest = be16_to_cpu(bf[0].length);
1372		/*
1373		 * If the data block is now empty we can get rid of it
1374		 * (usually).
1375		 */
1376		if (longest == geo->blksize - geo->data_entry_offset) {
1377			/*
1378			 * Try to punch out the data block.
1379			 */
1380			error = xfs_dir2_shrink_inode(args, db, dbp);
1381			if (error == 0) {
1382				dblk->bp = NULL;
1383				hdr = NULL;
1384			}
1385			/*
1386			 * We can get ENOSPC if there's no space reservation.
1387			 * In this case just drop the buffer and some one else
1388			 * will eventually get rid of the empty block.
1389			 */
1390			else if (!(error == -ENOSPC && args->total == 0))
1391				return error;
1392		}
1393		/*
1394		 * If we got rid of the data block, we can eliminate that entry
1395		 * in the free block.
1396		 */
1397		error = xfs_dir3_data_block_free(args, hdr, free,
1398						 fdb, findex, fbp, longest);
1399		if (error)
1400			return error;
1401	}
1402
1403	xfs_dir3_leaf_check(dp, bp);
1404	/*
1405	 * Return indication of whether this leaf block is empty enough
1406	 * to justify trying to join it with a neighbor.
1407	 */
1408	*rval = (geo->leaf_hdr_size +
1409		 (uint)sizeof(leafhdr.ents) * (leafhdr.count - leafhdr.stale)) <
1410		geo->magicpct;
1411	return 0;
1412}
1413
1414/*
1415 * Split the leaf entries in the old block into old and new blocks.
1416 */
1417int						/* error */
1418xfs_dir2_leafn_split(
1419	xfs_da_state_t		*state,		/* btree cursor */
1420	xfs_da_state_blk_t	*oldblk,	/* original block */
1421	xfs_da_state_blk_t	*newblk)	/* newly created block */
1422{
1423	xfs_da_args_t		*args;		/* operation arguments */
1424	xfs_dablk_t		blkno;		/* new leaf block number */
1425	int			error;		/* error return value */
1426	struct xfs_inode	*dp;
1427
1428	/*
1429	 * Allocate space for a new leaf node.
1430	 */
1431	args = state->args;
1432	dp = args->dp;
1433	ASSERT(oldblk->magic == XFS_DIR2_LEAFN_MAGIC);
1434	error = xfs_da_grow_inode(args, &blkno);
1435	if (error) {
1436		return error;
1437	}
1438	/*
1439	 * Initialize the new leaf block.
1440	 */
1441	error = xfs_dir3_leaf_get_buf(args, xfs_dir2_da_to_db(args->geo, blkno),
1442				      &newblk->bp, XFS_DIR2_LEAFN_MAGIC);
1443	if (error)
1444		return error;
1445
1446	newblk->blkno = blkno;
1447	newblk->magic = XFS_DIR2_LEAFN_MAGIC;
1448	/*
1449	 * Rebalance the entries across the two leaves, link the new
1450	 * block into the leaves.
1451	 */
1452	xfs_dir2_leafn_rebalance(state, oldblk, newblk);
1453	error = xfs_da3_blk_link(state, oldblk, newblk);
1454	if (error) {
1455		return error;
1456	}
1457	/*
1458	 * Insert the new entry in the correct block.
1459	 */
1460	if (state->inleaf)
1461		error = xfs_dir2_leafn_add(oldblk->bp, args, oldblk->index);
1462	else
1463		error = xfs_dir2_leafn_add(newblk->bp, args, newblk->index);
1464	/*
1465	 * Update last hashval in each block since we added the name.
1466	 */
1467	oldblk->hashval = xfs_dir2_leaf_lasthash(dp, oldblk->bp, NULL);
1468	newblk->hashval = xfs_dir2_leaf_lasthash(dp, newblk->bp, NULL);
1469	xfs_dir3_leaf_check(dp, oldblk->bp);
1470	xfs_dir3_leaf_check(dp, newblk->bp);
1471	return error;
1472}
1473
1474/*
1475 * Check a leaf block and its neighbors to see if the block should be
1476 * collapsed into one or the other neighbor.  Always keep the block
1477 * with the smaller block number.
1478 * If the current block is over 50% full, don't try to join it, return 0.
1479 * If the block is empty, fill in the state structure and return 2.
1480 * If it can be collapsed, fill in the state structure and return 1.
1481 * If nothing can be done, return 0.
1482 */
1483int						/* error */
1484xfs_dir2_leafn_toosmall(
1485	xfs_da_state_t		*state,		/* btree cursor */
1486	int			*action)	/* resulting action to take */
1487{
1488	xfs_da_state_blk_t	*blk;		/* leaf block */
1489	xfs_dablk_t		blkno;		/* leaf block number */
1490	struct xfs_buf		*bp;		/* leaf buffer */
1491	int			bytes;		/* bytes in use */
1492	int			count;		/* leaf live entry count */
1493	int			error;		/* error return value */
1494	int			forward;	/* sibling block direction */
1495	int			i;		/* sibling counter */
1496	xfs_dir2_leaf_t		*leaf;		/* leaf structure */
1497	int			rval;		/* result from path_shift */
1498	struct xfs_dir3_icleaf_hdr leafhdr;
1499	struct xfs_dir2_leaf_entry *ents;
1500	struct xfs_inode	*dp = state->args->dp;
1501
1502	/*
1503	 * Check for the degenerate case of the block being over 50% full.
1504	 * If so, it's not worth even looking to see if we might be able
1505	 * to coalesce with a sibling.
1506	 */
1507	blk = &state->path.blk[state->path.active - 1];
1508	leaf = blk->bp->b_addr;
1509	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
1510	ents = leafhdr.ents;
1511	xfs_dir3_leaf_check(dp, blk->bp);
1512
1513	count = leafhdr.count - leafhdr.stale;
1514	bytes = state->args->geo->leaf_hdr_size + count * sizeof(ents[0]);
1515	if (bytes > (state->args->geo->blksize >> 1)) {
1516		/*
1517		 * Blk over 50%, don't try to join.
1518		 */
1519		*action = 0;
1520		return 0;
1521	}
1522	/*
1523	 * Check for the degenerate case of the block being empty.
1524	 * If the block is empty, we'll simply delete it, no need to
1525	 * coalesce it with a sibling block.  We choose (arbitrarily)
1526	 * to merge with the forward block unless it is NULL.
1527	 */
1528	if (count == 0) {
1529		/*
1530		 * Make altpath point to the block we want to keep and
1531		 * path point to the block we want to drop (this one).
1532		 */
1533		forward = (leafhdr.forw != 0);
1534		memcpy(&state->altpath, &state->path, sizeof(state->path));
1535		error = xfs_da3_path_shift(state, &state->altpath, forward, 0,
1536			&rval);
1537		if (error)
1538			return error;
1539		*action = rval ? 2 : 0;
1540		return 0;
1541	}
1542	/*
1543	 * Examine each sibling block to see if we can coalesce with
1544	 * at least 25% free space to spare.  We need to figure out
1545	 * whether to merge with the forward or the backward block.
1546	 * We prefer coalescing with the lower numbered sibling so as
1547	 * to shrink a directory over time.
1548	 */
1549	forward = leafhdr.forw < leafhdr.back;
1550	for (i = 0, bp = NULL; i < 2; forward = !forward, i++) {
1551		struct xfs_dir3_icleaf_hdr hdr2;
1552
1553		blkno = forward ? leafhdr.forw : leafhdr.back;
1554		if (blkno == 0)
1555			continue;
1556		/*
1557		 * Read the sibling leaf block.
1558		 */
1559		error = xfs_dir3_leafn_read(state->args->trans, dp, blkno, &bp);
1560		if (error)
1561			return error;
1562
1563		/*
1564		 * Count bytes in the two blocks combined.
1565		 */
1566		count = leafhdr.count - leafhdr.stale;
1567		bytes = state->args->geo->blksize -
1568			(state->args->geo->blksize >> 2);
1569
1570		leaf = bp->b_addr;
1571		xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr2, leaf);
1572		ents = hdr2.ents;
1573		count += hdr2.count - hdr2.stale;
1574		bytes -= count * sizeof(ents[0]);
1575
1576		/*
1577		 * Fits with at least 25% to spare.
1578		 */
1579		if (bytes >= 0)
1580			break;
1581		xfs_trans_brelse(state->args->trans, bp);
1582	}
1583	/*
1584	 * Didn't like either block, give up.
1585	 */
1586	if (i >= 2) {
1587		*action = 0;
1588		return 0;
1589	}
1590
1591	/*
1592	 * Make altpath point to the block we want to keep (the lower
1593	 * numbered block) and path point to the block we want to drop.
1594	 */
1595	memcpy(&state->altpath, &state->path, sizeof(state->path));
1596	if (blkno < blk->blkno)
1597		error = xfs_da3_path_shift(state, &state->altpath, forward, 0,
1598			&rval);
1599	else
1600		error = xfs_da3_path_shift(state, &state->path, forward, 0,
1601			&rval);
1602	if (error) {
1603		return error;
1604	}
1605	*action = rval ? 0 : 1;
1606	return 0;
1607}
1608
1609/*
1610 * Move all the leaf entries from drop_blk to save_blk.
1611 * This is done as part of a join operation.
1612 */
1613void
1614xfs_dir2_leafn_unbalance(
1615	xfs_da_state_t		*state,		/* cursor */
1616	xfs_da_state_blk_t	*drop_blk,	/* dead block */
1617	xfs_da_state_blk_t	*save_blk)	/* surviving block */
1618{
1619	xfs_da_args_t		*args;		/* operation arguments */
1620	xfs_dir2_leaf_t		*drop_leaf;	/* dead leaf structure */
1621	xfs_dir2_leaf_t		*save_leaf;	/* surviving leaf structure */
1622	struct xfs_dir3_icleaf_hdr savehdr;
1623	struct xfs_dir3_icleaf_hdr drophdr;
1624	struct xfs_dir2_leaf_entry *sents;
1625	struct xfs_dir2_leaf_entry *dents;
1626	struct xfs_inode	*dp = state->args->dp;
1627
1628	args = state->args;
1629	ASSERT(drop_blk->magic == XFS_DIR2_LEAFN_MAGIC);
1630	ASSERT(save_blk->magic == XFS_DIR2_LEAFN_MAGIC);
1631	drop_leaf = drop_blk->bp->b_addr;
1632	save_leaf = save_blk->bp->b_addr;
1633
1634	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &savehdr, save_leaf);
1635	xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &drophdr, drop_leaf);
1636	sents = savehdr.ents;
1637	dents = drophdr.ents;
1638
1639	/*
1640	 * If there are any stale leaf entries, take this opportunity
1641	 * to purge them.
1642	 */
1643	if (drophdr.stale)
1644		xfs_dir3_leaf_compact(args, &drophdr, drop_blk->bp);
1645	if (savehdr.stale)
1646		xfs_dir3_leaf_compact(args, &savehdr, save_blk->bp);
1647
1648	/*
1649	 * Move the entries from drop to the appropriate end of save.
1650	 */
1651	drop_blk->hashval = be32_to_cpu(dents[drophdr.count - 1].hashval);
1652	if (xfs_dir2_leafn_order(dp, save_blk->bp, drop_blk->bp))
1653		xfs_dir3_leafn_moveents(args, drop_blk->bp, &drophdr, dents, 0,
1654					save_blk->bp, &savehdr, sents, 0,
1655					drophdr.count);
1656	else
1657		xfs_dir3_leafn_moveents(args, drop_blk->bp, &drophdr, dents, 0,
1658					save_blk->bp, &savehdr, sents,
1659					savehdr.count, drophdr.count);
1660	save_blk->hashval = be32_to_cpu(sents[savehdr.count - 1].hashval);
1661
1662	/* log the changes made when moving the entries */
1663	xfs_dir2_leaf_hdr_to_disk(dp->i_mount, save_leaf, &savehdr);
1664	xfs_dir2_leaf_hdr_to_disk(dp->i_mount, drop_leaf, &drophdr);
1665	xfs_dir3_leaf_log_header(args, save_blk->bp);
1666	xfs_dir3_leaf_log_header(args, drop_blk->bp);
1667
1668	xfs_dir3_leaf_check(dp, save_blk->bp);
1669	xfs_dir3_leaf_check(dp, drop_blk->bp);
1670}
1671
1672/*
1673 * Add a new data block to the directory at the free space index that the caller
1674 * has specified.
1675 */
1676static int
1677xfs_dir2_node_add_datablk(
1678	struct xfs_da_args	*args,
1679	struct xfs_da_state_blk	*fblk,
1680	xfs_dir2_db_t		*dbno,
1681	struct xfs_buf		**dbpp,
1682	struct xfs_buf		**fbpp,
1683	struct xfs_dir3_icfree_hdr *hdr,
1684	int			*findex)
1685{
1686	struct xfs_inode	*dp = args->dp;
1687	struct xfs_trans	*tp = args->trans;
1688	struct xfs_mount	*mp = dp->i_mount;
1689	struct xfs_dir2_data_free *bf;
1690	xfs_dir2_db_t		fbno;
1691	struct xfs_buf		*fbp;
1692	struct xfs_buf		*dbp;
1693	int			error;
1694
1695	/* Not allowed to allocate, return failure. */
1696	if (args->total == 0)
1697		return -ENOSPC;
1698
1699	/* Allocate and initialize the new data block.  */
1700	error = xfs_dir2_grow_inode(args, XFS_DIR2_DATA_SPACE, dbno);
1701	if (error)
1702		return error;
1703	error = xfs_dir3_data_init(args, *dbno, &dbp);
1704	if (error)
1705		return error;
1706
1707	/*
1708	 * Get the freespace block corresponding to the data block
1709	 * that was just allocated.
1710	 */
1711	fbno = xfs_dir2_db_to_fdb(args->geo, *dbno);
1712	error = xfs_dir2_free_try_read(tp, dp,
1713			       xfs_dir2_db_to_da(args->geo, fbno), &fbp);
1714	if (error)
1715		return error;
1716
1717	/*
1718	 * If there wasn't a freespace block, the read will
1719	 * return a NULL fbp.  Allocate and initialize a new one.
1720	 */
1721	if (!fbp) {
1722		error = xfs_dir2_grow_inode(args, XFS_DIR2_FREE_SPACE, &fbno);
1723		if (error)
1724			return error;
1725
1726		if (XFS_IS_CORRUPT(mp,
1727				   xfs_dir2_db_to_fdb(args->geo, *dbno) !=
1728				   fbno)) {
1729			xfs_alert(mp,
1730"%s: dir ino %llu needed freesp block %lld for data block %lld, got %lld",
1731				__func__, (unsigned long long)dp->i_ino,
1732				(long long)xfs_dir2_db_to_fdb(args->geo, *dbno),
1733				(long long)*dbno, (long long)fbno);
1734			if (fblk) {
1735				xfs_alert(mp,
1736			" fblk "PTR_FMT" blkno %llu index %d magic 0x%x",
1737					fblk, (unsigned long long)fblk->blkno,
1738					fblk->index, fblk->magic);
1739			} else {
1740				xfs_alert(mp, " ... fblk is NULL");
1741			}
 
1742			return -EFSCORRUPTED;
1743		}
1744
1745		/* Get a buffer for the new block. */
1746		error = xfs_dir3_free_get_buf(args, fbno, &fbp);
1747		if (error)
1748			return error;
1749		xfs_dir2_free_hdr_from_disk(mp, hdr, fbp->b_addr);
1750
1751		/* Remember the first slot as our empty slot. */
1752		hdr->firstdb = (fbno - xfs_dir2_byte_to_db(args->geo,
1753							XFS_DIR2_FREE_OFFSET)) *
1754				args->geo->free_max_bests;
1755	} else {
1756		xfs_dir2_free_hdr_from_disk(mp, hdr, fbp->b_addr);
1757	}
1758
1759	/* Set the freespace block index from the data block number. */
1760	*findex = xfs_dir2_db_to_fdindex(args->geo, *dbno);
1761
1762	/* Extend the freespace table if the new data block is off the end. */
1763	if (*findex >= hdr->nvalid) {
1764		ASSERT(*findex < args->geo->free_max_bests);
1765		hdr->nvalid = *findex + 1;
1766		hdr->bests[*findex] = cpu_to_be16(NULLDATAOFF);
1767	}
1768
1769	/*
1770	 * If this entry was for an empty data block (this should always be
1771	 * true) then update the header.
1772	 */
1773	if (hdr->bests[*findex] == cpu_to_be16(NULLDATAOFF)) {
1774		hdr->nused++;
1775		xfs_dir2_free_hdr_to_disk(mp, fbp->b_addr, hdr);
1776		xfs_dir2_free_log_header(args, fbp);
1777	}
1778
1779	/* Update the freespace value for the new block in the table. */
1780	bf = xfs_dir2_data_bestfree_p(mp, dbp->b_addr);
1781	hdr->bests[*findex] = bf[0].length;
1782
1783	*dbpp = dbp;
1784	*fbpp = fbp;
1785	return 0;
1786}
1787
1788static int
1789xfs_dir2_node_find_freeblk(
1790	struct xfs_da_args	*args,
1791	struct xfs_da_state_blk	*fblk,
1792	xfs_dir2_db_t		*dbnop,
1793	struct xfs_buf		**fbpp,
1794	struct xfs_dir3_icfree_hdr *hdr,
1795	int			*findexp,
1796	int			length)
1797{
1798	struct xfs_inode	*dp = args->dp;
1799	struct xfs_trans	*tp = args->trans;
1800	struct xfs_buf		*fbp = NULL;
1801	xfs_dir2_db_t		firstfbno;
1802	xfs_dir2_db_t		lastfbno;
1803	xfs_dir2_db_t		ifbno = -1;
1804	xfs_dir2_db_t		dbno = -1;
1805	xfs_dir2_db_t		fbno;
1806	xfs_fileoff_t		fo;
1807	int			findex = 0;
1808	int			error;
1809
1810	/*
1811	 * If we came in with a freespace block that means that lookup
1812	 * found an entry with our hash value.  This is the freespace
1813	 * block for that data entry.
1814	 */
1815	if (fblk) {
1816		fbp = fblk->bp;
1817		findex = fblk->index;
1818		xfs_dir2_free_hdr_from_disk(dp->i_mount, hdr, fbp->b_addr);
1819		if (findex >= 0) {
1820			/* caller already found the freespace for us. */
1821			ASSERT(findex < hdr->nvalid);
1822			ASSERT(be16_to_cpu(hdr->bests[findex]) != NULLDATAOFF);
1823			ASSERT(be16_to_cpu(hdr->bests[findex]) >= length);
1824			dbno = hdr->firstdb + findex;
1825			goto found_block;
1826		}
1827
1828		/*
1829		 * The data block looked at didn't have enough room.
1830		 * We'll start at the beginning of the freespace entries.
1831		 */
1832		ifbno = fblk->blkno;
1833		xfs_trans_brelse(tp, fbp);
1834		fbp = NULL;
1835		fblk->bp = NULL;
1836	}
1837
1838	/*
1839	 * If we don't have a data block yet, we're going to scan the freespace
1840	 * data for a data block with enough free space in it.
1841	 */
1842	error = xfs_bmap_last_offset(dp, &fo, XFS_DATA_FORK);
1843	if (error)
1844		return error;
1845	lastfbno = xfs_dir2_da_to_db(args->geo, (xfs_dablk_t)fo);
1846	firstfbno = xfs_dir2_byte_to_db(args->geo, XFS_DIR2_FREE_OFFSET);
1847
1848	for (fbno = lastfbno - 1; fbno >= firstfbno; fbno--) {
1849		/* If it's ifbno we already looked at it. */
1850		if (fbno == ifbno)
1851			continue;
1852
1853		/*
1854		 * Read the block.  There can be holes in the freespace blocks,
1855		 * so this might not succeed.  This should be really rare, so
1856		 * there's no reason to avoid it.
1857		 */
1858		error = xfs_dir2_free_try_read(tp, dp,
1859				xfs_dir2_db_to_da(args->geo, fbno),
1860				&fbp);
1861		if (error)
1862			return error;
1863		if (!fbp)
1864			continue;
1865
1866		xfs_dir2_free_hdr_from_disk(dp->i_mount, hdr, fbp->b_addr);
1867
1868		/* Scan the free entry array for a large enough free space. */
1869		for (findex = hdr->nvalid - 1; findex >= 0; findex--) {
1870			if (be16_to_cpu(hdr->bests[findex]) != NULLDATAOFF &&
1871			    be16_to_cpu(hdr->bests[findex]) >= length) {
1872				dbno = hdr->firstdb + findex;
1873				goto found_block;
1874			}
1875		}
1876
1877		/* Didn't find free space, go on to next free block */
1878		xfs_trans_brelse(tp, fbp);
1879	}
1880
1881found_block:
1882	*dbnop = dbno;
1883	*fbpp = fbp;
1884	*findexp = findex;
1885	return 0;
1886}
1887
1888/*
1889 * Add the data entry for a node-format directory name addition.
1890 * The leaf entry is added in xfs_dir2_leafn_add.
1891 * We may enter with a freespace block that the lookup found.
1892 */
1893static int
1894xfs_dir2_node_addname_int(
1895	struct xfs_da_args	*args,		/* operation arguments */
1896	struct xfs_da_state_blk	*fblk)		/* optional freespace block */
1897{
1898	struct xfs_dir2_data_unused *dup;	/* data unused entry pointer */
1899	struct xfs_dir2_data_entry *dep;	/* data entry pointer */
1900	struct xfs_dir2_data_hdr *hdr;		/* data block header */
1901	struct xfs_dir2_data_free *bf;
1902	struct xfs_trans	*tp = args->trans;
1903	struct xfs_inode	*dp = args->dp;
1904	struct xfs_dir3_icfree_hdr freehdr;
1905	struct xfs_buf		*dbp;		/* data block buffer */
1906	struct xfs_buf		*fbp;		/* freespace buffer */
1907	xfs_dir2_data_aoff_t	aoff;
1908	xfs_dir2_db_t		dbno;		/* data block number */
1909	int			error;		/* error return value */
1910	int			findex;		/* freespace entry index */
1911	int			length;		/* length of the new entry */
1912	int			logfree = 0;	/* need to log free entry */
1913	int			needlog = 0;	/* need to log data header */
1914	int			needscan = 0;	/* need to rescan data frees */
1915	__be16			*tagp;		/* data entry tag pointer */
1916
1917	length = xfs_dir2_data_entsize(dp->i_mount, args->namelen);
1918	error = xfs_dir2_node_find_freeblk(args, fblk, &dbno, &fbp, &freehdr,
1919					   &findex, length);
1920	if (error)
1921		return error;
1922
1923	/*
1924	 * Now we know if we must allocate blocks, so if we are checking whether
1925	 * we can insert without allocation then we can return now.
1926	 */
1927	if (args->op_flags & XFS_DA_OP_JUSTCHECK) {
1928		if (dbno == -1)
1929			return -ENOSPC;
1930		return 0;
1931	}
1932
1933	/*
1934	 * If we don't have a data block, we need to allocate one and make
1935	 * the freespace entries refer to it.
1936	 */
1937	if (dbno == -1) {
1938		/* we're going to have to log the free block index later */
1939		logfree = 1;
1940		error = xfs_dir2_node_add_datablk(args, fblk, &dbno, &dbp, &fbp,
1941						  &freehdr, &findex);
1942	} else {
1943		/* Read the data block in. */
1944		error = xfs_dir3_data_read(tp, dp,
1945					   xfs_dir2_db_to_da(args->geo, dbno),
1946					   0, &dbp);
1947	}
1948	if (error)
1949		return error;
1950
1951	/* setup for data block up now */
1952	hdr = dbp->b_addr;
1953	bf = xfs_dir2_data_bestfree_p(dp->i_mount, hdr);
1954	ASSERT(be16_to_cpu(bf[0].length) >= length);
1955
1956	/* Point to the existing unused space. */
1957	dup = (xfs_dir2_data_unused_t *)
1958	      ((char *)hdr + be16_to_cpu(bf[0].offset));
1959
1960	/* Mark the first part of the unused space, inuse for us. */
1961	aoff = (xfs_dir2_data_aoff_t)((char *)dup - (char *)hdr);
1962	error = xfs_dir2_data_use_free(args, dbp, dup, aoff, length,
1963			&needlog, &needscan);
1964	if (error) {
1965		xfs_trans_brelse(tp, dbp);
1966		return error;
1967	}
1968
1969	/* Fill in the new entry and log it. */
1970	dep = (xfs_dir2_data_entry_t *)dup;
1971	dep->inumber = cpu_to_be64(args->inumber);
1972	dep->namelen = args->namelen;
1973	memcpy(dep->name, args->name, dep->namelen);
1974	xfs_dir2_data_put_ftype(dp->i_mount, dep, args->filetype);
1975	tagp = xfs_dir2_data_entry_tag_p(dp->i_mount, dep);
1976	*tagp = cpu_to_be16((char *)dep - (char *)hdr);
1977	xfs_dir2_data_log_entry(args, dbp, dep);
1978
1979	/* Rescan the freespace and log the data block if needed. */
1980	if (needscan)
1981		xfs_dir2_data_freescan(dp->i_mount, hdr, &needlog);
1982	if (needlog)
1983		xfs_dir2_data_log_header(args, dbp);
1984
1985	/* If the freespace block entry is now wrong, update it. */
1986	if (freehdr.bests[findex] != bf[0].length) {
1987		freehdr.bests[findex] = bf[0].length;
1988		logfree = 1;
1989	}
1990
1991	/* Log the freespace entry if needed. */
1992	if (logfree)
1993		xfs_dir2_free_log_bests(args, &freehdr, fbp, findex, findex);
1994
1995	/* Return the data block and offset in args. */
1996	args->blkno = (xfs_dablk_t)dbno;
1997	args->index = be16_to_cpu(*tagp);
1998	return 0;
1999}
2000
2001/*
2002 * Top-level node form directory addname routine.
2003 */
2004int						/* error */
2005xfs_dir2_node_addname(
2006	xfs_da_args_t		*args)		/* operation arguments */
2007{
2008	xfs_da_state_blk_t	*blk;		/* leaf block for insert */
2009	int			error;		/* error return value */
2010	int			rval;		/* sub-return value */
2011	xfs_da_state_t		*state;		/* btree cursor */
2012
2013	trace_xfs_dir2_node_addname(args);
2014
2015	/*
2016	 * Allocate and initialize the state (btree cursor).
2017	 */
2018	state = xfs_da_state_alloc(args);
2019	/*
2020	 * Look up the name.  We're not supposed to find it, but
2021	 * this gives us the insertion point.
2022	 */
2023	error = xfs_da3_node_lookup_int(state, &rval);
2024	if (error)
2025		rval = error;
2026	if (rval != -ENOENT) {
2027		goto done;
2028	}
2029	/*
2030	 * Add the data entry to a data block.
2031	 * Extravalid is set to a freeblock found by lookup.
2032	 */
2033	rval = xfs_dir2_node_addname_int(args,
2034		state->extravalid ? &state->extrablk : NULL);
2035	if (rval) {
2036		goto done;
2037	}
2038	blk = &state->path.blk[state->path.active - 1];
2039	ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2040	/*
2041	 * Add the new leaf entry.
2042	 */
2043	rval = xfs_dir2_leafn_add(blk->bp, args, blk->index);
2044	if (rval == 0) {
2045		/*
2046		 * It worked, fix the hash values up the btree.
2047		 */
2048		if (!(args->op_flags & XFS_DA_OP_JUSTCHECK))
2049			xfs_da3_fixhashpath(state, &state->path);
2050	} else {
2051		/*
2052		 * It didn't work, we need to split the leaf block.
2053		 */
2054		if (args->total == 0) {
2055			ASSERT(rval == -ENOSPC);
2056			goto done;
2057		}
2058		/*
2059		 * Split the leaf block and insert the new entry.
2060		 */
2061		rval = xfs_da3_split(state);
2062	}
2063done:
2064	xfs_da_state_free(state);
2065	return rval;
2066}
2067
2068/*
2069 * Lookup an entry in a node-format directory.
2070 * All the real work happens in xfs_da3_node_lookup_int.
2071 * The only real output is the inode number of the entry.
2072 */
2073int						/* error */
2074xfs_dir2_node_lookup(
2075	xfs_da_args_t	*args)			/* operation arguments */
2076{
2077	int		error;			/* error return value */
2078	int		i;			/* btree level */
2079	int		rval;			/* operation return value */
2080	xfs_da_state_t	*state;			/* btree cursor */
2081
2082	trace_xfs_dir2_node_lookup(args);
2083
2084	/*
2085	 * Allocate and initialize the btree cursor.
2086	 */
2087	state = xfs_da_state_alloc(args);
2088
2089	/*
2090	 * Fill in the path to the entry in the cursor.
2091	 */
2092	error = xfs_da3_node_lookup_int(state, &rval);
2093	if (error)
2094		rval = error;
2095	else if (rval == -ENOENT && args->cmpresult == XFS_CMP_CASE) {
2096		/* If a CI match, dup the actual name and return -EEXIST */
2097		xfs_dir2_data_entry_t	*dep;
2098
2099		dep = (xfs_dir2_data_entry_t *)
2100			((char *)state->extrablk.bp->b_addr +
2101						 state->extrablk.index);
2102		rval = xfs_dir_cilookup_result(args, dep->name, dep->namelen);
2103	}
2104	/*
2105	 * Release the btree blocks and leaf block.
2106	 */
2107	for (i = 0; i < state->path.active; i++) {
2108		xfs_trans_brelse(args->trans, state->path.blk[i].bp);
2109		state->path.blk[i].bp = NULL;
2110	}
2111	/*
2112	 * Release the data block if we have it.
2113	 */
2114	if (state->extravalid && state->extrablk.bp) {
2115		xfs_trans_brelse(args->trans, state->extrablk.bp);
2116		state->extrablk.bp = NULL;
2117	}
2118	xfs_da_state_free(state);
2119	return rval;
2120}
2121
2122/*
2123 * Remove an entry from a node-format directory.
2124 */
2125int						/* error */
2126xfs_dir2_node_removename(
2127	struct xfs_da_args	*args)		/* operation arguments */
2128{
2129	struct xfs_da_state_blk	*blk;		/* leaf block */
2130	int			error;		/* error return value */
2131	int			rval;		/* operation return value */
2132	struct xfs_da_state	*state;		/* btree cursor */
2133
2134	trace_xfs_dir2_node_removename(args);
2135
2136	/*
2137	 * Allocate and initialize the btree cursor.
2138	 */
2139	state = xfs_da_state_alloc(args);
2140
2141	/* Look up the entry we're deleting, set up the cursor. */
2142	error = xfs_da3_node_lookup_int(state, &rval);
2143	if (error)
2144		goto out_free;
2145
2146	/* Didn't find it, upper layer screwed up. */
2147	if (rval != -EEXIST) {
2148		error = rval;
2149		goto out_free;
2150	}
2151
2152	blk = &state->path.blk[state->path.active - 1];
2153	ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2154	ASSERT(state->extravalid);
2155	/*
2156	 * Remove the leaf and data entries.
2157	 * Extrablk refers to the data block.
2158	 */
2159	error = xfs_dir2_leafn_remove(args, blk->bp, blk->index,
2160		&state->extrablk, &rval);
2161	if (error)
2162		goto out_free;
2163	/*
2164	 * Fix the hash values up the btree.
2165	 */
2166	xfs_da3_fixhashpath(state, &state->path);
2167	/*
2168	 * If we need to join leaf blocks, do it.
2169	 */
2170	if (rval && state->path.active > 1)
2171		error = xfs_da3_join(state);
2172	/*
2173	 * If no errors so far, try conversion to leaf format.
2174	 */
2175	if (!error)
2176		error = xfs_dir2_node_to_leaf(state);
2177out_free:
2178	xfs_da_state_free(state);
2179	return error;
2180}
2181
2182/*
2183 * Replace an entry's inode number in a node-format directory.
2184 */
2185int						/* error */
2186xfs_dir2_node_replace(
2187	xfs_da_args_t		*args)		/* operation arguments */
2188{
2189	xfs_da_state_blk_t	*blk;		/* leaf block */
2190	xfs_dir2_data_hdr_t	*hdr;		/* data block header */
2191	xfs_dir2_data_entry_t	*dep;		/* data entry changed */
2192	int			error;		/* error return value */
2193	int			i;		/* btree level */
2194	xfs_ino_t		inum;		/* new inode number */
2195	int			ftype;		/* new file type */
2196	int			rval;		/* internal return value */
2197	xfs_da_state_t		*state;		/* btree cursor */
2198
2199	trace_xfs_dir2_node_replace(args);
2200
2201	/*
2202	 * Allocate and initialize the btree cursor.
2203	 */
2204	state = xfs_da_state_alloc(args);
2205
2206	/*
2207	 * We have to save new inode number and ftype since
2208	 * xfs_da3_node_lookup_int() is going to overwrite them
2209	 */
2210	inum = args->inumber;
2211	ftype = args->filetype;
2212
2213	/*
2214	 * Lookup the entry to change in the btree.
2215	 */
2216	error = xfs_da3_node_lookup_int(state, &rval);
2217	if (error) {
2218		rval = error;
2219	}
2220	/*
2221	 * It should be found, since the vnodeops layer has looked it up
2222	 * and locked it.  But paranoia is good.
2223	 */
2224	if (rval == -EEXIST) {
2225		struct xfs_dir3_icleaf_hdr	leafhdr;
2226
2227		/*
2228		 * Find the leaf entry.
2229		 */
2230		blk = &state->path.blk[state->path.active - 1];
2231		ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2232		ASSERT(state->extravalid);
2233
2234		xfs_dir2_leaf_hdr_from_disk(state->mp, &leafhdr,
2235					    blk->bp->b_addr);
2236		/*
2237		 * Point to the data entry.
2238		 */
2239		hdr = state->extrablk.bp->b_addr;
2240		ASSERT(hdr->magic == cpu_to_be32(XFS_DIR2_DATA_MAGIC) ||
2241		       hdr->magic == cpu_to_be32(XFS_DIR3_DATA_MAGIC));
2242		dep = (xfs_dir2_data_entry_t *)
2243		      ((char *)hdr +
2244		       xfs_dir2_dataptr_to_off(args->geo,
2245				be32_to_cpu(leafhdr.ents[blk->index].address)));
2246		ASSERT(inum != be64_to_cpu(dep->inumber));
2247		/*
2248		 * Fill in the new inode number and log the entry.
2249		 */
2250		dep->inumber = cpu_to_be64(inum);
2251		xfs_dir2_data_put_ftype(state->mp, dep, ftype);
2252		xfs_dir2_data_log_entry(args, state->extrablk.bp, dep);
2253		rval = 0;
2254	}
2255	/*
2256	 * Didn't find it, and we're holding a data block.  Drop it.
2257	 */
2258	else if (state->extravalid) {
2259		xfs_trans_brelse(args->trans, state->extrablk.bp);
2260		state->extrablk.bp = NULL;
2261	}
2262	/*
2263	 * Release all the buffers in the cursor.
2264	 */
2265	for (i = 0; i < state->path.active; i++) {
2266		xfs_trans_brelse(args->trans, state->path.blk[i].bp);
2267		state->path.blk[i].bp = NULL;
2268	}
2269	xfs_da_state_free(state);
2270	return rval;
2271}
2272
2273/*
2274 * Trim off a trailing empty freespace block.
2275 * Return (in rvalp) 1 if we did it, 0 if not.
2276 */
2277int						/* error */
2278xfs_dir2_node_trim_free(
2279	xfs_da_args_t		*args,		/* operation arguments */
2280	xfs_fileoff_t		fo,		/* free block number */
2281	int			*rvalp)		/* out: did something */
2282{
2283	struct xfs_buf		*bp;		/* freespace buffer */
2284	xfs_inode_t		*dp;		/* incore directory inode */
2285	int			error;		/* error return code */
2286	xfs_dir2_free_t		*free;		/* freespace structure */
2287	xfs_trans_t		*tp;		/* transaction pointer */
2288	struct xfs_dir3_icfree_hdr freehdr;
2289
2290	dp = args->dp;
2291	tp = args->trans;
2292
2293	*rvalp = 0;
2294
2295	/*
2296	 * Read the freespace block.
2297	 */
2298	error = xfs_dir2_free_try_read(tp, dp, fo, &bp);
2299	if (error)
2300		return error;
2301	/*
2302	 * There can be holes in freespace.  If fo is a hole, there's
2303	 * nothing to do.
2304	 */
2305	if (!bp)
2306		return 0;
2307	free = bp->b_addr;
2308	xfs_dir2_free_hdr_from_disk(dp->i_mount, &freehdr, free);
2309
2310	/*
2311	 * If there are used entries, there's nothing to do.
2312	 */
2313	if (freehdr.nused > 0) {
2314		xfs_trans_brelse(tp, bp);
2315		return 0;
2316	}
2317	/*
2318	 * Blow the block away.
2319	 */
2320	error = xfs_dir2_shrink_inode(args,
2321			xfs_dir2_da_to_db(args->geo, (xfs_dablk_t)fo), bp);
2322	if (error) {
2323		/*
2324		 * Can't fail with ENOSPC since that only happens with no
2325		 * space reservation, when breaking up an extent into two
2326		 * pieces.  This is the last block of an extent.
2327		 */
2328		ASSERT(error != -ENOSPC);
2329		xfs_trans_brelse(tp, bp);
2330		return error;
2331	}
2332	/*
2333	 * Return that we succeeded.
2334	 */
2335	*rvalp = 1;
2336	return 0;
2337}