xref: /openbmc/linux/fs/ext4/xattr.c (revision 9d56dd3b083a3bec56e9da35ce07baca81030b03)
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 <linux/rwsem.h>
59 #include "ext4_jbd2.h"
60 #include "ext4.h"
61 #include "xattr.h"
62 #include "acl.h"
63 
64 #define BHDR(bh) ((struct ext4_xattr_header *)((bh)->b_data))
65 #define ENTRY(ptr) ((struct ext4_xattr_entry *)(ptr))
66 #define BFIRST(bh) ENTRY(BHDR(bh)+1)
67 #define IS_LAST_ENTRY(entry) (*(__u32 *)(entry) == 0)
68 
69 #ifdef EXT4_XATTR_DEBUG
70 # define ea_idebug(inode, f...) do { \
71 		printk(KERN_DEBUG "inode %s:%lu: ", \
72 			inode->i_sb->s_id, inode->i_ino); \
73 		printk(f); \
74 		printk("\n"); \
75 	} while (0)
76 # define ea_bdebug(bh, f...) do { \
77 		char b[BDEVNAME_SIZE]; \
78 		printk(KERN_DEBUG "block %s:%lu: ", \
79 			bdevname(bh->b_bdev, b), \
80 			(unsigned long) bh->b_blocknr); \
81 		printk(f); \
82 		printk("\n"); \
83 	} while (0)
84 #else
85 # define ea_idebug(f...)
86 # define ea_bdebug(f...)
87 #endif
88 
89 static void ext4_xattr_cache_insert(struct buffer_head *);
90 static struct buffer_head *ext4_xattr_cache_find(struct inode *,
91 						 struct ext4_xattr_header *,
92 						 struct mb_cache_entry **);
93 static void ext4_xattr_rehash(struct ext4_xattr_header *,
94 			      struct ext4_xattr_entry *);
95 static int ext4_xattr_list(struct dentry *dentry, char *buffer,
96 			   size_t buffer_size);
97 
98 static struct mb_cache *ext4_xattr_cache;
99 
100 static struct xattr_handler *ext4_xattr_handler_map[] = {
101 	[EXT4_XATTR_INDEX_USER]		     = &ext4_xattr_user_handler,
102 #ifdef CONFIG_EXT4_FS_POSIX_ACL
103 	[EXT4_XATTR_INDEX_POSIX_ACL_ACCESS]  = &ext4_xattr_acl_access_handler,
104 	[EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT] = &ext4_xattr_acl_default_handler,
105 #endif
106 	[EXT4_XATTR_INDEX_TRUSTED]	     = &ext4_xattr_trusted_handler,
107 #ifdef CONFIG_EXT4_FS_SECURITY
108 	[EXT4_XATTR_INDEX_SECURITY]	     = &ext4_xattr_security_handler,
109 #endif
110 };
111 
112 struct xattr_handler *ext4_xattr_handlers[] = {
113 	&ext4_xattr_user_handler,
114 	&ext4_xattr_trusted_handler,
115 #ifdef CONFIG_EXT4_FS_POSIX_ACL
116 	&ext4_xattr_acl_access_handler,
117 	&ext4_xattr_acl_default_handler,
118 #endif
119 #ifdef CONFIG_EXT4_FS_SECURITY
120 	&ext4_xattr_security_handler,
121 #endif
122 	NULL
123 };
124 
125 static inline struct xattr_handler *
126 ext4_xattr_handler(int name_index)
127 {
128 	struct xattr_handler *handler = NULL;
129 
130 	if (name_index > 0 && name_index < ARRAY_SIZE(ext4_xattr_handler_map))
131 		handler = ext4_xattr_handler_map[name_index];
132 	return handler;
133 }
134 
135 /*
136  * Inode operation listxattr()
137  *
138  * dentry->d_inode->i_mutex: don't care
139  */
140 ssize_t
141 ext4_listxattr(struct dentry *dentry, char *buffer, size_t size)
142 {
143 	return ext4_xattr_list(dentry, buffer, size);
144 }
145 
146 static int
147 ext4_xattr_check_names(struct ext4_xattr_entry *entry, void *end)
148 {
149 	while (!IS_LAST_ENTRY(entry)) {
150 		struct ext4_xattr_entry *next = EXT4_XATTR_NEXT(entry);
151 		if ((void *)next >= end)
152 			return -EIO;
153 		entry = next;
154 	}
155 	return 0;
156 }
157 
158 static inline int
159 ext4_xattr_check_block(struct buffer_head *bh)
160 {
161 	int error;
162 
163 	if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
164 	    BHDR(bh)->h_blocks != cpu_to_le32(1))
165 		return -EIO;
166 	error = ext4_xattr_check_names(BFIRST(bh), bh->b_data + bh->b_size);
167 	return error;
168 }
169 
170 static inline int
171 ext4_xattr_check_entry(struct ext4_xattr_entry *entry, size_t size)
172 {
173 	size_t value_size = le32_to_cpu(entry->e_value_size);
174 
175 	if (entry->e_value_block != 0 || value_size > size ||
176 	    le16_to_cpu(entry->e_value_offs) + value_size > size)
177 		return -EIO;
178 	return 0;
179 }
180 
181 static int
182 ext4_xattr_find_entry(struct ext4_xattr_entry **pentry, int name_index,
183 		      const char *name, size_t size, int sorted)
184 {
185 	struct ext4_xattr_entry *entry;
186 	size_t name_len;
187 	int cmp = 1;
188 
189 	if (name == NULL)
190 		return -EINVAL;
191 	name_len = strlen(name);
192 	entry = *pentry;
193 	for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
194 		cmp = name_index - entry->e_name_index;
195 		if (!cmp)
196 			cmp = name_len - entry->e_name_len;
197 		if (!cmp)
198 			cmp = memcmp(name, entry->e_name, name_len);
199 		if (cmp <= 0 && (sorted || cmp == 0))
200 			break;
201 	}
202 	*pentry = entry;
203 	if (!cmp && ext4_xattr_check_entry(entry, size))
204 			return -EIO;
205 	return cmp ? -ENODATA : 0;
206 }
207 
208 static int
209 ext4_xattr_block_get(struct inode *inode, int name_index, const char *name,
210 		     void *buffer, size_t buffer_size)
211 {
212 	struct buffer_head *bh = NULL;
213 	struct ext4_xattr_entry *entry;
214 	size_t size;
215 	int error;
216 
217 	ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
218 		  name_index, name, buffer, (long)buffer_size);
219 
220 	error = -ENODATA;
221 	if (!EXT4_I(inode)->i_file_acl)
222 		goto cleanup;
223 	ea_idebug(inode, "reading block %u", EXT4_I(inode)->i_file_acl);
224 	bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
225 	if (!bh)
226 		goto cleanup;
227 	ea_bdebug(bh, "b_count=%d, refcount=%d",
228 		atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
229 	if (ext4_xattr_check_block(bh)) {
230 bad_block:	ext4_error(inode->i_sb, __func__,
231 			   "inode %lu: bad block %llu", inode->i_ino,
232 			   EXT4_I(inode)->i_file_acl);
233 		error = -EIO;
234 		goto cleanup;
235 	}
236 	ext4_xattr_cache_insert(bh);
237 	entry = BFIRST(bh);
238 	error = ext4_xattr_find_entry(&entry, name_index, name, bh->b_size, 1);
239 	if (error == -EIO)
240 		goto bad_block;
241 	if (error)
242 		goto cleanup;
243 	size = le32_to_cpu(entry->e_value_size);
244 	if (buffer) {
245 		error = -ERANGE;
246 		if (size > buffer_size)
247 			goto cleanup;
248 		memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs),
249 		       size);
250 	}
251 	error = size;
252 
253 cleanup:
254 	brelse(bh);
255 	return error;
256 }
257 
258 static int
259 ext4_xattr_ibody_get(struct inode *inode, int name_index, const char *name,
260 		     void *buffer, size_t buffer_size)
261 {
262 	struct ext4_xattr_ibody_header *header;
263 	struct ext4_xattr_entry *entry;
264 	struct ext4_inode *raw_inode;
265 	struct ext4_iloc iloc;
266 	size_t size;
267 	void *end;
268 	int error;
269 
270 	if (!(EXT4_I(inode)->i_state & EXT4_STATE_XATTR))
271 		return -ENODATA;
272 	error = ext4_get_inode_loc(inode, &iloc);
273 	if (error)
274 		return error;
275 	raw_inode = ext4_raw_inode(&iloc);
276 	header = IHDR(inode, raw_inode);
277 	entry = IFIRST(header);
278 	end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
279 	error = ext4_xattr_check_names(entry, end);
280 	if (error)
281 		goto cleanup;
282 	error = ext4_xattr_find_entry(&entry, name_index, name,
283 				      end - (void *)entry, 0);
284 	if (error)
285 		goto cleanup;
286 	size = le32_to_cpu(entry->e_value_size);
287 	if (buffer) {
288 		error = -ERANGE;
289 		if (size > buffer_size)
290 			goto cleanup;
291 		memcpy(buffer, (void *)IFIRST(header) +
292 		       le16_to_cpu(entry->e_value_offs), size);
293 	}
294 	error = size;
295 
296 cleanup:
297 	brelse(iloc.bh);
298 	return error;
299 }
300 
301 /*
302  * ext4_xattr_get()
303  *
304  * Copy an extended attribute into the buffer
305  * provided, or compute the buffer size required.
306  * Buffer is NULL to compute the size of the buffer required.
307  *
308  * Returns a negative error number on failure, or the number of bytes
309  * used / required on success.
310  */
311 int
312 ext4_xattr_get(struct inode *inode, int name_index, const char *name,
313 	       void *buffer, size_t buffer_size)
314 {
315 	int error;
316 
317 	down_read(&EXT4_I(inode)->xattr_sem);
318 	error = ext4_xattr_ibody_get(inode, name_index, name, buffer,
319 				     buffer_size);
320 	if (error == -ENODATA)
321 		error = ext4_xattr_block_get(inode, name_index, name, buffer,
322 					     buffer_size);
323 	up_read(&EXT4_I(inode)->xattr_sem);
324 	return error;
325 }
326 
327 static int
328 ext4_xattr_list_entries(struct dentry *dentry, struct ext4_xattr_entry *entry,
329 			char *buffer, size_t buffer_size)
330 {
331 	size_t rest = buffer_size;
332 
333 	for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
334 		struct xattr_handler *handler =
335 			ext4_xattr_handler(entry->e_name_index);
336 
337 		if (handler) {
338 			size_t size = handler->list(dentry, buffer, rest,
339 						    entry->e_name,
340 						    entry->e_name_len,
341 						    handler->flags);
342 			if (buffer) {
343 				if (size > rest)
344 					return -ERANGE;
345 				buffer += size;
346 			}
347 			rest -= size;
348 		}
349 	}
350 	return buffer_size - rest;
351 }
352 
353 static int
354 ext4_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size)
355 {
356 	struct inode *inode = dentry->d_inode;
357 	struct buffer_head *bh = NULL;
358 	int error;
359 
360 	ea_idebug(inode, "buffer=%p, buffer_size=%ld",
361 		  buffer, (long)buffer_size);
362 
363 	error = 0;
364 	if (!EXT4_I(inode)->i_file_acl)
365 		goto cleanup;
366 	ea_idebug(inode, "reading block %u", EXT4_I(inode)->i_file_acl);
367 	bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
368 	error = -EIO;
369 	if (!bh)
370 		goto cleanup;
371 	ea_bdebug(bh, "b_count=%d, refcount=%d",
372 		atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
373 	if (ext4_xattr_check_block(bh)) {
374 		ext4_error(inode->i_sb, __func__,
375 			   "inode %lu: bad block %llu", inode->i_ino,
376 			   EXT4_I(inode)->i_file_acl);
377 		error = -EIO;
378 		goto cleanup;
379 	}
380 	ext4_xattr_cache_insert(bh);
381 	error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size);
382 
383 cleanup:
384 	brelse(bh);
385 
386 	return error;
387 }
388 
389 static int
390 ext4_xattr_ibody_list(struct dentry *dentry, char *buffer, size_t buffer_size)
391 {
392 	struct inode *inode = dentry->d_inode;
393 	struct ext4_xattr_ibody_header *header;
394 	struct ext4_inode *raw_inode;
395 	struct ext4_iloc iloc;
396 	void *end;
397 	int error;
398 
399 	if (!(EXT4_I(inode)->i_state & EXT4_STATE_XATTR))
400 		return 0;
401 	error = ext4_get_inode_loc(inode, &iloc);
402 	if (error)
403 		return error;
404 	raw_inode = ext4_raw_inode(&iloc);
405 	header = IHDR(inode, raw_inode);
406 	end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
407 	error = ext4_xattr_check_names(IFIRST(header), end);
408 	if (error)
409 		goto cleanup;
410 	error = ext4_xattr_list_entries(dentry, IFIRST(header),
411 					buffer, buffer_size);
412 
413 cleanup:
414 	brelse(iloc.bh);
415 	return error;
416 }
417 
418 /*
419  * ext4_xattr_list()
420  *
421  * Copy a list of attribute names into the buffer
422  * provided, or compute the buffer size required.
423  * Buffer is NULL to compute the size of the buffer required.
424  *
425  * Returns a negative error number on failure, or the number of bytes
426  * used / required on success.
427  */
428 static int
429 ext4_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size)
430 {
431 	int i_error, b_error;
432 
433 	down_read(&EXT4_I(dentry->d_inode)->xattr_sem);
434 	i_error = ext4_xattr_ibody_list(dentry, buffer, buffer_size);
435 	if (i_error < 0) {
436 		b_error = 0;
437 	} else {
438 		if (buffer) {
439 			buffer += i_error;
440 			buffer_size -= i_error;
441 		}
442 		b_error = ext4_xattr_block_list(dentry, buffer, buffer_size);
443 		if (b_error < 0)
444 			i_error = 0;
445 	}
446 	up_read(&EXT4_I(dentry->d_inode)->xattr_sem);
447 	return i_error + b_error;
448 }
449 
450 /*
451  * If the EXT4_FEATURE_COMPAT_EXT_ATTR feature of this file system is
452  * not set, set it.
453  */
454 static void ext4_xattr_update_super_block(handle_t *handle,
455 					  struct super_block *sb)
456 {
457 	if (EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_EXT_ATTR))
458 		return;
459 
460 	if (ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh) == 0) {
461 		EXT4_SET_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_EXT_ATTR);
462 		sb->s_dirt = 1;
463 		ext4_handle_dirty_metadata(handle, NULL, EXT4_SB(sb)->s_sbh);
464 	}
465 }
466 
467 /*
468  * Release the xattr block BH: If the reference count is > 1, decrement
469  * it; otherwise free the block.
470  */
471 static void
472 ext4_xattr_release_block(handle_t *handle, struct inode *inode,
473 			 struct buffer_head *bh)
474 {
475 	struct mb_cache_entry *ce = NULL;
476 	int error = 0;
477 
478 	ce = mb_cache_entry_get(ext4_xattr_cache, bh->b_bdev, bh->b_blocknr);
479 	error = ext4_journal_get_write_access(handle, bh);
480 	if (error)
481 		goto out;
482 
483 	lock_buffer(bh);
484 	if (BHDR(bh)->h_refcount == cpu_to_le32(1)) {
485 		ea_bdebug(bh, "refcount now=0; freeing");
486 		if (ce)
487 			mb_cache_entry_free(ce);
488 		get_bh(bh);
489 		ext4_free_blocks(handle, inode, bh, 0, 1,
490 				 EXT4_FREE_BLOCKS_METADATA |
491 				 EXT4_FREE_BLOCKS_FORGET);
492 	} else {
493 		le32_add_cpu(&BHDR(bh)->h_refcount, -1);
494 		error = ext4_handle_dirty_metadata(handle, inode, bh);
495 		if (IS_SYNC(inode))
496 			ext4_handle_sync(handle);
497 		vfs_dq_free_block(inode, 1);
498 		ea_bdebug(bh, "refcount now=%d; releasing",
499 			  le32_to_cpu(BHDR(bh)->h_refcount));
500 		if (ce)
501 			mb_cache_entry_release(ce);
502 	}
503 	unlock_buffer(bh);
504 out:
505 	ext4_std_error(inode->i_sb, error);
506 	return;
507 }
508 
509 /*
510  * Find the available free space for EAs. This also returns the total number of
511  * bytes used by EA entries.
512  */
513 static size_t ext4_xattr_free_space(struct ext4_xattr_entry *last,
514 				    size_t *min_offs, void *base, int *total)
515 {
516 	for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
517 		*total += EXT4_XATTR_LEN(last->e_name_len);
518 		if (!last->e_value_block && last->e_value_size) {
519 			size_t offs = le16_to_cpu(last->e_value_offs);
520 			if (offs < *min_offs)
521 				*min_offs = offs;
522 		}
523 	}
524 	return (*min_offs - ((void *)last - base) - sizeof(__u32));
525 }
526 
527 struct ext4_xattr_info {
528 	int name_index;
529 	const char *name;
530 	const void *value;
531 	size_t value_len;
532 };
533 
534 struct ext4_xattr_search {
535 	struct ext4_xattr_entry *first;
536 	void *base;
537 	void *end;
538 	struct ext4_xattr_entry *here;
539 	int not_found;
540 };
541 
542 static int
543 ext4_xattr_set_entry(struct ext4_xattr_info *i, struct ext4_xattr_search *s)
544 {
545 	struct ext4_xattr_entry *last;
546 	size_t free, min_offs = s->end - s->base, name_len = strlen(i->name);
547 
548 	/* Compute min_offs and last. */
549 	last = s->first;
550 	for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
551 		if (!last->e_value_block && last->e_value_size) {
552 			size_t offs = le16_to_cpu(last->e_value_offs);
553 			if (offs < min_offs)
554 				min_offs = offs;
555 		}
556 	}
557 	free = min_offs - ((void *)last - s->base) - sizeof(__u32);
558 	if (!s->not_found) {
559 		if (!s->here->e_value_block && s->here->e_value_size) {
560 			size_t size = le32_to_cpu(s->here->e_value_size);
561 			free += EXT4_XATTR_SIZE(size);
562 		}
563 		free += EXT4_XATTR_LEN(name_len);
564 	}
565 	if (i->value) {
566 		if (free < EXT4_XATTR_SIZE(i->value_len) ||
567 		    free < EXT4_XATTR_LEN(name_len) +
568 			   EXT4_XATTR_SIZE(i->value_len))
569 			return -ENOSPC;
570 	}
571 
572 	if (i->value && s->not_found) {
573 		/* Insert the new name. */
574 		size_t size = EXT4_XATTR_LEN(name_len);
575 		size_t rest = (void *)last - (void *)s->here + sizeof(__u32);
576 		memmove((void *)s->here + size, s->here, rest);
577 		memset(s->here, 0, size);
578 		s->here->e_name_index = i->name_index;
579 		s->here->e_name_len = name_len;
580 		memcpy(s->here->e_name, i->name, name_len);
581 	} else {
582 		if (!s->here->e_value_block && s->here->e_value_size) {
583 			void *first_val = s->base + min_offs;
584 			size_t offs = le16_to_cpu(s->here->e_value_offs);
585 			void *val = s->base + offs;
586 			size_t size = EXT4_XATTR_SIZE(
587 				le32_to_cpu(s->here->e_value_size));
588 
589 			if (i->value && size == EXT4_XATTR_SIZE(i->value_len)) {
590 				/* The old and the new value have the same
591 				   size. Just replace. */
592 				s->here->e_value_size =
593 					cpu_to_le32(i->value_len);
594 				memset(val + size - EXT4_XATTR_PAD, 0,
595 				       EXT4_XATTR_PAD); /* Clear pad bytes. */
596 				memcpy(val, i->value, i->value_len);
597 				return 0;
598 			}
599 
600 			/* Remove the old value. */
601 			memmove(first_val + size, first_val, val - first_val);
602 			memset(first_val, 0, size);
603 			s->here->e_value_size = 0;
604 			s->here->e_value_offs = 0;
605 			min_offs += size;
606 
607 			/* Adjust all value offsets. */
608 			last = s->first;
609 			while (!IS_LAST_ENTRY(last)) {
610 				size_t o = le16_to_cpu(last->e_value_offs);
611 				if (!last->e_value_block &&
612 				    last->e_value_size && o < offs)
613 					last->e_value_offs =
614 						cpu_to_le16(o + size);
615 				last = EXT4_XATTR_NEXT(last);
616 			}
617 		}
618 		if (!i->value) {
619 			/* Remove the old name. */
620 			size_t size = EXT4_XATTR_LEN(name_len);
621 			last = ENTRY((void *)last - size);
622 			memmove(s->here, (void *)s->here + size,
623 				(void *)last - (void *)s->here + sizeof(__u32));
624 			memset(last, 0, size);
625 		}
626 	}
627 
628 	if (i->value) {
629 		/* Insert the new value. */
630 		s->here->e_value_size = cpu_to_le32(i->value_len);
631 		if (i->value_len) {
632 			size_t size = EXT4_XATTR_SIZE(i->value_len);
633 			void *val = s->base + min_offs - size;
634 			s->here->e_value_offs = cpu_to_le16(min_offs - size);
635 			memset(val + size - EXT4_XATTR_PAD, 0,
636 			       EXT4_XATTR_PAD); /* Clear the pad bytes. */
637 			memcpy(val, i->value, i->value_len);
638 		}
639 	}
640 	return 0;
641 }
642 
643 struct ext4_xattr_block_find {
644 	struct ext4_xattr_search s;
645 	struct buffer_head *bh;
646 };
647 
648 static int
649 ext4_xattr_block_find(struct inode *inode, struct ext4_xattr_info *i,
650 		      struct ext4_xattr_block_find *bs)
651 {
652 	struct super_block *sb = inode->i_sb;
653 	int error;
654 
655 	ea_idebug(inode, "name=%d.%s, value=%p, value_len=%ld",
656 		  i->name_index, i->name, i->value, (long)i->value_len);
657 
658 	if (EXT4_I(inode)->i_file_acl) {
659 		/* The inode already has an extended attribute block. */
660 		bs->bh = sb_bread(sb, EXT4_I(inode)->i_file_acl);
661 		error = -EIO;
662 		if (!bs->bh)
663 			goto cleanup;
664 		ea_bdebug(bs->bh, "b_count=%d, refcount=%d",
665 			atomic_read(&(bs->bh->b_count)),
666 			le32_to_cpu(BHDR(bs->bh)->h_refcount));
667 		if (ext4_xattr_check_block(bs->bh)) {
668 			ext4_error(sb, __func__,
669 				"inode %lu: bad block %llu", inode->i_ino,
670 				EXT4_I(inode)->i_file_acl);
671 			error = -EIO;
672 			goto cleanup;
673 		}
674 		/* Find the named attribute. */
675 		bs->s.base = BHDR(bs->bh);
676 		bs->s.first = BFIRST(bs->bh);
677 		bs->s.end = bs->bh->b_data + bs->bh->b_size;
678 		bs->s.here = bs->s.first;
679 		error = ext4_xattr_find_entry(&bs->s.here, i->name_index,
680 					      i->name, bs->bh->b_size, 1);
681 		if (error && error != -ENODATA)
682 			goto cleanup;
683 		bs->s.not_found = error;
684 	}
685 	error = 0;
686 
687 cleanup:
688 	return error;
689 }
690 
691 static int
692 ext4_xattr_block_set(handle_t *handle, struct inode *inode,
693 		     struct ext4_xattr_info *i,
694 		     struct ext4_xattr_block_find *bs)
695 {
696 	struct super_block *sb = inode->i_sb;
697 	struct buffer_head *new_bh = NULL;
698 	struct ext4_xattr_search *s = &bs->s;
699 	struct mb_cache_entry *ce = NULL;
700 	int error = 0;
701 
702 #define header(x) ((struct ext4_xattr_header *)(x))
703 
704 	if (i->value && i->value_len > sb->s_blocksize)
705 		return -ENOSPC;
706 	if (s->base) {
707 		ce = mb_cache_entry_get(ext4_xattr_cache, bs->bh->b_bdev,
708 					bs->bh->b_blocknr);
709 		error = ext4_journal_get_write_access(handle, bs->bh);
710 		if (error)
711 			goto cleanup;
712 		lock_buffer(bs->bh);
713 
714 		if (header(s->base)->h_refcount == cpu_to_le32(1)) {
715 			if (ce) {
716 				mb_cache_entry_free(ce);
717 				ce = NULL;
718 			}
719 			ea_bdebug(bs->bh, "modifying in-place");
720 			error = ext4_xattr_set_entry(i, s);
721 			if (!error) {
722 				if (!IS_LAST_ENTRY(s->first))
723 					ext4_xattr_rehash(header(s->base),
724 							  s->here);
725 				ext4_xattr_cache_insert(bs->bh);
726 			}
727 			unlock_buffer(bs->bh);
728 			if (error == -EIO)
729 				goto bad_block;
730 			if (!error)
731 				error = ext4_handle_dirty_metadata(handle,
732 								   inode,
733 								   bs->bh);
734 			if (error)
735 				goto cleanup;
736 			goto inserted;
737 		} else {
738 			int offset = (char *)s->here - bs->bh->b_data;
739 
740 			unlock_buffer(bs->bh);
741 			jbd2_journal_release_buffer(handle, bs->bh);
742 			if (ce) {
743 				mb_cache_entry_release(ce);
744 				ce = NULL;
745 			}
746 			ea_bdebug(bs->bh, "cloning");
747 			s->base = kmalloc(bs->bh->b_size, GFP_NOFS);
748 			error = -ENOMEM;
749 			if (s->base == NULL)
750 				goto cleanup;
751 			memcpy(s->base, BHDR(bs->bh), bs->bh->b_size);
752 			s->first = ENTRY(header(s->base)+1);
753 			header(s->base)->h_refcount = cpu_to_le32(1);
754 			s->here = ENTRY(s->base + offset);
755 			s->end = s->base + bs->bh->b_size;
756 		}
757 	} else {
758 		/* Allocate a buffer where we construct the new block. */
759 		s->base = kzalloc(sb->s_blocksize, GFP_NOFS);
760 		/* assert(header == s->base) */
761 		error = -ENOMEM;
762 		if (s->base == NULL)
763 			goto cleanup;
764 		header(s->base)->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
765 		header(s->base)->h_blocks = cpu_to_le32(1);
766 		header(s->base)->h_refcount = cpu_to_le32(1);
767 		s->first = ENTRY(header(s->base)+1);
768 		s->here = ENTRY(header(s->base)+1);
769 		s->end = s->base + sb->s_blocksize;
770 	}
771 
772 	error = ext4_xattr_set_entry(i, s);
773 	if (error == -EIO)
774 		goto bad_block;
775 	if (error)
776 		goto cleanup;
777 	if (!IS_LAST_ENTRY(s->first))
778 		ext4_xattr_rehash(header(s->base), s->here);
779 
780 inserted:
781 	if (!IS_LAST_ENTRY(s->first)) {
782 		new_bh = ext4_xattr_cache_find(inode, header(s->base), &ce);
783 		if (new_bh) {
784 			/* We found an identical block in the cache. */
785 			if (new_bh == bs->bh)
786 				ea_bdebug(new_bh, "keeping");
787 			else {
788 				/* The old block is released after updating
789 				   the inode. */
790 				error = -EDQUOT;
791 				if (vfs_dq_alloc_block(inode, 1))
792 					goto cleanup;
793 				error = ext4_journal_get_write_access(handle,
794 								      new_bh);
795 				if (error)
796 					goto cleanup_dquot;
797 				lock_buffer(new_bh);
798 				le32_add_cpu(&BHDR(new_bh)->h_refcount, 1);
799 				ea_bdebug(new_bh, "reusing; refcount now=%d",
800 					le32_to_cpu(BHDR(new_bh)->h_refcount));
801 				unlock_buffer(new_bh);
802 				error = ext4_handle_dirty_metadata(handle,
803 								   inode,
804 								   new_bh);
805 				if (error)
806 					goto cleanup_dquot;
807 			}
808 			mb_cache_entry_release(ce);
809 			ce = NULL;
810 		} else if (bs->bh && s->base == bs->bh->b_data) {
811 			/* We were modifying this block in-place. */
812 			ea_bdebug(bs->bh, "keeping this block");
813 			new_bh = bs->bh;
814 			get_bh(new_bh);
815 		} else {
816 			/* We need to allocate a new block */
817 			ext4_fsblk_t goal, block;
818 
819 			goal = ext4_group_first_block_no(sb,
820 						EXT4_I(inode)->i_block_group);
821 
822 			/* non-extent files can't have physical blocks past 2^32 */
823 			if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
824 				goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
825 
826 			block = ext4_new_meta_blocks(handle, inode,
827 						  goal, NULL, &error);
828 			if (error)
829 				goto cleanup;
830 
831 			if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
832 				BUG_ON(block > EXT4_MAX_BLOCK_FILE_PHYS);
833 
834 			ea_idebug(inode, "creating block %d", block);
835 
836 			new_bh = sb_getblk(sb, block);
837 			if (!new_bh) {
838 getblk_failed:
839 				ext4_free_blocks(handle, inode, 0, block, 1,
840 						 EXT4_FREE_BLOCKS_METADATA);
841 				error = -EIO;
842 				goto cleanup;
843 			}
844 			lock_buffer(new_bh);
845 			error = ext4_journal_get_create_access(handle, new_bh);
846 			if (error) {
847 				unlock_buffer(new_bh);
848 				goto getblk_failed;
849 			}
850 			memcpy(new_bh->b_data, s->base, new_bh->b_size);
851 			set_buffer_uptodate(new_bh);
852 			unlock_buffer(new_bh);
853 			ext4_xattr_cache_insert(new_bh);
854 			error = ext4_handle_dirty_metadata(handle,
855 							   inode, new_bh);
856 			if (error)
857 				goto cleanup;
858 		}
859 	}
860 
861 	/* Update the inode. */
862 	EXT4_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
863 
864 	/* Drop the previous xattr block. */
865 	if (bs->bh && bs->bh != new_bh)
866 		ext4_xattr_release_block(handle, inode, bs->bh);
867 	error = 0;
868 
869 cleanup:
870 	if (ce)
871 		mb_cache_entry_release(ce);
872 	brelse(new_bh);
873 	if (!(bs->bh && s->base == bs->bh->b_data))
874 		kfree(s->base);
875 
876 	return error;
877 
878 cleanup_dquot:
879 	vfs_dq_free_block(inode, 1);
880 	goto cleanup;
881 
882 bad_block:
883 	ext4_error(inode->i_sb, __func__,
884 		   "inode %lu: bad block %llu", inode->i_ino,
885 		   EXT4_I(inode)->i_file_acl);
886 	goto cleanup;
887 
888 #undef header
889 }
890 
891 struct ext4_xattr_ibody_find {
892 	struct ext4_xattr_search s;
893 	struct ext4_iloc iloc;
894 };
895 
896 static int
897 ext4_xattr_ibody_find(struct inode *inode, struct ext4_xattr_info *i,
898 		      struct ext4_xattr_ibody_find *is)
899 {
900 	struct ext4_xattr_ibody_header *header;
901 	struct ext4_inode *raw_inode;
902 	int error;
903 
904 	if (EXT4_I(inode)->i_extra_isize == 0)
905 		return 0;
906 	raw_inode = ext4_raw_inode(&is->iloc);
907 	header = IHDR(inode, raw_inode);
908 	is->s.base = is->s.first = IFIRST(header);
909 	is->s.here = is->s.first;
910 	is->s.end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
911 	if (EXT4_I(inode)->i_state & EXT4_STATE_XATTR) {
912 		error = ext4_xattr_check_names(IFIRST(header), is->s.end);
913 		if (error)
914 			return error;
915 		/* Find the named attribute. */
916 		error = ext4_xattr_find_entry(&is->s.here, i->name_index,
917 					      i->name, is->s.end -
918 					      (void *)is->s.base, 0);
919 		if (error && error != -ENODATA)
920 			return error;
921 		is->s.not_found = error;
922 	}
923 	return 0;
924 }
925 
926 static int
927 ext4_xattr_ibody_set(handle_t *handle, struct inode *inode,
928 		     struct ext4_xattr_info *i,
929 		     struct ext4_xattr_ibody_find *is)
930 {
931 	struct ext4_xattr_ibody_header *header;
932 	struct ext4_xattr_search *s = &is->s;
933 	int error;
934 
935 	if (EXT4_I(inode)->i_extra_isize == 0)
936 		return -ENOSPC;
937 	error = ext4_xattr_set_entry(i, s);
938 	if (error)
939 		return error;
940 	header = IHDR(inode, ext4_raw_inode(&is->iloc));
941 	if (!IS_LAST_ENTRY(s->first)) {
942 		header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
943 		EXT4_I(inode)->i_state |= EXT4_STATE_XATTR;
944 	} else {
945 		header->h_magic = cpu_to_le32(0);
946 		EXT4_I(inode)->i_state &= ~EXT4_STATE_XATTR;
947 	}
948 	return 0;
949 }
950 
951 /*
952  * ext4_xattr_set_handle()
953  *
954  * Create, replace or remove an extended attribute for this inode. Buffer
955  * is NULL to remove an existing extended attribute, and non-NULL to
956  * either replace an existing extended attribute, or create a new extended
957  * attribute. The flags XATTR_REPLACE and XATTR_CREATE
958  * specify that an extended attribute must exist and must not exist
959  * previous to the call, respectively.
960  *
961  * Returns 0, or a negative error number on failure.
962  */
963 int
964 ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
965 		      const char *name, const void *value, size_t value_len,
966 		      int flags)
967 {
968 	struct ext4_xattr_info i = {
969 		.name_index = name_index,
970 		.name = name,
971 		.value = value,
972 		.value_len = value_len,
973 
974 	};
975 	struct ext4_xattr_ibody_find is = {
976 		.s = { .not_found = -ENODATA, },
977 	};
978 	struct ext4_xattr_block_find bs = {
979 		.s = { .not_found = -ENODATA, },
980 	};
981 	unsigned long no_expand;
982 	int error;
983 
984 	if (!name)
985 		return -EINVAL;
986 	if (strlen(name) > 255)
987 		return -ERANGE;
988 	down_write(&EXT4_I(inode)->xattr_sem);
989 	no_expand = EXT4_I(inode)->i_state & EXT4_STATE_NO_EXPAND;
990 	EXT4_I(inode)->i_state |= EXT4_STATE_NO_EXPAND;
991 
992 	error = ext4_get_inode_loc(inode, &is.iloc);
993 	if (error)
994 		goto cleanup;
995 
996 	error = ext4_journal_get_write_access(handle, is.iloc.bh);
997 	if (error)
998 		goto cleanup;
999 
1000 	if (EXT4_I(inode)->i_state & EXT4_STATE_NEW) {
1001 		struct ext4_inode *raw_inode = ext4_raw_inode(&is.iloc);
1002 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
1003 		EXT4_I(inode)->i_state &= ~EXT4_STATE_NEW;
1004 	}
1005 
1006 	error = ext4_xattr_ibody_find(inode, &i, &is);
1007 	if (error)
1008 		goto cleanup;
1009 	if (is.s.not_found)
1010 		error = ext4_xattr_block_find(inode, &i, &bs);
1011 	if (error)
1012 		goto cleanup;
1013 	if (is.s.not_found && bs.s.not_found) {
1014 		error = -ENODATA;
1015 		if (flags & XATTR_REPLACE)
1016 			goto cleanup;
1017 		error = 0;
1018 		if (!value)
1019 			goto cleanup;
1020 	} else {
1021 		error = -EEXIST;
1022 		if (flags & XATTR_CREATE)
1023 			goto cleanup;
1024 	}
1025 	if (!value) {
1026 		if (!is.s.not_found)
1027 			error = ext4_xattr_ibody_set(handle, inode, &i, &is);
1028 		else if (!bs.s.not_found)
1029 			error = ext4_xattr_block_set(handle, inode, &i, &bs);
1030 	} else {
1031 		error = ext4_xattr_ibody_set(handle, inode, &i, &is);
1032 		if (!error && !bs.s.not_found) {
1033 			i.value = NULL;
1034 			error = ext4_xattr_block_set(handle, inode, &i, &bs);
1035 		} else if (error == -ENOSPC) {
1036 			if (EXT4_I(inode)->i_file_acl && !bs.s.base) {
1037 				error = ext4_xattr_block_find(inode, &i, &bs);
1038 				if (error)
1039 					goto cleanup;
1040 			}
1041 			error = ext4_xattr_block_set(handle, inode, &i, &bs);
1042 			if (error)
1043 				goto cleanup;
1044 			if (!is.s.not_found) {
1045 				i.value = NULL;
1046 				error = ext4_xattr_ibody_set(handle, inode, &i,
1047 							     &is);
1048 			}
1049 		}
1050 	}
1051 	if (!error) {
1052 		ext4_xattr_update_super_block(handle, inode->i_sb);
1053 		inode->i_ctime = ext4_current_time(inode);
1054 		if (!value)
1055 			EXT4_I(inode)->i_state &= ~EXT4_STATE_NO_EXPAND;
1056 		error = ext4_mark_iloc_dirty(handle, inode, &is.iloc);
1057 		/*
1058 		 * The bh is consumed by ext4_mark_iloc_dirty, even with
1059 		 * error != 0.
1060 		 */
1061 		is.iloc.bh = NULL;
1062 		if (IS_SYNC(inode))
1063 			ext4_handle_sync(handle);
1064 	}
1065 
1066 cleanup:
1067 	brelse(is.iloc.bh);
1068 	brelse(bs.bh);
1069 	if (no_expand == 0)
1070 		EXT4_I(inode)->i_state &= ~EXT4_STATE_NO_EXPAND;
1071 	up_write(&EXT4_I(inode)->xattr_sem);
1072 	return error;
1073 }
1074 
1075 /*
1076  * ext4_xattr_set()
1077  *
1078  * Like ext4_xattr_set_handle, but start from an inode. This extended
1079  * attribute modification is a filesystem transaction by itself.
1080  *
1081  * Returns 0, or a negative error number on failure.
1082  */
1083 int
1084 ext4_xattr_set(struct inode *inode, int name_index, const char *name,
1085 	       const void *value, size_t value_len, int flags)
1086 {
1087 	handle_t *handle;
1088 	int error, retries = 0;
1089 
1090 retry:
1091 	handle = ext4_journal_start(inode, EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
1092 	if (IS_ERR(handle)) {
1093 		error = PTR_ERR(handle);
1094 	} else {
1095 		int error2;
1096 
1097 		error = ext4_xattr_set_handle(handle, inode, name_index, name,
1098 					      value, value_len, flags);
1099 		error2 = ext4_journal_stop(handle);
1100 		if (error == -ENOSPC &&
1101 		    ext4_should_retry_alloc(inode->i_sb, &retries))
1102 			goto retry;
1103 		if (error == 0)
1104 			error = error2;
1105 	}
1106 
1107 	return error;
1108 }
1109 
1110 /*
1111  * Shift the EA entries in the inode to create space for the increased
1112  * i_extra_isize.
1113  */
1114 static void ext4_xattr_shift_entries(struct ext4_xattr_entry *entry,
1115 				     int value_offs_shift, void *to,
1116 				     void *from, size_t n, int blocksize)
1117 {
1118 	struct ext4_xattr_entry *last = entry;
1119 	int new_offs;
1120 
1121 	/* Adjust the value offsets of the entries */
1122 	for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
1123 		if (!last->e_value_block && last->e_value_size) {
1124 			new_offs = le16_to_cpu(last->e_value_offs) +
1125 							value_offs_shift;
1126 			BUG_ON(new_offs + le32_to_cpu(last->e_value_size)
1127 				 > blocksize);
1128 			last->e_value_offs = cpu_to_le16(new_offs);
1129 		}
1130 	}
1131 	/* Shift the entries by n bytes */
1132 	memmove(to, from, n);
1133 }
1134 
1135 /*
1136  * Expand an inode by new_extra_isize bytes when EAs are present.
1137  * Returns 0 on success or negative error number on failure.
1138  */
1139 int ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize,
1140 			       struct ext4_inode *raw_inode, handle_t *handle)
1141 {
1142 	struct ext4_xattr_ibody_header *header;
1143 	struct ext4_xattr_entry *entry, *last, *first;
1144 	struct buffer_head *bh = NULL;
1145 	struct ext4_xattr_ibody_find *is = NULL;
1146 	struct ext4_xattr_block_find *bs = NULL;
1147 	char *buffer = NULL, *b_entry_name = NULL;
1148 	size_t min_offs, free;
1149 	int total_ino, total_blk;
1150 	void *base, *start, *end;
1151 	int extra_isize = 0, error = 0, tried_min_extra_isize = 0;
1152 	int s_min_extra_isize = le16_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_min_extra_isize);
1153 
1154 	down_write(&EXT4_I(inode)->xattr_sem);
1155 retry:
1156 	if (EXT4_I(inode)->i_extra_isize >= new_extra_isize) {
1157 		up_write(&EXT4_I(inode)->xattr_sem);
1158 		return 0;
1159 	}
1160 
1161 	header = IHDR(inode, raw_inode);
1162 	entry = IFIRST(header);
1163 
1164 	/*
1165 	 * Check if enough free space is available in the inode to shift the
1166 	 * entries ahead by new_extra_isize.
1167 	 */
1168 
1169 	base = start = entry;
1170 	end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
1171 	min_offs = end - base;
1172 	last = entry;
1173 	total_ino = sizeof(struct ext4_xattr_ibody_header);
1174 
1175 	free = ext4_xattr_free_space(last, &min_offs, base, &total_ino);
1176 	if (free >= new_extra_isize) {
1177 		entry = IFIRST(header);
1178 		ext4_xattr_shift_entries(entry,	EXT4_I(inode)->i_extra_isize
1179 				- new_extra_isize, (void *)raw_inode +
1180 				EXT4_GOOD_OLD_INODE_SIZE + new_extra_isize,
1181 				(void *)header, total_ino,
1182 				inode->i_sb->s_blocksize);
1183 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
1184 		error = 0;
1185 		goto cleanup;
1186 	}
1187 
1188 	/*
1189 	 * Enough free space isn't available in the inode, check if
1190 	 * EA block can hold new_extra_isize bytes.
1191 	 */
1192 	if (EXT4_I(inode)->i_file_acl) {
1193 		bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
1194 		error = -EIO;
1195 		if (!bh)
1196 			goto cleanup;
1197 		if (ext4_xattr_check_block(bh)) {
1198 			ext4_error(inode->i_sb, __func__,
1199 				"inode %lu: bad block %llu", inode->i_ino,
1200 				EXT4_I(inode)->i_file_acl);
1201 			error = -EIO;
1202 			goto cleanup;
1203 		}
1204 		base = BHDR(bh);
1205 		first = BFIRST(bh);
1206 		end = bh->b_data + bh->b_size;
1207 		min_offs = end - base;
1208 		free = ext4_xattr_free_space(first, &min_offs, base,
1209 					     &total_blk);
1210 		if (free < new_extra_isize) {
1211 			if (!tried_min_extra_isize && s_min_extra_isize) {
1212 				tried_min_extra_isize++;
1213 				new_extra_isize = s_min_extra_isize;
1214 				brelse(bh);
1215 				goto retry;
1216 			}
1217 			error = -1;
1218 			goto cleanup;
1219 		}
1220 	} else {
1221 		free = inode->i_sb->s_blocksize;
1222 	}
1223 
1224 	while (new_extra_isize > 0) {
1225 		size_t offs, size, entry_size;
1226 		struct ext4_xattr_entry *small_entry = NULL;
1227 		struct ext4_xattr_info i = {
1228 			.value = NULL,
1229 			.value_len = 0,
1230 		};
1231 		unsigned int total_size;  /* EA entry size + value size */
1232 		unsigned int shift_bytes; /* No. of bytes to shift EAs by? */
1233 		unsigned int min_total_size = ~0U;
1234 
1235 		is = kzalloc(sizeof(struct ext4_xattr_ibody_find), GFP_NOFS);
1236 		bs = kzalloc(sizeof(struct ext4_xattr_block_find), GFP_NOFS);
1237 		if (!is || !bs) {
1238 			error = -ENOMEM;
1239 			goto cleanup;
1240 		}
1241 
1242 		is->s.not_found = -ENODATA;
1243 		bs->s.not_found = -ENODATA;
1244 		is->iloc.bh = NULL;
1245 		bs->bh = NULL;
1246 
1247 		last = IFIRST(header);
1248 		/* Find the entry best suited to be pushed into EA block */
1249 		entry = NULL;
1250 		for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
1251 			total_size =
1252 			EXT4_XATTR_SIZE(le32_to_cpu(last->e_value_size)) +
1253 					EXT4_XATTR_LEN(last->e_name_len);
1254 			if (total_size <= free && total_size < min_total_size) {
1255 				if (total_size < new_extra_isize) {
1256 					small_entry = last;
1257 				} else {
1258 					entry = last;
1259 					min_total_size = total_size;
1260 				}
1261 			}
1262 		}
1263 
1264 		if (entry == NULL) {
1265 			if (small_entry) {
1266 				entry = small_entry;
1267 			} else {
1268 				if (!tried_min_extra_isize &&
1269 				    s_min_extra_isize) {
1270 					tried_min_extra_isize++;
1271 					new_extra_isize = s_min_extra_isize;
1272 					goto retry;
1273 				}
1274 				error = -1;
1275 				goto cleanup;
1276 			}
1277 		}
1278 		offs = le16_to_cpu(entry->e_value_offs);
1279 		size = le32_to_cpu(entry->e_value_size);
1280 		entry_size = EXT4_XATTR_LEN(entry->e_name_len);
1281 		i.name_index = entry->e_name_index,
1282 		buffer = kmalloc(EXT4_XATTR_SIZE(size), GFP_NOFS);
1283 		b_entry_name = kmalloc(entry->e_name_len + 1, GFP_NOFS);
1284 		if (!buffer || !b_entry_name) {
1285 			error = -ENOMEM;
1286 			goto cleanup;
1287 		}
1288 		/* Save the entry name and the entry value */
1289 		memcpy(buffer, (void *)IFIRST(header) + offs,
1290 		       EXT4_XATTR_SIZE(size));
1291 		memcpy(b_entry_name, entry->e_name, entry->e_name_len);
1292 		b_entry_name[entry->e_name_len] = '\0';
1293 		i.name = b_entry_name;
1294 
1295 		error = ext4_get_inode_loc(inode, &is->iloc);
1296 		if (error)
1297 			goto cleanup;
1298 
1299 		error = ext4_xattr_ibody_find(inode, &i, is);
1300 		if (error)
1301 			goto cleanup;
1302 
1303 		/* Remove the chosen entry from the inode */
1304 		error = ext4_xattr_ibody_set(handle, inode, &i, is);
1305 
1306 		entry = IFIRST(header);
1307 		if (entry_size + EXT4_XATTR_SIZE(size) >= new_extra_isize)
1308 			shift_bytes = new_extra_isize;
1309 		else
1310 			shift_bytes = entry_size + size;
1311 		/* Adjust the offsets and shift the remaining entries ahead */
1312 		ext4_xattr_shift_entries(entry, EXT4_I(inode)->i_extra_isize -
1313 			shift_bytes, (void *)raw_inode +
1314 			EXT4_GOOD_OLD_INODE_SIZE + extra_isize + shift_bytes,
1315 			(void *)header, total_ino - entry_size,
1316 			inode->i_sb->s_blocksize);
1317 
1318 		extra_isize += shift_bytes;
1319 		new_extra_isize -= shift_bytes;
1320 		EXT4_I(inode)->i_extra_isize = extra_isize;
1321 
1322 		i.name = b_entry_name;
1323 		i.value = buffer;
1324 		i.value_len = size;
1325 		error = ext4_xattr_block_find(inode, &i, bs);
1326 		if (error)
1327 			goto cleanup;
1328 
1329 		/* Add entry which was removed from the inode into the block */
1330 		error = ext4_xattr_block_set(handle, inode, &i, bs);
1331 		if (error)
1332 			goto cleanup;
1333 		kfree(b_entry_name);
1334 		kfree(buffer);
1335 		b_entry_name = NULL;
1336 		buffer = NULL;
1337 		brelse(is->iloc.bh);
1338 		kfree(is);
1339 		kfree(bs);
1340 	}
1341 	brelse(bh);
1342 	up_write(&EXT4_I(inode)->xattr_sem);
1343 	return 0;
1344 
1345 cleanup:
1346 	kfree(b_entry_name);
1347 	kfree(buffer);
1348 	if (is)
1349 		brelse(is->iloc.bh);
1350 	kfree(is);
1351 	kfree(bs);
1352 	brelse(bh);
1353 	up_write(&EXT4_I(inode)->xattr_sem);
1354 	return error;
1355 }
1356 
1357 
1358 
1359 /*
1360  * ext4_xattr_delete_inode()
1361  *
1362  * Free extended attribute resources associated with this inode. This
1363  * is called immediately before an inode is freed. We have exclusive
1364  * access to the inode.
1365  */
1366 void
1367 ext4_xattr_delete_inode(handle_t *handle, struct inode *inode)
1368 {
1369 	struct buffer_head *bh = NULL;
1370 
1371 	if (!EXT4_I(inode)->i_file_acl)
1372 		goto cleanup;
1373 	bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
1374 	if (!bh) {
1375 		ext4_error(inode->i_sb, __func__,
1376 			"inode %lu: block %llu read error", inode->i_ino,
1377 			EXT4_I(inode)->i_file_acl);
1378 		goto cleanup;
1379 	}
1380 	if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
1381 	    BHDR(bh)->h_blocks != cpu_to_le32(1)) {
1382 		ext4_error(inode->i_sb, __func__,
1383 			"inode %lu: bad block %llu", inode->i_ino,
1384 			EXT4_I(inode)->i_file_acl);
1385 		goto cleanup;
1386 	}
1387 	ext4_xattr_release_block(handle, inode, bh);
1388 	EXT4_I(inode)->i_file_acl = 0;
1389 
1390 cleanup:
1391 	brelse(bh);
1392 }
1393 
1394 /*
1395  * ext4_xattr_put_super()
1396  *
1397  * This is called when a file system is unmounted.
1398  */
1399 void
1400 ext4_xattr_put_super(struct super_block *sb)
1401 {
1402 	mb_cache_shrink(sb->s_bdev);
1403 }
1404 
1405 /*
1406  * ext4_xattr_cache_insert()
1407  *
1408  * Create a new entry in the extended attribute cache, and insert
1409  * it unless such an entry is already in the cache.
1410  *
1411  * Returns 0, or a negative error number on failure.
1412  */
1413 static void
1414 ext4_xattr_cache_insert(struct buffer_head *bh)
1415 {
1416 	__u32 hash = le32_to_cpu(BHDR(bh)->h_hash);
1417 	struct mb_cache_entry *ce;
1418 	int error;
1419 
1420 	ce = mb_cache_entry_alloc(ext4_xattr_cache, GFP_NOFS);
1421 	if (!ce) {
1422 		ea_bdebug(bh, "out of memory");
1423 		return;
1424 	}
1425 	error = mb_cache_entry_insert(ce, bh->b_bdev, bh->b_blocknr, &hash);
1426 	if (error) {
1427 		mb_cache_entry_free(ce);
1428 		if (error == -EBUSY) {
1429 			ea_bdebug(bh, "already in cache");
1430 			error = 0;
1431 		}
1432 	} else {
1433 		ea_bdebug(bh, "inserting [%x]", (int)hash);
1434 		mb_cache_entry_release(ce);
1435 	}
1436 }
1437 
1438 /*
1439  * ext4_xattr_cmp()
1440  *
1441  * Compare two extended attribute blocks for equality.
1442  *
1443  * Returns 0 if the blocks are equal, 1 if they differ, and
1444  * a negative error number on errors.
1445  */
1446 static int
1447 ext4_xattr_cmp(struct ext4_xattr_header *header1,
1448 	       struct ext4_xattr_header *header2)
1449 {
1450 	struct ext4_xattr_entry *entry1, *entry2;
1451 
1452 	entry1 = ENTRY(header1+1);
1453 	entry2 = ENTRY(header2+1);
1454 	while (!IS_LAST_ENTRY(entry1)) {
1455 		if (IS_LAST_ENTRY(entry2))
1456 			return 1;
1457 		if (entry1->e_hash != entry2->e_hash ||
1458 		    entry1->e_name_index != entry2->e_name_index ||
1459 		    entry1->e_name_len != entry2->e_name_len ||
1460 		    entry1->e_value_size != entry2->e_value_size ||
1461 		    memcmp(entry1->e_name, entry2->e_name, entry1->e_name_len))
1462 			return 1;
1463 		if (entry1->e_value_block != 0 || entry2->e_value_block != 0)
1464 			return -EIO;
1465 		if (memcmp((char *)header1 + le16_to_cpu(entry1->e_value_offs),
1466 			   (char *)header2 + le16_to_cpu(entry2->e_value_offs),
1467 			   le32_to_cpu(entry1->e_value_size)))
1468 			return 1;
1469 
1470 		entry1 = EXT4_XATTR_NEXT(entry1);
1471 		entry2 = EXT4_XATTR_NEXT(entry2);
1472 	}
1473 	if (!IS_LAST_ENTRY(entry2))
1474 		return 1;
1475 	return 0;
1476 }
1477 
1478 /*
1479  * ext4_xattr_cache_find()
1480  *
1481  * Find an identical extended attribute block.
1482  *
1483  * Returns a pointer to the block found, or NULL if such a block was
1484  * not found or an error occurred.
1485  */
1486 static struct buffer_head *
1487 ext4_xattr_cache_find(struct inode *inode, struct ext4_xattr_header *header,
1488 		      struct mb_cache_entry **pce)
1489 {
1490 	__u32 hash = le32_to_cpu(header->h_hash);
1491 	struct mb_cache_entry *ce;
1492 
1493 	if (!header->h_hash)
1494 		return NULL;  /* never share */
1495 	ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
1496 again:
1497 	ce = mb_cache_entry_find_first(ext4_xattr_cache, 0,
1498 				       inode->i_sb->s_bdev, hash);
1499 	while (ce) {
1500 		struct buffer_head *bh;
1501 
1502 		if (IS_ERR(ce)) {
1503 			if (PTR_ERR(ce) == -EAGAIN)
1504 				goto again;
1505 			break;
1506 		}
1507 		bh = sb_bread(inode->i_sb, ce->e_block);
1508 		if (!bh) {
1509 			ext4_error(inode->i_sb, __func__,
1510 				"inode %lu: block %lu read error",
1511 				inode->i_ino, (unsigned long) ce->e_block);
1512 		} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
1513 				EXT4_XATTR_REFCOUNT_MAX) {
1514 			ea_idebug(inode, "block %lu refcount %d>=%d",
1515 				  (unsigned long) ce->e_block,
1516 				  le32_to_cpu(BHDR(bh)->h_refcount),
1517 					  EXT4_XATTR_REFCOUNT_MAX);
1518 		} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
1519 			*pce = ce;
1520 			return bh;
1521 		}
1522 		brelse(bh);
1523 		ce = mb_cache_entry_find_next(ce, 0, inode->i_sb->s_bdev, hash);
1524 	}
1525 	return NULL;
1526 }
1527 
1528 #define NAME_HASH_SHIFT 5
1529 #define VALUE_HASH_SHIFT 16
1530 
1531 /*
1532  * ext4_xattr_hash_entry()
1533  *
1534  * Compute the hash of an extended attribute.
1535  */
1536 static inline void ext4_xattr_hash_entry(struct ext4_xattr_header *header,
1537 					 struct ext4_xattr_entry *entry)
1538 {
1539 	__u32 hash = 0;
1540 	char *name = entry->e_name;
1541 	int n;
1542 
1543 	for (n = 0; n < entry->e_name_len; n++) {
1544 		hash = (hash << NAME_HASH_SHIFT) ^
1545 		       (hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
1546 		       *name++;
1547 	}
1548 
1549 	if (entry->e_value_block == 0 && entry->e_value_size != 0) {
1550 		__le32 *value = (__le32 *)((char *)header +
1551 			le16_to_cpu(entry->e_value_offs));
1552 		for (n = (le32_to_cpu(entry->e_value_size) +
1553 		     EXT4_XATTR_ROUND) >> EXT4_XATTR_PAD_BITS; n; n--) {
1554 			hash = (hash << VALUE_HASH_SHIFT) ^
1555 			       (hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
1556 			       le32_to_cpu(*value++);
1557 		}
1558 	}
1559 	entry->e_hash = cpu_to_le32(hash);
1560 }
1561 
1562 #undef NAME_HASH_SHIFT
1563 #undef VALUE_HASH_SHIFT
1564 
1565 #define BLOCK_HASH_SHIFT 16
1566 
1567 /*
1568  * ext4_xattr_rehash()
1569  *
1570  * Re-compute the extended attribute hash value after an entry has changed.
1571  */
1572 static void ext4_xattr_rehash(struct ext4_xattr_header *header,
1573 			      struct ext4_xattr_entry *entry)
1574 {
1575 	struct ext4_xattr_entry *here;
1576 	__u32 hash = 0;
1577 
1578 	ext4_xattr_hash_entry(header, entry);
1579 	here = ENTRY(header+1);
1580 	while (!IS_LAST_ENTRY(here)) {
1581 		if (!here->e_hash) {
1582 			/* Block is not shared if an entry's hash value == 0 */
1583 			hash = 0;
1584 			break;
1585 		}
1586 		hash = (hash << BLOCK_HASH_SHIFT) ^
1587 		       (hash >> (8*sizeof(hash) - BLOCK_HASH_SHIFT)) ^
1588 		       le32_to_cpu(here->e_hash);
1589 		here = EXT4_XATTR_NEXT(here);
1590 	}
1591 	header->h_hash = cpu_to_le32(hash);
1592 }
1593 
1594 #undef BLOCK_HASH_SHIFT
1595 
1596 int __init
1597 init_ext4_xattr(void)
1598 {
1599 	ext4_xattr_cache = mb_cache_create("ext4_xattr", NULL,
1600 		sizeof(struct mb_cache_entry) +
1601 		sizeof(((struct mb_cache_entry *) 0)->e_indexes[0]), 1, 6);
1602 	if (!ext4_xattr_cache)
1603 		return -ENOMEM;
1604 	return 0;
1605 }
1606 
1607 void
1608 exit_ext4_xattr(void)
1609 {
1610 	if (ext4_xattr_cache)
1611 		mb_cache_destroy(ext4_xattr_cache);
1612 	ext4_xattr_cache = NULL;
1613 }
1614