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