xref: /openbmc/linux/fs/ext2/xattr.c (revision 6c71b489)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * linux/fs/ext2/xattr.c
4  *
5  * Copyright (C) 2001-2003 Andreas Gruenbacher <agruen@suse.de>
6  *
7  * Fix by Harrison Xing <harrison@mountainviewdata.com>.
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  *
13  */
14 
15 /*
16  * Extended attributes are stored on disk blocks allocated outside of
17  * any inode. The i_file_acl field is then made to point to this allocated
18  * block. If all extended attributes of an inode are identical, these
19  * inodes may share the same extended attribute block. Such situations
20  * are automatically detected by keeping a cache of recent attribute block
21  * numbers and hashes over the block's contents in memory.
22  *
23  *
24  * Extended attribute block layout:
25  *
26  *   +------------------+
27  *   | header           |
28  *   | entry 1          | |
29  *   | entry 2          | | growing downwards
30  *   | entry 3          | v
31  *   | four null bytes  |
32  *   | . . .            |
33  *   | value 1          | ^
34  *   | value 3          | | growing upwards
35  *   | value 2          | |
36  *   +------------------+
37  *
38  * The block header is followed by multiple entry descriptors. These entry
39  * descriptors are variable in size, and aligned to EXT2_XATTR_PAD
40  * byte boundaries. The entry descriptors are sorted by attribute name,
41  * so that two extended attribute blocks can be compared efficiently.
42  *
43  * Attribute values are aligned to the end of the block, stored in
44  * no specific order. They are also padded to EXT2_XATTR_PAD byte
45  * boundaries. No additional gaps are left between them.
46  *
47  * Locking strategy
48  * ----------------
49  * EXT2_I(inode)->i_file_acl is protected by EXT2_I(inode)->xattr_sem.
50  * EA blocks are only changed if they are exclusive to an inode, so
51  * holding xattr_sem also means that nothing but the EA block's reference
52  * count will change. Multiple writers to an EA block are synchronized
53  * by the bh lock. No more than a single bh lock is held at any time
54  * to avoid deadlocks.
55  */
56 
57 #include <linux/buffer_head.h>
58 #include <linux/init.h>
59 #include <linux/slab.h>
60 #include <linux/mbcache.h>
61 #include <linux/quotaops.h>
62 #include <linux/rwsem.h>
63 #include <linux/security.h>
64 #include "ext2.h"
65 #include "xattr.h"
66 #include "acl.h"
67 
68 #define HDR(bh) ((struct ext2_xattr_header *)((bh)->b_data))
69 #define ENTRY(ptr) ((struct ext2_xattr_entry *)(ptr))
70 #define FIRST_ENTRY(bh) ENTRY(HDR(bh)+1)
71 #define IS_LAST_ENTRY(entry) (*(__u32 *)(entry) == 0)
72 
73 #ifdef EXT2_XATTR_DEBUG
74 # define ea_idebug(inode, f...) do { \
75 		printk(KERN_DEBUG "inode %s:%ld: ", \
76 			inode->i_sb->s_id, inode->i_ino); \
77 		printk(f); \
78 		printk("\n"); \
79 	} while (0)
80 # define ea_bdebug(bh, f...) do { \
81 		printk(KERN_DEBUG "block %pg:%lu: ", \
82 			bh->b_bdev, (unsigned long) bh->b_blocknr); \
83 		printk(f); \
84 		printk("\n"); \
85 	} while (0)
86 #else
87 # define ea_idebug(f...)
88 # define ea_bdebug(f...)
89 #endif
90 
91 static int ext2_xattr_set2(struct inode *, struct buffer_head *,
92 			   struct ext2_xattr_header *);
93 
94 static int ext2_xattr_cache_insert(struct mb_cache *, struct buffer_head *);
95 static struct buffer_head *ext2_xattr_cache_find(struct inode *,
96 						 struct ext2_xattr_header *);
97 static void ext2_xattr_rehash(struct ext2_xattr_header *,
98 			      struct ext2_xattr_entry *);
99 
100 static const struct xattr_handler *ext2_xattr_handler_map[] = {
101 	[EXT2_XATTR_INDEX_USER]		     = &ext2_xattr_user_handler,
102 #ifdef CONFIG_EXT2_FS_POSIX_ACL
103 	[EXT2_XATTR_INDEX_POSIX_ACL_ACCESS]  = &posix_acl_access_xattr_handler,
104 	[EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT] = &posix_acl_default_xattr_handler,
105 #endif
106 	[EXT2_XATTR_INDEX_TRUSTED]	     = &ext2_xattr_trusted_handler,
107 #ifdef CONFIG_EXT2_FS_SECURITY
108 	[EXT2_XATTR_INDEX_SECURITY]	     = &ext2_xattr_security_handler,
109 #endif
110 };
111 
112 const struct xattr_handler *ext2_xattr_handlers[] = {
113 	&ext2_xattr_user_handler,
114 	&ext2_xattr_trusted_handler,
115 #ifdef CONFIG_EXT2_FS_POSIX_ACL
116 	&posix_acl_access_xattr_handler,
117 	&posix_acl_default_xattr_handler,
118 #endif
119 #ifdef CONFIG_EXT2_FS_SECURITY
120 	&ext2_xattr_security_handler,
121 #endif
122 	NULL
123 };
124 
125 #define EA_BLOCK_CACHE(inode)	(EXT2_SB(inode->i_sb)->s_ea_block_cache)
126 
127 static inline const struct xattr_handler *
128 ext2_xattr_handler(int name_index)
129 {
130 	const struct xattr_handler *handler = NULL;
131 
132 	if (name_index > 0 && name_index < ARRAY_SIZE(ext2_xattr_handler_map))
133 		handler = ext2_xattr_handler_map[name_index];
134 	return handler;
135 }
136 
137 static bool
138 ext2_xattr_header_valid(struct ext2_xattr_header *header)
139 {
140 	if (header->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) ||
141 	    header->h_blocks != cpu_to_le32(1))
142 		return false;
143 
144 	return true;
145 }
146 
147 static bool
148 ext2_xattr_entry_valid(struct ext2_xattr_entry *entry, size_t end_offs)
149 {
150 	size_t size;
151 
152 	if (entry->e_value_block != 0)
153 		return false;
154 
155 	size = le32_to_cpu(entry->e_value_size);
156 	if (size > end_offs ||
157 	    le16_to_cpu(entry->e_value_offs) + size > end_offs)
158 		return false;
159 
160 	return true;
161 }
162 
163 /*
164  * ext2_xattr_get()
165  *
166  * Copy an extended attribute into the buffer
167  * provided, or compute the buffer size required.
168  * Buffer is NULL to compute the size of the buffer required.
169  *
170  * Returns a negative error number on failure, or the number of bytes
171  * used / required on success.
172  */
173 int
174 ext2_xattr_get(struct inode *inode, int name_index, const char *name,
175 	       void *buffer, size_t buffer_size)
176 {
177 	struct buffer_head *bh = NULL;
178 	struct ext2_xattr_entry *entry;
179 	size_t name_len, size;
180 	char *end;
181 	int error;
182 	struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
183 
184 	ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
185 		  name_index, name, buffer, (long)buffer_size);
186 
187 	if (name == NULL)
188 		return -EINVAL;
189 	name_len = strlen(name);
190 	if (name_len > 255)
191 		return -ERANGE;
192 
193 	down_read(&EXT2_I(inode)->xattr_sem);
194 	error = -ENODATA;
195 	if (!EXT2_I(inode)->i_file_acl)
196 		goto cleanup;
197 	ea_idebug(inode, "reading block %d", EXT2_I(inode)->i_file_acl);
198 	bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl);
199 	error = -EIO;
200 	if (!bh)
201 		goto cleanup;
202 	ea_bdebug(bh, "b_count=%d, refcount=%d",
203 		atomic_read(&(bh->b_count)), le32_to_cpu(HDR(bh)->h_refcount));
204 	end = bh->b_data + bh->b_size;
205 	if (!ext2_xattr_header_valid(HDR(bh))) {
206 bad_block:
207 		ext2_error(inode->i_sb, "ext2_xattr_get",
208 			"inode %ld: bad block %d", inode->i_ino,
209 			EXT2_I(inode)->i_file_acl);
210 		error = -EIO;
211 		goto cleanup;
212 	}
213 
214 	/* find named attribute */
215 	entry = FIRST_ENTRY(bh);
216 	while (!IS_LAST_ENTRY(entry)) {
217 		struct ext2_xattr_entry *next =
218 			EXT2_XATTR_NEXT(entry);
219 		if ((char *)next >= end)
220 			goto bad_block;
221 		if (!ext2_xattr_entry_valid(entry, inode->i_sb->s_blocksize))
222 			goto bad_block;
223 		if (name_index == entry->e_name_index &&
224 		    name_len == entry->e_name_len &&
225 		    memcmp(name, entry->e_name, name_len) == 0)
226 			goto found;
227 		entry = next;
228 	}
229 	if (ext2_xattr_cache_insert(ea_block_cache, bh))
230 		ea_idebug(inode, "cache insert failed");
231 	error = -ENODATA;
232 	goto cleanup;
233 found:
234 	size = le32_to_cpu(entry->e_value_size);
235 	if (ext2_xattr_cache_insert(ea_block_cache, bh))
236 		ea_idebug(inode, "cache insert failed");
237 	if (buffer) {
238 		error = -ERANGE;
239 		if (size > buffer_size)
240 			goto cleanup;
241 		/* return value of attribute */
242 		memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs),
243 			size);
244 	}
245 	error = size;
246 
247 cleanup:
248 	brelse(bh);
249 	up_read(&EXT2_I(inode)->xattr_sem);
250 
251 	return error;
252 }
253 
254 /*
255  * ext2_xattr_list()
256  *
257  * Copy a list of attribute names into the buffer
258  * provided, or compute the buffer size required.
259  * Buffer is NULL to compute the size of the buffer required.
260  *
261  * Returns a negative error number on failure, or the number of bytes
262  * used / required on success.
263  */
264 static int
265 ext2_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size)
266 {
267 	struct inode *inode = d_inode(dentry);
268 	struct buffer_head *bh = NULL;
269 	struct ext2_xattr_entry *entry;
270 	char *end;
271 	size_t rest = buffer_size;
272 	int error;
273 	struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
274 
275 	ea_idebug(inode, "buffer=%p, buffer_size=%ld",
276 		  buffer, (long)buffer_size);
277 
278 	down_read(&EXT2_I(inode)->xattr_sem);
279 	error = 0;
280 	if (!EXT2_I(inode)->i_file_acl)
281 		goto cleanup;
282 	ea_idebug(inode, "reading block %d", EXT2_I(inode)->i_file_acl);
283 	bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl);
284 	error = -EIO;
285 	if (!bh)
286 		goto cleanup;
287 	ea_bdebug(bh, "b_count=%d, refcount=%d",
288 		atomic_read(&(bh->b_count)), le32_to_cpu(HDR(bh)->h_refcount));
289 	end = bh->b_data + bh->b_size;
290 	if (!ext2_xattr_header_valid(HDR(bh))) {
291 bad_block:
292 		ext2_error(inode->i_sb, "ext2_xattr_list",
293 			"inode %ld: bad block %d", inode->i_ino,
294 			EXT2_I(inode)->i_file_acl);
295 		error = -EIO;
296 		goto cleanup;
297 	}
298 
299 	/* check the on-disk data structure */
300 	entry = FIRST_ENTRY(bh);
301 	while (!IS_LAST_ENTRY(entry)) {
302 		struct ext2_xattr_entry *next = EXT2_XATTR_NEXT(entry);
303 
304 		if ((char *)next >= end)
305 			goto bad_block;
306 		if (!ext2_xattr_entry_valid(entry, inode->i_sb->s_blocksize))
307 			goto bad_block;
308 		entry = next;
309 	}
310 	if (ext2_xattr_cache_insert(ea_block_cache, bh))
311 		ea_idebug(inode, "cache insert failed");
312 
313 	/* list the attribute names */
314 	for (entry = FIRST_ENTRY(bh); !IS_LAST_ENTRY(entry);
315 	     entry = EXT2_XATTR_NEXT(entry)) {
316 		const struct xattr_handler *handler =
317 			ext2_xattr_handler(entry->e_name_index);
318 
319 		if (handler && (!handler->list || handler->list(dentry))) {
320 			const char *prefix = handler->prefix ?: handler->name;
321 			size_t prefix_len = strlen(prefix);
322 			size_t size = prefix_len + entry->e_name_len + 1;
323 
324 			if (buffer) {
325 				if (size > rest) {
326 					error = -ERANGE;
327 					goto cleanup;
328 				}
329 				memcpy(buffer, prefix, prefix_len);
330 				buffer += prefix_len;
331 				memcpy(buffer, entry->e_name, entry->e_name_len);
332 				buffer += entry->e_name_len;
333 				*buffer++ = 0;
334 			}
335 			rest -= size;
336 		}
337 	}
338 	error = buffer_size - rest;  /* total size */
339 
340 cleanup:
341 	brelse(bh);
342 	up_read(&EXT2_I(inode)->xattr_sem);
343 
344 	return error;
345 }
346 
347 /*
348  * Inode operation listxattr()
349  *
350  * d_inode(dentry)->i_mutex: don't care
351  */
352 ssize_t
353 ext2_listxattr(struct dentry *dentry, char *buffer, size_t size)
354 {
355 	return ext2_xattr_list(dentry, buffer, size);
356 }
357 
358 /*
359  * If the EXT2_FEATURE_COMPAT_EXT_ATTR feature of this file system is
360  * not set, set it.
361  */
362 static void ext2_xattr_update_super_block(struct super_block *sb)
363 {
364 	if (EXT2_HAS_COMPAT_FEATURE(sb, EXT2_FEATURE_COMPAT_EXT_ATTR))
365 		return;
366 
367 	spin_lock(&EXT2_SB(sb)->s_lock);
368 	ext2_update_dynamic_rev(sb);
369 	EXT2_SET_COMPAT_FEATURE(sb, EXT2_FEATURE_COMPAT_EXT_ATTR);
370 	spin_unlock(&EXT2_SB(sb)->s_lock);
371 	mark_buffer_dirty(EXT2_SB(sb)->s_sbh);
372 }
373 
374 /*
375  * ext2_xattr_set()
376  *
377  * Create, replace or remove an extended attribute for this inode.  Value
378  * is NULL to remove an existing extended attribute, and non-NULL to
379  * either replace an existing extended attribute, or create a new extended
380  * attribute. The flags XATTR_REPLACE and XATTR_CREATE
381  * specify that an extended attribute must exist and must not exist
382  * previous to the call, respectively.
383  *
384  * Returns 0, or a negative error number on failure.
385  */
386 int
387 ext2_xattr_set(struct inode *inode, int name_index, const char *name,
388 	       const void *value, size_t value_len, int flags)
389 {
390 	struct super_block *sb = inode->i_sb;
391 	struct buffer_head *bh = NULL;
392 	struct ext2_xattr_header *header = NULL;
393 	struct ext2_xattr_entry *here, *last;
394 	size_t name_len, free, min_offs = sb->s_blocksize;
395 	int not_found = 1, error;
396 	char *end;
397 
398 	/*
399 	 * header -- Points either into bh, or to a temporarily
400 	 *           allocated buffer.
401 	 * here -- The named entry found, or the place for inserting, within
402 	 *         the block pointed to by header.
403 	 * last -- Points right after the last named entry within the block
404 	 *         pointed to by header.
405 	 * min_offs -- The offset of the first value (values are aligned
406 	 *             towards the end of the block).
407 	 * end -- Points right after the block pointed to by header.
408 	 */
409 
410 	ea_idebug(inode, "name=%d.%s, value=%p, value_len=%ld",
411 		  name_index, name, value, (long)value_len);
412 
413 	if (value == NULL)
414 		value_len = 0;
415 	if (name == NULL)
416 		return -EINVAL;
417 	name_len = strlen(name);
418 	if (name_len > 255 || value_len > sb->s_blocksize)
419 		return -ERANGE;
420 	down_write(&EXT2_I(inode)->xattr_sem);
421 	if (EXT2_I(inode)->i_file_acl) {
422 		/* The inode already has an extended attribute block. */
423 		bh = sb_bread(sb, EXT2_I(inode)->i_file_acl);
424 		error = -EIO;
425 		if (!bh)
426 			goto cleanup;
427 		ea_bdebug(bh, "b_count=%d, refcount=%d",
428 			atomic_read(&(bh->b_count)),
429 			le32_to_cpu(HDR(bh)->h_refcount));
430 		header = HDR(bh);
431 		end = bh->b_data + bh->b_size;
432 		if (!ext2_xattr_header_valid(header)) {
433 bad_block:
434 			ext2_error(sb, "ext2_xattr_set",
435 				"inode %ld: bad block %d", inode->i_ino,
436 				   EXT2_I(inode)->i_file_acl);
437 			error = -EIO;
438 			goto cleanup;
439 		}
440 		/*
441 		 * Find the named attribute. If not found, 'here' will point
442 		 * to entry where the new attribute should be inserted to
443 		 * maintain sorting.
444 		 */
445 		last = FIRST_ENTRY(bh);
446 		while (!IS_LAST_ENTRY(last)) {
447 			struct ext2_xattr_entry *next = EXT2_XATTR_NEXT(last);
448 			if ((char *)next >= end)
449 				goto bad_block;
450 			if (!ext2_xattr_entry_valid(last, sb->s_blocksize))
451 				goto bad_block;
452 			if (last->e_value_size) {
453 				size_t offs = le16_to_cpu(last->e_value_offs);
454 				if (offs < min_offs)
455 					min_offs = offs;
456 			}
457 			if (not_found > 0) {
458 				not_found = name_index - last->e_name_index;
459 				if (!not_found)
460 					not_found = name_len - last->e_name_len;
461 				if (!not_found) {
462 					not_found = memcmp(name, last->e_name,
463 							   name_len);
464 				}
465 				if (not_found <= 0)
466 					here = last;
467 			}
468 			last = next;
469 		}
470 		if (not_found > 0)
471 			here = last;
472 
473 		/* Check whether we have enough space left. */
474 		free = min_offs - ((char*)last - (char*)header) - sizeof(__u32);
475 	} else {
476 		/* We will use a new extended attribute block. */
477 		free = sb->s_blocksize -
478 			sizeof(struct ext2_xattr_header) - sizeof(__u32);
479 		here = last = NULL;  /* avoid gcc uninitialized warning. */
480 	}
481 
482 	if (not_found) {
483 		/* Request to remove a nonexistent attribute? */
484 		error = -ENODATA;
485 		if (flags & XATTR_REPLACE)
486 			goto cleanup;
487 		error = 0;
488 		if (value == NULL)
489 			goto cleanup;
490 	} else {
491 		/* Request to create an existing attribute? */
492 		error = -EEXIST;
493 		if (flags & XATTR_CREATE)
494 			goto cleanup;
495 		free += EXT2_XATTR_SIZE(le32_to_cpu(here->e_value_size));
496 		free += EXT2_XATTR_LEN(name_len);
497 	}
498 	error = -ENOSPC;
499 	if (free < EXT2_XATTR_LEN(name_len) + EXT2_XATTR_SIZE(value_len))
500 		goto cleanup;
501 
502 	/* Here we know that we can set the new attribute. */
503 
504 	if (header) {
505 		/* assert(header == HDR(bh)); */
506 		lock_buffer(bh);
507 		if (header->h_refcount == cpu_to_le32(1)) {
508 			__u32 hash = le32_to_cpu(header->h_hash);
509 
510 			ea_bdebug(bh, "modifying in-place");
511 			/*
512 			 * This must happen under buffer lock for
513 			 * ext2_xattr_set2() to reliably detect modified block
514 			 */
515 			mb_cache_entry_delete(EA_BLOCK_CACHE(inode), hash,
516 					      bh->b_blocknr);
517 
518 			/* keep the buffer locked while modifying it. */
519 		} else {
520 			int offset;
521 
522 			unlock_buffer(bh);
523 			ea_bdebug(bh, "cloning");
524 			header = kmalloc(bh->b_size, GFP_KERNEL);
525 			error = -ENOMEM;
526 			if (header == NULL)
527 				goto cleanup;
528 			memcpy(header, HDR(bh), bh->b_size);
529 			header->h_refcount = cpu_to_le32(1);
530 
531 			offset = (char *)here - bh->b_data;
532 			here = ENTRY((char *)header + offset);
533 			offset = (char *)last - bh->b_data;
534 			last = ENTRY((char *)header + offset);
535 		}
536 	} else {
537 		/* Allocate a buffer where we construct the new block. */
538 		header = kzalloc(sb->s_blocksize, GFP_KERNEL);
539 		error = -ENOMEM;
540 		if (header == NULL)
541 			goto cleanup;
542 		end = (char *)header + sb->s_blocksize;
543 		header->h_magic = cpu_to_le32(EXT2_XATTR_MAGIC);
544 		header->h_blocks = header->h_refcount = cpu_to_le32(1);
545 		last = here = ENTRY(header+1);
546 	}
547 
548 	/* Iff we are modifying the block in-place, bh is locked here. */
549 
550 	if (not_found) {
551 		/* Insert the new name. */
552 		size_t size = EXT2_XATTR_LEN(name_len);
553 		size_t rest = (char *)last - (char *)here;
554 		memmove((char *)here + size, here, rest);
555 		memset(here, 0, size);
556 		here->e_name_index = name_index;
557 		here->e_name_len = name_len;
558 		memcpy(here->e_name, name, name_len);
559 	} else {
560 		if (here->e_value_size) {
561 			char *first_val = (char *)header + min_offs;
562 			size_t offs = le16_to_cpu(here->e_value_offs);
563 			char *val = (char *)header + offs;
564 			size_t size = EXT2_XATTR_SIZE(
565 				le32_to_cpu(here->e_value_size));
566 
567 			if (size == EXT2_XATTR_SIZE(value_len)) {
568 				/* The old and the new value have the same
569 				   size. Just replace. */
570 				here->e_value_size = cpu_to_le32(value_len);
571 				memset(val + size - EXT2_XATTR_PAD, 0,
572 				       EXT2_XATTR_PAD); /* Clear pad bytes. */
573 				memcpy(val, value, value_len);
574 				goto skip_replace;
575 			}
576 
577 			/* Remove the old value. */
578 			memmove(first_val + size, first_val, val - first_val);
579 			memset(first_val, 0, size);
580 			here->e_value_offs = 0;
581 			min_offs += size;
582 
583 			/* Adjust all value offsets. */
584 			last = ENTRY(header+1);
585 			while (!IS_LAST_ENTRY(last)) {
586 				size_t o = le16_to_cpu(last->e_value_offs);
587 				if (o < offs)
588 					last->e_value_offs =
589 						cpu_to_le16(o + size);
590 				last = EXT2_XATTR_NEXT(last);
591 			}
592 		}
593 		if (value == NULL) {
594 			/* Remove the old name. */
595 			size_t size = EXT2_XATTR_LEN(name_len);
596 			last = ENTRY((char *)last - size);
597 			memmove(here, (char*)here + size,
598 				(char*)last - (char*)here);
599 			memset(last, 0, size);
600 		}
601 	}
602 
603 	if (value != NULL) {
604 		/* Insert the new value. */
605 		here->e_value_size = cpu_to_le32(value_len);
606 		if (value_len) {
607 			size_t size = EXT2_XATTR_SIZE(value_len);
608 			char *val = (char *)header + min_offs - size;
609 			here->e_value_offs =
610 				cpu_to_le16((char *)val - (char *)header);
611 			memset(val + size - EXT2_XATTR_PAD, 0,
612 			       EXT2_XATTR_PAD); /* Clear the pad bytes. */
613 			memcpy(val, value, value_len);
614 		}
615 	}
616 
617 skip_replace:
618 	if (IS_LAST_ENTRY(ENTRY(header+1))) {
619 		/* This block is now empty. */
620 		if (bh && header == HDR(bh))
621 			unlock_buffer(bh);  /* we were modifying in-place. */
622 		error = ext2_xattr_set2(inode, bh, NULL);
623 	} else {
624 		ext2_xattr_rehash(header, here);
625 		if (bh && header == HDR(bh))
626 			unlock_buffer(bh);  /* we were modifying in-place. */
627 		error = ext2_xattr_set2(inode, bh, header);
628 	}
629 
630 cleanup:
631 	if (!(bh && header == HDR(bh)))
632 		kfree(header);
633 	brelse(bh);
634 	up_write(&EXT2_I(inode)->xattr_sem);
635 
636 	return error;
637 }
638 
639 /*
640  * Second half of ext2_xattr_set(): Update the file system.
641  */
642 static int
643 ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh,
644 		struct ext2_xattr_header *header)
645 {
646 	struct super_block *sb = inode->i_sb;
647 	struct buffer_head *new_bh = NULL;
648 	int error;
649 	struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
650 
651 	if (header) {
652 		new_bh = ext2_xattr_cache_find(inode, header);
653 		if (new_bh) {
654 			/* We found an identical block in the cache. */
655 			if (new_bh == old_bh) {
656 				ea_bdebug(new_bh, "keeping this block");
657 			} else {
658 				/* The old block is released after updating
659 				   the inode.  */
660 				ea_bdebug(new_bh, "reusing block");
661 
662 				error = dquot_alloc_block(inode, 1);
663 				if (error) {
664 					unlock_buffer(new_bh);
665 					goto cleanup;
666 				}
667 				le32_add_cpu(&HDR(new_bh)->h_refcount, 1);
668 				ea_bdebug(new_bh, "refcount now=%d",
669 					le32_to_cpu(HDR(new_bh)->h_refcount));
670 			}
671 			unlock_buffer(new_bh);
672 		} else if (old_bh && header == HDR(old_bh)) {
673 			/* Keep this block. No need to lock the block as we
674 			   don't need to change the reference count. */
675 			new_bh = old_bh;
676 			get_bh(new_bh);
677 			ext2_xattr_cache_insert(ea_block_cache, new_bh);
678 		} else {
679 			/* We need to allocate a new block */
680 			ext2_fsblk_t goal = ext2_group_first_block_no(sb,
681 						EXT2_I(inode)->i_block_group);
682 			int block = ext2_new_block(inode, goal, &error);
683 			if (error)
684 				goto cleanup;
685 			ea_idebug(inode, "creating block %d", block);
686 
687 			new_bh = sb_getblk(sb, block);
688 			if (unlikely(!new_bh)) {
689 				ext2_free_blocks(inode, block, 1);
690 				mark_inode_dirty(inode);
691 				error = -ENOMEM;
692 				goto cleanup;
693 			}
694 			lock_buffer(new_bh);
695 			memcpy(new_bh->b_data, header, new_bh->b_size);
696 			set_buffer_uptodate(new_bh);
697 			unlock_buffer(new_bh);
698 			ext2_xattr_cache_insert(ea_block_cache, new_bh);
699 
700 			ext2_xattr_update_super_block(sb);
701 		}
702 		mark_buffer_dirty(new_bh);
703 		if (IS_SYNC(inode)) {
704 			sync_dirty_buffer(new_bh);
705 			error = -EIO;
706 			if (buffer_req(new_bh) && !buffer_uptodate(new_bh))
707 				goto cleanup;
708 		}
709 	}
710 
711 	/* Update the inode. */
712 	EXT2_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
713 	inode->i_ctime = current_time(inode);
714 	if (IS_SYNC(inode)) {
715 		error = sync_inode_metadata(inode, 1);
716 		/* In case sync failed due to ENOSPC the inode was actually
717 		 * written (only some dirty data were not) so we just proceed
718 		 * as if nothing happened and cleanup the unused block */
719 		if (error && error != -ENOSPC) {
720 			if (new_bh && new_bh != old_bh) {
721 				dquot_free_block_nodirty(inode, 1);
722 				mark_inode_dirty(inode);
723 			}
724 			goto cleanup;
725 		}
726 	} else
727 		mark_inode_dirty(inode);
728 
729 	error = 0;
730 	if (old_bh && old_bh != new_bh) {
731 		/*
732 		 * If there was an old block and we are no longer using it,
733 		 * release the old block.
734 		 */
735 		lock_buffer(old_bh);
736 		if (HDR(old_bh)->h_refcount == cpu_to_le32(1)) {
737 			__u32 hash = le32_to_cpu(HDR(old_bh)->h_hash);
738 
739 			/*
740 			 * This must happen under buffer lock for
741 			 * ext2_xattr_set2() to reliably detect freed block
742 			 */
743 			mb_cache_entry_delete(ea_block_cache, hash,
744 					      old_bh->b_blocknr);
745 			/* Free the old block. */
746 			ea_bdebug(old_bh, "freeing");
747 			ext2_free_blocks(inode, old_bh->b_blocknr, 1);
748 			mark_inode_dirty(inode);
749 			/* We let our caller release old_bh, so we
750 			 * need to duplicate the buffer before. */
751 			get_bh(old_bh);
752 			bforget(old_bh);
753 		} else {
754 			/* Decrement the refcount only. */
755 			le32_add_cpu(&HDR(old_bh)->h_refcount, -1);
756 			dquot_free_block_nodirty(inode, 1);
757 			mark_inode_dirty(inode);
758 			mark_buffer_dirty(old_bh);
759 			ea_bdebug(old_bh, "refcount now=%d",
760 				le32_to_cpu(HDR(old_bh)->h_refcount));
761 		}
762 		unlock_buffer(old_bh);
763 	}
764 
765 cleanup:
766 	brelse(new_bh);
767 
768 	return error;
769 }
770 
771 /*
772  * ext2_xattr_delete_inode()
773  *
774  * Free extended attribute resources associated with this inode. This
775  * is called immediately before an inode is freed.
776  */
777 void
778 ext2_xattr_delete_inode(struct inode *inode)
779 {
780 	struct buffer_head *bh = NULL;
781 	struct ext2_sb_info *sbi = EXT2_SB(inode->i_sb);
782 
783 	down_write(&EXT2_I(inode)->xattr_sem);
784 	if (!EXT2_I(inode)->i_file_acl)
785 		goto cleanup;
786 
787 	if (!ext2_data_block_valid(sbi, EXT2_I(inode)->i_file_acl, 0)) {
788 		ext2_error(inode->i_sb, "ext2_xattr_delete_inode",
789 			"inode %ld: xattr block %d is out of data blocks range",
790 			inode->i_ino, EXT2_I(inode)->i_file_acl);
791 		goto cleanup;
792 	}
793 
794 	bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl);
795 	if (!bh) {
796 		ext2_error(inode->i_sb, "ext2_xattr_delete_inode",
797 			"inode %ld: block %d read error", inode->i_ino,
798 			EXT2_I(inode)->i_file_acl);
799 		goto cleanup;
800 	}
801 	ea_bdebug(bh, "b_count=%d", atomic_read(&(bh->b_count)));
802 	if (!ext2_xattr_header_valid(HDR(bh))) {
803 		ext2_error(inode->i_sb, "ext2_xattr_delete_inode",
804 			"inode %ld: bad block %d", inode->i_ino,
805 			EXT2_I(inode)->i_file_acl);
806 		goto cleanup;
807 	}
808 	lock_buffer(bh);
809 	if (HDR(bh)->h_refcount == cpu_to_le32(1)) {
810 		__u32 hash = le32_to_cpu(HDR(bh)->h_hash);
811 
812 		/*
813 		 * This must happen under buffer lock for ext2_xattr_set2() to
814 		 * reliably detect freed block
815 		 */
816 		mb_cache_entry_delete(EA_BLOCK_CACHE(inode), hash,
817 				      bh->b_blocknr);
818 		ext2_free_blocks(inode, EXT2_I(inode)->i_file_acl, 1);
819 		get_bh(bh);
820 		bforget(bh);
821 		unlock_buffer(bh);
822 	} else {
823 		le32_add_cpu(&HDR(bh)->h_refcount, -1);
824 		ea_bdebug(bh, "refcount now=%d",
825 			le32_to_cpu(HDR(bh)->h_refcount));
826 		unlock_buffer(bh);
827 		mark_buffer_dirty(bh);
828 		if (IS_SYNC(inode))
829 			sync_dirty_buffer(bh);
830 		dquot_free_block_nodirty(inode, 1);
831 	}
832 	EXT2_I(inode)->i_file_acl = 0;
833 
834 cleanup:
835 	brelse(bh);
836 	up_write(&EXT2_I(inode)->xattr_sem);
837 }
838 
839 /*
840  * ext2_xattr_cache_insert()
841  *
842  * Create a new entry in the extended attribute cache, and insert
843  * it unless such an entry is already in the cache.
844  *
845  * Returns 0, or a negative error number on failure.
846  */
847 static int
848 ext2_xattr_cache_insert(struct mb_cache *cache, struct buffer_head *bh)
849 {
850 	__u32 hash = le32_to_cpu(HDR(bh)->h_hash);
851 	int error;
852 
853 	error = mb_cache_entry_create(cache, GFP_NOFS, hash, bh->b_blocknr,
854 				      true);
855 	if (error) {
856 		if (error == -EBUSY) {
857 			ea_bdebug(bh, "already in cache (%d cache entries)",
858 				atomic_read(&ext2_xattr_cache->c_entry_count));
859 			error = 0;
860 		}
861 	} else
862 		ea_bdebug(bh, "inserting [%x]", (int)hash);
863 	return error;
864 }
865 
866 /*
867  * ext2_xattr_cmp()
868  *
869  * Compare two extended attribute blocks for equality.
870  *
871  * Returns 0 if the blocks are equal, 1 if they differ, and
872  * a negative error number on errors.
873  */
874 static int
875 ext2_xattr_cmp(struct ext2_xattr_header *header1,
876 	       struct ext2_xattr_header *header2)
877 {
878 	struct ext2_xattr_entry *entry1, *entry2;
879 
880 	entry1 = ENTRY(header1+1);
881 	entry2 = ENTRY(header2+1);
882 	while (!IS_LAST_ENTRY(entry1)) {
883 		if (IS_LAST_ENTRY(entry2))
884 			return 1;
885 		if (entry1->e_hash != entry2->e_hash ||
886 		    entry1->e_name_index != entry2->e_name_index ||
887 		    entry1->e_name_len != entry2->e_name_len ||
888 		    entry1->e_value_size != entry2->e_value_size ||
889 		    memcmp(entry1->e_name, entry2->e_name, entry1->e_name_len))
890 			return 1;
891 		if (entry1->e_value_block != 0 || entry2->e_value_block != 0)
892 			return -EIO;
893 		if (memcmp((char *)header1 + le16_to_cpu(entry1->e_value_offs),
894 			   (char *)header2 + le16_to_cpu(entry2->e_value_offs),
895 			   le32_to_cpu(entry1->e_value_size)))
896 			return 1;
897 
898 		entry1 = EXT2_XATTR_NEXT(entry1);
899 		entry2 = EXT2_XATTR_NEXT(entry2);
900 	}
901 	if (!IS_LAST_ENTRY(entry2))
902 		return 1;
903 	return 0;
904 }
905 
906 /*
907  * ext2_xattr_cache_find()
908  *
909  * Find an identical extended attribute block.
910  *
911  * Returns a locked buffer head to the block found, or NULL if such
912  * a block was not found or an error occurred.
913  */
914 static struct buffer_head *
915 ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header)
916 {
917 	__u32 hash = le32_to_cpu(header->h_hash);
918 	struct mb_cache_entry *ce;
919 	struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
920 
921 	if (!header->h_hash)
922 		return NULL;  /* never share */
923 	ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
924 again:
925 	ce = mb_cache_entry_find_first(ea_block_cache, hash);
926 	while (ce) {
927 		struct buffer_head *bh;
928 
929 		bh = sb_bread(inode->i_sb, ce->e_value);
930 		if (!bh) {
931 			ext2_error(inode->i_sb, "ext2_xattr_cache_find",
932 				"inode %ld: block %ld read error",
933 				inode->i_ino, (unsigned long) ce->e_value);
934 		} else {
935 			lock_buffer(bh);
936 			/*
937 			 * We have to be careful about races with freeing or
938 			 * rehashing of xattr block. Once we hold buffer lock
939 			 * xattr block's state is stable so we can check
940 			 * whether the block got freed / rehashed or not.
941 			 * Since we unhash mbcache entry under buffer lock when
942 			 * freeing / rehashing xattr block, checking whether
943 			 * entry is still hashed is reliable.
944 			 */
945 			if (hlist_bl_unhashed(&ce->e_hash_list)) {
946 				mb_cache_entry_put(ea_block_cache, ce);
947 				unlock_buffer(bh);
948 				brelse(bh);
949 				goto again;
950 			} else if (le32_to_cpu(HDR(bh)->h_refcount) >
951 				   EXT2_XATTR_REFCOUNT_MAX) {
952 				ea_idebug(inode, "block %ld refcount %d>%d",
953 					  (unsigned long) ce->e_value,
954 					  le32_to_cpu(HDR(bh)->h_refcount),
955 					  EXT2_XATTR_REFCOUNT_MAX);
956 			} else if (!ext2_xattr_cmp(header, HDR(bh))) {
957 				ea_bdebug(bh, "b_count=%d",
958 					  atomic_read(&(bh->b_count)));
959 				mb_cache_entry_touch(ea_block_cache, ce);
960 				mb_cache_entry_put(ea_block_cache, ce);
961 				return bh;
962 			}
963 			unlock_buffer(bh);
964 			brelse(bh);
965 		}
966 		ce = mb_cache_entry_find_next(ea_block_cache, ce);
967 	}
968 	return NULL;
969 }
970 
971 #define NAME_HASH_SHIFT 5
972 #define VALUE_HASH_SHIFT 16
973 
974 /*
975  * ext2_xattr_hash_entry()
976  *
977  * Compute the hash of an extended attribute.
978  */
979 static inline void ext2_xattr_hash_entry(struct ext2_xattr_header *header,
980 					 struct ext2_xattr_entry *entry)
981 {
982 	__u32 hash = 0;
983 	char *name = entry->e_name;
984 	int n;
985 
986 	for (n=0; n < entry->e_name_len; n++) {
987 		hash = (hash << NAME_HASH_SHIFT) ^
988 		       (hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
989 		       *name++;
990 	}
991 
992 	if (entry->e_value_block == 0 && entry->e_value_size != 0) {
993 		__le32 *value = (__le32 *)((char *)header +
994 			le16_to_cpu(entry->e_value_offs));
995 		for (n = (le32_to_cpu(entry->e_value_size) +
996 		     EXT2_XATTR_ROUND) >> EXT2_XATTR_PAD_BITS; n; n--) {
997 			hash = (hash << VALUE_HASH_SHIFT) ^
998 			       (hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
999 			       le32_to_cpu(*value++);
1000 		}
1001 	}
1002 	entry->e_hash = cpu_to_le32(hash);
1003 }
1004 
1005 #undef NAME_HASH_SHIFT
1006 #undef VALUE_HASH_SHIFT
1007 
1008 #define BLOCK_HASH_SHIFT 16
1009 
1010 /*
1011  * ext2_xattr_rehash()
1012  *
1013  * Re-compute the extended attribute hash value after an entry has changed.
1014  */
1015 static void ext2_xattr_rehash(struct ext2_xattr_header *header,
1016 			      struct ext2_xattr_entry *entry)
1017 {
1018 	struct ext2_xattr_entry *here;
1019 	__u32 hash = 0;
1020 
1021 	ext2_xattr_hash_entry(header, entry);
1022 	here = ENTRY(header+1);
1023 	while (!IS_LAST_ENTRY(here)) {
1024 		if (!here->e_hash) {
1025 			/* Block is not shared if an entry's hash value == 0 */
1026 			hash = 0;
1027 			break;
1028 		}
1029 		hash = (hash << BLOCK_HASH_SHIFT) ^
1030 		       (hash >> (8*sizeof(hash) - BLOCK_HASH_SHIFT)) ^
1031 		       le32_to_cpu(here->e_hash);
1032 		here = EXT2_XATTR_NEXT(here);
1033 	}
1034 	header->h_hash = cpu_to_le32(hash);
1035 }
1036 
1037 #undef BLOCK_HASH_SHIFT
1038 
1039 #define HASH_BUCKET_BITS 10
1040 
1041 struct mb_cache *ext2_xattr_create_cache(void)
1042 {
1043 	return mb_cache_create(HASH_BUCKET_BITS);
1044 }
1045 
1046 void ext2_xattr_destroy_cache(struct mb_cache *cache)
1047 {
1048 	if (cache)
1049 		mb_cache_destroy(cache);
1050 }
1051