GNU Linux-libre 4.9.308-gnu1
[releases.git] / fs / ext4 / namei.c
1 /*
2  *  linux/fs/ext4/namei.c
3  *
4  * Copyright (C) 1992, 1993, 1994, 1995
5  * Remy Card (card@masi.ibp.fr)
6  * Laboratoire MASI - Institut Blaise Pascal
7  * Universite Pierre et Marie Curie (Paris VI)
8  *
9  *  from
10  *
11  *  linux/fs/minix/namei.c
12  *
13  *  Copyright (C) 1991, 1992  Linus Torvalds
14  *
15  *  Big-endian to little-endian byte-swapping/bitmaps by
16  *        David S. Miller (davem@caip.rutgers.edu), 1995
17  *  Directory entry file type support and forward compatibility hooks
18  *      for B-tree directories by Theodore Ts'o (tytso@mit.edu), 1998
19  *  Hash Tree Directory indexing (c)
20  *      Daniel Phillips, 2001
21  *  Hash Tree Directory indexing porting
22  *      Christopher Li, 2002
23  *  Hash Tree Directory indexing cleanup
24  *      Theodore Ts'o, 2002
25  */
26
27 #include <linux/fs.h>
28 #include <linux/pagemap.h>
29 #include <linux/time.h>
30 #include <linux/fcntl.h>
31 #include <linux/stat.h>
32 #include <linux/string.h>
33 #include <linux/quotaops.h>
34 #include <linux/buffer_head.h>
35 #include <linux/bio.h>
36 #include "ext4.h"
37 #include "ext4_jbd2.h"
38
39 #include "xattr.h"
40 #include "acl.h"
41
42 #include <trace/events/ext4.h>
43 /*
44  * define how far ahead to read directories while searching them.
45  */
46 #define NAMEI_RA_CHUNKS  2
47 #define NAMEI_RA_BLOCKS  4
48 #define NAMEI_RA_SIZE        (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
49
50 static struct buffer_head *ext4_append(handle_t *handle,
51                                         struct inode *inode,
52                                         ext4_lblk_t *block)
53 {
54         struct buffer_head *bh;
55         int err;
56
57         if (unlikely(EXT4_SB(inode->i_sb)->s_max_dir_size_kb &&
58                      ((inode->i_size >> 10) >=
59                       EXT4_SB(inode->i_sb)->s_max_dir_size_kb)))
60                 return ERR_PTR(-ENOSPC);
61
62         *block = inode->i_size >> inode->i_sb->s_blocksize_bits;
63
64         bh = ext4_bread(handle, inode, *block, EXT4_GET_BLOCKS_CREATE);
65         if (IS_ERR(bh))
66                 return bh;
67         inode->i_size += inode->i_sb->s_blocksize;
68         EXT4_I(inode)->i_disksize = inode->i_size;
69         BUFFER_TRACE(bh, "get_write_access");
70         err = ext4_journal_get_write_access(handle, bh);
71         if (err) {
72                 brelse(bh);
73                 ext4_std_error(inode->i_sb, err);
74                 return ERR_PTR(err);
75         }
76         return bh;
77 }
78
79 static int ext4_dx_csum_verify(struct inode *inode,
80                                struct ext4_dir_entry *dirent);
81
82 /*
83  * Hints to ext4_read_dirblock regarding whether we expect a directory
84  * block being read to be an index block, or a block containing
85  * directory entries (and if the latter, whether it was found via a
86  * logical block in an htree index block).  This is used to control
87  * what sort of sanity checkinig ext4_read_dirblock() will do on the
88  * directory block read from the storage device.  EITHER will means
89  * the caller doesn't know what kind of directory block will be read,
90  * so no specific verification will be done.
91  */
92 typedef enum {
93         EITHER, INDEX, DIRENT, DIRENT_HTREE
94 } dirblock_type_t;
95
96 #define ext4_read_dirblock(inode, block, type) \
97         __ext4_read_dirblock((inode), (block), (type), __func__, __LINE__)
98
99 static struct buffer_head *__ext4_read_dirblock(struct inode *inode,
100                                                 ext4_lblk_t block,
101                                                 dirblock_type_t type,
102                                                 const char *func,
103                                                 unsigned int line)
104 {
105         struct buffer_head *bh;
106         struct ext4_dir_entry *dirent;
107         int is_dx_block = 0;
108
109         bh = ext4_bread(NULL, inode, block, 0);
110         if (IS_ERR(bh)) {
111                 __ext4_warning(inode->i_sb, func, line,
112                                "inode #%lu: lblock %lu: comm %s: "
113                                "error %ld reading directory block",
114                                inode->i_ino, (unsigned long)block,
115                                current->comm, PTR_ERR(bh));
116
117                 return bh;
118         }
119         if (!bh && (type == INDEX || type == DIRENT_HTREE)) {
120                 ext4_error_inode(inode, func, line, block,
121                                  "Directory hole found for htree %s block",
122                                  (type == INDEX) ? "index" : "leaf");
123                 return ERR_PTR(-EFSCORRUPTED);
124         }
125         if (!bh)
126                 return NULL;
127         dirent = (struct ext4_dir_entry *) bh->b_data;
128         /* Determine whether or not we have an index block */
129         if (is_dx(inode)) {
130                 if (block == 0)
131                         is_dx_block = 1;
132                 else if (ext4_rec_len_from_disk(dirent->rec_len,
133                                                 inode->i_sb->s_blocksize) ==
134                          inode->i_sb->s_blocksize)
135                         is_dx_block = 1;
136         }
137         if (!is_dx_block && type == INDEX) {
138                 ext4_error_inode(inode, func, line, block,
139                        "directory leaf block found instead of index block");
140                 brelse(bh);
141                 return ERR_PTR(-EFSCORRUPTED);
142         }
143         if (!ext4_has_metadata_csum(inode->i_sb) ||
144             buffer_verified(bh))
145                 return bh;
146
147         /*
148          * An empty leaf block can get mistaken for a index block; for
149          * this reason, we can only check the index checksum when the
150          * caller is sure it should be an index block.
151          */
152         if (is_dx_block && type == INDEX) {
153                 if (ext4_dx_csum_verify(inode, dirent))
154                         set_buffer_verified(bh);
155                 else {
156                         ext4_error_inode(inode, func, line, block,
157                                          "Directory index failed checksum");
158                         brelse(bh);
159                         return ERR_PTR(-EFSBADCRC);
160                 }
161         }
162         if (!is_dx_block) {
163                 if (ext4_dirent_csum_verify(inode, dirent))
164                         set_buffer_verified(bh);
165                 else {
166                         ext4_error_inode(inode, func, line, block,
167                                          "Directory block failed checksum");
168                         brelse(bh);
169                         return ERR_PTR(-EFSBADCRC);
170                 }
171         }
172         return bh;
173 }
174
175 #ifndef assert
176 #define assert(test) J_ASSERT(test)
177 #endif
178
179 #ifdef DX_DEBUG
180 #define dxtrace(command) command
181 #else
182 #define dxtrace(command)
183 #endif
184
185 struct fake_dirent
186 {
187         __le32 inode;
188         __le16 rec_len;
189         u8 name_len;
190         u8 file_type;
191 };
192
193 struct dx_countlimit
194 {
195         __le16 limit;
196         __le16 count;
197 };
198
199 struct dx_entry
200 {
201         __le32 hash;
202         __le32 block;
203 };
204
205 /*
206  * dx_root_info is laid out so that if it should somehow get overlaid by a
207  * dirent the two low bits of the hash version will be zero.  Therefore, the
208  * hash version mod 4 should never be 0.  Sincerely, the paranoia department.
209  */
210
211 struct dx_root
212 {
213         struct fake_dirent dot;
214         char dot_name[4];
215         struct fake_dirent dotdot;
216         char dotdot_name[4];
217         struct dx_root_info
218         {
219                 __le32 reserved_zero;
220                 u8 hash_version;
221                 u8 info_length; /* 8 */
222                 u8 indirect_levels;
223                 u8 unused_flags;
224         }
225         info;
226         struct dx_entry entries[0];
227 };
228
229 struct dx_node
230 {
231         struct fake_dirent fake;
232         struct dx_entry entries[0];
233 };
234
235
236 struct dx_frame
237 {
238         struct buffer_head *bh;
239         struct dx_entry *entries;
240         struct dx_entry *at;
241 };
242
243 struct dx_map_entry
244 {
245         u32 hash;
246         u16 offs;
247         u16 size;
248 };
249
250 /*
251  * This goes at the end of each htree block.
252  */
253 struct dx_tail {
254         u32 dt_reserved;
255         __le32 dt_checksum;     /* crc32c(uuid+inum+dirblock) */
256 };
257
258 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry);
259 static void dx_set_block(struct dx_entry *entry, ext4_lblk_t value);
260 static inline unsigned dx_get_hash(struct dx_entry *entry);
261 static void dx_set_hash(struct dx_entry *entry, unsigned value);
262 static unsigned dx_get_count(struct dx_entry *entries);
263 static unsigned dx_get_limit(struct dx_entry *entries);
264 static void dx_set_count(struct dx_entry *entries, unsigned value);
265 static void dx_set_limit(struct dx_entry *entries, unsigned value);
266 static unsigned dx_root_limit(struct inode *dir, unsigned infosize);
267 static unsigned dx_node_limit(struct inode *dir);
268 static struct dx_frame *dx_probe(struct ext4_filename *fname,
269                                  struct inode *dir,
270                                  struct dx_hash_info *hinfo,
271                                  struct dx_frame *frame);
272 static void dx_release(struct dx_frame *frames);
273 static int dx_make_map(struct inode *dir, struct ext4_dir_entry_2 *de,
274                        unsigned blocksize, struct dx_hash_info *hinfo,
275                        struct dx_map_entry map[]);
276 static void dx_sort_map(struct dx_map_entry *map, unsigned count);
277 static struct ext4_dir_entry_2 *dx_move_dirents(char *from, char *to,
278                 struct dx_map_entry *offsets, int count, unsigned blocksize);
279 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize);
280 static void dx_insert_block(struct dx_frame *frame,
281                                         u32 hash, ext4_lblk_t block);
282 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
283                                  struct dx_frame *frame,
284                                  struct dx_frame *frames,
285                                  __u32 *start_hash);
286 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
287                 struct ext4_filename *fname,
288                 struct ext4_dir_entry_2 **res_dir);
289 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
290                              struct inode *dir, struct inode *inode);
291
292 /* checksumming functions */
293 void initialize_dirent_tail(struct ext4_dir_entry_tail *t,
294                             unsigned int blocksize)
295 {
296         memset(t, 0, sizeof(struct ext4_dir_entry_tail));
297         t->det_rec_len = ext4_rec_len_to_disk(
298                         sizeof(struct ext4_dir_entry_tail), blocksize);
299         t->det_reserved_ft = EXT4_FT_DIR_CSUM;
300 }
301
302 /* Walk through a dirent block to find a checksum "dirent" at the tail */
303 static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode,
304                                                    struct ext4_dir_entry *de)
305 {
306         struct ext4_dir_entry_tail *t;
307
308 #ifdef PARANOID
309         struct ext4_dir_entry *d, *top;
310
311         d = de;
312         top = (struct ext4_dir_entry *)(((void *)de) +
313                 (EXT4_BLOCK_SIZE(inode->i_sb) -
314                 sizeof(struct ext4_dir_entry_tail)));
315         while (d < top && d->rec_len)
316                 d = (struct ext4_dir_entry *)(((void *)d) +
317                     le16_to_cpu(d->rec_len));
318
319         if (d != top)
320                 return NULL;
321
322         t = (struct ext4_dir_entry_tail *)d;
323 #else
324         t = EXT4_DIRENT_TAIL(de, EXT4_BLOCK_SIZE(inode->i_sb));
325 #endif
326
327         if (t->det_reserved_zero1 ||
328             le16_to_cpu(t->det_rec_len) != sizeof(struct ext4_dir_entry_tail) ||
329             t->det_reserved_zero2 ||
330             t->det_reserved_ft != EXT4_FT_DIR_CSUM)
331                 return NULL;
332
333         return t;
334 }
335
336 static __le32 ext4_dirent_csum(struct inode *inode,
337                                struct ext4_dir_entry *dirent, int size)
338 {
339         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
340         struct ext4_inode_info *ei = EXT4_I(inode);
341         __u32 csum;
342
343         csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
344         return cpu_to_le32(csum);
345 }
346
347 #define warn_no_space_for_csum(inode)                                   \
348         __warn_no_space_for_csum((inode), __func__, __LINE__)
349
350 static void __warn_no_space_for_csum(struct inode *inode, const char *func,
351                                      unsigned int line)
352 {
353         __ext4_warning_inode(inode, func, line,
354                 "No space for directory leaf checksum. Please run e2fsck -D.");
355 }
356
357 int ext4_dirent_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent)
358 {
359         struct ext4_dir_entry_tail *t;
360
361         if (!ext4_has_metadata_csum(inode->i_sb))
362                 return 1;
363
364         t = get_dirent_tail(inode, dirent);
365         if (!t) {
366                 warn_no_space_for_csum(inode);
367                 return 0;
368         }
369
370         if (t->det_checksum != ext4_dirent_csum(inode, dirent,
371                                                 (void *)t - (void *)dirent))
372                 return 0;
373
374         return 1;
375 }
376
377 static void ext4_dirent_csum_set(struct inode *inode,
378                                  struct ext4_dir_entry *dirent)
379 {
380         struct ext4_dir_entry_tail *t;
381
382         if (!ext4_has_metadata_csum(inode->i_sb))
383                 return;
384
385         t = get_dirent_tail(inode, dirent);
386         if (!t) {
387                 warn_no_space_for_csum(inode);
388                 return;
389         }
390
391         t->det_checksum = ext4_dirent_csum(inode, dirent,
392                                            (void *)t - (void *)dirent);
393 }
394
395 int ext4_handle_dirty_dirent_node(handle_t *handle,
396                                   struct inode *inode,
397                                   struct buffer_head *bh)
398 {
399         ext4_dirent_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
400         return ext4_handle_dirty_metadata(handle, inode, bh);
401 }
402
403 static struct dx_countlimit *get_dx_countlimit(struct inode *inode,
404                                                struct ext4_dir_entry *dirent,
405                                                int *offset)
406 {
407         struct ext4_dir_entry *dp;
408         struct dx_root_info *root;
409         int count_offset;
410
411         if (le16_to_cpu(dirent->rec_len) == EXT4_BLOCK_SIZE(inode->i_sb))
412                 count_offset = 8;
413         else if (le16_to_cpu(dirent->rec_len) == 12) {
414                 dp = (struct ext4_dir_entry *)(((void *)dirent) + 12);
415                 if (le16_to_cpu(dp->rec_len) !=
416                     EXT4_BLOCK_SIZE(inode->i_sb) - 12)
417                         return NULL;
418                 root = (struct dx_root_info *)(((void *)dp + 12));
419                 if (root->reserved_zero ||
420                     root->info_length != sizeof(struct dx_root_info))
421                         return NULL;
422                 count_offset = 32;
423         } else
424                 return NULL;
425
426         if (offset)
427                 *offset = count_offset;
428         return (struct dx_countlimit *)(((void *)dirent) + count_offset);
429 }
430
431 static __le32 ext4_dx_csum(struct inode *inode, struct ext4_dir_entry *dirent,
432                            int count_offset, int count, struct dx_tail *t)
433 {
434         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
435         struct ext4_inode_info *ei = EXT4_I(inode);
436         __u32 csum;
437         int size;
438         __u32 dummy_csum = 0;
439         int offset = offsetof(struct dx_tail, dt_checksum);
440
441         size = count_offset + (count * sizeof(struct dx_entry));
442         csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
443         csum = ext4_chksum(sbi, csum, (__u8 *)t, offset);
444         csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
445
446         return cpu_to_le32(csum);
447 }
448
449 static int ext4_dx_csum_verify(struct inode *inode,
450                                struct ext4_dir_entry *dirent)
451 {
452         struct dx_countlimit *c;
453         struct dx_tail *t;
454         int count_offset, limit, count;
455
456         if (!ext4_has_metadata_csum(inode->i_sb))
457                 return 1;
458
459         c = get_dx_countlimit(inode, dirent, &count_offset);
460         if (!c) {
461                 EXT4_ERROR_INODE(inode, "dir seems corrupt?  Run e2fsck -D.");
462                 return 0;
463         }
464         limit = le16_to_cpu(c->limit);
465         count = le16_to_cpu(c->count);
466         if (count_offset + (limit * sizeof(struct dx_entry)) >
467             EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
468                 warn_no_space_for_csum(inode);
469                 return 0;
470         }
471         t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
472
473         if (t->dt_checksum != ext4_dx_csum(inode, dirent, count_offset,
474                                             count, t))
475                 return 0;
476         return 1;
477 }
478
479 static void ext4_dx_csum_set(struct inode *inode, struct ext4_dir_entry *dirent)
480 {
481         struct dx_countlimit *c;
482         struct dx_tail *t;
483         int count_offset, limit, count;
484
485         if (!ext4_has_metadata_csum(inode->i_sb))
486                 return;
487
488         c = get_dx_countlimit(inode, dirent, &count_offset);
489         if (!c) {
490                 EXT4_ERROR_INODE(inode, "dir seems corrupt?  Run e2fsck -D.");
491                 return;
492         }
493         limit = le16_to_cpu(c->limit);
494         count = le16_to_cpu(c->count);
495         if (count_offset + (limit * sizeof(struct dx_entry)) >
496             EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
497                 warn_no_space_for_csum(inode);
498                 return;
499         }
500         t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
501
502         t->dt_checksum = ext4_dx_csum(inode, dirent, count_offset, count, t);
503 }
504
505 static inline int ext4_handle_dirty_dx_node(handle_t *handle,
506                                             struct inode *inode,
507                                             struct buffer_head *bh)
508 {
509         ext4_dx_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
510         return ext4_handle_dirty_metadata(handle, inode, bh);
511 }
512
513 /*
514  * p is at least 6 bytes before the end of page
515  */
516 static inline struct ext4_dir_entry_2 *
517 ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize)
518 {
519         return (struct ext4_dir_entry_2 *)((char *)p +
520                 ext4_rec_len_from_disk(p->rec_len, blocksize));
521 }
522
523 /*
524  * Future: use high four bits of block for coalesce-on-delete flags
525  * Mask them off for now.
526  */
527
528 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry)
529 {
530         return le32_to_cpu(entry->block) & 0x00ffffff;
531 }
532
533 static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value)
534 {
535         entry->block = cpu_to_le32(value);
536 }
537
538 static inline unsigned dx_get_hash(struct dx_entry *entry)
539 {
540         return le32_to_cpu(entry->hash);
541 }
542
543 static inline void dx_set_hash(struct dx_entry *entry, unsigned value)
544 {
545         entry->hash = cpu_to_le32(value);
546 }
547
548 static inline unsigned dx_get_count(struct dx_entry *entries)
549 {
550         return le16_to_cpu(((struct dx_countlimit *) entries)->count);
551 }
552
553 static inline unsigned dx_get_limit(struct dx_entry *entries)
554 {
555         return le16_to_cpu(((struct dx_countlimit *) entries)->limit);
556 }
557
558 static inline void dx_set_count(struct dx_entry *entries, unsigned value)
559 {
560         ((struct dx_countlimit *) entries)->count = cpu_to_le16(value);
561 }
562
563 static inline void dx_set_limit(struct dx_entry *entries, unsigned value)
564 {
565         ((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
566 }
567
568 static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize)
569 {
570         unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(1) -
571                 EXT4_DIR_REC_LEN(2) - infosize;
572
573         if (ext4_has_metadata_csum(dir->i_sb))
574                 entry_space -= sizeof(struct dx_tail);
575         return entry_space / sizeof(struct dx_entry);
576 }
577
578 static inline unsigned dx_node_limit(struct inode *dir)
579 {
580         unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0);
581
582         if (ext4_has_metadata_csum(dir->i_sb))
583                 entry_space -= sizeof(struct dx_tail);
584         return entry_space / sizeof(struct dx_entry);
585 }
586
587 /*
588  * Debug
589  */
590 #ifdef DX_DEBUG
591 static void dx_show_index(char * label, struct dx_entry *entries)
592 {
593         int i, n = dx_get_count (entries);
594         printk(KERN_DEBUG "%s index", label);
595         for (i = 0; i < n; i++) {
596                 printk(KERN_CONT " %x->%lu",
597                        i ? dx_get_hash(entries + i) : 0,
598                        (unsigned long)dx_get_block(entries + i));
599         }
600         printk(KERN_CONT "\n");
601 }
602
603 struct stats
604 {
605         unsigned names;
606         unsigned space;
607         unsigned bcount;
608 };
609
610 static struct stats dx_show_leaf(struct inode *dir,
611                                 struct dx_hash_info *hinfo,
612                                 struct ext4_dir_entry_2 *de,
613                                 int size, int show_names)
614 {
615         unsigned names = 0, space = 0;
616         char *base = (char *) de;
617         struct dx_hash_info h = *hinfo;
618
619         printk("names: ");
620         while ((char *) de < base + size)
621         {
622                 if (de->inode)
623                 {
624                         if (show_names)
625                         {
626 #ifdef CONFIG_EXT4_FS_ENCRYPTION
627                                 int len;
628                                 char *name;
629                                 struct fscrypt_str fname_crypto_str =
630                                         FSTR_INIT(NULL, 0);
631                                 int res = 0;
632
633                                 name  = de->name;
634                                 len = de->name_len;
635                                 if (ext4_encrypted_inode(dir))
636                                         res = fscrypt_get_encryption_info(dir);
637                                 if (res) {
638                                         printk(KERN_WARNING "Error setting up"
639                                                " fname crypto: %d\n", res);
640                                 }
641                                 if (!fscrypt_has_encryption_key(dir)) {
642                                         /* Directory is not encrypted */
643                                         ext4fs_dirhash(de->name,
644                                                 de->name_len, &h);
645                                         printk("%*.s:(U)%x.%u ", len,
646                                                name, h.hash,
647                                                (unsigned) ((char *) de
648                                                            - base));
649                                 } else {
650                                         struct fscrypt_str de_name =
651                                                 FSTR_INIT(name, len);
652
653                                         /* Directory is encrypted */
654                                         res = fscrypt_fname_alloc_buffer(
655                                                 dir, len,
656                                                 &fname_crypto_str);
657                                         if (res)
658                                                 printk(KERN_WARNING "Error "
659                                                         "allocating crypto "
660                                                         "buffer--skipping "
661                                                         "crypto\n");
662                                         res = fscrypt_fname_disk_to_usr(dir,
663                                                 0, 0, &de_name,
664                                                 &fname_crypto_str);
665                                         if (res) {
666                                                 printk(KERN_WARNING "Error "
667                                                         "converting filename "
668                                                         "from disk to usr"
669                                                         "\n");
670                                                 name = "??";
671                                                 len = 2;
672                                         } else {
673                                                 name = fname_crypto_str.name;
674                                                 len = fname_crypto_str.len;
675                                         }
676                                         ext4fs_dirhash(de->name, de->name_len,
677                                                        &h);
678                                         printk("%*.s:(E)%x.%u ", len, name,
679                                                h.hash, (unsigned) ((char *) de
680                                                                    - base));
681                                         fscrypt_fname_free_buffer(
682                                                         &fname_crypto_str);
683                                 }
684 #else
685                                 int len = de->name_len;
686                                 char *name = de->name;
687                                 ext4fs_dirhash(de->name, de->name_len, &h);
688                                 printk("%*.s:%x.%u ", len, name, h.hash,
689                                        (unsigned) ((char *) de - base));
690 #endif
691                         }
692                         space += EXT4_DIR_REC_LEN(de->name_len);
693                         names++;
694                 }
695                 de = ext4_next_entry(de, size);
696         }
697         printk(KERN_CONT "(%i)\n", names);
698         return (struct stats) { names, space, 1 };
699 }
700
701 struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir,
702                              struct dx_entry *entries, int levels)
703 {
704         unsigned blocksize = dir->i_sb->s_blocksize;
705         unsigned count = dx_get_count(entries), names = 0, space = 0, i;
706         unsigned bcount = 0;
707         struct buffer_head *bh;
708         printk("%i indexed blocks...\n", count);
709         for (i = 0; i < count; i++, entries++)
710         {
711                 ext4_lblk_t block = dx_get_block(entries);
712                 ext4_lblk_t hash  = i ? dx_get_hash(entries): 0;
713                 u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash;
714                 struct stats stats;
715                 printk("%s%3u:%03u hash %8x/%8x ",levels?"":"   ", i, block, hash, range);
716                 bh = ext4_bread(NULL,dir, block, 0);
717                 if (!bh || IS_ERR(bh))
718                         continue;
719                 stats = levels?
720                    dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1):
721                    dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *)
722                         bh->b_data, blocksize, 0);
723                 names += stats.names;
724                 space += stats.space;
725                 bcount += stats.bcount;
726                 brelse(bh);
727         }
728         if (bcount)
729                 printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n",
730                        levels ? "" : "   ", names, space/bcount,
731                        (space/bcount)*100/blocksize);
732         return (struct stats) { names, space, bcount};
733 }
734 #endif /* DX_DEBUG */
735
736 /*
737  * Probe for a directory leaf block to search.
738  *
739  * dx_probe can return ERR_BAD_DX_DIR, which means there was a format
740  * error in the directory index, and the caller should fall back to
741  * searching the directory normally.  The callers of dx_probe **MUST**
742  * check for this error code, and make sure it never gets reflected
743  * back to userspace.
744  */
745 static struct dx_frame *
746 dx_probe(struct ext4_filename *fname, struct inode *dir,
747          struct dx_hash_info *hinfo, struct dx_frame *frame_in)
748 {
749         unsigned count, indirect;
750         struct dx_entry *at, *entries, *p, *q, *m;
751         struct dx_root *root;
752         struct dx_frame *frame = frame_in;
753         struct dx_frame *ret_err = ERR_PTR(ERR_BAD_DX_DIR);
754         u32 hash;
755
756         frame->bh = ext4_read_dirblock(dir, 0, INDEX);
757         if (IS_ERR(frame->bh))
758                 return (struct dx_frame *) frame->bh;
759
760         root = (struct dx_root *) frame->bh->b_data;
761         if (root->info.hash_version != DX_HASH_TEA &&
762             root->info.hash_version != DX_HASH_HALF_MD4 &&
763             root->info.hash_version != DX_HASH_LEGACY) {
764                 ext4_warning_inode(dir, "Unrecognised inode hash code %u",
765                                    root->info.hash_version);
766                 goto fail;
767         }
768         if (fname)
769                 hinfo = &fname->hinfo;
770         hinfo->hash_version = root->info.hash_version;
771         if (hinfo->hash_version <= DX_HASH_TEA)
772                 hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
773         hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed;
774         if (fname && fname_name(fname))
775                 ext4fs_dirhash(fname_name(fname), fname_len(fname), hinfo);
776         hash = hinfo->hash;
777
778         if (root->info.unused_flags & 1) {
779                 ext4_warning_inode(dir, "Unimplemented hash flags: %#06x",
780                                    root->info.unused_flags);
781                 goto fail;
782         }
783
784         indirect = root->info.indirect_levels;
785         if (indirect > 1) {
786                 ext4_warning_inode(dir, "Unimplemented hash depth: %#06x",
787                                    root->info.indirect_levels);
788                 goto fail;
789         }
790
791         entries = (struct dx_entry *)(((char *)&root->info) +
792                                       root->info.info_length);
793
794         if (dx_get_limit(entries) != dx_root_limit(dir,
795                                                    root->info.info_length)) {
796                 ext4_warning_inode(dir, "dx entry: limit %u != root limit %u",
797                                    dx_get_limit(entries),
798                                    dx_root_limit(dir, root->info.info_length));
799                 goto fail;
800         }
801
802         dxtrace(printk("Look up %x", hash));
803         while (1) {
804                 count = dx_get_count(entries);
805                 if (!count || count > dx_get_limit(entries)) {
806                         ext4_warning_inode(dir,
807                                            "dx entry: count %u beyond limit %u",
808                                            count, dx_get_limit(entries));
809                         goto fail;
810                 }
811
812                 p = entries + 1;
813                 q = entries + count - 1;
814                 while (p <= q) {
815                         m = p + (q - p) / 2;
816                         dxtrace(printk(KERN_CONT "."));
817                         if (dx_get_hash(m) > hash)
818                                 q = m - 1;
819                         else
820                                 p = m + 1;
821                 }
822
823                 if (0) { // linear search cross check
824                         unsigned n = count - 1;
825                         at = entries;
826                         while (n--)
827                         {
828                                 dxtrace(printk(KERN_CONT ","));
829                                 if (dx_get_hash(++at) > hash)
830                                 {
831                                         at--;
832                                         break;
833                                 }
834                         }
835                         assert (at == p - 1);
836                 }
837
838                 at = p - 1;
839                 dxtrace(printk(KERN_CONT " %x->%u\n",
840                                at == entries ? 0 : dx_get_hash(at),
841                                dx_get_block(at)));
842                 frame->entries = entries;
843                 frame->at = at;
844                 if (!indirect--)
845                         return frame;
846                 frame++;
847                 frame->bh = ext4_read_dirblock(dir, dx_get_block(at), INDEX);
848                 if (IS_ERR(frame->bh)) {
849                         ret_err = (struct dx_frame *) frame->bh;
850                         frame->bh = NULL;
851                         goto fail;
852                 }
853                 entries = ((struct dx_node *) frame->bh->b_data)->entries;
854
855                 if (dx_get_limit(entries) != dx_node_limit(dir)) {
856                         ext4_warning_inode(dir,
857                                 "dx entry: limit %u != node limit %u",
858                                 dx_get_limit(entries), dx_node_limit(dir));
859                         goto fail;
860                 }
861         }
862 fail:
863         while (frame >= frame_in) {
864                 brelse(frame->bh);
865                 frame--;
866         }
867
868         if (ret_err == ERR_PTR(ERR_BAD_DX_DIR))
869                 ext4_warning_inode(dir,
870                         "Corrupt directory, running e2fsck is recommended");
871         return ret_err;
872 }
873
874 static void dx_release(struct dx_frame *frames)
875 {
876         if (frames[0].bh == NULL)
877                 return;
878
879         if (((struct dx_root *)frames[0].bh->b_data)->info.indirect_levels)
880                 brelse(frames[1].bh);
881         brelse(frames[0].bh);
882 }
883
884 /*
885  * This function increments the frame pointer to search the next leaf
886  * block, and reads in the necessary intervening nodes if the search
887  * should be necessary.  Whether or not the search is necessary is
888  * controlled by the hash parameter.  If the hash value is even, then
889  * the search is only continued if the next block starts with that
890  * hash value.  This is used if we are searching for a specific file.
891  *
892  * If the hash value is HASH_NB_ALWAYS, then always go to the next block.
893  *
894  * This function returns 1 if the caller should continue to search,
895  * or 0 if it should not.  If there is an error reading one of the
896  * index blocks, it will a negative error code.
897  *
898  * If start_hash is non-null, it will be filled in with the starting
899  * hash of the next page.
900  */
901 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
902                                  struct dx_frame *frame,
903                                  struct dx_frame *frames,
904                                  __u32 *start_hash)
905 {
906         struct dx_frame *p;
907         struct buffer_head *bh;
908         int num_frames = 0;
909         __u32 bhash;
910
911         p = frame;
912         /*
913          * Find the next leaf page by incrementing the frame pointer.
914          * If we run out of entries in the interior node, loop around and
915          * increment pointer in the parent node.  When we break out of
916          * this loop, num_frames indicates the number of interior
917          * nodes need to be read.
918          */
919         while (1) {
920                 if (++(p->at) < p->entries + dx_get_count(p->entries))
921                         break;
922                 if (p == frames)
923                         return 0;
924                 num_frames++;
925                 p--;
926         }
927
928         /*
929          * If the hash is 1, then continue only if the next page has a
930          * continuation hash of any value.  This is used for readdir
931          * handling.  Otherwise, check to see if the hash matches the
932          * desired contiuation hash.  If it doesn't, return since
933          * there's no point to read in the successive index pages.
934          */
935         bhash = dx_get_hash(p->at);
936         if (start_hash)
937                 *start_hash = bhash;
938         if ((hash & 1) == 0) {
939                 if ((bhash & ~1) != hash)
940                         return 0;
941         }
942         /*
943          * If the hash is HASH_NB_ALWAYS, we always go to the next
944          * block so no check is necessary
945          */
946         while (num_frames--) {
947                 bh = ext4_read_dirblock(dir, dx_get_block(p->at), INDEX);
948                 if (IS_ERR(bh))
949                         return PTR_ERR(bh);
950                 p++;
951                 brelse(p->bh);
952                 p->bh = bh;
953                 p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
954         }
955         return 1;
956 }
957
958
959 /*
960  * This function fills a red-black tree with information from a
961  * directory block.  It returns the number directory entries loaded
962  * into the tree.  If there is an error it is returned in err.
963  */
964 static int htree_dirblock_to_tree(struct file *dir_file,
965                                   struct inode *dir, ext4_lblk_t block,
966                                   struct dx_hash_info *hinfo,
967                                   __u32 start_hash, __u32 start_minor_hash)
968 {
969         struct buffer_head *bh;
970         struct ext4_dir_entry_2 *de, *top;
971         int err = 0, count = 0;
972         struct fscrypt_str fname_crypto_str = FSTR_INIT(NULL, 0), tmp_str;
973
974         dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n",
975                                                         (unsigned long)block));
976         bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
977         if (IS_ERR(bh))
978                 return PTR_ERR(bh);
979
980         de = (struct ext4_dir_entry_2 *) bh->b_data;
981         top = (struct ext4_dir_entry_2 *) ((char *) de +
982                                            dir->i_sb->s_blocksize -
983                                            EXT4_DIR_REC_LEN(0));
984 #ifdef CONFIG_EXT4_FS_ENCRYPTION
985         /* Check if the directory is encrypted */
986         if (ext4_encrypted_inode(dir)) {
987                 err = fscrypt_get_encryption_info(dir);
988                 if (err < 0) {
989                         brelse(bh);
990                         return err;
991                 }
992                 err = fscrypt_fname_alloc_buffer(dir, EXT4_NAME_LEN,
993                                                      &fname_crypto_str);
994                 if (err < 0) {
995                         brelse(bh);
996                         return err;
997                 }
998         }
999 #endif
1000         for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) {
1001                 if (ext4_check_dir_entry(dir, NULL, de, bh,
1002                                 bh->b_data, bh->b_size,
1003                                 (block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb))
1004                                          + ((char *)de - bh->b_data))) {
1005                         /* silently ignore the rest of the block */
1006                         break;
1007                 }
1008                 ext4fs_dirhash(de->name, de->name_len, hinfo);
1009                 if ((hinfo->hash < start_hash) ||
1010                     ((hinfo->hash == start_hash) &&
1011                      (hinfo->minor_hash < start_minor_hash)))
1012                         continue;
1013                 if (de->inode == 0)
1014                         continue;
1015                 if (!ext4_encrypted_inode(dir)) {
1016                         tmp_str.name = de->name;
1017                         tmp_str.len = de->name_len;
1018                         err = ext4_htree_store_dirent(dir_file,
1019                                    hinfo->hash, hinfo->minor_hash, de,
1020                                    &tmp_str);
1021                 } else {
1022                         int save_len = fname_crypto_str.len;
1023                         struct fscrypt_str de_name = FSTR_INIT(de->name,
1024                                                                 de->name_len);
1025
1026                         /* Directory is encrypted */
1027                         err = fscrypt_fname_disk_to_usr(dir, hinfo->hash,
1028                                         hinfo->minor_hash, &de_name,
1029                                         &fname_crypto_str);
1030                         if (err) {
1031                                 count = err;
1032                                 goto errout;
1033                         }
1034                         err = ext4_htree_store_dirent(dir_file,
1035                                    hinfo->hash, hinfo->minor_hash, de,
1036                                         &fname_crypto_str);
1037                         fname_crypto_str.len = save_len;
1038                 }
1039                 if (err != 0) {
1040                         count = err;
1041                         goto errout;
1042                 }
1043                 count++;
1044         }
1045 errout:
1046         brelse(bh);
1047 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1048         fscrypt_fname_free_buffer(&fname_crypto_str);
1049 #endif
1050         return count;
1051 }
1052
1053
1054 /*
1055  * This function fills a red-black tree with information from a
1056  * directory.  We start scanning the directory in hash order, starting
1057  * at start_hash and start_minor_hash.
1058  *
1059  * This function returns the number of entries inserted into the tree,
1060  * or a negative error code.
1061  */
1062 int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
1063                          __u32 start_minor_hash, __u32 *next_hash)
1064 {
1065         struct dx_hash_info hinfo;
1066         struct ext4_dir_entry_2 *de;
1067         struct dx_frame frames[2], *frame;
1068         struct inode *dir;
1069         ext4_lblk_t block;
1070         int count = 0;
1071         int ret, err;
1072         __u32 hashval;
1073         struct fscrypt_str tmp_str;
1074
1075         dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n",
1076                        start_hash, start_minor_hash));
1077         dir = file_inode(dir_file);
1078         if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) {
1079                 hinfo.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
1080                 if (hinfo.hash_version <= DX_HASH_TEA)
1081                         hinfo.hash_version +=
1082                                 EXT4_SB(dir->i_sb)->s_hash_unsigned;
1083                 hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
1084                 if (ext4_has_inline_data(dir)) {
1085                         int has_inline_data = 1;
1086                         count = htree_inlinedir_to_tree(dir_file, dir, 0,
1087                                                         &hinfo, start_hash,
1088                                                         start_minor_hash,
1089                                                         &has_inline_data);
1090                         if (has_inline_data) {
1091                                 *next_hash = ~0;
1092                                 return count;
1093                         }
1094                 }
1095                 count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo,
1096                                                start_hash, start_minor_hash);
1097                 *next_hash = ~0;
1098                 return count;
1099         }
1100         hinfo.hash = start_hash;
1101         hinfo.minor_hash = 0;
1102         frame = dx_probe(NULL, dir, &hinfo, frames);
1103         if (IS_ERR(frame))
1104                 return PTR_ERR(frame);
1105
1106         /* Add '.' and '..' from the htree header */
1107         if (!start_hash && !start_minor_hash) {
1108                 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1109                 tmp_str.name = de->name;
1110                 tmp_str.len = de->name_len;
1111                 err = ext4_htree_store_dirent(dir_file, 0, 0,
1112                                               de, &tmp_str);
1113                 if (err != 0)
1114                         goto errout;
1115                 count++;
1116         }
1117         if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) {
1118                 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1119                 de = ext4_next_entry(de, dir->i_sb->s_blocksize);
1120                 tmp_str.name = de->name;
1121                 tmp_str.len = de->name_len;
1122                 err = ext4_htree_store_dirent(dir_file, 2, 0,
1123                                               de, &tmp_str);
1124                 if (err != 0)
1125                         goto errout;
1126                 count++;
1127         }
1128
1129         while (1) {
1130                 if (fatal_signal_pending(current)) {
1131                         err = -ERESTARTSYS;
1132                         goto errout;
1133                 }
1134                 cond_resched();
1135                 block = dx_get_block(frame->at);
1136                 ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
1137                                              start_hash, start_minor_hash);
1138                 if (ret < 0) {
1139                         err = ret;
1140                         goto errout;
1141                 }
1142                 count += ret;
1143                 hashval = ~0;
1144                 ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS,
1145                                             frame, frames, &hashval);
1146                 *next_hash = hashval;
1147                 if (ret < 0) {
1148                         err = ret;
1149                         goto errout;
1150                 }
1151                 /*
1152                  * Stop if:  (a) there are no more entries, or
1153                  * (b) we have inserted at least one entry and the
1154                  * next hash value is not a continuation
1155                  */
1156                 if ((ret == 0) ||
1157                     (count && ((hashval & 1) == 0)))
1158                         break;
1159         }
1160         dx_release(frames);
1161         dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, "
1162                        "next hash: %x\n", count, *next_hash));
1163         return count;
1164 errout:
1165         dx_release(frames);
1166         return (err);
1167 }
1168
1169 static inline int search_dirblock(struct buffer_head *bh,
1170                                   struct inode *dir,
1171                                   struct ext4_filename *fname,
1172                                   const struct qstr *d_name,
1173                                   unsigned int offset,
1174                                   struct ext4_dir_entry_2 **res_dir)
1175 {
1176         return ext4_search_dir(bh, bh->b_data, dir->i_sb->s_blocksize, dir,
1177                                fname, d_name, offset, res_dir);
1178 }
1179
1180 /*
1181  * Directory block splitting, compacting
1182  */
1183
1184 /*
1185  * Create map of hash values, offsets, and sizes, stored at end of block.
1186  * Returns number of entries mapped.
1187  */
1188 static int dx_make_map(struct inode *dir, struct ext4_dir_entry_2 *de,
1189                        unsigned blocksize, struct dx_hash_info *hinfo,
1190                        struct dx_map_entry *map_tail)
1191 {
1192         int count = 0;
1193         char *base = (char *) de;
1194         struct dx_hash_info h = *hinfo;
1195
1196         while ((char *) de < base + blocksize) {
1197                 if (de->name_len && de->inode) {
1198                         ext4fs_dirhash(de->name, de->name_len, &h);
1199                         map_tail--;
1200                         map_tail->hash = h.hash;
1201                         map_tail->offs = ((char *) de - base)>>2;
1202                         map_tail->size = le16_to_cpu(de->rec_len);
1203                         count++;
1204                         cond_resched();
1205                 }
1206                 /* XXX: do we need to check rec_len == 0 case? -Chris */
1207                 de = ext4_next_entry(de, blocksize);
1208         }
1209         return count;
1210 }
1211
1212 /* Sort map by hash value */
1213 static void dx_sort_map (struct dx_map_entry *map, unsigned count)
1214 {
1215         struct dx_map_entry *p, *q, *top = map + count - 1;
1216         int more;
1217         /* Combsort until bubble sort doesn't suck */
1218         while (count > 2) {
1219                 count = count*10/13;
1220                 if (count - 9 < 2) /* 9, 10 -> 11 */
1221                         count = 11;
1222                 for (p = top, q = p - count; q >= map; p--, q--)
1223                         if (p->hash < q->hash)
1224                                 swap(*p, *q);
1225         }
1226         /* Garden variety bubble sort */
1227         do {
1228                 more = 0;
1229                 q = top;
1230                 while (q-- > map) {
1231                         if (q[1].hash >= q[0].hash)
1232                                 continue;
1233                         swap(*(q+1), *q);
1234                         more = 1;
1235                 }
1236         } while(more);
1237 }
1238
1239 static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block)
1240 {
1241         struct dx_entry *entries = frame->entries;
1242         struct dx_entry *old = frame->at, *new = old + 1;
1243         int count = dx_get_count(entries);
1244
1245         assert(count < dx_get_limit(entries));
1246         assert(old < entries + count);
1247         memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
1248         dx_set_hash(new, hash);
1249         dx_set_block(new, block);
1250         dx_set_count(entries, count + 1);
1251 }
1252
1253 /*
1254  * Test whether a directory entry matches the filename being searched for.
1255  *
1256  * Return: %true if the directory entry matches, otherwise %false.
1257  */
1258 static inline bool ext4_match(const struct ext4_filename *fname,
1259                               const struct ext4_dir_entry_2 *de)
1260 {
1261         const void *name = fname_name(fname);
1262         u32 len = fname_len(fname);
1263
1264         if (!de->inode)
1265                 return false;
1266
1267 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1268         if (unlikely(!name)) {
1269                 if (fname->usr_fname->name[0] == '_') {
1270                         int ret;
1271                         if (de->name_len <= 32)
1272                                 return 0;
1273                         ret = memcmp(de->name + ((de->name_len - 17) & ~15),
1274                                      fname->crypto_buf.name + 8, 16);
1275                         return (ret == 0) ? 1 : 0;
1276                 }
1277                 name = fname->crypto_buf.name;
1278                 len = fname->crypto_buf.len;
1279         }
1280 #endif
1281         if (de->name_len != len)
1282                 return 0;
1283         return (memcmp(de->name, name, len) == 0) ? 1 : 0;
1284 }
1285
1286 /*
1287  * Returns 0 if not found, -1 on failure, and 1 on success
1288  */
1289 int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size,
1290                     struct inode *dir, struct ext4_filename *fname,
1291                     const struct qstr *d_name,
1292                     unsigned int offset, struct ext4_dir_entry_2 **res_dir)
1293 {
1294         struct ext4_dir_entry_2 * de;
1295         char * dlimit;
1296         int de_len;
1297
1298         de = (struct ext4_dir_entry_2 *)search_buf;
1299         dlimit = search_buf + buf_size;
1300         while ((char *) de < dlimit) {
1301                 /* this code is executed quadratically often */
1302                 /* do minimal checking `by hand' */
1303                 if ((char *) de + de->name_len <= dlimit &&
1304                     ext4_match(fname, de)) {
1305                         /* found a match - just to be sure, do
1306                          * a full check */
1307                         if (ext4_check_dir_entry(dir, NULL, de, bh, search_buf,
1308                                                  buf_size, offset))
1309                                 return -1;
1310                         *res_dir = de;
1311                         return 1;
1312                 }
1313                 /* prevent looping on a bad block */
1314                 de_len = ext4_rec_len_from_disk(de->rec_len,
1315                                                 dir->i_sb->s_blocksize);
1316                 if (de_len <= 0)
1317                         return -1;
1318                 offset += de_len;
1319                 de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
1320         }
1321         return 0;
1322 }
1323
1324 static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block,
1325                                struct ext4_dir_entry *de)
1326 {
1327         struct super_block *sb = dir->i_sb;
1328
1329         if (!is_dx(dir))
1330                 return 0;
1331         if (block == 0)
1332                 return 1;
1333         if (de->inode == 0 &&
1334             ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) ==
1335                         sb->s_blocksize)
1336                 return 1;
1337         return 0;
1338 }
1339
1340 /*
1341  *      ext4_find_entry()
1342  *
1343  * finds an entry in the specified directory with the wanted name. It
1344  * returns the cache buffer in which the entry was found, and the entry
1345  * itself (as a parameter - res_dir). It does NOT read the inode of the
1346  * entry - you'll have to do that yourself if you want to.
1347  *
1348  * The returned buffer_head has ->b_count elevated.  The caller is expected
1349  * to brelse() it when appropriate.
1350  */
1351 static struct buffer_head * ext4_find_entry (struct inode *dir,
1352                                         const struct qstr *d_name,
1353                                         struct ext4_dir_entry_2 **res_dir,
1354                                         int *inlined)
1355 {
1356         struct super_block *sb;
1357         struct buffer_head *bh_use[NAMEI_RA_SIZE];
1358         struct buffer_head *bh, *ret = NULL;
1359         ext4_lblk_t start, block, b;
1360         const u8 *name = d_name->name;
1361         int ra_max = 0;         /* Number of bh's in the readahead
1362                                    buffer, bh_use[] */
1363         int ra_ptr = 0;         /* Current index into readahead
1364                                    buffer */
1365         int num = 0;
1366         ext4_lblk_t  nblocks;
1367         int i, namelen, retval;
1368         struct ext4_filename fname;
1369
1370         *res_dir = NULL;
1371         sb = dir->i_sb;
1372         namelen = d_name->len;
1373         if (namelen > EXT4_NAME_LEN)
1374                 return NULL;
1375
1376         retval = ext4_fname_setup_filename(dir, d_name, 1, &fname);
1377         if (retval == -ENOENT)
1378                 return NULL;
1379         if (retval)
1380                 return ERR_PTR(retval);
1381
1382         if (ext4_has_inline_data(dir)) {
1383                 int has_inline_data = 1;
1384                 ret = ext4_find_inline_entry(dir, &fname, d_name, res_dir,
1385                                              &has_inline_data);
1386                 if (has_inline_data) {
1387                         if (inlined)
1388                                 *inlined = 1;
1389                         goto cleanup_and_exit;
1390                 }
1391         }
1392
1393         if ((namelen <= 2) && (name[0] == '.') &&
1394             (name[1] == '.' || name[1] == '\0')) {
1395                 /*
1396                  * "." or ".." will only be in the first block
1397                  * NFS may look up ".."; "." should be handled by the VFS
1398                  */
1399                 block = start = 0;
1400                 nblocks = 1;
1401                 goto restart;
1402         }
1403         if (is_dx(dir)) {
1404                 ret = ext4_dx_find_entry(dir, &fname, res_dir);
1405                 /*
1406                  * On success, or if the error was file not found,
1407                  * return.  Otherwise, fall back to doing a search the
1408                  * old fashioned way.
1409                  */
1410                 if (!IS_ERR(ret) || PTR_ERR(ret) != ERR_BAD_DX_DIR)
1411                         goto cleanup_and_exit;
1412                 dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
1413                                "falling back\n"));
1414                 ret = NULL;
1415         }
1416         nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1417         if (!nblocks) {
1418                 ret = NULL;
1419                 goto cleanup_and_exit;
1420         }
1421         start = EXT4_I(dir)->i_dir_start_lookup;
1422         if (start >= nblocks)
1423                 start = 0;
1424         block = start;
1425 restart:
1426         do {
1427                 /*
1428                  * We deal with the read-ahead logic here.
1429                  */
1430                 cond_resched();
1431                 if (ra_ptr >= ra_max) {
1432                         /* Refill the readahead buffer */
1433                         ra_ptr = 0;
1434                         b = block;
1435                         for (ra_max = 0; ra_max < NAMEI_RA_SIZE; ra_max++) {
1436                                 /*
1437                                  * Terminate if we reach the end of the
1438                                  * directory and must wrap, or if our
1439                                  * search has finished at this block.
1440                                  */
1441                                 if (b >= nblocks || (num && block == start)) {
1442                                         bh_use[ra_max] = NULL;
1443                                         break;
1444                                 }
1445                                 num++;
1446                                 bh = ext4_getblk(NULL, dir, b++, 0);
1447                                 if (IS_ERR(bh)) {
1448                                         if (ra_max == 0) {
1449                                                 ret = bh;
1450                                                 goto cleanup_and_exit;
1451                                         }
1452                                         break;
1453                                 }
1454                                 bh_use[ra_max] = bh;
1455                                 if (bh)
1456                                         ll_rw_block(REQ_OP_READ,
1457                                                     REQ_META | REQ_PRIO,
1458                                                     1, &bh);
1459                         }
1460                 }
1461                 if ((bh = bh_use[ra_ptr++]) == NULL)
1462                         goto next;
1463                 wait_on_buffer(bh);
1464                 if (!buffer_uptodate(bh)) {
1465                         /* read error, skip block & hope for the best */
1466                         EXT4_ERROR_INODE(dir, "reading directory lblock %lu",
1467                                          (unsigned long) block);
1468                         brelse(bh);
1469                         goto next;
1470                 }
1471                 if (!buffer_verified(bh) &&
1472                     !is_dx_internal_node(dir, block,
1473                                          (struct ext4_dir_entry *)bh->b_data) &&
1474                     !ext4_dirent_csum_verify(dir,
1475                                 (struct ext4_dir_entry *)bh->b_data)) {
1476                         EXT4_ERROR_INODE(dir, "checksumming directory "
1477                                          "block %lu", (unsigned long)block);
1478                         brelse(bh);
1479                         goto next;
1480                 }
1481                 set_buffer_verified(bh);
1482                 i = search_dirblock(bh, dir, &fname, d_name,
1483                             block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
1484                 if (i == 1) {
1485                         EXT4_I(dir)->i_dir_start_lookup = block;
1486                         ret = bh;
1487                         goto cleanup_and_exit;
1488                 } else {
1489                         brelse(bh);
1490                         if (i < 0)
1491                                 goto cleanup_and_exit;
1492                 }
1493         next:
1494                 if (++block >= nblocks)
1495                         block = 0;
1496         } while (block != start);
1497
1498         /*
1499          * If the directory has grown while we were searching, then
1500          * search the last part of the directory before giving up.
1501          */
1502         block = nblocks;
1503         nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1504         if (block < nblocks) {
1505                 start = 0;
1506                 goto restart;
1507         }
1508
1509 cleanup_and_exit:
1510         /* Clean up the read-ahead blocks */
1511         for (; ra_ptr < ra_max; ra_ptr++)
1512                 brelse(bh_use[ra_ptr]);
1513         ext4_fname_free_filename(&fname);
1514         return ret;
1515 }
1516
1517 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
1518                         struct ext4_filename *fname,
1519                         struct ext4_dir_entry_2 **res_dir)
1520 {
1521         struct super_block * sb = dir->i_sb;
1522         struct dx_frame frames[2], *frame;
1523         const struct qstr *d_name = fname->usr_fname;
1524         struct buffer_head *bh;
1525         ext4_lblk_t block;
1526         int retval;
1527
1528 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1529         *res_dir = NULL;
1530 #endif
1531         frame = dx_probe(fname, dir, NULL, frames);
1532         if (IS_ERR(frame))
1533                 return (struct buffer_head *) frame;
1534         do {
1535                 block = dx_get_block(frame->at);
1536                 bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
1537                 if (IS_ERR(bh))
1538                         goto errout;
1539
1540                 retval = search_dirblock(bh, dir, fname, d_name,
1541                                          block << EXT4_BLOCK_SIZE_BITS(sb),
1542                                          res_dir);
1543                 if (retval == 1)
1544                         goto success;
1545                 brelse(bh);
1546                 if (retval == -1) {
1547                         bh = ERR_PTR(ERR_BAD_DX_DIR);
1548                         goto errout;
1549                 }
1550
1551                 /* Check to see if we should continue to search */
1552                 retval = ext4_htree_next_block(dir, fname->hinfo.hash, frame,
1553                                                frames, NULL);
1554                 if (retval < 0) {
1555                         ext4_warning_inode(dir,
1556                                 "error %d reading directory index block",
1557                                 retval);
1558                         bh = ERR_PTR(retval);
1559                         goto errout;
1560                 }
1561         } while (retval == 1);
1562
1563         bh = NULL;
1564 errout:
1565         dxtrace(printk(KERN_DEBUG "%s not found\n", d_name->name));
1566 success:
1567         dx_release(frames);
1568         return bh;
1569 }
1570
1571 static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
1572 {
1573         struct inode *inode;
1574         struct ext4_dir_entry_2 *de;
1575         struct buffer_head *bh;
1576
1577         if (ext4_encrypted_inode(dir)) {
1578                 int res = fscrypt_get_encryption_info(dir);
1579
1580                 /*
1581                  * DCACHE_ENCRYPTED_WITH_KEY is set if the dentry is
1582                  * created while the directory was encrypted and we
1583                  * have access to the key.
1584                  */
1585                 if (fscrypt_has_encryption_key(dir))
1586                         fscrypt_set_encrypted_dentry(dentry);
1587                 fscrypt_set_d_op(dentry);
1588                 if (res && res != -ENOKEY)
1589                         return ERR_PTR(res);
1590         }
1591
1592        if (dentry->d_name.len > EXT4_NAME_LEN)
1593                return ERR_PTR(-ENAMETOOLONG);
1594
1595         bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
1596         if (IS_ERR(bh))
1597                 return (struct dentry *) bh;
1598         inode = NULL;
1599         if (bh) {
1600                 __u32 ino = le32_to_cpu(de->inode);
1601                 brelse(bh);
1602                 if (!ext4_valid_inum(dir->i_sb, ino)) {
1603                         EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
1604                         return ERR_PTR(-EFSCORRUPTED);
1605                 }
1606                 if (unlikely(ino == dir->i_ino)) {
1607                         EXT4_ERROR_INODE(dir, "'%pd' linked to parent dir",
1608                                          dentry);
1609                         return ERR_PTR(-EFSCORRUPTED);
1610                 }
1611                 inode = ext4_iget(dir->i_sb, ino, EXT4_IGET_NORMAL);
1612                 if (inode == ERR_PTR(-ESTALE)) {
1613                         EXT4_ERROR_INODE(dir,
1614                                          "deleted inode referenced: %u",
1615                                          ino);
1616                         return ERR_PTR(-EFSCORRUPTED);
1617                 }
1618                 if (!IS_ERR(inode) && ext4_encrypted_inode(dir) &&
1619                     (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
1620                     !fscrypt_has_permitted_context(dir, inode)) {
1621                         int nokey = ext4_encrypted_inode(inode) &&
1622                                 !fscrypt_has_encryption_key(inode);
1623                         if (nokey) {
1624                                 iput(inode);
1625                                 return ERR_PTR(-ENOKEY);
1626                         }
1627                         ext4_warning(inode->i_sb,
1628                                      "Inconsistent encryption contexts: %lu/%lu",
1629                                      (unsigned long) dir->i_ino,
1630                                      (unsigned long) inode->i_ino);
1631                         iput(inode);
1632                         return ERR_PTR(-EPERM);
1633                 }
1634         }
1635         return d_splice_alias(inode, dentry);
1636 }
1637
1638
1639 struct dentry *ext4_get_parent(struct dentry *child)
1640 {
1641         __u32 ino;
1642         static const struct qstr dotdot = QSTR_INIT("..", 2);
1643         struct ext4_dir_entry_2 * de;
1644         struct buffer_head *bh;
1645
1646         bh = ext4_find_entry(d_inode(child), &dotdot, &de, NULL);
1647         if (IS_ERR(bh))
1648                 return (struct dentry *) bh;
1649         if (!bh)
1650                 return ERR_PTR(-ENOENT);
1651         ino = le32_to_cpu(de->inode);
1652         brelse(bh);
1653
1654         if (!ext4_valid_inum(child->d_sb, ino)) {
1655                 EXT4_ERROR_INODE(d_inode(child),
1656                                  "bad parent inode number: %u", ino);
1657                 return ERR_PTR(-EFSCORRUPTED);
1658         }
1659
1660         return d_obtain_alias(ext4_iget(child->d_sb, ino, EXT4_IGET_NORMAL));
1661 }
1662
1663 /*
1664  * Move count entries from end of map between two memory locations.
1665  * Returns pointer to last entry moved.
1666  */
1667 static struct ext4_dir_entry_2 *
1668 dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count,
1669                 unsigned blocksize)
1670 {
1671         unsigned rec_len = 0;
1672
1673         while (count--) {
1674                 struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
1675                                                 (from + (map->offs<<2));
1676                 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1677                 memcpy (to, de, rec_len);
1678                 ((struct ext4_dir_entry_2 *) to)->rec_len =
1679                                 ext4_rec_len_to_disk(rec_len, blocksize);
1680                 de->inode = 0;
1681                 map++;
1682                 to += rec_len;
1683         }
1684         return (struct ext4_dir_entry_2 *) (to - rec_len);
1685 }
1686
1687 /*
1688  * Compact each dir entry in the range to the minimal rec_len.
1689  * Returns pointer to last entry in range.
1690  */
1691 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize)
1692 {
1693         struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
1694         unsigned rec_len = 0;
1695
1696         prev = to = de;
1697         while ((char*)de < base + blocksize) {
1698                 next = ext4_next_entry(de, blocksize);
1699                 if (de->inode && de->name_len) {
1700                         rec_len = EXT4_DIR_REC_LEN(de->name_len);
1701                         if (de > to)
1702                                 memmove(to, de, rec_len);
1703                         to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
1704                         prev = to;
1705                         to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
1706                 }
1707                 de = next;
1708         }
1709         return prev;
1710 }
1711
1712 /*
1713  * Split a full leaf block to make room for a new dir entry.
1714  * Allocate a new block, and move entries so that they are approx. equally full.
1715  * Returns pointer to de in block into which the new entry will be inserted.
1716  */
1717 static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
1718                         struct buffer_head **bh,struct dx_frame *frame,
1719                         struct dx_hash_info *hinfo)
1720 {
1721         unsigned blocksize = dir->i_sb->s_blocksize;
1722         unsigned count, continued;
1723         struct buffer_head *bh2;
1724         ext4_lblk_t newblock;
1725         u32 hash2;
1726         struct dx_map_entry *map;
1727         char *data1 = (*bh)->b_data, *data2;
1728         unsigned split, move, size;
1729         struct ext4_dir_entry_2 *de = NULL, *de2;
1730         struct ext4_dir_entry_tail *t;
1731         int     csum_size = 0;
1732         int     err = 0, i;
1733
1734         if (ext4_has_metadata_csum(dir->i_sb))
1735                 csum_size = sizeof(struct ext4_dir_entry_tail);
1736
1737         bh2 = ext4_append(handle, dir, &newblock);
1738         if (IS_ERR(bh2)) {
1739                 brelse(*bh);
1740                 *bh = NULL;
1741                 return (struct ext4_dir_entry_2 *) bh2;
1742         }
1743
1744         BUFFER_TRACE(*bh, "get_write_access");
1745         err = ext4_journal_get_write_access(handle, *bh);
1746         if (err)
1747                 goto journal_error;
1748
1749         BUFFER_TRACE(frame->bh, "get_write_access");
1750         err = ext4_journal_get_write_access(handle, frame->bh);
1751         if (err)
1752                 goto journal_error;
1753
1754         data2 = bh2->b_data;
1755
1756         /* create map in the end of data2 block */
1757         map = (struct dx_map_entry *) (data2 + blocksize);
1758         count = dx_make_map(dir, (struct ext4_dir_entry_2 *) data1,
1759                              blocksize, hinfo, map);
1760         map -= count;
1761         dx_sort_map(map, count);
1762         /* Ensure that neither split block is over half full */
1763         size = 0;
1764         move = 0;
1765         for (i = count-1; i >= 0; i--) {
1766                 /* is more than half of this entry in 2nd half of the block? */
1767                 if (size + map[i].size/2 > blocksize/2)
1768                         break;
1769                 size += map[i].size;
1770                 move++;
1771         }
1772         /*
1773          * map index at which we will split
1774          *
1775          * If the sum of active entries didn't exceed half the block size, just
1776          * split it in half by count; each resulting block will have at least
1777          * half the space free.
1778          */
1779         if (i > 0)
1780                 split = count - move;
1781         else
1782                 split = count/2;
1783
1784         hash2 = map[split].hash;
1785         continued = hash2 == map[split - 1].hash;
1786         dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
1787                         (unsigned long)dx_get_block(frame->at),
1788                                         hash2, split, count-split));
1789
1790         /* Fancy dance to stay within two buffers */
1791         de2 = dx_move_dirents(data1, data2, map + split, count - split,
1792                               blocksize);
1793         de = dx_pack_dirents(data1, blocksize);
1794         de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
1795                                            (char *) de,
1796                                            blocksize);
1797         de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
1798                                             (char *) de2,
1799                                             blocksize);
1800         if (csum_size) {
1801                 t = EXT4_DIRENT_TAIL(data2, blocksize);
1802                 initialize_dirent_tail(t, blocksize);
1803
1804                 t = EXT4_DIRENT_TAIL(data1, blocksize);
1805                 initialize_dirent_tail(t, blocksize);
1806         }
1807
1808         dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,
1809                         blocksize, 1));
1810         dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,
1811                         blocksize, 1));
1812
1813         /* Which block gets the new entry? */
1814         if (hinfo->hash >= hash2) {
1815                 swap(*bh, bh2);
1816                 de = de2;
1817         }
1818         dx_insert_block(frame, hash2 + continued, newblock);
1819         err = ext4_handle_dirty_dirent_node(handle, dir, bh2);
1820         if (err)
1821                 goto journal_error;
1822         err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
1823         if (err)
1824                 goto journal_error;
1825         brelse(bh2);
1826         dxtrace(dx_show_index("frame", frame->entries));
1827         return de;
1828
1829 journal_error:
1830         brelse(*bh);
1831         brelse(bh2);
1832         *bh = NULL;
1833         ext4_std_error(dir->i_sb, err);
1834         return ERR_PTR(err);
1835 }
1836
1837 int ext4_find_dest_de(struct inode *dir, struct inode *inode,
1838                       struct buffer_head *bh,
1839                       void *buf, int buf_size,
1840                       struct ext4_filename *fname,
1841                       struct ext4_dir_entry_2 **dest_de)
1842 {
1843         struct ext4_dir_entry_2 *de;
1844         unsigned short reclen = EXT4_DIR_REC_LEN(fname_len(fname));
1845         int nlen, rlen;
1846         unsigned int offset = 0;
1847         char *top;
1848
1849         de = (struct ext4_dir_entry_2 *)buf;
1850         top = buf + buf_size - reclen;
1851         while ((char *) de <= top) {
1852                 if (ext4_check_dir_entry(dir, NULL, de, bh,
1853                                          buf, buf_size, offset))
1854                         return -EFSCORRUPTED;
1855                 if (ext4_match(fname, de))
1856                         return -EEXIST;
1857                 nlen = EXT4_DIR_REC_LEN(de->name_len);
1858                 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1859                 if ((de->inode ? rlen - nlen : rlen) >= reclen)
1860                         break;
1861                 de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
1862                 offset += rlen;
1863         }
1864         if ((char *) de > top)
1865                 return -ENOSPC;
1866
1867         *dest_de = de;
1868         return 0;
1869 }
1870
1871 int ext4_insert_dentry(struct inode *dir,
1872                        struct inode *inode,
1873                        struct ext4_dir_entry_2 *de,
1874                        int buf_size,
1875                        struct ext4_filename *fname)
1876 {
1877
1878         int nlen, rlen;
1879
1880         nlen = EXT4_DIR_REC_LEN(de->name_len);
1881         rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1882         if (de->inode) {
1883                 struct ext4_dir_entry_2 *de1 =
1884                         (struct ext4_dir_entry_2 *)((char *)de + nlen);
1885                 de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size);
1886                 de->rec_len = ext4_rec_len_to_disk(nlen, buf_size);
1887                 de = de1;
1888         }
1889         de->file_type = EXT4_FT_UNKNOWN;
1890         de->inode = cpu_to_le32(inode->i_ino);
1891         ext4_set_de_type(inode->i_sb, de, inode->i_mode);
1892         de->name_len = fname_len(fname);
1893         memcpy(de->name, fname_name(fname), fname_len(fname));
1894         return 0;
1895 }
1896
1897 /*
1898  * Add a new entry into a directory (leaf) block.  If de is non-NULL,
1899  * it points to a directory entry which is guaranteed to be large
1900  * enough for new directory entry.  If de is NULL, then
1901  * add_dirent_to_buf will attempt search the directory block for
1902  * space.  It will return -ENOSPC if no space is available, and -EIO
1903  * and -EEXIST if directory entry already exists.
1904  */
1905 static int add_dirent_to_buf(handle_t *handle, struct ext4_filename *fname,
1906                              struct inode *dir,
1907                              struct inode *inode, struct ext4_dir_entry_2 *de,
1908                              struct buffer_head *bh)
1909 {
1910         unsigned int    blocksize = dir->i_sb->s_blocksize;
1911         int             csum_size = 0;
1912         int             err;
1913
1914         if (ext4_has_metadata_csum(inode->i_sb))
1915                 csum_size = sizeof(struct ext4_dir_entry_tail);
1916
1917         if (!de) {
1918                 err = ext4_find_dest_de(dir, inode, bh, bh->b_data,
1919                                         blocksize - csum_size, fname, &de);
1920                 if (err)
1921                         return err;
1922         }
1923         BUFFER_TRACE(bh, "get_write_access");
1924         err = ext4_journal_get_write_access(handle, bh);
1925         if (err) {
1926                 ext4_std_error(dir->i_sb, err);
1927                 return err;
1928         }
1929
1930         /* By now the buffer is marked for journaling. Due to crypto operations,
1931          * the following function call may fail */
1932         err = ext4_insert_dentry(dir, inode, de, blocksize, fname);
1933         if (err < 0)
1934                 return err;
1935
1936         /*
1937          * XXX shouldn't update any times until successful
1938          * completion of syscall, but too many callers depend
1939          * on this.
1940          *
1941          * XXX similarly, too many callers depend on
1942          * ext4_new_inode() setting the times, but error
1943          * recovery deletes the inode, so the worst that can
1944          * happen is that the times are slightly out of date
1945          * and/or different from the directory change time.
1946          */
1947         dir->i_mtime = dir->i_ctime = ext4_current_time(dir);
1948         ext4_update_dx_flag(dir);
1949         dir->i_version++;
1950         ext4_mark_inode_dirty(handle, dir);
1951         BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1952         err = ext4_handle_dirty_dirent_node(handle, dir, bh);
1953         if (err)
1954                 ext4_std_error(dir->i_sb, err);
1955         return 0;
1956 }
1957
1958 /*
1959  * This converts a one block unindexed directory to a 3 block indexed
1960  * directory, and adds the dentry to the indexed directory.
1961  */
1962 static int make_indexed_dir(handle_t *handle, struct ext4_filename *fname,
1963                             struct inode *dir,
1964                             struct inode *inode, struct buffer_head *bh)
1965 {
1966         struct buffer_head *bh2;
1967         struct dx_root  *root;
1968         struct dx_frame frames[2], *frame;
1969         struct dx_entry *entries;
1970         struct ext4_dir_entry_2 *de, *de2;
1971         struct ext4_dir_entry_tail *t;
1972         char            *data1, *top;
1973         unsigned        len;
1974         int             retval;
1975         unsigned        blocksize;
1976         ext4_lblk_t  block;
1977         struct fake_dirent *fde;
1978         int csum_size = 0;
1979
1980         if (ext4_has_metadata_csum(inode->i_sb))
1981                 csum_size = sizeof(struct ext4_dir_entry_tail);
1982
1983         blocksize =  dir->i_sb->s_blocksize;
1984         dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
1985         BUFFER_TRACE(bh, "get_write_access");
1986         retval = ext4_journal_get_write_access(handle, bh);
1987         if (retval) {
1988                 ext4_std_error(dir->i_sb, retval);
1989                 brelse(bh);
1990                 return retval;
1991         }
1992         root = (struct dx_root *) bh->b_data;
1993
1994         /* The 0th block becomes the root, move the dirents out */
1995         fde = &root->dotdot;
1996         de = (struct ext4_dir_entry_2 *)((char *)fde +
1997                 ext4_rec_len_from_disk(fde->rec_len, blocksize));
1998         if ((char *) de >= (((char *) root) + blocksize)) {
1999                 EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
2000                 brelse(bh);
2001                 return -EFSCORRUPTED;
2002         }
2003         len = ((char *) root) + (blocksize - csum_size) - (char *) de;
2004
2005         /* Allocate new block for the 0th block's dirents */
2006         bh2 = ext4_append(handle, dir, &block);
2007         if (IS_ERR(bh2)) {
2008                 brelse(bh);
2009                 return PTR_ERR(bh2);
2010         }
2011         ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
2012         data1 = bh2->b_data;
2013
2014         memcpy (data1, de, len);
2015         de = (struct ext4_dir_entry_2 *) data1;
2016         top = data1 + len;
2017         while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top)
2018                 de = de2;
2019         de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
2020                                            (char *) de,
2021                                            blocksize);
2022
2023         if (csum_size) {
2024                 t = EXT4_DIRENT_TAIL(data1, blocksize);
2025                 initialize_dirent_tail(t, blocksize);
2026         }
2027
2028         /* Initialize the root; the dot dirents already exist */
2029         de = (struct ext4_dir_entry_2 *) (&root->dotdot);
2030         de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
2031                                            blocksize);
2032         memset (&root->info, 0, sizeof(root->info));
2033         root->info.info_length = sizeof(root->info);
2034         root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
2035         entries = root->entries;
2036         dx_set_block(entries, 1);
2037         dx_set_count(entries, 1);
2038         dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
2039
2040         /* Initialize as for dx_probe */
2041         fname->hinfo.hash_version = root->info.hash_version;
2042         if (fname->hinfo.hash_version <= DX_HASH_TEA)
2043                 fname->hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
2044         fname->hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
2045         ext4fs_dirhash(fname_name(fname), fname_len(fname), &fname->hinfo);
2046
2047         memset(frames, 0, sizeof(frames));
2048         frame = frames;
2049         frame->entries = entries;
2050         frame->at = entries;
2051         frame->bh = bh;
2052
2053         retval = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2054         if (retval)
2055                 goto out_frames;        
2056         retval = ext4_handle_dirty_dirent_node(handle, dir, bh2);
2057         if (retval)
2058                 goto out_frames;        
2059
2060         de = do_split(handle,dir, &bh2, frame, &fname->hinfo);
2061         if (IS_ERR(de)) {
2062                 retval = PTR_ERR(de);
2063                 goto out_frames;
2064         }
2065
2066         retval = add_dirent_to_buf(handle, fname, dir, inode, de, bh2);
2067 out_frames:
2068         /*
2069          * Even if the block split failed, we have to properly write
2070          * out all the changes we did so far. Otherwise we can end up
2071          * with corrupted filesystem.
2072          */
2073         if (retval)
2074                 ext4_mark_inode_dirty(handle, dir);
2075         dx_release(frames);
2076         brelse(bh2);
2077         return retval;
2078 }
2079
2080 /*
2081  *      ext4_add_entry()
2082  *
2083  * adds a file entry to the specified directory, using the same
2084  * semantics as ext4_find_entry(). It returns NULL if it failed.
2085  *
2086  * NOTE!! The inode part of 'de' is left at 0 - which means you
2087  * may not sleep between calling this and putting something into
2088  * the entry, as someone else might have used it while you slept.
2089  */
2090 static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
2091                           struct inode *inode)
2092 {
2093         struct inode *dir = d_inode(dentry->d_parent);
2094         struct buffer_head *bh = NULL;
2095         struct ext4_dir_entry_2 *de;
2096         struct ext4_dir_entry_tail *t;
2097         struct super_block *sb;
2098         struct ext4_filename fname;
2099         int     retval;
2100         int     dx_fallback=0;
2101         unsigned blocksize;
2102         ext4_lblk_t block, blocks;
2103         int     csum_size = 0;
2104
2105         if (ext4_has_metadata_csum(inode->i_sb))
2106                 csum_size = sizeof(struct ext4_dir_entry_tail);
2107
2108         sb = dir->i_sb;
2109         blocksize = sb->s_blocksize;
2110         if (!dentry->d_name.len)
2111                 return -EINVAL;
2112
2113         retval = ext4_fname_setup_filename(dir, &dentry->d_name, 0, &fname);
2114         if (retval)
2115                 return retval;
2116
2117         if (ext4_has_inline_data(dir)) {
2118                 retval = ext4_try_add_inline_entry(handle, &fname, dir, inode);
2119                 if (retval < 0)
2120                         goto out;
2121                 if (retval == 1) {
2122                         retval = 0;
2123                         goto out;
2124                 }
2125         }
2126
2127         if (is_dx(dir)) {
2128                 retval = ext4_dx_add_entry(handle, &fname, dir, inode);
2129                 if (!retval || (retval != ERR_BAD_DX_DIR))
2130                         goto out;
2131                 /* Can we just ignore htree data? */
2132                 if (ext4_has_metadata_csum(sb)) {
2133                         EXT4_ERROR_INODE(dir,
2134                                 "Directory has corrupted htree index.");
2135                         retval = -EFSCORRUPTED;
2136                         goto out;
2137                 }
2138                 ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
2139                 dx_fallback++;
2140                 ext4_mark_inode_dirty(handle, dir);
2141         }
2142         blocks = dir->i_size >> sb->s_blocksize_bits;
2143         for (block = 0; block < blocks; block++) {
2144                 bh = ext4_read_dirblock(dir, block, DIRENT);
2145                 if (bh == NULL) {
2146                         bh = ext4_bread(handle, dir, block,
2147                                         EXT4_GET_BLOCKS_CREATE);
2148                         goto add_to_new_block;
2149                 }
2150                 if (IS_ERR(bh)) {
2151                         retval = PTR_ERR(bh);
2152                         bh = NULL;
2153                         goto out;
2154                 }
2155                 retval = add_dirent_to_buf(handle, &fname, dir, inode,
2156                                            NULL, bh);
2157                 if (retval != -ENOSPC)
2158                         goto out;
2159
2160                 if (blocks == 1 && !dx_fallback &&
2161                     ext4_has_feature_dir_index(sb)) {
2162                         retval = make_indexed_dir(handle, &fname, dir,
2163                                                   inode, bh);
2164                         bh = NULL; /* make_indexed_dir releases bh */
2165                         goto out;
2166                 }
2167                 brelse(bh);
2168         }
2169         bh = ext4_append(handle, dir, &block);
2170 add_to_new_block:
2171         if (IS_ERR(bh)) {
2172                 retval = PTR_ERR(bh);
2173                 bh = NULL;
2174                 goto out;
2175         }
2176         de = (struct ext4_dir_entry_2 *) bh->b_data;
2177         de->inode = 0;
2178         de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
2179
2180         if (csum_size) {
2181                 t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
2182                 initialize_dirent_tail(t, blocksize);
2183         }
2184
2185         retval = add_dirent_to_buf(handle, &fname, dir, inode, de, bh);
2186 out:
2187         ext4_fname_free_filename(&fname);
2188         brelse(bh);
2189         if (retval == 0)
2190                 ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
2191         return retval;
2192 }
2193
2194 /*
2195  * Returns 0 for success, or a negative error value
2196  */
2197 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
2198                              struct inode *dir, struct inode *inode)
2199 {
2200         struct dx_frame frames[2], *frame;
2201         struct dx_entry *entries, *at;
2202         struct buffer_head *bh;
2203         struct super_block *sb = dir->i_sb;
2204         struct ext4_dir_entry_2 *de;
2205         int err;
2206
2207         frame = dx_probe(fname, dir, NULL, frames);
2208         if (IS_ERR(frame))
2209                 return PTR_ERR(frame);
2210         entries = frame->entries;
2211         at = frame->at;
2212         bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT_HTREE);
2213         if (IS_ERR(bh)) {
2214                 err = PTR_ERR(bh);
2215                 bh = NULL;
2216                 goto cleanup;
2217         }
2218
2219         BUFFER_TRACE(bh, "get_write_access");
2220         err = ext4_journal_get_write_access(handle, bh);
2221         if (err)
2222                 goto journal_error;
2223
2224         err = add_dirent_to_buf(handle, fname, dir, inode, NULL, bh);
2225         if (err != -ENOSPC)
2226                 goto cleanup;
2227
2228         /* Block full, should compress but for now just split */
2229         dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
2230                        dx_get_count(entries), dx_get_limit(entries)));
2231         /* Need to split index? */
2232         if (dx_get_count(entries) == dx_get_limit(entries)) {
2233                 ext4_lblk_t newblock;
2234                 unsigned icount = dx_get_count(entries);
2235                 int levels = frame - frames;
2236                 struct dx_entry *entries2;
2237                 struct dx_node *node2;
2238                 struct buffer_head *bh2;
2239
2240                 if (levels && (dx_get_count(frames->entries) ==
2241                                dx_get_limit(frames->entries))) {
2242                         ext4_warning_inode(dir, "Directory index full!");
2243                         err = -ENOSPC;
2244                         goto cleanup;
2245                 }
2246                 bh2 = ext4_append(handle, dir, &newblock);
2247                 if (IS_ERR(bh2)) {
2248                         err = PTR_ERR(bh2);
2249                         goto cleanup;
2250                 }
2251                 node2 = (struct dx_node *)(bh2->b_data);
2252                 entries2 = node2->entries;
2253                 memset(&node2->fake, 0, sizeof(struct fake_dirent));
2254                 node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
2255                                                            sb->s_blocksize);
2256                 BUFFER_TRACE(frame->bh, "get_write_access");
2257                 err = ext4_journal_get_write_access(handle, frame->bh);
2258                 if (err)
2259                         goto journal_error;
2260                 if (levels) {
2261                         unsigned icount1 = icount/2, icount2 = icount - icount1;
2262                         unsigned hash2 = dx_get_hash(entries + icount1);
2263                         dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
2264                                        icount1, icount2));
2265
2266                         BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
2267                         err = ext4_journal_get_write_access(handle,
2268                                                              frames[0].bh);
2269                         if (err)
2270                                 goto journal_error;
2271
2272                         memcpy((char *) entries2, (char *) (entries + icount1),
2273                                icount2 * sizeof(struct dx_entry));
2274                         dx_set_count(entries, icount1);
2275                         dx_set_count(entries2, icount2);
2276                         dx_set_limit(entries2, dx_node_limit(dir));
2277
2278                         /* Which index block gets the new entry? */
2279                         if (at - entries >= icount1) {
2280                                 frame->at = at = at - entries - icount1 + entries2;
2281                                 frame->entries = entries = entries2;
2282                                 swap(frame->bh, bh2);
2283                         }
2284                         dx_insert_block(frames + 0, hash2, newblock);
2285                         dxtrace(dx_show_index("node", frames[1].entries));
2286                         dxtrace(dx_show_index("node",
2287                                ((struct dx_node *) bh2->b_data)->entries));
2288                         err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2289                         if (err)
2290                                 goto journal_error;
2291                         brelse (bh2);
2292                 } else {
2293                         dxtrace(printk(KERN_DEBUG
2294                                        "Creating second level index...\n"));
2295                         memcpy((char *) entries2, (char *) entries,
2296                                icount * sizeof(struct dx_entry));
2297                         dx_set_limit(entries2, dx_node_limit(dir));
2298
2299                         /* Set up root */
2300                         dx_set_count(entries, 1);
2301                         dx_set_block(entries + 0, newblock);
2302                         ((struct dx_root *) frames[0].bh->b_data)->info.indirect_levels = 1;
2303
2304                         /* Add new access path frame */
2305                         frame = frames + 1;
2306                         frame->at = at = at - entries + entries2;
2307                         frame->entries = entries = entries2;
2308                         frame->bh = bh2;
2309                         err = ext4_journal_get_write_access(handle,
2310                                                              frame->bh);
2311                         if (err)
2312                                 goto journal_error;
2313                 }
2314                 err = ext4_handle_dirty_dx_node(handle, dir, frames[0].bh);
2315                 if (err) {
2316                         ext4_std_error(inode->i_sb, err);
2317                         goto cleanup;
2318                 }
2319         }
2320         de = do_split(handle, dir, &bh, frame, &fname->hinfo);
2321         if (IS_ERR(de)) {
2322                 err = PTR_ERR(de);
2323                 goto cleanup;
2324         }
2325         err = add_dirent_to_buf(handle, fname, dir, inode, de, bh);
2326         goto cleanup;
2327
2328 journal_error:
2329         ext4_std_error(dir->i_sb, err);
2330 cleanup:
2331         brelse(bh);
2332         dx_release(frames);
2333         return err;
2334 }
2335
2336 /*
2337  * ext4_generic_delete_entry deletes a directory entry by merging it
2338  * with the previous entry
2339  */
2340 int ext4_generic_delete_entry(handle_t *handle,
2341                               struct inode *dir,
2342                               struct ext4_dir_entry_2 *de_del,
2343                               struct buffer_head *bh,
2344                               void *entry_buf,
2345                               int buf_size,
2346                               int csum_size)
2347 {
2348         struct ext4_dir_entry_2 *de, *pde;
2349         unsigned int blocksize = dir->i_sb->s_blocksize;
2350         int i;
2351
2352         i = 0;
2353         pde = NULL;
2354         de = (struct ext4_dir_entry_2 *)entry_buf;
2355         while (i < buf_size - csum_size) {
2356                 if (ext4_check_dir_entry(dir, NULL, de, bh,
2357                                          entry_buf, buf_size, i))
2358                         return -EFSCORRUPTED;
2359                 if (de == de_del)  {
2360                         if (pde)
2361                                 pde->rec_len = ext4_rec_len_to_disk(
2362                                         ext4_rec_len_from_disk(pde->rec_len,
2363                                                                blocksize) +
2364                                         ext4_rec_len_from_disk(de->rec_len,
2365                                                                blocksize),
2366                                         blocksize);
2367                         else
2368                                 de->inode = 0;
2369                         dir->i_version++;
2370                         return 0;
2371                 }
2372                 i += ext4_rec_len_from_disk(de->rec_len, blocksize);
2373                 pde = de;
2374                 de = ext4_next_entry(de, blocksize);
2375         }
2376         return -ENOENT;
2377 }
2378
2379 static int ext4_delete_entry(handle_t *handle,
2380                              struct inode *dir,
2381                              struct ext4_dir_entry_2 *de_del,
2382                              struct buffer_head *bh)
2383 {
2384         int err, csum_size = 0;
2385
2386         if (ext4_has_inline_data(dir)) {
2387                 int has_inline_data = 1;
2388                 err = ext4_delete_inline_entry(handle, dir, de_del, bh,
2389                                                &has_inline_data);
2390                 if (has_inline_data)
2391                         return err;
2392         }
2393
2394         if (ext4_has_metadata_csum(dir->i_sb))
2395                 csum_size = sizeof(struct ext4_dir_entry_tail);
2396
2397         BUFFER_TRACE(bh, "get_write_access");
2398         err = ext4_journal_get_write_access(handle, bh);
2399         if (unlikely(err))
2400                 goto out;
2401
2402         err = ext4_generic_delete_entry(handle, dir, de_del,
2403                                         bh, bh->b_data,
2404                                         dir->i_sb->s_blocksize, csum_size);
2405         if (err)
2406                 goto out;
2407
2408         BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
2409         err = ext4_handle_dirty_dirent_node(handle, dir, bh);
2410         if (unlikely(err))
2411                 goto out;
2412
2413         return 0;
2414 out:
2415         if (err != -ENOENT)
2416                 ext4_std_error(dir->i_sb, err);
2417         return err;
2418 }
2419
2420 /*
2421  * DIR_NLINK feature is set if 1) nlinks > EXT4_LINK_MAX or 2) nlinks == 2,
2422  * since this indicates that nlinks count was previously 1.
2423  */
2424 static void ext4_inc_count(handle_t *handle, struct inode *inode)
2425 {
2426         inc_nlink(inode);
2427         if (is_dx(inode) && inode->i_nlink > 1) {
2428                 /* limit is 16-bit i_links_count */
2429                 if (inode->i_nlink >= EXT4_LINK_MAX || inode->i_nlink == 2) {
2430                         set_nlink(inode, 1);
2431                         ext4_set_feature_dir_nlink(inode->i_sb);
2432                 }
2433         }
2434 }
2435
2436 /*
2437  * If a directory had nlink == 1, then we should let it be 1. This indicates
2438  * directory has >EXT4_LINK_MAX subdirs.
2439  */
2440 static void ext4_dec_count(handle_t *handle, struct inode *inode)
2441 {
2442         if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
2443                 drop_nlink(inode);
2444 }
2445
2446
2447 static int ext4_add_nondir(handle_t *handle,
2448                 struct dentry *dentry, struct inode *inode)
2449 {
2450         int err = ext4_add_entry(handle, dentry, inode);
2451         if (!err) {
2452                 ext4_mark_inode_dirty(handle, inode);
2453                 d_instantiate_new(dentry, inode);
2454                 return 0;
2455         }
2456         drop_nlink(inode);
2457         unlock_new_inode(inode);
2458         iput(inode);
2459         return err;
2460 }
2461
2462 /*
2463  * By the time this is called, we already have created
2464  * the directory cache entry for the new file, but it
2465  * is so far negative - it has no inode.
2466  *
2467  * If the create succeeds, we fill in the inode information
2468  * with d_instantiate().
2469  */
2470 static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2471                        bool excl)
2472 {
2473         handle_t *handle;
2474         struct inode *inode;
2475         int err, credits, retries = 0;
2476
2477         err = dquot_initialize(dir);
2478         if (err)
2479                 return err;
2480
2481         credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2482                    EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2483 retry:
2484         inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2485                                             NULL, EXT4_HT_DIR, credits);
2486         handle = ext4_journal_current_handle();
2487         err = PTR_ERR(inode);
2488         if (!IS_ERR(inode)) {
2489                 inode->i_op = &ext4_file_inode_operations;
2490                 inode->i_fop = &ext4_file_operations;
2491                 ext4_set_aops(inode);
2492                 err = ext4_add_nondir(handle, dentry, inode);
2493                 if (!err && IS_DIRSYNC(dir))
2494                         ext4_handle_sync(handle);
2495         }
2496         if (handle)
2497                 ext4_journal_stop(handle);
2498         if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2499                 goto retry;
2500         return err;
2501 }
2502
2503 static int ext4_mknod(struct inode *dir, struct dentry *dentry,
2504                       umode_t mode, dev_t rdev)
2505 {
2506         handle_t *handle;
2507         struct inode *inode;
2508         int err, credits, retries = 0;
2509
2510         err = dquot_initialize(dir);
2511         if (err)
2512                 return err;
2513
2514         credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2515                    EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2516 retry:
2517         inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2518                                             NULL, EXT4_HT_DIR, credits);
2519         handle = ext4_journal_current_handle();
2520         err = PTR_ERR(inode);
2521         if (!IS_ERR(inode)) {
2522                 init_special_inode(inode, inode->i_mode, rdev);
2523                 inode->i_op = &ext4_special_inode_operations;
2524                 err = ext4_add_nondir(handle, dentry, inode);
2525                 if (!err && IS_DIRSYNC(dir))
2526                         ext4_handle_sync(handle);
2527         }
2528         if (handle)
2529                 ext4_journal_stop(handle);
2530         if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2531                 goto retry;
2532         return err;
2533 }
2534
2535 static int ext4_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2536 {
2537         handle_t *handle;
2538         struct inode *inode;
2539         int err, retries = 0;
2540
2541         err = dquot_initialize(dir);
2542         if (err)
2543                 return err;
2544
2545 retry:
2546         inode = ext4_new_inode_start_handle(dir, mode,
2547                                             NULL, 0, NULL,
2548                                             EXT4_HT_DIR,
2549                         EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
2550                           4 + EXT4_XATTR_TRANS_BLOCKS);
2551         handle = ext4_journal_current_handle();
2552         err = PTR_ERR(inode);
2553         if (!IS_ERR(inode)) {
2554                 inode->i_op = &ext4_file_inode_operations;
2555                 inode->i_fop = &ext4_file_operations;
2556                 ext4_set_aops(inode);
2557                 d_tmpfile(dentry, inode);
2558                 err = ext4_orphan_add(handle, inode);
2559                 if (err)
2560                         goto err_unlock_inode;
2561                 mark_inode_dirty(inode);
2562                 unlock_new_inode(inode);
2563         }
2564         if (handle)
2565                 ext4_journal_stop(handle);
2566         if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2567                 goto retry;
2568         return err;
2569 err_unlock_inode:
2570         ext4_journal_stop(handle);
2571         unlock_new_inode(inode);
2572         return err;
2573 }
2574
2575 struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode,
2576                           struct ext4_dir_entry_2 *de,
2577                           int blocksize, int csum_size,
2578                           unsigned int parent_ino, int dotdot_real_len)
2579 {
2580         de->inode = cpu_to_le32(inode->i_ino);
2581         de->name_len = 1;
2582         de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
2583                                            blocksize);
2584         strcpy(de->name, ".");
2585         ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2586
2587         de = ext4_next_entry(de, blocksize);
2588         de->inode = cpu_to_le32(parent_ino);
2589         de->name_len = 2;
2590         if (!dotdot_real_len)
2591                 de->rec_len = ext4_rec_len_to_disk(blocksize -
2592                                         (csum_size + EXT4_DIR_REC_LEN(1)),
2593                                         blocksize);
2594         else
2595                 de->rec_len = ext4_rec_len_to_disk(
2596                                 EXT4_DIR_REC_LEN(de->name_len), blocksize);
2597         strcpy(de->name, "..");
2598         ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2599
2600         return ext4_next_entry(de, blocksize);
2601 }
2602
2603 static int ext4_init_new_dir(handle_t *handle, struct inode *dir,
2604                              struct inode *inode)
2605 {
2606         struct buffer_head *dir_block = NULL;
2607         struct ext4_dir_entry_2 *de;
2608         struct ext4_dir_entry_tail *t;
2609         ext4_lblk_t block = 0;
2610         unsigned int blocksize = dir->i_sb->s_blocksize;
2611         int csum_size = 0;
2612         int err;
2613
2614         if (ext4_has_metadata_csum(dir->i_sb))
2615                 csum_size = sizeof(struct ext4_dir_entry_tail);
2616
2617         if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2618                 err = ext4_try_create_inline_dir(handle, dir, inode);
2619                 if (err < 0 && err != -ENOSPC)
2620                         goto out;
2621                 if (!err)
2622                         goto out;
2623         }
2624
2625         inode->i_size = 0;
2626         dir_block = ext4_append(handle, inode, &block);
2627         if (IS_ERR(dir_block))
2628                 return PTR_ERR(dir_block);
2629         de = (struct ext4_dir_entry_2 *)dir_block->b_data;
2630         ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0);
2631         set_nlink(inode, 2);
2632         if (csum_size) {
2633                 t = EXT4_DIRENT_TAIL(dir_block->b_data, blocksize);
2634                 initialize_dirent_tail(t, blocksize);
2635         }
2636
2637         BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
2638         err = ext4_handle_dirty_dirent_node(handle, inode, dir_block);
2639         if (err)
2640                 goto out;
2641         set_buffer_verified(dir_block);
2642 out:
2643         brelse(dir_block);
2644         return err;
2645 }
2646
2647 static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2648 {
2649         handle_t *handle;
2650         struct inode *inode;
2651         int err, credits, retries = 0;
2652
2653         if (EXT4_DIR_LINK_MAX(dir))
2654                 return -EMLINK;
2655
2656         err = dquot_initialize(dir);
2657         if (err)
2658                 return err;
2659
2660         credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2661                    EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2662 retry:
2663         inode = ext4_new_inode_start_handle(dir, S_IFDIR | mode,
2664                                             &dentry->d_name,
2665                                             0, NULL, EXT4_HT_DIR, credits);
2666         handle = ext4_journal_current_handle();
2667         err = PTR_ERR(inode);
2668         if (IS_ERR(inode))
2669                 goto out_stop;
2670
2671         inode->i_op = &ext4_dir_inode_operations;
2672         inode->i_fop = &ext4_dir_operations;
2673         err = ext4_init_new_dir(handle, dir, inode);
2674         if (err)
2675                 goto out_clear_inode;
2676         err = ext4_mark_inode_dirty(handle, inode);
2677         if (!err)
2678                 err = ext4_add_entry(handle, dentry, inode);
2679         if (err) {
2680 out_clear_inode:
2681                 clear_nlink(inode);
2682                 unlock_new_inode(inode);
2683                 ext4_mark_inode_dirty(handle, inode);
2684                 iput(inode);
2685                 goto out_stop;
2686         }
2687         ext4_inc_count(handle, dir);
2688         ext4_update_dx_flag(dir);
2689         err = ext4_mark_inode_dirty(handle, dir);
2690         if (err)
2691                 goto out_clear_inode;
2692         d_instantiate_new(dentry, inode);
2693         if (IS_DIRSYNC(dir))
2694                 ext4_handle_sync(handle);
2695
2696 out_stop:
2697         if (handle)
2698                 ext4_journal_stop(handle);
2699         if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2700                 goto retry;
2701         return err;
2702 }
2703
2704 /*
2705  * routine to check that the specified directory is empty (for rmdir)
2706  */
2707 bool ext4_empty_dir(struct inode *inode)
2708 {
2709         unsigned int offset;
2710         struct buffer_head *bh;
2711         struct ext4_dir_entry_2 *de;
2712         struct super_block *sb;
2713
2714         if (ext4_has_inline_data(inode)) {
2715                 int has_inline_data = 1;
2716                 int ret;
2717
2718                 ret = empty_inline_dir(inode, &has_inline_data);
2719                 if (has_inline_data)
2720                         return ret;
2721         }
2722
2723         sb = inode->i_sb;
2724         if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2)) {
2725                 EXT4_ERROR_INODE(inode, "invalid size");
2726                 return true;
2727         }
2728         /* The first directory block must not be a hole,
2729          * so treat it as DIRENT_HTREE
2730          */
2731         bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
2732         if (IS_ERR(bh))
2733                 return true;
2734
2735         de = (struct ext4_dir_entry_2 *) bh->b_data;
2736         if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2737                                  0) ||
2738             le32_to_cpu(de->inode) != inode->i_ino || strcmp(".", de->name)) {
2739                 ext4_warning_inode(inode, "directory missing '.'");
2740                 brelse(bh);
2741                 return true;
2742         }
2743         offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2744         de = ext4_next_entry(de, sb->s_blocksize);
2745         if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2746                                  offset) ||
2747             le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
2748                 ext4_warning_inode(inode, "directory missing '..'");
2749                 brelse(bh);
2750                 return true;
2751         }
2752         offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2753         while (offset < inode->i_size) {
2754                 if (!(offset & (sb->s_blocksize - 1))) {
2755                         unsigned int lblock;
2756                         brelse(bh);
2757                         lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
2758                         bh = ext4_read_dirblock(inode, lblock, EITHER);
2759                         if (bh == NULL) {
2760                                 offset += sb->s_blocksize;
2761                                 continue;
2762                         }
2763                         if (IS_ERR(bh))
2764                                 return true;
2765                 }
2766                 de = (struct ext4_dir_entry_2 *) (bh->b_data +
2767                                         (offset & (sb->s_blocksize - 1)));
2768                 if (ext4_check_dir_entry(inode, NULL, de, bh,
2769                                          bh->b_data, bh->b_size, offset)) {
2770                         offset = (offset | (sb->s_blocksize - 1)) + 1;
2771                         continue;
2772                 }
2773                 if (le32_to_cpu(de->inode)) {
2774                         brelse(bh);
2775                         return false;
2776                 }
2777                 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2778         }
2779         brelse(bh);
2780         return true;
2781 }
2782
2783 /*
2784  * ext4_orphan_add() links an unlinked or truncated inode into a list of
2785  * such inodes, starting at the superblock, in case we crash before the
2786  * file is closed/deleted, or in case the inode truncate spans multiple
2787  * transactions and the last transaction is not recovered after a crash.
2788  *
2789  * At filesystem recovery time, we walk this list deleting unlinked
2790  * inodes and truncating linked inodes in ext4_orphan_cleanup().
2791  *
2792  * Orphan list manipulation functions must be called under i_mutex unless
2793  * we are just creating the inode or deleting it.
2794  */
2795 int ext4_orphan_add(handle_t *handle, struct inode *inode)
2796 {
2797         struct super_block *sb = inode->i_sb;
2798         struct ext4_sb_info *sbi = EXT4_SB(sb);
2799         struct ext4_iloc iloc;
2800         int err = 0, rc;
2801         bool dirty = false;
2802
2803         if (!sbi->s_journal || is_bad_inode(inode))
2804                 return 0;
2805
2806         WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2807                      !inode_is_locked(inode));
2808         /*
2809          * Exit early if inode already is on orphan list. This is a big speedup
2810          * since we don't have to contend on the global s_orphan_lock.
2811          */
2812         if (!list_empty(&EXT4_I(inode)->i_orphan))
2813                 return 0;
2814
2815         /*
2816          * Orphan handling is only valid for files with data blocks
2817          * being truncated, or files being unlinked. Note that we either
2818          * hold i_mutex, or the inode can not be referenced from outside,
2819          * so i_nlink should not be bumped due to race
2820          */
2821         J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
2822                   S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
2823
2824         BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2825         err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2826         if (err)
2827                 goto out;
2828
2829         err = ext4_reserve_inode_write(handle, inode, &iloc);
2830         if (err)
2831                 goto out;
2832
2833         mutex_lock(&sbi->s_orphan_lock);
2834         /*
2835          * Due to previous errors inode may be already a part of on-disk
2836          * orphan list. If so skip on-disk list modification.
2837          */
2838         if (!NEXT_ORPHAN(inode) || NEXT_ORPHAN(inode) >
2839             (le32_to_cpu(sbi->s_es->s_inodes_count))) {
2840                 /* Insert this inode at the head of the on-disk orphan list */
2841                 NEXT_ORPHAN(inode) = le32_to_cpu(sbi->s_es->s_last_orphan);
2842                 sbi->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
2843                 dirty = true;
2844         }
2845         list_add(&EXT4_I(inode)->i_orphan, &sbi->s_orphan);
2846         mutex_unlock(&sbi->s_orphan_lock);
2847
2848         if (dirty) {
2849                 err = ext4_handle_dirty_super(handle, sb);
2850                 rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
2851                 if (!err)
2852                         err = rc;
2853                 if (err) {
2854                         /*
2855                          * We have to remove inode from in-memory list if
2856                          * addition to on disk orphan list failed. Stray orphan
2857                          * list entries can cause panics at unmount time.
2858                          */
2859                         mutex_lock(&sbi->s_orphan_lock);
2860                         list_del_init(&EXT4_I(inode)->i_orphan);
2861                         mutex_unlock(&sbi->s_orphan_lock);
2862                 }
2863         } else
2864                 brelse(iloc.bh);
2865
2866         jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
2867         jbd_debug(4, "orphan inode %lu will point to %d\n",
2868                         inode->i_ino, NEXT_ORPHAN(inode));
2869 out:
2870         ext4_std_error(sb, err);
2871         return err;
2872 }
2873
2874 /*
2875  * ext4_orphan_del() removes an unlinked or truncated inode from the list
2876  * of such inodes stored on disk, because it is finally being cleaned up.
2877  */
2878 int ext4_orphan_del(handle_t *handle, struct inode *inode)
2879 {
2880         struct list_head *prev;
2881         struct ext4_inode_info *ei = EXT4_I(inode);
2882         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2883         __u32 ino_next;
2884         struct ext4_iloc iloc;
2885         int err = 0;
2886
2887         if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS))
2888                 return 0;
2889
2890         WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2891                      !inode_is_locked(inode));
2892         /* Do this quick check before taking global s_orphan_lock. */
2893         if (list_empty(&ei->i_orphan))
2894                 return 0;
2895
2896         if (handle) {
2897                 /* Grab inode buffer early before taking global s_orphan_lock */
2898                 err = ext4_reserve_inode_write(handle, inode, &iloc);
2899         }
2900
2901         mutex_lock(&sbi->s_orphan_lock);
2902         jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
2903
2904         prev = ei->i_orphan.prev;
2905         list_del_init(&ei->i_orphan);
2906
2907         /* If we're on an error path, we may not have a valid
2908          * transaction handle with which to update the orphan list on
2909          * disk, but we still need to remove the inode from the linked
2910          * list in memory. */
2911         if (!handle || err) {
2912                 mutex_unlock(&sbi->s_orphan_lock);
2913                 goto out_err;
2914         }
2915
2916         ino_next = NEXT_ORPHAN(inode);
2917         if (prev == &sbi->s_orphan) {
2918                 jbd_debug(4, "superblock will point to %u\n", ino_next);
2919                 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2920                 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2921                 if (err) {
2922                         mutex_unlock(&sbi->s_orphan_lock);
2923                         goto out_brelse;
2924                 }
2925                 sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
2926                 mutex_unlock(&sbi->s_orphan_lock);
2927                 err = ext4_handle_dirty_super(handle, inode->i_sb);
2928         } else {
2929                 struct ext4_iloc iloc2;
2930                 struct inode *i_prev =
2931                         &list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
2932
2933                 jbd_debug(4, "orphan inode %lu will point to %u\n",
2934                           i_prev->i_ino, ino_next);
2935                 err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
2936                 if (err) {
2937                         mutex_unlock(&sbi->s_orphan_lock);
2938                         goto out_brelse;
2939                 }
2940                 NEXT_ORPHAN(i_prev) = ino_next;
2941                 err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
2942                 mutex_unlock(&sbi->s_orphan_lock);
2943         }
2944         if (err)
2945                 goto out_brelse;
2946         NEXT_ORPHAN(inode) = 0;
2947         err = ext4_mark_iloc_dirty(handle, inode, &iloc);
2948 out_err:
2949         ext4_std_error(inode->i_sb, err);
2950         return err;
2951
2952 out_brelse:
2953         brelse(iloc.bh);
2954         goto out_err;
2955 }
2956
2957 static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
2958 {
2959         int retval;
2960         struct inode *inode;
2961         struct buffer_head *bh;
2962         struct ext4_dir_entry_2 *de;
2963         handle_t *handle = NULL;
2964
2965         /* Initialize quotas before so that eventual writes go in
2966          * separate transaction */
2967         retval = dquot_initialize(dir);
2968         if (retval)
2969                 return retval;
2970         retval = dquot_initialize(d_inode(dentry));
2971         if (retval)
2972                 return retval;
2973
2974         retval = -ENOENT;
2975         bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
2976         if (IS_ERR(bh))
2977                 return PTR_ERR(bh);
2978         if (!bh)
2979                 goto end_rmdir;
2980
2981         inode = d_inode(dentry);
2982
2983         retval = -EFSCORRUPTED;
2984         if (le32_to_cpu(de->inode) != inode->i_ino)
2985                 goto end_rmdir;
2986
2987         retval = -ENOTEMPTY;
2988         if (!ext4_empty_dir(inode))
2989                 goto end_rmdir;
2990
2991         handle = ext4_journal_start(dir, EXT4_HT_DIR,
2992                                     EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
2993         if (IS_ERR(handle)) {
2994                 retval = PTR_ERR(handle);
2995                 handle = NULL;
2996                 goto end_rmdir;
2997         }
2998
2999         if (IS_DIRSYNC(dir))
3000                 ext4_handle_sync(handle);
3001
3002         retval = ext4_delete_entry(handle, dir, de, bh);
3003         if (retval)
3004                 goto end_rmdir;
3005         if (!EXT4_DIR_LINK_EMPTY(inode))
3006                 ext4_warning_inode(inode,
3007                              "empty directory '%.*s' has too many links (%u)",
3008                              dentry->d_name.len, dentry->d_name.name,
3009                              inode->i_nlink);
3010         inode->i_version++;
3011         clear_nlink(inode);
3012         /* There's no need to set i_disksize: the fact that i_nlink is
3013          * zero will ensure that the right thing happens during any
3014          * recovery. */
3015         inode->i_size = 0;
3016         ext4_orphan_add(handle, inode);
3017         inode->i_ctime = dir->i_ctime = dir->i_mtime = ext4_current_time(inode);
3018         ext4_mark_inode_dirty(handle, inode);
3019         ext4_dec_count(handle, dir);
3020         ext4_update_dx_flag(dir);
3021         ext4_mark_inode_dirty(handle, dir);
3022
3023 end_rmdir:
3024         brelse(bh);
3025         if (handle)
3026                 ext4_journal_stop(handle);
3027         return retval;
3028 }
3029
3030 static int ext4_unlink(struct inode *dir, struct dentry *dentry)
3031 {
3032         int retval;
3033         struct inode *inode;
3034         struct buffer_head *bh;
3035         struct ext4_dir_entry_2 *de;
3036         handle_t *handle = NULL;
3037
3038         trace_ext4_unlink_enter(dir, dentry);
3039         /* Initialize quotas before so that eventual writes go
3040          * in separate transaction */
3041         retval = dquot_initialize(dir);
3042         if (retval)
3043                 return retval;
3044         retval = dquot_initialize(d_inode(dentry));
3045         if (retval)
3046                 return retval;
3047
3048         retval = -ENOENT;
3049         bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3050         if (IS_ERR(bh))
3051                 return PTR_ERR(bh);
3052         if (!bh)
3053                 goto end_unlink;
3054
3055         inode = d_inode(dentry);
3056
3057         retval = -EFSCORRUPTED;
3058         if (le32_to_cpu(de->inode) != inode->i_ino)
3059                 goto end_unlink;
3060
3061         handle = ext4_journal_start(dir, EXT4_HT_DIR,
3062                                     EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3063         if (IS_ERR(handle)) {
3064                 retval = PTR_ERR(handle);
3065                 handle = NULL;
3066                 goto end_unlink;
3067         }
3068
3069         if (IS_DIRSYNC(dir))
3070                 ext4_handle_sync(handle);
3071
3072         retval = ext4_delete_entry(handle, dir, de, bh);
3073         if (retval)
3074                 goto end_unlink;
3075         dir->i_ctime = dir->i_mtime = ext4_current_time(dir);
3076         ext4_update_dx_flag(dir);
3077         ext4_mark_inode_dirty(handle, dir);
3078         if (inode->i_nlink == 0)
3079                 ext4_warning_inode(inode, "Deleting file '%.*s' with no links",
3080                                    dentry->d_name.len, dentry->d_name.name);
3081         else
3082                 drop_nlink(inode);
3083         if (!inode->i_nlink)
3084                 ext4_orphan_add(handle, inode);
3085         inode->i_ctime = ext4_current_time(inode);
3086         ext4_mark_inode_dirty(handle, inode);
3087
3088 end_unlink:
3089         brelse(bh);
3090         if (handle)
3091                 ext4_journal_stop(handle);
3092         trace_ext4_unlink_exit(dentry, retval);
3093         return retval;
3094 }
3095
3096 static int ext4_symlink(struct inode *dir,
3097                         struct dentry *dentry, const char *symname)
3098 {
3099         handle_t *handle;
3100         struct inode *inode;
3101         int err, len = strlen(symname);
3102         int credits;
3103         bool encryption_required;
3104         struct fscrypt_str disk_link;
3105         struct fscrypt_symlink_data *sd = NULL;
3106
3107         disk_link.len = len + 1;
3108         disk_link.name = (char *) symname;
3109
3110         encryption_required = (ext4_encrypted_inode(dir) ||
3111                                DUMMY_ENCRYPTION_ENABLED(EXT4_SB(dir->i_sb)));
3112         if (encryption_required) {
3113                 err = fscrypt_get_encryption_info(dir);
3114                 if (err)
3115                         return err;
3116                 if (!fscrypt_has_encryption_key(dir))
3117                         return -ENOKEY;
3118                 disk_link.len = (fscrypt_fname_encrypted_size(dir, len) +
3119                                  sizeof(struct fscrypt_symlink_data));
3120                 sd = kzalloc(disk_link.len, GFP_KERNEL);
3121                 if (!sd)
3122                         return -ENOMEM;
3123         }
3124
3125         if (disk_link.len > dir->i_sb->s_blocksize) {
3126                 err = -ENAMETOOLONG;
3127                 goto err_free_sd;
3128         }
3129
3130         err = dquot_initialize(dir);
3131         if (err)
3132                 goto err_free_sd;
3133
3134         if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3135                 /*
3136                  * For non-fast symlinks, we just allocate inode and put it on
3137                  * orphan list in the first transaction => we need bitmap,
3138                  * group descriptor, sb, inode block, quota blocks, and
3139                  * possibly selinux xattr blocks.
3140                  */
3141                 credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
3142                           EXT4_XATTR_TRANS_BLOCKS;
3143         } else {
3144                 /*
3145                  * Fast symlink. We have to add entry to directory
3146                  * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
3147                  * allocate new inode (bitmap, group descriptor, inode block,
3148                  * quota blocks, sb is already counted in previous macros).
3149                  */
3150                 credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3151                           EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3;
3152         }
3153
3154         inode = ext4_new_inode_start_handle(dir, S_IFLNK|S_IRWXUGO,
3155                                             &dentry->d_name, 0, NULL,
3156                                             EXT4_HT_DIR, credits);
3157         handle = ext4_journal_current_handle();
3158         if (IS_ERR(inode)) {
3159                 if (handle)
3160                         ext4_journal_stop(handle);
3161                 err = PTR_ERR(inode);
3162                 goto err_free_sd;
3163         }
3164
3165         if (encryption_required) {
3166                 struct qstr istr;
3167                 struct fscrypt_str ostr =
3168                         FSTR_INIT(sd->encrypted_path, disk_link.len);
3169
3170                 istr.name = (const unsigned char *) symname;
3171                 istr.len = len;
3172                 err = fscrypt_fname_usr_to_disk(inode, &istr, &ostr);
3173                 if (err)
3174                         goto err_drop_inode;
3175                 sd->len = cpu_to_le16(ostr.len);
3176                 disk_link.name = (char *) sd;
3177                 inode->i_op = &ext4_encrypted_symlink_inode_operations;
3178         }
3179
3180         if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3181                 if (!encryption_required)
3182                         inode->i_op = &ext4_symlink_inode_operations;
3183                 inode_nohighmem(inode);
3184                 ext4_set_aops(inode);
3185                 /*
3186                  * We cannot call page_symlink() with transaction started
3187                  * because it calls into ext4_write_begin() which can wait
3188                  * for transaction commit if we are running out of space
3189                  * and thus we deadlock. So we have to stop transaction now
3190                  * and restart it when symlink contents is written.
3191                  * 
3192                  * To keep fs consistent in case of crash, we have to put inode
3193                  * to orphan list in the mean time.
3194                  */
3195                 drop_nlink(inode);
3196                 err = ext4_orphan_add(handle, inode);
3197                 ext4_journal_stop(handle);
3198                 handle = NULL;
3199                 if (err)
3200                         goto err_drop_inode;
3201                 err = __page_symlink(inode, disk_link.name, disk_link.len, 1);
3202                 if (err)
3203                         goto err_drop_inode;
3204                 /*
3205                  * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
3206                  * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
3207                  */
3208                 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3209                                 EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3210                                 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
3211                 if (IS_ERR(handle)) {
3212                         err = PTR_ERR(handle);
3213                         handle = NULL;
3214                         goto err_drop_inode;
3215                 }
3216                 set_nlink(inode, 1);
3217                 err = ext4_orphan_del(handle, inode);
3218                 if (err)
3219                         goto err_drop_inode;
3220         } else {
3221                 /* clear the extent format for fast symlink */
3222                 ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
3223                 if (!encryption_required) {
3224                         inode->i_op = &ext4_fast_symlink_inode_operations;
3225                         inode->i_link = (char *)&EXT4_I(inode)->i_data;
3226                 }
3227                 memcpy((char *)&EXT4_I(inode)->i_data, disk_link.name,
3228                        disk_link.len);
3229                 inode->i_size = disk_link.len - 1;
3230         }
3231         EXT4_I(inode)->i_disksize = inode->i_size;
3232         err = ext4_add_nondir(handle, dentry, inode);
3233         if (!err && IS_DIRSYNC(dir))
3234                 ext4_handle_sync(handle);
3235
3236         if (handle)
3237                 ext4_journal_stop(handle);
3238         kfree(sd);
3239         return err;
3240 err_drop_inode:
3241         if (handle)
3242                 ext4_journal_stop(handle);
3243         clear_nlink(inode);
3244         unlock_new_inode(inode);
3245         iput(inode);
3246 err_free_sd:
3247         kfree(sd);
3248         return err;
3249 }
3250
3251 static int ext4_link(struct dentry *old_dentry,
3252                      struct inode *dir, struct dentry *dentry)
3253 {
3254         handle_t *handle;
3255         struct inode *inode = d_inode(old_dentry);
3256         int err, retries = 0;
3257
3258         if (inode->i_nlink >= EXT4_LINK_MAX)
3259                 return -EMLINK;
3260         if (ext4_encrypted_inode(dir) &&
3261                         !fscrypt_has_permitted_context(dir, inode))
3262                 return -EXDEV;
3263
3264        if ((ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT)) &&
3265            (!projid_eq(EXT4_I(dir)->i_projid,
3266                        EXT4_I(old_dentry->d_inode)->i_projid)))
3267                 return -EXDEV;
3268
3269         err = dquot_initialize(dir);
3270         if (err)
3271                 return err;
3272
3273 retry:
3274         handle = ext4_journal_start(dir, EXT4_HT_DIR,
3275                 (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3276                  EXT4_INDEX_EXTRA_TRANS_BLOCKS) + 1);
3277         if (IS_ERR(handle))
3278                 return PTR_ERR(handle);
3279
3280         if (IS_DIRSYNC(dir))
3281                 ext4_handle_sync(handle);
3282
3283         inode->i_ctime = ext4_current_time(inode);
3284         ext4_inc_count(handle, inode);
3285         ihold(inode);
3286
3287         err = ext4_add_entry(handle, dentry, inode);
3288         if (!err) {
3289                 ext4_mark_inode_dirty(handle, inode);
3290                 /* this can happen only for tmpfile being
3291                  * linked the first time
3292                  */
3293                 if (inode->i_nlink == 1)
3294                         ext4_orphan_del(handle, inode);
3295                 d_instantiate(dentry, inode);
3296         } else {
3297                 drop_nlink(inode);
3298                 iput(inode);
3299         }
3300         ext4_journal_stop(handle);
3301         if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
3302                 goto retry;
3303         return err;
3304 }
3305
3306
3307 /*
3308  * Try to find buffer head where contains the parent block.
3309  * It should be the inode block if it is inlined or the 1st block
3310  * if it is a normal dir.
3311  */
3312 static struct buffer_head *ext4_get_first_dir_block(handle_t *handle,
3313                                         struct inode *inode,
3314                                         int *retval,
3315                                         struct ext4_dir_entry_2 **parent_de,
3316                                         int *inlined)
3317 {
3318         struct buffer_head *bh;
3319
3320         if (!ext4_has_inline_data(inode)) {
3321                 /* The first directory block must not be a hole, so
3322                  * treat it as DIRENT_HTREE
3323                  */
3324                 bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
3325                 if (IS_ERR(bh)) {
3326                         *retval = PTR_ERR(bh);
3327                         return NULL;
3328                 }
3329                 *parent_de = ext4_next_entry(
3330                                         (struct ext4_dir_entry_2 *)bh->b_data,
3331                                         inode->i_sb->s_blocksize);
3332                 return bh;
3333         }
3334
3335         *inlined = 1;
3336         return ext4_get_first_inline_block(inode, parent_de, retval);
3337 }
3338
3339 struct ext4_renament {
3340         struct inode *dir;
3341         struct dentry *dentry;
3342         struct inode *inode;
3343         bool is_dir;
3344         int dir_nlink_delta;
3345
3346         /* entry for "dentry" */
3347         struct buffer_head *bh;
3348         struct ext4_dir_entry_2 *de;
3349         int inlined;
3350
3351         /* entry for ".." in inode if it's a directory */
3352         struct buffer_head *dir_bh;
3353         struct ext4_dir_entry_2 *parent_de;
3354         int dir_inlined;
3355 };
3356
3357 static int ext4_rename_dir_prepare(handle_t *handle, struct ext4_renament *ent)
3358 {
3359         int retval;
3360
3361         ent->dir_bh = ext4_get_first_dir_block(handle, ent->inode,
3362                                               &retval, &ent->parent_de,
3363                                               &ent->dir_inlined);
3364         if (!ent->dir_bh)
3365                 return retval;
3366         if (le32_to_cpu(ent->parent_de->inode) != ent->dir->i_ino)
3367                 return -EFSCORRUPTED;
3368         BUFFER_TRACE(ent->dir_bh, "get_write_access");
3369         return ext4_journal_get_write_access(handle, ent->dir_bh);
3370 }
3371
3372 static int ext4_rename_dir_finish(handle_t *handle, struct ext4_renament *ent,
3373                                   unsigned dir_ino)
3374 {
3375         int retval;
3376
3377         ent->parent_de->inode = cpu_to_le32(dir_ino);
3378         BUFFER_TRACE(ent->dir_bh, "call ext4_handle_dirty_metadata");
3379         if (!ent->dir_inlined) {
3380                 if (is_dx(ent->inode)) {
3381                         retval = ext4_handle_dirty_dx_node(handle,
3382                                                            ent->inode,
3383                                                            ent->dir_bh);
3384                 } else {
3385                         retval = ext4_handle_dirty_dirent_node(handle,
3386                                                                ent->inode,
3387                                                                ent->dir_bh);
3388                 }
3389         } else {
3390                 retval = ext4_mark_inode_dirty(handle, ent->inode);
3391         }
3392         if (retval) {
3393                 ext4_std_error(ent->dir->i_sb, retval);
3394                 return retval;
3395         }
3396         return 0;
3397 }
3398
3399 static int ext4_setent(handle_t *handle, struct ext4_renament *ent,
3400                        unsigned ino, unsigned file_type)
3401 {
3402         int retval;
3403
3404         BUFFER_TRACE(ent->bh, "get write access");
3405         retval = ext4_journal_get_write_access(handle, ent->bh);
3406         if (retval)
3407                 return retval;
3408         ent->de->inode = cpu_to_le32(ino);
3409         if (ext4_has_feature_filetype(ent->dir->i_sb))
3410                 ent->de->file_type = file_type;
3411         ent->dir->i_version++;
3412         ent->dir->i_ctime = ent->dir->i_mtime =
3413                 ext4_current_time(ent->dir);
3414         ext4_mark_inode_dirty(handle, ent->dir);
3415         BUFFER_TRACE(ent->bh, "call ext4_handle_dirty_metadata");
3416         if (!ent->inlined) {
3417                 retval = ext4_handle_dirty_dirent_node(handle,
3418                                                        ent->dir, ent->bh);
3419                 if (unlikely(retval)) {
3420                         ext4_std_error(ent->dir->i_sb, retval);
3421                         return retval;
3422                 }
3423         }
3424
3425         return 0;
3426 }
3427
3428 static void ext4_resetent(handle_t *handle, struct ext4_renament *ent,
3429                           unsigned ino, unsigned file_type)
3430 {
3431         struct ext4_renament old = *ent;
3432         int retval = 0;
3433
3434         /*
3435          * old->de could have moved from under us during make indexed dir,
3436          * so the old->de may no longer valid and need to find it again
3437          * before reset old inode info.
3438          */
3439         old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de, NULL);
3440         if (IS_ERR(old.bh))
3441                 retval = PTR_ERR(old.bh);
3442         if (!old.bh)
3443                 retval = -ENOENT;
3444         if (retval) {
3445                 ext4_std_error(old.dir->i_sb, retval);
3446                 return;
3447         }
3448
3449         ext4_setent(handle, &old, ino, file_type);
3450         brelse(old.bh);
3451 }
3452
3453 static int ext4_find_delete_entry(handle_t *handle, struct inode *dir,
3454                                   const struct qstr *d_name)
3455 {
3456         int retval = -ENOENT;
3457         struct buffer_head *bh;
3458         struct ext4_dir_entry_2 *de;
3459
3460         bh = ext4_find_entry(dir, d_name, &de, NULL);
3461         if (IS_ERR(bh))
3462                 return PTR_ERR(bh);
3463         if (bh) {
3464                 retval = ext4_delete_entry(handle, dir, de, bh);
3465                 brelse(bh);
3466         }
3467         return retval;
3468 }
3469
3470 static void ext4_rename_delete(handle_t *handle, struct ext4_renament *ent,
3471                                int force_reread)
3472 {
3473         int retval;
3474         /*
3475          * ent->de could have moved from under us during htree split, so make
3476          * sure that we are deleting the right entry.  We might also be pointing
3477          * to a stale entry in the unused part of ent->bh so just checking inum
3478          * and the name isn't enough.
3479          */
3480         if (le32_to_cpu(ent->de->inode) != ent->inode->i_ino ||
3481             ent->de->name_len != ent->dentry->d_name.len ||
3482             strncmp(ent->de->name, ent->dentry->d_name.name,
3483                     ent->de->name_len) ||
3484             force_reread) {
3485                 retval = ext4_find_delete_entry(handle, ent->dir,
3486                                                 &ent->dentry->d_name);
3487         } else {
3488                 retval = ext4_delete_entry(handle, ent->dir, ent->de, ent->bh);
3489                 if (retval == -ENOENT) {
3490                         retval = ext4_find_delete_entry(handle, ent->dir,
3491                                                         &ent->dentry->d_name);
3492                 }
3493         }
3494
3495         if (retval) {
3496                 ext4_warning_inode(ent->dir,
3497                                    "Deleting old file: nlink %d, error=%d",
3498                                    ent->dir->i_nlink, retval);
3499         }
3500 }
3501
3502 static void ext4_update_dir_count(handle_t *handle, struct ext4_renament *ent)
3503 {
3504         if (ent->dir_nlink_delta) {
3505                 if (ent->dir_nlink_delta == -1)
3506                         ext4_dec_count(handle, ent->dir);
3507                 else
3508                         ext4_inc_count(handle, ent->dir);
3509                 ext4_mark_inode_dirty(handle, ent->dir);
3510         }
3511 }
3512
3513 static struct inode *ext4_whiteout_for_rename(struct ext4_renament *ent,
3514                                               int credits, handle_t **h)
3515 {
3516         struct inode *wh;
3517         handle_t *handle;
3518         int retries = 0;
3519
3520         /*
3521          * for inode block, sb block, group summaries,
3522          * and inode bitmap
3523          */
3524         credits += (EXT4_MAXQUOTAS_TRANS_BLOCKS(ent->dir->i_sb) +
3525                     EXT4_XATTR_TRANS_BLOCKS + 4);
3526 retry:
3527         wh = ext4_new_inode_start_handle(ent->dir, S_IFCHR | WHITEOUT_MODE,
3528                                          &ent->dentry->d_name, 0, NULL,
3529                                          EXT4_HT_DIR, credits);
3530
3531         handle = ext4_journal_current_handle();
3532         if (IS_ERR(wh)) {
3533                 if (handle)
3534                         ext4_journal_stop(handle);
3535                 if (PTR_ERR(wh) == -ENOSPC &&
3536                     ext4_should_retry_alloc(ent->dir->i_sb, &retries))
3537                         goto retry;
3538         } else {
3539                 *h = handle;
3540                 init_special_inode(wh, wh->i_mode, WHITEOUT_DEV);
3541                 wh->i_op = &ext4_special_inode_operations;
3542         }
3543         return wh;
3544 }
3545
3546 /*
3547  * Anybody can rename anything with this: the permission checks are left to the
3548  * higher-level routines.
3549  *
3550  * n.b.  old_{dentry,inode) refers to the source dentry/inode
3551  * while new_{dentry,inode) refers to the destination dentry/inode
3552  * This comes from rename(const char *oldpath, const char *newpath)
3553  */
3554 static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
3555                        struct inode *new_dir, struct dentry *new_dentry,
3556                        unsigned int flags)
3557 {
3558         handle_t *handle = NULL;
3559         struct ext4_renament old = {
3560                 .dir = old_dir,
3561                 .dentry = old_dentry,
3562                 .inode = d_inode(old_dentry),
3563         };
3564         struct ext4_renament new = {
3565                 .dir = new_dir,
3566                 .dentry = new_dentry,
3567                 .inode = d_inode(new_dentry),
3568         };
3569         int force_reread;
3570         int retval;
3571         struct inode *whiteout = NULL;
3572         int credits;
3573         u8 old_file_type;
3574
3575         if (new.inode && new.inode->i_nlink == 0) {
3576                 EXT4_ERROR_INODE(new.inode,
3577                                  "target of rename is already freed");
3578                 return -EFSCORRUPTED;
3579         }
3580
3581         if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT)) &&
3582             (!projid_eq(EXT4_I(new_dir)->i_projid,
3583                         EXT4_I(old_dentry->d_inode)->i_projid)))
3584                 return -EXDEV;
3585
3586         if ((ext4_encrypted_inode(old_dir) &&
3587              !fscrypt_has_encryption_key(old_dir)) ||
3588             (ext4_encrypted_inode(new_dir) &&
3589              !fscrypt_has_encryption_key(new_dir)))
3590                 return -ENOKEY;
3591
3592         retval = dquot_initialize(old.dir);
3593         if (retval)
3594                 return retval;
3595         retval = dquot_initialize(new.dir);
3596         if (retval)
3597                 return retval;
3598
3599         /* Initialize quotas before so that eventual writes go
3600          * in separate transaction */
3601         if (new.inode) {
3602                 retval = dquot_initialize(new.inode);
3603                 if (retval)
3604                         return retval;
3605         }
3606
3607         old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de, NULL);
3608         if (IS_ERR(old.bh))
3609                 return PTR_ERR(old.bh);
3610         /*
3611          *  Check for inode number is _not_ due to possible IO errors.
3612          *  We might rmdir the source, keep it as pwd of some process
3613          *  and merrily kill the link to whatever was created under the
3614          *  same name. Goodbye sticky bit ;-<
3615          */
3616         retval = -ENOENT;
3617         if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3618                 goto release_bh;
3619
3620         if ((old.dir != new.dir) &&
3621             ext4_encrypted_inode(new.dir) &&
3622             !fscrypt_has_permitted_context(new.dir, old.inode)) {
3623                 retval = -EXDEV;
3624                 goto release_bh;
3625         }
3626
3627         new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3628                                  &new.de, &new.inlined);
3629         if (IS_ERR(new.bh)) {
3630                 retval = PTR_ERR(new.bh);
3631                 new.bh = NULL;
3632                 goto release_bh;
3633         }
3634         if (new.bh) {
3635                 if (!new.inode) {
3636                         brelse(new.bh);
3637                         new.bh = NULL;
3638                 }
3639         }
3640         if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC))
3641                 ext4_alloc_da_blocks(old.inode);
3642
3643         credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3644                    EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
3645         if (!(flags & RENAME_WHITEOUT)) {
3646                 handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits);
3647                 if (IS_ERR(handle)) {
3648                         retval = PTR_ERR(handle);
3649                         goto release_bh;
3650                 }
3651         } else {
3652                 whiteout = ext4_whiteout_for_rename(&old, credits, &handle);
3653                 if (IS_ERR(whiteout)) {
3654                         retval = PTR_ERR(whiteout);
3655                         goto release_bh;
3656                 }
3657         }
3658
3659         old_file_type = old.de->file_type;
3660         if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3661                 ext4_handle_sync(handle);
3662
3663         if (S_ISDIR(old.inode->i_mode)) {
3664                 if (new.inode) {
3665                         retval = -ENOTEMPTY;
3666                         if (!ext4_empty_dir(new.inode))
3667                                 goto end_rename;
3668                 } else {
3669                         retval = -EMLINK;
3670                         if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir))
3671                                 goto end_rename;
3672                 }
3673                 retval = ext4_rename_dir_prepare(handle, &old);
3674                 if (retval)
3675                         goto end_rename;
3676         }
3677         /*
3678          * If we're renaming a file within an inline_data dir and adding or
3679          * setting the new dirent causes a conversion from inline_data to
3680          * extents/blockmap, we need to force the dirent delete code to
3681          * re-read the directory, or else we end up trying to delete a dirent
3682          * from what is now the extent tree root (or a block map).
3683          */
3684         force_reread = (new.dir->i_ino == old.dir->i_ino &&
3685                         ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA));
3686
3687         if (whiteout) {
3688                 /*
3689                  * Do this before adding a new entry, so the old entry is sure
3690                  * to be still pointing to the valid old entry.
3691                  */
3692                 retval = ext4_setent(handle, &old, whiteout->i_ino,
3693                                      EXT4_FT_CHRDEV);
3694                 if (retval)
3695                         goto end_rename;
3696                 ext4_mark_inode_dirty(handle, whiteout);
3697         }
3698         if (!new.bh) {
3699                 retval = ext4_add_entry(handle, new.dentry, old.inode);
3700                 if (retval)
3701                         goto end_rename;
3702         } else {
3703                 retval = ext4_setent(handle, &new,
3704                                      old.inode->i_ino, old_file_type);
3705                 if (retval)
3706                         goto end_rename;
3707         }
3708         if (force_reread)
3709                 force_reread = !ext4_test_inode_flag(new.dir,
3710                                                      EXT4_INODE_INLINE_DATA);
3711
3712         /*
3713          * Like most other Unix systems, set the ctime for inodes on a
3714          * rename.
3715          */
3716         old.inode->i_ctime = ext4_current_time(old.inode);
3717         ext4_mark_inode_dirty(handle, old.inode);
3718
3719         if (!whiteout) {
3720                 /*
3721                  * ok, that's it
3722                  */
3723                 ext4_rename_delete(handle, &old, force_reread);
3724         }
3725
3726         if (new.inode) {
3727                 ext4_dec_count(handle, new.inode);
3728                 new.inode->i_ctime = ext4_current_time(new.inode);
3729         }
3730         old.dir->i_ctime = old.dir->i_mtime = ext4_current_time(old.dir);
3731         ext4_update_dx_flag(old.dir);
3732         if (old.dir_bh) {
3733                 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3734                 if (retval)
3735                         goto end_rename;
3736
3737                 ext4_dec_count(handle, old.dir);
3738                 if (new.inode) {
3739                         /* checked ext4_empty_dir above, can't have another
3740                          * parent, ext4_dec_count() won't work for many-linked
3741                          * dirs */
3742                         clear_nlink(new.inode);
3743                 } else {
3744                         ext4_inc_count(handle, new.dir);
3745                         ext4_update_dx_flag(new.dir);
3746                         ext4_mark_inode_dirty(handle, new.dir);
3747                 }
3748         }
3749         ext4_mark_inode_dirty(handle, old.dir);
3750         if (new.inode) {
3751                 ext4_mark_inode_dirty(handle, new.inode);
3752                 if (!new.inode->i_nlink)
3753                         ext4_orphan_add(handle, new.inode);
3754         }
3755         retval = 0;
3756
3757 end_rename:
3758         if (whiteout) {
3759                 if (retval) {
3760                         ext4_resetent(handle, &old,
3761                                       old.inode->i_ino, old_file_type);
3762                         drop_nlink(whiteout);
3763                         ext4_orphan_add(handle, whiteout);
3764                 }
3765                 unlock_new_inode(whiteout);
3766                 ext4_journal_stop(handle);
3767                 iput(whiteout);
3768         } else {
3769                 ext4_journal_stop(handle);
3770         }
3771 release_bh:
3772         brelse(old.dir_bh);
3773         brelse(old.bh);
3774         brelse(new.bh);
3775         return retval;
3776 }
3777
3778 static int ext4_cross_rename(struct inode *old_dir, struct dentry *old_dentry,
3779                              struct inode *new_dir, struct dentry *new_dentry)
3780 {
3781         handle_t *handle = NULL;
3782         struct ext4_renament old = {
3783                 .dir = old_dir,
3784                 .dentry = old_dentry,
3785                 .inode = d_inode(old_dentry),
3786         };
3787         struct ext4_renament new = {
3788                 .dir = new_dir,
3789                 .dentry = new_dentry,
3790                 .inode = d_inode(new_dentry),
3791         };
3792         u8 new_file_type;
3793         int retval;
3794
3795         if ((ext4_encrypted_inode(old_dir) &&
3796              !fscrypt_has_encryption_key(old_dir)) ||
3797             (ext4_encrypted_inode(new_dir) &&
3798              !fscrypt_has_encryption_key(new_dir)))
3799                 return -ENOKEY;
3800
3801         if ((ext4_encrypted_inode(old_dir) ||
3802              ext4_encrypted_inode(new_dir)) &&
3803             (old_dir != new_dir) &&
3804             (!fscrypt_has_permitted_context(new_dir, old.inode) ||
3805              !fscrypt_has_permitted_context(old_dir, new.inode)))
3806                 return -EXDEV;
3807
3808         if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT) &&
3809              !projid_eq(EXT4_I(new_dir)->i_projid,
3810                         EXT4_I(old_dentry->d_inode)->i_projid)) ||
3811             (ext4_test_inode_flag(old_dir, EXT4_INODE_PROJINHERIT) &&
3812              !projid_eq(EXT4_I(old_dir)->i_projid,
3813                         EXT4_I(new_dentry->d_inode)->i_projid)))
3814                 return -EXDEV;
3815
3816         retval = dquot_initialize(old.dir);
3817         if (retval)
3818                 return retval;
3819         retval = dquot_initialize(new.dir);
3820         if (retval)
3821                 return retval;
3822
3823         old.bh = ext4_find_entry(old.dir, &old.dentry->d_name,
3824                                  &old.de, &old.inlined);
3825         if (IS_ERR(old.bh))
3826                 return PTR_ERR(old.bh);
3827         /*
3828          *  Check for inode number is _not_ due to possible IO errors.
3829          *  We might rmdir the source, keep it as pwd of some process
3830          *  and merrily kill the link to whatever was created under the
3831          *  same name. Goodbye sticky bit ;-<
3832          */
3833         retval = -ENOENT;
3834         if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3835                 goto end_rename;
3836
3837         new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3838                                  &new.de, &new.inlined);
3839         if (IS_ERR(new.bh)) {
3840                 retval = PTR_ERR(new.bh);
3841                 new.bh = NULL;
3842                 goto end_rename;
3843         }
3844
3845         /* RENAME_EXCHANGE case: old *and* new must both exist */
3846         if (!new.bh || le32_to_cpu(new.de->inode) != new.inode->i_ino)
3847                 goto end_rename;
3848
3849         handle = ext4_journal_start(old.dir, EXT4_HT_DIR,
3850                 (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3851                  2 * EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2));
3852         if (IS_ERR(handle)) {
3853                 retval = PTR_ERR(handle);
3854                 handle = NULL;
3855                 goto end_rename;
3856         }
3857
3858         if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3859                 ext4_handle_sync(handle);
3860
3861         if (S_ISDIR(old.inode->i_mode)) {
3862                 old.is_dir = true;
3863                 retval = ext4_rename_dir_prepare(handle, &old);
3864                 if (retval)
3865                         goto end_rename;
3866         }
3867         if (S_ISDIR(new.inode->i_mode)) {
3868                 new.is_dir = true;
3869                 retval = ext4_rename_dir_prepare(handle, &new);
3870                 if (retval)
3871                         goto end_rename;
3872         }
3873
3874         /*
3875          * Other than the special case of overwriting a directory, parents'
3876          * nlink only needs to be modified if this is a cross directory rename.
3877          */
3878         if (old.dir != new.dir && old.is_dir != new.is_dir) {
3879                 old.dir_nlink_delta = old.is_dir ? -1 : 1;
3880                 new.dir_nlink_delta = -old.dir_nlink_delta;
3881                 retval = -EMLINK;
3882                 if ((old.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(old.dir)) ||
3883                     (new.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(new.dir)))
3884                         goto end_rename;
3885         }
3886
3887         new_file_type = new.de->file_type;
3888         retval = ext4_setent(handle, &new, old.inode->i_ino, old.de->file_type);
3889         if (retval)
3890                 goto end_rename;
3891
3892         retval = ext4_setent(handle, &old, new.inode->i_ino, new_file_type);
3893         if (retval)
3894                 goto end_rename;
3895
3896         /*
3897          * Like most other Unix systems, set the ctime for inodes on a
3898          * rename.
3899          */
3900         old.inode->i_ctime = ext4_current_time(old.inode);
3901         new.inode->i_ctime = ext4_current_time(new.inode);
3902         ext4_mark_inode_dirty(handle, old.inode);
3903         ext4_mark_inode_dirty(handle, new.inode);
3904
3905         if (old.dir_bh) {
3906                 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3907                 if (retval)
3908                         goto end_rename;
3909         }
3910         if (new.dir_bh) {
3911                 retval = ext4_rename_dir_finish(handle, &new, old.dir->i_ino);
3912                 if (retval)
3913                         goto end_rename;
3914         }
3915         ext4_update_dir_count(handle, &old);
3916         ext4_update_dir_count(handle, &new);
3917         retval = 0;
3918
3919 end_rename:
3920         brelse(old.dir_bh);
3921         brelse(new.dir_bh);
3922         brelse(old.bh);
3923         brelse(new.bh);
3924         if (handle)
3925                 ext4_journal_stop(handle);
3926         return retval;
3927 }
3928
3929 static int ext4_rename2(struct inode *old_dir, struct dentry *old_dentry,
3930                         struct inode *new_dir, struct dentry *new_dentry,
3931                         unsigned int flags)
3932 {
3933         if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
3934                 return -EINVAL;
3935
3936         if (flags & RENAME_EXCHANGE) {
3937                 return ext4_cross_rename(old_dir, old_dentry,
3938                                          new_dir, new_dentry);
3939         }
3940
3941         return ext4_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
3942 }
3943
3944 /*
3945  * directories can handle most operations...
3946  */
3947 const struct inode_operations ext4_dir_inode_operations = {
3948         .create         = ext4_create,
3949         .lookup         = ext4_lookup,
3950         .link           = ext4_link,
3951         .unlink         = ext4_unlink,
3952         .symlink        = ext4_symlink,
3953         .mkdir          = ext4_mkdir,
3954         .rmdir          = ext4_rmdir,
3955         .mknod          = ext4_mknod,
3956         .tmpfile        = ext4_tmpfile,
3957         .rename         = ext4_rename2,
3958         .setattr        = ext4_setattr,
3959         .listxattr      = ext4_listxattr,
3960         .get_acl        = ext4_get_acl,
3961         .set_acl        = ext4_set_acl,
3962         .fiemap         = ext4_fiemap,
3963 };
3964
3965 const struct inode_operations ext4_special_inode_operations = {
3966         .setattr        = ext4_setattr,
3967         .listxattr      = ext4_listxattr,
3968         .get_acl        = ext4_get_acl,
3969         .set_acl        = ext4_set_acl,
3970 };