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