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