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