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