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