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