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