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