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