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