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