xref: /openbmc/linux/fs/ext4/xattr.c (revision 0545810f)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * linux/fs/ext4/xattr.c
4  *
5  * Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
6  *
7  * Fix by Harrison Xing <harrison@mountainviewdata.com>.
8  * Ext4 code with a lot of help from Eric Jarman <ejarman@acm.org>.
9  * Extended attributes for symlinks and special files added per
10  *  suggestion of Luka Renko <luka.renko@hermes.si>.
11  * xattr consolidation Copyright (c) 2004 James Morris <jmorris@redhat.com>,
12  *  Red Hat Inc.
13  * ea-in-inode support by Alex Tomas <alex@clusterfs.com> aka bzzz
14  *  and Andreas Gruenbacher <agruen@suse.de>.
15  */
16 
17 /*
18  * Extended attributes are stored directly in inodes (on file systems with
19  * inodes bigger than 128 bytes) and on additional disk blocks. The i_file_acl
20  * field contains the block number if an inode uses an additional block. All
21  * attributes must fit in the inode and one additional block. Blocks that
22  * contain the identical set of attributes may be shared among several inodes.
23  * Identical blocks are detected by keeping a cache of blocks that have
24  * recently been accessed.
25  *
26  * The attributes in inodes and on blocks have a different header; the entries
27  * are stored in the same format:
28  *
29  *   +------------------+
30  *   | header           |
31  *   | entry 1          | |
32  *   | entry 2          | | growing downwards
33  *   | entry 3          | v
34  *   | four null bytes  |
35  *   | . . .            |
36  *   | value 1          | ^
37  *   | value 3          | | growing upwards
38  *   | value 2          | |
39  *   +------------------+
40  *
41  * The header is followed by multiple entry descriptors. In disk blocks, the
42  * entry descriptors are kept sorted. In inodes, they are unsorted. The
43  * attribute values are aligned to the end of the block in no specific order.
44  *
45  * Locking strategy
46  * ----------------
47  * EXT4_I(inode)->i_file_acl is protected by EXT4_I(inode)->xattr_sem.
48  * EA blocks are only changed if they are exclusive to an inode, so
49  * holding xattr_sem also means that nothing but the EA block's reference
50  * count can change. Multiple writers to the same block are synchronized
51  * by the buffer lock.
52  */
53 
54 #include <linux/init.h>
55 #include <linux/fs.h>
56 #include <linux/slab.h>
57 #include <linux/mbcache.h>
58 #include <linux/quotaops.h>
59 #include <linux/iversion.h>
60 #include "ext4_jbd2.h"
61 #include "ext4.h"
62 #include "xattr.h"
63 #include "acl.h"
64 
65 #ifdef EXT4_XATTR_DEBUG
66 # define ea_idebug(inode, fmt, ...)					\
67 	printk(KERN_DEBUG "inode %s:%lu: " fmt "\n",			\
68 	       inode->i_sb->s_id, inode->i_ino, ##__VA_ARGS__)
69 # define ea_bdebug(bh, fmt, ...)					\
70 	printk(KERN_DEBUG "block %pg:%lu: " fmt "\n",			\
71 	       bh->b_bdev, (unsigned long)bh->b_blocknr, ##__VA_ARGS__)
72 #else
73 # define ea_idebug(inode, fmt, ...)	no_printk(fmt, ##__VA_ARGS__)
74 # define ea_bdebug(bh, fmt, ...)	no_printk(fmt, ##__VA_ARGS__)
75 #endif
76 
77 static void ext4_xattr_block_cache_insert(struct mb_cache *,
78 					  struct buffer_head *);
79 static struct buffer_head *
80 ext4_xattr_block_cache_find(struct inode *, struct ext4_xattr_header *,
81 			    struct mb_cache_entry **);
82 static __le32 ext4_xattr_hash_entry(char *name, size_t name_len, __le32 *value,
83 				    size_t value_count);
84 static __le32 ext4_xattr_hash_entry_signed(char *name, size_t name_len, __le32 *value,
85 				    size_t value_count);
86 static void ext4_xattr_rehash(struct ext4_xattr_header *);
87 
88 static const struct xattr_handler * const ext4_xattr_handler_map[] = {
89 	[EXT4_XATTR_INDEX_USER]		     = &ext4_xattr_user_handler,
90 #ifdef CONFIG_EXT4_FS_POSIX_ACL
91 	[EXT4_XATTR_INDEX_POSIX_ACL_ACCESS]  = &nop_posix_acl_access,
92 	[EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT] = &nop_posix_acl_default,
93 #endif
94 	[EXT4_XATTR_INDEX_TRUSTED]	     = &ext4_xattr_trusted_handler,
95 #ifdef CONFIG_EXT4_FS_SECURITY
96 	[EXT4_XATTR_INDEX_SECURITY]	     = &ext4_xattr_security_handler,
97 #endif
98 	[EXT4_XATTR_INDEX_HURD]		     = &ext4_xattr_hurd_handler,
99 };
100 
101 const struct xattr_handler *ext4_xattr_handlers[] = {
102 	&ext4_xattr_user_handler,
103 	&ext4_xattr_trusted_handler,
104 #ifdef CONFIG_EXT4_FS_SECURITY
105 	&ext4_xattr_security_handler,
106 #endif
107 	&ext4_xattr_hurd_handler,
108 	NULL
109 };
110 
111 #define EA_BLOCK_CACHE(inode)	(((struct ext4_sb_info *) \
112 				inode->i_sb->s_fs_info)->s_ea_block_cache)
113 
114 #define EA_INODE_CACHE(inode)	(((struct ext4_sb_info *) \
115 				inode->i_sb->s_fs_info)->s_ea_inode_cache)
116 
117 static int
118 ext4_expand_inode_array(struct ext4_xattr_inode_array **ea_inode_array,
119 			struct inode *inode);
120 
121 #ifdef CONFIG_LOCKDEP
122 void ext4_xattr_inode_set_class(struct inode *ea_inode)
123 {
124 	lockdep_set_subclass(&ea_inode->i_rwsem, 1);
125 }
126 #endif
127 
128 static __le32 ext4_xattr_block_csum(struct inode *inode,
129 				    sector_t block_nr,
130 				    struct ext4_xattr_header *hdr)
131 {
132 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
133 	__u32 csum;
134 	__le64 dsk_block_nr = cpu_to_le64(block_nr);
135 	__u32 dummy_csum = 0;
136 	int offset = offsetof(struct ext4_xattr_header, h_checksum);
137 
138 	csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&dsk_block_nr,
139 			   sizeof(dsk_block_nr));
140 	csum = ext4_chksum(sbi, csum, (__u8 *)hdr, offset);
141 	csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
142 	offset += sizeof(dummy_csum);
143 	csum = ext4_chksum(sbi, csum, (__u8 *)hdr + offset,
144 			   EXT4_BLOCK_SIZE(inode->i_sb) - offset);
145 
146 	return cpu_to_le32(csum);
147 }
148 
149 static int ext4_xattr_block_csum_verify(struct inode *inode,
150 					struct buffer_head *bh)
151 {
152 	struct ext4_xattr_header *hdr = BHDR(bh);
153 	int ret = 1;
154 
155 	if (ext4_has_metadata_csum(inode->i_sb)) {
156 		lock_buffer(bh);
157 		ret = (hdr->h_checksum == ext4_xattr_block_csum(inode,
158 							bh->b_blocknr, hdr));
159 		unlock_buffer(bh);
160 	}
161 	return ret;
162 }
163 
164 static void ext4_xattr_block_csum_set(struct inode *inode,
165 				      struct buffer_head *bh)
166 {
167 	if (ext4_has_metadata_csum(inode->i_sb))
168 		BHDR(bh)->h_checksum = ext4_xattr_block_csum(inode,
169 						bh->b_blocknr, BHDR(bh));
170 }
171 
172 static inline const char *ext4_xattr_prefix(int name_index,
173 					    struct dentry *dentry)
174 {
175 	const struct xattr_handler *handler = NULL;
176 
177 	if (name_index > 0 && name_index < ARRAY_SIZE(ext4_xattr_handler_map))
178 		handler = ext4_xattr_handler_map[name_index];
179 
180 	if (!xattr_handler_can_list(handler, dentry))
181 		return NULL;
182 
183 	return xattr_prefix(handler);
184 }
185 
186 static int
187 check_xattrs(struct inode *inode, struct buffer_head *bh,
188 	     struct ext4_xattr_entry *entry, void *end, void *value_start,
189 	     const char *function, unsigned int line)
190 {
191 	struct ext4_xattr_entry *e = entry;
192 	int err = -EFSCORRUPTED;
193 	char *err_str;
194 
195 	if (bh) {
196 		if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
197 		    BHDR(bh)->h_blocks != cpu_to_le32(1)) {
198 			err_str = "invalid header";
199 			goto errout;
200 		}
201 		if (buffer_verified(bh))
202 			return 0;
203 		if (!ext4_xattr_block_csum_verify(inode, bh)) {
204 			err = -EFSBADCRC;
205 			err_str = "invalid checksum";
206 			goto errout;
207 		}
208 	} else {
209 		struct ext4_xattr_ibody_header *header = value_start;
210 
211 		header -= 1;
212 		if (end - (void *)header < sizeof(*header) + sizeof(u32)) {
213 			err_str = "in-inode xattr block too small";
214 			goto errout;
215 		}
216 		if (header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
217 			err_str = "bad magic number in in-inode xattr";
218 			goto errout;
219 		}
220 	}
221 
222 	/* Find the end of the names list */
223 	while (!IS_LAST_ENTRY(e)) {
224 		struct ext4_xattr_entry *next = EXT4_XATTR_NEXT(e);
225 		if ((void *)next >= end) {
226 			err_str = "e_name out of bounds";
227 			goto errout;
228 		}
229 		if (strnlen(e->e_name, e->e_name_len) != e->e_name_len) {
230 			err_str = "bad e_name length";
231 			goto errout;
232 		}
233 		e = next;
234 	}
235 
236 	/* Check the values */
237 	while (!IS_LAST_ENTRY(entry)) {
238 		u32 size = le32_to_cpu(entry->e_value_size);
239 		unsigned long ea_ino = le32_to_cpu(entry->e_value_inum);
240 
241 		if (!ext4_has_feature_ea_inode(inode->i_sb) && ea_ino) {
242 			err_str = "ea_inode specified without ea_inode feature enabled";
243 			goto errout;
244 		}
245 		if (ea_ino && ((ea_ino == EXT4_ROOT_INO) ||
246 			       !ext4_valid_inum(inode->i_sb, ea_ino))) {
247 			err_str = "invalid ea_ino";
248 			goto errout;
249 		}
250 		if (size > EXT4_XATTR_SIZE_MAX) {
251 			err_str = "e_value size too large";
252 			goto errout;
253 		}
254 
255 		if (size != 0 && entry->e_value_inum == 0) {
256 			u16 offs = le16_to_cpu(entry->e_value_offs);
257 			void *value;
258 
259 			/*
260 			 * The value cannot overlap the names, and the value
261 			 * with padding cannot extend beyond 'end'.  Check both
262 			 * the padded and unpadded sizes, since the size may
263 			 * overflow to 0 when adding padding.
264 			 */
265 			if (offs > end - value_start) {
266 				err_str = "e_value out of bounds";
267 				goto errout;
268 			}
269 			value = value_start + offs;
270 			if (value < (void *)e + sizeof(u32) ||
271 			    size > end - value ||
272 			    EXT4_XATTR_SIZE(size) > end - value) {
273 				err_str = "overlapping e_value ";
274 				goto errout;
275 			}
276 		}
277 		entry = EXT4_XATTR_NEXT(entry);
278 	}
279 	if (bh)
280 		set_buffer_verified(bh);
281 	return 0;
282 
283 errout:
284 	if (bh)
285 		__ext4_error_inode(inode, function, line, 0, -err,
286 				   "corrupted xattr block %llu: %s",
287 				   (unsigned long long) bh->b_blocknr,
288 				   err_str);
289 	else
290 		__ext4_error_inode(inode, function, line, 0, -err,
291 				   "corrupted in-inode xattr: %s", err_str);
292 	return err;
293 }
294 
295 static inline int
296 __ext4_xattr_check_block(struct inode *inode, struct buffer_head *bh,
297 			 const char *function, unsigned int line)
298 {
299 	return check_xattrs(inode, bh, BFIRST(bh), bh->b_data + bh->b_size,
300 			    bh->b_data, function, line);
301 }
302 
303 #define ext4_xattr_check_block(inode, bh) \
304 	__ext4_xattr_check_block((inode), (bh),  __func__, __LINE__)
305 
306 
307 static inline int
308 __xattr_check_inode(struct inode *inode, struct ext4_xattr_ibody_header *header,
309 			 void *end, const char *function, unsigned int line)
310 {
311 	return check_xattrs(inode, NULL, IFIRST(header), end, IFIRST(header),
312 			    function, line);
313 }
314 
315 #define xattr_check_inode(inode, header, end) \
316 	__xattr_check_inode((inode), (header), (end), __func__, __LINE__)
317 
318 static int
319 xattr_find_entry(struct inode *inode, struct ext4_xattr_entry **pentry,
320 		 void *end, int name_index, const char *name, int sorted)
321 {
322 	struct ext4_xattr_entry *entry, *next;
323 	size_t name_len;
324 	int cmp = 1;
325 
326 	if (name == NULL)
327 		return -EINVAL;
328 	name_len = strlen(name);
329 	for (entry = *pentry; !IS_LAST_ENTRY(entry); entry = next) {
330 		next = EXT4_XATTR_NEXT(entry);
331 		if ((void *) next >= end) {
332 			EXT4_ERROR_INODE(inode, "corrupted xattr entries");
333 			return -EFSCORRUPTED;
334 		}
335 		cmp = name_index - entry->e_name_index;
336 		if (!cmp)
337 			cmp = name_len - entry->e_name_len;
338 		if (!cmp)
339 			cmp = memcmp(name, entry->e_name, name_len);
340 		if (cmp <= 0 && (sorted || cmp == 0))
341 			break;
342 	}
343 	*pentry = entry;
344 	return cmp ? -ENODATA : 0;
345 }
346 
347 static u32
348 ext4_xattr_inode_hash(struct ext4_sb_info *sbi, const void *buffer, size_t size)
349 {
350 	return ext4_chksum(sbi, sbi->s_csum_seed, buffer, size);
351 }
352 
353 static u64 ext4_xattr_inode_get_ref(struct inode *ea_inode)
354 {
355 	return ((u64)ea_inode->i_ctime.tv_sec << 32) |
356 		(u32) inode_peek_iversion_raw(ea_inode);
357 }
358 
359 static void ext4_xattr_inode_set_ref(struct inode *ea_inode, u64 ref_count)
360 {
361 	ea_inode->i_ctime.tv_sec = (u32)(ref_count >> 32);
362 	inode_set_iversion_raw(ea_inode, ref_count & 0xffffffff);
363 }
364 
365 static u32 ext4_xattr_inode_get_hash(struct inode *ea_inode)
366 {
367 	return (u32)ea_inode->i_atime.tv_sec;
368 }
369 
370 static void ext4_xattr_inode_set_hash(struct inode *ea_inode, u32 hash)
371 {
372 	ea_inode->i_atime.tv_sec = hash;
373 }
374 
375 /*
376  * Read the EA value from an inode.
377  */
378 static int ext4_xattr_inode_read(struct inode *ea_inode, void *buf, size_t size)
379 {
380 	int blocksize = 1 << ea_inode->i_blkbits;
381 	int bh_count = (size + blocksize - 1) >> ea_inode->i_blkbits;
382 	int tail_size = (size % blocksize) ?: blocksize;
383 	struct buffer_head *bhs_inline[8];
384 	struct buffer_head **bhs = bhs_inline;
385 	int i, ret;
386 
387 	if (bh_count > ARRAY_SIZE(bhs_inline)) {
388 		bhs = kmalloc_array(bh_count, sizeof(*bhs), GFP_NOFS);
389 		if (!bhs)
390 			return -ENOMEM;
391 	}
392 
393 	ret = ext4_bread_batch(ea_inode, 0 /* block */, bh_count,
394 			       true /* wait */, bhs);
395 	if (ret)
396 		goto free_bhs;
397 
398 	for (i = 0; i < bh_count; i++) {
399 		/* There shouldn't be any holes in ea_inode. */
400 		if (!bhs[i]) {
401 			ret = -EFSCORRUPTED;
402 			goto put_bhs;
403 		}
404 		memcpy((char *)buf + blocksize * i, bhs[i]->b_data,
405 		       i < bh_count - 1 ? blocksize : tail_size);
406 	}
407 	ret = 0;
408 put_bhs:
409 	for (i = 0; i < bh_count; i++)
410 		brelse(bhs[i]);
411 free_bhs:
412 	if (bhs != bhs_inline)
413 		kfree(bhs);
414 	return ret;
415 }
416 
417 #define EXT4_XATTR_INODE_GET_PARENT(inode) ((__u32)(inode)->i_mtime.tv_sec)
418 
419 static int ext4_xattr_inode_iget(struct inode *parent, unsigned long ea_ino,
420 				 u32 ea_inode_hash, struct inode **ea_inode)
421 {
422 	struct inode *inode;
423 	int err;
424 
425 	/*
426 	 * We have to check for this corruption early as otherwise
427 	 * iget_locked() could wait indefinitely for the state of our
428 	 * parent inode.
429 	 */
430 	if (parent->i_ino == ea_ino) {
431 		ext4_error(parent->i_sb,
432 			   "Parent and EA inode have the same ino %lu", ea_ino);
433 		return -EFSCORRUPTED;
434 	}
435 
436 	inode = ext4_iget(parent->i_sb, ea_ino, EXT4_IGET_NORMAL);
437 	if (IS_ERR(inode)) {
438 		err = PTR_ERR(inode);
439 		ext4_error(parent->i_sb,
440 			   "error while reading EA inode %lu err=%d", ea_ino,
441 			   err);
442 		return err;
443 	}
444 
445 	if (is_bad_inode(inode)) {
446 		ext4_error(parent->i_sb,
447 			   "error while reading EA inode %lu is_bad_inode",
448 			   ea_ino);
449 		err = -EIO;
450 		goto error;
451 	}
452 
453 	if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
454 		ext4_error(parent->i_sb,
455 			   "EA inode %lu does not have EXT4_EA_INODE_FL flag",
456 			    ea_ino);
457 		err = -EINVAL;
458 		goto error;
459 	}
460 
461 	ext4_xattr_inode_set_class(inode);
462 
463 	/*
464 	 * Check whether this is an old Lustre-style xattr inode. Lustre
465 	 * implementation does not have hash validation, rather it has a
466 	 * backpointer from ea_inode to the parent inode.
467 	 */
468 	if (ea_inode_hash != ext4_xattr_inode_get_hash(inode) &&
469 	    EXT4_XATTR_INODE_GET_PARENT(inode) == parent->i_ino &&
470 	    inode->i_generation == parent->i_generation) {
471 		ext4_set_inode_state(inode, EXT4_STATE_LUSTRE_EA_INODE);
472 		ext4_xattr_inode_set_ref(inode, 1);
473 	} else {
474 		inode_lock(inode);
475 		inode->i_flags |= S_NOQUOTA;
476 		inode_unlock(inode);
477 	}
478 
479 	*ea_inode = inode;
480 	return 0;
481 error:
482 	iput(inode);
483 	return err;
484 }
485 
486 /* Remove entry from mbcache when EA inode is getting evicted */
487 void ext4_evict_ea_inode(struct inode *inode)
488 {
489 	struct mb_cache_entry *oe;
490 
491 	if (!EA_INODE_CACHE(inode))
492 		return;
493 	/* Wait for entry to get unused so that we can remove it */
494 	while ((oe = mb_cache_entry_delete_or_get(EA_INODE_CACHE(inode),
495 			ext4_xattr_inode_get_hash(inode), inode->i_ino))) {
496 		mb_cache_entry_wait_unused(oe);
497 		mb_cache_entry_put(EA_INODE_CACHE(inode), oe);
498 	}
499 }
500 
501 static int
502 ext4_xattr_inode_verify_hashes(struct inode *ea_inode,
503 			       struct ext4_xattr_entry *entry, void *buffer,
504 			       size_t size)
505 {
506 	u32 hash;
507 
508 	/* Verify stored hash matches calculated hash. */
509 	hash = ext4_xattr_inode_hash(EXT4_SB(ea_inode->i_sb), buffer, size);
510 	if (hash != ext4_xattr_inode_get_hash(ea_inode))
511 		return -EFSCORRUPTED;
512 
513 	if (entry) {
514 		__le32 e_hash, tmp_data;
515 
516 		/* Verify entry hash. */
517 		tmp_data = cpu_to_le32(hash);
518 		e_hash = ext4_xattr_hash_entry(entry->e_name, entry->e_name_len,
519 					       &tmp_data, 1);
520 		/* All good? */
521 		if (e_hash == entry->e_hash)
522 			return 0;
523 
524 		/*
525 		 * Not good. Maybe the entry hash was calculated
526 		 * using the buggy signed char version?
527 		 */
528 		e_hash = ext4_xattr_hash_entry_signed(entry->e_name, entry->e_name_len,
529 							&tmp_data, 1);
530 		/* Still no match - bad */
531 		if (e_hash != entry->e_hash)
532 			return -EFSCORRUPTED;
533 
534 		/* Let people know about old hash */
535 		pr_warn_once("ext4: filesystem with signed xattr name hash");
536 	}
537 	return 0;
538 }
539 
540 /*
541  * Read xattr value from the EA inode.
542  */
543 static int
544 ext4_xattr_inode_get(struct inode *inode, struct ext4_xattr_entry *entry,
545 		     void *buffer, size_t size)
546 {
547 	struct mb_cache *ea_inode_cache = EA_INODE_CACHE(inode);
548 	struct inode *ea_inode;
549 	int err;
550 
551 	err = ext4_xattr_inode_iget(inode, le32_to_cpu(entry->e_value_inum),
552 				    le32_to_cpu(entry->e_hash), &ea_inode);
553 	if (err) {
554 		ea_inode = NULL;
555 		goto out;
556 	}
557 
558 	if (i_size_read(ea_inode) != size) {
559 		ext4_warning_inode(ea_inode,
560 				   "ea_inode file size=%llu entry size=%zu",
561 				   i_size_read(ea_inode), size);
562 		err = -EFSCORRUPTED;
563 		goto out;
564 	}
565 
566 	err = ext4_xattr_inode_read(ea_inode, buffer, size);
567 	if (err)
568 		goto out;
569 
570 	if (!ext4_test_inode_state(ea_inode, EXT4_STATE_LUSTRE_EA_INODE)) {
571 		err = ext4_xattr_inode_verify_hashes(ea_inode, entry, buffer,
572 						     size);
573 		if (err) {
574 			ext4_warning_inode(ea_inode,
575 					   "EA inode hash validation failed");
576 			goto out;
577 		}
578 
579 		if (ea_inode_cache)
580 			mb_cache_entry_create(ea_inode_cache, GFP_NOFS,
581 					ext4_xattr_inode_get_hash(ea_inode),
582 					ea_inode->i_ino, true /* reusable */);
583 	}
584 out:
585 	iput(ea_inode);
586 	return err;
587 }
588 
589 static int
590 ext4_xattr_block_get(struct inode *inode, int name_index, const char *name,
591 		     void *buffer, size_t buffer_size)
592 {
593 	struct buffer_head *bh = NULL;
594 	struct ext4_xattr_entry *entry;
595 	size_t size;
596 	void *end;
597 	int error;
598 	struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
599 
600 	ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
601 		  name_index, name, buffer, (long)buffer_size);
602 
603 	if (!EXT4_I(inode)->i_file_acl)
604 		return -ENODATA;
605 	ea_idebug(inode, "reading block %llu",
606 		  (unsigned long long)EXT4_I(inode)->i_file_acl);
607 	bh = ext4_sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
608 	if (IS_ERR(bh))
609 		return PTR_ERR(bh);
610 	ea_bdebug(bh, "b_count=%d, refcount=%d",
611 		atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
612 	error = ext4_xattr_check_block(inode, bh);
613 	if (error)
614 		goto cleanup;
615 	ext4_xattr_block_cache_insert(ea_block_cache, bh);
616 	entry = BFIRST(bh);
617 	end = bh->b_data + bh->b_size;
618 	error = xattr_find_entry(inode, &entry, end, name_index, name, 1);
619 	if (error)
620 		goto cleanup;
621 	size = le32_to_cpu(entry->e_value_size);
622 	error = -ERANGE;
623 	if (unlikely(size > EXT4_XATTR_SIZE_MAX))
624 		goto cleanup;
625 	if (buffer) {
626 		if (size > buffer_size)
627 			goto cleanup;
628 		if (entry->e_value_inum) {
629 			error = ext4_xattr_inode_get(inode, entry, buffer,
630 						     size);
631 			if (error)
632 				goto cleanup;
633 		} else {
634 			u16 offset = le16_to_cpu(entry->e_value_offs);
635 			void *p = bh->b_data + offset;
636 
637 			if (unlikely(p + size > end))
638 				goto cleanup;
639 			memcpy(buffer, p, size);
640 		}
641 	}
642 	error = size;
643 
644 cleanup:
645 	brelse(bh);
646 	return error;
647 }
648 
649 int
650 ext4_xattr_ibody_get(struct inode *inode, int name_index, const char *name,
651 		     void *buffer, size_t buffer_size)
652 {
653 	struct ext4_xattr_ibody_header *header;
654 	struct ext4_xattr_entry *entry;
655 	struct ext4_inode *raw_inode;
656 	struct ext4_iloc iloc;
657 	size_t size;
658 	void *end;
659 	int error;
660 
661 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR))
662 		return -ENODATA;
663 	error = ext4_get_inode_loc(inode, &iloc);
664 	if (error)
665 		return error;
666 	raw_inode = ext4_raw_inode(&iloc);
667 	header = IHDR(inode, raw_inode);
668 	end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
669 	error = xattr_check_inode(inode, header, end);
670 	if (error)
671 		goto cleanup;
672 	entry = IFIRST(header);
673 	error = xattr_find_entry(inode, &entry, end, name_index, name, 0);
674 	if (error)
675 		goto cleanup;
676 	size = le32_to_cpu(entry->e_value_size);
677 	error = -ERANGE;
678 	if (unlikely(size > EXT4_XATTR_SIZE_MAX))
679 		goto cleanup;
680 	if (buffer) {
681 		if (size > buffer_size)
682 			goto cleanup;
683 		if (entry->e_value_inum) {
684 			error = ext4_xattr_inode_get(inode, entry, buffer,
685 						     size);
686 			if (error)
687 				goto cleanup;
688 		} else {
689 			u16 offset = le16_to_cpu(entry->e_value_offs);
690 			void *p = (void *)IFIRST(header) + offset;
691 
692 			if (unlikely(p + size > end))
693 				goto cleanup;
694 			memcpy(buffer, p, size);
695 		}
696 	}
697 	error = size;
698 
699 cleanup:
700 	brelse(iloc.bh);
701 	return error;
702 }
703 
704 /*
705  * ext4_xattr_get()
706  *
707  * Copy an extended attribute into the buffer
708  * provided, or compute the buffer size required.
709  * Buffer is NULL to compute the size of the buffer required.
710  *
711  * Returns a negative error number on failure, or the number of bytes
712  * used / required on success.
713  */
714 int
715 ext4_xattr_get(struct inode *inode, int name_index, const char *name,
716 	       void *buffer, size_t buffer_size)
717 {
718 	int error;
719 
720 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
721 		return -EIO;
722 
723 	if (strlen(name) > 255)
724 		return -ERANGE;
725 
726 	down_read(&EXT4_I(inode)->xattr_sem);
727 	error = ext4_xattr_ibody_get(inode, name_index, name, buffer,
728 				     buffer_size);
729 	if (error == -ENODATA)
730 		error = ext4_xattr_block_get(inode, name_index, name, buffer,
731 					     buffer_size);
732 	up_read(&EXT4_I(inode)->xattr_sem);
733 	return error;
734 }
735 
736 static int
737 ext4_xattr_list_entries(struct dentry *dentry, struct ext4_xattr_entry *entry,
738 			char *buffer, size_t buffer_size)
739 {
740 	size_t rest = buffer_size;
741 
742 	for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
743 		const char *prefix;
744 
745 		prefix = ext4_xattr_prefix(entry->e_name_index, dentry);
746 		if (prefix) {
747 			size_t prefix_len = strlen(prefix);
748 			size_t size = prefix_len + entry->e_name_len + 1;
749 
750 			if (buffer) {
751 				if (size > rest)
752 					return -ERANGE;
753 				memcpy(buffer, prefix, prefix_len);
754 				buffer += prefix_len;
755 				memcpy(buffer, entry->e_name, entry->e_name_len);
756 				buffer += entry->e_name_len;
757 				*buffer++ = 0;
758 			}
759 			rest -= size;
760 		}
761 	}
762 	return buffer_size - rest;  /* total size */
763 }
764 
765 static int
766 ext4_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size)
767 {
768 	struct inode *inode = d_inode(dentry);
769 	struct buffer_head *bh = NULL;
770 	int error;
771 
772 	ea_idebug(inode, "buffer=%p, buffer_size=%ld",
773 		  buffer, (long)buffer_size);
774 
775 	if (!EXT4_I(inode)->i_file_acl)
776 		return 0;
777 	ea_idebug(inode, "reading block %llu",
778 		  (unsigned long long)EXT4_I(inode)->i_file_acl);
779 	bh = ext4_sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
780 	if (IS_ERR(bh))
781 		return PTR_ERR(bh);
782 	ea_bdebug(bh, "b_count=%d, refcount=%d",
783 		atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
784 	error = ext4_xattr_check_block(inode, bh);
785 	if (error)
786 		goto cleanup;
787 	ext4_xattr_block_cache_insert(EA_BLOCK_CACHE(inode), bh);
788 	error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer,
789 					buffer_size);
790 cleanup:
791 	brelse(bh);
792 	return error;
793 }
794 
795 static int
796 ext4_xattr_ibody_list(struct dentry *dentry, char *buffer, size_t buffer_size)
797 {
798 	struct inode *inode = d_inode(dentry);
799 	struct ext4_xattr_ibody_header *header;
800 	struct ext4_inode *raw_inode;
801 	struct ext4_iloc iloc;
802 	void *end;
803 	int error;
804 
805 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR))
806 		return 0;
807 	error = ext4_get_inode_loc(inode, &iloc);
808 	if (error)
809 		return error;
810 	raw_inode = ext4_raw_inode(&iloc);
811 	header = IHDR(inode, raw_inode);
812 	end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
813 	error = xattr_check_inode(inode, header, end);
814 	if (error)
815 		goto cleanup;
816 	error = ext4_xattr_list_entries(dentry, IFIRST(header),
817 					buffer, buffer_size);
818 
819 cleanup:
820 	brelse(iloc.bh);
821 	return error;
822 }
823 
824 /*
825  * Inode operation listxattr()
826  *
827  * d_inode(dentry)->i_rwsem: don't care
828  *
829  * Copy a list of attribute names into the buffer
830  * provided, or compute the buffer size required.
831  * Buffer is NULL to compute the size of the buffer required.
832  *
833  * Returns a negative error number on failure, or the number of bytes
834  * used / required on success.
835  */
836 ssize_t
837 ext4_listxattr(struct dentry *dentry, char *buffer, size_t buffer_size)
838 {
839 	int ret, ret2;
840 
841 	down_read(&EXT4_I(d_inode(dentry))->xattr_sem);
842 	ret = ret2 = ext4_xattr_ibody_list(dentry, buffer, buffer_size);
843 	if (ret < 0)
844 		goto errout;
845 	if (buffer) {
846 		buffer += ret;
847 		buffer_size -= ret;
848 	}
849 	ret = ext4_xattr_block_list(dentry, buffer, buffer_size);
850 	if (ret < 0)
851 		goto errout;
852 	ret += ret2;
853 errout:
854 	up_read(&EXT4_I(d_inode(dentry))->xattr_sem);
855 	return ret;
856 }
857 
858 /*
859  * If the EXT4_FEATURE_COMPAT_EXT_ATTR feature of this file system is
860  * not set, set it.
861  */
862 static void ext4_xattr_update_super_block(handle_t *handle,
863 					  struct super_block *sb)
864 {
865 	if (ext4_has_feature_xattr(sb))
866 		return;
867 
868 	BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access");
869 	if (ext4_journal_get_write_access(handle, sb, EXT4_SB(sb)->s_sbh,
870 					  EXT4_JTR_NONE) == 0) {
871 		lock_buffer(EXT4_SB(sb)->s_sbh);
872 		ext4_set_feature_xattr(sb);
873 		ext4_superblock_csum_set(sb);
874 		unlock_buffer(EXT4_SB(sb)->s_sbh);
875 		ext4_handle_dirty_metadata(handle, NULL, EXT4_SB(sb)->s_sbh);
876 	}
877 }
878 
879 int ext4_get_inode_usage(struct inode *inode, qsize_t *usage)
880 {
881 	struct ext4_iloc iloc = { .bh = NULL };
882 	struct buffer_head *bh = NULL;
883 	struct ext4_inode *raw_inode;
884 	struct ext4_xattr_ibody_header *header;
885 	struct ext4_xattr_entry *entry;
886 	qsize_t ea_inode_refs = 0;
887 	void *end;
888 	int ret;
889 
890 	lockdep_assert_held_read(&EXT4_I(inode)->xattr_sem);
891 
892 	if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
893 		ret = ext4_get_inode_loc(inode, &iloc);
894 		if (ret)
895 			goto out;
896 		raw_inode = ext4_raw_inode(&iloc);
897 		header = IHDR(inode, raw_inode);
898 		end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
899 		ret = xattr_check_inode(inode, header, end);
900 		if (ret)
901 			goto out;
902 
903 		for (entry = IFIRST(header); !IS_LAST_ENTRY(entry);
904 		     entry = EXT4_XATTR_NEXT(entry))
905 			if (entry->e_value_inum)
906 				ea_inode_refs++;
907 	}
908 
909 	if (EXT4_I(inode)->i_file_acl) {
910 		bh = ext4_sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
911 		if (IS_ERR(bh)) {
912 			ret = PTR_ERR(bh);
913 			bh = NULL;
914 			goto out;
915 		}
916 
917 		ret = ext4_xattr_check_block(inode, bh);
918 		if (ret)
919 			goto out;
920 
921 		for (entry = BFIRST(bh); !IS_LAST_ENTRY(entry);
922 		     entry = EXT4_XATTR_NEXT(entry))
923 			if (entry->e_value_inum)
924 				ea_inode_refs++;
925 	}
926 	*usage = ea_inode_refs + 1;
927 	ret = 0;
928 out:
929 	brelse(iloc.bh);
930 	brelse(bh);
931 	return ret;
932 }
933 
934 static inline size_t round_up_cluster(struct inode *inode, size_t length)
935 {
936 	struct super_block *sb = inode->i_sb;
937 	size_t cluster_size = 1 << (EXT4_SB(sb)->s_cluster_bits +
938 				    inode->i_blkbits);
939 	size_t mask = ~(cluster_size - 1);
940 
941 	return (length + cluster_size - 1) & mask;
942 }
943 
944 static int ext4_xattr_inode_alloc_quota(struct inode *inode, size_t len)
945 {
946 	int err;
947 
948 	err = dquot_alloc_inode(inode);
949 	if (err)
950 		return err;
951 	err = dquot_alloc_space_nodirty(inode, round_up_cluster(inode, len));
952 	if (err)
953 		dquot_free_inode(inode);
954 	return err;
955 }
956 
957 static void ext4_xattr_inode_free_quota(struct inode *parent,
958 					struct inode *ea_inode,
959 					size_t len)
960 {
961 	if (ea_inode &&
962 	    ext4_test_inode_state(ea_inode, EXT4_STATE_LUSTRE_EA_INODE))
963 		return;
964 	dquot_free_space_nodirty(parent, round_up_cluster(parent, len));
965 	dquot_free_inode(parent);
966 }
967 
968 int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
969 			     struct buffer_head *block_bh, size_t value_len,
970 			     bool is_create)
971 {
972 	int credits;
973 	int blocks;
974 
975 	/*
976 	 * 1) Owner inode update
977 	 * 2) Ref count update on old xattr block
978 	 * 3) new xattr block
979 	 * 4) block bitmap update for new xattr block
980 	 * 5) group descriptor for new xattr block
981 	 * 6) block bitmap update for old xattr block
982 	 * 7) group descriptor for old block
983 	 *
984 	 * 6 & 7 can happen if we have two racing threads T_a and T_b
985 	 * which are each trying to set an xattr on inodes I_a and I_b
986 	 * which were both initially sharing an xattr block.
987 	 */
988 	credits = 7;
989 
990 	/* Quota updates. */
991 	credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(sb);
992 
993 	/*
994 	 * In case of inline data, we may push out the data to a block,
995 	 * so we need to reserve credits for this eventuality
996 	 */
997 	if (inode && ext4_has_inline_data(inode))
998 		credits += ext4_writepage_trans_blocks(inode) + 1;
999 
1000 	/* We are done if ea_inode feature is not enabled. */
1001 	if (!ext4_has_feature_ea_inode(sb))
1002 		return credits;
1003 
1004 	/* New ea_inode, inode map, block bitmap, group descriptor. */
1005 	credits += 4;
1006 
1007 	/* Data blocks. */
1008 	blocks = (value_len + sb->s_blocksize - 1) >> sb->s_blocksize_bits;
1009 
1010 	/* Indirection block or one level of extent tree. */
1011 	blocks += 1;
1012 
1013 	/* Block bitmap and group descriptor updates for each block. */
1014 	credits += blocks * 2;
1015 
1016 	/* Blocks themselves. */
1017 	credits += blocks;
1018 
1019 	if (!is_create) {
1020 		/* Dereference ea_inode holding old xattr value.
1021 		 * Old ea_inode, inode map, block bitmap, group descriptor.
1022 		 */
1023 		credits += 4;
1024 
1025 		/* Data blocks for old ea_inode. */
1026 		blocks = XATTR_SIZE_MAX >> sb->s_blocksize_bits;
1027 
1028 		/* Indirection block or one level of extent tree for old
1029 		 * ea_inode.
1030 		 */
1031 		blocks += 1;
1032 
1033 		/* Block bitmap and group descriptor updates for each block. */
1034 		credits += blocks * 2;
1035 	}
1036 
1037 	/* We may need to clone the existing xattr block in which case we need
1038 	 * to increment ref counts for existing ea_inodes referenced by it.
1039 	 */
1040 	if (block_bh) {
1041 		struct ext4_xattr_entry *entry = BFIRST(block_bh);
1042 
1043 		for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry))
1044 			if (entry->e_value_inum)
1045 				/* Ref count update on ea_inode. */
1046 				credits += 1;
1047 	}
1048 	return credits;
1049 }
1050 
1051 static int ext4_xattr_inode_update_ref(handle_t *handle, struct inode *ea_inode,
1052 				       int ref_change)
1053 {
1054 	struct ext4_iloc iloc;
1055 	s64 ref_count;
1056 	int ret;
1057 
1058 	inode_lock(ea_inode);
1059 
1060 	ret = ext4_reserve_inode_write(handle, ea_inode, &iloc);
1061 	if (ret)
1062 		goto out;
1063 
1064 	ref_count = ext4_xattr_inode_get_ref(ea_inode);
1065 	ref_count += ref_change;
1066 	ext4_xattr_inode_set_ref(ea_inode, ref_count);
1067 
1068 	if (ref_change > 0) {
1069 		WARN_ONCE(ref_count <= 0, "EA inode %lu ref_count=%lld",
1070 			  ea_inode->i_ino, ref_count);
1071 
1072 		if (ref_count == 1) {
1073 			WARN_ONCE(ea_inode->i_nlink, "EA inode %lu i_nlink=%u",
1074 				  ea_inode->i_ino, ea_inode->i_nlink);
1075 
1076 			set_nlink(ea_inode, 1);
1077 			ext4_orphan_del(handle, ea_inode);
1078 		}
1079 	} else {
1080 		WARN_ONCE(ref_count < 0, "EA inode %lu ref_count=%lld",
1081 			  ea_inode->i_ino, ref_count);
1082 
1083 		if (ref_count == 0) {
1084 			WARN_ONCE(ea_inode->i_nlink != 1,
1085 				  "EA inode %lu i_nlink=%u",
1086 				  ea_inode->i_ino, ea_inode->i_nlink);
1087 
1088 			clear_nlink(ea_inode);
1089 			ext4_orphan_add(handle, ea_inode);
1090 		}
1091 	}
1092 
1093 	ret = ext4_mark_iloc_dirty(handle, ea_inode, &iloc);
1094 	if (ret)
1095 		ext4_warning_inode(ea_inode,
1096 				   "ext4_mark_iloc_dirty() failed ret=%d", ret);
1097 out:
1098 	inode_unlock(ea_inode);
1099 	return ret;
1100 }
1101 
1102 static int ext4_xattr_inode_inc_ref(handle_t *handle, struct inode *ea_inode)
1103 {
1104 	return ext4_xattr_inode_update_ref(handle, ea_inode, 1);
1105 }
1106 
1107 static int ext4_xattr_inode_dec_ref(handle_t *handle, struct inode *ea_inode)
1108 {
1109 	return ext4_xattr_inode_update_ref(handle, ea_inode, -1);
1110 }
1111 
1112 static int ext4_xattr_inode_inc_ref_all(handle_t *handle, struct inode *parent,
1113 					struct ext4_xattr_entry *first)
1114 {
1115 	struct inode *ea_inode;
1116 	struct ext4_xattr_entry *entry;
1117 	struct ext4_xattr_entry *failed_entry;
1118 	unsigned int ea_ino;
1119 	int err, saved_err;
1120 
1121 	for (entry = first; !IS_LAST_ENTRY(entry);
1122 	     entry = EXT4_XATTR_NEXT(entry)) {
1123 		if (!entry->e_value_inum)
1124 			continue;
1125 		ea_ino = le32_to_cpu(entry->e_value_inum);
1126 		err = ext4_xattr_inode_iget(parent, ea_ino,
1127 					    le32_to_cpu(entry->e_hash),
1128 					    &ea_inode);
1129 		if (err)
1130 			goto cleanup;
1131 		err = ext4_xattr_inode_inc_ref(handle, ea_inode);
1132 		if (err) {
1133 			ext4_warning_inode(ea_inode, "inc ref error %d", err);
1134 			iput(ea_inode);
1135 			goto cleanup;
1136 		}
1137 		iput(ea_inode);
1138 	}
1139 	return 0;
1140 
1141 cleanup:
1142 	saved_err = err;
1143 	failed_entry = entry;
1144 
1145 	for (entry = first; entry != failed_entry;
1146 	     entry = EXT4_XATTR_NEXT(entry)) {
1147 		if (!entry->e_value_inum)
1148 			continue;
1149 		ea_ino = le32_to_cpu(entry->e_value_inum);
1150 		err = ext4_xattr_inode_iget(parent, ea_ino,
1151 					    le32_to_cpu(entry->e_hash),
1152 					    &ea_inode);
1153 		if (err) {
1154 			ext4_warning(parent->i_sb,
1155 				     "cleanup ea_ino %u iget error %d", ea_ino,
1156 				     err);
1157 			continue;
1158 		}
1159 		err = ext4_xattr_inode_dec_ref(handle, ea_inode);
1160 		if (err)
1161 			ext4_warning_inode(ea_inode, "cleanup dec ref error %d",
1162 					   err);
1163 		iput(ea_inode);
1164 	}
1165 	return saved_err;
1166 }
1167 
1168 static int ext4_xattr_restart_fn(handle_t *handle, struct inode *inode,
1169 			struct buffer_head *bh, bool block_csum, bool dirty)
1170 {
1171 	int error;
1172 
1173 	if (bh && dirty) {
1174 		if (block_csum)
1175 			ext4_xattr_block_csum_set(inode, bh);
1176 		error = ext4_handle_dirty_metadata(handle, NULL, bh);
1177 		if (error) {
1178 			ext4_warning(inode->i_sb, "Handle metadata (error %d)",
1179 				     error);
1180 			return error;
1181 		}
1182 	}
1183 	return 0;
1184 }
1185 
1186 static void
1187 ext4_xattr_inode_dec_ref_all(handle_t *handle, struct inode *parent,
1188 			     struct buffer_head *bh,
1189 			     struct ext4_xattr_entry *first, bool block_csum,
1190 			     struct ext4_xattr_inode_array **ea_inode_array,
1191 			     int extra_credits, bool skip_quota)
1192 {
1193 	struct inode *ea_inode;
1194 	struct ext4_xattr_entry *entry;
1195 	bool dirty = false;
1196 	unsigned int ea_ino;
1197 	int err;
1198 	int credits;
1199 
1200 	/* One credit for dec ref on ea_inode, one for orphan list addition, */
1201 	credits = 2 + extra_credits;
1202 
1203 	for (entry = first; !IS_LAST_ENTRY(entry);
1204 	     entry = EXT4_XATTR_NEXT(entry)) {
1205 		if (!entry->e_value_inum)
1206 			continue;
1207 		ea_ino = le32_to_cpu(entry->e_value_inum);
1208 		err = ext4_xattr_inode_iget(parent, ea_ino,
1209 					    le32_to_cpu(entry->e_hash),
1210 					    &ea_inode);
1211 		if (err)
1212 			continue;
1213 
1214 		err = ext4_expand_inode_array(ea_inode_array, ea_inode);
1215 		if (err) {
1216 			ext4_warning_inode(ea_inode,
1217 					   "Expand inode array err=%d", err);
1218 			iput(ea_inode);
1219 			continue;
1220 		}
1221 
1222 		err = ext4_journal_ensure_credits_fn(handle, credits, credits,
1223 			ext4_free_metadata_revoke_credits(parent->i_sb, 1),
1224 			ext4_xattr_restart_fn(handle, parent, bh, block_csum,
1225 					      dirty));
1226 		if (err < 0) {
1227 			ext4_warning_inode(ea_inode, "Ensure credits err=%d",
1228 					   err);
1229 			continue;
1230 		}
1231 		if (err > 0) {
1232 			err = ext4_journal_get_write_access(handle,
1233 					parent->i_sb, bh, EXT4_JTR_NONE);
1234 			if (err) {
1235 				ext4_warning_inode(ea_inode,
1236 						"Re-get write access err=%d",
1237 						err);
1238 				continue;
1239 			}
1240 		}
1241 
1242 		err = ext4_xattr_inode_dec_ref(handle, ea_inode);
1243 		if (err) {
1244 			ext4_warning_inode(ea_inode, "ea_inode dec ref err=%d",
1245 					   err);
1246 			continue;
1247 		}
1248 
1249 		if (!skip_quota)
1250 			ext4_xattr_inode_free_quota(parent, ea_inode,
1251 					      le32_to_cpu(entry->e_value_size));
1252 
1253 		/*
1254 		 * Forget about ea_inode within the same transaction that
1255 		 * decrements the ref count. This avoids duplicate decrements in
1256 		 * case the rest of the work spills over to subsequent
1257 		 * transactions.
1258 		 */
1259 		entry->e_value_inum = 0;
1260 		entry->e_value_size = 0;
1261 
1262 		dirty = true;
1263 	}
1264 
1265 	if (dirty) {
1266 		/*
1267 		 * Note that we are deliberately skipping csum calculation for
1268 		 * the final update because we do not expect any journal
1269 		 * restarts until xattr block is freed.
1270 		 */
1271 
1272 		err = ext4_handle_dirty_metadata(handle, NULL, bh);
1273 		if (err)
1274 			ext4_warning_inode(parent,
1275 					   "handle dirty metadata err=%d", err);
1276 	}
1277 }
1278 
1279 /*
1280  * Release the xattr block BH: If the reference count is > 1, decrement it;
1281  * otherwise free the block.
1282  */
1283 static void
1284 ext4_xattr_release_block(handle_t *handle, struct inode *inode,
1285 			 struct buffer_head *bh,
1286 			 struct ext4_xattr_inode_array **ea_inode_array,
1287 			 int extra_credits)
1288 {
1289 	struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
1290 	u32 hash, ref;
1291 	int error = 0;
1292 
1293 	BUFFER_TRACE(bh, "get_write_access");
1294 	error = ext4_journal_get_write_access(handle, inode->i_sb, bh,
1295 					      EXT4_JTR_NONE);
1296 	if (error)
1297 		goto out;
1298 
1299 retry_ref:
1300 	lock_buffer(bh);
1301 	hash = le32_to_cpu(BHDR(bh)->h_hash);
1302 	ref = le32_to_cpu(BHDR(bh)->h_refcount);
1303 	if (ref == 1) {
1304 		ea_bdebug(bh, "refcount now=0; freeing");
1305 		/*
1306 		 * This must happen under buffer lock for
1307 		 * ext4_xattr_block_set() to reliably detect freed block
1308 		 */
1309 		if (ea_block_cache) {
1310 			struct mb_cache_entry *oe;
1311 
1312 			oe = mb_cache_entry_delete_or_get(ea_block_cache, hash,
1313 							  bh->b_blocknr);
1314 			if (oe) {
1315 				unlock_buffer(bh);
1316 				mb_cache_entry_wait_unused(oe);
1317 				mb_cache_entry_put(ea_block_cache, oe);
1318 				goto retry_ref;
1319 			}
1320 		}
1321 		get_bh(bh);
1322 		unlock_buffer(bh);
1323 
1324 		if (ext4_has_feature_ea_inode(inode->i_sb))
1325 			ext4_xattr_inode_dec_ref_all(handle, inode, bh,
1326 						     BFIRST(bh),
1327 						     true /* block_csum */,
1328 						     ea_inode_array,
1329 						     extra_credits,
1330 						     true /* skip_quota */);
1331 		ext4_free_blocks(handle, inode, bh, 0, 1,
1332 				 EXT4_FREE_BLOCKS_METADATA |
1333 				 EXT4_FREE_BLOCKS_FORGET);
1334 	} else {
1335 		ref--;
1336 		BHDR(bh)->h_refcount = cpu_to_le32(ref);
1337 		if (ref == EXT4_XATTR_REFCOUNT_MAX - 1) {
1338 			struct mb_cache_entry *ce;
1339 
1340 			if (ea_block_cache) {
1341 				ce = mb_cache_entry_get(ea_block_cache, hash,
1342 							bh->b_blocknr);
1343 				if (ce) {
1344 					set_bit(MBE_REUSABLE_B, &ce->e_flags);
1345 					mb_cache_entry_put(ea_block_cache, ce);
1346 				}
1347 			}
1348 		}
1349 
1350 		ext4_xattr_block_csum_set(inode, bh);
1351 		/*
1352 		 * Beware of this ugliness: Releasing of xattr block references
1353 		 * from different inodes can race and so we have to protect
1354 		 * from a race where someone else frees the block (and releases
1355 		 * its journal_head) before we are done dirtying the buffer. In
1356 		 * nojournal mode this race is harmless and we actually cannot
1357 		 * call ext4_handle_dirty_metadata() with locked buffer as
1358 		 * that function can call sync_dirty_buffer() so for that case
1359 		 * we handle the dirtying after unlocking the buffer.
1360 		 */
1361 		if (ext4_handle_valid(handle))
1362 			error = ext4_handle_dirty_metadata(handle, inode, bh);
1363 		unlock_buffer(bh);
1364 		if (!ext4_handle_valid(handle))
1365 			error = ext4_handle_dirty_metadata(handle, inode, bh);
1366 		if (IS_SYNC(inode))
1367 			ext4_handle_sync(handle);
1368 		dquot_free_block(inode, EXT4_C2B(EXT4_SB(inode->i_sb), 1));
1369 		ea_bdebug(bh, "refcount now=%d; releasing",
1370 			  le32_to_cpu(BHDR(bh)->h_refcount));
1371 	}
1372 out:
1373 	ext4_std_error(inode->i_sb, error);
1374 	return;
1375 }
1376 
1377 /*
1378  * Find the available free space for EAs. This also returns the total number of
1379  * bytes used by EA entries.
1380  */
1381 static size_t ext4_xattr_free_space(struct ext4_xattr_entry *last,
1382 				    size_t *min_offs, void *base, int *total)
1383 {
1384 	for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
1385 		if (!last->e_value_inum && last->e_value_size) {
1386 			size_t offs = le16_to_cpu(last->e_value_offs);
1387 			if (offs < *min_offs)
1388 				*min_offs = offs;
1389 		}
1390 		if (total)
1391 			*total += EXT4_XATTR_LEN(last->e_name_len);
1392 	}
1393 	return (*min_offs - ((void *)last - base) - sizeof(__u32));
1394 }
1395 
1396 /*
1397  * Write the value of the EA in an inode.
1398  */
1399 static int ext4_xattr_inode_write(handle_t *handle, struct inode *ea_inode,
1400 				  const void *buf, int bufsize)
1401 {
1402 	struct buffer_head *bh = NULL;
1403 	unsigned long block = 0;
1404 	int blocksize = ea_inode->i_sb->s_blocksize;
1405 	int max_blocks = (bufsize + blocksize - 1) >> ea_inode->i_blkbits;
1406 	int csize, wsize = 0;
1407 	int ret = 0, ret2 = 0;
1408 	int retries = 0;
1409 
1410 retry:
1411 	while (ret >= 0 && ret < max_blocks) {
1412 		struct ext4_map_blocks map;
1413 		map.m_lblk = block += ret;
1414 		map.m_len = max_blocks -= ret;
1415 
1416 		ret = ext4_map_blocks(handle, ea_inode, &map,
1417 				      EXT4_GET_BLOCKS_CREATE);
1418 		if (ret <= 0) {
1419 			ext4_mark_inode_dirty(handle, ea_inode);
1420 			if (ret == -ENOSPC &&
1421 			    ext4_should_retry_alloc(ea_inode->i_sb, &retries)) {
1422 				ret = 0;
1423 				goto retry;
1424 			}
1425 			break;
1426 		}
1427 	}
1428 
1429 	if (ret < 0)
1430 		return ret;
1431 
1432 	block = 0;
1433 	while (wsize < bufsize) {
1434 		brelse(bh);
1435 		csize = (bufsize - wsize) > blocksize ? blocksize :
1436 								bufsize - wsize;
1437 		bh = ext4_getblk(handle, ea_inode, block, 0);
1438 		if (IS_ERR(bh))
1439 			return PTR_ERR(bh);
1440 		if (!bh) {
1441 			WARN_ON_ONCE(1);
1442 			EXT4_ERROR_INODE(ea_inode,
1443 					 "ext4_getblk() return bh = NULL");
1444 			return -EFSCORRUPTED;
1445 		}
1446 		ret = ext4_journal_get_write_access(handle, ea_inode->i_sb, bh,
1447 						   EXT4_JTR_NONE);
1448 		if (ret)
1449 			goto out;
1450 
1451 		memcpy(bh->b_data, buf, csize);
1452 		set_buffer_uptodate(bh);
1453 		ext4_handle_dirty_metadata(handle, ea_inode, bh);
1454 
1455 		buf += csize;
1456 		wsize += csize;
1457 		block += 1;
1458 	}
1459 
1460 	inode_lock(ea_inode);
1461 	i_size_write(ea_inode, wsize);
1462 	ext4_update_i_disksize(ea_inode, wsize);
1463 	inode_unlock(ea_inode);
1464 
1465 	ret2 = ext4_mark_inode_dirty(handle, ea_inode);
1466 	if (unlikely(ret2 && !ret))
1467 		ret = ret2;
1468 
1469 out:
1470 	brelse(bh);
1471 
1472 	return ret;
1473 }
1474 
1475 /*
1476  * Create an inode to store the value of a large EA.
1477  */
1478 static struct inode *ext4_xattr_inode_create(handle_t *handle,
1479 					     struct inode *inode, u32 hash)
1480 {
1481 	struct inode *ea_inode = NULL;
1482 	uid_t owner[2] = { i_uid_read(inode), i_gid_read(inode) };
1483 	int err;
1484 
1485 	if (inode->i_sb->s_root == NULL) {
1486 		ext4_warning(inode->i_sb,
1487 			     "refuse to create EA inode when umounting");
1488 		WARN_ON(1);
1489 		return ERR_PTR(-EINVAL);
1490 	}
1491 
1492 	/*
1493 	 * Let the next inode be the goal, so we try and allocate the EA inode
1494 	 * in the same group, or nearby one.
1495 	 */
1496 	ea_inode = ext4_new_inode(handle, inode->i_sb->s_root->d_inode,
1497 				  S_IFREG | 0600, NULL, inode->i_ino + 1, owner,
1498 				  EXT4_EA_INODE_FL);
1499 	if (!IS_ERR(ea_inode)) {
1500 		ea_inode->i_op = &ext4_file_inode_operations;
1501 		ea_inode->i_fop = &ext4_file_operations;
1502 		ext4_set_aops(ea_inode);
1503 		ext4_xattr_inode_set_class(ea_inode);
1504 		unlock_new_inode(ea_inode);
1505 		ext4_xattr_inode_set_ref(ea_inode, 1);
1506 		ext4_xattr_inode_set_hash(ea_inode, hash);
1507 		err = ext4_mark_inode_dirty(handle, ea_inode);
1508 		if (!err)
1509 			err = ext4_inode_attach_jinode(ea_inode);
1510 		if (err) {
1511 			if (ext4_xattr_inode_dec_ref(handle, ea_inode))
1512 				ext4_warning_inode(ea_inode,
1513 					"cleanup dec ref error %d", err);
1514 			iput(ea_inode);
1515 			return ERR_PTR(err);
1516 		}
1517 
1518 		/*
1519 		 * Xattr inodes are shared therefore quota charging is performed
1520 		 * at a higher level.
1521 		 */
1522 		dquot_free_inode(ea_inode);
1523 		dquot_drop(ea_inode);
1524 		inode_lock(ea_inode);
1525 		ea_inode->i_flags |= S_NOQUOTA;
1526 		inode_unlock(ea_inode);
1527 	}
1528 
1529 	return ea_inode;
1530 }
1531 
1532 static struct inode *
1533 ext4_xattr_inode_cache_find(struct inode *inode, const void *value,
1534 			    size_t value_len, u32 hash)
1535 {
1536 	struct inode *ea_inode;
1537 	struct mb_cache_entry *ce;
1538 	struct mb_cache *ea_inode_cache = EA_INODE_CACHE(inode);
1539 	void *ea_data;
1540 
1541 	if (!ea_inode_cache)
1542 		return NULL;
1543 
1544 	ce = mb_cache_entry_find_first(ea_inode_cache, hash);
1545 	if (!ce)
1546 		return NULL;
1547 
1548 	WARN_ON_ONCE(ext4_handle_valid(journal_current_handle()) &&
1549 		     !(current->flags & PF_MEMALLOC_NOFS));
1550 
1551 	ea_data = kvmalloc(value_len, GFP_KERNEL);
1552 	if (!ea_data) {
1553 		mb_cache_entry_put(ea_inode_cache, ce);
1554 		return NULL;
1555 	}
1556 
1557 	while (ce) {
1558 		ea_inode = ext4_iget(inode->i_sb, ce->e_value,
1559 				     EXT4_IGET_NORMAL);
1560 		if (!IS_ERR(ea_inode) &&
1561 		    !is_bad_inode(ea_inode) &&
1562 		    (EXT4_I(ea_inode)->i_flags & EXT4_EA_INODE_FL) &&
1563 		    i_size_read(ea_inode) == value_len &&
1564 		    !ext4_xattr_inode_read(ea_inode, ea_data, value_len) &&
1565 		    !ext4_xattr_inode_verify_hashes(ea_inode, NULL, ea_data,
1566 						    value_len) &&
1567 		    !memcmp(value, ea_data, value_len)) {
1568 			mb_cache_entry_touch(ea_inode_cache, ce);
1569 			mb_cache_entry_put(ea_inode_cache, ce);
1570 			kvfree(ea_data);
1571 			return ea_inode;
1572 		}
1573 
1574 		if (!IS_ERR(ea_inode))
1575 			iput(ea_inode);
1576 		ce = mb_cache_entry_find_next(ea_inode_cache, ce);
1577 	}
1578 	kvfree(ea_data);
1579 	return NULL;
1580 }
1581 
1582 /*
1583  * Add value of the EA in an inode.
1584  */
1585 static int ext4_xattr_inode_lookup_create(handle_t *handle, struct inode *inode,
1586 					  const void *value, size_t value_len,
1587 					  struct inode **ret_inode)
1588 {
1589 	struct inode *ea_inode;
1590 	u32 hash;
1591 	int err;
1592 
1593 	hash = ext4_xattr_inode_hash(EXT4_SB(inode->i_sb), value, value_len);
1594 	ea_inode = ext4_xattr_inode_cache_find(inode, value, value_len, hash);
1595 	if (ea_inode) {
1596 		err = ext4_xattr_inode_inc_ref(handle, ea_inode);
1597 		if (err) {
1598 			iput(ea_inode);
1599 			return err;
1600 		}
1601 
1602 		*ret_inode = ea_inode;
1603 		return 0;
1604 	}
1605 
1606 	/* Create an inode for the EA value */
1607 	ea_inode = ext4_xattr_inode_create(handle, inode, hash);
1608 	if (IS_ERR(ea_inode))
1609 		return PTR_ERR(ea_inode);
1610 
1611 	err = ext4_xattr_inode_write(handle, ea_inode, value, value_len);
1612 	if (err) {
1613 		if (ext4_xattr_inode_dec_ref(handle, ea_inode))
1614 			ext4_warning_inode(ea_inode, "cleanup dec ref error %d", err);
1615 		iput(ea_inode);
1616 		return err;
1617 	}
1618 
1619 	if (EA_INODE_CACHE(inode))
1620 		mb_cache_entry_create(EA_INODE_CACHE(inode), GFP_NOFS, hash,
1621 				      ea_inode->i_ino, true /* reusable */);
1622 
1623 	*ret_inode = ea_inode;
1624 	return 0;
1625 }
1626 
1627 /*
1628  * Reserve min(block_size/8, 1024) bytes for xattr entries/names if ea_inode
1629  * feature is enabled.
1630  */
1631 #define EXT4_XATTR_BLOCK_RESERVE(inode)	min(i_blocksize(inode)/8, 1024U)
1632 
1633 static int ext4_xattr_set_entry(struct ext4_xattr_info *i,
1634 				struct ext4_xattr_search *s,
1635 				handle_t *handle, struct inode *inode,
1636 				bool is_block)
1637 {
1638 	struct ext4_xattr_entry *last, *next;
1639 	struct ext4_xattr_entry *here = s->here;
1640 	size_t min_offs = s->end - s->base, name_len = strlen(i->name);
1641 	int in_inode = i->in_inode;
1642 	struct inode *old_ea_inode = NULL;
1643 	struct inode *new_ea_inode = NULL;
1644 	size_t old_size, new_size;
1645 	int ret;
1646 
1647 	/* Space used by old and new values. */
1648 	old_size = (!s->not_found && !here->e_value_inum) ?
1649 			EXT4_XATTR_SIZE(le32_to_cpu(here->e_value_size)) : 0;
1650 	new_size = (i->value && !in_inode) ? EXT4_XATTR_SIZE(i->value_len) : 0;
1651 
1652 	/*
1653 	 * Optimization for the simple case when old and new values have the
1654 	 * same padded sizes. Not applicable if external inodes are involved.
1655 	 */
1656 	if (new_size && new_size == old_size) {
1657 		size_t offs = le16_to_cpu(here->e_value_offs);
1658 		void *val = s->base + offs;
1659 
1660 		here->e_value_size = cpu_to_le32(i->value_len);
1661 		if (i->value == EXT4_ZERO_XATTR_VALUE) {
1662 			memset(val, 0, new_size);
1663 		} else {
1664 			memcpy(val, i->value, i->value_len);
1665 			/* Clear padding bytes. */
1666 			memset(val + i->value_len, 0, new_size - i->value_len);
1667 		}
1668 		goto update_hash;
1669 	}
1670 
1671 	/* Compute min_offs and last. */
1672 	last = s->first;
1673 	for (; !IS_LAST_ENTRY(last); last = next) {
1674 		next = EXT4_XATTR_NEXT(last);
1675 		if ((void *)next >= s->end) {
1676 			EXT4_ERROR_INODE(inode, "corrupted xattr entries");
1677 			ret = -EFSCORRUPTED;
1678 			goto out;
1679 		}
1680 		if (!last->e_value_inum && last->e_value_size) {
1681 			size_t offs = le16_to_cpu(last->e_value_offs);
1682 			if (offs < min_offs)
1683 				min_offs = offs;
1684 		}
1685 	}
1686 
1687 	/* Check whether we have enough space. */
1688 	if (i->value) {
1689 		size_t free;
1690 
1691 		free = min_offs - ((void *)last - s->base) - sizeof(__u32);
1692 		if (!s->not_found)
1693 			free += EXT4_XATTR_LEN(name_len) + old_size;
1694 
1695 		if (free < EXT4_XATTR_LEN(name_len) + new_size) {
1696 			ret = -ENOSPC;
1697 			goto out;
1698 		}
1699 
1700 		/*
1701 		 * If storing the value in an external inode is an option,
1702 		 * reserve space for xattr entries/names in the external
1703 		 * attribute block so that a long value does not occupy the
1704 		 * whole space and prevent further entries being added.
1705 		 */
1706 		if (ext4_has_feature_ea_inode(inode->i_sb) &&
1707 		    new_size && is_block &&
1708 		    (min_offs + old_size - new_size) <
1709 					EXT4_XATTR_BLOCK_RESERVE(inode)) {
1710 			ret = -ENOSPC;
1711 			goto out;
1712 		}
1713 	}
1714 
1715 	/*
1716 	 * Getting access to old and new ea inodes is subject to failures.
1717 	 * Finish that work before doing any modifications to the xattr data.
1718 	 */
1719 	if (!s->not_found && here->e_value_inum) {
1720 		ret = ext4_xattr_inode_iget(inode,
1721 					    le32_to_cpu(here->e_value_inum),
1722 					    le32_to_cpu(here->e_hash),
1723 					    &old_ea_inode);
1724 		if (ret) {
1725 			old_ea_inode = NULL;
1726 			goto out;
1727 		}
1728 	}
1729 	if (i->value && in_inode) {
1730 		WARN_ON_ONCE(!i->value_len);
1731 
1732 		ret = ext4_xattr_inode_alloc_quota(inode, i->value_len);
1733 		if (ret)
1734 			goto out;
1735 
1736 		ret = ext4_xattr_inode_lookup_create(handle, inode, i->value,
1737 						     i->value_len,
1738 						     &new_ea_inode);
1739 		if (ret) {
1740 			new_ea_inode = NULL;
1741 			ext4_xattr_inode_free_quota(inode, NULL, i->value_len);
1742 			goto out;
1743 		}
1744 	}
1745 
1746 	if (old_ea_inode) {
1747 		/* We are ready to release ref count on the old_ea_inode. */
1748 		ret = ext4_xattr_inode_dec_ref(handle, old_ea_inode);
1749 		if (ret) {
1750 			/* Release newly required ref count on new_ea_inode. */
1751 			if (new_ea_inode) {
1752 				int err;
1753 
1754 				err = ext4_xattr_inode_dec_ref(handle,
1755 							       new_ea_inode);
1756 				if (err)
1757 					ext4_warning_inode(new_ea_inode,
1758 						  "dec ref new_ea_inode err=%d",
1759 						  err);
1760 				ext4_xattr_inode_free_quota(inode, new_ea_inode,
1761 							    i->value_len);
1762 			}
1763 			goto out;
1764 		}
1765 
1766 		ext4_xattr_inode_free_quota(inode, old_ea_inode,
1767 					    le32_to_cpu(here->e_value_size));
1768 	}
1769 
1770 	/* No failures allowed past this point. */
1771 
1772 	if (!s->not_found && here->e_value_size && !here->e_value_inum) {
1773 		/* Remove the old value. */
1774 		void *first_val = s->base + min_offs;
1775 		size_t offs = le16_to_cpu(here->e_value_offs);
1776 		void *val = s->base + offs;
1777 
1778 		memmove(first_val + old_size, first_val, val - first_val);
1779 		memset(first_val, 0, old_size);
1780 		min_offs += old_size;
1781 
1782 		/* Adjust all value offsets. */
1783 		last = s->first;
1784 		while (!IS_LAST_ENTRY(last)) {
1785 			size_t o = le16_to_cpu(last->e_value_offs);
1786 
1787 			if (!last->e_value_inum &&
1788 			    last->e_value_size && o < offs)
1789 				last->e_value_offs = cpu_to_le16(o + old_size);
1790 			last = EXT4_XATTR_NEXT(last);
1791 		}
1792 	}
1793 
1794 	if (!i->value) {
1795 		/* Remove old name. */
1796 		size_t size = EXT4_XATTR_LEN(name_len);
1797 
1798 		last = ENTRY((void *)last - size);
1799 		memmove(here, (void *)here + size,
1800 			(void *)last - (void *)here + sizeof(__u32));
1801 		memset(last, 0, size);
1802 	} else if (s->not_found) {
1803 		/* Insert new name. */
1804 		size_t size = EXT4_XATTR_LEN(name_len);
1805 		size_t rest = (void *)last - (void *)here + sizeof(__u32);
1806 
1807 		memmove((void *)here + size, here, rest);
1808 		memset(here, 0, size);
1809 		here->e_name_index = i->name_index;
1810 		here->e_name_len = name_len;
1811 		memcpy(here->e_name, i->name, name_len);
1812 	} else {
1813 		/* This is an update, reset value info. */
1814 		here->e_value_inum = 0;
1815 		here->e_value_offs = 0;
1816 		here->e_value_size = 0;
1817 	}
1818 
1819 	if (i->value) {
1820 		/* Insert new value. */
1821 		if (in_inode) {
1822 			here->e_value_inum = cpu_to_le32(new_ea_inode->i_ino);
1823 		} else if (i->value_len) {
1824 			void *val = s->base + min_offs - new_size;
1825 
1826 			here->e_value_offs = cpu_to_le16(min_offs - new_size);
1827 			if (i->value == EXT4_ZERO_XATTR_VALUE) {
1828 				memset(val, 0, new_size);
1829 			} else {
1830 				memcpy(val, i->value, i->value_len);
1831 				/* Clear padding bytes. */
1832 				memset(val + i->value_len, 0,
1833 				       new_size - i->value_len);
1834 			}
1835 		}
1836 		here->e_value_size = cpu_to_le32(i->value_len);
1837 	}
1838 
1839 update_hash:
1840 	if (i->value) {
1841 		__le32 hash = 0;
1842 
1843 		/* Entry hash calculation. */
1844 		if (in_inode) {
1845 			__le32 crc32c_hash;
1846 
1847 			/*
1848 			 * Feed crc32c hash instead of the raw value for entry
1849 			 * hash calculation. This is to avoid walking
1850 			 * potentially long value buffer again.
1851 			 */
1852 			crc32c_hash = cpu_to_le32(
1853 				       ext4_xattr_inode_get_hash(new_ea_inode));
1854 			hash = ext4_xattr_hash_entry(here->e_name,
1855 						     here->e_name_len,
1856 						     &crc32c_hash, 1);
1857 		} else if (is_block) {
1858 			__le32 *value = s->base + le16_to_cpu(
1859 							here->e_value_offs);
1860 
1861 			hash = ext4_xattr_hash_entry(here->e_name,
1862 						     here->e_name_len, value,
1863 						     new_size >> 2);
1864 		}
1865 		here->e_hash = hash;
1866 	}
1867 
1868 	if (is_block)
1869 		ext4_xattr_rehash((struct ext4_xattr_header *)s->base);
1870 
1871 	ret = 0;
1872 out:
1873 	iput(old_ea_inode);
1874 	iput(new_ea_inode);
1875 	return ret;
1876 }
1877 
1878 struct ext4_xattr_block_find {
1879 	struct ext4_xattr_search s;
1880 	struct buffer_head *bh;
1881 };
1882 
1883 static int
1884 ext4_xattr_block_find(struct inode *inode, struct ext4_xattr_info *i,
1885 		      struct ext4_xattr_block_find *bs)
1886 {
1887 	struct super_block *sb = inode->i_sb;
1888 	int error;
1889 
1890 	ea_idebug(inode, "name=%d.%s, value=%p, value_len=%ld",
1891 		  i->name_index, i->name, i->value, (long)i->value_len);
1892 
1893 	if (EXT4_I(inode)->i_file_acl) {
1894 		/* The inode already has an extended attribute block. */
1895 		bs->bh = ext4_sb_bread(sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
1896 		if (IS_ERR(bs->bh)) {
1897 			error = PTR_ERR(bs->bh);
1898 			bs->bh = NULL;
1899 			return error;
1900 		}
1901 		ea_bdebug(bs->bh, "b_count=%d, refcount=%d",
1902 			atomic_read(&(bs->bh->b_count)),
1903 			le32_to_cpu(BHDR(bs->bh)->h_refcount));
1904 		error = ext4_xattr_check_block(inode, bs->bh);
1905 		if (error)
1906 			return error;
1907 		/* Find the named attribute. */
1908 		bs->s.base = BHDR(bs->bh);
1909 		bs->s.first = BFIRST(bs->bh);
1910 		bs->s.end = bs->bh->b_data + bs->bh->b_size;
1911 		bs->s.here = bs->s.first;
1912 		error = xattr_find_entry(inode, &bs->s.here, bs->s.end,
1913 					 i->name_index, i->name, 1);
1914 		if (error && error != -ENODATA)
1915 			return error;
1916 		bs->s.not_found = error;
1917 	}
1918 	return 0;
1919 }
1920 
1921 static int
1922 ext4_xattr_block_set(handle_t *handle, struct inode *inode,
1923 		     struct ext4_xattr_info *i,
1924 		     struct ext4_xattr_block_find *bs)
1925 {
1926 	struct super_block *sb = inode->i_sb;
1927 	struct buffer_head *new_bh = NULL;
1928 	struct ext4_xattr_search s_copy = bs->s;
1929 	struct ext4_xattr_search *s = &s_copy;
1930 	struct mb_cache_entry *ce = NULL;
1931 	int error = 0;
1932 	struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
1933 	struct inode *ea_inode = NULL, *tmp_inode;
1934 	size_t old_ea_inode_quota = 0;
1935 	unsigned int ea_ino;
1936 
1937 
1938 #define header(x) ((struct ext4_xattr_header *)(x))
1939 
1940 	if (s->base) {
1941 		int offset = (char *)s->here - bs->bh->b_data;
1942 
1943 		BUFFER_TRACE(bs->bh, "get_write_access");
1944 		error = ext4_journal_get_write_access(handle, sb, bs->bh,
1945 						      EXT4_JTR_NONE);
1946 		if (error)
1947 			goto cleanup;
1948 		lock_buffer(bs->bh);
1949 
1950 		if (header(s->base)->h_refcount == cpu_to_le32(1)) {
1951 			__u32 hash = le32_to_cpu(BHDR(bs->bh)->h_hash);
1952 
1953 			/*
1954 			 * This must happen under buffer lock for
1955 			 * ext4_xattr_block_set() to reliably detect modified
1956 			 * block
1957 			 */
1958 			if (ea_block_cache) {
1959 				struct mb_cache_entry *oe;
1960 
1961 				oe = mb_cache_entry_delete_or_get(ea_block_cache,
1962 					hash, bs->bh->b_blocknr);
1963 				if (oe) {
1964 					/*
1965 					 * Xattr block is getting reused. Leave
1966 					 * it alone.
1967 					 */
1968 					mb_cache_entry_put(ea_block_cache, oe);
1969 					goto clone_block;
1970 				}
1971 			}
1972 			ea_bdebug(bs->bh, "modifying in-place");
1973 			error = ext4_xattr_set_entry(i, s, handle, inode,
1974 						     true /* is_block */);
1975 			ext4_xattr_block_csum_set(inode, bs->bh);
1976 			unlock_buffer(bs->bh);
1977 			if (error == -EFSCORRUPTED)
1978 				goto bad_block;
1979 			if (!error)
1980 				error = ext4_handle_dirty_metadata(handle,
1981 								   inode,
1982 								   bs->bh);
1983 			if (error)
1984 				goto cleanup;
1985 			goto inserted;
1986 		}
1987 clone_block:
1988 		unlock_buffer(bs->bh);
1989 		ea_bdebug(bs->bh, "cloning");
1990 		s->base = kmemdup(BHDR(bs->bh), bs->bh->b_size, GFP_NOFS);
1991 		error = -ENOMEM;
1992 		if (s->base == NULL)
1993 			goto cleanup;
1994 		s->first = ENTRY(header(s->base)+1);
1995 		header(s->base)->h_refcount = cpu_to_le32(1);
1996 		s->here = ENTRY(s->base + offset);
1997 		s->end = s->base + bs->bh->b_size;
1998 
1999 		/*
2000 		 * If existing entry points to an xattr inode, we need
2001 		 * to prevent ext4_xattr_set_entry() from decrementing
2002 		 * ref count on it because the reference belongs to the
2003 		 * original block. In this case, make the entry look
2004 		 * like it has an empty value.
2005 		 */
2006 		if (!s->not_found && s->here->e_value_inum) {
2007 			ea_ino = le32_to_cpu(s->here->e_value_inum);
2008 			error = ext4_xattr_inode_iget(inode, ea_ino,
2009 				      le32_to_cpu(s->here->e_hash),
2010 				      &tmp_inode);
2011 			if (error)
2012 				goto cleanup;
2013 
2014 			if (!ext4_test_inode_state(tmp_inode,
2015 					EXT4_STATE_LUSTRE_EA_INODE)) {
2016 				/*
2017 				 * Defer quota free call for previous
2018 				 * inode until success is guaranteed.
2019 				 */
2020 				old_ea_inode_quota = le32_to_cpu(
2021 						s->here->e_value_size);
2022 			}
2023 			iput(tmp_inode);
2024 
2025 			s->here->e_value_inum = 0;
2026 			s->here->e_value_size = 0;
2027 		}
2028 	} else {
2029 		/* Allocate a buffer where we construct the new block. */
2030 		s->base = kzalloc(sb->s_blocksize, GFP_NOFS);
2031 		error = -ENOMEM;
2032 		if (s->base == NULL)
2033 			goto cleanup;
2034 		header(s->base)->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
2035 		header(s->base)->h_blocks = cpu_to_le32(1);
2036 		header(s->base)->h_refcount = cpu_to_le32(1);
2037 		s->first = ENTRY(header(s->base)+1);
2038 		s->here = ENTRY(header(s->base)+1);
2039 		s->end = s->base + sb->s_blocksize;
2040 	}
2041 
2042 	error = ext4_xattr_set_entry(i, s, handle, inode, true /* is_block */);
2043 	if (error == -EFSCORRUPTED)
2044 		goto bad_block;
2045 	if (error)
2046 		goto cleanup;
2047 
2048 	if (i->value && s->here->e_value_inum) {
2049 		/*
2050 		 * A ref count on ea_inode has been taken as part of the call to
2051 		 * ext4_xattr_set_entry() above. We would like to drop this
2052 		 * extra ref but we have to wait until the xattr block is
2053 		 * initialized and has its own ref count on the ea_inode.
2054 		 */
2055 		ea_ino = le32_to_cpu(s->here->e_value_inum);
2056 		error = ext4_xattr_inode_iget(inode, ea_ino,
2057 					      le32_to_cpu(s->here->e_hash),
2058 					      &ea_inode);
2059 		if (error) {
2060 			ea_inode = NULL;
2061 			goto cleanup;
2062 		}
2063 	}
2064 
2065 inserted:
2066 	if (!IS_LAST_ENTRY(s->first)) {
2067 		new_bh = ext4_xattr_block_cache_find(inode, header(s->base),
2068 						     &ce);
2069 		if (new_bh) {
2070 			/* We found an identical block in the cache. */
2071 			if (new_bh == bs->bh)
2072 				ea_bdebug(new_bh, "keeping");
2073 			else {
2074 				u32 ref;
2075 
2076 				WARN_ON_ONCE(dquot_initialize_needed(inode));
2077 
2078 				/* The old block is released after updating
2079 				   the inode. */
2080 				error = dquot_alloc_block(inode,
2081 						EXT4_C2B(EXT4_SB(sb), 1));
2082 				if (error)
2083 					goto cleanup;
2084 				BUFFER_TRACE(new_bh, "get_write_access");
2085 				error = ext4_journal_get_write_access(
2086 						handle, sb, new_bh,
2087 						EXT4_JTR_NONE);
2088 				if (error)
2089 					goto cleanup_dquot;
2090 				lock_buffer(new_bh);
2091 				/*
2092 				 * We have to be careful about races with
2093 				 * adding references to xattr block. Once we
2094 				 * hold buffer lock xattr block's state is
2095 				 * stable so we can check the additional
2096 				 * reference fits.
2097 				 */
2098 				ref = le32_to_cpu(BHDR(new_bh)->h_refcount) + 1;
2099 				if (ref > EXT4_XATTR_REFCOUNT_MAX) {
2100 					/*
2101 					 * Undo everything and check mbcache
2102 					 * again.
2103 					 */
2104 					unlock_buffer(new_bh);
2105 					dquot_free_block(inode,
2106 							 EXT4_C2B(EXT4_SB(sb),
2107 								  1));
2108 					brelse(new_bh);
2109 					mb_cache_entry_put(ea_block_cache, ce);
2110 					ce = NULL;
2111 					new_bh = NULL;
2112 					goto inserted;
2113 				}
2114 				BHDR(new_bh)->h_refcount = cpu_to_le32(ref);
2115 				if (ref == EXT4_XATTR_REFCOUNT_MAX)
2116 					clear_bit(MBE_REUSABLE_B, &ce->e_flags);
2117 				ea_bdebug(new_bh, "reusing; refcount now=%d",
2118 					  ref);
2119 				ext4_xattr_block_csum_set(inode, new_bh);
2120 				unlock_buffer(new_bh);
2121 				error = ext4_handle_dirty_metadata(handle,
2122 								   inode,
2123 								   new_bh);
2124 				if (error)
2125 					goto cleanup_dquot;
2126 			}
2127 			mb_cache_entry_touch(ea_block_cache, ce);
2128 			mb_cache_entry_put(ea_block_cache, ce);
2129 			ce = NULL;
2130 		} else if (bs->bh && s->base == bs->bh->b_data) {
2131 			/* We were modifying this block in-place. */
2132 			ea_bdebug(bs->bh, "keeping this block");
2133 			ext4_xattr_block_cache_insert(ea_block_cache, bs->bh);
2134 			new_bh = bs->bh;
2135 			get_bh(new_bh);
2136 		} else {
2137 			/* We need to allocate a new block */
2138 			ext4_fsblk_t goal, block;
2139 
2140 			WARN_ON_ONCE(dquot_initialize_needed(inode));
2141 
2142 			goal = ext4_group_first_block_no(sb,
2143 						EXT4_I(inode)->i_block_group);
2144 			block = ext4_new_meta_blocks(handle, inode, goal, 0,
2145 						     NULL, &error);
2146 			if (error)
2147 				goto cleanup;
2148 
2149 			ea_idebug(inode, "creating block %llu",
2150 				  (unsigned long long)block);
2151 
2152 			new_bh = sb_getblk(sb, block);
2153 			if (unlikely(!new_bh)) {
2154 				error = -ENOMEM;
2155 getblk_failed:
2156 				ext4_free_blocks(handle, inode, NULL, block, 1,
2157 						 EXT4_FREE_BLOCKS_METADATA);
2158 				goto cleanup;
2159 			}
2160 			error = ext4_xattr_inode_inc_ref_all(handle, inode,
2161 						      ENTRY(header(s->base)+1));
2162 			if (error)
2163 				goto getblk_failed;
2164 			if (ea_inode) {
2165 				/* Drop the extra ref on ea_inode. */
2166 				error = ext4_xattr_inode_dec_ref(handle,
2167 								 ea_inode);
2168 				if (error)
2169 					ext4_warning_inode(ea_inode,
2170 							   "dec ref error=%d",
2171 							   error);
2172 				iput(ea_inode);
2173 				ea_inode = NULL;
2174 			}
2175 
2176 			lock_buffer(new_bh);
2177 			error = ext4_journal_get_create_access(handle, sb,
2178 							new_bh, EXT4_JTR_NONE);
2179 			if (error) {
2180 				unlock_buffer(new_bh);
2181 				error = -EIO;
2182 				goto getblk_failed;
2183 			}
2184 			memcpy(new_bh->b_data, s->base, new_bh->b_size);
2185 			ext4_xattr_block_csum_set(inode, new_bh);
2186 			set_buffer_uptodate(new_bh);
2187 			unlock_buffer(new_bh);
2188 			ext4_xattr_block_cache_insert(ea_block_cache, new_bh);
2189 			error = ext4_handle_dirty_metadata(handle, inode,
2190 							   new_bh);
2191 			if (error)
2192 				goto cleanup;
2193 		}
2194 	}
2195 
2196 	if (old_ea_inode_quota)
2197 		ext4_xattr_inode_free_quota(inode, NULL, old_ea_inode_quota);
2198 
2199 	/* Update the inode. */
2200 	EXT4_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
2201 
2202 	/* Drop the previous xattr block. */
2203 	if (bs->bh && bs->bh != new_bh) {
2204 		struct ext4_xattr_inode_array *ea_inode_array = NULL;
2205 
2206 		ext4_xattr_release_block(handle, inode, bs->bh,
2207 					 &ea_inode_array,
2208 					 0 /* extra_credits */);
2209 		ext4_xattr_inode_array_free(ea_inode_array);
2210 	}
2211 	error = 0;
2212 
2213 cleanup:
2214 	if (ea_inode) {
2215 		int error2;
2216 
2217 		error2 = ext4_xattr_inode_dec_ref(handle, ea_inode);
2218 		if (error2)
2219 			ext4_warning_inode(ea_inode, "dec ref error=%d",
2220 					   error2);
2221 
2222 		/* If there was an error, revert the quota charge. */
2223 		if (error)
2224 			ext4_xattr_inode_free_quota(inode, ea_inode,
2225 						    i_size_read(ea_inode));
2226 		iput(ea_inode);
2227 	}
2228 	if (ce)
2229 		mb_cache_entry_put(ea_block_cache, ce);
2230 	brelse(new_bh);
2231 	if (!(bs->bh && s->base == bs->bh->b_data))
2232 		kfree(s->base);
2233 
2234 	return error;
2235 
2236 cleanup_dquot:
2237 	dquot_free_block(inode, EXT4_C2B(EXT4_SB(sb), 1));
2238 	goto cleanup;
2239 
2240 bad_block:
2241 	EXT4_ERROR_INODE(inode, "bad block %llu",
2242 			 EXT4_I(inode)->i_file_acl);
2243 	goto cleanup;
2244 
2245 #undef header
2246 }
2247 
2248 int ext4_xattr_ibody_find(struct inode *inode, struct ext4_xattr_info *i,
2249 			  struct ext4_xattr_ibody_find *is)
2250 {
2251 	struct ext4_xattr_ibody_header *header;
2252 	struct ext4_inode *raw_inode;
2253 	int error;
2254 
2255 	if (!EXT4_INODE_HAS_XATTR_SPACE(inode))
2256 		return 0;
2257 
2258 	raw_inode = ext4_raw_inode(&is->iloc);
2259 	header = IHDR(inode, raw_inode);
2260 	is->s.base = is->s.first = IFIRST(header);
2261 	is->s.here = is->s.first;
2262 	is->s.end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
2263 	if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
2264 		error = xattr_check_inode(inode, header, is->s.end);
2265 		if (error)
2266 			return error;
2267 		/* Find the named attribute. */
2268 		error = xattr_find_entry(inode, &is->s.here, is->s.end,
2269 					 i->name_index, i->name, 0);
2270 		if (error && error != -ENODATA)
2271 			return error;
2272 		is->s.not_found = error;
2273 	}
2274 	return 0;
2275 }
2276 
2277 int ext4_xattr_ibody_set(handle_t *handle, struct inode *inode,
2278 				struct ext4_xattr_info *i,
2279 				struct ext4_xattr_ibody_find *is)
2280 {
2281 	struct ext4_xattr_ibody_header *header;
2282 	struct ext4_xattr_search *s = &is->s;
2283 	int error;
2284 
2285 	if (!EXT4_INODE_HAS_XATTR_SPACE(inode))
2286 		return -ENOSPC;
2287 
2288 	error = ext4_xattr_set_entry(i, s, handle, inode, false /* is_block */);
2289 	if (error)
2290 		return error;
2291 	header = IHDR(inode, ext4_raw_inode(&is->iloc));
2292 	if (!IS_LAST_ENTRY(s->first)) {
2293 		header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
2294 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
2295 	} else {
2296 		header->h_magic = cpu_to_le32(0);
2297 		ext4_clear_inode_state(inode, EXT4_STATE_XATTR);
2298 	}
2299 	return 0;
2300 }
2301 
2302 static int ext4_xattr_value_same(struct ext4_xattr_search *s,
2303 				 struct ext4_xattr_info *i)
2304 {
2305 	void *value;
2306 
2307 	/* When e_value_inum is set the value is stored externally. */
2308 	if (s->here->e_value_inum)
2309 		return 0;
2310 	if (le32_to_cpu(s->here->e_value_size) != i->value_len)
2311 		return 0;
2312 	value = ((void *)s->base) + le16_to_cpu(s->here->e_value_offs);
2313 	return !memcmp(value, i->value, i->value_len);
2314 }
2315 
2316 static struct buffer_head *ext4_xattr_get_block(struct inode *inode)
2317 {
2318 	struct buffer_head *bh;
2319 	int error;
2320 
2321 	if (!EXT4_I(inode)->i_file_acl)
2322 		return NULL;
2323 	bh = ext4_sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
2324 	if (IS_ERR(bh))
2325 		return bh;
2326 	error = ext4_xattr_check_block(inode, bh);
2327 	if (error) {
2328 		brelse(bh);
2329 		return ERR_PTR(error);
2330 	}
2331 	return bh;
2332 }
2333 
2334 /*
2335  * ext4_xattr_set_handle()
2336  *
2337  * Create, replace or remove an extended attribute for this inode.  Value
2338  * is NULL to remove an existing extended attribute, and non-NULL to
2339  * either replace an existing extended attribute, or create a new extended
2340  * attribute. The flags XATTR_REPLACE and XATTR_CREATE
2341  * specify that an extended attribute must exist and must not exist
2342  * previous to the call, respectively.
2343  *
2344  * Returns 0, or a negative error number on failure.
2345  */
2346 int
2347 ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
2348 		      const char *name, const void *value, size_t value_len,
2349 		      int flags)
2350 {
2351 	struct ext4_xattr_info i = {
2352 		.name_index = name_index,
2353 		.name = name,
2354 		.value = value,
2355 		.value_len = value_len,
2356 		.in_inode = 0,
2357 	};
2358 	struct ext4_xattr_ibody_find is = {
2359 		.s = { .not_found = -ENODATA, },
2360 	};
2361 	struct ext4_xattr_block_find bs = {
2362 		.s = { .not_found = -ENODATA, },
2363 	};
2364 	int no_expand;
2365 	int error;
2366 
2367 	if (!name)
2368 		return -EINVAL;
2369 	if (strlen(name) > 255)
2370 		return -ERANGE;
2371 
2372 	ext4_write_lock_xattr(inode, &no_expand);
2373 
2374 	/* Check journal credits under write lock. */
2375 	if (ext4_handle_valid(handle)) {
2376 		struct buffer_head *bh;
2377 		int credits;
2378 
2379 		bh = ext4_xattr_get_block(inode);
2380 		if (IS_ERR(bh)) {
2381 			error = PTR_ERR(bh);
2382 			goto cleanup;
2383 		}
2384 
2385 		credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
2386 						   value_len,
2387 						   flags & XATTR_CREATE);
2388 		brelse(bh);
2389 
2390 		if (jbd2_handle_buffer_credits(handle) < credits) {
2391 			error = -ENOSPC;
2392 			goto cleanup;
2393 		}
2394 		WARN_ON_ONCE(!(current->flags & PF_MEMALLOC_NOFS));
2395 	}
2396 
2397 	error = ext4_reserve_inode_write(handle, inode, &is.iloc);
2398 	if (error)
2399 		goto cleanup;
2400 
2401 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW)) {
2402 		struct ext4_inode *raw_inode = ext4_raw_inode(&is.iloc);
2403 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
2404 		ext4_clear_inode_state(inode, EXT4_STATE_NEW);
2405 	}
2406 
2407 	error = ext4_xattr_ibody_find(inode, &i, &is);
2408 	if (error)
2409 		goto cleanup;
2410 	if (is.s.not_found)
2411 		error = ext4_xattr_block_find(inode, &i, &bs);
2412 	if (error)
2413 		goto cleanup;
2414 	if (is.s.not_found && bs.s.not_found) {
2415 		error = -ENODATA;
2416 		if (flags & XATTR_REPLACE)
2417 			goto cleanup;
2418 		error = 0;
2419 		if (!value)
2420 			goto cleanup;
2421 	} else {
2422 		error = -EEXIST;
2423 		if (flags & XATTR_CREATE)
2424 			goto cleanup;
2425 	}
2426 
2427 	if (!value) {
2428 		if (!is.s.not_found)
2429 			error = ext4_xattr_ibody_set(handle, inode, &i, &is);
2430 		else if (!bs.s.not_found)
2431 			error = ext4_xattr_block_set(handle, inode, &i, &bs);
2432 	} else {
2433 		error = 0;
2434 		/* Xattr value did not change? Save us some work and bail out */
2435 		if (!is.s.not_found && ext4_xattr_value_same(&is.s, &i))
2436 			goto cleanup;
2437 		if (!bs.s.not_found && ext4_xattr_value_same(&bs.s, &i))
2438 			goto cleanup;
2439 
2440 		if (ext4_has_feature_ea_inode(inode->i_sb) &&
2441 		    (EXT4_XATTR_SIZE(i.value_len) >
2442 			EXT4_XATTR_MIN_LARGE_EA_SIZE(inode->i_sb->s_blocksize)))
2443 			i.in_inode = 1;
2444 retry_inode:
2445 		error = ext4_xattr_ibody_set(handle, inode, &i, &is);
2446 		if (!error && !bs.s.not_found) {
2447 			i.value = NULL;
2448 			error = ext4_xattr_block_set(handle, inode, &i, &bs);
2449 		} else if (error == -ENOSPC) {
2450 			if (EXT4_I(inode)->i_file_acl && !bs.s.base) {
2451 				brelse(bs.bh);
2452 				bs.bh = NULL;
2453 				error = ext4_xattr_block_find(inode, &i, &bs);
2454 				if (error)
2455 					goto cleanup;
2456 			}
2457 			error = ext4_xattr_block_set(handle, inode, &i, &bs);
2458 			if (!error && !is.s.not_found) {
2459 				i.value = NULL;
2460 				error = ext4_xattr_ibody_set(handle, inode, &i,
2461 							     &is);
2462 			} else if (error == -ENOSPC) {
2463 				/*
2464 				 * Xattr does not fit in the block, store at
2465 				 * external inode if possible.
2466 				 */
2467 				if (ext4_has_feature_ea_inode(inode->i_sb) &&
2468 				    i.value_len && !i.in_inode) {
2469 					i.in_inode = 1;
2470 					goto retry_inode;
2471 				}
2472 			}
2473 		}
2474 	}
2475 	if (!error) {
2476 		ext4_xattr_update_super_block(handle, inode->i_sb);
2477 		inode->i_ctime = current_time(inode);
2478 		inode_inc_iversion(inode);
2479 		if (!value)
2480 			no_expand = 0;
2481 		error = ext4_mark_iloc_dirty(handle, inode, &is.iloc);
2482 		/*
2483 		 * The bh is consumed by ext4_mark_iloc_dirty, even with
2484 		 * error != 0.
2485 		 */
2486 		is.iloc.bh = NULL;
2487 		if (IS_SYNC(inode))
2488 			ext4_handle_sync(handle);
2489 	}
2490 	ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_XATTR, handle);
2491 
2492 cleanup:
2493 	brelse(is.iloc.bh);
2494 	brelse(bs.bh);
2495 	ext4_write_unlock_xattr(inode, &no_expand);
2496 	return error;
2497 }
2498 
2499 int ext4_xattr_set_credits(struct inode *inode, size_t value_len,
2500 			   bool is_create, int *credits)
2501 {
2502 	struct buffer_head *bh;
2503 	int err;
2504 
2505 	*credits = 0;
2506 
2507 	if (!EXT4_SB(inode->i_sb)->s_journal)
2508 		return 0;
2509 
2510 	down_read(&EXT4_I(inode)->xattr_sem);
2511 
2512 	bh = ext4_xattr_get_block(inode);
2513 	if (IS_ERR(bh)) {
2514 		err = PTR_ERR(bh);
2515 	} else {
2516 		*credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
2517 						    value_len, is_create);
2518 		brelse(bh);
2519 		err = 0;
2520 	}
2521 
2522 	up_read(&EXT4_I(inode)->xattr_sem);
2523 	return err;
2524 }
2525 
2526 /*
2527  * ext4_xattr_set()
2528  *
2529  * Like ext4_xattr_set_handle, but start from an inode. This extended
2530  * attribute modification is a filesystem transaction by itself.
2531  *
2532  * Returns 0, or a negative error number on failure.
2533  */
2534 int
2535 ext4_xattr_set(struct inode *inode, int name_index, const char *name,
2536 	       const void *value, size_t value_len, int flags)
2537 {
2538 	handle_t *handle;
2539 	struct super_block *sb = inode->i_sb;
2540 	int error, retries = 0;
2541 	int credits;
2542 
2543 	error = dquot_initialize(inode);
2544 	if (error)
2545 		return error;
2546 
2547 retry:
2548 	error = ext4_xattr_set_credits(inode, value_len, flags & XATTR_CREATE,
2549 				       &credits);
2550 	if (error)
2551 		return error;
2552 
2553 	handle = ext4_journal_start(inode, EXT4_HT_XATTR, credits);
2554 	if (IS_ERR(handle)) {
2555 		error = PTR_ERR(handle);
2556 	} else {
2557 		int error2;
2558 
2559 		error = ext4_xattr_set_handle(handle, inode, name_index, name,
2560 					      value, value_len, flags);
2561 		error2 = ext4_journal_stop(handle);
2562 		if (error == -ENOSPC &&
2563 		    ext4_should_retry_alloc(sb, &retries))
2564 			goto retry;
2565 		if (error == 0)
2566 			error = error2;
2567 	}
2568 	ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_XATTR, NULL);
2569 
2570 	return error;
2571 }
2572 
2573 /*
2574  * Shift the EA entries in the inode to create space for the increased
2575  * i_extra_isize.
2576  */
2577 static void ext4_xattr_shift_entries(struct ext4_xattr_entry *entry,
2578 				     int value_offs_shift, void *to,
2579 				     void *from, size_t n)
2580 {
2581 	struct ext4_xattr_entry *last = entry;
2582 	int new_offs;
2583 
2584 	/* We always shift xattr headers further thus offsets get lower */
2585 	BUG_ON(value_offs_shift > 0);
2586 
2587 	/* Adjust the value offsets of the entries */
2588 	for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
2589 		if (!last->e_value_inum && last->e_value_size) {
2590 			new_offs = le16_to_cpu(last->e_value_offs) +
2591 							value_offs_shift;
2592 			last->e_value_offs = cpu_to_le16(new_offs);
2593 		}
2594 	}
2595 	/* Shift the entries by n bytes */
2596 	memmove(to, from, n);
2597 }
2598 
2599 /*
2600  * Move xattr pointed to by 'entry' from inode into external xattr block
2601  */
2602 static int ext4_xattr_move_to_block(handle_t *handle, struct inode *inode,
2603 				    struct ext4_inode *raw_inode,
2604 				    struct ext4_xattr_entry *entry)
2605 {
2606 	struct ext4_xattr_ibody_find *is = NULL;
2607 	struct ext4_xattr_block_find *bs = NULL;
2608 	char *buffer = NULL, *b_entry_name = NULL;
2609 	size_t value_size = le32_to_cpu(entry->e_value_size);
2610 	struct ext4_xattr_info i = {
2611 		.value = NULL,
2612 		.value_len = 0,
2613 		.name_index = entry->e_name_index,
2614 		.in_inode = !!entry->e_value_inum,
2615 	};
2616 	struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode);
2617 	int needs_kvfree = 0;
2618 	int error;
2619 
2620 	is = kzalloc(sizeof(struct ext4_xattr_ibody_find), GFP_NOFS);
2621 	bs = kzalloc(sizeof(struct ext4_xattr_block_find), GFP_NOFS);
2622 	b_entry_name = kmalloc(entry->e_name_len + 1, GFP_NOFS);
2623 	if (!is || !bs || !b_entry_name) {
2624 		error = -ENOMEM;
2625 		goto out;
2626 	}
2627 
2628 	is->s.not_found = -ENODATA;
2629 	bs->s.not_found = -ENODATA;
2630 	is->iloc.bh = NULL;
2631 	bs->bh = NULL;
2632 
2633 	/* Save the entry name and the entry value */
2634 	if (entry->e_value_inum) {
2635 		buffer = kvmalloc(value_size, GFP_NOFS);
2636 		if (!buffer) {
2637 			error = -ENOMEM;
2638 			goto out;
2639 		}
2640 		needs_kvfree = 1;
2641 		error = ext4_xattr_inode_get(inode, entry, buffer, value_size);
2642 		if (error)
2643 			goto out;
2644 	} else {
2645 		size_t value_offs = le16_to_cpu(entry->e_value_offs);
2646 		buffer = (void *)IFIRST(header) + value_offs;
2647 	}
2648 
2649 	memcpy(b_entry_name, entry->e_name, entry->e_name_len);
2650 	b_entry_name[entry->e_name_len] = '\0';
2651 	i.name = b_entry_name;
2652 
2653 	error = ext4_get_inode_loc(inode, &is->iloc);
2654 	if (error)
2655 		goto out;
2656 
2657 	error = ext4_xattr_ibody_find(inode, &i, is);
2658 	if (error)
2659 		goto out;
2660 
2661 	i.value = buffer;
2662 	i.value_len = value_size;
2663 	error = ext4_xattr_block_find(inode, &i, bs);
2664 	if (error)
2665 		goto out;
2666 
2667 	/* Move ea entry from the inode into the block */
2668 	error = ext4_xattr_block_set(handle, inode, &i, bs);
2669 	if (error)
2670 		goto out;
2671 
2672 	/* Remove the chosen entry from the inode */
2673 	i.value = NULL;
2674 	i.value_len = 0;
2675 	error = ext4_xattr_ibody_set(handle, inode, &i, is);
2676 
2677 out:
2678 	kfree(b_entry_name);
2679 	if (needs_kvfree && buffer)
2680 		kvfree(buffer);
2681 	if (is)
2682 		brelse(is->iloc.bh);
2683 	if (bs)
2684 		brelse(bs->bh);
2685 	kfree(is);
2686 	kfree(bs);
2687 
2688 	return error;
2689 }
2690 
2691 static int ext4_xattr_make_inode_space(handle_t *handle, struct inode *inode,
2692 				       struct ext4_inode *raw_inode,
2693 				       int isize_diff, size_t ifree,
2694 				       size_t bfree, int *total_ino)
2695 {
2696 	struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode);
2697 	struct ext4_xattr_entry *small_entry;
2698 	struct ext4_xattr_entry *entry;
2699 	struct ext4_xattr_entry *last;
2700 	unsigned int entry_size;	/* EA entry size */
2701 	unsigned int total_size;	/* EA entry size + value size */
2702 	unsigned int min_total_size;
2703 	int error;
2704 
2705 	while (isize_diff > ifree) {
2706 		entry = NULL;
2707 		small_entry = NULL;
2708 		min_total_size = ~0U;
2709 		last = IFIRST(header);
2710 		/* Find the entry best suited to be pushed into EA block */
2711 		for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
2712 			/* never move system.data out of the inode */
2713 			if ((last->e_name_len == 4) &&
2714 			    (last->e_name_index == EXT4_XATTR_INDEX_SYSTEM) &&
2715 			    !memcmp(last->e_name, "data", 4))
2716 				continue;
2717 			total_size = EXT4_XATTR_LEN(last->e_name_len);
2718 			if (!last->e_value_inum)
2719 				total_size += EXT4_XATTR_SIZE(
2720 					       le32_to_cpu(last->e_value_size));
2721 			if (total_size <= bfree &&
2722 			    total_size < min_total_size) {
2723 				if (total_size + ifree < isize_diff) {
2724 					small_entry = last;
2725 				} else {
2726 					entry = last;
2727 					min_total_size = total_size;
2728 				}
2729 			}
2730 		}
2731 
2732 		if (entry == NULL) {
2733 			if (small_entry == NULL)
2734 				return -ENOSPC;
2735 			entry = small_entry;
2736 		}
2737 
2738 		entry_size = EXT4_XATTR_LEN(entry->e_name_len);
2739 		total_size = entry_size;
2740 		if (!entry->e_value_inum)
2741 			total_size += EXT4_XATTR_SIZE(
2742 					      le32_to_cpu(entry->e_value_size));
2743 		error = ext4_xattr_move_to_block(handle, inode, raw_inode,
2744 						 entry);
2745 		if (error)
2746 			return error;
2747 
2748 		*total_ino -= entry_size;
2749 		ifree += total_size;
2750 		bfree -= total_size;
2751 	}
2752 
2753 	return 0;
2754 }
2755 
2756 /*
2757  * Expand an inode by new_extra_isize bytes when EAs are present.
2758  * Returns 0 on success or negative error number on failure.
2759  */
2760 int ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize,
2761 			       struct ext4_inode *raw_inode, handle_t *handle)
2762 {
2763 	struct ext4_xattr_ibody_header *header;
2764 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2765 	static unsigned int mnt_count;
2766 	size_t min_offs;
2767 	size_t ifree, bfree;
2768 	int total_ino;
2769 	void *base, *end;
2770 	int error = 0, tried_min_extra_isize = 0;
2771 	int s_min_extra_isize = le16_to_cpu(sbi->s_es->s_min_extra_isize);
2772 	int isize_diff;	/* How much do we need to grow i_extra_isize */
2773 
2774 retry:
2775 	isize_diff = new_extra_isize - EXT4_I(inode)->i_extra_isize;
2776 	if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
2777 		return 0;
2778 
2779 	header = IHDR(inode, raw_inode);
2780 
2781 	/*
2782 	 * Check if enough free space is available in the inode to shift the
2783 	 * entries ahead by new_extra_isize.
2784 	 */
2785 
2786 	base = IFIRST(header);
2787 	end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
2788 	min_offs = end - base;
2789 	total_ino = sizeof(struct ext4_xattr_ibody_header) + sizeof(u32);
2790 
2791 	error = xattr_check_inode(inode, header, end);
2792 	if (error)
2793 		goto cleanup;
2794 
2795 	ifree = ext4_xattr_free_space(base, &min_offs, base, &total_ino);
2796 	if (ifree >= isize_diff)
2797 		goto shift;
2798 
2799 	/*
2800 	 * Enough free space isn't available in the inode, check if
2801 	 * EA block can hold new_extra_isize bytes.
2802 	 */
2803 	if (EXT4_I(inode)->i_file_acl) {
2804 		struct buffer_head *bh;
2805 
2806 		bh = ext4_sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
2807 		if (IS_ERR(bh)) {
2808 			error = PTR_ERR(bh);
2809 			goto cleanup;
2810 		}
2811 		error = ext4_xattr_check_block(inode, bh);
2812 		if (error) {
2813 			brelse(bh);
2814 			goto cleanup;
2815 		}
2816 		base = BHDR(bh);
2817 		end = bh->b_data + bh->b_size;
2818 		min_offs = end - base;
2819 		bfree = ext4_xattr_free_space(BFIRST(bh), &min_offs, base,
2820 					      NULL);
2821 		brelse(bh);
2822 		if (bfree + ifree < isize_diff) {
2823 			if (!tried_min_extra_isize && s_min_extra_isize) {
2824 				tried_min_extra_isize++;
2825 				new_extra_isize = s_min_extra_isize;
2826 				goto retry;
2827 			}
2828 			error = -ENOSPC;
2829 			goto cleanup;
2830 		}
2831 	} else {
2832 		bfree = inode->i_sb->s_blocksize;
2833 	}
2834 
2835 	error = ext4_xattr_make_inode_space(handle, inode, raw_inode,
2836 					    isize_diff, ifree, bfree,
2837 					    &total_ino);
2838 	if (error) {
2839 		if (error == -ENOSPC && !tried_min_extra_isize &&
2840 		    s_min_extra_isize) {
2841 			tried_min_extra_isize++;
2842 			new_extra_isize = s_min_extra_isize;
2843 			goto retry;
2844 		}
2845 		goto cleanup;
2846 	}
2847 shift:
2848 	/* Adjust the offsets and shift the remaining entries ahead */
2849 	ext4_xattr_shift_entries(IFIRST(header), EXT4_I(inode)->i_extra_isize
2850 			- new_extra_isize, (void *)raw_inode +
2851 			EXT4_GOOD_OLD_INODE_SIZE + new_extra_isize,
2852 			(void *)header, total_ino);
2853 	EXT4_I(inode)->i_extra_isize = new_extra_isize;
2854 
2855 	if (ext4_has_inline_data(inode))
2856 		error = ext4_find_inline_data_nolock(inode);
2857 
2858 cleanup:
2859 	if (error && (mnt_count != le16_to_cpu(sbi->s_es->s_mnt_count))) {
2860 		ext4_warning(inode->i_sb, "Unable to expand inode %lu. Delete some EAs or run e2fsck.",
2861 			     inode->i_ino);
2862 		mnt_count = le16_to_cpu(sbi->s_es->s_mnt_count);
2863 	}
2864 	return error;
2865 }
2866 
2867 #define EIA_INCR 16 /* must be 2^n */
2868 #define EIA_MASK (EIA_INCR - 1)
2869 
2870 /* Add the large xattr @inode into @ea_inode_array for deferred iput().
2871  * If @ea_inode_array is new or full it will be grown and the old
2872  * contents copied over.
2873  */
2874 static int
2875 ext4_expand_inode_array(struct ext4_xattr_inode_array **ea_inode_array,
2876 			struct inode *inode)
2877 {
2878 	if (*ea_inode_array == NULL) {
2879 		/*
2880 		 * Start with 15 inodes, so it fits into a power-of-two size.
2881 		 * If *ea_inode_array is NULL, this is essentially offsetof()
2882 		 */
2883 		(*ea_inode_array) =
2884 			kmalloc(offsetof(struct ext4_xattr_inode_array,
2885 					 inodes[EIA_MASK]),
2886 				GFP_NOFS);
2887 		if (*ea_inode_array == NULL)
2888 			return -ENOMEM;
2889 		(*ea_inode_array)->count = 0;
2890 	} else if (((*ea_inode_array)->count & EIA_MASK) == EIA_MASK) {
2891 		/* expand the array once all 15 + n * 16 slots are full */
2892 		struct ext4_xattr_inode_array *new_array = NULL;
2893 		int count = (*ea_inode_array)->count;
2894 
2895 		/* if new_array is NULL, this is essentially offsetof() */
2896 		new_array = kmalloc(
2897 				offsetof(struct ext4_xattr_inode_array,
2898 					 inodes[count + EIA_INCR]),
2899 				GFP_NOFS);
2900 		if (new_array == NULL)
2901 			return -ENOMEM;
2902 		memcpy(new_array, *ea_inode_array,
2903 		       offsetof(struct ext4_xattr_inode_array, inodes[count]));
2904 		kfree(*ea_inode_array);
2905 		*ea_inode_array = new_array;
2906 	}
2907 	(*ea_inode_array)->inodes[(*ea_inode_array)->count++] = inode;
2908 	return 0;
2909 }
2910 
2911 /*
2912  * ext4_xattr_delete_inode()
2913  *
2914  * Free extended attribute resources associated with this inode. Traverse
2915  * all entries and decrement reference on any xattr inodes associated with this
2916  * inode. This is called immediately before an inode is freed. We have exclusive
2917  * access to the inode. If an orphan inode is deleted it will also release its
2918  * references on xattr block and xattr inodes.
2919  */
2920 int ext4_xattr_delete_inode(handle_t *handle, struct inode *inode,
2921 			    struct ext4_xattr_inode_array **ea_inode_array,
2922 			    int extra_credits)
2923 {
2924 	struct buffer_head *bh = NULL;
2925 	struct ext4_xattr_ibody_header *header;
2926 	struct ext4_iloc iloc = { .bh = NULL };
2927 	struct ext4_xattr_entry *entry;
2928 	struct inode *ea_inode;
2929 	int error;
2930 
2931 	error = ext4_journal_ensure_credits(handle, extra_credits,
2932 			ext4_free_metadata_revoke_credits(inode->i_sb, 1));
2933 	if (error < 0) {
2934 		EXT4_ERROR_INODE(inode, "ensure credits (error %d)", error);
2935 		goto cleanup;
2936 	}
2937 
2938 	if (ext4_has_feature_ea_inode(inode->i_sb) &&
2939 	    ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
2940 
2941 		error = ext4_get_inode_loc(inode, &iloc);
2942 		if (error) {
2943 			EXT4_ERROR_INODE(inode, "inode loc (error %d)", error);
2944 			goto cleanup;
2945 		}
2946 
2947 		error = ext4_journal_get_write_access(handle, inode->i_sb,
2948 						iloc.bh, EXT4_JTR_NONE);
2949 		if (error) {
2950 			EXT4_ERROR_INODE(inode, "write access (error %d)",
2951 					 error);
2952 			goto cleanup;
2953 		}
2954 
2955 		header = IHDR(inode, ext4_raw_inode(&iloc));
2956 		if (header->h_magic == cpu_to_le32(EXT4_XATTR_MAGIC))
2957 			ext4_xattr_inode_dec_ref_all(handle, inode, iloc.bh,
2958 						     IFIRST(header),
2959 						     false /* block_csum */,
2960 						     ea_inode_array,
2961 						     extra_credits,
2962 						     false /* skip_quota */);
2963 	}
2964 
2965 	if (EXT4_I(inode)->i_file_acl) {
2966 		bh = ext4_sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
2967 		if (IS_ERR(bh)) {
2968 			error = PTR_ERR(bh);
2969 			if (error == -EIO) {
2970 				EXT4_ERROR_INODE_ERR(inode, EIO,
2971 						     "block %llu read error",
2972 						     EXT4_I(inode)->i_file_acl);
2973 			}
2974 			bh = NULL;
2975 			goto cleanup;
2976 		}
2977 		error = ext4_xattr_check_block(inode, bh);
2978 		if (error)
2979 			goto cleanup;
2980 
2981 		if (ext4_has_feature_ea_inode(inode->i_sb)) {
2982 			for (entry = BFIRST(bh); !IS_LAST_ENTRY(entry);
2983 			     entry = EXT4_XATTR_NEXT(entry)) {
2984 				if (!entry->e_value_inum)
2985 					continue;
2986 				error = ext4_xattr_inode_iget(inode,
2987 					      le32_to_cpu(entry->e_value_inum),
2988 					      le32_to_cpu(entry->e_hash),
2989 					      &ea_inode);
2990 				if (error)
2991 					continue;
2992 				ext4_xattr_inode_free_quota(inode, ea_inode,
2993 					      le32_to_cpu(entry->e_value_size));
2994 				iput(ea_inode);
2995 			}
2996 
2997 		}
2998 
2999 		ext4_xattr_release_block(handle, inode, bh, ea_inode_array,
3000 					 extra_credits);
3001 		/*
3002 		 * Update i_file_acl value in the same transaction that releases
3003 		 * block.
3004 		 */
3005 		EXT4_I(inode)->i_file_acl = 0;
3006 		error = ext4_mark_inode_dirty(handle, inode);
3007 		if (error) {
3008 			EXT4_ERROR_INODE(inode, "mark inode dirty (error %d)",
3009 					 error);
3010 			goto cleanup;
3011 		}
3012 		ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_XATTR, handle);
3013 	}
3014 	error = 0;
3015 cleanup:
3016 	brelse(iloc.bh);
3017 	brelse(bh);
3018 	return error;
3019 }
3020 
3021 void ext4_xattr_inode_array_free(struct ext4_xattr_inode_array *ea_inode_array)
3022 {
3023 	int idx;
3024 
3025 	if (ea_inode_array == NULL)
3026 		return;
3027 
3028 	for (idx = 0; idx < ea_inode_array->count; ++idx)
3029 		iput(ea_inode_array->inodes[idx]);
3030 	kfree(ea_inode_array);
3031 }
3032 
3033 /*
3034  * ext4_xattr_block_cache_insert()
3035  *
3036  * Create a new entry in the extended attribute block cache, and insert
3037  * it unless such an entry is already in the cache.
3038  *
3039  * Returns 0, or a negative error number on failure.
3040  */
3041 static void
3042 ext4_xattr_block_cache_insert(struct mb_cache *ea_block_cache,
3043 			      struct buffer_head *bh)
3044 {
3045 	struct ext4_xattr_header *header = BHDR(bh);
3046 	__u32 hash = le32_to_cpu(header->h_hash);
3047 	int reusable = le32_to_cpu(header->h_refcount) <
3048 		       EXT4_XATTR_REFCOUNT_MAX;
3049 	int error;
3050 
3051 	if (!ea_block_cache)
3052 		return;
3053 	error = mb_cache_entry_create(ea_block_cache, GFP_NOFS, hash,
3054 				      bh->b_blocknr, reusable);
3055 	if (error) {
3056 		if (error == -EBUSY)
3057 			ea_bdebug(bh, "already in cache");
3058 	} else
3059 		ea_bdebug(bh, "inserting [%x]", (int)hash);
3060 }
3061 
3062 /*
3063  * ext4_xattr_cmp()
3064  *
3065  * Compare two extended attribute blocks for equality.
3066  *
3067  * Returns 0 if the blocks are equal, 1 if they differ, and
3068  * a negative error number on errors.
3069  */
3070 static int
3071 ext4_xattr_cmp(struct ext4_xattr_header *header1,
3072 	       struct ext4_xattr_header *header2)
3073 {
3074 	struct ext4_xattr_entry *entry1, *entry2;
3075 
3076 	entry1 = ENTRY(header1+1);
3077 	entry2 = ENTRY(header2+1);
3078 	while (!IS_LAST_ENTRY(entry1)) {
3079 		if (IS_LAST_ENTRY(entry2))
3080 			return 1;
3081 		if (entry1->e_hash != entry2->e_hash ||
3082 		    entry1->e_name_index != entry2->e_name_index ||
3083 		    entry1->e_name_len != entry2->e_name_len ||
3084 		    entry1->e_value_size != entry2->e_value_size ||
3085 		    entry1->e_value_inum != entry2->e_value_inum ||
3086 		    memcmp(entry1->e_name, entry2->e_name, entry1->e_name_len))
3087 			return 1;
3088 		if (!entry1->e_value_inum &&
3089 		    memcmp((char *)header1 + le16_to_cpu(entry1->e_value_offs),
3090 			   (char *)header2 + le16_to_cpu(entry2->e_value_offs),
3091 			   le32_to_cpu(entry1->e_value_size)))
3092 			return 1;
3093 
3094 		entry1 = EXT4_XATTR_NEXT(entry1);
3095 		entry2 = EXT4_XATTR_NEXT(entry2);
3096 	}
3097 	if (!IS_LAST_ENTRY(entry2))
3098 		return 1;
3099 	return 0;
3100 }
3101 
3102 /*
3103  * ext4_xattr_block_cache_find()
3104  *
3105  * Find an identical extended attribute block.
3106  *
3107  * Returns a pointer to the block found, or NULL if such a block was
3108  * not found or an error occurred.
3109  */
3110 static struct buffer_head *
3111 ext4_xattr_block_cache_find(struct inode *inode,
3112 			    struct ext4_xattr_header *header,
3113 			    struct mb_cache_entry **pce)
3114 {
3115 	__u32 hash = le32_to_cpu(header->h_hash);
3116 	struct mb_cache_entry *ce;
3117 	struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
3118 
3119 	if (!ea_block_cache)
3120 		return NULL;
3121 	if (!header->h_hash)
3122 		return NULL;  /* never share */
3123 	ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
3124 	ce = mb_cache_entry_find_first(ea_block_cache, hash);
3125 	while (ce) {
3126 		struct buffer_head *bh;
3127 
3128 		bh = ext4_sb_bread(inode->i_sb, ce->e_value, REQ_PRIO);
3129 		if (IS_ERR(bh)) {
3130 			if (PTR_ERR(bh) == -ENOMEM)
3131 				return NULL;
3132 			bh = NULL;
3133 			EXT4_ERROR_INODE(inode, "block %lu read error",
3134 					 (unsigned long)ce->e_value);
3135 		} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
3136 			*pce = ce;
3137 			return bh;
3138 		}
3139 		brelse(bh);
3140 		ce = mb_cache_entry_find_next(ea_block_cache, ce);
3141 	}
3142 	return NULL;
3143 }
3144 
3145 #define NAME_HASH_SHIFT 5
3146 #define VALUE_HASH_SHIFT 16
3147 
3148 /*
3149  * ext4_xattr_hash_entry()
3150  *
3151  * Compute the hash of an extended attribute.
3152  */
3153 static __le32 ext4_xattr_hash_entry(char *name, size_t name_len, __le32 *value,
3154 				    size_t value_count)
3155 {
3156 	__u32 hash = 0;
3157 
3158 	while (name_len--) {
3159 		hash = (hash << NAME_HASH_SHIFT) ^
3160 		       (hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
3161 		       (unsigned char)*name++;
3162 	}
3163 	while (value_count--) {
3164 		hash = (hash << VALUE_HASH_SHIFT) ^
3165 		       (hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
3166 		       le32_to_cpu(*value++);
3167 	}
3168 	return cpu_to_le32(hash);
3169 }
3170 
3171 /*
3172  * ext4_xattr_hash_entry_signed()
3173  *
3174  * Compute the hash of an extended attribute incorrectly.
3175  */
3176 static __le32 ext4_xattr_hash_entry_signed(char *name, size_t name_len, __le32 *value, size_t value_count)
3177 {
3178 	__u32 hash = 0;
3179 
3180 	while (name_len--) {
3181 		hash = (hash << NAME_HASH_SHIFT) ^
3182 		       (hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
3183 		       (signed char)*name++;
3184 	}
3185 	while (value_count--) {
3186 		hash = (hash << VALUE_HASH_SHIFT) ^
3187 		       (hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
3188 		       le32_to_cpu(*value++);
3189 	}
3190 	return cpu_to_le32(hash);
3191 }
3192 
3193 #undef NAME_HASH_SHIFT
3194 #undef VALUE_HASH_SHIFT
3195 
3196 #define BLOCK_HASH_SHIFT 16
3197 
3198 /*
3199  * ext4_xattr_rehash()
3200  *
3201  * Re-compute the extended attribute hash value after an entry has changed.
3202  */
3203 static void ext4_xattr_rehash(struct ext4_xattr_header *header)
3204 {
3205 	struct ext4_xattr_entry *here;
3206 	__u32 hash = 0;
3207 
3208 	here = ENTRY(header+1);
3209 	while (!IS_LAST_ENTRY(here)) {
3210 		if (!here->e_hash) {
3211 			/* Block is not shared if an entry's hash value == 0 */
3212 			hash = 0;
3213 			break;
3214 		}
3215 		hash = (hash << BLOCK_HASH_SHIFT) ^
3216 		       (hash >> (8*sizeof(hash) - BLOCK_HASH_SHIFT)) ^
3217 		       le32_to_cpu(here->e_hash);
3218 		here = EXT4_XATTR_NEXT(here);
3219 	}
3220 	header->h_hash = cpu_to_le32(hash);
3221 }
3222 
3223 #undef BLOCK_HASH_SHIFT
3224 
3225 #define	HASH_BUCKET_BITS	10
3226 
3227 struct mb_cache *
3228 ext4_xattr_create_cache(void)
3229 {
3230 	return mb_cache_create(HASH_BUCKET_BITS);
3231 }
3232 
3233 void ext4_xattr_destroy_cache(struct mb_cache *cache)
3234 {
3235 	if (cache)
3236 		mb_cache_destroy(cache);
3237 }
3238 
3239