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