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