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