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