xref: /linux/fs/xfs/libxfs/xfs_attr_leaf.c (revision ce58cff1077dfb9ec3d0e6f5da1b06a85be035bb)
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_platform.h"
8 #include "xfs_fs.h"
9 #include "xfs_shared.h"
10 #include "xfs_format.h"
11 #include "xfs_log_format.h"
12 #include "xfs_trans_resv.h"
13 #include "xfs_sb.h"
14 #include "xfs_mount.h"
15 #include "xfs_da_format.h"
16 #include "xfs_da_btree.h"
17 #include "xfs_inode.h"
18 #include "xfs_trans.h"
19 #include "xfs_bmap_btree.h"
20 #include "xfs_bmap.h"
21 #include "xfs_attr_sf.h"
22 #include "xfs_attr.h"
23 #include "xfs_attr_remote.h"
24 #include "xfs_attr_leaf.h"
25 #include "xfs_error.h"
26 #include "xfs_trace.h"
27 #include "xfs_buf_item.h"
28 #include "xfs_dir2.h"
29 #include "xfs_log.h"
30 #include "xfs_ag.h"
31 #include "xfs_errortag.h"
32 #include "xfs_health.h"
33 
34 
35 /*
36  * xfs_attr_leaf.c
37  *
38  * Routines to implement leaf blocks of attributes as Btrees of hashed names.
39  */
40 
41 /*========================================================================
42  * Function prototypes for the kernel.
43  *========================================================================*/
44 
45 /*
46  * Routines used for growing the Btree.
47  */
48 STATIC int xfs_attr3_leaf_create(struct xfs_da_args *args,
49 				 xfs_dablk_t which_block, struct xfs_buf **bpp);
50 STATIC void xfs_attr3_leaf_add_work(struct xfs_buf *leaf_buffer,
51 				   struct xfs_attr3_icleaf_hdr *ichdr,
52 				   struct xfs_da_args *args, int freemap_index);
53 STATIC void xfs_attr3_leaf_compact(struct xfs_da_args *args,
54 				   struct xfs_attr3_icleaf_hdr *ichdr,
55 				   struct xfs_buf *leaf_buffer);
56 STATIC void xfs_attr3_leaf_rebalance(xfs_da_state_t *state,
57 						   xfs_da_state_blk_t *blk1,
58 						   xfs_da_state_blk_t *blk2);
59 STATIC int xfs_attr3_leaf_figure_balance(xfs_da_state_t *state,
60 			xfs_da_state_blk_t *leaf_blk_1,
61 			struct xfs_attr3_icleaf_hdr *ichdr1,
62 			xfs_da_state_blk_t *leaf_blk_2,
63 			struct xfs_attr3_icleaf_hdr *ichdr2,
64 			int *number_entries_in_blk1,
65 			int *number_usedbytes_in_blk1);
66 
67 /*
68  * Utility routines.
69  */
70 STATIC void xfs_attr3_leaf_moveents(struct xfs_da_args *args,
71 			struct xfs_attr_leafblock *src_leaf,
72 			struct xfs_attr3_icleaf_hdr *src_ichdr, int src_start,
73 			struct xfs_attr_leafblock *dst_leaf,
74 			struct xfs_attr3_icleaf_hdr *dst_ichdr, int dst_start,
75 			int move_count);
76 STATIC int xfs_attr_leaf_entsize(xfs_attr_leafblock_t *leaf, int index);
77 
78 /* Compute the byte offset of the end of the leaf entry array. */
79 static inline int
80 xfs_attr_leaf_entries_end(
81 	unsigned int			hdrcount,
82 	const struct xfs_attr_leafblock	*leaf)
83 {
84 	return hdrcount * sizeof(struct xfs_attr_leaf_entry) +
85 			xfs_attr3_leaf_hdr_size(leaf);
86 }
87 
88 static inline bool
89 ichdr_freemaps_overlap(
90 	const struct xfs_attr3_icleaf_hdr	*ichdr,
91 	unsigned int				x,
92 	unsigned int				y)
93 {
94 	const unsigned int			xend =
95 		ichdr->freemap[x].base + ichdr->freemap[x].size;
96 	const unsigned int			yend =
97 		ichdr->freemap[y].base + ichdr->freemap[y].size;
98 
99 	/* empty slots do not overlap */
100 	if (!ichdr->freemap[x].size || !ichdr->freemap[y].size)
101 		return false;
102 
103 	return ichdr->freemap[x].base < yend && xend > ichdr->freemap[y].base;
104 }
105 
106 static inline xfs_failaddr_t
107 xfs_attr_leaf_ichdr_freemaps_verify(
108 	const struct xfs_attr3_icleaf_hdr	*ichdr,
109 	const struct xfs_attr_leafblock		*leaf)
110 {
111 	unsigned int				entries_end =
112 		xfs_attr_leaf_entries_end(ichdr->count, leaf);
113 	int					i;
114 
115 	if (ichdr_freemaps_overlap(ichdr, 0, 1))
116 		return __this_address;
117 	if (ichdr_freemaps_overlap(ichdr, 0, 2))
118 		return __this_address;
119 	if (ichdr_freemaps_overlap(ichdr, 1, 2))
120 		return __this_address;
121 
122 	for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
123 		if (ichdr->freemap[i].size > 0 &&
124 		    ichdr->freemap[i].base < entries_end)
125 			return __this_address;
126 	}
127 
128 	return NULL;
129 }
130 
131 /*
132  * attr3 block 'firstused' conversion helpers.
133  *
134  * firstused refers to the offset of the first used byte of the nameval region
135  * of an attr leaf block. The region starts at the tail of the block and expands
136  * backwards towards the middle. As such, firstused is initialized to the block
137  * size for an empty leaf block and is reduced from there.
138  *
139  * The attr3 block size is pegged to the fsb size and the maximum fsb is 64k.
140  * The in-core firstused field is 32-bit and thus supports the maximum fsb size.
141  * The on-disk field is only 16-bit, however, and overflows at 64k. Since this
142  * only occurs at exactly 64k, we use zero as a magic on-disk value to represent
143  * the attr block size. The following helpers manage the conversion between the
144  * in-core and on-disk formats.
145  */
146 
147 static void
148 xfs_attr3_leaf_firstused_from_disk(
149 	struct xfs_da_geometry		*geo,
150 	struct xfs_attr3_icleaf_hdr	*to,
151 	struct xfs_attr_leafblock	*from)
152 {
153 	struct xfs_attr3_leaf_hdr	*hdr3;
154 
155 	if (from->hdr.info.magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC)) {
156 		hdr3 = (struct xfs_attr3_leaf_hdr *) from;
157 		to->firstused = be16_to_cpu(hdr3->firstused);
158 	} else {
159 		to->firstused = be16_to_cpu(from->hdr.firstused);
160 	}
161 
162 	/*
163 	 * Convert from the magic fsb size value to actual blocksize. This
164 	 * should only occur for empty blocks when the block size overflows
165 	 * 16-bits.
166 	 */
167 	if (to->firstused == XFS_ATTR3_LEAF_NULLOFF) {
168 		ASSERT(!to->count && !to->usedbytes);
169 		ASSERT(geo->blksize > USHRT_MAX);
170 		to->firstused = geo->blksize;
171 	}
172 }
173 
174 static void
175 xfs_attr3_leaf_firstused_to_disk(
176 	struct xfs_da_geometry		*geo,
177 	struct xfs_attr_leafblock	*to,
178 	struct xfs_attr3_icleaf_hdr	*from)
179 {
180 	struct xfs_attr3_leaf_hdr	*hdr3;
181 	uint32_t			firstused;
182 
183 	/* magic value should only be seen on disk */
184 	ASSERT(from->firstused != XFS_ATTR3_LEAF_NULLOFF);
185 
186 	/*
187 	 * Scale down the 32-bit in-core firstused value to the 16-bit on-disk
188 	 * value. This only overflows at the max supported value of 64k. Use the
189 	 * magic on-disk value to represent block size in this case.
190 	 */
191 	firstused = from->firstused;
192 	if (firstused > USHRT_MAX) {
193 		ASSERT(from->firstused == geo->blksize);
194 		firstused = XFS_ATTR3_LEAF_NULLOFF;
195 	}
196 
197 	if (from->magic == XFS_ATTR3_LEAF_MAGIC) {
198 		hdr3 = (struct xfs_attr3_leaf_hdr *) to;
199 		hdr3->firstused = cpu_to_be16(firstused);
200 	} else {
201 		to->hdr.firstused = cpu_to_be16(firstused);
202 	}
203 }
204 
205 void
206 xfs_attr3_leaf_hdr_from_disk(
207 	struct xfs_da_geometry		*geo,
208 	struct xfs_attr3_icleaf_hdr	*to,
209 	struct xfs_attr_leafblock	*from)
210 {
211 	int	i;
212 
213 	ASSERT(from->hdr.info.magic == cpu_to_be16(XFS_ATTR_LEAF_MAGIC) ||
214 	       from->hdr.info.magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC));
215 
216 	if (from->hdr.info.magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC)) {
217 		struct xfs_attr3_leaf_hdr *hdr3 = (struct xfs_attr3_leaf_hdr *)from;
218 
219 		to->forw = be32_to_cpu(hdr3->info.hdr.forw);
220 		to->back = be32_to_cpu(hdr3->info.hdr.back);
221 		to->magic = be16_to_cpu(hdr3->info.hdr.magic);
222 		to->count = be16_to_cpu(hdr3->count);
223 		to->usedbytes = be16_to_cpu(hdr3->usedbytes);
224 		xfs_attr3_leaf_firstused_from_disk(geo, to, from);
225 		to->holes = hdr3->holes;
226 
227 		for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
228 			to->freemap[i].base = be16_to_cpu(hdr3->freemap[i].base);
229 			to->freemap[i].size = be16_to_cpu(hdr3->freemap[i].size);
230 		}
231 		return;
232 	}
233 	to->forw = be32_to_cpu(from->hdr.info.forw);
234 	to->back = be32_to_cpu(from->hdr.info.back);
235 	to->magic = be16_to_cpu(from->hdr.info.magic);
236 	to->count = be16_to_cpu(from->hdr.count);
237 	to->usedbytes = be16_to_cpu(from->hdr.usedbytes);
238 	xfs_attr3_leaf_firstused_from_disk(geo, to, from);
239 	to->holes = from->hdr.holes;
240 
241 	for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
242 		to->freemap[i].base = be16_to_cpu(from->hdr.freemap[i].base);
243 		to->freemap[i].size = be16_to_cpu(from->hdr.freemap[i].size);
244 	}
245 }
246 
247 void
248 xfs_attr3_leaf_hdr_to_disk(
249 	struct xfs_da_geometry		*geo,
250 	struct xfs_attr_leafblock	*to,
251 	struct xfs_attr3_icleaf_hdr	*from)
252 {
253 	int				i;
254 
255 	ASSERT(from->magic == XFS_ATTR_LEAF_MAGIC ||
256 	       from->magic == XFS_ATTR3_LEAF_MAGIC);
257 
258 	if (from->magic == XFS_ATTR3_LEAF_MAGIC) {
259 		struct xfs_attr3_leaf_hdr *hdr3 = (struct xfs_attr3_leaf_hdr *)to;
260 
261 		hdr3->info.hdr.forw = cpu_to_be32(from->forw);
262 		hdr3->info.hdr.back = cpu_to_be32(from->back);
263 		hdr3->info.hdr.magic = cpu_to_be16(from->magic);
264 		hdr3->count = cpu_to_be16(from->count);
265 		hdr3->usedbytes = cpu_to_be16(from->usedbytes);
266 		xfs_attr3_leaf_firstused_to_disk(geo, to, from);
267 		hdr3->holes = from->holes;
268 		hdr3->pad1 = 0;
269 
270 		for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
271 			hdr3->freemap[i].base = cpu_to_be16(from->freemap[i].base);
272 			hdr3->freemap[i].size = cpu_to_be16(from->freemap[i].size);
273 		}
274 
275 		ASSERT(xfs_attr_leaf_ichdr_freemaps_verify(from, to) == NULL);
276 		return;
277 	}
278 	to->hdr.info.forw = cpu_to_be32(from->forw);
279 	to->hdr.info.back = cpu_to_be32(from->back);
280 	to->hdr.info.magic = cpu_to_be16(from->magic);
281 	to->hdr.count = cpu_to_be16(from->count);
282 	to->hdr.usedbytes = cpu_to_be16(from->usedbytes);
283 	xfs_attr3_leaf_firstused_to_disk(geo, to, from);
284 	to->hdr.holes = from->holes;
285 	to->hdr.pad1 = 0;
286 
287 	for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
288 		to->hdr.freemap[i].base = cpu_to_be16(from->freemap[i].base);
289 		to->hdr.freemap[i].size = cpu_to_be16(from->freemap[i].size);
290 	}
291 
292 	ASSERT(xfs_attr_leaf_ichdr_freemaps_verify(from, to) == NULL);
293 }
294 
295 static xfs_failaddr_t
296 xfs_attr3_leaf_verify_entry(
297 	struct xfs_mount			*mp,
298 	char					*buf_end,
299 	struct xfs_attr_leafblock		*leaf,
300 	struct xfs_attr3_icleaf_hdr		*leafhdr,
301 	struct xfs_attr_leaf_entry		*ent,
302 	int					idx,
303 	__u32					*last_hashval)
304 {
305 	struct xfs_attr_leaf_name_local		*lentry;
306 	struct xfs_attr_leaf_name_remote	*rentry;
307 	char					*name_end;
308 	unsigned int				nameidx;
309 	unsigned int				namesize;
310 	__u32					hashval;
311 
312 	/* hash order check */
313 	hashval = be32_to_cpu(ent->hashval);
314 	if (hashval < *last_hashval)
315 		return __this_address;
316 	*last_hashval = hashval;
317 
318 	nameidx = be16_to_cpu(ent->nameidx);
319 	if (nameidx < leafhdr->firstused || nameidx >= mp->m_attr_geo->blksize)
320 		return __this_address;
321 
322 	/*
323 	 * Check the name information.  The namelen fields are u8 so we can't
324 	 * possibly exceed the maximum name length of 255 bytes.
325 	 */
326 	if (ent->flags & XFS_ATTR_LOCAL) {
327 		lentry = xfs_attr3_leaf_name_local(leaf, idx);
328 
329 		/* Validate lentry pointer is within bounds before field access */
330 		if ((char *)lentry >= buf_end)
331 			return __this_address;
332 		if ((char *)lentry + offsetof(struct xfs_attr_leaf_name_local, nameval) > buf_end)
333 			return __this_address;
334 
335 		namesize = xfs_attr_leaf_entsize_local(lentry->namelen,
336 				be16_to_cpu(lentry->valuelen));
337 		name_end = (char *)lentry + namesize;
338 		if (lentry->namelen == 0)
339 			return __this_address;
340 	} else {
341 		rentry = xfs_attr3_leaf_name_remote(leaf, idx);
342 
343 		/* Validate rentry pointer is within bounds before field access */
344 		if ((char *)rentry >= buf_end)
345 			return __this_address;
346 		if ((char *)rentry + offsetof(struct xfs_attr_leaf_name_remote, name) > buf_end)
347 			return __this_address;
348 
349 		namesize = xfs_attr_leaf_entsize_remote(rentry->namelen);
350 		name_end = (char *)rentry + namesize;
351 		if (rentry->namelen == 0)
352 			return __this_address;
353 		if (!(ent->flags & XFS_ATTR_INCOMPLETE) &&
354 		    rentry->valueblk == 0)
355 			return __this_address;
356 		if (be32_to_cpu(rentry->valuelen) > XFS_XATTR_SIZE_MAX)
357 			return __this_address;
358 	}
359 
360 	if (name_end > buf_end)
361 		return __this_address;
362 
363 	return NULL;
364 }
365 
366 /*
367  * Validate an attribute leaf block.
368  *
369  * Empty leaf blocks can occur under the following circumstances:
370  *
371  * 1. setxattr adds a new extended attribute to a file;
372  * 2. The file has zero existing attributes;
373  * 3. The attribute is too large to fit in the attribute fork;
374  * 4. The attribute is small enough to fit in a leaf block;
375  * 5. A log flush occurs after committing the transaction that creates
376  *    the (empty) leaf block; and
377  * 6. The filesystem goes down after the log flush but before the new
378  *    attribute can be committed to the leaf block.
379  *
380  * Hence we need to ensure that we don't fail the validation purely
381  * because the leaf is empty.
382  */
383 static xfs_failaddr_t
384 xfs_attr3_leaf_verify(
385 	struct xfs_buf			*bp)
386 {
387 	struct xfs_attr3_icleaf_hdr	ichdr;
388 	struct xfs_mount		*mp = bp->b_mount;
389 	struct xfs_attr_leafblock	*leaf = bp->b_addr;
390 	struct xfs_attr_leaf_entry	*entries;
391 	struct xfs_attr_leaf_entry	*ent;
392 	char				*buf_end;
393 	uint32_t			end;	/* must be 32bit - see below */
394 	__u32				last_hashval = 0;
395 	int				i;
396 	xfs_failaddr_t			fa;
397 
398 	xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &ichdr, leaf);
399 
400 	fa = xfs_da3_blkinfo_verify(bp, bp->b_addr);
401 	if (fa)
402 		return fa;
403 
404 	/*
405 	 * firstused is the block offset of the first name info structure.
406 	 * Make sure it doesn't go off the block or crash into the header.
407 	 */
408 	if (ichdr.firstused > mp->m_attr_geo->blksize)
409 		return __this_address;
410 	if (ichdr.firstused < xfs_attr3_leaf_hdr_size(leaf))
411 		return __this_address;
412 
413 	/* Make sure the entries array doesn't crash into the name info. */
414 	entries = xfs_attr3_leaf_entryp(bp->b_addr);
415 	if ((char *)&entries[ichdr.count] >
416 	    (char *)bp->b_addr + ichdr.firstused)
417 		return __this_address;
418 
419 	/*
420 	 * NOTE: This verifier historically failed empty leaf buffers because
421 	 * we expect the fork to be in another format. Empty attr fork format
422 	 * conversions are possible during xattr set, however, and format
423 	 * conversion is not atomic with the xattr set that triggers it. We
424 	 * cannot assume leaf blocks are non-empty until that is addressed.
425 	*/
426 	buf_end = (char *)bp->b_addr + mp->m_attr_geo->blksize;
427 	for (i = 0, ent = entries; i < ichdr.count; ent++, i++) {
428 		fa = xfs_attr3_leaf_verify_entry(mp, buf_end, leaf, &ichdr,
429 				ent, i, &last_hashval);
430 		if (fa)
431 			return fa;
432 	}
433 
434 	/*
435 	 * Quickly check the freemap information.  Attribute data has to be
436 	 * aligned to 4-byte boundaries, and likewise for the free space.
437 	 *
438 	 * Note that for 64k block size filesystems, the freemap entries cannot
439 	 * overflow as they are only be16 fields. However, when checking end
440 	 * pointer of the freemap, we have to be careful to detect overflows and
441 	 * so use uint32_t for those checks.
442 	 */
443 	for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
444 		if (ichdr.freemap[i].base > mp->m_attr_geo->blksize)
445 			return __this_address;
446 		if (ichdr.freemap[i].base & 0x3)
447 			return __this_address;
448 		if (ichdr.freemap[i].size > mp->m_attr_geo->blksize)
449 			return __this_address;
450 		if (ichdr.freemap[i].size & 0x3)
451 			return __this_address;
452 
453 		/* be care of 16 bit overflows here */
454 		end = (uint32_t)ichdr.freemap[i].base + ichdr.freemap[i].size;
455 		if (end < ichdr.freemap[i].base)
456 			return __this_address;
457 		if (end > mp->m_attr_geo->blksize)
458 			return __this_address;
459 	}
460 
461 	fa = xfs_attr_leaf_ichdr_freemaps_verify(&ichdr, leaf);
462 	if (fa)
463 		return fa;
464 
465 	return NULL;
466 }
467 
468 xfs_failaddr_t
469 xfs_attr3_leaf_header_check(
470 	struct xfs_buf		*bp,
471 	xfs_ino_t		owner)
472 {
473 	struct xfs_mount	*mp = bp->b_mount;
474 
475 	if (xfs_has_crc(mp)) {
476 		struct xfs_attr3_leafblock *hdr3 = bp->b_addr;
477 
478 		if (hdr3->hdr.info.hdr.magic !=
479 				cpu_to_be16(XFS_ATTR3_LEAF_MAGIC))
480 			return __this_address;
481 
482 		if (be64_to_cpu(hdr3->hdr.info.owner) != owner)
483 			return __this_address;
484 	}
485 
486 	return NULL;
487 }
488 
489 static void
490 xfs_attr3_leaf_write_verify(
491 	struct xfs_buf	*bp)
492 {
493 	struct xfs_mount	*mp = bp->b_mount;
494 	struct xfs_buf_log_item	*bip = bp->b_log_item;
495 	struct xfs_attr3_leaf_hdr *hdr3 = bp->b_addr;
496 	xfs_failaddr_t		fa;
497 
498 	fa = xfs_attr3_leaf_verify(bp);
499 	if (fa) {
500 		xfs_verifier_error(bp, -EFSCORRUPTED, fa);
501 		return;
502 	}
503 
504 	if (!xfs_has_crc(mp))
505 		return;
506 
507 	if (bip)
508 		hdr3->info.lsn = cpu_to_be64(bip->bli_item.li_lsn);
509 
510 	xfs_buf_update_cksum(bp, XFS_ATTR3_LEAF_CRC_OFF);
511 }
512 
513 /*
514  * leaf/node format detection on trees is sketchy, so a node read can be done on
515  * leaf level blocks when detection identifies the tree as a node format tree
516  * incorrectly. In this case, we need to swap the verifier to match the correct
517  * format of the block being read.
518  */
519 static void
520 xfs_attr3_leaf_read_verify(
521 	struct xfs_buf		*bp)
522 {
523 	struct xfs_mount	*mp = bp->b_mount;
524 	xfs_failaddr_t		fa;
525 
526 	if (xfs_has_crc(mp) &&
527 	     !xfs_buf_verify_cksum(bp, XFS_ATTR3_LEAF_CRC_OFF))
528 		xfs_verifier_error(bp, -EFSBADCRC, __this_address);
529 	else {
530 		fa = xfs_attr3_leaf_verify(bp);
531 		if (fa)
532 			xfs_verifier_error(bp, -EFSCORRUPTED, fa);
533 	}
534 }
535 
536 const struct xfs_buf_ops xfs_attr3_leaf_buf_ops = {
537 	.name = "xfs_attr3_leaf",
538 	.magic16 = { cpu_to_be16(XFS_ATTR_LEAF_MAGIC),
539 		     cpu_to_be16(XFS_ATTR3_LEAF_MAGIC) },
540 	.verify_read = xfs_attr3_leaf_read_verify,
541 	.verify_write = xfs_attr3_leaf_write_verify,
542 	.verify_struct = xfs_attr3_leaf_verify,
543 };
544 
545 int
546 xfs_attr3_leaf_read(
547 	struct xfs_trans	*tp,
548 	struct xfs_inode	*dp,
549 	xfs_ino_t		owner,
550 	xfs_dablk_t		bno,
551 	struct xfs_buf		**bpp)
552 {
553 	xfs_failaddr_t		fa;
554 	int			err;
555 
556 	err = xfs_da_read_buf(tp, dp, bno, 0, bpp, XFS_ATTR_FORK,
557 			&xfs_attr3_leaf_buf_ops);
558 	if (err || !(*bpp))
559 		return err;
560 
561 	fa = xfs_attr3_leaf_header_check(*bpp, owner);
562 	if (fa) {
563 		__xfs_buf_mark_corrupt(*bpp, fa);
564 		xfs_trans_brelse(tp, *bpp);
565 		*bpp = NULL;
566 		xfs_dirattr_mark_sick(dp, XFS_ATTR_FORK);
567 		return -EFSCORRUPTED;
568 	}
569 
570 	if (tp)
571 		xfs_trans_buf_set_type(tp, *bpp, XFS_BLFT_ATTR_LEAF_BUF);
572 	return 0;
573 }
574 
575 /*========================================================================
576  * Namespace helper routines
577  *========================================================================*/
578 
579 /*
580  * If we are in log recovery, then we want the lookup to ignore the INCOMPLETE
581  * flag on disk - if there's an incomplete attr then recovery needs to tear it
582  * down. If there's no incomplete attr, then recovery needs to tear that attr
583  * down to replace it with the attr that has been logged. In this case, the
584  * INCOMPLETE flag will not be set in attr->attr_filter, but rather
585  * XFS_DA_OP_RECOVERY will be set in args->op_flags.
586  */
587 static inline unsigned int xfs_attr_match_mask(const struct xfs_da_args *args)
588 {
589 	if (args->op_flags & XFS_DA_OP_RECOVERY)
590 		return XFS_ATTR_NSP_ONDISK_MASK;
591 	return XFS_ATTR_NSP_ONDISK_MASK | XFS_ATTR_INCOMPLETE;
592 }
593 
594 static inline bool
595 xfs_attr_parent_match(
596 	const struct xfs_da_args	*args,
597 	const void			*value,
598 	unsigned int			valuelen)
599 {
600 	ASSERT(args->value != NULL);
601 
602 	/* Parent pointers do not use remote values */
603 	if (!value)
604 		return false;
605 
606 	/*
607 	 * The only value we support is a parent rec.  However, we'll accept
608 	 * any valuelen so that offline repair can delete ATTR_PARENT values
609 	 * that are not parent pointers.
610 	 */
611 	if (valuelen != args->valuelen)
612 		return false;
613 
614 	return memcmp(args->value, value, valuelen) == 0;
615 }
616 
617 static bool
618 xfs_attr_match(
619 	struct xfs_da_args	*args,
620 	unsigned int		attr_flags,
621 	const unsigned char	*name,
622 	unsigned int		namelen,
623 	const void		*value,
624 	unsigned int		valuelen)
625 {
626 	unsigned int		mask = xfs_attr_match_mask(args);
627 
628 	if (args->namelen != namelen)
629 		return false;
630 	if ((args->attr_filter & mask) != (attr_flags & mask))
631 		return false;
632 	if (memcmp(args->name, name, namelen) != 0)
633 		return false;
634 
635 	if (attr_flags & XFS_ATTR_PARENT)
636 		return xfs_attr_parent_match(args, value, valuelen);
637 
638 	return true;
639 }
640 
641 static int
642 xfs_attr_copy_value(
643 	struct xfs_da_args	*args,
644 	unsigned char		*value,
645 	int			valuelen)
646 {
647 	/*
648 	 * A value length that is negative or larger than the maximum xattr
649 	 * size is on-disk corruption.  The remote value length is an on-disk
650 	 * __be32 stored into the signed args->rmtvaluelen, so a crafted value
651 	 * such as 0x80000000 becomes negative and would slip past the
652 	 * "args->valuelen < valuelen" check below and be used as a copy
653 	 * length.  Reject it before that can happen.
654 	 */
655 	if (valuelen < 0 || valuelen > XFS_XATTR_SIZE_MAX)
656 		return -EFSCORRUPTED;
657 
658 	/*
659 	 * Parent pointer lookups require the caller to specify the name and
660 	 * value, so don't copy anything.
661 	 */
662 	if (args->attr_filter & XFS_ATTR_PARENT)
663 		return 0;
664 
665 	/*
666 	 * No copy if all we have to do is get the length
667 	 */
668 	if (!args->valuelen) {
669 		args->valuelen = valuelen;
670 		return 0;
671 	}
672 
673 	/*
674 	 * No copy if the length of the existing buffer is too small
675 	 */
676 	if (args->valuelen < valuelen) {
677 		args->valuelen = valuelen;
678 		return -ERANGE;
679 	}
680 
681 	if (!args->value) {
682 		args->value = kvmalloc(valuelen, GFP_KERNEL | __GFP_NOLOCKDEP);
683 		if (!args->value)
684 			return -ENOMEM;
685 	}
686 	args->valuelen = valuelen;
687 
688 	/* remote block xattr requires IO for copy-in */
689 	if (args->rmtblkno)
690 		return xfs_attr_rmtval_get(args);
691 
692 	/*
693 	 * This is to prevent a GCC warning because the remote xattr case
694 	 * doesn't have a value to pass in. In that case, we never reach here,
695 	 * but GCC can't work that out and so throws a "passing NULL to
696 	 * memcpy" warning.
697 	 */
698 	if (!value)
699 		return -EINVAL;
700 	memcpy(args->value, value, valuelen);
701 	return 0;
702 }
703 
704 /*========================================================================
705  * External routines when attribute fork size < XFS_LITINO(mp).
706  *========================================================================*/
707 
708 /*
709  * Query whether the total requested number of attr fork bytes of extended
710  * attribute space will be able to fit inline.
711  *
712  * Returns zero if not, else the i_forkoff fork offset to be used in the
713  * literal area for attribute data once the new bytes have been added.
714  *
715  * i_forkoff must be 8 byte aligned, hence is stored as a >>3 value;
716  * special case for dev/uuid inodes, they have fixed size data forks.
717  */
718 int
719 xfs_attr_shortform_bytesfit(
720 	struct xfs_inode	*dp,
721 	int			bytes)
722 {
723 	struct xfs_mount	*mp = dp->i_mount;
724 	int64_t			dsize;
725 	int			minforkoff;
726 	int			maxforkoff;
727 	int			offset;
728 
729 	/*
730 	 * Check if the new size could fit at all first:
731 	 */
732 	if (bytes > XFS_LITINO(mp))
733 		return 0;
734 
735 	/* rounded down */
736 	offset = XFS_B_TO_FORKOFFT(XFS_LITINO(mp) - bytes);
737 
738 	if (dp->i_df.if_format == XFS_DINODE_FMT_DEV) {
739 		minforkoff = XFS_B_TO_FORKOFF(sizeof(xfs_dev_t));
740 		return (offset >= minforkoff) ? minforkoff : 0;
741 	}
742 
743 	/*
744 	 * If the requested numbers of bytes is smaller or equal to the
745 	 * current attribute fork size we can always proceed.
746 	 *
747 	 * Note that if_bytes in the data fork might actually be larger than
748 	 * the current data fork size is due to delalloc extents. In that
749 	 * case either the extent count will go down when they are converted
750 	 * to real extents, or the delalloc conversion will take care of the
751 	 * literal area rebalancing.
752 	 */
753 	if (bytes <= xfs_inode_attr_fork_size(dp))
754 		return dp->i_forkoff;
755 
756 	/*
757 	 * For attr2 we can try to move the forkoff if there is space in the
758 	 * literal area
759 	 */
760 	dsize = dp->i_df.if_bytes;
761 
762 	switch (dp->i_df.if_format) {
763 	case XFS_DINODE_FMT_EXTENTS:
764 		/*
765 		 * If there is no attr fork and the data fork is extents,
766 		 * determine if creating the default attr fork will result
767 		 * in the extents form migrating to btree. If so, the
768 		 * minimum offset only needs to be the space required for
769 		 * the btree root.
770 		 */
771 		if (!dp->i_forkoff && dp->i_df.if_bytes >
772 		    xfs_default_attroffset(dp))
773 			dsize = xfs_bmdr_space_calc(MINDBTPTRS);
774 		break;
775 	case XFS_DINODE_FMT_BTREE:
776 		/*
777 		 * If we have a data btree then keep forkoff if we have one,
778 		 * otherwise we are adding a new attr, so then we set
779 		 * minforkoff to where the btree root can finish so we have
780 		 * plenty of room for attrs
781 		 */
782 		if (dp->i_forkoff) {
783 			if (offset < dp->i_forkoff)
784 				return 0;
785 			return dp->i_forkoff;
786 		}
787 		dsize = xfs_bmap_bmdr_space(dp->i_df.if_broot);
788 		break;
789 	}
790 
791 	/*
792 	 * A data fork btree root must have space for at least
793 	 * MINDBTPTRS key/ptr pairs if the data fork is small or empty.
794 	 */
795 	minforkoff = XFS_B_TO_FORKOFF(
796 			max_t(int64_t, dsize, xfs_bmdr_space_calc(MINDBTPTRS)));
797 
798 	/* attr fork btree root can have at least this many key/ptr pairs */
799 	maxforkoff = XFS_B_TO_FORKOFFT(
800 			XFS_LITINO(mp) - xfs_bmdr_space_calc(MINABTPTRS));
801 
802 	if (offset >= maxforkoff)
803 		return maxforkoff;
804 	if (offset >= minforkoff)
805 		return offset;
806 	return 0;
807 }
808 
809 /*
810  * Switch on the ATTR2 superblock bit (implies also FEATURES2) unless
811  * on-disk version bit says it is already set
812  */
813 STATIC void
814 xfs_sbversion_add_attr2(
815 	struct xfs_mount	*mp,
816 	struct xfs_trans	*tp)
817 {
818 	if (mp->m_sb.sb_features2 & XFS_SB_VERSION2_ATTR2BIT)
819 		return;
820 
821 	spin_lock(&mp->m_sb_lock);
822 	xfs_add_attr2(mp);
823 	spin_unlock(&mp->m_sb_lock);
824 	xfs_log_sb(tp);
825 }
826 
827 /*
828  * Create the initial contents of a shortform attribute list.
829  */
830 void
831 xfs_attr_shortform_create(
832 	struct xfs_da_args	*args)
833 {
834 	struct xfs_inode	*dp = args->dp;
835 	struct xfs_ifork	*ifp = &dp->i_af;
836 	struct xfs_attr_sf_hdr	*hdr;
837 
838 	trace_xfs_attr_sf_create(args);
839 
840 	ASSERT(ifp->if_bytes == 0);
841 	if (ifp->if_format == XFS_DINODE_FMT_EXTENTS)
842 		ifp->if_format = XFS_DINODE_FMT_LOCAL;
843 
844 	hdr = xfs_idata_realloc(dp, sizeof(*hdr), XFS_ATTR_FORK);
845 	memset(hdr, 0, sizeof(*hdr));
846 	hdr->totsize = cpu_to_be16(sizeof(*hdr));
847 	xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_ADATA);
848 }
849 
850 /*
851  * Return the entry if the attr in args is found, or NULL if not.
852  */
853 struct xfs_attr_sf_entry *
854 xfs_attr_sf_findname(
855 	struct xfs_da_args		*args)
856 {
857 	struct xfs_attr_sf_hdr		*sf = args->dp->i_af.if_data;
858 	struct xfs_attr_sf_entry	*sfe;
859 
860 	for (sfe = xfs_attr_sf_firstentry(sf);
861 	     sfe < xfs_attr_sf_endptr(sf);
862 	     sfe = xfs_attr_sf_nextentry(sfe)) {
863 		if (xfs_attr_match(args, sfe->flags, sfe->nameval,
864 				sfe->namelen, &sfe->nameval[sfe->namelen],
865 				sfe->valuelen))
866 			return sfe;
867 	}
868 
869 	return NULL;
870 }
871 
872 /*
873  * Replace a shortform xattr if it's the right length.  Returns 0 on success,
874  * -ENOSPC if the length is wrong, or -ENOATTR if the attr was not found.
875  */
876 int
877 xfs_attr_shortform_replace(
878 	struct xfs_da_args		*args)
879 {
880 	struct xfs_attr_sf_entry	*sfe;
881 
882 	ASSERT(args->dp->i_af.if_format == XFS_DINODE_FMT_LOCAL);
883 
884 	trace_xfs_attr_sf_replace(args);
885 
886 	sfe = xfs_attr_sf_findname(args);
887 	if (!sfe)
888 		return -ENOATTR;
889 
890 	if (args->attr_filter & XFS_ATTR_PARENT) {
891 		if (sfe->namelen != args->new_namelen ||
892 		    sfe->valuelen != args->new_valuelen)
893 			return -ENOSPC;
894 
895 		memcpy(sfe->nameval, args->new_name, sfe->namelen);
896 		memcpy(&sfe->nameval[sfe->namelen], args->new_value,
897 				sfe->valuelen);
898 	} else {
899 		if (sfe->valuelen != args->valuelen)
900 			return -ENOSPC;
901 		memcpy(&sfe->nameval[sfe->namelen], args->value,
902 				sfe->valuelen);
903 	}
904 
905 	xfs_trans_log_inode(args->trans, args->dp,
906 			XFS_ILOG_CORE | XFS_ILOG_ADATA);
907 	return 0;
908 }
909 
910 /*
911  * Add a name/value pair to the shortform attribute list.
912  * Overflow from the inode has already been checked for.
913  */
914 void
915 xfs_attr_shortform_add(
916 	struct xfs_da_args		*args,
917 	int				forkoff)
918 {
919 	struct xfs_inode		*dp = args->dp;
920 	struct xfs_mount		*mp = dp->i_mount;
921 	struct xfs_ifork		*ifp = &dp->i_af;
922 	struct xfs_attr_sf_hdr		*sf = ifp->if_data;
923 	struct xfs_attr_sf_entry	*sfe;
924 	int				size;
925 
926 	trace_xfs_attr_sf_add(args);
927 
928 	dp->i_forkoff = forkoff;
929 
930 	ASSERT(ifp->if_format == XFS_DINODE_FMT_LOCAL);
931 	ASSERT(!xfs_attr_sf_findname(args));
932 
933 	size = xfs_attr_sf_entsize_byname(args->namelen, args->valuelen);
934 	sf = xfs_idata_realloc(dp, size, XFS_ATTR_FORK);
935 
936 	sfe = xfs_attr_sf_endptr(sf);
937 	sfe->namelen = args->namelen;
938 	sfe->valuelen = args->valuelen;
939 	sfe->flags = args->attr_filter;
940 	memcpy(sfe->nameval, args->name, args->namelen);
941 	memcpy(&sfe->nameval[args->namelen], args->value, args->valuelen);
942 	sf->count++;
943 	be16_add_cpu(&sf->totsize, size);
944 	xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_ADATA);
945 
946 	xfs_sbversion_add_attr2(mp, args->trans);
947 }
948 
949 /*
950  * After the last attribute is removed revert to original inode format,
951  * making all literal area available to the data fork once more.
952  */
953 void
954 xfs_attr_fork_remove(
955 	struct xfs_inode	*ip,
956 	struct xfs_trans	*tp)
957 {
958 	ASSERT(ip->i_af.if_nextents == 0);
959 
960 	xfs_ifork_zap_attr(ip);
961 	ip->i_forkoff = 0;
962 	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
963 }
964 
965 /*
966  * Remove an attribute from the shortform attribute list structure.
967  */
968 int
969 xfs_attr_sf_removename(
970 	struct xfs_da_args		*args)
971 {
972 	struct xfs_inode		*dp = args->dp;
973 	struct xfs_mount		*mp = dp->i_mount;
974 	struct xfs_attr_sf_hdr		*sf = dp->i_af.if_data;
975 	struct xfs_attr_sf_entry	*sfe;
976 	uint16_t			totsize = be16_to_cpu(sf->totsize);
977 	void				*next, *end;
978 	int				size = 0;
979 
980 	trace_xfs_attr_sf_remove(args);
981 
982 	sfe = xfs_attr_sf_findname(args);
983 	if (!sfe) {
984 		/*
985 		 * If we are recovering an operation, finding nothing to remove
986 		 * is not an error, it just means there was nothing to clean up.
987 		 */
988 		if (args->op_flags & XFS_DA_OP_RECOVERY)
989 			return 0;
990 		return -ENOATTR;
991 	}
992 
993 	/*
994 	 * Fix up the attribute fork data, covering the hole
995 	 */
996 	size = xfs_attr_sf_entsize(sfe);
997 	next = xfs_attr_sf_nextentry(sfe);
998 	end = xfs_attr_sf_endptr(sf);
999 	if (next < end)
1000 		memmove(sfe, next, end - next);
1001 	sf->count--;
1002 	totsize -= size;
1003 	sf->totsize = cpu_to_be16(totsize);
1004 
1005 	/*
1006 	 * Fix up the start offset of the attribute fork
1007 	 */
1008 	if (totsize == sizeof(struct xfs_attr_sf_hdr) &&
1009 	    (dp->i_df.if_format != XFS_DINODE_FMT_BTREE) &&
1010 	    !(args->op_flags & (XFS_DA_OP_ADDNAME | XFS_DA_OP_REPLACE)) &&
1011 	    !xfs_has_parent(mp)) {
1012 		xfs_attr_fork_remove(dp, args->trans);
1013 	} else {
1014 		xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
1015 		dp->i_forkoff = xfs_attr_shortform_bytesfit(dp, totsize);
1016 		ASSERT(dp->i_forkoff);
1017 		ASSERT(totsize > sizeof(struct xfs_attr_sf_hdr) ||
1018 				(args->op_flags & XFS_DA_OP_ADDNAME) ||
1019 				dp->i_df.if_format == XFS_DINODE_FMT_BTREE ||
1020 				xfs_has_parent(mp));
1021 		xfs_trans_log_inode(args->trans, dp,
1022 					XFS_ILOG_CORE | XFS_ILOG_ADATA);
1023 	}
1024 
1025 	xfs_sbversion_add_attr2(mp, args->trans);
1026 
1027 	return 0;
1028 }
1029 
1030 /*
1031  * Retrieve the attribute value and length.
1032  *
1033  * If args->valuelen is zero, only the length needs to be returned.  Unlike a
1034  * lookup, we only return an error if the attribute does not exist or we can't
1035  * retrieve the value.
1036  */
1037 int
1038 xfs_attr_shortform_getvalue(
1039 	struct xfs_da_args		*args)
1040 {
1041 	struct xfs_attr_sf_entry	*sfe;
1042 
1043 	ASSERT(args->dp->i_af.if_format == XFS_DINODE_FMT_LOCAL);
1044 
1045 	trace_xfs_attr_sf_lookup(args);
1046 
1047 	sfe = xfs_attr_sf_findname(args);
1048 	if (!sfe)
1049 		return -ENOATTR;
1050 	return xfs_attr_copy_value(args, &sfe->nameval[args->namelen],
1051 			sfe->valuelen);
1052 }
1053 
1054 /* Convert from using the shortform to the leaf format. */
1055 int
1056 xfs_attr_shortform_to_leaf(
1057 	struct xfs_da_args		*args)
1058 {
1059 	struct xfs_inode		*dp = args->dp;
1060 	struct xfs_ifork		*ifp = &dp->i_af;
1061 	struct xfs_attr_sf_hdr		*sf = ifp->if_data;
1062 	struct xfs_attr_sf_entry	*sfe;
1063 	int				size = be16_to_cpu(sf->totsize);
1064 	struct xfs_da_args		nargs;
1065 	char				*tmpbuffer;
1066 	int				error, i;
1067 	xfs_dablk_t			blkno;
1068 	struct xfs_buf			*bp;
1069 
1070 	trace_xfs_attr_sf_to_leaf(args);
1071 
1072 	tmpbuffer = kmalloc(size, GFP_KERNEL | __GFP_NOFAIL);
1073 	memcpy(tmpbuffer, ifp->if_data, size);
1074 	sf = (struct xfs_attr_sf_hdr *)tmpbuffer;
1075 
1076 	xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
1077 	xfs_bmap_local_to_extents_empty(args->trans, dp, XFS_ATTR_FORK);
1078 
1079 	bp = NULL;
1080 	error = xfs_da_grow_inode(args, &blkno);
1081 	if (error)
1082 		goto out;
1083 
1084 	ASSERT(blkno == 0);
1085 	error = xfs_attr3_leaf_create(args, blkno, &bp);
1086 	if (error)
1087 		goto out;
1088 
1089 	memset((char *)&nargs, 0, sizeof(nargs));
1090 	nargs.dp = dp;
1091 	nargs.geo = args->geo;
1092 	nargs.total = args->total;
1093 	nargs.whichfork = XFS_ATTR_FORK;
1094 	nargs.trans = args->trans;
1095 	nargs.op_flags = XFS_DA_OP_OKNOENT;
1096 	nargs.owner = args->owner;
1097 
1098 	sfe = xfs_attr_sf_firstentry(sf);
1099 	for (i = 0; i < sf->count; i++) {
1100 		nargs.name = sfe->nameval;
1101 		nargs.namelen = sfe->namelen;
1102 		nargs.value = &sfe->nameval[nargs.namelen];
1103 		nargs.valuelen = sfe->valuelen;
1104 		nargs.attr_filter = sfe->flags & XFS_ATTR_NSP_ONDISK_MASK;
1105 		if (!xfs_attr_check_namespace(sfe->flags)) {
1106 			xfs_da_mark_sick(args);
1107 			error = -EFSCORRUPTED;
1108 			goto out;
1109 		}
1110 		xfs_attr_sethash(&nargs);
1111 		error = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */
1112 		ASSERT(error == -ENOATTR);
1113 		if (!xfs_attr3_leaf_add(bp, &nargs))
1114 			ASSERT(0);
1115 		sfe = xfs_attr_sf_nextentry(sfe);
1116 	}
1117 	error = 0;
1118 out:
1119 	kfree(tmpbuffer);
1120 	return error;
1121 }
1122 
1123 /*
1124  * Check a leaf attribute block to see if all the entries would fit into
1125  * a shortform attribute list.
1126  */
1127 int
1128 xfs_attr_shortform_allfit(
1129 	struct xfs_buf		*bp,
1130 	struct xfs_inode	*dp)
1131 {
1132 	struct xfs_attr_leafblock *leaf;
1133 	struct xfs_attr_leaf_entry *entry;
1134 	xfs_attr_leaf_name_local_t *name_loc;
1135 	struct xfs_attr3_icleaf_hdr leafhdr;
1136 	int			bytes;
1137 	int			i;
1138 	struct xfs_mount	*mp = bp->b_mount;
1139 
1140 	leaf = bp->b_addr;
1141 	xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &leafhdr, leaf);
1142 	entry = xfs_attr3_leaf_entryp(leaf);
1143 
1144 	bytes = sizeof(struct xfs_attr_sf_hdr);
1145 	for (i = 0; i < leafhdr.count; entry++, i++) {
1146 		if (entry->flags & XFS_ATTR_INCOMPLETE)
1147 			continue;		/* don't copy partial entries */
1148 		if (!(entry->flags & XFS_ATTR_LOCAL))
1149 			return 0;
1150 		name_loc = xfs_attr3_leaf_name_local(leaf, i);
1151 		if (name_loc->namelen >= XFS_ATTR_SF_ENTSIZE_MAX)
1152 			return 0;
1153 		if (be16_to_cpu(name_loc->valuelen) >= XFS_ATTR_SF_ENTSIZE_MAX)
1154 			return 0;
1155 		bytes += xfs_attr_sf_entsize_byname(name_loc->namelen,
1156 					be16_to_cpu(name_loc->valuelen));
1157 	}
1158 	if ((dp->i_df.if_format != XFS_DINODE_FMT_BTREE) &&
1159 	    (bytes == sizeof(struct xfs_attr_sf_hdr)))
1160 		return -1;
1161 	return xfs_attr_shortform_bytesfit(dp, bytes);
1162 }
1163 
1164 /* Verify the consistency of a raw inline attribute fork. */
1165 xfs_failaddr_t
1166 xfs_attr_shortform_verify(
1167 	struct xfs_attr_sf_hdr		*sfp,
1168 	size_t				size)
1169 {
1170 	struct xfs_attr_sf_entry	*sfep = xfs_attr_sf_firstentry(sfp);
1171 	struct xfs_attr_sf_entry	*next_sfep;
1172 	char				*endp;
1173 	int				i;
1174 
1175 	/*
1176 	 * Give up if the attribute is way too short.
1177 	 */
1178 	if (size < sizeof(struct xfs_attr_sf_hdr))
1179 		return __this_address;
1180 
1181 	endp = (char *)sfp + size;
1182 
1183 	/* Check all reported entries */
1184 	for (i = 0; i < sfp->count; i++) {
1185 		/*
1186 		 * struct xfs_attr_sf_entry has a variable length.
1187 		 * Check the fixed-offset parts of the structure are
1188 		 * within the data buffer.
1189 		 * xfs_attr_sf_entry is defined with a 1-byte variable
1190 		 * array at the end, so we must subtract that off.
1191 		 */
1192 		if (((char *)sfep + sizeof(*sfep)) >= endp)
1193 			return __this_address;
1194 
1195 		/* Don't allow names with known bad length. */
1196 		if (sfep->namelen == 0)
1197 			return __this_address;
1198 
1199 		/*
1200 		 * Check that the variable-length part of the structure is
1201 		 * within the data buffer.  The next entry starts after the
1202 		 * name component, so nextentry is an acceptable test.
1203 		 */
1204 		next_sfep = xfs_attr_sf_nextentry(sfep);
1205 		if ((char *)next_sfep > endp)
1206 			return __this_address;
1207 
1208 		/*
1209 		 * Check for unknown flags.  Short form doesn't support
1210 		 * the incomplete or local bits, so we can use the namespace
1211 		 * mask here.
1212 		 */
1213 		if (sfep->flags & ~XFS_ATTR_NSP_ONDISK_MASK)
1214 			return __this_address;
1215 
1216 		/*
1217 		 * Check for invalid namespace combinations.  We only allow
1218 		 * one namespace flag per xattr, so we can just count the
1219 		 * bits (i.e. hweight) here.
1220 		 */
1221 		if (!xfs_attr_check_namespace(sfep->flags))
1222 			return __this_address;
1223 
1224 		sfep = next_sfep;
1225 	}
1226 	if ((void *)sfep != (void *)endp)
1227 		return __this_address;
1228 
1229 	return NULL;
1230 }
1231 
1232 /*
1233  * Convert a leaf attribute list to shortform attribute list
1234  */
1235 int
1236 xfs_attr3_leaf_to_shortform(
1237 	struct xfs_buf		*bp,
1238 	struct xfs_da_args	*args,
1239 	int			forkoff)
1240 {
1241 	struct xfs_attr_leafblock *leaf;
1242 	struct xfs_attr3_icleaf_hdr ichdr;
1243 	struct xfs_attr_leaf_entry *entry;
1244 	struct xfs_attr_leaf_name_local *name_loc;
1245 	struct xfs_da_args	nargs;
1246 	struct xfs_inode	*dp = args->dp;
1247 	char			*tmpbuffer;
1248 	int			error;
1249 	int			i;
1250 
1251 	trace_xfs_attr_leaf_to_sf(args);
1252 
1253 	tmpbuffer = kvmalloc(args->geo->blksize, GFP_KERNEL | __GFP_NOFAIL);
1254 	memcpy(tmpbuffer, bp->b_addr, args->geo->blksize);
1255 
1256 	leaf = (xfs_attr_leafblock_t *)tmpbuffer;
1257 	xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
1258 	entry = xfs_attr3_leaf_entryp(leaf);
1259 
1260 	/* XXX (dgc): buffer is about to be marked stale - why zero it? */
1261 	memset(bp->b_addr, 0, args->geo->blksize);
1262 
1263 	/*
1264 	 * Clean out the prior contents of the attribute list.
1265 	 */
1266 	error = xfs_da_shrink_inode(args, 0, bp);
1267 	if (error)
1268 		goto out;
1269 
1270 	if (forkoff == -1) {
1271 		/*
1272 		 * Don't remove the attr fork if this operation is the first
1273 		 * part of a attr replace operations. We're going to add a new
1274 		 * attr immediately, so we need to keep the attr fork around in
1275 		 * this case.
1276 		 */
1277 		if (!(args->op_flags & XFS_DA_OP_REPLACE)) {
1278 			ASSERT(dp->i_df.if_format != XFS_DINODE_FMT_BTREE);
1279 			xfs_attr_fork_remove(dp, args->trans);
1280 		}
1281 		goto out;
1282 	}
1283 
1284 	xfs_attr_shortform_create(args);
1285 
1286 	/*
1287 	 * Copy the attributes
1288 	 */
1289 	memset((char *)&nargs, 0, sizeof(nargs));
1290 	nargs.geo = args->geo;
1291 	nargs.dp = dp;
1292 	nargs.total = args->total;
1293 	nargs.whichfork = XFS_ATTR_FORK;
1294 	nargs.trans = args->trans;
1295 	nargs.op_flags = XFS_DA_OP_OKNOENT;
1296 	nargs.owner = args->owner;
1297 
1298 	for (i = 0; i < ichdr.count; entry++, i++) {
1299 		if (entry->flags & XFS_ATTR_INCOMPLETE)
1300 			continue;	/* don't copy partial entries */
1301 		if (!entry->nameidx)
1302 			continue;
1303 		ASSERT(entry->flags & XFS_ATTR_LOCAL);
1304 		name_loc = xfs_attr3_leaf_name_local(leaf, i);
1305 		nargs.name = name_loc->nameval;
1306 		nargs.namelen = name_loc->namelen;
1307 		nargs.value = &name_loc->nameval[nargs.namelen];
1308 		nargs.valuelen = be16_to_cpu(name_loc->valuelen);
1309 		nargs.hashval = be32_to_cpu(entry->hashval);
1310 		nargs.attr_filter = entry->flags & XFS_ATTR_NSP_ONDISK_MASK;
1311 		xfs_attr_shortform_add(&nargs, forkoff);
1312 	}
1313 	error = 0;
1314 
1315 out:
1316 	kvfree(tmpbuffer);
1317 	return error;
1318 }
1319 
1320 /*
1321  * Convert from using a single leaf to a root node and a leaf.
1322  */
1323 int
1324 xfs_attr3_leaf_to_node(
1325 	struct xfs_da_args	*args)
1326 {
1327 	struct xfs_attr_leafblock *leaf;
1328 	struct xfs_attr3_icleaf_hdr icleafhdr;
1329 	struct xfs_attr_leaf_entry *entries;
1330 	struct xfs_da3_icnode_hdr icnodehdr;
1331 	struct xfs_da_intnode	*node;
1332 	struct xfs_inode	*dp = args->dp;
1333 	struct xfs_mount	*mp = dp->i_mount;
1334 	struct xfs_buf		*bp1 = NULL;
1335 	struct xfs_buf		*bp2 = NULL;
1336 	xfs_dablk_t		blkno;
1337 	int			error;
1338 
1339 	trace_xfs_attr_leaf_to_node(args);
1340 
1341 	if (XFS_TEST_ERROR(mp, XFS_ERRTAG_ATTR_LEAF_TO_NODE)) {
1342 		error = -EIO;
1343 		goto out;
1344 	}
1345 
1346 	error = xfs_da_grow_inode(args, &blkno);
1347 	if (error)
1348 		goto out;
1349 	error = xfs_attr3_leaf_read(args->trans, dp, args->owner, 0, &bp1);
1350 	if (error)
1351 		goto out;
1352 
1353 	error = xfs_da_get_buf(args->trans, dp, blkno, &bp2, XFS_ATTR_FORK);
1354 	if (error)
1355 		goto out;
1356 
1357 	/*
1358 	 * Copy leaf to new buffer and log it.
1359 	 */
1360 	xfs_da_buf_copy(bp2, bp1, args->geo->blksize);
1361 	xfs_trans_log_buf(args->trans, bp2, 0, args->geo->blksize - 1);
1362 
1363 	/*
1364 	 * Set up the new root node.
1365 	 */
1366 	error = xfs_da3_node_create(args, 0, 1, &bp1, XFS_ATTR_FORK);
1367 	if (error)
1368 		goto out;
1369 	node = bp1->b_addr;
1370 	xfs_da3_node_hdr_from_disk(mp, &icnodehdr, node);
1371 
1372 	leaf = bp2->b_addr;
1373 	xfs_attr3_leaf_hdr_from_disk(args->geo, &icleafhdr, leaf);
1374 	entries = xfs_attr3_leaf_entryp(leaf);
1375 
1376 	/* both on-disk, don't endian-flip twice */
1377 	icnodehdr.btree[0].hashval = entries[icleafhdr.count - 1].hashval;
1378 	icnodehdr.btree[0].before = cpu_to_be32(blkno);
1379 	icnodehdr.count = 1;
1380 	xfs_da3_node_hdr_to_disk(dp->i_mount, node, &icnodehdr);
1381 	xfs_trans_log_buf(args->trans, bp1, 0, args->geo->blksize - 1);
1382 	error = 0;
1383 out:
1384 	return error;
1385 }
1386 
1387 /*========================================================================
1388  * Routines used for growing the Btree.
1389  *========================================================================*/
1390 
1391 /*
1392  * Create the initial contents of a leaf attribute list
1393  * or a leaf in a node attribute list.
1394  */
1395 STATIC int
1396 xfs_attr3_leaf_create(
1397 	struct xfs_da_args	*args,
1398 	xfs_dablk_t		blkno,
1399 	struct xfs_buf		**bpp)
1400 {
1401 	struct xfs_attr_leafblock *leaf;
1402 	struct xfs_attr3_icleaf_hdr ichdr;
1403 	struct xfs_inode	*dp = args->dp;
1404 	struct xfs_mount	*mp = dp->i_mount;
1405 	struct xfs_buf		*bp;
1406 	int			error;
1407 
1408 	trace_xfs_attr_leaf_create(args);
1409 
1410 	error = xfs_da_get_buf(args->trans, args->dp, blkno, &bp,
1411 					    XFS_ATTR_FORK);
1412 	if (error)
1413 		return error;
1414 	bp->b_ops = &xfs_attr3_leaf_buf_ops;
1415 	xfs_trans_buf_set_type(args->trans, bp, XFS_BLFT_ATTR_LEAF_BUF);
1416 	leaf = bp->b_addr;
1417 	memset(leaf, 0, args->geo->blksize);
1418 
1419 	memset(&ichdr, 0, sizeof(ichdr));
1420 	ichdr.firstused = args->geo->blksize;
1421 
1422 	if (xfs_has_crc(mp)) {
1423 		struct xfs_da3_blkinfo *hdr3 = bp->b_addr;
1424 
1425 		ichdr.magic = XFS_ATTR3_LEAF_MAGIC;
1426 
1427 		hdr3->blkno = cpu_to_be64(xfs_buf_daddr(bp));
1428 		hdr3->owner = cpu_to_be64(args->owner);
1429 		uuid_copy(&hdr3->uuid, &mp->m_sb.sb_meta_uuid);
1430 
1431 		ichdr.freemap[0].base = sizeof(struct xfs_attr3_leaf_hdr);
1432 	} else {
1433 		ichdr.magic = XFS_ATTR_LEAF_MAGIC;
1434 		ichdr.freemap[0].base = sizeof(struct xfs_attr_leaf_hdr);
1435 	}
1436 	ichdr.freemap[0].size = ichdr.firstused - ichdr.freemap[0].base;
1437 
1438 	xfs_attr3_leaf_hdr_to_disk(args->geo, leaf, &ichdr);
1439 	xfs_trans_log_buf(args->trans, bp, 0, args->geo->blksize - 1);
1440 
1441 	*bpp = bp;
1442 	return 0;
1443 }
1444 
1445 /*
1446  * Reinitialize an existing attr fork block as an empty leaf, and attach
1447  * the buffer to tp.
1448  */
1449 int
1450 xfs_attr3_leaf_init(
1451 	struct xfs_trans	*tp,
1452 	struct xfs_inode	*dp,
1453 	xfs_dablk_t		blkno)
1454 {
1455 	struct xfs_buf		*bp = NULL;
1456 	struct xfs_da_args	args = {
1457 		.trans		= tp,
1458 		.dp		= dp,
1459 		.owner		= I_INO(dp),
1460 		.geo		= dp->i_mount->m_attr_geo,
1461 	};
1462 
1463 	ASSERT(tp != NULL);
1464 
1465 	return xfs_attr3_leaf_create(&args, blkno, &bp);
1466 }
1467 /*
1468  * Split the leaf node, rebalance, then add the new entry.
1469  *
1470  * Returns 0 if the entry was added, 1 if a further split is needed or a
1471  * negative error number otherwise.
1472  */
1473 int
1474 xfs_attr3_leaf_split(
1475 	struct xfs_da_state	*state,
1476 	struct xfs_da_state_blk	*oldblk,
1477 	struct xfs_da_state_blk	*newblk)
1478 {
1479 	bool			added;
1480 	xfs_dablk_t		blkno;
1481 	int			error;
1482 
1483 	trace_xfs_attr_leaf_split(state->args);
1484 
1485 	/*
1486 	 * Allocate space for a new leaf node.
1487 	 */
1488 	ASSERT(oldblk->magic == XFS_ATTR_LEAF_MAGIC);
1489 	error = xfs_da_grow_inode(state->args, &blkno);
1490 	if (error)
1491 		return error;
1492 	error = xfs_attr3_leaf_create(state->args, blkno, &newblk->bp);
1493 	if (error)
1494 		return error;
1495 	newblk->blkno = blkno;
1496 	newblk->magic = XFS_ATTR_LEAF_MAGIC;
1497 
1498 	/*
1499 	 * Rebalance the entries across the two leaves.
1500 	 * NOTE: rebalance() currently depends on the 2nd block being empty.
1501 	 */
1502 	xfs_attr3_leaf_rebalance(state, oldblk, newblk);
1503 	error = xfs_da3_blk_link(state, oldblk, newblk);
1504 	if (error)
1505 		return error;
1506 
1507 	/*
1508 	 * Save info on "old" attribute for "atomic rename" ops, leaf_add()
1509 	 * modifies the index/blkno/rmtblk/rmtblkcnt fields to show the
1510 	 * "new" attrs info.  Will need the "old" info to remove it later.
1511 	 *
1512 	 * Insert the "new" entry in the correct block.
1513 	 */
1514 	if (state->inleaf) {
1515 		trace_xfs_attr_leaf_add_old(state->args);
1516 		added = xfs_attr3_leaf_add(oldblk->bp, state->args);
1517 	} else {
1518 		trace_xfs_attr_leaf_add_new(state->args);
1519 		added = xfs_attr3_leaf_add(newblk->bp, state->args);
1520 	}
1521 
1522 	/*
1523 	 * Update last hashval in each block since we added the name.
1524 	 */
1525 	oldblk->hashval = xfs_attr_leaf_lasthash(oldblk->bp, NULL);
1526 	newblk->hashval = xfs_attr_leaf_lasthash(newblk->bp, NULL);
1527 	if (!added)
1528 		return 1;
1529 	return 0;
1530 }
1531 
1532 /*
1533  * Add a name to the leaf attribute list structure.
1534  */
1535 bool
1536 xfs_attr3_leaf_add(
1537 	struct xfs_buf		*bp,
1538 	struct xfs_da_args	*args)
1539 {
1540 	struct xfs_attr_leafblock *leaf;
1541 	struct xfs_attr3_icleaf_hdr ichdr;
1542 	int			tablesize;
1543 	int			entsize;
1544 	bool			added = true;
1545 	int			sum;
1546 	int			tmp;
1547 	int			i;
1548 
1549 	trace_xfs_attr_leaf_add(args);
1550 
1551 	leaf = bp->b_addr;
1552 	xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
1553 	ASSERT(args->index >= 0 && args->index <= ichdr.count);
1554 	entsize = xfs_attr_leaf_newentsize(args, NULL);
1555 
1556 	/*
1557 	 * Search through freemap for first-fit on new name length.
1558 	 * (may need to figure in size of entry struct too)
1559 	 */
1560 	tablesize = xfs_attr_leaf_entries_end(ichdr.count + 1, leaf);
1561 	for (sum = 0, i = XFS_ATTR_LEAF_MAPSIZE - 1; i >= 0; i--) {
1562 		if (tablesize > ichdr.firstused) {
1563 			sum += ichdr.freemap[i].size;
1564 			continue;
1565 		}
1566 		if (!ichdr.freemap[i].size)
1567 			continue;	/* no space in this map */
1568 		tmp = entsize;
1569 		if (ichdr.freemap[i].base < ichdr.firstused)
1570 			tmp += sizeof(xfs_attr_leaf_entry_t);
1571 		if (ichdr.freemap[i].size >= tmp) {
1572 			xfs_attr3_leaf_add_work(bp, &ichdr, args, i);
1573 			goto out_log_hdr;
1574 		}
1575 		sum += ichdr.freemap[i].size;
1576 	}
1577 
1578 	/*
1579 	 * If there are no holes in the address space of the block,
1580 	 * and we don't have enough freespace, then compaction will do us
1581 	 * no good and we should just give up.
1582 	 */
1583 	if (!ichdr.holes && sum < entsize)
1584 		return false;
1585 
1586 	/*
1587 	 * Compact the entries to coalesce free space.
1588 	 * This may change the hdr->count via dropping INCOMPLETE entries.
1589 	 */
1590 	xfs_attr3_leaf_compact(args, &ichdr, bp);
1591 
1592 	/*
1593 	 * After compaction, the block is guaranteed to have only one
1594 	 * free region, in freemap[0].  If it is not big enough, give up.
1595 	 */
1596 	if (ichdr.freemap[0].size < (entsize + sizeof(xfs_attr_leaf_entry_t))) {
1597 		added = false;
1598 		goto out_log_hdr;
1599 	}
1600 
1601 	xfs_attr3_leaf_add_work(bp, &ichdr, args, 0);
1602 
1603 out_log_hdr:
1604 	xfs_attr3_leaf_hdr_to_disk(args->geo, leaf, &ichdr);
1605 	xfs_trans_log_buf(args->trans, bp,
1606 		XFS_DA_LOGRANGE(leaf, &leaf->hdr,
1607 				xfs_attr3_leaf_hdr_size(leaf)));
1608 	return added;
1609 }
1610 
1611 /*
1612  * Add a name to a leaf attribute list structure.
1613  */
1614 STATIC void
1615 xfs_attr3_leaf_add_work(
1616 	struct xfs_buf		*bp,
1617 	struct xfs_attr3_icleaf_hdr *ichdr,
1618 	struct xfs_da_args	*args,
1619 	int			mapindex)
1620 {
1621 	struct xfs_attr_leafblock *leaf;
1622 	struct xfs_attr_leaf_entry *entry;
1623 	struct xfs_attr_leaf_name_local *name_loc;
1624 	struct xfs_attr_leaf_name_remote *name_rmt;
1625 	struct xfs_mount	*mp;
1626 	int			old_end, new_end;
1627 	int			tmp;
1628 	int			i;
1629 
1630 	trace_xfs_attr_leaf_add_work(args);
1631 
1632 	leaf = bp->b_addr;
1633 	ASSERT(mapindex >= 0 && mapindex < XFS_ATTR_LEAF_MAPSIZE);
1634 	ASSERT(args->index >= 0 && args->index <= ichdr->count);
1635 
1636 	/*
1637 	 * Force open some space in the entry array and fill it in.
1638 	 */
1639 	entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
1640 	if (args->index < ichdr->count) {
1641 		tmp  = ichdr->count - args->index;
1642 		tmp *= sizeof(xfs_attr_leaf_entry_t);
1643 		memmove(entry + 1, entry, tmp);
1644 		xfs_trans_log_buf(args->trans, bp,
1645 		    XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(*entry)));
1646 	}
1647 	ichdr->count++;
1648 
1649 	/*
1650 	 * Allocate space for the new string (at the end of the run).
1651 	 */
1652 	mp = args->trans->t_mountp;
1653 	ASSERT(ichdr->freemap[mapindex].base < args->geo->blksize);
1654 	ASSERT((ichdr->freemap[mapindex].base & 0x3) == 0);
1655 	ASSERT(ichdr->freemap[mapindex].size >=
1656 		xfs_attr_leaf_newentsize(args, NULL));
1657 	ASSERT(ichdr->freemap[mapindex].size < args->geo->blksize);
1658 	ASSERT((ichdr->freemap[mapindex].size & 0x3) == 0);
1659 
1660 	ichdr->freemap[mapindex].size -= xfs_attr_leaf_newentsize(args, &tmp);
1661 
1662 	entry->nameidx = cpu_to_be16(ichdr->freemap[mapindex].base +
1663 				     ichdr->freemap[mapindex].size);
1664 	entry->hashval = cpu_to_be32(args->hashval);
1665 	entry->flags = args->attr_filter;
1666 	if (tmp)
1667 		entry->flags |= XFS_ATTR_LOCAL;
1668 	if (args->op_flags & XFS_DA_OP_REPLACE) {
1669 		if (!(args->op_flags & XFS_DA_OP_LOGGED))
1670 			entry->flags |= XFS_ATTR_INCOMPLETE;
1671 		if ((args->blkno2 == args->blkno) &&
1672 		    (args->index2 <= args->index)) {
1673 			args->index2++;
1674 		}
1675 	}
1676 	xfs_trans_log_buf(args->trans, bp,
1677 			  XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
1678 	ASSERT((args->index == 0) ||
1679 	       (be32_to_cpu(entry->hashval) >= be32_to_cpu((entry-1)->hashval)));
1680 	ASSERT((args->index == ichdr->count - 1) ||
1681 	       (be32_to_cpu(entry->hashval) <= be32_to_cpu((entry+1)->hashval)));
1682 
1683 	/*
1684 	 * For "remote" attribute values, simply note that we need to
1685 	 * allocate space for the "remote" value.  We can't actually
1686 	 * allocate the extents in this transaction, and we can't decide
1687 	 * which blocks they should be as we might allocate more blocks
1688 	 * as part of this transaction (a split operation for example).
1689 	 */
1690 	if (entry->flags & XFS_ATTR_LOCAL) {
1691 		name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
1692 		name_loc->namelen = args->namelen;
1693 		name_loc->valuelen = cpu_to_be16(args->valuelen);
1694 		memcpy((char *)name_loc->nameval, args->name, args->namelen);
1695 		memcpy((char *)&name_loc->nameval[args->namelen], args->value,
1696 				   be16_to_cpu(name_loc->valuelen));
1697 	} else {
1698 		name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
1699 		name_rmt->namelen = args->namelen;
1700 		memcpy((char *)name_rmt->name, args->name, args->namelen);
1701 		entry->flags |= XFS_ATTR_INCOMPLETE;
1702 		/* just in case */
1703 		name_rmt->valuelen = 0;
1704 		name_rmt->valueblk = 0;
1705 		args->rmtblkno = 1;
1706 		args->rmtblkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen);
1707 		args->rmtvaluelen = args->valuelen;
1708 	}
1709 	xfs_trans_log_buf(args->trans, bp,
1710 	     XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index),
1711 				   xfs_attr_leaf_entsize(leaf, args->index)));
1712 
1713 	/*
1714 	 * Update the control info for this leaf node
1715 	 */
1716 	if (be16_to_cpu(entry->nameidx) < ichdr->firstused)
1717 		ichdr->firstused = be16_to_cpu(entry->nameidx);
1718 
1719 	new_end = xfs_attr_leaf_entries_end(ichdr->count, leaf);
1720 	old_end = new_end - sizeof(struct xfs_attr_leaf_entry);
1721 
1722 	ASSERT(ichdr->firstused >= new_end);
1723 
1724 	for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
1725 		int		diff = 0;
1726 
1727 		if (ichdr->freemap[i].base == old_end) {
1728 			/*
1729 			 * This freemap entry starts at the old end of the
1730 			 * leaf entry array, so we need to adjust its base
1731 			 * upward to accommodate the larger array.
1732 			 */
1733 			diff = sizeof(struct xfs_attr_leaf_entry);
1734 		} else if (ichdr->freemap[i].size > 0 &&
1735 			   ichdr->freemap[i].base < new_end) {
1736 			/*
1737 			 * This freemap entry starts in the space claimed by
1738 			 * the new leaf entry.  Adjust its base upward to
1739 			 * reflect that.
1740 			 */
1741 			diff = new_end - ichdr->freemap[i].base;
1742 		}
1743 
1744 		if (diff) {
1745 			ichdr->freemap[i].base += diff;
1746 			ichdr->freemap[i].size -=
1747 				min_t(uint16_t, ichdr->freemap[i].size, diff);
1748 		}
1749 
1750 		/*
1751 		 * Don't leave zero-length freemaps with nonzero base lying
1752 		 * around, because we don't want the code in _remove that
1753 		 * matches on base address to get confused and create
1754 		 * overlapping freemaps.  If we end up with no freemap entries
1755 		 * then the next _add will compact the leaf block and
1756 		 * regenerate the freemaps.
1757 		 */
1758 		if (ichdr->freemap[i].size == 0 && ichdr->freemap[i].base > 0) {
1759 			ichdr->freemap[i].base = 0;
1760 			ichdr->holes = 1;
1761 		}
1762 	}
1763 	ichdr->usedbytes += xfs_attr_leaf_entsize(leaf, args->index);
1764 }
1765 
1766 /*
1767  * Garbage collect a leaf attribute list block by copying it to a new buffer.
1768  */
1769 STATIC void
1770 xfs_attr3_leaf_compact(
1771 	struct xfs_da_args	*args,
1772 	struct xfs_attr3_icleaf_hdr *ichdr_dst,
1773 	struct xfs_buf		*bp)
1774 {
1775 	struct xfs_attr_leafblock *leaf_src;
1776 	struct xfs_attr_leafblock *leaf_dst;
1777 	struct xfs_attr3_icleaf_hdr ichdr_src;
1778 	struct xfs_trans	*trans = args->trans;
1779 	char			*tmpbuffer;
1780 
1781 	trace_xfs_attr_leaf_compact(args);
1782 
1783 	tmpbuffer = kvmalloc(args->geo->blksize, GFP_KERNEL | __GFP_NOFAIL);
1784 	memcpy(tmpbuffer, bp->b_addr, args->geo->blksize);
1785 	memset(bp->b_addr, 0, args->geo->blksize);
1786 	leaf_src = (xfs_attr_leafblock_t *)tmpbuffer;
1787 	leaf_dst = bp->b_addr;
1788 
1789 	/*
1790 	 * Copy the on-disk header back into the destination buffer to ensure
1791 	 * all the information in the header that is not part of the incore
1792 	 * header structure is preserved.
1793 	 */
1794 	memcpy(bp->b_addr, tmpbuffer, xfs_attr3_leaf_hdr_size(leaf_src));
1795 
1796 	/* Initialise the incore headers */
1797 	ichdr_src = *ichdr_dst;	/* struct copy */
1798 	ichdr_dst->firstused = args->geo->blksize;
1799 	ichdr_dst->usedbytes = 0;
1800 	ichdr_dst->count = 0;
1801 	ichdr_dst->holes = 0;
1802 	ichdr_dst->freemap[0].base = xfs_attr3_leaf_hdr_size(leaf_src);
1803 	ichdr_dst->freemap[0].size = ichdr_dst->firstused -
1804 						ichdr_dst->freemap[0].base;
1805 	ichdr_dst->freemap[1].base = 0;
1806 	ichdr_dst->freemap[2].base = 0;
1807 	ichdr_dst->freemap[1].size = 0;
1808 	ichdr_dst->freemap[2].size = 0;
1809 
1810 	/* write the header back to initialise the underlying buffer */
1811 	xfs_attr3_leaf_hdr_to_disk(args->geo, leaf_dst, ichdr_dst);
1812 
1813 	/*
1814 	 * Copy all entry's in the same (sorted) order,
1815 	 * but allocate name/value pairs packed and in sequence.
1816 	 */
1817 	xfs_attr3_leaf_moveents(args, leaf_src, &ichdr_src, 0,
1818 				leaf_dst, ichdr_dst, 0, ichdr_src.count);
1819 	/*
1820 	 * this logs the entire buffer, but the caller must write the header
1821 	 * back to the buffer when it is finished modifying it.
1822 	 */
1823 	xfs_trans_log_buf(trans, bp, 0, args->geo->blksize - 1);
1824 
1825 	kvfree(tmpbuffer);
1826 }
1827 
1828 /*
1829  * Compare two leaf blocks "order".
1830  * Return 0 unless leaf2 should go before leaf1.
1831  */
1832 static int
1833 xfs_attr3_leaf_order(
1834 	struct xfs_buf	*leaf1_bp,
1835 	struct xfs_attr3_icleaf_hdr *leaf1hdr,
1836 	struct xfs_buf	*leaf2_bp,
1837 	struct xfs_attr3_icleaf_hdr *leaf2hdr)
1838 {
1839 	struct xfs_attr_leaf_entry *entries1;
1840 	struct xfs_attr_leaf_entry *entries2;
1841 
1842 	entries1 = xfs_attr3_leaf_entryp(leaf1_bp->b_addr);
1843 	entries2 = xfs_attr3_leaf_entryp(leaf2_bp->b_addr);
1844 	if (leaf1hdr->count > 0 && leaf2hdr->count > 0 &&
1845 	    ((be32_to_cpu(entries2[0].hashval) <
1846 	      be32_to_cpu(entries1[0].hashval)) ||
1847 	     (be32_to_cpu(entries2[leaf2hdr->count - 1].hashval) <
1848 	      be32_to_cpu(entries1[leaf1hdr->count - 1].hashval)))) {
1849 		return 1;
1850 	}
1851 	return 0;
1852 }
1853 
1854 int
1855 xfs_attr_leaf_order(
1856 	struct xfs_buf	*leaf1_bp,
1857 	struct xfs_buf	*leaf2_bp)
1858 {
1859 	struct xfs_attr3_icleaf_hdr ichdr1;
1860 	struct xfs_attr3_icleaf_hdr ichdr2;
1861 	struct xfs_mount *mp = leaf1_bp->b_mount;
1862 
1863 	xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &ichdr1, leaf1_bp->b_addr);
1864 	xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &ichdr2, leaf2_bp->b_addr);
1865 	return xfs_attr3_leaf_order(leaf1_bp, &ichdr1, leaf2_bp, &ichdr2);
1866 }
1867 
1868 /*
1869  * Redistribute the attribute list entries between two leaf nodes,
1870  * taking into account the size of the new entry.
1871  *
1872  * NOTE: if new block is empty, then it will get the upper half of the
1873  * old block.  At present, all (one) callers pass in an empty second block.
1874  *
1875  * This code adjusts the args->index/blkno and args->index2/blkno2 fields
1876  * to match what it is doing in splitting the attribute leaf block.  Those
1877  * values are used in "atomic rename" operations on attributes.  Note that
1878  * the "new" and "old" values can end up in different blocks.
1879  */
1880 STATIC void
1881 xfs_attr3_leaf_rebalance(
1882 	struct xfs_da_state	*state,
1883 	struct xfs_da_state_blk	*blk1,
1884 	struct xfs_da_state_blk	*blk2)
1885 {
1886 	struct xfs_da_args	*args;
1887 	struct xfs_attr_leafblock *leaf1;
1888 	struct xfs_attr_leafblock *leaf2;
1889 	struct xfs_attr3_icleaf_hdr ichdr1;
1890 	struct xfs_attr3_icleaf_hdr ichdr2;
1891 	struct xfs_attr_leaf_entry *entries1;
1892 	struct xfs_attr_leaf_entry *entries2;
1893 	int			count;
1894 	int			totallen;
1895 	int			max;
1896 	int			space;
1897 	int			swap;
1898 
1899 	/*
1900 	 * Set up environment.
1901 	 */
1902 	ASSERT(blk1->magic == XFS_ATTR_LEAF_MAGIC);
1903 	ASSERT(blk2->magic == XFS_ATTR_LEAF_MAGIC);
1904 	leaf1 = blk1->bp->b_addr;
1905 	leaf2 = blk2->bp->b_addr;
1906 	xfs_attr3_leaf_hdr_from_disk(state->args->geo, &ichdr1, leaf1);
1907 	xfs_attr3_leaf_hdr_from_disk(state->args->geo, &ichdr2, leaf2);
1908 	ASSERT(ichdr2.count == 0);
1909 	args = state->args;
1910 
1911 	trace_xfs_attr_leaf_rebalance(args);
1912 
1913 	/*
1914 	 * Check ordering of blocks, reverse if it makes things simpler.
1915 	 *
1916 	 * NOTE: Given that all (current) callers pass in an empty
1917 	 * second block, this code should never set "swap".
1918 	 */
1919 	swap = 0;
1920 	if (xfs_attr3_leaf_order(blk1->bp, &ichdr1, blk2->bp, &ichdr2)) {
1921 		swap(blk1, blk2);
1922 
1923 		/* swap structures rather than reconverting them */
1924 		swap(ichdr1, ichdr2);
1925 
1926 		leaf1 = blk1->bp->b_addr;
1927 		leaf2 = blk2->bp->b_addr;
1928 		swap = 1;
1929 	}
1930 
1931 	/*
1932 	 * Examine entries until we reduce the absolute difference in
1933 	 * byte usage between the two blocks to a minimum.  Then get
1934 	 * the direction to copy and the number of elements to move.
1935 	 *
1936 	 * "inleaf" is true if the new entry should be inserted into blk1.
1937 	 * If "swap" is also true, then reverse the sense of "inleaf".
1938 	 */
1939 	state->inleaf = xfs_attr3_leaf_figure_balance(state, blk1, &ichdr1,
1940 						      blk2, &ichdr2,
1941 						      &count, &totallen);
1942 	if (swap)
1943 		state->inleaf = !state->inleaf;
1944 
1945 	/*
1946 	 * Move any entries required from leaf to leaf:
1947 	 */
1948 	if (count < ichdr1.count) {
1949 		/*
1950 		 * Figure the total bytes to be added to the destination leaf.
1951 		 */
1952 		/* number entries being moved */
1953 		count = ichdr1.count - count;
1954 		space  = ichdr1.usedbytes - totallen;
1955 		space += count * sizeof(xfs_attr_leaf_entry_t);
1956 
1957 		/*
1958 		 * leaf2 is the destination, compact it if it looks tight.
1959 		 */
1960 		max = ichdr2.firstused -
1961 				xfs_attr_leaf_entries_end(ichdr2.count, leaf1);
1962 		if (space > max)
1963 			xfs_attr3_leaf_compact(args, &ichdr2, blk2->bp);
1964 
1965 		/*
1966 		 * Move high entries from leaf1 to low end of leaf2.
1967 		 */
1968 		xfs_attr3_leaf_moveents(args, leaf1, &ichdr1,
1969 				ichdr1.count - count, leaf2, &ichdr2, 0, count);
1970 
1971 	} else if (count > ichdr1.count) {
1972 		/*
1973 		 * I assert that since all callers pass in an empty
1974 		 * second buffer, this code should never execute.
1975 		 */
1976 		ASSERT(0);
1977 
1978 		/*
1979 		 * Figure the total bytes to be added to the destination leaf.
1980 		 */
1981 		/* number entries being moved */
1982 		count -= ichdr1.count;
1983 		space  = totallen - ichdr1.usedbytes;
1984 		space += count * sizeof(xfs_attr_leaf_entry_t);
1985 
1986 		/*
1987 		 * leaf1 is the destination, compact it if it looks tight.
1988 		 */
1989 		max = ichdr1.firstused -
1990 				xfs_attr_leaf_entries_end(ichdr1.count, leaf1);
1991 		if (space > max)
1992 			xfs_attr3_leaf_compact(args, &ichdr1, blk1->bp);
1993 
1994 		/*
1995 		 * Move low entries from leaf2 to high end of leaf1.
1996 		 */
1997 		xfs_attr3_leaf_moveents(args, leaf2, &ichdr2, 0, leaf1, &ichdr1,
1998 					ichdr1.count, count);
1999 	}
2000 
2001 	xfs_attr3_leaf_hdr_to_disk(state->args->geo, leaf1, &ichdr1);
2002 	xfs_attr3_leaf_hdr_to_disk(state->args->geo, leaf2, &ichdr2);
2003 	xfs_trans_log_buf(args->trans, blk1->bp, 0, args->geo->blksize - 1);
2004 	xfs_trans_log_buf(args->trans, blk2->bp, 0, args->geo->blksize - 1);
2005 
2006 	/*
2007 	 * Copy out last hashval in each block for B-tree code.
2008 	 */
2009 	entries1 = xfs_attr3_leaf_entryp(leaf1);
2010 	entries2 = xfs_attr3_leaf_entryp(leaf2);
2011 	blk1->hashval = be32_to_cpu(entries1[ichdr1.count - 1].hashval);
2012 	blk2->hashval = be32_to_cpu(entries2[ichdr2.count - 1].hashval);
2013 
2014 	/*
2015 	 * Adjust the expected index for insertion.
2016 	 * NOTE: this code depends on the (current) situation that the
2017 	 * second block was originally empty.
2018 	 *
2019 	 * If the insertion point moved to the 2nd block, we must adjust
2020 	 * the index.  We must also track the entry just following the
2021 	 * new entry for use in an "atomic rename" operation, that entry
2022 	 * is always the "old" entry and the "new" entry is what we are
2023 	 * inserting.  The index/blkno fields refer to the "old" entry,
2024 	 * while the index2/blkno2 fields refer to the "new" entry.
2025 	 */
2026 	if (blk1->index > ichdr1.count) {
2027 		ASSERT(state->inleaf == 0);
2028 		blk2->index = blk1->index - ichdr1.count;
2029 		args->index = args->index2 = blk2->index;
2030 		args->blkno = args->blkno2 = blk2->blkno;
2031 	} else if (blk1->index == ichdr1.count) {
2032 		if (state->inleaf) {
2033 			args->index = blk1->index;
2034 			args->blkno = blk1->blkno;
2035 			args->index2 = 0;
2036 			args->blkno2 = blk2->blkno;
2037 		} else {
2038 			/*
2039 			 * On a double leaf split, the original attr location
2040 			 * is already stored in blkno2/index2, so don't
2041 			 * overwrite it overwise we corrupt the tree.
2042 			 */
2043 			blk2->index = blk1->index - ichdr1.count;
2044 			args->index = blk2->index;
2045 			args->blkno = blk2->blkno;
2046 			if (!state->extravalid) {
2047 				/*
2048 				 * set the new attr location to match the old
2049 				 * one and let the higher level split code
2050 				 * decide where in the leaf to place it.
2051 				 */
2052 				args->index2 = blk2->index;
2053 				args->blkno2 = blk2->blkno;
2054 			}
2055 		}
2056 	} else {
2057 		ASSERT(state->inleaf == 1);
2058 		args->index = args->index2 = blk1->index;
2059 		args->blkno = args->blkno2 = blk1->blkno;
2060 	}
2061 }
2062 
2063 /*
2064  * Examine entries until we reduce the absolute difference in
2065  * byte usage between the two blocks to a minimum.
2066  * GROT: Is this really necessary?  With other than a 512 byte blocksize,
2067  * GROT: there will always be enough room in either block for a new entry.
2068  * GROT: Do a double-split for this case?
2069  */
2070 STATIC int
2071 xfs_attr3_leaf_figure_balance(
2072 	struct xfs_da_state		*state,
2073 	struct xfs_da_state_blk		*blk1,
2074 	struct xfs_attr3_icleaf_hdr	*ichdr1,
2075 	struct xfs_da_state_blk		*blk2,
2076 	struct xfs_attr3_icleaf_hdr	*ichdr2,
2077 	int				*countarg,
2078 	int				*usedbytesarg)
2079 {
2080 	struct xfs_attr_leafblock	*leaf1 = blk1->bp->b_addr;
2081 	struct xfs_attr_leafblock	*leaf2 = blk2->bp->b_addr;
2082 	struct xfs_attr_leaf_entry	*entry;
2083 	int				count;
2084 	int				max;
2085 	int				index;
2086 	int				totallen = 0;
2087 	int				half;
2088 	int				lastdelta;
2089 	int				foundit = 0;
2090 	int				tmp;
2091 
2092 	/*
2093 	 * Examine entries until we reduce the absolute difference in
2094 	 * byte usage between the two blocks to a minimum.
2095 	 */
2096 	max = ichdr1->count + ichdr2->count;
2097 	half = (max + 1) * sizeof(*entry);
2098 	half += ichdr1->usedbytes + ichdr2->usedbytes +
2099 			xfs_attr_leaf_newentsize(state->args, NULL);
2100 	half /= 2;
2101 	lastdelta = state->args->geo->blksize;
2102 	entry = xfs_attr3_leaf_entryp(leaf1);
2103 	for (count = index = 0; count < max; entry++, index++, count++) {
2104 
2105 #define XFS_ATTR_ABS(A)	(((A) < 0) ? -(A) : (A))
2106 		/*
2107 		 * The new entry is in the first block, account for it.
2108 		 */
2109 		if (count == blk1->index) {
2110 			tmp = totallen + sizeof(*entry) +
2111 				xfs_attr_leaf_newentsize(state->args, NULL);
2112 			if (XFS_ATTR_ABS(half - tmp) > lastdelta)
2113 				break;
2114 			lastdelta = XFS_ATTR_ABS(half - tmp);
2115 			totallen = tmp;
2116 			foundit = 1;
2117 		}
2118 
2119 		/*
2120 		 * Wrap around into the second block if necessary.
2121 		 */
2122 		if (count == ichdr1->count) {
2123 			leaf1 = leaf2;
2124 			entry = xfs_attr3_leaf_entryp(leaf1);
2125 			index = 0;
2126 		}
2127 
2128 		/*
2129 		 * Figure out if next leaf entry would be too much.
2130 		 */
2131 		tmp = totallen + sizeof(*entry) + xfs_attr_leaf_entsize(leaf1,
2132 									index);
2133 		if (XFS_ATTR_ABS(half - tmp) > lastdelta)
2134 			break;
2135 		lastdelta = XFS_ATTR_ABS(half - tmp);
2136 		totallen = tmp;
2137 #undef XFS_ATTR_ABS
2138 	}
2139 
2140 	/*
2141 	 * Calculate the number of usedbytes that will end up in lower block.
2142 	 * If new entry not in lower block, fix up the count.
2143 	 */
2144 	totallen -= count * sizeof(*entry);
2145 	if (foundit) {
2146 		totallen -= sizeof(*entry) +
2147 				xfs_attr_leaf_newentsize(state->args, NULL);
2148 	}
2149 
2150 	*countarg = count;
2151 	*usedbytesarg = totallen;
2152 	return foundit;
2153 }
2154 
2155 /*========================================================================
2156  * Routines used for shrinking the Btree.
2157  *========================================================================*/
2158 
2159 /*
2160  * Check a leaf block and its neighbors to see if the block should be
2161  * collapsed into one or the other neighbor.  Always keep the block
2162  * with the smaller block number.
2163  * If the current block is over 50% full, don't try to join it, return 0.
2164  * If the block is empty, fill in the state structure and return 2.
2165  * If it can be collapsed, fill in the state structure and return 1.
2166  * If nothing can be done, return 0.
2167  *
2168  * GROT: allow for INCOMPLETE entries in calculation.
2169  */
2170 int
2171 xfs_attr3_leaf_toosmall(
2172 	struct xfs_da_state	*state,
2173 	int			*action)
2174 {
2175 	struct xfs_attr_leafblock *leaf;
2176 	struct xfs_da_state_blk	*blk;
2177 	struct xfs_attr3_icleaf_hdr ichdr;
2178 	struct xfs_buf		*bp;
2179 	xfs_dablk_t		blkno;
2180 	int			bytes;
2181 	int			forward;
2182 	int			error;
2183 	int			retval;
2184 	int			i;
2185 
2186 	trace_xfs_attr_leaf_toosmall(state->args);
2187 
2188 	/*
2189 	 * Check for the degenerate case of the block being over 50% full.
2190 	 * If so, it's not worth even looking to see if we might be able
2191 	 * to coalesce with a sibling.
2192 	 */
2193 	blk = &state->path.blk[ state->path.active-1 ];
2194 	leaf = blk->bp->b_addr;
2195 	xfs_attr3_leaf_hdr_from_disk(state->args->geo, &ichdr, leaf);
2196 	bytes = xfs_attr_leaf_entries_end(ichdr.count, leaf) + ichdr.usedbytes;
2197 	if (bytes > (state->args->geo->blksize >> 1)) {
2198 		*action = 0;	/* blk over 50%, don't try to join */
2199 		return 0;
2200 	}
2201 
2202 	/*
2203 	 * Check for the degenerate case of the block being empty.
2204 	 * If the block is empty, we'll simply delete it, no need to
2205 	 * coalesce it with a sibling block.  We choose (arbitrarily)
2206 	 * to merge with the forward block unless it is NULL.
2207 	 */
2208 	if (ichdr.count == 0) {
2209 		/*
2210 		 * Make altpath point to the block we want to keep and
2211 		 * path point to the block we want to drop (this one).
2212 		 */
2213 		forward = (ichdr.forw != 0);
2214 		memcpy(&state->altpath, &state->path, sizeof(state->path));
2215 		error = xfs_da3_path_shift(state, &state->altpath, forward,
2216 						 0, &retval);
2217 		if (error)
2218 			return error;
2219 		if (retval) {
2220 			*action = 0;
2221 		} else {
2222 			*action = 2;
2223 		}
2224 		return 0;
2225 	}
2226 
2227 	/*
2228 	 * Examine each sibling block to see if we can coalesce with
2229 	 * at least 25% free space to spare.  We need to figure out
2230 	 * whether to merge with the forward or the backward block.
2231 	 * We prefer coalescing with the lower numbered sibling so as
2232 	 * to shrink an attribute list over time.
2233 	 */
2234 	/* start with smaller blk num */
2235 	forward = ichdr.forw < ichdr.back;
2236 	for (i = 0; i < 2; forward = !forward, i++) {
2237 		struct xfs_attr3_icleaf_hdr ichdr2;
2238 		if (forward)
2239 			blkno = ichdr.forw;
2240 		else
2241 			blkno = ichdr.back;
2242 		if (blkno == 0)
2243 			continue;
2244 		error = xfs_attr3_leaf_read(state->args->trans, state->args->dp,
2245 					state->args->owner, blkno, &bp);
2246 		if (error)
2247 			return error;
2248 
2249 		xfs_attr3_leaf_hdr_from_disk(state->args->geo, &ichdr2, bp->b_addr);
2250 
2251 		bytes = state->args->geo->blksize -
2252 			(state->args->geo->blksize >> 2) -
2253 			ichdr.usedbytes - ichdr2.usedbytes -
2254 			xfs_attr_leaf_entries_end(ichdr.count + ichdr2.count,
2255 					leaf);
2256 
2257 		xfs_trans_brelse(state->args->trans, bp);
2258 		if (bytes >= 0)
2259 			break;	/* fits with at least 25% to spare */
2260 	}
2261 	if (i >= 2) {
2262 		*action = 0;
2263 		return 0;
2264 	}
2265 
2266 	/*
2267 	 * Make altpath point to the block we want to keep (the lower
2268 	 * numbered block) and path point to the block we want to drop.
2269 	 */
2270 	memcpy(&state->altpath, &state->path, sizeof(state->path));
2271 	if (blkno < blk->blkno) {
2272 		error = xfs_da3_path_shift(state, &state->altpath, forward,
2273 						 0, &retval);
2274 	} else {
2275 		error = xfs_da3_path_shift(state, &state->path, forward,
2276 						 0, &retval);
2277 	}
2278 	if (error)
2279 		return error;
2280 	if (retval) {
2281 		*action = 0;
2282 	} else {
2283 		*action = 1;
2284 	}
2285 	return 0;
2286 }
2287 
2288 /*
2289  * Remove a name from the leaf attribute list structure.
2290  *
2291  * Return 1 if leaf is less than 37% full, 0 if >= 37% full.
2292  * If two leaves are 37% full, when combined they will leave 25% free.
2293  */
2294 int
2295 xfs_attr3_leaf_remove(
2296 	struct xfs_buf		*bp,
2297 	struct xfs_da_args	*args)
2298 {
2299 	struct xfs_attr_leafblock *leaf;
2300 	struct xfs_attr3_icleaf_hdr ichdr;
2301 	struct xfs_attr_leaf_entry *entry;
2302 	int			before;
2303 	int			after;
2304 	int			smallest;
2305 	int			entsize;
2306 	int			tablesize;
2307 	int			tmp;
2308 	int			i;
2309 
2310 	trace_xfs_attr_leaf_remove(args);
2311 
2312 	leaf = bp->b_addr;
2313 	xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
2314 
2315 	ASSERT(ichdr.count > 0 && ichdr.count < args->geo->blksize / 8);
2316 	ASSERT(args->index >= 0 && args->index < ichdr.count);
2317 	ASSERT(ichdr.firstused >= xfs_attr_leaf_entries_end(ichdr.count, leaf));
2318 
2319 	entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
2320 
2321 	ASSERT(be16_to_cpu(entry->nameidx) >= ichdr.firstused);
2322 	ASSERT(be16_to_cpu(entry->nameidx) < args->geo->blksize);
2323 
2324 	/*
2325 	 * Scan through free region table:
2326 	 *    check for adjacency of free'd entry with an existing one,
2327 	 *    find smallest free region in case we need to replace it,
2328 	 *    adjust any map that borders the entry table,
2329 	 */
2330 	tablesize = xfs_attr_leaf_entries_end(ichdr.count, leaf);
2331 	tmp = ichdr.freemap[0].size;
2332 	before = after = -1;
2333 	smallest = XFS_ATTR_LEAF_MAPSIZE - 1;
2334 	entsize = xfs_attr_leaf_entsize(leaf, args->index);
2335 	for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) {
2336 		ASSERT(ichdr.freemap[i].base < args->geo->blksize);
2337 		ASSERT(ichdr.freemap[i].size < args->geo->blksize);
2338 		if (ichdr.freemap[i].base == tablesize) {
2339 			ichdr.freemap[i].base -= sizeof(xfs_attr_leaf_entry_t);
2340 			ichdr.freemap[i].size += sizeof(xfs_attr_leaf_entry_t);
2341 		}
2342 
2343 		if (ichdr.freemap[i].base + ichdr.freemap[i].size ==
2344 				be16_to_cpu(entry->nameidx)) {
2345 			before = i;
2346 		} else if (ichdr.freemap[i].base ==
2347 				(be16_to_cpu(entry->nameidx) + entsize)) {
2348 			after = i;
2349 		} else if (ichdr.freemap[i].size < tmp) {
2350 			tmp = ichdr.freemap[i].size;
2351 			smallest = i;
2352 		}
2353 	}
2354 
2355 	/*
2356 	 * Coalesce adjacent freemap regions,
2357 	 * or replace the smallest region.
2358 	 */
2359 	if ((before >= 0) || (after >= 0)) {
2360 		if ((before >= 0) && (after >= 0)) {
2361 			ichdr.freemap[before].size += entsize;
2362 			ichdr.freemap[before].size += ichdr.freemap[after].size;
2363 			ichdr.freemap[after].base = 0;
2364 			ichdr.freemap[after].size = 0;
2365 		} else if (before >= 0) {
2366 			ichdr.freemap[before].size += entsize;
2367 		} else {
2368 			ichdr.freemap[after].base = be16_to_cpu(entry->nameidx);
2369 			ichdr.freemap[after].size += entsize;
2370 		}
2371 	} else {
2372 		/*
2373 		 * Replace smallest region (if it is smaller than free'd entry)
2374 		 */
2375 		if (ichdr.freemap[smallest].size < entsize) {
2376 			ichdr.freemap[smallest].base = be16_to_cpu(entry->nameidx);
2377 			ichdr.freemap[smallest].size = entsize;
2378 		}
2379 	}
2380 
2381 	/*
2382 	 * Did we remove the first entry?
2383 	 */
2384 	if (be16_to_cpu(entry->nameidx) == ichdr.firstused)
2385 		smallest = 1;
2386 	else
2387 		smallest = 0;
2388 
2389 	/*
2390 	 * Compress the remaining entries and zero out the removed stuff.
2391 	 */
2392 	memset(xfs_attr3_leaf_name(leaf, args->index), 0, entsize);
2393 	ichdr.usedbytes -= entsize;
2394 	xfs_trans_log_buf(args->trans, bp,
2395 	     XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index),
2396 				   entsize));
2397 
2398 	tmp = (ichdr.count - args->index) * sizeof(xfs_attr_leaf_entry_t);
2399 	memmove(entry, entry + 1, tmp);
2400 	ichdr.count--;
2401 	xfs_trans_log_buf(args->trans, bp,
2402 	    XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(xfs_attr_leaf_entry_t)));
2403 
2404 	entry = &xfs_attr3_leaf_entryp(leaf)[ichdr.count];
2405 	memset(entry, 0, sizeof(xfs_attr_leaf_entry_t));
2406 
2407 	/*
2408 	 * If we removed the first entry, re-find the first used byte
2409 	 * in the name area.  Note that if the entry was the "firstused",
2410 	 * then we don't have a "hole" in our block resulting from
2411 	 * removing the name.
2412 	 */
2413 	if (smallest) {
2414 		tmp = args->geo->blksize;
2415 		entry = xfs_attr3_leaf_entryp(leaf);
2416 		for (i = ichdr.count - 1; i >= 0; entry++, i--) {
2417 			ASSERT(be16_to_cpu(entry->nameidx) >= ichdr.firstused);
2418 			ASSERT(be16_to_cpu(entry->nameidx) < args->geo->blksize);
2419 
2420 			if (be16_to_cpu(entry->nameidx) < tmp)
2421 				tmp = be16_to_cpu(entry->nameidx);
2422 		}
2423 		ichdr.firstused = tmp;
2424 		ASSERT(ichdr.firstused != 0);
2425 	} else {
2426 		ichdr.holes = 1;	/* mark as needing compaction */
2427 	}
2428 	xfs_attr3_leaf_hdr_to_disk(args->geo, leaf, &ichdr);
2429 	xfs_trans_log_buf(args->trans, bp,
2430 			  XFS_DA_LOGRANGE(leaf, &leaf->hdr,
2431 					  xfs_attr3_leaf_hdr_size(leaf)));
2432 
2433 	/*
2434 	 * Check if leaf is less than 50% full, caller may want to
2435 	 * "join" the leaf with a sibling if so.
2436 	 */
2437 	tmp = ichdr.usedbytes + xfs_attr_leaf_entries_end(ichdr.count, leaf);
2438 
2439 	return tmp < args->geo->magicpct; /* leaf is < 37% full */
2440 }
2441 
2442 /*
2443  * Move all the attribute list entries from drop_leaf into save_leaf.
2444  */
2445 void
2446 xfs_attr3_leaf_unbalance(
2447 	struct xfs_da_state	*state,
2448 	struct xfs_da_state_blk	*drop_blk,
2449 	struct xfs_da_state_blk	*save_blk)
2450 {
2451 	struct xfs_attr_leafblock *drop_leaf = drop_blk->bp->b_addr;
2452 	struct xfs_attr_leafblock *save_leaf = save_blk->bp->b_addr;
2453 	struct xfs_attr3_icleaf_hdr drophdr;
2454 	struct xfs_attr3_icleaf_hdr savehdr;
2455 	struct xfs_attr_leaf_entry *entry;
2456 
2457 	trace_xfs_attr_leaf_unbalance(state->args);
2458 
2459 	xfs_attr3_leaf_hdr_from_disk(state->args->geo, &drophdr, drop_leaf);
2460 	xfs_attr3_leaf_hdr_from_disk(state->args->geo, &savehdr, save_leaf);
2461 	entry = xfs_attr3_leaf_entryp(drop_leaf);
2462 
2463 	/*
2464 	 * Save last hashval from dying block for later Btree fixup.
2465 	 */
2466 	drop_blk->hashval = be32_to_cpu(entry[drophdr.count - 1].hashval);
2467 
2468 	/*
2469 	 * Check if we need a temp buffer, or can we do it in place.
2470 	 * Note that we don't check "leaf" for holes because we will
2471 	 * always be dropping it, toosmall() decided that for us already.
2472 	 */
2473 	if (savehdr.holes == 0) {
2474 		/*
2475 		 * dest leaf has no holes, so we add there.  May need
2476 		 * to make some room in the entry array.
2477 		 */
2478 		if (xfs_attr3_leaf_order(save_blk->bp, &savehdr,
2479 					 drop_blk->bp, &drophdr)) {
2480 			xfs_attr3_leaf_moveents(state->args,
2481 						drop_leaf, &drophdr, 0,
2482 						save_leaf, &savehdr, 0,
2483 						drophdr.count);
2484 		} else {
2485 			xfs_attr3_leaf_moveents(state->args,
2486 						drop_leaf, &drophdr, 0,
2487 						save_leaf, &savehdr,
2488 						savehdr.count, drophdr.count);
2489 		}
2490 	} else {
2491 		/*
2492 		 * Destination has holes, so we make a temporary copy
2493 		 * of the leaf and add them both to that.
2494 		 */
2495 		struct xfs_attr_leafblock *tmp_leaf;
2496 		struct xfs_attr3_icleaf_hdr tmphdr;
2497 
2498 		tmp_leaf = kvzalloc(state->args->geo->blksize,
2499 				GFP_KERNEL | __GFP_NOFAIL);
2500 
2501 		/*
2502 		 * Copy the header into the temp leaf so that all the stuff
2503 		 * not in the incore header is present and gets copied back in
2504 		 * once we've moved all the entries.
2505 		 */
2506 		memcpy(tmp_leaf, save_leaf, xfs_attr3_leaf_hdr_size(save_leaf));
2507 
2508 		memset(&tmphdr, 0, sizeof(tmphdr));
2509 		tmphdr.magic = savehdr.magic;
2510 		tmphdr.forw = savehdr.forw;
2511 		tmphdr.back = savehdr.back;
2512 		tmphdr.firstused = state->args->geo->blksize;
2513 
2514 		/* write the header to the temp buffer to initialise it */
2515 		xfs_attr3_leaf_hdr_to_disk(state->args->geo, tmp_leaf, &tmphdr);
2516 
2517 		if (xfs_attr3_leaf_order(save_blk->bp, &savehdr,
2518 					 drop_blk->bp, &drophdr)) {
2519 			xfs_attr3_leaf_moveents(state->args,
2520 						drop_leaf, &drophdr, 0,
2521 						tmp_leaf, &tmphdr, 0,
2522 						drophdr.count);
2523 			xfs_attr3_leaf_moveents(state->args,
2524 						save_leaf, &savehdr, 0,
2525 						tmp_leaf, &tmphdr, tmphdr.count,
2526 						savehdr.count);
2527 		} else {
2528 			xfs_attr3_leaf_moveents(state->args,
2529 						save_leaf, &savehdr, 0,
2530 						tmp_leaf, &tmphdr, 0,
2531 						savehdr.count);
2532 			xfs_attr3_leaf_moveents(state->args,
2533 						drop_leaf, &drophdr, 0,
2534 						tmp_leaf, &tmphdr, tmphdr.count,
2535 						drophdr.count);
2536 		}
2537 		memcpy(save_leaf, tmp_leaf, state->args->geo->blksize);
2538 		savehdr = tmphdr; /* struct copy */
2539 		kvfree(tmp_leaf);
2540 	}
2541 
2542 	xfs_attr3_leaf_hdr_to_disk(state->args->geo, save_leaf, &savehdr);
2543 	xfs_trans_log_buf(state->args->trans, save_blk->bp, 0,
2544 					   state->args->geo->blksize - 1);
2545 
2546 	/*
2547 	 * Copy out last hashval in each block for B-tree code.
2548 	 */
2549 	entry = xfs_attr3_leaf_entryp(save_leaf);
2550 	save_blk->hashval = be32_to_cpu(entry[savehdr.count - 1].hashval);
2551 }
2552 
2553 /*========================================================================
2554  * Routines used for finding things in the Btree.
2555  *========================================================================*/
2556 
2557 /*
2558  * Look up a name in a leaf attribute list structure.
2559  * This is the internal routine, it uses the caller's buffer.
2560  *
2561  * Note that duplicate keys are allowed, but only check within the
2562  * current leaf node.  The Btree code must check in adjacent leaf nodes.
2563  *
2564  * Return in args->index the index into the entry[] array of either
2565  * the found entry, or where the entry should have been (insert before
2566  * that entry).
2567  *
2568  * Don't change the args->value unless we find the attribute.
2569  */
2570 int
2571 xfs_attr3_leaf_lookup_int(
2572 	struct xfs_buf		*bp,
2573 	struct xfs_da_args	*args)
2574 {
2575 	struct xfs_attr_leafblock *leaf;
2576 	struct xfs_attr3_icleaf_hdr ichdr;
2577 	struct xfs_attr_leaf_entry *entry;
2578 	struct xfs_attr_leaf_entry *entries;
2579 	struct xfs_attr_leaf_name_local *name_loc;
2580 	struct xfs_attr_leaf_name_remote *name_rmt;
2581 	xfs_dahash_t		hashval;
2582 	int			probe;
2583 	int			span;
2584 
2585 	trace_xfs_attr_leaf_lookup(args);
2586 
2587 	leaf = bp->b_addr;
2588 	xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
2589 	entries = xfs_attr3_leaf_entryp(leaf);
2590 	if (ichdr.count >= args->geo->blksize / 8) {
2591 		xfs_buf_mark_corrupt(bp);
2592 		xfs_da_mark_sick(args);
2593 		return -EFSCORRUPTED;
2594 	}
2595 
2596 	/*
2597 	 * Binary search.  (note: small blocks will skip this loop)
2598 	 */
2599 	hashval = args->hashval;
2600 	probe = span = ichdr.count / 2;
2601 	for (entry = &entries[probe]; span > 4; entry = &entries[probe]) {
2602 		span /= 2;
2603 		if (be32_to_cpu(entry->hashval) < hashval)
2604 			probe += span;
2605 		else if (be32_to_cpu(entry->hashval) > hashval)
2606 			probe -= span;
2607 		else
2608 			break;
2609 	}
2610 	if (!(probe >= 0 && (!ichdr.count || probe < ichdr.count))) {
2611 		xfs_buf_mark_corrupt(bp);
2612 		xfs_da_mark_sick(args);
2613 		return -EFSCORRUPTED;
2614 	}
2615 	if (!(span <= 4 || be32_to_cpu(entry->hashval) == hashval)) {
2616 		xfs_buf_mark_corrupt(bp);
2617 		xfs_da_mark_sick(args);
2618 		return -EFSCORRUPTED;
2619 	}
2620 
2621 	/*
2622 	 * Since we may have duplicate hashval's, find the first matching
2623 	 * hashval in the leaf.
2624 	 */
2625 	while (probe > 0 && be32_to_cpu(entry->hashval) >= hashval) {
2626 		entry--;
2627 		probe--;
2628 	}
2629 	while (probe < ichdr.count &&
2630 	       be32_to_cpu(entry->hashval) < hashval) {
2631 		entry++;
2632 		probe++;
2633 	}
2634 	if (probe == ichdr.count || be32_to_cpu(entry->hashval) != hashval) {
2635 		args->index = probe;
2636 		return -ENOATTR;
2637 	}
2638 
2639 	/*
2640 	 * Duplicate keys may be present, so search all of them for a match.
2641 	 */
2642 	for (; probe < ichdr.count && (be32_to_cpu(entry->hashval) == hashval);
2643 			entry++, probe++) {
2644 /*
2645  * GROT: Add code to remove incomplete entries.
2646  */
2647 		if (entry->flags & XFS_ATTR_LOCAL) {
2648 			name_loc = xfs_attr3_leaf_name_local(leaf, probe);
2649 			if (!xfs_attr_match(args, entry->flags,
2650 					name_loc->nameval, name_loc->namelen,
2651 					&name_loc->nameval[name_loc->namelen],
2652 					be16_to_cpu(name_loc->valuelen)))
2653 				continue;
2654 			args->index = probe;
2655 			return -EEXIST;
2656 		} else {
2657 			unsigned int	valuelen;
2658 
2659 			name_rmt = xfs_attr3_leaf_name_remote(leaf, probe);
2660 			valuelen = be32_to_cpu(name_rmt->valuelen);
2661 			if (!xfs_attr_match(args, entry->flags, name_rmt->name,
2662 					name_rmt->namelen, NULL, valuelen))
2663 				continue;
2664 			args->index = probe;
2665 			args->rmtvaluelen = valuelen;
2666 			args->rmtblkno = be32_to_cpu(name_rmt->valueblk);
2667 			args->rmtblkcnt = xfs_attr3_rmt_blocks(
2668 							args->dp->i_mount,
2669 							args->rmtvaluelen);
2670 			return -EEXIST;
2671 		}
2672 	}
2673 	args->index = probe;
2674 	return -ENOATTR;
2675 }
2676 
2677 /*
2678  * Get the value associated with an attribute name from a leaf attribute
2679  * list structure.
2680  *
2681  * If args->valuelen is zero, only the length needs to be returned.  Unlike a
2682  * lookup, we only return an error if the attribute does not exist or we can't
2683  * retrieve the value.
2684  */
2685 int
2686 xfs_attr3_leaf_getvalue(
2687 	struct xfs_buf		*bp,
2688 	struct xfs_da_args	*args)
2689 {
2690 	struct xfs_attr_leafblock *leaf;
2691 	struct xfs_attr3_icleaf_hdr ichdr;
2692 	struct xfs_attr_leaf_entry *entry;
2693 	struct xfs_attr_leaf_name_local *name_loc;
2694 	struct xfs_attr_leaf_name_remote *name_rmt;
2695 
2696 	leaf = bp->b_addr;
2697 	xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
2698 	ASSERT(ichdr.count < args->geo->blksize / 8);
2699 	ASSERT(args->index < ichdr.count);
2700 
2701 	entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
2702 	if (entry->flags & XFS_ATTR_LOCAL) {
2703 		name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
2704 		ASSERT(name_loc->namelen == args->namelen);
2705 		ASSERT(memcmp(args->name, name_loc->nameval, args->namelen) == 0);
2706 		return xfs_attr_copy_value(args,
2707 					&name_loc->nameval[args->namelen],
2708 					be16_to_cpu(name_loc->valuelen));
2709 	}
2710 
2711 	name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
2712 	ASSERT(name_rmt->namelen == args->namelen);
2713 	ASSERT(memcmp(args->name, name_rmt->name, args->namelen) == 0);
2714 	args->rmtvaluelen = be32_to_cpu(name_rmt->valuelen);
2715 	args->rmtblkno = be32_to_cpu(name_rmt->valueblk);
2716 	args->rmtblkcnt = xfs_attr3_rmt_blocks(args->dp->i_mount,
2717 					       args->rmtvaluelen);
2718 	return xfs_attr_copy_value(args, NULL, args->rmtvaluelen);
2719 }
2720 
2721 /*========================================================================
2722  * Utility routines.
2723  *========================================================================*/
2724 
2725 /*
2726  * Move the indicated entries from one leaf to another.
2727  * NOTE: this routine modifies both source and destination leaves.
2728  */
2729 /*ARGSUSED*/
2730 STATIC void
2731 xfs_attr3_leaf_moveents(
2732 	struct xfs_da_args		*args,
2733 	struct xfs_attr_leafblock	*leaf_s,
2734 	struct xfs_attr3_icleaf_hdr	*ichdr_s,
2735 	int				start_s,
2736 	struct xfs_attr_leafblock	*leaf_d,
2737 	struct xfs_attr3_icleaf_hdr	*ichdr_d,
2738 	int				start_d,
2739 	int				count)
2740 {
2741 	struct xfs_attr_leaf_entry	*entry_s;
2742 	struct xfs_attr_leaf_entry	*entry_d;
2743 	int				desti;
2744 	int				tmp;
2745 	int				i;
2746 
2747 	/*
2748 	 * Check for nothing to do.
2749 	 */
2750 	if (count == 0)
2751 		return;
2752 
2753 	/*
2754 	 * Set up environment.
2755 	 */
2756 	ASSERT(ichdr_s->magic == XFS_ATTR_LEAF_MAGIC ||
2757 	       ichdr_s->magic == XFS_ATTR3_LEAF_MAGIC);
2758 	ASSERT(ichdr_s->magic == ichdr_d->magic);
2759 	ASSERT(ichdr_s->count > 0 && ichdr_s->count < args->geo->blksize / 8);
2760 	ASSERT(ichdr_s->firstused >=
2761 			xfs_attr_leaf_entries_end(ichdr_s->count, leaf_s));
2762 	ASSERT(ichdr_d->count < args->geo->blksize / 8);
2763 	ASSERT(ichdr_d->firstused >=
2764 			xfs_attr_leaf_entries_end(ichdr_d->count, leaf_d));
2765 
2766 	ASSERT(start_s < ichdr_s->count);
2767 	ASSERT(start_d <= ichdr_d->count);
2768 	ASSERT(count <= ichdr_s->count);
2769 
2770 
2771 	/*
2772 	 * Move the entries in the destination leaf up to make a hole?
2773 	 */
2774 	if (start_d < ichdr_d->count) {
2775 		tmp  = ichdr_d->count - start_d;
2776 		tmp *= sizeof(xfs_attr_leaf_entry_t);
2777 		entry_s = &xfs_attr3_leaf_entryp(leaf_d)[start_d];
2778 		entry_d = &xfs_attr3_leaf_entryp(leaf_d)[start_d + count];
2779 		memmove(entry_d, entry_s, tmp);
2780 	}
2781 
2782 	/*
2783 	 * Copy all entry's in the same (sorted) order,
2784 	 * but allocate attribute info packed and in sequence.
2785 	 */
2786 	entry_s = &xfs_attr3_leaf_entryp(leaf_s)[start_s];
2787 	entry_d = &xfs_attr3_leaf_entryp(leaf_d)[start_d];
2788 	desti = start_d;
2789 	for (i = 0; i < count; entry_s++, entry_d++, desti++, i++) {
2790 		ASSERT(be16_to_cpu(entry_s->nameidx) >= ichdr_s->firstused);
2791 		tmp = xfs_attr_leaf_entsize(leaf_s, start_s + i);
2792 #ifdef GROT
2793 		/*
2794 		 * Code to drop INCOMPLETE entries.  Difficult to use as we
2795 		 * may also need to change the insertion index.  Code turned
2796 		 * off for 6.2, should be revisited later.
2797 		 */
2798 		if (entry_s->flags & XFS_ATTR_INCOMPLETE) { /* skip partials? */
2799 			memset(xfs_attr3_leaf_name(leaf_s, start_s + i), 0, tmp);
2800 			ichdr_s->usedbytes -= tmp;
2801 			ichdr_s->count -= 1;
2802 			entry_d--;	/* to compensate for ++ in loop hdr */
2803 			desti--;
2804 			if ((start_s + i) < offset)
2805 				result++;	/* insertion index adjustment */
2806 		} else {
2807 #endif /* GROT */
2808 			ichdr_d->firstused -= tmp;
2809 			/* both on-disk, don't endian flip twice */
2810 			entry_d->hashval = entry_s->hashval;
2811 			entry_d->nameidx = cpu_to_be16(ichdr_d->firstused);
2812 			entry_d->flags = entry_s->flags;
2813 			ASSERT(be16_to_cpu(entry_d->nameidx) + tmp
2814 							<= args->geo->blksize);
2815 			memmove(xfs_attr3_leaf_name(leaf_d, desti),
2816 				xfs_attr3_leaf_name(leaf_s, start_s + i), tmp);
2817 			ASSERT(be16_to_cpu(entry_s->nameidx) + tmp
2818 							<= args->geo->blksize);
2819 			memset(xfs_attr3_leaf_name(leaf_s, start_s + i), 0, tmp);
2820 			ichdr_s->usedbytes -= tmp;
2821 			ichdr_d->usedbytes += tmp;
2822 			ichdr_s->count -= 1;
2823 			ichdr_d->count += 1;
2824 			tmp = xfs_attr_leaf_entries_end(ichdr_d->count, leaf_d);
2825 			ASSERT(ichdr_d->firstused >= tmp);
2826 #ifdef GROT
2827 		}
2828 #endif /* GROT */
2829 	}
2830 
2831 	/*
2832 	 * Zero out the entries we just copied.
2833 	 */
2834 	if (start_s == ichdr_s->count) {
2835 		tmp = count * sizeof(xfs_attr_leaf_entry_t);
2836 		entry_s = &xfs_attr3_leaf_entryp(leaf_s)[start_s];
2837 		ASSERT(((char *)entry_s + tmp) <=
2838 		       ((char *)leaf_s + args->geo->blksize));
2839 		memset(entry_s, 0, tmp);
2840 	} else {
2841 		/*
2842 		 * Move the remaining entries down to fill the hole,
2843 		 * then zero the entries at the top.
2844 		 */
2845 		tmp  = (ichdr_s->count - count) * sizeof(xfs_attr_leaf_entry_t);
2846 		entry_s = &xfs_attr3_leaf_entryp(leaf_s)[start_s + count];
2847 		entry_d = &xfs_attr3_leaf_entryp(leaf_s)[start_s];
2848 		memmove(entry_d, entry_s, tmp);
2849 
2850 		tmp = count * sizeof(xfs_attr_leaf_entry_t);
2851 		entry_s = &xfs_attr3_leaf_entryp(leaf_s)[ichdr_s->count];
2852 		ASSERT(((char *)entry_s + tmp) <=
2853 		       ((char *)leaf_s + args->geo->blksize));
2854 		memset(entry_s, 0, tmp);
2855 	}
2856 
2857 	/*
2858 	 * Fill in the freemap information
2859 	 */
2860 	ichdr_d->freemap[0].base =
2861 		xfs_attr_leaf_entries_end(ichdr_d->count, leaf_d);
2862 	ichdr_d->freemap[0].size = ichdr_d->firstused - ichdr_d->freemap[0].base;
2863 	ichdr_d->freemap[1].base = 0;
2864 	ichdr_d->freemap[2].base = 0;
2865 	ichdr_d->freemap[1].size = 0;
2866 	ichdr_d->freemap[2].size = 0;
2867 	ichdr_s->holes = 1;	/* leaf may not be compact */
2868 }
2869 
2870 /*
2871  * Pick up the last hashvalue from a leaf block.
2872  */
2873 xfs_dahash_t
2874 xfs_attr_leaf_lasthash(
2875 	struct xfs_buf	*bp,
2876 	int		*count)
2877 {
2878 	struct xfs_attr3_icleaf_hdr ichdr;
2879 	struct xfs_attr_leaf_entry *entries;
2880 	struct xfs_mount *mp = bp->b_mount;
2881 
2882 	xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &ichdr, bp->b_addr);
2883 	entries = xfs_attr3_leaf_entryp(bp->b_addr);
2884 	if (count)
2885 		*count = ichdr.count;
2886 	if (!ichdr.count)
2887 		return 0;
2888 	return be32_to_cpu(entries[ichdr.count - 1].hashval);
2889 }
2890 
2891 /*
2892  * Calculate the number of bytes used to store the indicated attribute
2893  * (whether local or remote only calculate bytes in this block).
2894  */
2895 STATIC int
2896 xfs_attr_leaf_entsize(xfs_attr_leafblock_t *leaf, int index)
2897 {
2898 	struct xfs_attr_leaf_entry *entries;
2899 	xfs_attr_leaf_name_local_t *name_loc;
2900 	xfs_attr_leaf_name_remote_t *name_rmt;
2901 	int size;
2902 
2903 	entries = xfs_attr3_leaf_entryp(leaf);
2904 	if (entries[index].flags & XFS_ATTR_LOCAL) {
2905 		name_loc = xfs_attr3_leaf_name_local(leaf, index);
2906 		size = xfs_attr_leaf_entsize_local(name_loc->namelen,
2907 						   be16_to_cpu(name_loc->valuelen));
2908 	} else {
2909 		name_rmt = xfs_attr3_leaf_name_remote(leaf, index);
2910 		size = xfs_attr_leaf_entsize_remote(name_rmt->namelen);
2911 	}
2912 	return size;
2913 }
2914 
2915 /*
2916  * Calculate the number of bytes that would be required to store the new
2917  * attribute (whether local or remote only calculate bytes in this block).
2918  * This routine decides as a side effect whether the attribute will be
2919  * a "local" or a "remote" attribute.
2920  */
2921 int
2922 xfs_attr_leaf_newentsize(
2923 	struct xfs_da_args	*args,
2924 	int			*local)
2925 {
2926 	int			size;
2927 
2928 	size = xfs_attr_leaf_entsize_local(args->namelen, args->valuelen);
2929 	if (size < xfs_attr_leaf_entsize_local_max(args->geo->blksize)) {
2930 		if (local)
2931 			*local = 1;
2932 		return size;
2933 	}
2934 	if (local)
2935 		*local = 0;
2936 	return xfs_attr_leaf_entsize_remote(args->namelen);
2937 }
2938 
2939 
2940 /*========================================================================
2941  * Manage the INCOMPLETE flag in a leaf entry
2942  *========================================================================*/
2943 
2944 /*
2945  * Clear the INCOMPLETE flag on an entry in a leaf block.
2946  */
2947 int
2948 xfs_attr3_leaf_clearflag(
2949 	struct xfs_da_args	*args)
2950 {
2951 	struct xfs_attr_leafblock *leaf;
2952 	struct xfs_attr_leaf_entry *entry;
2953 	struct xfs_attr_leaf_name_remote *name_rmt;
2954 	struct xfs_buf		*bp;
2955 	int			error;
2956 #ifdef DEBUG
2957 	struct xfs_attr3_icleaf_hdr ichdr;
2958 	xfs_attr_leaf_name_local_t *name_loc;
2959 	int namelen;
2960 	char *name;
2961 #endif /* DEBUG */
2962 
2963 	trace_xfs_attr_leaf_clearflag(args);
2964 	/*
2965 	 * Set up the operation.
2966 	 */
2967 	error = xfs_attr3_leaf_read(args->trans, args->dp, args->owner,
2968 			args->blkno, &bp);
2969 	if (error)
2970 		return error;
2971 
2972 	leaf = bp->b_addr;
2973 	entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
2974 	ASSERT(entry->flags & XFS_ATTR_INCOMPLETE);
2975 
2976 #ifdef DEBUG
2977 	xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
2978 	ASSERT(args->index < ichdr.count);
2979 	ASSERT(args->index >= 0);
2980 
2981 	if (entry->flags & XFS_ATTR_LOCAL) {
2982 		name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
2983 		namelen = name_loc->namelen;
2984 		name = (char *)name_loc->nameval;
2985 	} else {
2986 		name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
2987 		namelen = name_rmt->namelen;
2988 		name = (char *)name_rmt->name;
2989 	}
2990 	ASSERT(be32_to_cpu(entry->hashval) == args->hashval);
2991 	ASSERT(namelen == args->namelen);
2992 	ASSERT(memcmp(name, args->name, namelen) == 0);
2993 #endif /* DEBUG */
2994 
2995 	entry->flags &= ~XFS_ATTR_INCOMPLETE;
2996 	xfs_trans_log_buf(args->trans, bp,
2997 			 XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
2998 
2999 	if (args->rmtblkno) {
3000 		ASSERT((entry->flags & XFS_ATTR_LOCAL) == 0);
3001 		name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
3002 		name_rmt->valueblk = cpu_to_be32(args->rmtblkno);
3003 		name_rmt->valuelen = cpu_to_be32(args->rmtvaluelen);
3004 		xfs_trans_log_buf(args->trans, bp,
3005 			 XFS_DA_LOGRANGE(leaf, name_rmt, sizeof(*name_rmt)));
3006 	}
3007 
3008 	return 0;
3009 }
3010 
3011 /*
3012  * Set the INCOMPLETE flag on an entry in a leaf block.
3013  */
3014 int
3015 xfs_attr3_leaf_setflag(
3016 	struct xfs_da_args	*args)
3017 {
3018 	struct xfs_attr_leafblock *leaf;
3019 	struct xfs_attr_leaf_entry *entry;
3020 	struct xfs_attr_leaf_name_remote *name_rmt;
3021 	struct xfs_buf		*bp;
3022 	int error;
3023 #ifdef DEBUG
3024 	struct xfs_attr3_icleaf_hdr ichdr;
3025 #endif
3026 
3027 	trace_xfs_attr_leaf_setflag(args);
3028 
3029 	/*
3030 	 * Set up the operation.
3031 	 */
3032 	error = xfs_attr3_leaf_read(args->trans, args->dp, args->owner,
3033 			args->blkno, &bp);
3034 	if (error)
3035 		return error;
3036 
3037 	leaf = bp->b_addr;
3038 #ifdef DEBUG
3039 	xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr, leaf);
3040 	ASSERT(args->index < ichdr.count);
3041 	ASSERT(args->index >= 0);
3042 #endif
3043 	entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
3044 
3045 	ASSERT((entry->flags & XFS_ATTR_INCOMPLETE) == 0);
3046 	entry->flags |= XFS_ATTR_INCOMPLETE;
3047 	xfs_trans_log_buf(args->trans, bp,
3048 			XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));
3049 	if ((entry->flags & XFS_ATTR_LOCAL) == 0) {
3050 		name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
3051 		name_rmt->valueblk = 0;
3052 		name_rmt->valuelen = 0;
3053 		xfs_trans_log_buf(args->trans, bp,
3054 			 XFS_DA_LOGRANGE(leaf, name_rmt, sizeof(*name_rmt)));
3055 	}
3056 
3057 	return 0;
3058 }
3059 
3060 /*
3061  * In a single transaction, clear the INCOMPLETE flag on the leaf entry
3062  * given by args->blkno/index and set the INCOMPLETE flag on the leaf
3063  * entry given by args->blkno2/index2.
3064  *
3065  * Note that they could be in different blocks, or in the same block.
3066  */
3067 int
3068 xfs_attr3_leaf_flipflags(
3069 	struct xfs_da_args	*args)
3070 {
3071 	struct xfs_attr_leafblock *leaf1;
3072 	struct xfs_attr_leafblock *leaf2;
3073 	struct xfs_attr_leaf_entry *entry1;
3074 	struct xfs_attr_leaf_entry *entry2;
3075 	struct xfs_attr_leaf_name_remote *name_rmt;
3076 	struct xfs_buf		*bp1;
3077 	struct xfs_buf		*bp2;
3078 	int error;
3079 #ifdef DEBUG
3080 	struct xfs_attr3_icleaf_hdr ichdr1;
3081 	struct xfs_attr3_icleaf_hdr ichdr2;
3082 	xfs_attr_leaf_name_local_t *name_loc;
3083 	int namelen1, namelen2;
3084 	char *name1, *name2;
3085 #endif /* DEBUG */
3086 
3087 	trace_xfs_attr_leaf_flipflags(args);
3088 
3089 	/*
3090 	 * Read the block containing the "old" attr
3091 	 */
3092 	error = xfs_attr3_leaf_read(args->trans, args->dp, args->owner,
3093 			args->blkno, &bp1);
3094 	if (error)
3095 		return error;
3096 
3097 	/*
3098 	 * Read the block containing the "new" attr, if it is different
3099 	 */
3100 	if (args->blkno2 != args->blkno) {
3101 		error = xfs_attr3_leaf_read(args->trans, args->dp, args->owner,
3102 				args->blkno2, &bp2);
3103 		if (error)
3104 			return error;
3105 	} else {
3106 		bp2 = bp1;
3107 	}
3108 
3109 	leaf1 = bp1->b_addr;
3110 	entry1 = &xfs_attr3_leaf_entryp(leaf1)[args->index];
3111 
3112 	leaf2 = bp2->b_addr;
3113 	entry2 = &xfs_attr3_leaf_entryp(leaf2)[args->index2];
3114 
3115 #ifdef DEBUG
3116 	xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr1, leaf1);
3117 	ASSERT(args->index < ichdr1.count);
3118 	ASSERT(args->index >= 0);
3119 
3120 	xfs_attr3_leaf_hdr_from_disk(args->geo, &ichdr2, leaf2);
3121 	ASSERT(args->index2 < ichdr2.count);
3122 	ASSERT(args->index2 >= 0);
3123 
3124 	if (entry1->flags & XFS_ATTR_LOCAL) {
3125 		name_loc = xfs_attr3_leaf_name_local(leaf1, args->index);
3126 		namelen1 = name_loc->namelen;
3127 		name1 = (char *)name_loc->nameval;
3128 	} else {
3129 		name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index);
3130 		namelen1 = name_rmt->namelen;
3131 		name1 = (char *)name_rmt->name;
3132 	}
3133 	if (entry2->flags & XFS_ATTR_LOCAL) {
3134 		name_loc = xfs_attr3_leaf_name_local(leaf2, args->index2);
3135 		namelen2 = name_loc->namelen;
3136 		name2 = (char *)name_loc->nameval;
3137 	} else {
3138 		name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2);
3139 		namelen2 = name_rmt->namelen;
3140 		name2 = (char *)name_rmt->name;
3141 	}
3142 	ASSERT(be32_to_cpu(entry1->hashval) == be32_to_cpu(entry2->hashval));
3143 	ASSERT(namelen1 == namelen2);
3144 	ASSERT(memcmp(name1, name2, namelen1) == 0);
3145 #endif /* DEBUG */
3146 
3147 	ASSERT(entry1->flags & XFS_ATTR_INCOMPLETE);
3148 	ASSERT((entry2->flags & XFS_ATTR_INCOMPLETE) == 0);
3149 
3150 	entry1->flags &= ~XFS_ATTR_INCOMPLETE;
3151 	xfs_trans_log_buf(args->trans, bp1,
3152 			  XFS_DA_LOGRANGE(leaf1, entry1, sizeof(*entry1)));
3153 	if (args->rmtblkno) {
3154 		ASSERT((entry1->flags & XFS_ATTR_LOCAL) == 0);
3155 		name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index);
3156 		name_rmt->valueblk = cpu_to_be32(args->rmtblkno);
3157 		name_rmt->valuelen = cpu_to_be32(args->rmtvaluelen);
3158 		xfs_trans_log_buf(args->trans, bp1,
3159 			 XFS_DA_LOGRANGE(leaf1, name_rmt, sizeof(*name_rmt)));
3160 	}
3161 
3162 	entry2->flags |= XFS_ATTR_INCOMPLETE;
3163 	xfs_trans_log_buf(args->trans, bp2,
3164 			  XFS_DA_LOGRANGE(leaf2, entry2, sizeof(*entry2)));
3165 	if ((entry2->flags & XFS_ATTR_LOCAL) == 0) {
3166 		name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2);
3167 		name_rmt->valueblk = 0;
3168 		name_rmt->valuelen = 0;
3169 		xfs_trans_log_buf(args->trans, bp2,
3170 			 XFS_DA_LOGRANGE(leaf2, name_rmt, sizeof(*name_rmt)));
3171 	}
3172 
3173 	return 0;
3174 }
3175