1 // SPDX-License-Identifier: GPL-2.0
3 * linux/fs/ext4/namei.c
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)
12 * linux/fs/minix/namei.c
14 * Copyright (C) 1991, 1992 Linus Torvalds
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
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>
40 #include "ext4_jbd2.h"
45 #include <trace/events/ext4.h>
47 * define how far ahead to read directories while searching them.
49 #define NAMEI_RA_CHUNKS 2
50 #define NAMEI_RA_BLOCKS 4
51 #define NAMEI_RA_SIZE (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
53 static struct buffer_head *ext4_append(handle_t *handle,
57 struct buffer_head *bh;
60 if (unlikely(EXT4_SB(inode->i_sb)->s_max_dir_size_kb &&
61 ((inode->i_size >> 10) >=
62 EXT4_SB(inode->i_sb)->s_max_dir_size_kb)))
63 return ERR_PTR(-ENOSPC);
65 *block = inode->i_size >> inode->i_sb->s_blocksize_bits;
67 bh = ext4_bread(handle, inode, *block, EXT4_GET_BLOCKS_CREATE);
70 inode->i_size += inode->i_sb->s_blocksize;
71 EXT4_I(inode)->i_disksize = inode->i_size;
72 BUFFER_TRACE(bh, "get_write_access");
73 err = ext4_journal_get_write_access(handle, bh);
76 ext4_std_error(inode->i_sb, err);
82 static int ext4_dx_csum_verify(struct inode *inode,
83 struct ext4_dir_entry *dirent);
89 #define ext4_read_dirblock(inode, block, type) \
90 __ext4_read_dirblock((inode), (block), (type), __func__, __LINE__)
92 static struct buffer_head *__ext4_read_dirblock(struct inode *inode,
98 struct buffer_head *bh;
99 struct ext4_dir_entry *dirent;
102 bh = ext4_bread(NULL, inode, block, 0);
104 __ext4_warning(inode->i_sb, func, line,
105 "inode #%lu: lblock %lu: comm %s: "
106 "error %ld reading directory block",
107 inode->i_ino, (unsigned long)block,
108 current->comm, PTR_ERR(bh));
113 ext4_error_inode(inode, func, line, block,
114 "Directory hole found");
115 return ERR_PTR(-EFSCORRUPTED);
117 dirent = (struct ext4_dir_entry *) bh->b_data;
118 /* Determine whether or not we have an index block */
122 else if (ext4_rec_len_from_disk(dirent->rec_len,
123 inode->i_sb->s_blocksize) ==
124 inode->i_sb->s_blocksize)
127 if (!is_dx_block && type == INDEX) {
128 ext4_error_inode(inode, func, line, block,
129 "directory leaf block found instead of index block");
131 return ERR_PTR(-EFSCORRUPTED);
133 if (!ext4_has_metadata_csum(inode->i_sb) ||
138 * An empty leaf block can get mistaken for a index block; for
139 * this reason, we can only check the index checksum when the
140 * caller is sure it should be an index block.
142 if (is_dx_block && type == INDEX) {
143 if (ext4_dx_csum_verify(inode, dirent))
144 set_buffer_verified(bh);
146 ext4_error_inode(inode, func, line, block,
147 "Directory index failed checksum");
149 return ERR_PTR(-EFSBADCRC);
153 if (ext4_dirent_csum_verify(inode, dirent))
154 set_buffer_verified(bh);
156 ext4_error_inode(inode, func, line, block,
157 "Directory block failed checksum");
159 return ERR_PTR(-EFSBADCRC);
166 #define assert(test) J_ASSERT(test)
170 #define dxtrace(command) command
172 #define dxtrace(command)
196 * dx_root_info is laid out so that if it should somehow get overlaid by a
197 * dirent the two low bits of the hash version will be zero. Therefore, the
198 * hash version mod 4 should never be 0. Sincerely, the paranoia department.
203 struct fake_dirent dot;
205 struct fake_dirent dotdot;
209 __le32 reserved_zero;
211 u8 info_length; /* 8 */
216 struct dx_entry entries[0];
221 struct fake_dirent fake;
222 struct dx_entry entries[0];
228 struct buffer_head *bh;
229 struct dx_entry *entries;
241 * This goes at the end of each htree block.
245 __le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */
248 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry);
249 static void dx_set_block(struct dx_entry *entry, ext4_lblk_t value);
250 static inline unsigned dx_get_hash(struct dx_entry *entry);
251 static void dx_set_hash(struct dx_entry *entry, unsigned value);
252 static unsigned dx_get_count(struct dx_entry *entries);
253 static unsigned dx_get_limit(struct dx_entry *entries);
254 static void dx_set_count(struct dx_entry *entries, unsigned value);
255 static void dx_set_limit(struct dx_entry *entries, unsigned value);
256 static unsigned dx_root_limit(struct inode *dir, unsigned infosize);
257 static unsigned dx_node_limit(struct inode *dir);
258 static struct dx_frame *dx_probe(struct ext4_filename *fname,
260 struct dx_hash_info *hinfo,
261 struct dx_frame *frame);
262 static void dx_release(struct dx_frame *frames);
263 static int dx_make_map(struct inode *dir, struct ext4_dir_entry_2 *de,
264 unsigned blocksize, struct dx_hash_info *hinfo,
265 struct dx_map_entry map[]);
266 static void dx_sort_map(struct dx_map_entry *map, unsigned count);
267 static struct ext4_dir_entry_2 *dx_move_dirents(char *from, char *to,
268 struct dx_map_entry *offsets, int count, unsigned blocksize);
269 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize);
270 static void dx_insert_block(struct dx_frame *frame,
271 u32 hash, ext4_lblk_t block);
272 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
273 struct dx_frame *frame,
274 struct dx_frame *frames,
276 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
277 struct ext4_filename *fname,
278 struct ext4_dir_entry_2 **res_dir);
279 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
280 struct inode *dir, struct inode *inode);
282 /* checksumming functions */
283 void initialize_dirent_tail(struct ext4_dir_entry_tail *t,
284 unsigned int blocksize)
286 memset(t, 0, sizeof(struct ext4_dir_entry_tail));
287 t->det_rec_len = ext4_rec_len_to_disk(
288 sizeof(struct ext4_dir_entry_tail), blocksize);
289 t->det_reserved_ft = EXT4_FT_DIR_CSUM;
292 /* Walk through a dirent block to find a checksum "dirent" at the tail */
293 static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode,
294 struct ext4_dir_entry *de)
296 struct ext4_dir_entry_tail *t;
299 struct ext4_dir_entry *d, *top;
302 top = (struct ext4_dir_entry *)(((void *)de) +
303 (EXT4_BLOCK_SIZE(inode->i_sb) -
304 sizeof(struct ext4_dir_entry_tail)));
305 while (d < top && d->rec_len)
306 d = (struct ext4_dir_entry *)(((void *)d) +
307 le16_to_cpu(d->rec_len));
312 t = (struct ext4_dir_entry_tail *)d;
314 t = EXT4_DIRENT_TAIL(de, EXT4_BLOCK_SIZE(inode->i_sb));
317 if (t->det_reserved_zero1 ||
318 le16_to_cpu(t->det_rec_len) != sizeof(struct ext4_dir_entry_tail) ||
319 t->det_reserved_zero2 ||
320 t->det_reserved_ft != EXT4_FT_DIR_CSUM)
326 static __le32 ext4_dirent_csum(struct inode *inode,
327 struct ext4_dir_entry *dirent, int size)
329 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
330 struct ext4_inode_info *ei = EXT4_I(inode);
333 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
334 return cpu_to_le32(csum);
337 #define warn_no_space_for_csum(inode) \
338 __warn_no_space_for_csum((inode), __func__, __LINE__)
340 static void __warn_no_space_for_csum(struct inode *inode, const char *func,
343 __ext4_warning_inode(inode, func, line,
344 "No space for directory leaf checksum. Please run e2fsck -D.");
347 int ext4_dirent_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent)
349 struct ext4_dir_entry_tail *t;
351 if (!ext4_has_metadata_csum(inode->i_sb))
354 t = get_dirent_tail(inode, dirent);
356 warn_no_space_for_csum(inode);
360 if (t->det_checksum != ext4_dirent_csum(inode, dirent,
361 (void *)t - (void *)dirent))
367 static void ext4_dirent_csum_set(struct inode *inode,
368 struct ext4_dir_entry *dirent)
370 struct ext4_dir_entry_tail *t;
372 if (!ext4_has_metadata_csum(inode->i_sb))
375 t = get_dirent_tail(inode, dirent);
377 warn_no_space_for_csum(inode);
381 t->det_checksum = ext4_dirent_csum(inode, dirent,
382 (void *)t - (void *)dirent);
385 int ext4_handle_dirty_dirent_node(handle_t *handle,
387 struct buffer_head *bh)
389 ext4_dirent_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
390 return ext4_handle_dirty_metadata(handle, inode, bh);
393 static struct dx_countlimit *get_dx_countlimit(struct inode *inode,
394 struct ext4_dir_entry *dirent,
397 struct ext4_dir_entry *dp;
398 struct dx_root_info *root;
401 if (le16_to_cpu(dirent->rec_len) == EXT4_BLOCK_SIZE(inode->i_sb))
403 else if (le16_to_cpu(dirent->rec_len) == 12) {
404 dp = (struct ext4_dir_entry *)(((void *)dirent) + 12);
405 if (le16_to_cpu(dp->rec_len) !=
406 EXT4_BLOCK_SIZE(inode->i_sb) - 12)
408 root = (struct dx_root_info *)(((void *)dp + 12));
409 if (root->reserved_zero ||
410 root->info_length != sizeof(struct dx_root_info))
417 *offset = count_offset;
418 return (struct dx_countlimit *)(((void *)dirent) + count_offset);
421 static __le32 ext4_dx_csum(struct inode *inode, struct ext4_dir_entry *dirent,
422 int count_offset, int count, struct dx_tail *t)
424 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
425 struct ext4_inode_info *ei = EXT4_I(inode);
428 __u32 dummy_csum = 0;
429 int offset = offsetof(struct dx_tail, dt_checksum);
431 size = count_offset + (count * sizeof(struct dx_entry));
432 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
433 csum = ext4_chksum(sbi, csum, (__u8 *)t, offset);
434 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
436 return cpu_to_le32(csum);
439 static int ext4_dx_csum_verify(struct inode *inode,
440 struct ext4_dir_entry *dirent)
442 struct dx_countlimit *c;
444 int count_offset, limit, count;
446 if (!ext4_has_metadata_csum(inode->i_sb))
449 c = get_dx_countlimit(inode, dirent, &count_offset);
451 EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
454 limit = le16_to_cpu(c->limit);
455 count = le16_to_cpu(c->count);
456 if (count_offset + (limit * sizeof(struct dx_entry)) >
457 EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
458 warn_no_space_for_csum(inode);
461 t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
463 if (t->dt_checksum != ext4_dx_csum(inode, dirent, count_offset,
469 static void ext4_dx_csum_set(struct inode *inode, struct ext4_dir_entry *dirent)
471 struct dx_countlimit *c;
473 int count_offset, limit, count;
475 if (!ext4_has_metadata_csum(inode->i_sb))
478 c = get_dx_countlimit(inode, dirent, &count_offset);
480 EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
483 limit = le16_to_cpu(c->limit);
484 count = le16_to_cpu(c->count);
485 if (count_offset + (limit * sizeof(struct dx_entry)) >
486 EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
487 warn_no_space_for_csum(inode);
490 t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
492 t->dt_checksum = ext4_dx_csum(inode, dirent, count_offset, count, t);
495 static inline int ext4_handle_dirty_dx_node(handle_t *handle,
497 struct buffer_head *bh)
499 ext4_dx_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
500 return ext4_handle_dirty_metadata(handle, inode, bh);
504 * p is at least 6 bytes before the end of page
506 static inline struct ext4_dir_entry_2 *
507 ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize)
509 return (struct ext4_dir_entry_2 *)((char *)p +
510 ext4_rec_len_from_disk(p->rec_len, blocksize));
514 * Future: use high four bits of block for coalesce-on-delete flags
515 * Mask them off for now.
518 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry)
520 return le32_to_cpu(entry->block) & 0x0fffffff;
523 static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value)
525 entry->block = cpu_to_le32(value);
528 static inline unsigned dx_get_hash(struct dx_entry *entry)
530 return le32_to_cpu(entry->hash);
533 static inline void dx_set_hash(struct dx_entry *entry, unsigned value)
535 entry->hash = cpu_to_le32(value);
538 static inline unsigned dx_get_count(struct dx_entry *entries)
540 return le16_to_cpu(((struct dx_countlimit *) entries)->count);
543 static inline unsigned dx_get_limit(struct dx_entry *entries)
545 return le16_to_cpu(((struct dx_countlimit *) entries)->limit);
548 static inline void dx_set_count(struct dx_entry *entries, unsigned value)
550 ((struct dx_countlimit *) entries)->count = cpu_to_le16(value);
553 static inline void dx_set_limit(struct dx_entry *entries, unsigned value)
555 ((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
558 static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize)
560 unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(1) -
561 EXT4_DIR_REC_LEN(2) - infosize;
563 if (ext4_has_metadata_csum(dir->i_sb))
564 entry_space -= sizeof(struct dx_tail);
565 return entry_space / sizeof(struct dx_entry);
568 static inline unsigned dx_node_limit(struct inode *dir)
570 unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0);
572 if (ext4_has_metadata_csum(dir->i_sb))
573 entry_space -= sizeof(struct dx_tail);
574 return entry_space / sizeof(struct dx_entry);
581 static void dx_show_index(char * label, struct dx_entry *entries)
583 int i, n = dx_get_count (entries);
584 printk(KERN_DEBUG "%s index", label);
585 for (i = 0; i < n; i++) {
586 printk(KERN_CONT " %x->%lu",
587 i ? dx_get_hash(entries + i) : 0,
588 (unsigned long)dx_get_block(entries + i));
590 printk(KERN_CONT "\n");
600 static struct stats dx_show_leaf(struct inode *dir,
601 struct dx_hash_info *hinfo,
602 struct ext4_dir_entry_2 *de,
603 int size, int show_names)
605 unsigned names = 0, space = 0;
606 char *base = (char *) de;
607 struct dx_hash_info h = *hinfo;
610 while ((char *) de < base + size)
616 #ifdef CONFIG_FS_ENCRYPTION
619 struct fscrypt_str fname_crypto_str =
625 if (IS_ENCRYPTED(dir))
626 res = fscrypt_get_encryption_info(dir);
628 printk(KERN_WARNING "Error setting up"
629 " fname crypto: %d\n", res);
631 if (!fscrypt_has_encryption_key(dir)) {
632 /* Directory is not encrypted */
633 ext4fs_dirhash(dir, de->name,
635 printk("%*.s:(U)%x.%u ", len,
637 (unsigned) ((char *) de
640 struct fscrypt_str de_name =
641 FSTR_INIT(name, len);
643 /* Directory is encrypted */
644 res = fscrypt_fname_alloc_buffer(
648 printk(KERN_WARNING "Error "
652 res = fscrypt_fname_disk_to_usr(dir,
656 printk(KERN_WARNING "Error "
657 "converting filename "
663 name = fname_crypto_str.name;
664 len = fname_crypto_str.len;
666 ext4fs_dirhash(dir, de->name,
668 printk("%*.s:(E)%x.%u ", len, name,
669 h.hash, (unsigned) ((char *) de
671 fscrypt_fname_free_buffer(
675 int len = de->name_len;
676 char *name = de->name;
677 ext4fs_dirhash(dir, de->name, de->name_len, &h);
678 printk("%*.s:%x.%u ", len, name, h.hash,
679 (unsigned) ((char *) de - base));
682 space += EXT4_DIR_REC_LEN(de->name_len);
685 de = ext4_next_entry(de, size);
687 printk(KERN_CONT "(%i)\n", names);
688 return (struct stats) { names, space, 1 };
691 struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir,
692 struct dx_entry *entries, int levels)
694 unsigned blocksize = dir->i_sb->s_blocksize;
695 unsigned count = dx_get_count(entries), names = 0, space = 0, i;
697 struct buffer_head *bh;
698 printk("%i indexed blocks...\n", count);
699 for (i = 0; i < count; i++, entries++)
701 ext4_lblk_t block = dx_get_block(entries);
702 ext4_lblk_t hash = i ? dx_get_hash(entries): 0;
703 u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash;
705 printk("%s%3u:%03u hash %8x/%8x ",levels?"":" ", i, block, hash, range);
706 bh = ext4_bread(NULL,dir, block, 0);
707 if (!bh || IS_ERR(bh))
710 dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1):
711 dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *)
712 bh->b_data, blocksize, 0);
713 names += stats.names;
714 space += stats.space;
715 bcount += stats.bcount;
719 printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n",
720 levels ? "" : " ", names, space/bcount,
721 (space/bcount)*100/blocksize);
722 return (struct stats) { names, space, bcount};
724 #endif /* DX_DEBUG */
727 * Probe for a directory leaf block to search.
729 * dx_probe can return ERR_BAD_DX_DIR, which means there was a format
730 * error in the directory index, and the caller should fall back to
731 * searching the directory normally. The callers of dx_probe **MUST**
732 * check for this error code, and make sure it never gets reflected
735 static struct dx_frame *
736 dx_probe(struct ext4_filename *fname, struct inode *dir,
737 struct dx_hash_info *hinfo, struct dx_frame *frame_in)
739 unsigned count, indirect;
740 struct dx_entry *at, *entries, *p, *q, *m;
741 struct dx_root *root;
742 struct dx_frame *frame = frame_in;
743 struct dx_frame *ret_err = ERR_PTR(ERR_BAD_DX_DIR);
746 memset(frame_in, 0, EXT4_HTREE_LEVEL * sizeof(frame_in[0]));
747 frame->bh = ext4_read_dirblock(dir, 0, INDEX);
748 if (IS_ERR(frame->bh))
749 return (struct dx_frame *) frame->bh;
751 root = (struct dx_root *) frame->bh->b_data;
752 if (root->info.hash_version != DX_HASH_TEA &&
753 root->info.hash_version != DX_HASH_HALF_MD4 &&
754 root->info.hash_version != DX_HASH_LEGACY) {
755 ext4_warning_inode(dir, "Unrecognised inode hash code %u",
756 root->info.hash_version);
760 hinfo = &fname->hinfo;
761 hinfo->hash_version = root->info.hash_version;
762 if (hinfo->hash_version <= DX_HASH_TEA)
763 hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
764 hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed;
765 if (fname && fname_name(fname))
766 ext4fs_dirhash(dir, fname_name(fname), fname_len(fname), hinfo);
769 if (root->info.unused_flags & 1) {
770 ext4_warning_inode(dir, "Unimplemented hash flags: %#06x",
771 root->info.unused_flags);
775 indirect = root->info.indirect_levels;
776 if (indirect >= ext4_dir_htree_level(dir->i_sb)) {
777 ext4_warning(dir->i_sb,
778 "Directory (ino: %lu) htree depth %#06x exceed"
779 "supported value", dir->i_ino,
780 ext4_dir_htree_level(dir->i_sb));
781 if (ext4_dir_htree_level(dir->i_sb) < EXT4_HTREE_LEVEL) {
782 ext4_warning(dir->i_sb, "Enable large directory "
783 "feature to access it");
788 entries = (struct dx_entry *)(((char *)&root->info) +
789 root->info.info_length);
791 if (dx_get_limit(entries) != dx_root_limit(dir,
792 root->info.info_length)) {
793 ext4_warning_inode(dir, "dx entry: limit %u != root limit %u",
794 dx_get_limit(entries),
795 dx_root_limit(dir, root->info.info_length));
799 dxtrace(printk("Look up %x", hash));
801 count = dx_get_count(entries);
802 if (!count || count > dx_get_limit(entries)) {
803 ext4_warning_inode(dir,
804 "dx entry: count %u beyond limit %u",
805 count, dx_get_limit(entries));
810 q = entries + count - 1;
813 dxtrace(printk(KERN_CONT "."));
814 if (dx_get_hash(m) > hash)
820 if (0) { // linear search cross check
821 unsigned n = count - 1;
825 dxtrace(printk(KERN_CONT ","));
826 if (dx_get_hash(++at) > hash)
832 assert (at == p - 1);
836 dxtrace(printk(KERN_CONT " %x->%u\n",
837 at == entries ? 0 : dx_get_hash(at),
839 frame->entries = entries;
844 frame->bh = ext4_read_dirblock(dir, dx_get_block(at), INDEX);
845 if (IS_ERR(frame->bh)) {
846 ret_err = (struct dx_frame *) frame->bh;
850 entries = ((struct dx_node *) frame->bh->b_data)->entries;
852 if (dx_get_limit(entries) != dx_node_limit(dir)) {
853 ext4_warning_inode(dir,
854 "dx entry: limit %u != node limit %u",
855 dx_get_limit(entries), dx_node_limit(dir));
860 while (frame >= frame_in) {
865 if (ret_err == ERR_PTR(ERR_BAD_DX_DIR))
866 ext4_warning_inode(dir,
867 "Corrupt directory, running e2fsck is recommended");
871 static void dx_release(struct dx_frame *frames)
873 struct dx_root_info *info;
876 if (frames[0].bh == NULL)
879 info = &((struct dx_root *)frames[0].bh->b_data)->info;
880 for (i = 0; i <= info->indirect_levels; i++) {
881 if (frames[i].bh == NULL)
883 brelse(frames[i].bh);
889 * This function increments the frame pointer to search the next leaf
890 * block, and reads in the necessary intervening nodes if the search
891 * should be necessary. Whether or not the search is necessary is
892 * controlled by the hash parameter. If the hash value is even, then
893 * the search is only continued if the next block starts with that
894 * hash value. This is used if we are searching for a specific file.
896 * If the hash value is HASH_NB_ALWAYS, then always go to the next block.
898 * This function returns 1 if the caller should continue to search,
899 * or 0 if it should not. If there is an error reading one of the
900 * index blocks, it will a negative error code.
902 * If start_hash is non-null, it will be filled in with the starting
903 * hash of the next page.
905 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
906 struct dx_frame *frame,
907 struct dx_frame *frames,
911 struct buffer_head *bh;
917 * Find the next leaf page by incrementing the frame pointer.
918 * If we run out of entries in the interior node, loop around and
919 * increment pointer in the parent node. When we break out of
920 * this loop, num_frames indicates the number of interior
921 * nodes need to be read.
924 if (++(p->at) < p->entries + dx_get_count(p->entries))
933 * If the hash is 1, then continue only if the next page has a
934 * continuation hash of any value. This is used for readdir
935 * handling. Otherwise, check to see if the hash matches the
936 * desired contiuation hash. If it doesn't, return since
937 * there's no point to read in the successive index pages.
939 bhash = dx_get_hash(p->at);
942 if ((hash & 1) == 0) {
943 if ((bhash & ~1) != hash)
947 * If the hash is HASH_NB_ALWAYS, we always go to the next
948 * block so no check is necessary
950 while (num_frames--) {
951 bh = ext4_read_dirblock(dir, dx_get_block(p->at), INDEX);
957 p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
964 * This function fills a red-black tree with information from a
965 * directory block. It returns the number directory entries loaded
966 * into the tree. If there is an error it is returned in err.
968 static int htree_dirblock_to_tree(struct file *dir_file,
969 struct inode *dir, ext4_lblk_t block,
970 struct dx_hash_info *hinfo,
971 __u32 start_hash, __u32 start_minor_hash)
973 struct buffer_head *bh;
974 struct ext4_dir_entry_2 *de, *top;
975 int err = 0, count = 0;
976 struct fscrypt_str fname_crypto_str = FSTR_INIT(NULL, 0), tmp_str;
978 dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n",
979 (unsigned long)block));
980 bh = ext4_read_dirblock(dir, block, DIRENT);
984 de = (struct ext4_dir_entry_2 *) bh->b_data;
985 top = (struct ext4_dir_entry_2 *) ((char *) de +
986 dir->i_sb->s_blocksize -
987 EXT4_DIR_REC_LEN(0));
988 #ifdef CONFIG_FS_ENCRYPTION
989 /* Check if the directory is encrypted */
990 if (IS_ENCRYPTED(dir)) {
991 err = fscrypt_get_encryption_info(dir);
996 err = fscrypt_fname_alloc_buffer(dir, EXT4_NAME_LEN,
1004 for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) {
1005 if (ext4_check_dir_entry(dir, NULL, de, bh,
1006 bh->b_data, bh->b_size,
1007 (block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb))
1008 + ((char *)de - bh->b_data))) {
1009 /* silently ignore the rest of the block */
1012 ext4fs_dirhash(dir, de->name, de->name_len, hinfo);
1013 if ((hinfo->hash < start_hash) ||
1014 ((hinfo->hash == start_hash) &&
1015 (hinfo->minor_hash < start_minor_hash)))
1019 if (!IS_ENCRYPTED(dir)) {
1020 tmp_str.name = de->name;
1021 tmp_str.len = de->name_len;
1022 err = ext4_htree_store_dirent(dir_file,
1023 hinfo->hash, hinfo->minor_hash, de,
1026 int save_len = fname_crypto_str.len;
1027 struct fscrypt_str de_name = FSTR_INIT(de->name,
1030 /* Directory is encrypted */
1031 err = fscrypt_fname_disk_to_usr(dir, hinfo->hash,
1032 hinfo->minor_hash, &de_name,
1038 err = ext4_htree_store_dirent(dir_file,
1039 hinfo->hash, hinfo->minor_hash, de,
1041 fname_crypto_str.len = save_len;
1051 #ifdef CONFIG_FS_ENCRYPTION
1052 fscrypt_fname_free_buffer(&fname_crypto_str);
1059 * This function fills a red-black tree with information from a
1060 * directory. We start scanning the directory in hash order, starting
1061 * at start_hash and start_minor_hash.
1063 * This function returns the number of entries inserted into the tree,
1064 * or a negative error code.
1066 int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
1067 __u32 start_minor_hash, __u32 *next_hash)
1069 struct dx_hash_info hinfo;
1070 struct ext4_dir_entry_2 *de;
1071 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1077 struct fscrypt_str tmp_str;
1079 dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n",
1080 start_hash, start_minor_hash));
1081 dir = file_inode(dir_file);
1082 if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) {
1083 hinfo.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
1084 if (hinfo.hash_version <= DX_HASH_TEA)
1085 hinfo.hash_version +=
1086 EXT4_SB(dir->i_sb)->s_hash_unsigned;
1087 hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
1088 if (ext4_has_inline_data(dir)) {
1089 int has_inline_data = 1;
1090 count = htree_inlinedir_to_tree(dir_file, dir, 0,
1094 if (has_inline_data) {
1099 count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo,
1100 start_hash, start_minor_hash);
1104 hinfo.hash = start_hash;
1105 hinfo.minor_hash = 0;
1106 frame = dx_probe(NULL, dir, &hinfo, frames);
1108 return PTR_ERR(frame);
1110 /* Add '.' and '..' from the htree header */
1111 if (!start_hash && !start_minor_hash) {
1112 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1113 tmp_str.name = de->name;
1114 tmp_str.len = de->name_len;
1115 err = ext4_htree_store_dirent(dir_file, 0, 0,
1121 if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) {
1122 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1123 de = ext4_next_entry(de, dir->i_sb->s_blocksize);
1124 tmp_str.name = de->name;
1125 tmp_str.len = de->name_len;
1126 err = ext4_htree_store_dirent(dir_file, 2, 0,
1134 if (fatal_signal_pending(current)) {
1139 block = dx_get_block(frame->at);
1140 ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
1141 start_hash, start_minor_hash);
1148 ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS,
1149 frame, frames, &hashval);
1150 *next_hash = hashval;
1156 * Stop if: (a) there are no more entries, or
1157 * (b) we have inserted at least one entry and the
1158 * next hash value is not a continuation
1161 (count && ((hashval & 1) == 0)))
1165 dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, "
1166 "next hash: %x\n", count, *next_hash));
1173 static inline int search_dirblock(struct buffer_head *bh,
1175 struct ext4_filename *fname,
1176 unsigned int offset,
1177 struct ext4_dir_entry_2 **res_dir)
1179 return ext4_search_dir(bh, bh->b_data, dir->i_sb->s_blocksize, dir,
1180 fname, offset, res_dir);
1184 * Directory block splitting, compacting
1188 * Create map of hash values, offsets, and sizes, stored at end of block.
1189 * Returns number of entries mapped.
1191 static int dx_make_map(struct inode *dir, struct ext4_dir_entry_2 *de,
1192 unsigned blocksize, struct dx_hash_info *hinfo,
1193 struct dx_map_entry *map_tail)
1196 char *base = (char *) de;
1197 struct dx_hash_info h = *hinfo;
1199 while ((char *) de < base + blocksize) {
1200 if (de->name_len && de->inode) {
1201 ext4fs_dirhash(dir, de->name, de->name_len, &h);
1203 map_tail->hash = h.hash;
1204 map_tail->offs = ((char *) de - base)>>2;
1205 map_tail->size = le16_to_cpu(de->rec_len);
1209 /* XXX: do we need to check rec_len == 0 case? -Chris */
1210 de = ext4_next_entry(de, blocksize);
1215 /* Sort map by hash value */
1216 static void dx_sort_map (struct dx_map_entry *map, unsigned count)
1218 struct dx_map_entry *p, *q, *top = map + count - 1;
1220 /* Combsort until bubble sort doesn't suck */
1222 count = count*10/13;
1223 if (count - 9 < 2) /* 9, 10 -> 11 */
1225 for (p = top, q = p - count; q >= map; p--, q--)
1226 if (p->hash < q->hash)
1229 /* Garden variety bubble sort */
1234 if (q[1].hash >= q[0].hash)
1242 static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block)
1244 struct dx_entry *entries = frame->entries;
1245 struct dx_entry *old = frame->at, *new = old + 1;
1246 int count = dx_get_count(entries);
1248 assert(count < dx_get_limit(entries));
1249 assert(old < entries + count);
1250 memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
1251 dx_set_hash(new, hash);
1252 dx_set_block(new, block);
1253 dx_set_count(entries, count + 1);
1256 #ifdef CONFIG_UNICODE
1258 * Test whether a case-insensitive directory entry matches the filename
1259 * being searched for.
1261 * Returns: 0 if the directory entry matches, more than 0 if it
1262 * doesn't match or less than zero on error.
1264 int ext4_ci_compare(const struct inode *parent, const struct qstr *name,
1265 const struct qstr *entry)
1267 const struct ext4_sb_info *sbi = EXT4_SB(parent->i_sb);
1268 const struct unicode_map *um = sbi->s_encoding;
1271 ret = utf8_strncasecmp(um, name, entry);
1273 /* Handle invalid character sequence as either an error
1274 * or as an opaque byte sequence.
1276 if (ext4_has_strict_mode(sbi))
1279 if (name->len != entry->len)
1282 return !!memcmp(name->name, entry->name, name->len);
1290 * Test whether a directory entry matches the filename being searched for.
1292 * Return: %true if the directory entry matches, otherwise %false.
1294 static inline bool ext4_match(const struct inode *parent,
1295 const struct ext4_filename *fname,
1296 const struct ext4_dir_entry_2 *de)
1298 struct fscrypt_name f;
1299 #ifdef CONFIG_UNICODE
1300 const struct qstr entry = {.name = de->name, .len = de->name_len};
1306 f.usr_fname = fname->usr_fname;
1307 f.disk_name = fname->disk_name;
1308 #ifdef CONFIG_FS_ENCRYPTION
1309 f.crypto_buf = fname->crypto_buf;
1312 #ifdef CONFIG_UNICODE
1313 if (EXT4_SB(parent->i_sb)->s_encoding && IS_CASEFOLDED(parent))
1314 return (ext4_ci_compare(parent, fname->usr_fname, &entry) == 0);
1317 return fscrypt_match_name(&f, de->name, de->name_len);
1321 * Returns 0 if not found, -1 on failure, and 1 on success
1323 int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size,
1324 struct inode *dir, struct ext4_filename *fname,
1325 unsigned int offset, struct ext4_dir_entry_2 **res_dir)
1327 struct ext4_dir_entry_2 * de;
1331 de = (struct ext4_dir_entry_2 *)search_buf;
1332 dlimit = search_buf + buf_size;
1333 while ((char *) de < dlimit) {
1334 /* this code is executed quadratically often */
1335 /* do minimal checking `by hand' */
1336 if ((char *) de + de->name_len <= dlimit &&
1337 ext4_match(dir, fname, de)) {
1338 /* found a match - just to be sure, do
1340 if (ext4_check_dir_entry(dir, NULL, de, bh, bh->b_data,
1341 bh->b_size, offset))
1346 /* prevent looping on a bad block */
1347 de_len = ext4_rec_len_from_disk(de->rec_len,
1348 dir->i_sb->s_blocksize);
1352 de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
1357 static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block,
1358 struct ext4_dir_entry *de)
1360 struct super_block *sb = dir->i_sb;
1366 if (de->inode == 0 &&
1367 ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) ==
1376 * finds an entry in the specified directory with the wanted name. It
1377 * returns the cache buffer in which the entry was found, and the entry
1378 * itself (as a parameter - res_dir). It does NOT read the inode of the
1379 * entry - you'll have to do that yourself if you want to.
1381 * The returned buffer_head has ->b_count elevated. The caller is expected
1382 * to brelse() it when appropriate.
1384 static struct buffer_head * ext4_find_entry (struct inode *dir,
1385 const struct qstr *d_name,
1386 struct ext4_dir_entry_2 **res_dir,
1389 struct super_block *sb;
1390 struct buffer_head *bh_use[NAMEI_RA_SIZE];
1391 struct buffer_head *bh, *ret = NULL;
1392 ext4_lblk_t start, block;
1393 const u8 *name = d_name->name;
1394 size_t ra_max = 0; /* Number of bh's in the readahead
1396 size_t ra_ptr = 0; /* Current index into readahead
1398 ext4_lblk_t nblocks;
1399 int i, namelen, retval;
1400 struct ext4_filename fname;
1404 namelen = d_name->len;
1405 if (namelen > EXT4_NAME_LEN)
1408 retval = ext4_fname_setup_filename(dir, d_name, 1, &fname);
1409 if (retval == -ENOENT)
1412 return ERR_PTR(retval);
1414 if (ext4_has_inline_data(dir)) {
1415 int has_inline_data = 1;
1416 ret = ext4_find_inline_entry(dir, &fname, res_dir,
1418 if (has_inline_data) {
1421 goto cleanup_and_exit;
1425 if ((namelen <= 2) && (name[0] == '.') &&
1426 (name[1] == '.' || name[1] == '\0')) {
1428 * "." or ".." will only be in the first block
1429 * NFS may look up ".."; "." should be handled by the VFS
1436 ret = ext4_dx_find_entry(dir, &fname, res_dir);
1438 * On success, or if the error was file not found,
1439 * return. Otherwise, fall back to doing a search the
1440 * old fashioned way.
1442 if (!IS_ERR(ret) || PTR_ERR(ret) != ERR_BAD_DX_DIR)
1443 goto cleanup_and_exit;
1444 dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
1448 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1451 goto cleanup_and_exit;
1453 start = EXT4_I(dir)->i_dir_start_lookup;
1454 if (start >= nblocks)
1460 * We deal with the read-ahead logic here.
1462 if (ra_ptr >= ra_max) {
1463 /* Refill the readahead buffer */
1466 ra_max = start - block;
1468 ra_max = nblocks - block;
1469 ra_max = min(ra_max, ARRAY_SIZE(bh_use));
1470 retval = ext4_bread_batch(dir, block, ra_max,
1471 false /* wait */, bh_use);
1473 ret = ERR_PTR(retval);
1475 goto cleanup_and_exit;
1478 if ((bh = bh_use[ra_ptr++]) == NULL)
1481 if (!buffer_uptodate(bh)) {
1482 EXT4_ERROR_INODE(dir, "reading directory lblock %lu",
1483 (unsigned long) block);
1485 ret = ERR_PTR(-EIO);
1486 goto cleanup_and_exit;
1488 if (!buffer_verified(bh) &&
1489 !is_dx_internal_node(dir, block,
1490 (struct ext4_dir_entry *)bh->b_data) &&
1491 !ext4_dirent_csum_verify(dir,
1492 (struct ext4_dir_entry *)bh->b_data)) {
1493 EXT4_ERROR_INODE(dir, "checksumming directory "
1494 "block %lu", (unsigned long)block);
1496 ret = ERR_PTR(-EFSBADCRC);
1497 goto cleanup_and_exit;
1499 set_buffer_verified(bh);
1500 i = search_dirblock(bh, dir, &fname,
1501 block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
1503 EXT4_I(dir)->i_dir_start_lookup = block;
1505 goto cleanup_and_exit;
1509 goto cleanup_and_exit;
1512 if (++block >= nblocks)
1514 } while (block != start);
1517 * If the directory has grown while we were searching, then
1518 * search the last part of the directory before giving up.
1521 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1522 if (block < nblocks) {
1528 /* Clean up the read-ahead blocks */
1529 for (; ra_ptr < ra_max; ra_ptr++)
1530 brelse(bh_use[ra_ptr]);
1531 ext4_fname_free_filename(&fname);
1535 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
1536 struct ext4_filename *fname,
1537 struct ext4_dir_entry_2 **res_dir)
1539 struct super_block * sb = dir->i_sb;
1540 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1541 struct buffer_head *bh;
1545 #ifdef CONFIG_FS_ENCRYPTION
1548 frame = dx_probe(fname, dir, NULL, frames);
1550 return (struct buffer_head *) frame;
1552 block = dx_get_block(frame->at);
1553 bh = ext4_read_dirblock(dir, block, DIRENT);
1557 retval = search_dirblock(bh, dir, fname,
1558 block << EXT4_BLOCK_SIZE_BITS(sb),
1564 bh = ERR_PTR(ERR_BAD_DX_DIR);
1568 /* Check to see if we should continue to search */
1569 retval = ext4_htree_next_block(dir, fname->hinfo.hash, frame,
1572 ext4_warning_inode(dir,
1573 "error %d reading directory index block",
1575 bh = ERR_PTR(retval);
1578 } while (retval == 1);
1582 dxtrace(printk(KERN_DEBUG "%s not found\n", fname->usr_fname->name));
1588 static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
1590 struct inode *inode;
1591 struct ext4_dir_entry_2 *de;
1592 struct buffer_head *bh;
1595 err = fscrypt_prepare_lookup(dir, dentry, flags);
1597 return ERR_PTR(err);
1599 if (dentry->d_name.len > EXT4_NAME_LEN)
1600 return ERR_PTR(-ENAMETOOLONG);
1602 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
1604 return ERR_CAST(bh);
1607 __u32 ino = le32_to_cpu(de->inode);
1609 if (!ext4_valid_inum(dir->i_sb, ino)) {
1610 EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
1611 return ERR_PTR(-EFSCORRUPTED);
1613 if (unlikely(ino == dir->i_ino)) {
1614 EXT4_ERROR_INODE(dir, "'%pd' linked to parent dir",
1616 return ERR_PTR(-EFSCORRUPTED);
1618 inode = ext4_iget(dir->i_sb, ino, EXT4_IGET_NORMAL);
1619 if (inode == ERR_PTR(-ESTALE)) {
1620 EXT4_ERROR_INODE(dir,
1621 "deleted inode referenced: %u",
1623 return ERR_PTR(-EFSCORRUPTED);
1625 if (!IS_ERR(inode) && IS_ENCRYPTED(dir) &&
1626 (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
1627 !fscrypt_has_permitted_context(dir, inode)) {
1628 ext4_warning(inode->i_sb,
1629 "Inconsistent encryption contexts: %lu/%lu",
1630 dir->i_ino, inode->i_ino);
1632 return ERR_PTR(-EPERM);
1636 #ifdef CONFIG_UNICODE
1637 if (!inode && IS_CASEFOLDED(dir)) {
1638 /* Eventually we want to call d_add_ci(dentry, NULL)
1639 * for negative dentries in the encoding case as
1640 * well. For now, prevent the negative dentry
1641 * from being cached.
1646 return d_splice_alias(inode, dentry);
1650 struct dentry *ext4_get_parent(struct dentry *child)
1653 static const struct qstr dotdot = QSTR_INIT("..", 2);
1654 struct ext4_dir_entry_2 * de;
1655 struct buffer_head *bh;
1657 bh = ext4_find_entry(d_inode(child), &dotdot, &de, NULL);
1659 return ERR_CAST(bh);
1661 return ERR_PTR(-ENOENT);
1662 ino = le32_to_cpu(de->inode);
1665 if (!ext4_valid_inum(child->d_sb, ino)) {
1666 EXT4_ERROR_INODE(d_inode(child),
1667 "bad parent inode number: %u", ino);
1668 return ERR_PTR(-EFSCORRUPTED);
1671 return d_obtain_alias(ext4_iget(child->d_sb, ino, EXT4_IGET_NORMAL));
1675 * Move count entries from end of map between two memory locations.
1676 * Returns pointer to last entry moved.
1678 static struct ext4_dir_entry_2 *
1679 dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count,
1682 unsigned rec_len = 0;
1685 struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
1686 (from + (map->offs<<2));
1687 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1688 memcpy (to, de, rec_len);
1689 ((struct ext4_dir_entry_2 *) to)->rec_len =
1690 ext4_rec_len_to_disk(rec_len, blocksize);
1695 return (struct ext4_dir_entry_2 *) (to - rec_len);
1699 * Compact each dir entry in the range to the minimal rec_len.
1700 * Returns pointer to last entry in range.
1702 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize)
1704 struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
1705 unsigned rec_len = 0;
1708 while ((char*)de < base + blocksize) {
1709 next = ext4_next_entry(de, blocksize);
1710 if (de->inode && de->name_len) {
1711 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1713 memmove(to, de, rec_len);
1714 to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
1716 to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
1724 * Split a full leaf block to make room for a new dir entry.
1725 * Allocate a new block, and move entries so that they are approx. equally full.
1726 * Returns pointer to de in block into which the new entry will be inserted.
1728 static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
1729 struct buffer_head **bh,struct dx_frame *frame,
1730 struct dx_hash_info *hinfo)
1732 unsigned blocksize = dir->i_sb->s_blocksize;
1733 unsigned count, continued;
1734 struct buffer_head *bh2;
1735 ext4_lblk_t newblock;
1737 struct dx_map_entry *map;
1738 char *data1 = (*bh)->b_data, *data2;
1739 unsigned split, move, size;
1740 struct ext4_dir_entry_2 *de = NULL, *de2;
1741 struct ext4_dir_entry_tail *t;
1745 if (ext4_has_metadata_csum(dir->i_sb))
1746 csum_size = sizeof(struct ext4_dir_entry_tail);
1748 bh2 = ext4_append(handle, dir, &newblock);
1752 return (struct ext4_dir_entry_2 *) bh2;
1755 BUFFER_TRACE(*bh, "get_write_access");
1756 err = ext4_journal_get_write_access(handle, *bh);
1760 BUFFER_TRACE(frame->bh, "get_write_access");
1761 err = ext4_journal_get_write_access(handle, frame->bh);
1765 data2 = bh2->b_data;
1767 /* create map in the end of data2 block */
1768 map = (struct dx_map_entry *) (data2 + blocksize);
1769 count = dx_make_map(dir, (struct ext4_dir_entry_2 *) data1,
1770 blocksize, hinfo, map);
1772 dx_sort_map(map, count);
1773 /* Split the existing block in the middle, size-wise */
1776 for (i = count-1; i >= 0; i--) {
1777 /* is more than half of this entry in 2nd half of the block? */
1778 if (size + map[i].size/2 > blocksize/2)
1780 size += map[i].size;
1783 /* map index at which we will split */
1784 split = count - move;
1785 hash2 = map[split].hash;
1786 continued = hash2 == map[split - 1].hash;
1787 dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
1788 (unsigned long)dx_get_block(frame->at),
1789 hash2, split, count-split));
1791 /* Fancy dance to stay within two buffers */
1792 de2 = dx_move_dirents(data1, data2, map + split, count - split,
1794 de = dx_pack_dirents(data1, blocksize);
1795 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
1798 de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
1802 t = EXT4_DIRENT_TAIL(data2, blocksize);
1803 initialize_dirent_tail(t, blocksize);
1805 t = EXT4_DIRENT_TAIL(data1, blocksize);
1806 initialize_dirent_tail(t, blocksize);
1809 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,
1811 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,
1814 /* Which block gets the new entry? */
1815 if (hinfo->hash >= hash2) {
1819 dx_insert_block(frame, hash2 + continued, newblock);
1820 err = ext4_handle_dirty_dirent_node(handle, dir, bh2);
1823 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
1827 dxtrace(dx_show_index("frame", frame->entries));
1834 ext4_std_error(dir->i_sb, err);
1835 return ERR_PTR(err);
1838 int ext4_find_dest_de(struct inode *dir, struct inode *inode,
1839 struct buffer_head *bh,
1840 void *buf, int buf_size,
1841 struct ext4_filename *fname,
1842 struct ext4_dir_entry_2 **dest_de)
1844 struct ext4_dir_entry_2 *de;
1845 unsigned short reclen = EXT4_DIR_REC_LEN(fname_len(fname));
1847 unsigned int offset = 0;
1850 de = (struct ext4_dir_entry_2 *)buf;
1851 top = buf + buf_size - reclen;
1852 while ((char *) de <= top) {
1853 if (ext4_check_dir_entry(dir, NULL, de, bh,
1854 buf, buf_size, offset))
1855 return -EFSCORRUPTED;
1856 if (ext4_match(dir, fname, de))
1858 nlen = EXT4_DIR_REC_LEN(de->name_len);
1859 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1860 if ((de->inode ? rlen - nlen : rlen) >= reclen)
1862 de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
1865 if ((char *) de > top)
1872 void ext4_insert_dentry(struct inode *inode,
1873 struct ext4_dir_entry_2 *de,
1875 struct ext4_filename *fname)
1880 nlen = EXT4_DIR_REC_LEN(de->name_len);
1881 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1883 struct ext4_dir_entry_2 *de1 =
1884 (struct ext4_dir_entry_2 *)((char *)de + nlen);
1885 de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size);
1886 de->rec_len = ext4_rec_len_to_disk(nlen, buf_size);
1889 de->file_type = EXT4_FT_UNKNOWN;
1890 de->inode = cpu_to_le32(inode->i_ino);
1891 ext4_set_de_type(inode->i_sb, de, inode->i_mode);
1892 de->name_len = fname_len(fname);
1893 memcpy(de->name, fname_name(fname), fname_len(fname));
1897 * Add a new entry into a directory (leaf) block. If de is non-NULL,
1898 * it points to a directory entry which is guaranteed to be large
1899 * enough for new directory entry. If de is NULL, then
1900 * add_dirent_to_buf will attempt search the directory block for
1901 * space. It will return -ENOSPC if no space is available, and -EIO
1902 * and -EEXIST if directory entry already exists.
1904 static int add_dirent_to_buf(handle_t *handle, struct ext4_filename *fname,
1906 struct inode *inode, struct ext4_dir_entry_2 *de,
1907 struct buffer_head *bh)
1909 unsigned int blocksize = dir->i_sb->s_blocksize;
1913 if (ext4_has_metadata_csum(inode->i_sb))
1914 csum_size = sizeof(struct ext4_dir_entry_tail);
1917 err = ext4_find_dest_de(dir, inode, bh, bh->b_data,
1918 blocksize - csum_size, fname, &de);
1922 BUFFER_TRACE(bh, "get_write_access");
1923 err = ext4_journal_get_write_access(handle, bh);
1925 ext4_std_error(dir->i_sb, err);
1929 /* By now the buffer is marked for journaling */
1930 ext4_insert_dentry(inode, de, blocksize, fname);
1933 * XXX shouldn't update any times until successful
1934 * completion of syscall, but too many callers depend
1937 * XXX similarly, too many callers depend on
1938 * ext4_new_inode() setting the times, but error
1939 * recovery deletes the inode, so the worst that can
1940 * happen is that the times are slightly out of date
1941 * and/or different from the directory change time.
1943 dir->i_mtime = dir->i_ctime = current_time(dir);
1944 ext4_update_dx_flag(dir);
1945 inode_inc_iversion(dir);
1946 ext4_mark_inode_dirty(handle, dir);
1947 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1948 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
1950 ext4_std_error(dir->i_sb, err);
1955 * This converts a one block unindexed directory to a 3 block indexed
1956 * directory, and adds the dentry to the indexed directory.
1958 static int make_indexed_dir(handle_t *handle, struct ext4_filename *fname,
1960 struct inode *inode, struct buffer_head *bh)
1962 struct buffer_head *bh2;
1963 struct dx_root *root;
1964 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1965 struct dx_entry *entries;
1966 struct ext4_dir_entry_2 *de, *de2;
1967 struct ext4_dir_entry_tail *t;
1973 struct fake_dirent *fde;
1976 if (ext4_has_metadata_csum(inode->i_sb))
1977 csum_size = sizeof(struct ext4_dir_entry_tail);
1979 blocksize = dir->i_sb->s_blocksize;
1980 dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
1981 BUFFER_TRACE(bh, "get_write_access");
1982 retval = ext4_journal_get_write_access(handle, bh);
1984 ext4_std_error(dir->i_sb, retval);
1988 root = (struct dx_root *) bh->b_data;
1990 /* The 0th block becomes the root, move the dirents out */
1991 fde = &root->dotdot;
1992 de = (struct ext4_dir_entry_2 *)((char *)fde +
1993 ext4_rec_len_from_disk(fde->rec_len, blocksize));
1994 if ((char *) de >= (((char *) root) + blocksize)) {
1995 EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
1997 return -EFSCORRUPTED;
1999 len = ((char *) root) + (blocksize - csum_size) - (char *) de;
2001 /* Allocate new block for the 0th block's dirents */
2002 bh2 = ext4_append(handle, dir, &block);
2005 return PTR_ERR(bh2);
2007 ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
2008 data1 = bh2->b_data;
2010 memcpy (data1, de, len);
2011 de = (struct ext4_dir_entry_2 *) data1;
2013 while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top)
2015 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
2020 t = EXT4_DIRENT_TAIL(data1, blocksize);
2021 initialize_dirent_tail(t, blocksize);
2024 /* Initialize the root; the dot dirents already exist */
2025 de = (struct ext4_dir_entry_2 *) (&root->dotdot);
2026 de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
2028 memset (&root->info, 0, sizeof(root->info));
2029 root->info.info_length = sizeof(root->info);
2030 root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
2031 entries = root->entries;
2032 dx_set_block(entries, 1);
2033 dx_set_count(entries, 1);
2034 dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
2036 /* Initialize as for dx_probe */
2037 fname->hinfo.hash_version = root->info.hash_version;
2038 if (fname->hinfo.hash_version <= DX_HASH_TEA)
2039 fname->hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
2040 fname->hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
2041 ext4fs_dirhash(dir, fname_name(fname), fname_len(fname), &fname->hinfo);
2043 memset(frames, 0, sizeof(frames));
2045 frame->entries = entries;
2046 frame->at = entries;
2049 retval = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2052 retval = ext4_handle_dirty_dirent_node(handle, dir, bh2);
2056 de = do_split(handle,dir, &bh2, frame, &fname->hinfo);
2058 retval = PTR_ERR(de);
2062 retval = add_dirent_to_buf(handle, fname, dir, inode, de, bh2);
2065 * Even if the block split failed, we have to properly write
2066 * out all the changes we did so far. Otherwise we can end up
2067 * with corrupted filesystem.
2070 ext4_mark_inode_dirty(handle, dir);
2079 * adds a file entry to the specified directory, using the same
2080 * semantics as ext4_find_entry(). It returns NULL if it failed.
2082 * NOTE!! The inode part of 'de' is left at 0 - which means you
2083 * may not sleep between calling this and putting something into
2084 * the entry, as someone else might have used it while you slept.
2086 static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
2087 struct inode *inode)
2089 struct inode *dir = d_inode(dentry->d_parent);
2090 struct buffer_head *bh = NULL;
2091 struct ext4_dir_entry_2 *de;
2092 struct ext4_dir_entry_tail *t;
2093 struct super_block *sb;
2094 struct ext4_sb_info *sbi;
2095 struct ext4_filename fname;
2099 ext4_lblk_t block, blocks;
2102 if (ext4_has_metadata_csum(inode->i_sb))
2103 csum_size = sizeof(struct ext4_dir_entry_tail);
2107 blocksize = sb->s_blocksize;
2108 if (!dentry->d_name.len)
2111 #ifdef CONFIG_UNICODE
2112 if (ext4_has_strict_mode(sbi) && IS_CASEFOLDED(dir) &&
2113 utf8_validate(sbi->s_encoding, &dentry->d_name))
2117 retval = ext4_fname_setup_filename(dir, &dentry->d_name, 0, &fname);
2121 if (ext4_has_inline_data(dir)) {
2122 retval = ext4_try_add_inline_entry(handle, &fname, dir, inode);
2132 retval = ext4_dx_add_entry(handle, &fname, dir, inode);
2133 if (!retval || (retval != ERR_BAD_DX_DIR))
2135 ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
2137 ext4_mark_inode_dirty(handle, dir);
2139 blocks = dir->i_size >> sb->s_blocksize_bits;
2140 for (block = 0; block < blocks; block++) {
2141 bh = ext4_read_dirblock(dir, block, DIRENT);
2143 retval = PTR_ERR(bh);
2147 retval = add_dirent_to_buf(handle, &fname, dir, inode,
2149 if (retval != -ENOSPC)
2152 if (blocks == 1 && !dx_fallback &&
2153 ext4_has_feature_dir_index(sb)) {
2154 retval = make_indexed_dir(handle, &fname, dir,
2156 bh = NULL; /* make_indexed_dir releases bh */
2161 bh = ext4_append(handle, dir, &block);
2163 retval = PTR_ERR(bh);
2167 de = (struct ext4_dir_entry_2 *) bh->b_data;
2169 de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
2172 t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
2173 initialize_dirent_tail(t, blocksize);
2176 retval = add_dirent_to_buf(handle, &fname, dir, inode, de, bh);
2178 ext4_fname_free_filename(&fname);
2181 ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
2186 * Returns 0 for success, or a negative error value
2188 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
2189 struct inode *dir, struct inode *inode)
2191 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
2192 struct dx_entry *entries, *at;
2193 struct buffer_head *bh;
2194 struct super_block *sb = dir->i_sb;
2195 struct ext4_dir_entry_2 *de;
2201 frame = dx_probe(fname, dir, NULL, frames);
2203 return PTR_ERR(frame);
2204 entries = frame->entries;
2206 bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT);
2213 BUFFER_TRACE(bh, "get_write_access");
2214 err = ext4_journal_get_write_access(handle, bh);
2218 err = add_dirent_to_buf(handle, fname, dir, inode, NULL, bh);
2223 /* Block full, should compress but for now just split */
2224 dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
2225 dx_get_count(entries), dx_get_limit(entries)));
2226 /* Need to split index? */
2227 if (dx_get_count(entries) == dx_get_limit(entries)) {
2228 ext4_lblk_t newblock;
2229 int levels = frame - frames + 1;
2230 unsigned int icount;
2232 struct dx_entry *entries2;
2233 struct dx_node *node2;
2234 struct buffer_head *bh2;
2236 while (frame > frames) {
2237 if (dx_get_count((frame - 1)->entries) <
2238 dx_get_limit((frame - 1)->entries)) {
2242 frame--; /* split higher index block */
2244 entries = frame->entries;
2247 if (add_level && levels == ext4_dir_htree_level(sb)) {
2248 ext4_warning(sb, "Directory (ino: %lu) index full, "
2249 "reach max htree level :%d",
2250 dir->i_ino, levels);
2251 if (ext4_dir_htree_level(sb) < EXT4_HTREE_LEVEL) {
2252 ext4_warning(sb, "Large directory feature is "
2253 "not enabled on this "
2259 icount = dx_get_count(entries);
2260 bh2 = ext4_append(handle, dir, &newblock);
2265 node2 = (struct dx_node *)(bh2->b_data);
2266 entries2 = node2->entries;
2267 memset(&node2->fake, 0, sizeof(struct fake_dirent));
2268 node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
2270 BUFFER_TRACE(frame->bh, "get_write_access");
2271 err = ext4_journal_get_write_access(handle, frame->bh);
2275 unsigned icount1 = icount/2, icount2 = icount - icount1;
2276 unsigned hash2 = dx_get_hash(entries + icount1);
2277 dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
2280 BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
2281 err = ext4_journal_get_write_access(handle,
2286 memcpy((char *) entries2, (char *) (entries + icount1),
2287 icount2 * sizeof(struct dx_entry));
2288 dx_set_count(entries, icount1);
2289 dx_set_count(entries2, icount2);
2290 dx_set_limit(entries2, dx_node_limit(dir));
2292 /* Which index block gets the new entry? */
2293 if (at - entries >= icount1) {
2294 frame->at = at = at - entries - icount1 + entries2;
2295 frame->entries = entries = entries2;
2296 swap(frame->bh, bh2);
2298 dx_insert_block((frame - 1), hash2, newblock);
2299 dxtrace(dx_show_index("node", frame->entries));
2300 dxtrace(dx_show_index("node",
2301 ((struct dx_node *) bh2->b_data)->entries));
2302 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2306 err = ext4_handle_dirty_dx_node(handle, dir,
2311 err = ext4_handle_dirty_dx_node(handle, dir,
2316 struct dx_root *dxroot;
2317 memcpy((char *) entries2, (char *) entries,
2318 icount * sizeof(struct dx_entry));
2319 dx_set_limit(entries2, dx_node_limit(dir));
2322 dx_set_count(entries, 1);
2323 dx_set_block(entries + 0, newblock);
2324 dxroot = (struct dx_root *)frames[0].bh->b_data;
2325 dxroot->info.indirect_levels += 1;
2326 dxtrace(printk(KERN_DEBUG
2327 "Creating %d level index...\n",
2328 dxroot->info.indirect_levels));
2329 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2332 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2338 de = do_split(handle, dir, &bh, frame, &fname->hinfo);
2343 err = add_dirent_to_buf(handle, fname, dir, inode, de, bh);
2347 ext4_std_error(dir->i_sb, err); /* this is a no-op if err == 0 */
2351 /* @restart is true means htree-path has been changed, we need to
2352 * repeat dx_probe() to find out valid htree-path
2354 if (restart && err == 0)
2360 * ext4_generic_delete_entry deletes a directory entry by merging it
2361 * with the previous entry
2363 int ext4_generic_delete_entry(handle_t *handle,
2365 struct ext4_dir_entry_2 *de_del,
2366 struct buffer_head *bh,
2371 struct ext4_dir_entry_2 *de, *pde;
2372 unsigned int blocksize = dir->i_sb->s_blocksize;
2377 de = (struct ext4_dir_entry_2 *)entry_buf;
2378 while (i < buf_size - csum_size) {
2379 if (ext4_check_dir_entry(dir, NULL, de, bh,
2380 bh->b_data, bh->b_size, i))
2381 return -EFSCORRUPTED;
2384 pde->rec_len = ext4_rec_len_to_disk(
2385 ext4_rec_len_from_disk(pde->rec_len,
2387 ext4_rec_len_from_disk(de->rec_len,
2392 inode_inc_iversion(dir);
2395 i += ext4_rec_len_from_disk(de->rec_len, blocksize);
2397 de = ext4_next_entry(de, blocksize);
2402 static int ext4_delete_entry(handle_t *handle,
2404 struct ext4_dir_entry_2 *de_del,
2405 struct buffer_head *bh)
2407 int err, csum_size = 0;
2409 if (ext4_has_inline_data(dir)) {
2410 int has_inline_data = 1;
2411 err = ext4_delete_inline_entry(handle, dir, de_del, bh,
2413 if (has_inline_data)
2417 if (ext4_has_metadata_csum(dir->i_sb))
2418 csum_size = sizeof(struct ext4_dir_entry_tail);
2420 BUFFER_TRACE(bh, "get_write_access");
2421 err = ext4_journal_get_write_access(handle, bh);
2425 err = ext4_generic_delete_entry(handle, dir, de_del,
2427 dir->i_sb->s_blocksize, csum_size);
2431 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
2432 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
2439 ext4_std_error(dir->i_sb, err);
2444 * Set directory link count to 1 if nlinks > EXT4_LINK_MAX, or if nlinks == 2
2445 * since this indicates that nlinks count was previously 1 to avoid overflowing
2446 * the 16-bit i_links_count field on disk. Directories with i_nlink == 1 mean
2447 * that subdirectory link counts are not being maintained accurately.
2449 * The caller has already checked for i_nlink overflow in case the DIR_LINK
2450 * feature is not enabled and returned -EMLINK. The is_dx() check is a proxy
2451 * for checking S_ISDIR(inode) (since the INODE_INDEX feature will not be set
2452 * on regular files) and to avoid creating huge/slow non-HTREE directories.
2454 static void ext4_inc_count(handle_t *handle, struct inode *inode)
2458 (inode->i_nlink > EXT4_LINK_MAX || inode->i_nlink == 2))
2459 set_nlink(inode, 1);
2463 * If a directory had nlink == 1, then we should let it be 1. This indicates
2464 * directory has >EXT4_LINK_MAX subdirs.
2466 static void ext4_dec_count(handle_t *handle, struct inode *inode)
2468 if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
2473 static int ext4_add_nondir(handle_t *handle,
2474 struct dentry *dentry, struct inode *inode)
2476 int err = ext4_add_entry(handle, dentry, inode);
2478 ext4_mark_inode_dirty(handle, inode);
2479 d_instantiate_new(dentry, inode);
2483 unlock_new_inode(inode);
2489 * By the time this is called, we already have created
2490 * the directory cache entry for the new file, but it
2491 * is so far negative - it has no inode.
2493 * If the create succeeds, we fill in the inode information
2494 * with d_instantiate().
2496 static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2500 struct inode *inode;
2501 int err, credits, retries = 0;
2503 err = dquot_initialize(dir);
2507 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2508 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2510 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2511 NULL, EXT4_HT_DIR, credits);
2512 handle = ext4_journal_current_handle();
2513 err = PTR_ERR(inode);
2514 if (!IS_ERR(inode)) {
2515 inode->i_op = &ext4_file_inode_operations;
2516 inode->i_fop = &ext4_file_operations;
2517 ext4_set_aops(inode);
2518 err = ext4_add_nondir(handle, dentry, inode);
2519 if (!err && IS_DIRSYNC(dir))
2520 ext4_handle_sync(handle);
2523 ext4_journal_stop(handle);
2524 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2529 static int ext4_mknod(struct inode *dir, struct dentry *dentry,
2530 umode_t mode, dev_t rdev)
2533 struct inode *inode;
2534 int err, credits, retries = 0;
2536 err = dquot_initialize(dir);
2540 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2541 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2543 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2544 NULL, EXT4_HT_DIR, credits);
2545 handle = ext4_journal_current_handle();
2546 err = PTR_ERR(inode);
2547 if (!IS_ERR(inode)) {
2548 init_special_inode(inode, inode->i_mode, rdev);
2549 inode->i_op = &ext4_special_inode_operations;
2550 err = ext4_add_nondir(handle, dentry, inode);
2551 if (!err && IS_DIRSYNC(dir))
2552 ext4_handle_sync(handle);
2555 ext4_journal_stop(handle);
2556 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2561 static int ext4_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2564 struct inode *inode;
2565 int err, retries = 0;
2567 err = dquot_initialize(dir);
2572 inode = ext4_new_inode_start_handle(dir, mode,
2575 EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
2576 4 + EXT4_XATTR_TRANS_BLOCKS);
2577 handle = ext4_journal_current_handle();
2578 err = PTR_ERR(inode);
2579 if (!IS_ERR(inode)) {
2580 inode->i_op = &ext4_file_inode_operations;
2581 inode->i_fop = &ext4_file_operations;
2582 ext4_set_aops(inode);
2583 d_tmpfile(dentry, inode);
2584 err = ext4_orphan_add(handle, inode);
2586 goto err_unlock_inode;
2587 mark_inode_dirty(inode);
2588 unlock_new_inode(inode);
2591 ext4_journal_stop(handle);
2592 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2596 ext4_journal_stop(handle);
2597 unlock_new_inode(inode);
2601 struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode,
2602 struct ext4_dir_entry_2 *de,
2603 int blocksize, int csum_size,
2604 unsigned int parent_ino, int dotdot_real_len)
2606 de->inode = cpu_to_le32(inode->i_ino);
2608 de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
2610 strcpy(de->name, ".");
2611 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2613 de = ext4_next_entry(de, blocksize);
2614 de->inode = cpu_to_le32(parent_ino);
2616 if (!dotdot_real_len)
2617 de->rec_len = ext4_rec_len_to_disk(blocksize -
2618 (csum_size + EXT4_DIR_REC_LEN(1)),
2621 de->rec_len = ext4_rec_len_to_disk(
2622 EXT4_DIR_REC_LEN(de->name_len), blocksize);
2623 strcpy(de->name, "..");
2624 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2626 return ext4_next_entry(de, blocksize);
2629 static int ext4_init_new_dir(handle_t *handle, struct inode *dir,
2630 struct inode *inode)
2632 struct buffer_head *dir_block = NULL;
2633 struct ext4_dir_entry_2 *de;
2634 struct ext4_dir_entry_tail *t;
2635 ext4_lblk_t block = 0;
2636 unsigned int blocksize = dir->i_sb->s_blocksize;
2640 if (ext4_has_metadata_csum(dir->i_sb))
2641 csum_size = sizeof(struct ext4_dir_entry_tail);
2643 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2644 err = ext4_try_create_inline_dir(handle, dir, inode);
2645 if (err < 0 && err != -ENOSPC)
2652 dir_block = ext4_append(handle, inode, &block);
2653 if (IS_ERR(dir_block))
2654 return PTR_ERR(dir_block);
2655 de = (struct ext4_dir_entry_2 *)dir_block->b_data;
2656 ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0);
2657 set_nlink(inode, 2);
2659 t = EXT4_DIRENT_TAIL(dir_block->b_data, blocksize);
2660 initialize_dirent_tail(t, blocksize);
2663 BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
2664 err = ext4_handle_dirty_dirent_node(handle, inode, dir_block);
2667 set_buffer_verified(dir_block);
2673 static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2676 struct inode *inode;
2677 int err, credits, retries = 0;
2679 if (EXT4_DIR_LINK_MAX(dir))
2682 err = dquot_initialize(dir);
2686 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2687 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2689 inode = ext4_new_inode_start_handle(dir, S_IFDIR | mode,
2691 0, NULL, EXT4_HT_DIR, credits);
2692 handle = ext4_journal_current_handle();
2693 err = PTR_ERR(inode);
2697 inode->i_op = &ext4_dir_inode_operations;
2698 inode->i_fop = &ext4_dir_operations;
2699 err = ext4_init_new_dir(handle, dir, inode);
2701 goto out_clear_inode;
2702 err = ext4_mark_inode_dirty(handle, inode);
2704 err = ext4_add_entry(handle, dentry, inode);
2708 unlock_new_inode(inode);
2709 ext4_mark_inode_dirty(handle, inode);
2713 ext4_inc_count(handle, dir);
2714 ext4_update_dx_flag(dir);
2715 err = ext4_mark_inode_dirty(handle, dir);
2717 goto out_clear_inode;
2718 d_instantiate_new(dentry, inode);
2719 if (IS_DIRSYNC(dir))
2720 ext4_handle_sync(handle);
2724 ext4_journal_stop(handle);
2725 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2731 * routine to check that the specified directory is empty (for rmdir)
2733 bool ext4_empty_dir(struct inode *inode)
2735 unsigned int offset;
2736 struct buffer_head *bh;
2737 struct ext4_dir_entry_2 *de, *de1;
2738 struct super_block *sb;
2740 if (ext4_has_inline_data(inode)) {
2741 int has_inline_data = 1;
2744 ret = empty_inline_dir(inode, &has_inline_data);
2745 if (has_inline_data)
2750 if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2)) {
2751 EXT4_ERROR_INODE(inode, "invalid size");
2754 bh = ext4_read_dirblock(inode, 0, EITHER);
2758 de = (struct ext4_dir_entry_2 *) bh->b_data;
2759 de1 = ext4_next_entry(de, sb->s_blocksize);
2760 if (le32_to_cpu(de->inode) != inode->i_ino ||
2761 le32_to_cpu(de1->inode) == 0 ||
2762 strcmp(".", de->name) || strcmp("..", de1->name)) {
2763 ext4_warning_inode(inode, "directory missing '.' and/or '..'");
2767 offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) +
2768 ext4_rec_len_from_disk(de1->rec_len, sb->s_blocksize);
2769 de = ext4_next_entry(de1, sb->s_blocksize);
2770 while (offset < inode->i_size) {
2771 if ((void *) de >= (void *) (bh->b_data+sb->s_blocksize)) {
2772 unsigned int lblock;
2774 lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
2775 bh = ext4_read_dirblock(inode, lblock, EITHER);
2778 de = (struct ext4_dir_entry_2 *) bh->b_data;
2780 if (ext4_check_dir_entry(inode, NULL, de, bh,
2781 bh->b_data, bh->b_size, offset)) {
2782 de = (struct ext4_dir_entry_2 *)(bh->b_data +
2784 offset = (offset | (sb->s_blocksize - 1)) + 1;
2787 if (le32_to_cpu(de->inode)) {
2791 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2792 de = ext4_next_entry(de, sb->s_blocksize);
2799 * ext4_orphan_add() links an unlinked or truncated inode into a list of
2800 * such inodes, starting at the superblock, in case we crash before the
2801 * file is closed/deleted, or in case the inode truncate spans multiple
2802 * transactions and the last transaction is not recovered after a crash.
2804 * At filesystem recovery time, we walk this list deleting unlinked
2805 * inodes and truncating linked inodes in ext4_orphan_cleanup().
2807 * Orphan list manipulation functions must be called under i_mutex unless
2808 * we are just creating the inode or deleting it.
2810 int ext4_orphan_add(handle_t *handle, struct inode *inode)
2812 struct super_block *sb = inode->i_sb;
2813 struct ext4_sb_info *sbi = EXT4_SB(sb);
2814 struct ext4_iloc iloc;
2818 if (!sbi->s_journal || is_bad_inode(inode))
2821 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2822 !inode_is_locked(inode));
2824 * Exit early if inode already is on orphan list. This is a big speedup
2825 * since we don't have to contend on the global s_orphan_lock.
2827 if (!list_empty(&EXT4_I(inode)->i_orphan))
2831 * Orphan handling is only valid for files with data blocks
2832 * being truncated, or files being unlinked. Note that we either
2833 * hold i_mutex, or the inode can not be referenced from outside,
2834 * so i_nlink should not be bumped due to race
2836 J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
2837 S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
2839 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2840 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2844 err = ext4_reserve_inode_write(handle, inode, &iloc);
2848 mutex_lock(&sbi->s_orphan_lock);
2850 * Due to previous errors inode may be already a part of on-disk
2851 * orphan list. If so skip on-disk list modification.
2853 if (!NEXT_ORPHAN(inode) || NEXT_ORPHAN(inode) >
2854 (le32_to_cpu(sbi->s_es->s_inodes_count))) {
2855 /* Insert this inode at the head of the on-disk orphan list */
2856 NEXT_ORPHAN(inode) = le32_to_cpu(sbi->s_es->s_last_orphan);
2857 sbi->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
2860 list_add(&EXT4_I(inode)->i_orphan, &sbi->s_orphan);
2861 mutex_unlock(&sbi->s_orphan_lock);
2864 err = ext4_handle_dirty_super(handle, sb);
2865 rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
2870 * We have to remove inode from in-memory list if
2871 * addition to on disk orphan list failed. Stray orphan
2872 * list entries can cause panics at unmount time.
2874 mutex_lock(&sbi->s_orphan_lock);
2875 list_del_init(&EXT4_I(inode)->i_orphan);
2876 mutex_unlock(&sbi->s_orphan_lock);
2881 jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
2882 jbd_debug(4, "orphan inode %lu will point to %d\n",
2883 inode->i_ino, NEXT_ORPHAN(inode));
2885 ext4_std_error(sb, err);
2890 * ext4_orphan_del() removes an unlinked or truncated inode from the list
2891 * of such inodes stored on disk, because it is finally being cleaned up.
2893 int ext4_orphan_del(handle_t *handle, struct inode *inode)
2895 struct list_head *prev;
2896 struct ext4_inode_info *ei = EXT4_I(inode);
2897 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2899 struct ext4_iloc iloc;
2902 if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS))
2905 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2906 !inode_is_locked(inode));
2907 /* Do this quick check before taking global s_orphan_lock. */
2908 if (list_empty(&ei->i_orphan))
2912 /* Grab inode buffer early before taking global s_orphan_lock */
2913 err = ext4_reserve_inode_write(handle, inode, &iloc);
2916 mutex_lock(&sbi->s_orphan_lock);
2917 jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
2919 prev = ei->i_orphan.prev;
2920 list_del_init(&ei->i_orphan);
2922 /* If we're on an error path, we may not have a valid
2923 * transaction handle with which to update the orphan list on
2924 * disk, but we still need to remove the inode from the linked
2925 * list in memory. */
2926 if (!handle || err) {
2927 mutex_unlock(&sbi->s_orphan_lock);
2931 ino_next = NEXT_ORPHAN(inode);
2932 if (prev == &sbi->s_orphan) {
2933 jbd_debug(4, "superblock will point to %u\n", ino_next);
2934 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2935 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2937 mutex_unlock(&sbi->s_orphan_lock);
2940 sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
2941 mutex_unlock(&sbi->s_orphan_lock);
2942 err = ext4_handle_dirty_super(handle, inode->i_sb);
2944 struct ext4_iloc iloc2;
2945 struct inode *i_prev =
2946 &list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
2948 jbd_debug(4, "orphan inode %lu will point to %u\n",
2949 i_prev->i_ino, ino_next);
2950 err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
2952 mutex_unlock(&sbi->s_orphan_lock);
2955 NEXT_ORPHAN(i_prev) = ino_next;
2956 err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
2957 mutex_unlock(&sbi->s_orphan_lock);
2961 NEXT_ORPHAN(inode) = 0;
2962 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
2964 ext4_std_error(inode->i_sb, err);
2972 static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
2975 struct inode *inode;
2976 struct buffer_head *bh;
2977 struct ext4_dir_entry_2 *de;
2978 handle_t *handle = NULL;
2980 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
2983 /* Initialize quotas before so that eventual writes go in
2984 * separate transaction */
2985 retval = dquot_initialize(dir);
2988 retval = dquot_initialize(d_inode(dentry));
2993 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
2999 inode = d_inode(dentry);
3001 retval = -EFSCORRUPTED;
3002 if (le32_to_cpu(de->inode) != inode->i_ino)
3005 retval = -ENOTEMPTY;
3006 if (!ext4_empty_dir(inode))
3009 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3010 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3011 if (IS_ERR(handle)) {
3012 retval = PTR_ERR(handle);
3017 if (IS_DIRSYNC(dir))
3018 ext4_handle_sync(handle);
3020 retval = ext4_delete_entry(handle, dir, de, bh);
3023 if (!EXT4_DIR_LINK_EMPTY(inode))
3024 ext4_warning_inode(inode,
3025 "empty directory '%.*s' has too many links (%u)",
3026 dentry->d_name.len, dentry->d_name.name,
3028 inode_inc_iversion(inode);
3030 /* There's no need to set i_disksize: the fact that i_nlink is
3031 * zero will ensure that the right thing happens during any
3034 ext4_orphan_add(handle, inode);
3035 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
3036 ext4_mark_inode_dirty(handle, inode);
3037 ext4_dec_count(handle, dir);
3038 ext4_update_dx_flag(dir);
3039 ext4_mark_inode_dirty(handle, dir);
3041 #ifdef CONFIG_UNICODE
3042 /* VFS negative dentries are incompatible with Encoding and
3043 * Case-insensitiveness. Eventually we'll want avoid
3044 * invalidating the dentries here, alongside with returning the
3045 * negative dentries at ext4_lookup(), when it is better
3046 * supported by the VFS for the CI case.
3048 if (IS_CASEFOLDED(dir))
3049 d_invalidate(dentry);
3055 ext4_journal_stop(handle);
3059 static int ext4_unlink(struct inode *dir, struct dentry *dentry)
3062 struct inode *inode;
3063 struct buffer_head *bh;
3064 struct ext4_dir_entry_2 *de;
3065 handle_t *handle = NULL;
3067 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3070 trace_ext4_unlink_enter(dir, dentry);
3071 /* Initialize quotas before so that eventual writes go
3072 * in separate transaction */
3073 retval = dquot_initialize(dir);
3076 retval = dquot_initialize(d_inode(dentry));
3081 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3087 inode = d_inode(dentry);
3089 retval = -EFSCORRUPTED;
3090 if (le32_to_cpu(de->inode) != inode->i_ino)
3093 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3094 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3095 if (IS_ERR(handle)) {
3096 retval = PTR_ERR(handle);
3101 if (IS_DIRSYNC(dir))
3102 ext4_handle_sync(handle);
3104 if (inode->i_nlink == 0) {
3105 ext4_warning_inode(inode, "Deleting file '%.*s' with no links",
3106 dentry->d_name.len, dentry->d_name.name);
3107 set_nlink(inode, 1);
3109 retval = ext4_delete_entry(handle, dir, de, bh);
3112 dir->i_ctime = dir->i_mtime = current_time(dir);
3113 ext4_update_dx_flag(dir);
3114 ext4_mark_inode_dirty(handle, dir);
3116 if (!inode->i_nlink)
3117 ext4_orphan_add(handle, inode);
3118 inode->i_ctime = current_time(inode);
3119 ext4_mark_inode_dirty(handle, inode);
3121 #ifdef CONFIG_UNICODE
3122 /* VFS negative dentries are incompatible with Encoding and
3123 * Case-insensitiveness. Eventually we'll want avoid
3124 * invalidating the dentries here, alongside with returning the
3125 * negative dentries at ext4_lookup(), when it is better
3126 * supported by the VFS for the CI case.
3128 if (IS_CASEFOLDED(dir))
3129 d_invalidate(dentry);
3135 ext4_journal_stop(handle);
3136 trace_ext4_unlink_exit(dentry, retval);
3140 static int ext4_symlink(struct inode *dir,
3141 struct dentry *dentry, const char *symname)
3144 struct inode *inode;
3145 int err, len = strlen(symname);
3147 struct fscrypt_str disk_link;
3149 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3152 err = fscrypt_prepare_symlink(dir, symname, len, dir->i_sb->s_blocksize,
3157 err = dquot_initialize(dir);
3161 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3163 * For non-fast symlinks, we just allocate inode and put it on
3164 * orphan list in the first transaction => we need bitmap,
3165 * group descriptor, sb, inode block, quota blocks, and
3166 * possibly selinux xattr blocks.
3168 credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
3169 EXT4_XATTR_TRANS_BLOCKS;
3172 * Fast symlink. We have to add entry to directory
3173 * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
3174 * allocate new inode (bitmap, group descriptor, inode block,
3175 * quota blocks, sb is already counted in previous macros).
3177 credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3178 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3;
3181 inode = ext4_new_inode_start_handle(dir, S_IFLNK|S_IRWXUGO,
3182 &dentry->d_name, 0, NULL,
3183 EXT4_HT_DIR, credits);
3184 handle = ext4_journal_current_handle();
3185 if (IS_ERR(inode)) {
3187 ext4_journal_stop(handle);
3188 return PTR_ERR(inode);
3191 if (IS_ENCRYPTED(inode)) {
3192 err = fscrypt_encrypt_symlink(inode, symname, len, &disk_link);
3194 goto err_drop_inode;
3195 inode->i_op = &ext4_encrypted_symlink_inode_operations;
3198 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3199 if (!IS_ENCRYPTED(inode))
3200 inode->i_op = &ext4_symlink_inode_operations;
3201 inode_nohighmem(inode);
3202 ext4_set_aops(inode);
3204 * We cannot call page_symlink() with transaction started
3205 * because it calls into ext4_write_begin() which can wait
3206 * for transaction commit if we are running out of space
3207 * and thus we deadlock. So we have to stop transaction now
3208 * and restart it when symlink contents is written.
3210 * To keep fs consistent in case of crash, we have to put inode
3211 * to orphan list in the mean time.
3214 err = ext4_orphan_add(handle, inode);
3215 ext4_journal_stop(handle);
3218 goto err_drop_inode;
3219 err = __page_symlink(inode, disk_link.name, disk_link.len, 1);
3221 goto err_drop_inode;
3223 * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
3224 * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
3226 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3227 EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3228 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
3229 if (IS_ERR(handle)) {
3230 err = PTR_ERR(handle);
3232 goto err_drop_inode;
3234 set_nlink(inode, 1);
3235 err = ext4_orphan_del(handle, inode);
3237 goto err_drop_inode;
3239 /* clear the extent format for fast symlink */
3240 ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
3241 if (!IS_ENCRYPTED(inode)) {
3242 inode->i_op = &ext4_fast_symlink_inode_operations;
3243 inode->i_link = (char *)&EXT4_I(inode)->i_data;
3245 memcpy((char *)&EXT4_I(inode)->i_data, disk_link.name,
3247 inode->i_size = disk_link.len - 1;
3249 EXT4_I(inode)->i_disksize = inode->i_size;
3250 err = ext4_add_nondir(handle, dentry, inode);
3251 if (!err && IS_DIRSYNC(dir))
3252 ext4_handle_sync(handle);
3255 ext4_journal_stop(handle);
3256 goto out_free_encrypted_link;
3260 ext4_journal_stop(handle);
3262 unlock_new_inode(inode);
3264 out_free_encrypted_link:
3265 if (disk_link.name != (unsigned char *)symname)
3266 kfree(disk_link.name);
3270 static int ext4_link(struct dentry *old_dentry,
3271 struct inode *dir, struct dentry *dentry)
3274 struct inode *inode = d_inode(old_dentry);
3275 int err, retries = 0;
3277 if (inode->i_nlink >= EXT4_LINK_MAX)
3280 err = fscrypt_prepare_link(old_dentry, dir, dentry);
3284 if ((ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT)) &&
3285 (!projid_eq(EXT4_I(dir)->i_projid,
3286 EXT4_I(old_dentry->d_inode)->i_projid)))
3289 err = dquot_initialize(dir);
3294 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3295 (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3296 EXT4_INDEX_EXTRA_TRANS_BLOCKS) + 1);
3298 return PTR_ERR(handle);
3300 if (IS_DIRSYNC(dir))
3301 ext4_handle_sync(handle);
3303 inode->i_ctime = current_time(inode);
3304 ext4_inc_count(handle, inode);
3307 err = ext4_add_entry(handle, dentry, inode);
3309 ext4_mark_inode_dirty(handle, inode);
3310 /* this can happen only for tmpfile being
3311 * linked the first time
3313 if (inode->i_nlink == 1)
3314 ext4_orphan_del(handle, inode);
3315 d_instantiate(dentry, inode);
3320 ext4_journal_stop(handle);
3321 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
3328 * Try to find buffer head where contains the parent block.
3329 * It should be the inode block if it is inlined or the 1st block
3330 * if it is a normal dir.
3332 static struct buffer_head *ext4_get_first_dir_block(handle_t *handle,
3333 struct inode *inode,
3335 struct ext4_dir_entry_2 **parent_de,
3338 struct buffer_head *bh;
3340 if (!ext4_has_inline_data(inode)) {
3341 bh = ext4_read_dirblock(inode, 0, EITHER);
3343 *retval = PTR_ERR(bh);
3346 *parent_de = ext4_next_entry(
3347 (struct ext4_dir_entry_2 *)bh->b_data,
3348 inode->i_sb->s_blocksize);
3353 return ext4_get_first_inline_block(inode, parent_de, retval);
3356 struct ext4_renament {
3358 struct dentry *dentry;
3359 struct inode *inode;
3361 int dir_nlink_delta;
3363 /* entry for "dentry" */
3364 struct buffer_head *bh;
3365 struct ext4_dir_entry_2 *de;
3368 /* entry for ".." in inode if it's a directory */
3369 struct buffer_head *dir_bh;
3370 struct ext4_dir_entry_2 *parent_de;
3374 static int ext4_rename_dir_prepare(handle_t *handle, struct ext4_renament *ent)
3378 ent->dir_bh = ext4_get_first_dir_block(handle, ent->inode,
3379 &retval, &ent->parent_de,
3383 if (le32_to_cpu(ent->parent_de->inode) != ent->dir->i_ino)
3384 return -EFSCORRUPTED;
3385 BUFFER_TRACE(ent->dir_bh, "get_write_access");
3386 return ext4_journal_get_write_access(handle, ent->dir_bh);
3389 static int ext4_rename_dir_finish(handle_t *handle, struct ext4_renament *ent,
3394 ent->parent_de->inode = cpu_to_le32(dir_ino);
3395 BUFFER_TRACE(ent->dir_bh, "call ext4_handle_dirty_metadata");
3396 if (!ent->dir_inlined) {
3397 if (is_dx(ent->inode)) {
3398 retval = ext4_handle_dirty_dx_node(handle,
3402 retval = ext4_handle_dirty_dirent_node(handle,
3407 retval = ext4_mark_inode_dirty(handle, ent->inode);
3410 ext4_std_error(ent->dir->i_sb, retval);
3416 static int ext4_setent(handle_t *handle, struct ext4_renament *ent,
3417 unsigned ino, unsigned file_type)
3421 BUFFER_TRACE(ent->bh, "get write access");
3422 retval = ext4_journal_get_write_access(handle, ent->bh);
3425 ent->de->inode = cpu_to_le32(ino);
3426 if (ext4_has_feature_filetype(ent->dir->i_sb))
3427 ent->de->file_type = file_type;
3428 inode_inc_iversion(ent->dir);
3429 ent->dir->i_ctime = ent->dir->i_mtime =
3430 current_time(ent->dir);
3431 ext4_mark_inode_dirty(handle, ent->dir);
3432 BUFFER_TRACE(ent->bh, "call ext4_handle_dirty_metadata");
3433 if (!ent->inlined) {
3434 retval = ext4_handle_dirty_dirent_node(handle,
3436 if (unlikely(retval)) {
3437 ext4_std_error(ent->dir->i_sb, retval);
3447 static int ext4_find_delete_entry(handle_t *handle, struct inode *dir,
3448 const struct qstr *d_name)
3450 int retval = -ENOENT;
3451 struct buffer_head *bh;
3452 struct ext4_dir_entry_2 *de;
3454 bh = ext4_find_entry(dir, d_name, &de, NULL);
3458 retval = ext4_delete_entry(handle, dir, de, bh);
3464 static void ext4_rename_delete(handle_t *handle, struct ext4_renament *ent,
3469 * ent->de could have moved from under us during htree split, so make
3470 * sure that we are deleting the right entry. We might also be pointing
3471 * to a stale entry in the unused part of ent->bh so just checking inum
3472 * and the name isn't enough.
3474 if (le32_to_cpu(ent->de->inode) != ent->inode->i_ino ||
3475 ent->de->name_len != ent->dentry->d_name.len ||
3476 strncmp(ent->de->name, ent->dentry->d_name.name,
3477 ent->de->name_len) ||
3479 retval = ext4_find_delete_entry(handle, ent->dir,
3480 &ent->dentry->d_name);
3482 retval = ext4_delete_entry(handle, ent->dir, ent->de, ent->bh);
3483 if (retval == -ENOENT) {
3484 retval = ext4_find_delete_entry(handle, ent->dir,
3485 &ent->dentry->d_name);
3490 ext4_warning_inode(ent->dir,
3491 "Deleting old file: nlink %d, error=%d",
3492 ent->dir->i_nlink, retval);
3496 static void ext4_update_dir_count(handle_t *handle, struct ext4_renament *ent)
3498 if (ent->dir_nlink_delta) {
3499 if (ent->dir_nlink_delta == -1)
3500 ext4_dec_count(handle, ent->dir);
3502 ext4_inc_count(handle, ent->dir);
3503 ext4_mark_inode_dirty(handle, ent->dir);
3507 static struct inode *ext4_whiteout_for_rename(struct ext4_renament *ent,
3508 int credits, handle_t **h)
3515 * for inode block, sb block, group summaries,
3518 credits += (EXT4_MAXQUOTAS_TRANS_BLOCKS(ent->dir->i_sb) +
3519 EXT4_XATTR_TRANS_BLOCKS + 4);
3521 wh = ext4_new_inode_start_handle(ent->dir, S_IFCHR | WHITEOUT_MODE,
3522 &ent->dentry->d_name, 0, NULL,
3523 EXT4_HT_DIR, credits);
3525 handle = ext4_journal_current_handle();
3528 ext4_journal_stop(handle);
3529 if (PTR_ERR(wh) == -ENOSPC &&
3530 ext4_should_retry_alloc(ent->dir->i_sb, &retries))
3534 init_special_inode(wh, wh->i_mode, WHITEOUT_DEV);
3535 wh->i_op = &ext4_special_inode_operations;
3541 * Anybody can rename anything with this: the permission checks are left to the
3542 * higher-level routines.
3544 * n.b. old_{dentry,inode) refers to the source dentry/inode
3545 * while new_{dentry,inode) refers to the destination dentry/inode
3546 * This comes from rename(const char *oldpath, const char *newpath)
3548 static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
3549 struct inode *new_dir, struct dentry *new_dentry,
3552 handle_t *handle = NULL;
3553 struct ext4_renament old = {
3555 .dentry = old_dentry,
3556 .inode = d_inode(old_dentry),
3558 struct ext4_renament new = {
3560 .dentry = new_dentry,
3561 .inode = d_inode(new_dentry),
3565 struct inode *whiteout = NULL;
3569 if (new.inode && new.inode->i_nlink == 0) {
3570 EXT4_ERROR_INODE(new.inode,
3571 "target of rename is already freed");
3572 return -EFSCORRUPTED;
3575 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT)) &&
3576 (!projid_eq(EXT4_I(new_dir)->i_projid,
3577 EXT4_I(old_dentry->d_inode)->i_projid)))
3580 retval = dquot_initialize(old.dir);
3583 retval = dquot_initialize(new.dir);
3587 /* Initialize quotas before so that eventual writes go
3588 * in separate transaction */
3590 retval = dquot_initialize(new.inode);
3595 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de, NULL);
3597 return PTR_ERR(old.bh);
3599 * Check for inode number is _not_ due to possible IO errors.
3600 * We might rmdir the source, keep it as pwd of some process
3601 * and merrily kill the link to whatever was created under the
3602 * same name. Goodbye sticky bit ;-<
3605 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3608 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3609 &new.de, &new.inlined);
3610 if (IS_ERR(new.bh)) {
3611 retval = PTR_ERR(new.bh);
3621 if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC))
3622 ext4_alloc_da_blocks(old.inode);
3624 credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3625 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
3626 if (!(flags & RENAME_WHITEOUT)) {
3627 handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits);
3628 if (IS_ERR(handle)) {
3629 retval = PTR_ERR(handle);
3634 whiteout = ext4_whiteout_for_rename(&old, credits, &handle);
3635 if (IS_ERR(whiteout)) {
3636 retval = PTR_ERR(whiteout);
3642 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3643 ext4_handle_sync(handle);
3645 if (S_ISDIR(old.inode->i_mode)) {
3647 retval = -ENOTEMPTY;
3648 if (!ext4_empty_dir(new.inode))
3652 if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir))
3655 retval = ext4_rename_dir_prepare(handle, &old);
3660 * If we're renaming a file within an inline_data dir and adding or
3661 * setting the new dirent causes a conversion from inline_data to
3662 * extents/blockmap, we need to force the dirent delete code to
3663 * re-read the directory, or else we end up trying to delete a dirent
3664 * from what is now the extent tree root (or a block map).
3666 force_reread = (new.dir->i_ino == old.dir->i_ino &&
3667 ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA));
3669 old_file_type = old.de->file_type;
3672 * Do this before adding a new entry, so the old entry is sure
3673 * to be still pointing to the valid old entry.
3675 retval = ext4_setent(handle, &old, whiteout->i_ino,
3679 ext4_mark_inode_dirty(handle, whiteout);
3682 retval = ext4_add_entry(handle, new.dentry, old.inode);
3686 retval = ext4_setent(handle, &new,
3687 old.inode->i_ino, old_file_type);
3692 force_reread = !ext4_test_inode_flag(new.dir,
3693 EXT4_INODE_INLINE_DATA);
3696 * Like most other Unix systems, set the ctime for inodes on a
3699 old.inode->i_ctime = current_time(old.inode);
3700 ext4_mark_inode_dirty(handle, old.inode);
3706 ext4_rename_delete(handle, &old, force_reread);
3710 ext4_dec_count(handle, new.inode);
3711 new.inode->i_ctime = current_time(new.inode);
3713 old.dir->i_ctime = old.dir->i_mtime = current_time(old.dir);
3714 ext4_update_dx_flag(old.dir);
3716 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3720 ext4_dec_count(handle, old.dir);
3722 /* checked ext4_empty_dir above, can't have another
3723 * parent, ext4_dec_count() won't work for many-linked
3725 clear_nlink(new.inode);
3727 ext4_inc_count(handle, new.dir);
3728 ext4_update_dx_flag(new.dir);
3729 ext4_mark_inode_dirty(handle, new.dir);
3732 ext4_mark_inode_dirty(handle, old.dir);
3734 ext4_mark_inode_dirty(handle, new.inode);
3735 if (!new.inode->i_nlink)
3736 ext4_orphan_add(handle, new.inode);
3746 drop_nlink(whiteout);
3747 unlock_new_inode(whiteout);
3751 ext4_journal_stop(handle);
3755 static int ext4_cross_rename(struct inode *old_dir, struct dentry *old_dentry,
3756 struct inode *new_dir, struct dentry *new_dentry)
3758 handle_t *handle = NULL;
3759 struct ext4_renament old = {
3761 .dentry = old_dentry,
3762 .inode = d_inode(old_dentry),
3764 struct ext4_renament new = {
3766 .dentry = new_dentry,
3767 .inode = d_inode(new_dentry),
3771 struct timespec64 ctime;
3773 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT) &&
3774 !projid_eq(EXT4_I(new_dir)->i_projid,
3775 EXT4_I(old_dentry->d_inode)->i_projid)) ||
3776 (ext4_test_inode_flag(old_dir, EXT4_INODE_PROJINHERIT) &&
3777 !projid_eq(EXT4_I(old_dir)->i_projid,
3778 EXT4_I(new_dentry->d_inode)->i_projid)))
3781 retval = dquot_initialize(old.dir);
3784 retval = dquot_initialize(new.dir);
3788 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name,
3789 &old.de, &old.inlined);
3791 return PTR_ERR(old.bh);
3793 * Check for inode number is _not_ due to possible IO errors.
3794 * We might rmdir the source, keep it as pwd of some process
3795 * and merrily kill the link to whatever was created under the
3796 * same name. Goodbye sticky bit ;-<
3799 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3802 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3803 &new.de, &new.inlined);
3804 if (IS_ERR(new.bh)) {
3805 retval = PTR_ERR(new.bh);
3810 /* RENAME_EXCHANGE case: old *and* new must both exist */
3811 if (!new.bh || le32_to_cpu(new.de->inode) != new.inode->i_ino)
3814 handle = ext4_journal_start(old.dir, EXT4_HT_DIR,
3815 (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3816 2 * EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2));
3817 if (IS_ERR(handle)) {
3818 retval = PTR_ERR(handle);
3823 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3824 ext4_handle_sync(handle);
3826 if (S_ISDIR(old.inode->i_mode)) {
3828 retval = ext4_rename_dir_prepare(handle, &old);
3832 if (S_ISDIR(new.inode->i_mode)) {
3834 retval = ext4_rename_dir_prepare(handle, &new);
3840 * Other than the special case of overwriting a directory, parents'
3841 * nlink only needs to be modified if this is a cross directory rename.
3843 if (old.dir != new.dir && old.is_dir != new.is_dir) {
3844 old.dir_nlink_delta = old.is_dir ? -1 : 1;
3845 new.dir_nlink_delta = -old.dir_nlink_delta;
3847 if ((old.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(old.dir)) ||
3848 (new.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(new.dir)))
3852 new_file_type = new.de->file_type;
3853 retval = ext4_setent(handle, &new, old.inode->i_ino, old.de->file_type);
3857 retval = ext4_setent(handle, &old, new.inode->i_ino, new_file_type);
3862 * Like most other Unix systems, set the ctime for inodes on a
3865 ctime = current_time(old.inode);
3866 old.inode->i_ctime = ctime;
3867 new.inode->i_ctime = ctime;
3868 ext4_mark_inode_dirty(handle, old.inode);
3869 ext4_mark_inode_dirty(handle, new.inode);
3872 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3877 retval = ext4_rename_dir_finish(handle, &new, old.dir->i_ino);
3881 ext4_update_dir_count(handle, &old);
3882 ext4_update_dir_count(handle, &new);
3891 ext4_journal_stop(handle);
3895 static int ext4_rename2(struct inode *old_dir, struct dentry *old_dentry,
3896 struct inode *new_dir, struct dentry *new_dentry,
3901 if (unlikely(ext4_forced_shutdown(EXT4_SB(old_dir->i_sb))))
3904 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
3907 err = fscrypt_prepare_rename(old_dir, old_dentry, new_dir, new_dentry,
3912 if (flags & RENAME_EXCHANGE) {
3913 return ext4_cross_rename(old_dir, old_dentry,
3914 new_dir, new_dentry);
3917 return ext4_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
3921 * directories can handle most operations...
3923 const struct inode_operations ext4_dir_inode_operations = {
3924 .create = ext4_create,
3925 .lookup = ext4_lookup,
3927 .unlink = ext4_unlink,
3928 .symlink = ext4_symlink,
3929 .mkdir = ext4_mkdir,
3930 .rmdir = ext4_rmdir,
3931 .mknod = ext4_mknod,
3932 .tmpfile = ext4_tmpfile,
3933 .rename = ext4_rename2,
3934 .setattr = ext4_setattr,
3935 .getattr = ext4_getattr,
3936 .listxattr = ext4_listxattr,
3937 .get_acl = ext4_get_acl,
3938 .set_acl = ext4_set_acl,
3939 .fiemap = ext4_fiemap,
3942 const struct inode_operations ext4_special_inode_operations = {
3943 .setattr = ext4_setattr,
3944 .getattr = ext4_getattr,
3945 .listxattr = ext4_listxattr,
3946 .get_acl = ext4_get_acl,
3947 .set_acl = ext4_set_acl,