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