xref: /openbmc/linux/fs/ext4/xattr.c (revision 8730046c)
1 /*
2  * linux/fs/ext4/xattr.c
3  *
4  * Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
5  *
6  * Fix by Harrison Xing <harrison@mountainviewdata.com>.
7  * Ext4 code with a lot of help from Eric Jarman <ejarman@acm.org>.
8  * Extended attributes for symlinks and special files added per
9  *  suggestion of Luka Renko <luka.renko@hermes.si>.
10  * xattr consolidation Copyright (c) 2004 James Morris <jmorris@redhat.com>,
11  *  Red Hat Inc.
12  * ea-in-inode support by Alex Tomas <alex@clusterfs.com> aka bzzz
13  *  and Andreas Gruenbacher <agruen@suse.de>.
14  */
15 
16 /*
17  * Extended attributes are stored directly in inodes (on file systems with
18  * inodes bigger than 128 bytes) and on additional disk blocks. The i_file_acl
19  * field contains the block number if an inode uses an additional block. All
20  * attributes must fit in the inode and one additional block. Blocks that
21  * contain the identical set of attributes may be shared among several inodes.
22  * Identical blocks are detected by keeping a cache of blocks that have
23  * recently been accessed.
24  *
25  * The attributes in inodes and on blocks have a different header; the entries
26  * are stored in the same format:
27  *
28  *   +------------------+
29  *   | header           |
30  *   | entry 1          | |
31  *   | entry 2          | | growing downwards
32  *   | entry 3          | v
33  *   | four null bytes  |
34  *   | . . .            |
35  *   | value 1          | ^
36  *   | value 3          | | growing upwards
37  *   | value 2          | |
38  *   +------------------+
39  *
40  * The header is followed by multiple entry descriptors. In disk blocks, the
41  * entry descriptors are kept sorted. In inodes, they are unsorted. The
42  * attribute values are aligned to the end of the block in no specific order.
43  *
44  * Locking strategy
45  * ----------------
46  * EXT4_I(inode)->i_file_acl is protected by EXT4_I(inode)->xattr_sem.
47  * EA blocks are only changed if they are exclusive to an inode, so
48  * holding xattr_sem also means that nothing but the EA block's reference
49  * count can change. Multiple writers to the same block are synchronized
50  * by the buffer lock.
51  */
52 
53 #include <linux/init.h>
54 #include <linux/fs.h>
55 #include <linux/slab.h>
56 #include <linux/mbcache.h>
57 #include <linux/quotaops.h>
58 #include "ext4_jbd2.h"
59 #include "ext4.h"
60 #include "xattr.h"
61 #include "acl.h"
62 
63 #ifdef EXT4_XATTR_DEBUG
64 # define ea_idebug(inode, fmt, ...)					\
65 	printk(KERN_DEBUG "inode %s:%lu: " fmt "\n",			\
66 	       inode->i_sb->s_id, inode->i_ino, ##__VA_ARGS__)
67 # define ea_bdebug(bh, fmt, ...)					\
68 	printk(KERN_DEBUG "block %pg:%lu: " fmt "\n",			\
69 	       bh->b_bdev, (unsigned long)bh->b_blocknr, ##__VA_ARGS__)
70 #else
71 # define ea_idebug(inode, fmt, ...)	no_printk(fmt, ##__VA_ARGS__)
72 # define ea_bdebug(bh, fmt, ...)	no_printk(fmt, ##__VA_ARGS__)
73 #endif
74 
75 static void ext4_xattr_cache_insert(struct mb_cache *, struct buffer_head *);
76 static struct buffer_head *ext4_xattr_cache_find(struct inode *,
77 						 struct ext4_xattr_header *,
78 						 struct mb_cache_entry **);
79 static void ext4_xattr_rehash(struct ext4_xattr_header *,
80 			      struct ext4_xattr_entry *);
81 static int ext4_xattr_list(struct dentry *dentry, char *buffer,
82 			   size_t buffer_size);
83 
84 static const struct xattr_handler *ext4_xattr_handler_map[] = {
85 	[EXT4_XATTR_INDEX_USER]		     = &ext4_xattr_user_handler,
86 #ifdef CONFIG_EXT4_FS_POSIX_ACL
87 	[EXT4_XATTR_INDEX_POSIX_ACL_ACCESS]  = &posix_acl_access_xattr_handler,
88 	[EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT] = &posix_acl_default_xattr_handler,
89 #endif
90 	[EXT4_XATTR_INDEX_TRUSTED]	     = &ext4_xattr_trusted_handler,
91 #ifdef CONFIG_EXT4_FS_SECURITY
92 	[EXT4_XATTR_INDEX_SECURITY]	     = &ext4_xattr_security_handler,
93 #endif
94 };
95 
96 const struct xattr_handler *ext4_xattr_handlers[] = {
97 	&ext4_xattr_user_handler,
98 	&ext4_xattr_trusted_handler,
99 #ifdef CONFIG_EXT4_FS_POSIX_ACL
100 	&posix_acl_access_xattr_handler,
101 	&posix_acl_default_xattr_handler,
102 #endif
103 #ifdef CONFIG_EXT4_FS_SECURITY
104 	&ext4_xattr_security_handler,
105 #endif
106 	NULL
107 };
108 
109 #define EXT4_GET_MB_CACHE(inode)	(((struct ext4_sb_info *) \
110 				inode->i_sb->s_fs_info)->s_mb_cache)
111 
112 static __le32 ext4_xattr_block_csum(struct inode *inode,
113 				    sector_t block_nr,
114 				    struct ext4_xattr_header *hdr)
115 {
116 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
117 	__u32 csum;
118 	__le64 dsk_block_nr = cpu_to_le64(block_nr);
119 	__u32 dummy_csum = 0;
120 	int offset = offsetof(struct ext4_xattr_header, h_checksum);
121 
122 	csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&dsk_block_nr,
123 			   sizeof(dsk_block_nr));
124 	csum = ext4_chksum(sbi, csum, (__u8 *)hdr, offset);
125 	csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
126 	offset += sizeof(dummy_csum);
127 	csum = ext4_chksum(sbi, csum, (__u8 *)hdr + offset,
128 			   EXT4_BLOCK_SIZE(inode->i_sb) - offset);
129 
130 	return cpu_to_le32(csum);
131 }
132 
133 static int ext4_xattr_block_csum_verify(struct inode *inode,
134 					sector_t block_nr,
135 					struct ext4_xattr_header *hdr)
136 {
137 	if (ext4_has_metadata_csum(inode->i_sb) &&
138 	    (hdr->h_checksum != ext4_xattr_block_csum(inode, block_nr, hdr)))
139 		return 0;
140 	return 1;
141 }
142 
143 static void ext4_xattr_block_csum_set(struct inode *inode,
144 				      sector_t block_nr,
145 				      struct ext4_xattr_header *hdr)
146 {
147 	if (!ext4_has_metadata_csum(inode->i_sb))
148 		return;
149 
150 	hdr->h_checksum = ext4_xattr_block_csum(inode, block_nr, hdr);
151 }
152 
153 static inline int ext4_handle_dirty_xattr_block(handle_t *handle,
154 						struct inode *inode,
155 						struct buffer_head *bh)
156 {
157 	ext4_xattr_block_csum_set(inode, bh->b_blocknr, BHDR(bh));
158 	return ext4_handle_dirty_metadata(handle, inode, bh);
159 }
160 
161 static inline const struct xattr_handler *
162 ext4_xattr_handler(int name_index)
163 {
164 	const struct xattr_handler *handler = NULL;
165 
166 	if (name_index > 0 && name_index < ARRAY_SIZE(ext4_xattr_handler_map))
167 		handler = ext4_xattr_handler_map[name_index];
168 	return handler;
169 }
170 
171 /*
172  * Inode operation listxattr()
173  *
174  * d_inode(dentry)->i_mutex: don't care
175  */
176 ssize_t
177 ext4_listxattr(struct dentry *dentry, char *buffer, size_t size)
178 {
179 	return ext4_xattr_list(dentry, buffer, size);
180 }
181 
182 static int
183 ext4_xattr_check_names(struct ext4_xattr_entry *entry, void *end,
184 		       void *value_start)
185 {
186 	struct ext4_xattr_entry *e = entry;
187 
188 	/* Find the end of the names list */
189 	while (!IS_LAST_ENTRY(e)) {
190 		struct ext4_xattr_entry *next = EXT4_XATTR_NEXT(e);
191 		if ((void *)next >= end)
192 			return -EFSCORRUPTED;
193 		e = next;
194 	}
195 
196 	/* Check the values */
197 	while (!IS_LAST_ENTRY(entry)) {
198 		if (entry->e_value_block != 0)
199 			return -EFSCORRUPTED;
200 		if (entry->e_value_size != 0) {
201 			u16 offs = le16_to_cpu(entry->e_value_offs);
202 			u32 size = le32_to_cpu(entry->e_value_size);
203 			void *value;
204 
205 			/*
206 			 * The value cannot overlap the names, and the value
207 			 * with padding cannot extend beyond 'end'.  Check both
208 			 * the padded and unpadded sizes, since the size may
209 			 * overflow to 0 when adding padding.
210 			 */
211 			if (offs > end - value_start)
212 				return -EFSCORRUPTED;
213 			value = value_start + offs;
214 			if (value < (void *)e + sizeof(u32) ||
215 			    size > end - value ||
216 			    EXT4_XATTR_SIZE(size) > end - value)
217 				return -EFSCORRUPTED;
218 		}
219 		entry = EXT4_XATTR_NEXT(entry);
220 	}
221 
222 	return 0;
223 }
224 
225 static inline int
226 ext4_xattr_check_block(struct inode *inode, struct buffer_head *bh)
227 {
228 	int error;
229 
230 	if (buffer_verified(bh))
231 		return 0;
232 
233 	if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
234 	    BHDR(bh)->h_blocks != cpu_to_le32(1))
235 		return -EFSCORRUPTED;
236 	if (!ext4_xattr_block_csum_verify(inode, bh->b_blocknr, BHDR(bh)))
237 		return -EFSBADCRC;
238 	error = ext4_xattr_check_names(BFIRST(bh), bh->b_data + bh->b_size,
239 				       bh->b_data);
240 	if (!error)
241 		set_buffer_verified(bh);
242 	return error;
243 }
244 
245 static int
246 __xattr_check_inode(struct inode *inode, struct ext4_xattr_ibody_header *header,
247 			 void *end, const char *function, unsigned int line)
248 {
249 	int error = -EFSCORRUPTED;
250 
251 	if (end - (void *)header < sizeof(*header) + sizeof(u32) ||
252 	    (header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)))
253 		goto errout;
254 	error = ext4_xattr_check_names(IFIRST(header), end, IFIRST(header));
255 errout:
256 	if (error)
257 		__ext4_error_inode(inode, function, line, 0,
258 				   "corrupted in-inode xattr");
259 	return error;
260 }
261 
262 #define xattr_check_inode(inode, header, end) \
263 	__xattr_check_inode((inode), (header), (end), __func__, __LINE__)
264 
265 static inline int
266 ext4_xattr_check_entry(struct ext4_xattr_entry *entry, size_t size)
267 {
268 	size_t value_size = le32_to_cpu(entry->e_value_size);
269 
270 	if (entry->e_value_block != 0 || value_size > size ||
271 	    le16_to_cpu(entry->e_value_offs) + value_size > size)
272 		return -EFSCORRUPTED;
273 	return 0;
274 }
275 
276 static int
277 ext4_xattr_find_entry(struct ext4_xattr_entry **pentry, int name_index,
278 		      const char *name, size_t size, int sorted)
279 {
280 	struct ext4_xattr_entry *entry;
281 	size_t name_len;
282 	int cmp = 1;
283 
284 	if (name == NULL)
285 		return -EINVAL;
286 	name_len = strlen(name);
287 	entry = *pentry;
288 	for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
289 		cmp = name_index - entry->e_name_index;
290 		if (!cmp)
291 			cmp = name_len - entry->e_name_len;
292 		if (!cmp)
293 			cmp = memcmp(name, entry->e_name, name_len);
294 		if (cmp <= 0 && (sorted || cmp == 0))
295 			break;
296 	}
297 	*pentry = entry;
298 	if (!cmp && ext4_xattr_check_entry(entry, size))
299 		return -EFSCORRUPTED;
300 	return cmp ? -ENODATA : 0;
301 }
302 
303 static int
304 ext4_xattr_block_get(struct inode *inode, int name_index, const char *name,
305 		     void *buffer, size_t buffer_size)
306 {
307 	struct buffer_head *bh = NULL;
308 	struct ext4_xattr_entry *entry;
309 	size_t size;
310 	int error;
311 	struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
312 
313 	ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
314 		  name_index, name, buffer, (long)buffer_size);
315 
316 	error = -ENODATA;
317 	if (!EXT4_I(inode)->i_file_acl)
318 		goto cleanup;
319 	ea_idebug(inode, "reading block %llu",
320 		  (unsigned long long)EXT4_I(inode)->i_file_acl);
321 	bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
322 	if (!bh)
323 		goto cleanup;
324 	ea_bdebug(bh, "b_count=%d, refcount=%d",
325 		atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
326 	if (ext4_xattr_check_block(inode, bh)) {
327 bad_block:
328 		EXT4_ERROR_INODE(inode, "bad block %llu",
329 				 EXT4_I(inode)->i_file_acl);
330 		error = -EFSCORRUPTED;
331 		goto cleanup;
332 	}
333 	ext4_xattr_cache_insert(ext4_mb_cache, bh);
334 	entry = BFIRST(bh);
335 	error = ext4_xattr_find_entry(&entry, name_index, name, bh->b_size, 1);
336 	if (error == -EFSCORRUPTED)
337 		goto bad_block;
338 	if (error)
339 		goto cleanup;
340 	size = le32_to_cpu(entry->e_value_size);
341 	if (buffer) {
342 		error = -ERANGE;
343 		if (size > buffer_size)
344 			goto cleanup;
345 		memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs),
346 		       size);
347 	}
348 	error = size;
349 
350 cleanup:
351 	brelse(bh);
352 	return error;
353 }
354 
355 int
356 ext4_xattr_ibody_get(struct inode *inode, int name_index, const char *name,
357 		     void *buffer, size_t buffer_size)
358 {
359 	struct ext4_xattr_ibody_header *header;
360 	struct ext4_xattr_entry *entry;
361 	struct ext4_inode *raw_inode;
362 	struct ext4_iloc iloc;
363 	size_t size;
364 	void *end;
365 	int error;
366 
367 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR))
368 		return -ENODATA;
369 	error = ext4_get_inode_loc(inode, &iloc);
370 	if (error)
371 		return error;
372 	raw_inode = ext4_raw_inode(&iloc);
373 	header = IHDR(inode, raw_inode);
374 	entry = IFIRST(header);
375 	end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
376 	error = xattr_check_inode(inode, header, end);
377 	if (error)
378 		goto cleanup;
379 	error = ext4_xattr_find_entry(&entry, name_index, name,
380 				      end - (void *)entry, 0);
381 	if (error)
382 		goto cleanup;
383 	size = le32_to_cpu(entry->e_value_size);
384 	if (buffer) {
385 		error = -ERANGE;
386 		if (size > buffer_size)
387 			goto cleanup;
388 		memcpy(buffer, (void *)IFIRST(header) +
389 		       le16_to_cpu(entry->e_value_offs), size);
390 	}
391 	error = size;
392 
393 cleanup:
394 	brelse(iloc.bh);
395 	return error;
396 }
397 
398 /*
399  * ext4_xattr_get()
400  *
401  * Copy an extended attribute into the buffer
402  * provided, or compute the buffer size required.
403  * Buffer is NULL to compute the size of the buffer required.
404  *
405  * Returns a negative error number on failure, or the number of bytes
406  * used / required on success.
407  */
408 int
409 ext4_xattr_get(struct inode *inode, int name_index, const char *name,
410 	       void *buffer, size_t buffer_size)
411 {
412 	int error;
413 
414 	if (strlen(name) > 255)
415 		return -ERANGE;
416 
417 	down_read(&EXT4_I(inode)->xattr_sem);
418 	error = ext4_xattr_ibody_get(inode, name_index, name, buffer,
419 				     buffer_size);
420 	if (error == -ENODATA)
421 		error = ext4_xattr_block_get(inode, name_index, name, buffer,
422 					     buffer_size);
423 	up_read(&EXT4_I(inode)->xattr_sem);
424 	return error;
425 }
426 
427 static int
428 ext4_xattr_list_entries(struct dentry *dentry, struct ext4_xattr_entry *entry,
429 			char *buffer, size_t buffer_size)
430 {
431 	size_t rest = buffer_size;
432 
433 	for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
434 		const struct xattr_handler *handler =
435 			ext4_xattr_handler(entry->e_name_index);
436 
437 		if (handler && (!handler->list || handler->list(dentry))) {
438 			const char *prefix = handler->prefix ?: handler->name;
439 			size_t prefix_len = strlen(prefix);
440 			size_t size = prefix_len + entry->e_name_len + 1;
441 
442 			if (buffer) {
443 				if (size > rest)
444 					return -ERANGE;
445 				memcpy(buffer, prefix, prefix_len);
446 				buffer += prefix_len;
447 				memcpy(buffer, entry->e_name, entry->e_name_len);
448 				buffer += entry->e_name_len;
449 				*buffer++ = 0;
450 			}
451 			rest -= size;
452 		}
453 	}
454 	return buffer_size - rest;  /* total size */
455 }
456 
457 static int
458 ext4_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size)
459 {
460 	struct inode *inode = d_inode(dentry);
461 	struct buffer_head *bh = NULL;
462 	int error;
463 	struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
464 
465 	ea_idebug(inode, "buffer=%p, buffer_size=%ld",
466 		  buffer, (long)buffer_size);
467 
468 	error = 0;
469 	if (!EXT4_I(inode)->i_file_acl)
470 		goto cleanup;
471 	ea_idebug(inode, "reading block %llu",
472 		  (unsigned long long)EXT4_I(inode)->i_file_acl);
473 	bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
474 	error = -EIO;
475 	if (!bh)
476 		goto cleanup;
477 	ea_bdebug(bh, "b_count=%d, refcount=%d",
478 		atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
479 	if (ext4_xattr_check_block(inode, bh)) {
480 		EXT4_ERROR_INODE(inode, "bad block %llu",
481 				 EXT4_I(inode)->i_file_acl);
482 		error = -EFSCORRUPTED;
483 		goto cleanup;
484 	}
485 	ext4_xattr_cache_insert(ext4_mb_cache, bh);
486 	error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size);
487 
488 cleanup:
489 	brelse(bh);
490 
491 	return error;
492 }
493 
494 static int
495 ext4_xattr_ibody_list(struct dentry *dentry, char *buffer, size_t buffer_size)
496 {
497 	struct inode *inode = d_inode(dentry);
498 	struct ext4_xattr_ibody_header *header;
499 	struct ext4_inode *raw_inode;
500 	struct ext4_iloc iloc;
501 	void *end;
502 	int error;
503 
504 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR))
505 		return 0;
506 	error = ext4_get_inode_loc(inode, &iloc);
507 	if (error)
508 		return error;
509 	raw_inode = ext4_raw_inode(&iloc);
510 	header = IHDR(inode, raw_inode);
511 	end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
512 	error = xattr_check_inode(inode, header, end);
513 	if (error)
514 		goto cleanup;
515 	error = ext4_xattr_list_entries(dentry, IFIRST(header),
516 					buffer, buffer_size);
517 
518 cleanup:
519 	brelse(iloc.bh);
520 	return error;
521 }
522 
523 /*
524  * ext4_xattr_list()
525  *
526  * Copy a list of attribute names into the buffer
527  * provided, or compute the buffer size required.
528  * Buffer is NULL to compute the size of the buffer required.
529  *
530  * Returns a negative error number on failure, or the number of bytes
531  * used / required on success.
532  */
533 static int
534 ext4_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size)
535 {
536 	int ret, ret2;
537 
538 	down_read(&EXT4_I(d_inode(dentry))->xattr_sem);
539 	ret = ret2 = ext4_xattr_ibody_list(dentry, buffer, buffer_size);
540 	if (ret < 0)
541 		goto errout;
542 	if (buffer) {
543 		buffer += ret;
544 		buffer_size -= ret;
545 	}
546 	ret = ext4_xattr_block_list(dentry, buffer, buffer_size);
547 	if (ret < 0)
548 		goto errout;
549 	ret += ret2;
550 errout:
551 	up_read(&EXT4_I(d_inode(dentry))->xattr_sem);
552 	return ret;
553 }
554 
555 /*
556  * If the EXT4_FEATURE_COMPAT_EXT_ATTR feature of this file system is
557  * not set, set it.
558  */
559 static void ext4_xattr_update_super_block(handle_t *handle,
560 					  struct super_block *sb)
561 {
562 	if (ext4_has_feature_xattr(sb))
563 		return;
564 
565 	BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access");
566 	if (ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh) == 0) {
567 		ext4_set_feature_xattr(sb);
568 		ext4_handle_dirty_super(handle, sb);
569 	}
570 }
571 
572 /*
573  * Release the xattr block BH: If the reference count is > 1, decrement it;
574  * otherwise free the block.
575  */
576 static void
577 ext4_xattr_release_block(handle_t *handle, struct inode *inode,
578 			 struct buffer_head *bh)
579 {
580 	struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
581 	u32 hash, ref;
582 	int error = 0;
583 
584 	BUFFER_TRACE(bh, "get_write_access");
585 	error = ext4_journal_get_write_access(handle, bh);
586 	if (error)
587 		goto out;
588 
589 	lock_buffer(bh);
590 	hash = le32_to_cpu(BHDR(bh)->h_hash);
591 	ref = le32_to_cpu(BHDR(bh)->h_refcount);
592 	if (ref == 1) {
593 		ea_bdebug(bh, "refcount now=0; freeing");
594 		/*
595 		 * This must happen under buffer lock for
596 		 * ext4_xattr_block_set() to reliably detect freed block
597 		 */
598 		mb_cache_entry_delete_block(ext4_mb_cache, hash, bh->b_blocknr);
599 		get_bh(bh);
600 		unlock_buffer(bh);
601 		ext4_free_blocks(handle, inode, bh, 0, 1,
602 				 EXT4_FREE_BLOCKS_METADATA |
603 				 EXT4_FREE_BLOCKS_FORGET);
604 	} else {
605 		ref--;
606 		BHDR(bh)->h_refcount = cpu_to_le32(ref);
607 		if (ref == EXT4_XATTR_REFCOUNT_MAX - 1) {
608 			struct mb_cache_entry *ce;
609 
610 			ce = mb_cache_entry_get(ext4_mb_cache, hash,
611 						bh->b_blocknr);
612 			if (ce) {
613 				ce->e_reusable = 1;
614 				mb_cache_entry_put(ext4_mb_cache, ce);
615 			}
616 		}
617 
618 		/*
619 		 * Beware of this ugliness: Releasing of xattr block references
620 		 * from different inodes can race and so we have to protect
621 		 * from a race where someone else frees the block (and releases
622 		 * its journal_head) before we are done dirtying the buffer. In
623 		 * nojournal mode this race is harmless and we actually cannot
624 		 * call ext4_handle_dirty_xattr_block() with locked buffer as
625 		 * that function can call sync_dirty_buffer() so for that case
626 		 * we handle the dirtying after unlocking the buffer.
627 		 */
628 		if (ext4_handle_valid(handle))
629 			error = ext4_handle_dirty_xattr_block(handle, inode,
630 							      bh);
631 		unlock_buffer(bh);
632 		if (!ext4_handle_valid(handle))
633 			error = ext4_handle_dirty_xattr_block(handle, inode,
634 							      bh);
635 		if (IS_SYNC(inode))
636 			ext4_handle_sync(handle);
637 		dquot_free_block(inode, EXT4_C2B(EXT4_SB(inode->i_sb), 1));
638 		ea_bdebug(bh, "refcount now=%d; releasing",
639 			  le32_to_cpu(BHDR(bh)->h_refcount));
640 	}
641 out:
642 	ext4_std_error(inode->i_sb, error);
643 	return;
644 }
645 
646 /*
647  * Find the available free space for EAs. This also returns the total number of
648  * bytes used by EA entries.
649  */
650 static size_t ext4_xattr_free_space(struct ext4_xattr_entry *last,
651 				    size_t *min_offs, void *base, int *total)
652 {
653 	for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
654 		if (last->e_value_size) {
655 			size_t offs = le16_to_cpu(last->e_value_offs);
656 			if (offs < *min_offs)
657 				*min_offs = offs;
658 		}
659 		if (total)
660 			*total += EXT4_XATTR_LEN(last->e_name_len);
661 	}
662 	return (*min_offs - ((void *)last - base) - sizeof(__u32));
663 }
664 
665 static int
666 ext4_xattr_set_entry(struct ext4_xattr_info *i, struct ext4_xattr_search *s)
667 {
668 	struct ext4_xattr_entry *last;
669 	size_t free, min_offs = s->end - s->base, name_len = strlen(i->name);
670 
671 	/* Compute min_offs and last. */
672 	last = s->first;
673 	for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
674 		if (last->e_value_size) {
675 			size_t offs = le16_to_cpu(last->e_value_offs);
676 			if (offs < min_offs)
677 				min_offs = offs;
678 		}
679 	}
680 	free = min_offs - ((void *)last - s->base) - sizeof(__u32);
681 	if (!s->not_found) {
682 		if (s->here->e_value_size) {
683 			size_t size = le32_to_cpu(s->here->e_value_size);
684 			free += EXT4_XATTR_SIZE(size);
685 		}
686 		free += EXT4_XATTR_LEN(name_len);
687 	}
688 	if (i->value) {
689 		if (free < EXT4_XATTR_LEN(name_len) +
690 			   EXT4_XATTR_SIZE(i->value_len))
691 			return -ENOSPC;
692 	}
693 
694 	if (i->value && s->not_found) {
695 		/* Insert the new name. */
696 		size_t size = EXT4_XATTR_LEN(name_len);
697 		size_t rest = (void *)last - (void *)s->here + sizeof(__u32);
698 		memmove((void *)s->here + size, s->here, rest);
699 		memset(s->here, 0, size);
700 		s->here->e_name_index = i->name_index;
701 		s->here->e_name_len = name_len;
702 		memcpy(s->here->e_name, i->name, name_len);
703 	} else {
704 		if (s->here->e_value_size) {
705 			void *first_val = s->base + min_offs;
706 			size_t offs = le16_to_cpu(s->here->e_value_offs);
707 			void *val = s->base + offs;
708 			size_t size = EXT4_XATTR_SIZE(
709 				le32_to_cpu(s->here->e_value_size));
710 
711 			if (i->value && size == EXT4_XATTR_SIZE(i->value_len)) {
712 				/* The old and the new value have the same
713 				   size. Just replace. */
714 				s->here->e_value_size =
715 					cpu_to_le32(i->value_len);
716 				if (i->value == EXT4_ZERO_XATTR_VALUE) {
717 					memset(val, 0, size);
718 				} else {
719 					/* Clear pad bytes first. */
720 					memset(val + size - EXT4_XATTR_PAD, 0,
721 					       EXT4_XATTR_PAD);
722 					memcpy(val, i->value, i->value_len);
723 				}
724 				return 0;
725 			}
726 
727 			/* Remove the old value. */
728 			memmove(first_val + size, first_val, val - first_val);
729 			memset(first_val, 0, size);
730 			s->here->e_value_size = 0;
731 			s->here->e_value_offs = 0;
732 			min_offs += size;
733 
734 			/* Adjust all value offsets. */
735 			last = s->first;
736 			while (!IS_LAST_ENTRY(last)) {
737 				size_t o = le16_to_cpu(last->e_value_offs);
738 				if (last->e_value_size && o < offs)
739 					last->e_value_offs =
740 						cpu_to_le16(o + size);
741 				last = EXT4_XATTR_NEXT(last);
742 			}
743 		}
744 		if (!i->value) {
745 			/* Remove the old name. */
746 			size_t size = EXT4_XATTR_LEN(name_len);
747 			last = ENTRY((void *)last - size);
748 			memmove(s->here, (void *)s->here + size,
749 				(void *)last - (void *)s->here + sizeof(__u32));
750 			memset(last, 0, size);
751 		}
752 	}
753 
754 	if (i->value) {
755 		/* Insert the new value. */
756 		s->here->e_value_size = cpu_to_le32(i->value_len);
757 		if (i->value_len) {
758 			size_t size = EXT4_XATTR_SIZE(i->value_len);
759 			void *val = s->base + min_offs - size;
760 			s->here->e_value_offs = cpu_to_le16(min_offs - size);
761 			if (i->value == EXT4_ZERO_XATTR_VALUE) {
762 				memset(val, 0, size);
763 			} else {
764 				/* Clear the pad bytes first. */
765 				memset(val + size - EXT4_XATTR_PAD, 0,
766 				       EXT4_XATTR_PAD);
767 				memcpy(val, i->value, i->value_len);
768 			}
769 		}
770 	}
771 	return 0;
772 }
773 
774 struct ext4_xattr_block_find {
775 	struct ext4_xattr_search s;
776 	struct buffer_head *bh;
777 };
778 
779 static int
780 ext4_xattr_block_find(struct inode *inode, struct ext4_xattr_info *i,
781 		      struct ext4_xattr_block_find *bs)
782 {
783 	struct super_block *sb = inode->i_sb;
784 	int error;
785 
786 	ea_idebug(inode, "name=%d.%s, value=%p, value_len=%ld",
787 		  i->name_index, i->name, i->value, (long)i->value_len);
788 
789 	if (EXT4_I(inode)->i_file_acl) {
790 		/* The inode already has an extended attribute block. */
791 		bs->bh = sb_bread(sb, EXT4_I(inode)->i_file_acl);
792 		error = -EIO;
793 		if (!bs->bh)
794 			goto cleanup;
795 		ea_bdebug(bs->bh, "b_count=%d, refcount=%d",
796 			atomic_read(&(bs->bh->b_count)),
797 			le32_to_cpu(BHDR(bs->bh)->h_refcount));
798 		if (ext4_xattr_check_block(inode, bs->bh)) {
799 			EXT4_ERROR_INODE(inode, "bad block %llu",
800 					 EXT4_I(inode)->i_file_acl);
801 			error = -EFSCORRUPTED;
802 			goto cleanup;
803 		}
804 		/* Find the named attribute. */
805 		bs->s.base = BHDR(bs->bh);
806 		bs->s.first = BFIRST(bs->bh);
807 		bs->s.end = bs->bh->b_data + bs->bh->b_size;
808 		bs->s.here = bs->s.first;
809 		error = ext4_xattr_find_entry(&bs->s.here, i->name_index,
810 					      i->name, bs->bh->b_size, 1);
811 		if (error && error != -ENODATA)
812 			goto cleanup;
813 		bs->s.not_found = error;
814 	}
815 	error = 0;
816 
817 cleanup:
818 	return error;
819 }
820 
821 static int
822 ext4_xattr_block_set(handle_t *handle, struct inode *inode,
823 		     struct ext4_xattr_info *i,
824 		     struct ext4_xattr_block_find *bs)
825 {
826 	struct super_block *sb = inode->i_sb;
827 	struct buffer_head *new_bh = NULL;
828 	struct ext4_xattr_search *s = &bs->s;
829 	struct mb_cache_entry *ce = NULL;
830 	int error = 0;
831 	struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
832 
833 #define header(x) ((struct ext4_xattr_header *)(x))
834 
835 	if (i->value && i->value_len > sb->s_blocksize)
836 		return -ENOSPC;
837 	if (s->base) {
838 		BUFFER_TRACE(bs->bh, "get_write_access");
839 		error = ext4_journal_get_write_access(handle, bs->bh);
840 		if (error)
841 			goto cleanup;
842 		lock_buffer(bs->bh);
843 
844 		if (header(s->base)->h_refcount == cpu_to_le32(1)) {
845 			__u32 hash = le32_to_cpu(BHDR(bs->bh)->h_hash);
846 
847 			/*
848 			 * This must happen under buffer lock for
849 			 * ext4_xattr_block_set() to reliably detect modified
850 			 * block
851 			 */
852 			mb_cache_entry_delete_block(ext4_mb_cache, hash,
853 						    bs->bh->b_blocknr);
854 			ea_bdebug(bs->bh, "modifying in-place");
855 			error = ext4_xattr_set_entry(i, s);
856 			if (!error) {
857 				if (!IS_LAST_ENTRY(s->first))
858 					ext4_xattr_rehash(header(s->base),
859 							  s->here);
860 				ext4_xattr_cache_insert(ext4_mb_cache,
861 					bs->bh);
862 			}
863 			unlock_buffer(bs->bh);
864 			if (error == -EFSCORRUPTED)
865 				goto bad_block;
866 			if (!error)
867 				error = ext4_handle_dirty_xattr_block(handle,
868 								      inode,
869 								      bs->bh);
870 			if (error)
871 				goto cleanup;
872 			goto inserted;
873 		} else {
874 			int offset = (char *)s->here - bs->bh->b_data;
875 
876 			unlock_buffer(bs->bh);
877 			ea_bdebug(bs->bh, "cloning");
878 			s->base = kmalloc(bs->bh->b_size, GFP_NOFS);
879 			error = -ENOMEM;
880 			if (s->base == NULL)
881 				goto cleanup;
882 			memcpy(s->base, BHDR(bs->bh), bs->bh->b_size);
883 			s->first = ENTRY(header(s->base)+1);
884 			header(s->base)->h_refcount = cpu_to_le32(1);
885 			s->here = ENTRY(s->base + offset);
886 			s->end = s->base + bs->bh->b_size;
887 		}
888 	} else {
889 		/* Allocate a buffer where we construct the new block. */
890 		s->base = kzalloc(sb->s_blocksize, GFP_NOFS);
891 		/* assert(header == s->base) */
892 		error = -ENOMEM;
893 		if (s->base == NULL)
894 			goto cleanup;
895 		header(s->base)->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
896 		header(s->base)->h_blocks = cpu_to_le32(1);
897 		header(s->base)->h_refcount = cpu_to_le32(1);
898 		s->first = ENTRY(header(s->base)+1);
899 		s->here = ENTRY(header(s->base)+1);
900 		s->end = s->base + sb->s_blocksize;
901 	}
902 
903 	error = ext4_xattr_set_entry(i, s);
904 	if (error == -EFSCORRUPTED)
905 		goto bad_block;
906 	if (error)
907 		goto cleanup;
908 	if (!IS_LAST_ENTRY(s->first))
909 		ext4_xattr_rehash(header(s->base), s->here);
910 
911 inserted:
912 	if (!IS_LAST_ENTRY(s->first)) {
913 		new_bh = ext4_xattr_cache_find(inode, header(s->base), &ce);
914 		if (new_bh) {
915 			/* We found an identical block in the cache. */
916 			if (new_bh == bs->bh)
917 				ea_bdebug(new_bh, "keeping");
918 			else {
919 				u32 ref;
920 
921 				/* The old block is released after updating
922 				   the inode. */
923 				error = dquot_alloc_block(inode,
924 						EXT4_C2B(EXT4_SB(sb), 1));
925 				if (error)
926 					goto cleanup;
927 				BUFFER_TRACE(new_bh, "get_write_access");
928 				error = ext4_journal_get_write_access(handle,
929 								      new_bh);
930 				if (error)
931 					goto cleanup_dquot;
932 				lock_buffer(new_bh);
933 				/*
934 				 * We have to be careful about races with
935 				 * freeing, rehashing or adding references to
936 				 * xattr block. Once we hold buffer lock xattr
937 				 * block's state is stable so we can check
938 				 * whether the block got freed / rehashed or
939 				 * not.  Since we unhash mbcache entry under
940 				 * buffer lock when freeing / rehashing xattr
941 				 * block, checking whether entry is still
942 				 * hashed is reliable. Same rules hold for
943 				 * e_reusable handling.
944 				 */
945 				if (hlist_bl_unhashed(&ce->e_hash_list) ||
946 				    !ce->e_reusable) {
947 					/*
948 					 * Undo everything and check mbcache
949 					 * again.
950 					 */
951 					unlock_buffer(new_bh);
952 					dquot_free_block(inode,
953 							 EXT4_C2B(EXT4_SB(sb),
954 								  1));
955 					brelse(new_bh);
956 					mb_cache_entry_put(ext4_mb_cache, ce);
957 					ce = NULL;
958 					new_bh = NULL;
959 					goto inserted;
960 				}
961 				ref = le32_to_cpu(BHDR(new_bh)->h_refcount) + 1;
962 				BHDR(new_bh)->h_refcount = cpu_to_le32(ref);
963 				if (ref >= EXT4_XATTR_REFCOUNT_MAX)
964 					ce->e_reusable = 0;
965 				ea_bdebug(new_bh, "reusing; refcount now=%d",
966 					  ref);
967 				unlock_buffer(new_bh);
968 				error = ext4_handle_dirty_xattr_block(handle,
969 								      inode,
970 								      new_bh);
971 				if (error)
972 					goto cleanup_dquot;
973 			}
974 			mb_cache_entry_touch(ext4_mb_cache, ce);
975 			mb_cache_entry_put(ext4_mb_cache, ce);
976 			ce = NULL;
977 		} else if (bs->bh && s->base == bs->bh->b_data) {
978 			/* We were modifying this block in-place. */
979 			ea_bdebug(bs->bh, "keeping this block");
980 			new_bh = bs->bh;
981 			get_bh(new_bh);
982 		} else {
983 			/* We need to allocate a new block */
984 			ext4_fsblk_t goal, block;
985 
986 			goal = ext4_group_first_block_no(sb,
987 						EXT4_I(inode)->i_block_group);
988 
989 			/* non-extent files can't have physical blocks past 2^32 */
990 			if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
991 				goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
992 
993 			block = ext4_new_meta_blocks(handle, inode, goal, 0,
994 						     NULL, &error);
995 			if (error)
996 				goto cleanup;
997 
998 			if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
999 				BUG_ON(block > EXT4_MAX_BLOCK_FILE_PHYS);
1000 
1001 			ea_idebug(inode, "creating block %llu",
1002 				  (unsigned long long)block);
1003 
1004 			new_bh = sb_getblk(sb, block);
1005 			if (unlikely(!new_bh)) {
1006 				error = -ENOMEM;
1007 getblk_failed:
1008 				ext4_free_blocks(handle, inode, NULL, block, 1,
1009 						 EXT4_FREE_BLOCKS_METADATA);
1010 				goto cleanup;
1011 			}
1012 			lock_buffer(new_bh);
1013 			error = ext4_journal_get_create_access(handle, new_bh);
1014 			if (error) {
1015 				unlock_buffer(new_bh);
1016 				error = -EIO;
1017 				goto getblk_failed;
1018 			}
1019 			memcpy(new_bh->b_data, s->base, new_bh->b_size);
1020 			set_buffer_uptodate(new_bh);
1021 			unlock_buffer(new_bh);
1022 			ext4_xattr_cache_insert(ext4_mb_cache, new_bh);
1023 			error = ext4_handle_dirty_xattr_block(handle,
1024 							      inode, new_bh);
1025 			if (error)
1026 				goto cleanup;
1027 		}
1028 	}
1029 
1030 	/* Update the inode. */
1031 	EXT4_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
1032 
1033 	/* Drop the previous xattr block. */
1034 	if (bs->bh && bs->bh != new_bh)
1035 		ext4_xattr_release_block(handle, inode, bs->bh);
1036 	error = 0;
1037 
1038 cleanup:
1039 	if (ce)
1040 		mb_cache_entry_put(ext4_mb_cache, ce);
1041 	brelse(new_bh);
1042 	if (!(bs->bh && s->base == bs->bh->b_data))
1043 		kfree(s->base);
1044 
1045 	return error;
1046 
1047 cleanup_dquot:
1048 	dquot_free_block(inode, EXT4_C2B(EXT4_SB(sb), 1));
1049 	goto cleanup;
1050 
1051 bad_block:
1052 	EXT4_ERROR_INODE(inode, "bad block %llu",
1053 			 EXT4_I(inode)->i_file_acl);
1054 	goto cleanup;
1055 
1056 #undef header
1057 }
1058 
1059 int ext4_xattr_ibody_find(struct inode *inode, struct ext4_xattr_info *i,
1060 			  struct ext4_xattr_ibody_find *is)
1061 {
1062 	struct ext4_xattr_ibody_header *header;
1063 	struct ext4_inode *raw_inode;
1064 	int error;
1065 
1066 	if (EXT4_I(inode)->i_extra_isize == 0)
1067 		return 0;
1068 	raw_inode = ext4_raw_inode(&is->iloc);
1069 	header = IHDR(inode, raw_inode);
1070 	is->s.base = is->s.first = IFIRST(header);
1071 	is->s.here = is->s.first;
1072 	is->s.end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
1073 	if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
1074 		error = xattr_check_inode(inode, header, is->s.end);
1075 		if (error)
1076 			return error;
1077 		/* Find the named attribute. */
1078 		error = ext4_xattr_find_entry(&is->s.here, i->name_index,
1079 					      i->name, is->s.end -
1080 					      (void *)is->s.base, 0);
1081 		if (error && error != -ENODATA)
1082 			return error;
1083 		is->s.not_found = error;
1084 	}
1085 	return 0;
1086 }
1087 
1088 int ext4_xattr_ibody_inline_set(handle_t *handle, struct inode *inode,
1089 				struct ext4_xattr_info *i,
1090 				struct ext4_xattr_ibody_find *is)
1091 {
1092 	struct ext4_xattr_ibody_header *header;
1093 	struct ext4_xattr_search *s = &is->s;
1094 	int error;
1095 
1096 	if (EXT4_I(inode)->i_extra_isize == 0)
1097 		return -ENOSPC;
1098 	error = ext4_xattr_set_entry(i, s);
1099 	if (error) {
1100 		if (error == -ENOSPC &&
1101 		    ext4_has_inline_data(inode)) {
1102 			error = ext4_try_to_evict_inline_data(handle, inode,
1103 					EXT4_XATTR_LEN(strlen(i->name) +
1104 					EXT4_XATTR_SIZE(i->value_len)));
1105 			if (error)
1106 				return error;
1107 			error = ext4_xattr_ibody_find(inode, i, is);
1108 			if (error)
1109 				return error;
1110 			error = ext4_xattr_set_entry(i, s);
1111 		}
1112 		if (error)
1113 			return error;
1114 	}
1115 	header = IHDR(inode, ext4_raw_inode(&is->iloc));
1116 	if (!IS_LAST_ENTRY(s->first)) {
1117 		header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
1118 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
1119 	} else {
1120 		header->h_magic = cpu_to_le32(0);
1121 		ext4_clear_inode_state(inode, EXT4_STATE_XATTR);
1122 	}
1123 	return 0;
1124 }
1125 
1126 static int ext4_xattr_ibody_set(struct inode *inode,
1127 				struct ext4_xattr_info *i,
1128 				struct ext4_xattr_ibody_find *is)
1129 {
1130 	struct ext4_xattr_ibody_header *header;
1131 	struct ext4_xattr_search *s = &is->s;
1132 	int error;
1133 
1134 	if (EXT4_I(inode)->i_extra_isize == 0)
1135 		return -ENOSPC;
1136 	error = ext4_xattr_set_entry(i, s);
1137 	if (error)
1138 		return error;
1139 	header = IHDR(inode, ext4_raw_inode(&is->iloc));
1140 	if (!IS_LAST_ENTRY(s->first)) {
1141 		header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
1142 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
1143 	} else {
1144 		header->h_magic = cpu_to_le32(0);
1145 		ext4_clear_inode_state(inode, EXT4_STATE_XATTR);
1146 	}
1147 	return 0;
1148 }
1149 
1150 static int ext4_xattr_value_same(struct ext4_xattr_search *s,
1151 				 struct ext4_xattr_info *i)
1152 {
1153 	void *value;
1154 
1155 	if (le32_to_cpu(s->here->e_value_size) != i->value_len)
1156 		return 0;
1157 	value = ((void *)s->base) + le16_to_cpu(s->here->e_value_offs);
1158 	return !memcmp(value, i->value, i->value_len);
1159 }
1160 
1161 /*
1162  * ext4_xattr_set_handle()
1163  *
1164  * Create, replace or remove an extended attribute for this inode.  Value
1165  * is NULL to remove an existing extended attribute, and non-NULL to
1166  * either replace an existing extended attribute, or create a new extended
1167  * attribute. The flags XATTR_REPLACE and XATTR_CREATE
1168  * specify that an extended attribute must exist and must not exist
1169  * previous to the call, respectively.
1170  *
1171  * Returns 0, or a negative error number on failure.
1172  */
1173 int
1174 ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
1175 		      const char *name, const void *value, size_t value_len,
1176 		      int flags)
1177 {
1178 	struct ext4_xattr_info i = {
1179 		.name_index = name_index,
1180 		.name = name,
1181 		.value = value,
1182 		.value_len = value_len,
1183 
1184 	};
1185 	struct ext4_xattr_ibody_find is = {
1186 		.s = { .not_found = -ENODATA, },
1187 	};
1188 	struct ext4_xattr_block_find bs = {
1189 		.s = { .not_found = -ENODATA, },
1190 	};
1191 	unsigned long no_expand;
1192 	int error;
1193 
1194 	if (!name)
1195 		return -EINVAL;
1196 	if (strlen(name) > 255)
1197 		return -ERANGE;
1198 	down_write(&EXT4_I(inode)->xattr_sem);
1199 	no_expand = ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND);
1200 	ext4_set_inode_state(inode, EXT4_STATE_NO_EXPAND);
1201 
1202 	error = ext4_reserve_inode_write(handle, inode, &is.iloc);
1203 	if (error)
1204 		goto cleanup;
1205 
1206 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW)) {
1207 		struct ext4_inode *raw_inode = ext4_raw_inode(&is.iloc);
1208 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
1209 		ext4_clear_inode_state(inode, EXT4_STATE_NEW);
1210 	}
1211 
1212 	error = ext4_xattr_ibody_find(inode, &i, &is);
1213 	if (error)
1214 		goto cleanup;
1215 	if (is.s.not_found)
1216 		error = ext4_xattr_block_find(inode, &i, &bs);
1217 	if (error)
1218 		goto cleanup;
1219 	if (is.s.not_found && bs.s.not_found) {
1220 		error = -ENODATA;
1221 		if (flags & XATTR_REPLACE)
1222 			goto cleanup;
1223 		error = 0;
1224 		if (!value)
1225 			goto cleanup;
1226 	} else {
1227 		error = -EEXIST;
1228 		if (flags & XATTR_CREATE)
1229 			goto cleanup;
1230 	}
1231 	if (!value) {
1232 		if (!is.s.not_found)
1233 			error = ext4_xattr_ibody_set(inode, &i, &is);
1234 		else if (!bs.s.not_found)
1235 			error = ext4_xattr_block_set(handle, inode, &i, &bs);
1236 	} else {
1237 		error = 0;
1238 		/* Xattr value did not change? Save us some work and bail out */
1239 		if (!is.s.not_found && ext4_xattr_value_same(&is.s, &i))
1240 			goto cleanup;
1241 		if (!bs.s.not_found && ext4_xattr_value_same(&bs.s, &i))
1242 			goto cleanup;
1243 
1244 		error = ext4_xattr_ibody_set(inode, &i, &is);
1245 		if (!error && !bs.s.not_found) {
1246 			i.value = NULL;
1247 			error = ext4_xattr_block_set(handle, inode, &i, &bs);
1248 		} else if (error == -ENOSPC) {
1249 			if (EXT4_I(inode)->i_file_acl && !bs.s.base) {
1250 				error = ext4_xattr_block_find(inode, &i, &bs);
1251 				if (error)
1252 					goto cleanup;
1253 			}
1254 			error = ext4_xattr_block_set(handle, inode, &i, &bs);
1255 			if (error)
1256 				goto cleanup;
1257 			if (!is.s.not_found) {
1258 				i.value = NULL;
1259 				error = ext4_xattr_ibody_set(inode, &i, &is);
1260 			}
1261 		}
1262 	}
1263 	if (!error) {
1264 		ext4_xattr_update_super_block(handle, inode->i_sb);
1265 		inode->i_ctime = current_time(inode);
1266 		if (!value)
1267 			ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND);
1268 		error = ext4_mark_iloc_dirty(handle, inode, &is.iloc);
1269 		/*
1270 		 * The bh is consumed by ext4_mark_iloc_dirty, even with
1271 		 * error != 0.
1272 		 */
1273 		is.iloc.bh = NULL;
1274 		if (IS_SYNC(inode))
1275 			ext4_handle_sync(handle);
1276 	}
1277 
1278 cleanup:
1279 	brelse(is.iloc.bh);
1280 	brelse(bs.bh);
1281 	if (no_expand == 0)
1282 		ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND);
1283 	up_write(&EXT4_I(inode)->xattr_sem);
1284 	return error;
1285 }
1286 
1287 /*
1288  * ext4_xattr_set()
1289  *
1290  * Like ext4_xattr_set_handle, but start from an inode. This extended
1291  * attribute modification is a filesystem transaction by itself.
1292  *
1293  * Returns 0, or a negative error number on failure.
1294  */
1295 int
1296 ext4_xattr_set(struct inode *inode, int name_index, const char *name,
1297 	       const void *value, size_t value_len, int flags)
1298 {
1299 	handle_t *handle;
1300 	int error, retries = 0;
1301 	int credits = ext4_jbd2_credits_xattr(inode);
1302 
1303 retry:
1304 	handle = ext4_journal_start(inode, EXT4_HT_XATTR, credits);
1305 	if (IS_ERR(handle)) {
1306 		error = PTR_ERR(handle);
1307 	} else {
1308 		int error2;
1309 
1310 		error = ext4_xattr_set_handle(handle, inode, name_index, name,
1311 					      value, value_len, flags);
1312 		error2 = ext4_journal_stop(handle);
1313 		if (error == -ENOSPC &&
1314 		    ext4_should_retry_alloc(inode->i_sb, &retries))
1315 			goto retry;
1316 		if (error == 0)
1317 			error = error2;
1318 	}
1319 
1320 	return error;
1321 }
1322 
1323 /*
1324  * Shift the EA entries in the inode to create space for the increased
1325  * i_extra_isize.
1326  */
1327 static void ext4_xattr_shift_entries(struct ext4_xattr_entry *entry,
1328 				     int value_offs_shift, void *to,
1329 				     void *from, size_t n)
1330 {
1331 	struct ext4_xattr_entry *last = entry;
1332 	int new_offs;
1333 
1334 	/* We always shift xattr headers further thus offsets get lower */
1335 	BUG_ON(value_offs_shift > 0);
1336 
1337 	/* Adjust the value offsets of the entries */
1338 	for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
1339 		if (last->e_value_size) {
1340 			new_offs = le16_to_cpu(last->e_value_offs) +
1341 							value_offs_shift;
1342 			last->e_value_offs = cpu_to_le16(new_offs);
1343 		}
1344 	}
1345 	/* Shift the entries by n bytes */
1346 	memmove(to, from, n);
1347 }
1348 
1349 /*
1350  * Move xattr pointed to by 'entry' from inode into external xattr block
1351  */
1352 static int ext4_xattr_move_to_block(handle_t *handle, struct inode *inode,
1353 				    struct ext4_inode *raw_inode,
1354 				    struct ext4_xattr_entry *entry)
1355 {
1356 	struct ext4_xattr_ibody_find *is = NULL;
1357 	struct ext4_xattr_block_find *bs = NULL;
1358 	char *buffer = NULL, *b_entry_name = NULL;
1359 	size_t value_offs, value_size;
1360 	struct ext4_xattr_info i = {
1361 		.value = NULL,
1362 		.value_len = 0,
1363 		.name_index = entry->e_name_index,
1364 	};
1365 	struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode);
1366 	int error;
1367 
1368 	value_offs = le16_to_cpu(entry->e_value_offs);
1369 	value_size = le32_to_cpu(entry->e_value_size);
1370 
1371 	is = kzalloc(sizeof(struct ext4_xattr_ibody_find), GFP_NOFS);
1372 	bs = kzalloc(sizeof(struct ext4_xattr_block_find), GFP_NOFS);
1373 	buffer = kmalloc(value_size, GFP_NOFS);
1374 	b_entry_name = kmalloc(entry->e_name_len + 1, GFP_NOFS);
1375 	if (!is || !bs || !buffer || !b_entry_name) {
1376 		error = -ENOMEM;
1377 		goto out;
1378 	}
1379 
1380 	is->s.not_found = -ENODATA;
1381 	bs->s.not_found = -ENODATA;
1382 	is->iloc.bh = NULL;
1383 	bs->bh = NULL;
1384 
1385 	/* Save the entry name and the entry value */
1386 	memcpy(buffer, (void *)IFIRST(header) + value_offs, value_size);
1387 	memcpy(b_entry_name, entry->e_name, entry->e_name_len);
1388 	b_entry_name[entry->e_name_len] = '\0';
1389 	i.name = b_entry_name;
1390 
1391 	error = ext4_get_inode_loc(inode, &is->iloc);
1392 	if (error)
1393 		goto out;
1394 
1395 	error = ext4_xattr_ibody_find(inode, &i, is);
1396 	if (error)
1397 		goto out;
1398 
1399 	/* Remove the chosen entry from the inode */
1400 	error = ext4_xattr_ibody_set(inode, &i, is);
1401 	if (error)
1402 		goto out;
1403 
1404 	i.name = b_entry_name;
1405 	i.value = buffer;
1406 	i.value_len = value_size;
1407 	error = ext4_xattr_block_find(inode, &i, bs);
1408 	if (error)
1409 		goto out;
1410 
1411 	/* Add entry which was removed from the inode into the block */
1412 	error = ext4_xattr_block_set(handle, inode, &i, bs);
1413 	if (error)
1414 		goto out;
1415 	error = 0;
1416 out:
1417 	kfree(b_entry_name);
1418 	kfree(buffer);
1419 	if (is)
1420 		brelse(is->iloc.bh);
1421 	kfree(is);
1422 	kfree(bs);
1423 
1424 	return error;
1425 }
1426 
1427 static int ext4_xattr_make_inode_space(handle_t *handle, struct inode *inode,
1428 				       struct ext4_inode *raw_inode,
1429 				       int isize_diff, size_t ifree,
1430 				       size_t bfree, int *total_ino)
1431 {
1432 	struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode);
1433 	struct ext4_xattr_entry *small_entry;
1434 	struct ext4_xattr_entry *entry;
1435 	struct ext4_xattr_entry *last;
1436 	unsigned int entry_size;	/* EA entry size */
1437 	unsigned int total_size;	/* EA entry size + value size */
1438 	unsigned int min_total_size;
1439 	int error;
1440 
1441 	while (isize_diff > ifree) {
1442 		entry = NULL;
1443 		small_entry = NULL;
1444 		min_total_size = ~0U;
1445 		last = IFIRST(header);
1446 		/* Find the entry best suited to be pushed into EA block */
1447 		for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
1448 			total_size =
1449 			EXT4_XATTR_SIZE(le32_to_cpu(last->e_value_size)) +
1450 					EXT4_XATTR_LEN(last->e_name_len);
1451 			if (total_size <= bfree &&
1452 			    total_size < min_total_size) {
1453 				if (total_size + ifree < isize_diff) {
1454 					small_entry = last;
1455 				} else {
1456 					entry = last;
1457 					min_total_size = total_size;
1458 				}
1459 			}
1460 		}
1461 
1462 		if (entry == NULL) {
1463 			if (small_entry == NULL)
1464 				return -ENOSPC;
1465 			entry = small_entry;
1466 		}
1467 
1468 		entry_size = EXT4_XATTR_LEN(entry->e_name_len);
1469 		total_size = entry_size +
1470 			EXT4_XATTR_SIZE(le32_to_cpu(entry->e_value_size));
1471 		error = ext4_xattr_move_to_block(handle, inode, raw_inode,
1472 						 entry);
1473 		if (error)
1474 			return error;
1475 
1476 		*total_ino -= entry_size;
1477 		ifree += total_size;
1478 		bfree -= total_size;
1479 	}
1480 
1481 	return 0;
1482 }
1483 
1484 /*
1485  * Expand an inode by new_extra_isize bytes when EAs are present.
1486  * Returns 0 on success or negative error number on failure.
1487  */
1488 int ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize,
1489 			       struct ext4_inode *raw_inode, handle_t *handle)
1490 {
1491 	struct ext4_xattr_ibody_header *header;
1492 	struct buffer_head *bh = NULL;
1493 	size_t min_offs;
1494 	size_t ifree, bfree;
1495 	int total_ino;
1496 	void *base, *end;
1497 	int error = 0, tried_min_extra_isize = 0;
1498 	int s_min_extra_isize = le16_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_min_extra_isize);
1499 	int isize_diff;	/* How much do we need to grow i_extra_isize */
1500 
1501 	down_write(&EXT4_I(inode)->xattr_sem);
1502 	/*
1503 	 * Set EXT4_STATE_NO_EXPAND to avoid recursion when marking inode dirty
1504 	 */
1505 	ext4_set_inode_state(inode, EXT4_STATE_NO_EXPAND);
1506 retry:
1507 	isize_diff = new_extra_isize - EXT4_I(inode)->i_extra_isize;
1508 	if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
1509 		goto out;
1510 
1511 	header = IHDR(inode, raw_inode);
1512 
1513 	/*
1514 	 * Check if enough free space is available in the inode to shift the
1515 	 * entries ahead by new_extra_isize.
1516 	 */
1517 
1518 	base = IFIRST(header);
1519 	end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
1520 	min_offs = end - base;
1521 	total_ino = sizeof(struct ext4_xattr_ibody_header);
1522 
1523 	error = xattr_check_inode(inode, header, end);
1524 	if (error)
1525 		goto cleanup;
1526 
1527 	ifree = ext4_xattr_free_space(base, &min_offs, base, &total_ino);
1528 	if (ifree >= isize_diff)
1529 		goto shift;
1530 
1531 	/*
1532 	 * Enough free space isn't available in the inode, check if
1533 	 * EA block can hold new_extra_isize bytes.
1534 	 */
1535 	if (EXT4_I(inode)->i_file_acl) {
1536 		bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
1537 		error = -EIO;
1538 		if (!bh)
1539 			goto cleanup;
1540 		if (ext4_xattr_check_block(inode, bh)) {
1541 			EXT4_ERROR_INODE(inode, "bad block %llu",
1542 					 EXT4_I(inode)->i_file_acl);
1543 			error = -EFSCORRUPTED;
1544 			goto cleanup;
1545 		}
1546 		base = BHDR(bh);
1547 		end = bh->b_data + bh->b_size;
1548 		min_offs = end - base;
1549 		bfree = ext4_xattr_free_space(BFIRST(bh), &min_offs, base,
1550 					      NULL);
1551 		if (bfree + ifree < isize_diff) {
1552 			if (!tried_min_extra_isize && s_min_extra_isize) {
1553 				tried_min_extra_isize++;
1554 				new_extra_isize = s_min_extra_isize;
1555 				brelse(bh);
1556 				goto retry;
1557 			}
1558 			error = -ENOSPC;
1559 			goto cleanup;
1560 		}
1561 	} else {
1562 		bfree = inode->i_sb->s_blocksize;
1563 	}
1564 
1565 	error = ext4_xattr_make_inode_space(handle, inode, raw_inode,
1566 					    isize_diff, ifree, bfree,
1567 					    &total_ino);
1568 	if (error) {
1569 		if (error == -ENOSPC && !tried_min_extra_isize &&
1570 		    s_min_extra_isize) {
1571 			tried_min_extra_isize++;
1572 			new_extra_isize = s_min_extra_isize;
1573 			brelse(bh);
1574 			goto retry;
1575 		}
1576 		goto cleanup;
1577 	}
1578 shift:
1579 	/* Adjust the offsets and shift the remaining entries ahead */
1580 	ext4_xattr_shift_entries(IFIRST(header), EXT4_I(inode)->i_extra_isize
1581 			- new_extra_isize, (void *)raw_inode +
1582 			EXT4_GOOD_OLD_INODE_SIZE + new_extra_isize,
1583 			(void *)header, total_ino);
1584 	EXT4_I(inode)->i_extra_isize = new_extra_isize;
1585 	brelse(bh);
1586 out:
1587 	ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND);
1588 	up_write(&EXT4_I(inode)->xattr_sem);
1589 	return 0;
1590 
1591 cleanup:
1592 	brelse(bh);
1593 	/*
1594 	 * We deliberately leave EXT4_STATE_NO_EXPAND set here since inode
1595 	 * size expansion failed.
1596 	 */
1597 	up_write(&EXT4_I(inode)->xattr_sem);
1598 	return error;
1599 }
1600 
1601 
1602 
1603 /*
1604  * ext4_xattr_delete_inode()
1605  *
1606  * Free extended attribute resources associated with this inode. This
1607  * is called immediately before an inode is freed. We have exclusive
1608  * access to the inode.
1609  */
1610 void
1611 ext4_xattr_delete_inode(handle_t *handle, struct inode *inode)
1612 {
1613 	struct buffer_head *bh = NULL;
1614 
1615 	if (!EXT4_I(inode)->i_file_acl)
1616 		goto cleanup;
1617 	bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
1618 	if (!bh) {
1619 		EXT4_ERROR_INODE(inode, "block %llu read error",
1620 				 EXT4_I(inode)->i_file_acl);
1621 		goto cleanup;
1622 	}
1623 	if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
1624 	    BHDR(bh)->h_blocks != cpu_to_le32(1)) {
1625 		EXT4_ERROR_INODE(inode, "bad block %llu",
1626 				 EXT4_I(inode)->i_file_acl);
1627 		goto cleanup;
1628 	}
1629 	ext4_xattr_release_block(handle, inode, bh);
1630 	EXT4_I(inode)->i_file_acl = 0;
1631 
1632 cleanup:
1633 	brelse(bh);
1634 }
1635 
1636 /*
1637  * ext4_xattr_cache_insert()
1638  *
1639  * Create a new entry in the extended attribute cache, and insert
1640  * it unless such an entry is already in the cache.
1641  *
1642  * Returns 0, or a negative error number on failure.
1643  */
1644 static void
1645 ext4_xattr_cache_insert(struct mb_cache *ext4_mb_cache, struct buffer_head *bh)
1646 {
1647 	struct ext4_xattr_header *header = BHDR(bh);
1648 	__u32 hash = le32_to_cpu(header->h_hash);
1649 	int reusable = le32_to_cpu(header->h_refcount) <
1650 		       EXT4_XATTR_REFCOUNT_MAX;
1651 	int error;
1652 
1653 	error = mb_cache_entry_create(ext4_mb_cache, GFP_NOFS, hash,
1654 				      bh->b_blocknr, reusable);
1655 	if (error) {
1656 		if (error == -EBUSY)
1657 			ea_bdebug(bh, "already in cache");
1658 	} else
1659 		ea_bdebug(bh, "inserting [%x]", (int)hash);
1660 }
1661 
1662 /*
1663  * ext4_xattr_cmp()
1664  *
1665  * Compare two extended attribute blocks for equality.
1666  *
1667  * Returns 0 if the blocks are equal, 1 if they differ, and
1668  * a negative error number on errors.
1669  */
1670 static int
1671 ext4_xattr_cmp(struct ext4_xattr_header *header1,
1672 	       struct ext4_xattr_header *header2)
1673 {
1674 	struct ext4_xattr_entry *entry1, *entry2;
1675 
1676 	entry1 = ENTRY(header1+1);
1677 	entry2 = ENTRY(header2+1);
1678 	while (!IS_LAST_ENTRY(entry1)) {
1679 		if (IS_LAST_ENTRY(entry2))
1680 			return 1;
1681 		if (entry1->e_hash != entry2->e_hash ||
1682 		    entry1->e_name_index != entry2->e_name_index ||
1683 		    entry1->e_name_len != entry2->e_name_len ||
1684 		    entry1->e_value_size != entry2->e_value_size ||
1685 		    memcmp(entry1->e_name, entry2->e_name, entry1->e_name_len))
1686 			return 1;
1687 		if (entry1->e_value_block != 0 || entry2->e_value_block != 0)
1688 			return -EFSCORRUPTED;
1689 		if (memcmp((char *)header1 + le16_to_cpu(entry1->e_value_offs),
1690 			   (char *)header2 + le16_to_cpu(entry2->e_value_offs),
1691 			   le32_to_cpu(entry1->e_value_size)))
1692 			return 1;
1693 
1694 		entry1 = EXT4_XATTR_NEXT(entry1);
1695 		entry2 = EXT4_XATTR_NEXT(entry2);
1696 	}
1697 	if (!IS_LAST_ENTRY(entry2))
1698 		return 1;
1699 	return 0;
1700 }
1701 
1702 /*
1703  * ext4_xattr_cache_find()
1704  *
1705  * Find an identical extended attribute block.
1706  *
1707  * Returns a pointer to the block found, or NULL if such a block was
1708  * not found or an error occurred.
1709  */
1710 static struct buffer_head *
1711 ext4_xattr_cache_find(struct inode *inode, struct ext4_xattr_header *header,
1712 		      struct mb_cache_entry **pce)
1713 {
1714 	__u32 hash = le32_to_cpu(header->h_hash);
1715 	struct mb_cache_entry *ce;
1716 	struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
1717 
1718 	if (!header->h_hash)
1719 		return NULL;  /* never share */
1720 	ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
1721 	ce = mb_cache_entry_find_first(ext4_mb_cache, hash);
1722 	while (ce) {
1723 		struct buffer_head *bh;
1724 
1725 		bh = sb_bread(inode->i_sb, ce->e_block);
1726 		if (!bh) {
1727 			EXT4_ERROR_INODE(inode, "block %lu read error",
1728 					 (unsigned long) ce->e_block);
1729 		} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
1730 			*pce = ce;
1731 			return bh;
1732 		}
1733 		brelse(bh);
1734 		ce = mb_cache_entry_find_next(ext4_mb_cache, ce);
1735 	}
1736 	return NULL;
1737 }
1738 
1739 #define NAME_HASH_SHIFT 5
1740 #define VALUE_HASH_SHIFT 16
1741 
1742 /*
1743  * ext4_xattr_hash_entry()
1744  *
1745  * Compute the hash of an extended attribute.
1746  */
1747 static inline void ext4_xattr_hash_entry(struct ext4_xattr_header *header,
1748 					 struct ext4_xattr_entry *entry)
1749 {
1750 	__u32 hash = 0;
1751 	char *name = entry->e_name;
1752 	int n;
1753 
1754 	for (n = 0; n < entry->e_name_len; n++) {
1755 		hash = (hash << NAME_HASH_SHIFT) ^
1756 		       (hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
1757 		       *name++;
1758 	}
1759 
1760 	if (entry->e_value_size != 0) {
1761 		__le32 *value = (__le32 *)((char *)header +
1762 			le16_to_cpu(entry->e_value_offs));
1763 		for (n = (le32_to_cpu(entry->e_value_size) +
1764 		     EXT4_XATTR_ROUND) >> EXT4_XATTR_PAD_BITS; n; n--) {
1765 			hash = (hash << VALUE_HASH_SHIFT) ^
1766 			       (hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
1767 			       le32_to_cpu(*value++);
1768 		}
1769 	}
1770 	entry->e_hash = cpu_to_le32(hash);
1771 }
1772 
1773 #undef NAME_HASH_SHIFT
1774 #undef VALUE_HASH_SHIFT
1775 
1776 #define BLOCK_HASH_SHIFT 16
1777 
1778 /*
1779  * ext4_xattr_rehash()
1780  *
1781  * Re-compute the extended attribute hash value after an entry has changed.
1782  */
1783 static void ext4_xattr_rehash(struct ext4_xattr_header *header,
1784 			      struct ext4_xattr_entry *entry)
1785 {
1786 	struct ext4_xattr_entry *here;
1787 	__u32 hash = 0;
1788 
1789 	ext4_xattr_hash_entry(header, entry);
1790 	here = ENTRY(header+1);
1791 	while (!IS_LAST_ENTRY(here)) {
1792 		if (!here->e_hash) {
1793 			/* Block is not shared if an entry's hash value == 0 */
1794 			hash = 0;
1795 			break;
1796 		}
1797 		hash = (hash << BLOCK_HASH_SHIFT) ^
1798 		       (hash >> (8*sizeof(hash) - BLOCK_HASH_SHIFT)) ^
1799 		       le32_to_cpu(here->e_hash);
1800 		here = EXT4_XATTR_NEXT(here);
1801 	}
1802 	header->h_hash = cpu_to_le32(hash);
1803 }
1804 
1805 #undef BLOCK_HASH_SHIFT
1806 
1807 #define	HASH_BUCKET_BITS	10
1808 
1809 struct mb_cache *
1810 ext4_xattr_create_cache(void)
1811 {
1812 	return mb_cache_create(HASH_BUCKET_BITS);
1813 }
1814 
1815 void ext4_xattr_destroy_cache(struct mb_cache *cache)
1816 {
1817 	if (cache)
1818 		mb_cache_destroy(cache);
1819 }
1820 
1821