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