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