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) ==
1374 * __ext4_find_entry()
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 struct ext4_filename *fname,
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 = fname->usr_fname->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;
1403 namelen = fname->usr_fname->len;
1404 if (namelen > EXT4_NAME_LEN)
1407 if (ext4_has_inline_data(dir)) {
1408 int has_inline_data = 1;
1409 ret = ext4_find_inline_entry(dir, fname, res_dir,
1411 if (has_inline_data) {
1414 goto cleanup_and_exit;
1418 if ((namelen <= 2) && (name[0] == '.') &&
1419 (name[1] == '.' || name[1] == '\0')) {
1421 * "." or ".." will only be in the first block
1422 * NFS may look up ".."; "." should be handled by the VFS
1429 ret = ext4_dx_find_entry(dir, fname, res_dir);
1431 * On success, or if the error was file not found,
1432 * return. Otherwise, fall back to doing a search the
1433 * old fashioned way.
1435 if (!IS_ERR(ret) || PTR_ERR(ret) != ERR_BAD_DX_DIR)
1436 goto cleanup_and_exit;
1437 dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
1441 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1444 goto cleanup_and_exit;
1446 start = EXT4_I(dir)->i_dir_start_lookup;
1447 if (start >= nblocks)
1453 * We deal with the read-ahead logic here.
1455 if (ra_ptr >= ra_max) {
1456 /* Refill the readahead buffer */
1459 ra_max = start - block;
1461 ra_max = nblocks - block;
1462 ra_max = min(ra_max, ARRAY_SIZE(bh_use));
1463 retval = ext4_bread_batch(dir, block, ra_max,
1464 false /* wait */, bh_use);
1466 ret = ERR_PTR(retval);
1468 goto cleanup_and_exit;
1471 if ((bh = bh_use[ra_ptr++]) == NULL)
1474 if (!buffer_uptodate(bh)) {
1475 EXT4_ERROR_INODE(dir, "reading directory lblock %lu",
1476 (unsigned long) block);
1478 ret = ERR_PTR(-EIO);
1479 goto cleanup_and_exit;
1481 if (!buffer_verified(bh) &&
1482 !is_dx_internal_node(dir, block,
1483 (struct ext4_dir_entry *)bh->b_data) &&
1484 !ext4_dirent_csum_verify(dir,
1485 (struct ext4_dir_entry *)bh->b_data)) {
1486 EXT4_ERROR_INODE(dir, "checksumming directory "
1487 "block %lu", (unsigned long)block);
1489 ret = ERR_PTR(-EFSBADCRC);
1490 goto cleanup_and_exit;
1492 set_buffer_verified(bh);
1493 i = search_dirblock(bh, dir, fname,
1494 block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
1496 EXT4_I(dir)->i_dir_start_lookup = block;
1498 goto cleanup_and_exit;
1502 goto cleanup_and_exit;
1505 if (++block >= nblocks)
1507 } while (block != start);
1510 * If the directory has grown while we were searching, then
1511 * search the last part of the directory before giving up.
1514 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1515 if (block < nblocks) {
1521 /* Clean up the read-ahead blocks */
1522 for (; ra_ptr < ra_max; ra_ptr++)
1523 brelse(bh_use[ra_ptr]);
1527 static struct buffer_head *ext4_find_entry(struct inode *dir,
1528 const struct qstr *d_name,
1529 struct ext4_dir_entry_2 **res_dir,
1533 struct ext4_filename fname;
1534 struct buffer_head *bh;
1536 err = ext4_fname_setup_filename(dir, d_name, 1, &fname);
1540 return ERR_PTR(err);
1542 bh = __ext4_find_entry(dir, &fname, res_dir, inlined);
1544 ext4_fname_free_filename(&fname);
1548 static struct buffer_head *ext4_lookup_entry(struct inode *dir,
1549 struct dentry *dentry,
1550 struct ext4_dir_entry_2 **res_dir)
1553 struct ext4_filename fname;
1554 struct buffer_head *bh;
1556 err = ext4_fname_prepare_lookup(dir, dentry, &fname);
1560 return ERR_PTR(err);
1562 bh = __ext4_find_entry(dir, &fname, res_dir, NULL);
1564 ext4_fname_free_filename(&fname);
1568 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
1569 struct ext4_filename *fname,
1570 struct ext4_dir_entry_2 **res_dir)
1572 struct super_block * sb = dir->i_sb;
1573 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1574 struct buffer_head *bh;
1578 #ifdef CONFIG_FS_ENCRYPTION
1581 frame = dx_probe(fname, dir, NULL, frames);
1583 return (struct buffer_head *) frame;
1585 block = dx_get_block(frame->at);
1586 bh = ext4_read_dirblock(dir, block, DIRENT);
1590 retval = search_dirblock(bh, dir, fname,
1591 block << EXT4_BLOCK_SIZE_BITS(sb),
1597 bh = ERR_PTR(ERR_BAD_DX_DIR);
1601 /* Check to see if we should continue to search */
1602 retval = ext4_htree_next_block(dir, fname->hinfo.hash, frame,
1605 ext4_warning_inode(dir,
1606 "error %d reading directory index block",
1608 bh = ERR_PTR(retval);
1611 } while (retval == 1);
1615 dxtrace(printk(KERN_DEBUG "%s not found\n", fname->usr_fname->name));
1621 static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
1623 struct inode *inode;
1624 struct ext4_dir_entry_2 *de;
1625 struct buffer_head *bh;
1627 if (dentry->d_name.len > EXT4_NAME_LEN)
1628 return ERR_PTR(-ENAMETOOLONG);
1630 bh = ext4_lookup_entry(dir, dentry, &de);
1632 return ERR_CAST(bh);
1635 __u32 ino = le32_to_cpu(de->inode);
1637 if (!ext4_valid_inum(dir->i_sb, ino)) {
1638 EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
1639 return ERR_PTR(-EFSCORRUPTED);
1641 if (unlikely(ino == dir->i_ino)) {
1642 EXT4_ERROR_INODE(dir, "'%pd' linked to parent dir",
1644 return ERR_PTR(-EFSCORRUPTED);
1646 inode = ext4_iget(dir->i_sb, ino, EXT4_IGET_NORMAL);
1647 if (inode == ERR_PTR(-ESTALE)) {
1648 EXT4_ERROR_INODE(dir,
1649 "deleted inode referenced: %u",
1651 return ERR_PTR(-EFSCORRUPTED);
1653 if (!IS_ERR(inode) && IS_ENCRYPTED(dir) &&
1654 (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
1655 !fscrypt_has_permitted_context(dir, inode)) {
1656 ext4_warning(inode->i_sb,
1657 "Inconsistent encryption contexts: %lu/%lu",
1658 dir->i_ino, inode->i_ino);
1660 return ERR_PTR(-EPERM);
1664 #ifdef CONFIG_UNICODE
1665 if (!inode && IS_CASEFOLDED(dir)) {
1666 /* Eventually we want to call d_add_ci(dentry, NULL)
1667 * for negative dentries in the encoding case as
1668 * well. For now, prevent the negative dentry
1669 * from being cached.
1674 return d_splice_alias(inode, dentry);
1678 struct dentry *ext4_get_parent(struct dentry *child)
1681 static const struct qstr dotdot = QSTR_INIT("..", 2);
1682 struct ext4_dir_entry_2 * de;
1683 struct buffer_head *bh;
1685 bh = ext4_find_entry(d_inode(child), &dotdot, &de, NULL);
1687 return ERR_CAST(bh);
1689 return ERR_PTR(-ENOENT);
1690 ino = le32_to_cpu(de->inode);
1693 if (!ext4_valid_inum(child->d_sb, ino)) {
1694 EXT4_ERROR_INODE(d_inode(child),
1695 "bad parent inode number: %u", ino);
1696 return ERR_PTR(-EFSCORRUPTED);
1699 return d_obtain_alias(ext4_iget(child->d_sb, ino, EXT4_IGET_NORMAL));
1703 * Move count entries from end of map between two memory locations.
1704 * Returns pointer to last entry moved.
1706 static struct ext4_dir_entry_2 *
1707 dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count,
1710 unsigned rec_len = 0;
1713 struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
1714 (from + (map->offs<<2));
1715 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1716 memcpy (to, de, rec_len);
1717 ((struct ext4_dir_entry_2 *) to)->rec_len =
1718 ext4_rec_len_to_disk(rec_len, blocksize);
1723 return (struct ext4_dir_entry_2 *) (to - rec_len);
1727 * Compact each dir entry in the range to the minimal rec_len.
1728 * Returns pointer to last entry in range.
1730 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize)
1732 struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
1733 unsigned rec_len = 0;
1736 while ((char*)de < base + blocksize) {
1737 next = ext4_next_entry(de, blocksize);
1738 if (de->inode && de->name_len) {
1739 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1741 memmove(to, de, rec_len);
1742 to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
1744 to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
1752 * Split a full leaf block to make room for a new dir entry.
1753 * Allocate a new block, and move entries so that they are approx. equally full.
1754 * Returns pointer to de in block into which the new entry will be inserted.
1756 static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
1757 struct buffer_head **bh,struct dx_frame *frame,
1758 struct dx_hash_info *hinfo)
1760 unsigned blocksize = dir->i_sb->s_blocksize;
1761 unsigned count, continued;
1762 struct buffer_head *bh2;
1763 ext4_lblk_t newblock;
1765 struct dx_map_entry *map;
1766 char *data1 = (*bh)->b_data, *data2;
1767 unsigned split, move, size;
1768 struct ext4_dir_entry_2 *de = NULL, *de2;
1769 struct ext4_dir_entry_tail *t;
1773 if (ext4_has_metadata_csum(dir->i_sb))
1774 csum_size = sizeof(struct ext4_dir_entry_tail);
1776 bh2 = ext4_append(handle, dir, &newblock);
1780 return (struct ext4_dir_entry_2 *) bh2;
1783 BUFFER_TRACE(*bh, "get_write_access");
1784 err = ext4_journal_get_write_access(handle, *bh);
1788 BUFFER_TRACE(frame->bh, "get_write_access");
1789 err = ext4_journal_get_write_access(handle, frame->bh);
1793 data2 = bh2->b_data;
1795 /* create map in the end of data2 block */
1796 map = (struct dx_map_entry *) (data2 + blocksize);
1797 count = dx_make_map(dir, (struct ext4_dir_entry_2 *) data1,
1798 blocksize, hinfo, map);
1800 dx_sort_map(map, count);
1801 /* Split the existing block in the middle, size-wise */
1804 for (i = count-1; i >= 0; i--) {
1805 /* is more than half of this entry in 2nd half of the block? */
1806 if (size + map[i].size/2 > blocksize/2)
1808 size += map[i].size;
1811 /* map index at which we will split */
1812 split = count - move;
1813 hash2 = map[split].hash;
1814 continued = hash2 == map[split - 1].hash;
1815 dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
1816 (unsigned long)dx_get_block(frame->at),
1817 hash2, split, count-split));
1819 /* Fancy dance to stay within two buffers */
1820 de2 = dx_move_dirents(data1, data2, map + split, count - split,
1822 de = dx_pack_dirents(data1, blocksize);
1823 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
1826 de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
1830 t = EXT4_DIRENT_TAIL(data2, blocksize);
1831 initialize_dirent_tail(t, blocksize);
1833 t = EXT4_DIRENT_TAIL(data1, blocksize);
1834 initialize_dirent_tail(t, blocksize);
1837 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,
1839 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,
1842 /* Which block gets the new entry? */
1843 if (hinfo->hash >= hash2) {
1847 dx_insert_block(frame, hash2 + continued, newblock);
1848 err = ext4_handle_dirty_dirent_node(handle, dir, bh2);
1851 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
1855 dxtrace(dx_show_index("frame", frame->entries));
1862 ext4_std_error(dir->i_sb, err);
1863 return ERR_PTR(err);
1866 int ext4_find_dest_de(struct inode *dir, struct inode *inode,
1867 struct buffer_head *bh,
1868 void *buf, int buf_size,
1869 struct ext4_filename *fname,
1870 struct ext4_dir_entry_2 **dest_de)
1872 struct ext4_dir_entry_2 *de;
1873 unsigned short reclen = EXT4_DIR_REC_LEN(fname_len(fname));
1875 unsigned int offset = 0;
1878 de = (struct ext4_dir_entry_2 *)buf;
1879 top = buf + buf_size - reclen;
1880 while ((char *) de <= top) {
1881 if (ext4_check_dir_entry(dir, NULL, de, bh,
1882 buf, buf_size, offset))
1883 return -EFSCORRUPTED;
1884 if (ext4_match(dir, fname, de))
1886 nlen = EXT4_DIR_REC_LEN(de->name_len);
1887 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1888 if ((de->inode ? rlen - nlen : rlen) >= reclen)
1890 de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
1893 if ((char *) de > top)
1900 void ext4_insert_dentry(struct inode *inode,
1901 struct ext4_dir_entry_2 *de,
1903 struct ext4_filename *fname)
1908 nlen = EXT4_DIR_REC_LEN(de->name_len);
1909 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1911 struct ext4_dir_entry_2 *de1 =
1912 (struct ext4_dir_entry_2 *)((char *)de + nlen);
1913 de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size);
1914 de->rec_len = ext4_rec_len_to_disk(nlen, buf_size);
1917 de->file_type = EXT4_FT_UNKNOWN;
1918 de->inode = cpu_to_le32(inode->i_ino);
1919 ext4_set_de_type(inode->i_sb, de, inode->i_mode);
1920 de->name_len = fname_len(fname);
1921 memcpy(de->name, fname_name(fname), fname_len(fname));
1925 * Add a new entry into a directory (leaf) block. If de is non-NULL,
1926 * it points to a directory entry which is guaranteed to be large
1927 * enough for new directory entry. If de is NULL, then
1928 * add_dirent_to_buf will attempt search the directory block for
1929 * space. It will return -ENOSPC if no space is available, and -EIO
1930 * and -EEXIST if directory entry already exists.
1932 static int add_dirent_to_buf(handle_t *handle, struct ext4_filename *fname,
1934 struct inode *inode, struct ext4_dir_entry_2 *de,
1935 struct buffer_head *bh)
1937 unsigned int blocksize = dir->i_sb->s_blocksize;
1941 if (ext4_has_metadata_csum(inode->i_sb))
1942 csum_size = sizeof(struct ext4_dir_entry_tail);
1945 err = ext4_find_dest_de(dir, inode, bh, bh->b_data,
1946 blocksize - csum_size, fname, &de);
1950 BUFFER_TRACE(bh, "get_write_access");
1951 err = ext4_journal_get_write_access(handle, bh);
1953 ext4_std_error(dir->i_sb, err);
1957 /* By now the buffer is marked for journaling */
1958 ext4_insert_dentry(inode, de, blocksize, fname);
1961 * XXX shouldn't update any times until successful
1962 * completion of syscall, but too many callers depend
1965 * XXX similarly, too many callers depend on
1966 * ext4_new_inode() setting the times, but error
1967 * recovery deletes the inode, so the worst that can
1968 * happen is that the times are slightly out of date
1969 * and/or different from the directory change time.
1971 dir->i_mtime = dir->i_ctime = current_time(dir);
1972 ext4_update_dx_flag(dir);
1973 inode_inc_iversion(dir);
1974 ext4_mark_inode_dirty(handle, dir);
1975 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1976 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
1978 ext4_std_error(dir->i_sb, err);
1983 * This converts a one block unindexed directory to a 3 block indexed
1984 * directory, and adds the dentry to the indexed directory.
1986 static int make_indexed_dir(handle_t *handle, struct ext4_filename *fname,
1988 struct inode *inode, struct buffer_head *bh)
1990 struct buffer_head *bh2;
1991 struct dx_root *root;
1992 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1993 struct dx_entry *entries;
1994 struct ext4_dir_entry_2 *de, *de2;
1995 struct ext4_dir_entry_tail *t;
2001 struct fake_dirent *fde;
2004 if (ext4_has_metadata_csum(inode->i_sb))
2005 csum_size = sizeof(struct ext4_dir_entry_tail);
2007 blocksize = dir->i_sb->s_blocksize;
2008 dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
2009 BUFFER_TRACE(bh, "get_write_access");
2010 retval = ext4_journal_get_write_access(handle, bh);
2012 ext4_std_error(dir->i_sb, retval);
2016 root = (struct dx_root *) bh->b_data;
2018 /* The 0th block becomes the root, move the dirents out */
2019 fde = &root->dotdot;
2020 de = (struct ext4_dir_entry_2 *)((char *)fde +
2021 ext4_rec_len_from_disk(fde->rec_len, blocksize));
2022 if ((char *) de >= (((char *) root) + blocksize)) {
2023 EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
2025 return -EFSCORRUPTED;
2027 len = ((char *) root) + (blocksize - csum_size) - (char *) de;
2029 /* Allocate new block for the 0th block's dirents */
2030 bh2 = ext4_append(handle, dir, &block);
2033 return PTR_ERR(bh2);
2035 ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
2036 data1 = bh2->b_data;
2038 memcpy (data1, de, len);
2039 de = (struct ext4_dir_entry_2 *) data1;
2041 while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top)
2043 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
2048 t = EXT4_DIRENT_TAIL(data1, blocksize);
2049 initialize_dirent_tail(t, blocksize);
2052 /* Initialize the root; the dot dirents already exist */
2053 de = (struct ext4_dir_entry_2 *) (&root->dotdot);
2054 de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
2056 memset (&root->info, 0, sizeof(root->info));
2057 root->info.info_length = sizeof(root->info);
2058 root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
2059 entries = root->entries;
2060 dx_set_block(entries, 1);
2061 dx_set_count(entries, 1);
2062 dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
2064 /* Initialize as for dx_probe */
2065 fname->hinfo.hash_version = root->info.hash_version;
2066 if (fname->hinfo.hash_version <= DX_HASH_TEA)
2067 fname->hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
2068 fname->hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
2069 ext4fs_dirhash(dir, fname_name(fname), fname_len(fname), &fname->hinfo);
2071 memset(frames, 0, sizeof(frames));
2073 frame->entries = entries;
2074 frame->at = entries;
2077 retval = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2080 retval = ext4_handle_dirty_dirent_node(handle, dir, bh2);
2084 de = do_split(handle,dir, &bh2, frame, &fname->hinfo);
2086 retval = PTR_ERR(de);
2090 retval = add_dirent_to_buf(handle, fname, dir, inode, de, bh2);
2093 * Even if the block split failed, we have to properly write
2094 * out all the changes we did so far. Otherwise we can end up
2095 * with corrupted filesystem.
2098 ext4_mark_inode_dirty(handle, dir);
2107 * adds a file entry to the specified directory, using the same
2108 * semantics as ext4_find_entry(). It returns NULL if it failed.
2110 * NOTE!! The inode part of 'de' is left at 0 - which means you
2111 * may not sleep between calling this and putting something into
2112 * the entry, as someone else might have used it while you slept.
2114 static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
2115 struct inode *inode)
2117 struct inode *dir = d_inode(dentry->d_parent);
2118 struct buffer_head *bh = NULL;
2119 struct ext4_dir_entry_2 *de;
2120 struct ext4_dir_entry_tail *t;
2121 struct super_block *sb;
2122 struct ext4_sb_info *sbi;
2123 struct ext4_filename fname;
2127 ext4_lblk_t block, blocks;
2130 if (ext4_has_metadata_csum(inode->i_sb))
2131 csum_size = sizeof(struct ext4_dir_entry_tail);
2135 blocksize = sb->s_blocksize;
2136 if (!dentry->d_name.len)
2139 #ifdef CONFIG_UNICODE
2140 if (ext4_has_strict_mode(sbi) && IS_CASEFOLDED(dir) &&
2141 utf8_validate(sbi->s_encoding, &dentry->d_name))
2145 retval = ext4_fname_setup_filename(dir, &dentry->d_name, 0, &fname);
2149 if (ext4_has_inline_data(dir)) {
2150 retval = ext4_try_add_inline_entry(handle, &fname, dir, inode);
2160 retval = ext4_dx_add_entry(handle, &fname, dir, inode);
2161 if (!retval || (retval != ERR_BAD_DX_DIR))
2163 ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
2165 ext4_mark_inode_dirty(handle, dir);
2167 blocks = dir->i_size >> sb->s_blocksize_bits;
2168 for (block = 0; block < blocks; block++) {
2169 bh = ext4_read_dirblock(dir, block, DIRENT);
2171 retval = PTR_ERR(bh);
2175 retval = add_dirent_to_buf(handle, &fname, dir, inode,
2177 if (retval != -ENOSPC)
2180 if (blocks == 1 && !dx_fallback &&
2181 ext4_has_feature_dir_index(sb)) {
2182 retval = make_indexed_dir(handle, &fname, dir,
2184 bh = NULL; /* make_indexed_dir releases bh */
2189 bh = ext4_append(handle, dir, &block);
2191 retval = PTR_ERR(bh);
2195 de = (struct ext4_dir_entry_2 *) bh->b_data;
2197 de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
2200 t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
2201 initialize_dirent_tail(t, blocksize);
2204 retval = add_dirent_to_buf(handle, &fname, dir, inode, de, bh);
2206 ext4_fname_free_filename(&fname);
2209 ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
2214 * Returns 0 for success, or a negative error value
2216 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
2217 struct inode *dir, struct inode *inode)
2219 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
2220 struct dx_entry *entries, *at;
2221 struct buffer_head *bh;
2222 struct super_block *sb = dir->i_sb;
2223 struct ext4_dir_entry_2 *de;
2229 frame = dx_probe(fname, dir, NULL, frames);
2231 return PTR_ERR(frame);
2232 entries = frame->entries;
2234 bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT);
2241 BUFFER_TRACE(bh, "get_write_access");
2242 err = ext4_journal_get_write_access(handle, bh);
2246 err = add_dirent_to_buf(handle, fname, dir, inode, NULL, bh);
2251 /* Block full, should compress but for now just split */
2252 dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
2253 dx_get_count(entries), dx_get_limit(entries)));
2254 /* Need to split index? */
2255 if (dx_get_count(entries) == dx_get_limit(entries)) {
2256 ext4_lblk_t newblock;
2257 int levels = frame - frames + 1;
2258 unsigned int icount;
2260 struct dx_entry *entries2;
2261 struct dx_node *node2;
2262 struct buffer_head *bh2;
2264 while (frame > frames) {
2265 if (dx_get_count((frame - 1)->entries) <
2266 dx_get_limit((frame - 1)->entries)) {
2270 frame--; /* split higher index block */
2272 entries = frame->entries;
2275 if (add_level && levels == ext4_dir_htree_level(sb)) {
2276 ext4_warning(sb, "Directory (ino: %lu) index full, "
2277 "reach max htree level :%d",
2278 dir->i_ino, levels);
2279 if (ext4_dir_htree_level(sb) < EXT4_HTREE_LEVEL) {
2280 ext4_warning(sb, "Large directory feature is "
2281 "not enabled on this "
2287 icount = dx_get_count(entries);
2288 bh2 = ext4_append(handle, dir, &newblock);
2293 node2 = (struct dx_node *)(bh2->b_data);
2294 entries2 = node2->entries;
2295 memset(&node2->fake, 0, sizeof(struct fake_dirent));
2296 node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
2298 BUFFER_TRACE(frame->bh, "get_write_access");
2299 err = ext4_journal_get_write_access(handle, frame->bh);
2303 unsigned icount1 = icount/2, icount2 = icount - icount1;
2304 unsigned hash2 = dx_get_hash(entries + icount1);
2305 dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
2308 BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
2309 err = ext4_journal_get_write_access(handle,
2314 memcpy((char *) entries2, (char *) (entries + icount1),
2315 icount2 * sizeof(struct dx_entry));
2316 dx_set_count(entries, icount1);
2317 dx_set_count(entries2, icount2);
2318 dx_set_limit(entries2, dx_node_limit(dir));
2320 /* Which index block gets the new entry? */
2321 if (at - entries >= icount1) {
2322 frame->at = at = at - entries - icount1 + entries2;
2323 frame->entries = entries = entries2;
2324 swap(frame->bh, bh2);
2326 dx_insert_block((frame - 1), hash2, newblock);
2327 dxtrace(dx_show_index("node", frame->entries));
2328 dxtrace(dx_show_index("node",
2329 ((struct dx_node *) bh2->b_data)->entries));
2330 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2334 err = ext4_handle_dirty_dx_node(handle, dir,
2339 err = ext4_handle_dirty_dx_node(handle, dir,
2344 struct dx_root *dxroot;
2345 memcpy((char *) entries2, (char *) entries,
2346 icount * sizeof(struct dx_entry));
2347 dx_set_limit(entries2, dx_node_limit(dir));
2350 dx_set_count(entries, 1);
2351 dx_set_block(entries + 0, newblock);
2352 dxroot = (struct dx_root *)frames[0].bh->b_data;
2353 dxroot->info.indirect_levels += 1;
2354 dxtrace(printk(KERN_DEBUG
2355 "Creating %d level index...\n",
2356 dxroot->info.indirect_levels));
2357 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2360 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2366 de = do_split(handle, dir, &bh, frame, &fname->hinfo);
2371 err = add_dirent_to_buf(handle, fname, dir, inode, de, bh);
2375 ext4_std_error(dir->i_sb, err); /* this is a no-op if err == 0 */
2379 /* @restart is true means htree-path has been changed, we need to
2380 * repeat dx_probe() to find out valid htree-path
2382 if (restart && err == 0)
2388 * ext4_generic_delete_entry deletes a directory entry by merging it
2389 * with the previous entry
2391 int ext4_generic_delete_entry(handle_t *handle,
2393 struct ext4_dir_entry_2 *de_del,
2394 struct buffer_head *bh,
2399 struct ext4_dir_entry_2 *de, *pde;
2400 unsigned int blocksize = dir->i_sb->s_blocksize;
2405 de = (struct ext4_dir_entry_2 *)entry_buf;
2406 while (i < buf_size - csum_size) {
2407 if (ext4_check_dir_entry(dir, NULL, de, bh,
2408 bh->b_data, bh->b_size, i))
2409 return -EFSCORRUPTED;
2412 pde->rec_len = ext4_rec_len_to_disk(
2413 ext4_rec_len_from_disk(pde->rec_len,
2415 ext4_rec_len_from_disk(de->rec_len,
2420 inode_inc_iversion(dir);
2423 i += ext4_rec_len_from_disk(de->rec_len, blocksize);
2425 de = ext4_next_entry(de, blocksize);
2430 static int ext4_delete_entry(handle_t *handle,
2432 struct ext4_dir_entry_2 *de_del,
2433 struct buffer_head *bh)
2435 int err, csum_size = 0;
2437 if (ext4_has_inline_data(dir)) {
2438 int has_inline_data = 1;
2439 err = ext4_delete_inline_entry(handle, dir, de_del, bh,
2441 if (has_inline_data)
2445 if (ext4_has_metadata_csum(dir->i_sb))
2446 csum_size = sizeof(struct ext4_dir_entry_tail);
2448 BUFFER_TRACE(bh, "get_write_access");
2449 err = ext4_journal_get_write_access(handle, bh);
2453 err = ext4_generic_delete_entry(handle, dir, de_del,
2455 dir->i_sb->s_blocksize, csum_size);
2459 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
2460 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
2467 ext4_std_error(dir->i_sb, err);
2472 * Set directory link count to 1 if nlinks > EXT4_LINK_MAX, or if nlinks == 2
2473 * since this indicates that nlinks count was previously 1 to avoid overflowing
2474 * the 16-bit i_links_count field on disk. Directories with i_nlink == 1 mean
2475 * that subdirectory link counts are not being maintained accurately.
2477 * The caller has already checked for i_nlink overflow in case the DIR_LINK
2478 * feature is not enabled and returned -EMLINK. The is_dx() check is a proxy
2479 * for checking S_ISDIR(inode) (since the INODE_INDEX feature will not be set
2480 * on regular files) and to avoid creating huge/slow non-HTREE directories.
2482 static void ext4_inc_count(handle_t *handle, struct inode *inode)
2486 (inode->i_nlink > EXT4_LINK_MAX || inode->i_nlink == 2))
2487 set_nlink(inode, 1);
2491 * If a directory had nlink == 1, then we should let it be 1. This indicates
2492 * directory has >EXT4_LINK_MAX subdirs.
2494 static void ext4_dec_count(handle_t *handle, struct inode *inode)
2496 if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
2501 static int ext4_add_nondir(handle_t *handle,
2502 struct dentry *dentry, struct inode *inode)
2504 int err = ext4_add_entry(handle, dentry, inode);
2506 ext4_mark_inode_dirty(handle, inode);
2507 d_instantiate_new(dentry, inode);
2511 unlock_new_inode(inode);
2517 * By the time this is called, we already have created
2518 * the directory cache entry for the new file, but it
2519 * is so far negative - it has no inode.
2521 * If the create succeeds, we fill in the inode information
2522 * with d_instantiate().
2524 static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2528 struct inode *inode;
2529 int err, credits, retries = 0;
2531 err = dquot_initialize(dir);
2535 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2536 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2538 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2539 NULL, EXT4_HT_DIR, credits);
2540 handle = ext4_journal_current_handle();
2541 err = PTR_ERR(inode);
2542 if (!IS_ERR(inode)) {
2543 inode->i_op = &ext4_file_inode_operations;
2544 inode->i_fop = &ext4_file_operations;
2545 ext4_set_aops(inode);
2546 err = ext4_add_nondir(handle, dentry, inode);
2547 if (!err && IS_DIRSYNC(dir))
2548 ext4_handle_sync(handle);
2551 ext4_journal_stop(handle);
2552 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2557 static int ext4_mknod(struct inode *dir, struct dentry *dentry,
2558 umode_t mode, dev_t rdev)
2561 struct inode *inode;
2562 int err, credits, retries = 0;
2564 err = dquot_initialize(dir);
2568 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2569 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2571 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2572 NULL, EXT4_HT_DIR, credits);
2573 handle = ext4_journal_current_handle();
2574 err = PTR_ERR(inode);
2575 if (!IS_ERR(inode)) {
2576 init_special_inode(inode, inode->i_mode, rdev);
2577 inode->i_op = &ext4_special_inode_operations;
2578 err = ext4_add_nondir(handle, dentry, inode);
2579 if (!err && IS_DIRSYNC(dir))
2580 ext4_handle_sync(handle);
2583 ext4_journal_stop(handle);
2584 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2589 static int ext4_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2592 struct inode *inode;
2593 int err, retries = 0;
2595 err = dquot_initialize(dir);
2600 inode = ext4_new_inode_start_handle(dir, mode,
2603 EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
2604 4 + EXT4_XATTR_TRANS_BLOCKS);
2605 handle = ext4_journal_current_handle();
2606 err = PTR_ERR(inode);
2607 if (!IS_ERR(inode)) {
2608 inode->i_op = &ext4_file_inode_operations;
2609 inode->i_fop = &ext4_file_operations;
2610 ext4_set_aops(inode);
2611 d_tmpfile(dentry, inode);
2612 err = ext4_orphan_add(handle, inode);
2614 goto err_unlock_inode;
2615 mark_inode_dirty(inode);
2616 unlock_new_inode(inode);
2619 ext4_journal_stop(handle);
2620 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2624 ext4_journal_stop(handle);
2625 unlock_new_inode(inode);
2629 struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode,
2630 struct ext4_dir_entry_2 *de,
2631 int blocksize, int csum_size,
2632 unsigned int parent_ino, int dotdot_real_len)
2634 de->inode = cpu_to_le32(inode->i_ino);
2636 de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
2638 strcpy(de->name, ".");
2639 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2641 de = ext4_next_entry(de, blocksize);
2642 de->inode = cpu_to_le32(parent_ino);
2644 if (!dotdot_real_len)
2645 de->rec_len = ext4_rec_len_to_disk(blocksize -
2646 (csum_size + EXT4_DIR_REC_LEN(1)),
2649 de->rec_len = ext4_rec_len_to_disk(
2650 EXT4_DIR_REC_LEN(de->name_len), blocksize);
2651 strcpy(de->name, "..");
2652 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2654 return ext4_next_entry(de, blocksize);
2657 static int ext4_init_new_dir(handle_t *handle, struct inode *dir,
2658 struct inode *inode)
2660 struct buffer_head *dir_block = NULL;
2661 struct ext4_dir_entry_2 *de;
2662 struct ext4_dir_entry_tail *t;
2663 ext4_lblk_t block = 0;
2664 unsigned int blocksize = dir->i_sb->s_blocksize;
2668 if (ext4_has_metadata_csum(dir->i_sb))
2669 csum_size = sizeof(struct ext4_dir_entry_tail);
2671 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2672 err = ext4_try_create_inline_dir(handle, dir, inode);
2673 if (err < 0 && err != -ENOSPC)
2680 dir_block = ext4_append(handle, inode, &block);
2681 if (IS_ERR(dir_block))
2682 return PTR_ERR(dir_block);
2683 de = (struct ext4_dir_entry_2 *)dir_block->b_data;
2684 ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0);
2685 set_nlink(inode, 2);
2687 t = EXT4_DIRENT_TAIL(dir_block->b_data, blocksize);
2688 initialize_dirent_tail(t, blocksize);
2691 BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
2692 err = ext4_handle_dirty_dirent_node(handle, inode, dir_block);
2695 set_buffer_verified(dir_block);
2701 static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2704 struct inode *inode;
2705 int err, credits, retries = 0;
2707 if (EXT4_DIR_LINK_MAX(dir))
2710 err = dquot_initialize(dir);
2714 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2715 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2717 inode = ext4_new_inode_start_handle(dir, S_IFDIR | mode,
2719 0, NULL, EXT4_HT_DIR, credits);
2720 handle = ext4_journal_current_handle();
2721 err = PTR_ERR(inode);
2725 inode->i_op = &ext4_dir_inode_operations;
2726 inode->i_fop = &ext4_dir_operations;
2727 err = ext4_init_new_dir(handle, dir, inode);
2729 goto out_clear_inode;
2730 err = ext4_mark_inode_dirty(handle, inode);
2732 err = ext4_add_entry(handle, dentry, inode);
2736 unlock_new_inode(inode);
2737 ext4_mark_inode_dirty(handle, inode);
2741 ext4_inc_count(handle, dir);
2742 ext4_update_dx_flag(dir);
2743 err = ext4_mark_inode_dirty(handle, dir);
2745 goto out_clear_inode;
2746 d_instantiate_new(dentry, inode);
2747 if (IS_DIRSYNC(dir))
2748 ext4_handle_sync(handle);
2752 ext4_journal_stop(handle);
2753 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2759 * routine to check that the specified directory is empty (for rmdir)
2761 bool ext4_empty_dir(struct inode *inode)
2763 unsigned int offset;
2764 struct buffer_head *bh;
2765 struct ext4_dir_entry_2 *de, *de1;
2766 struct super_block *sb;
2768 if (ext4_has_inline_data(inode)) {
2769 int has_inline_data = 1;
2772 ret = empty_inline_dir(inode, &has_inline_data);
2773 if (has_inline_data)
2778 if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2)) {
2779 EXT4_ERROR_INODE(inode, "invalid size");
2782 bh = ext4_read_dirblock(inode, 0, EITHER);
2786 de = (struct ext4_dir_entry_2 *) bh->b_data;
2787 de1 = ext4_next_entry(de, sb->s_blocksize);
2788 if (le32_to_cpu(de->inode) != inode->i_ino ||
2789 le32_to_cpu(de1->inode) == 0 ||
2790 strcmp(".", de->name) || strcmp("..", de1->name)) {
2791 ext4_warning_inode(inode, "directory missing '.' and/or '..'");
2795 offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) +
2796 ext4_rec_len_from_disk(de1->rec_len, sb->s_blocksize);
2797 de = ext4_next_entry(de1, sb->s_blocksize);
2798 while (offset < inode->i_size) {
2799 if ((void *) de >= (void *) (bh->b_data+sb->s_blocksize)) {
2800 unsigned int lblock;
2802 lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
2803 bh = ext4_read_dirblock(inode, lblock, EITHER);
2806 de = (struct ext4_dir_entry_2 *) bh->b_data;
2808 if (ext4_check_dir_entry(inode, NULL, de, bh,
2809 bh->b_data, bh->b_size, offset)) {
2810 de = (struct ext4_dir_entry_2 *)(bh->b_data +
2812 offset = (offset | (sb->s_blocksize - 1)) + 1;
2815 if (le32_to_cpu(de->inode)) {
2819 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2820 de = ext4_next_entry(de, sb->s_blocksize);
2827 * ext4_orphan_add() links an unlinked or truncated inode into a list of
2828 * such inodes, starting at the superblock, in case we crash before the
2829 * file is closed/deleted, or in case the inode truncate spans multiple
2830 * transactions and the last transaction is not recovered after a crash.
2832 * At filesystem recovery time, we walk this list deleting unlinked
2833 * inodes and truncating linked inodes in ext4_orphan_cleanup().
2835 * Orphan list manipulation functions must be called under i_mutex unless
2836 * we are just creating the inode or deleting it.
2838 int ext4_orphan_add(handle_t *handle, struct inode *inode)
2840 struct super_block *sb = inode->i_sb;
2841 struct ext4_sb_info *sbi = EXT4_SB(sb);
2842 struct ext4_iloc iloc;
2846 if (!sbi->s_journal || is_bad_inode(inode))
2849 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2850 !inode_is_locked(inode));
2852 * Exit early if inode already is on orphan list. This is a big speedup
2853 * since we don't have to contend on the global s_orphan_lock.
2855 if (!list_empty(&EXT4_I(inode)->i_orphan))
2859 * Orphan handling is only valid for files with data blocks
2860 * being truncated, or files being unlinked. Note that we either
2861 * hold i_mutex, or the inode can not be referenced from outside,
2862 * so i_nlink should not be bumped due to race
2864 J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
2865 S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
2867 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2868 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2872 err = ext4_reserve_inode_write(handle, inode, &iloc);
2876 mutex_lock(&sbi->s_orphan_lock);
2878 * Due to previous errors inode may be already a part of on-disk
2879 * orphan list. If so skip on-disk list modification.
2881 if (!NEXT_ORPHAN(inode) || NEXT_ORPHAN(inode) >
2882 (le32_to_cpu(sbi->s_es->s_inodes_count))) {
2883 /* Insert this inode at the head of the on-disk orphan list */
2884 NEXT_ORPHAN(inode) = le32_to_cpu(sbi->s_es->s_last_orphan);
2885 sbi->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
2888 list_add(&EXT4_I(inode)->i_orphan, &sbi->s_orphan);
2889 mutex_unlock(&sbi->s_orphan_lock);
2892 err = ext4_handle_dirty_super(handle, sb);
2893 rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
2898 * We have to remove inode from in-memory list if
2899 * addition to on disk orphan list failed. Stray orphan
2900 * list entries can cause panics at unmount time.
2902 mutex_lock(&sbi->s_orphan_lock);
2903 list_del_init(&EXT4_I(inode)->i_orphan);
2904 mutex_unlock(&sbi->s_orphan_lock);
2909 jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
2910 jbd_debug(4, "orphan inode %lu will point to %d\n",
2911 inode->i_ino, NEXT_ORPHAN(inode));
2913 ext4_std_error(sb, err);
2918 * ext4_orphan_del() removes an unlinked or truncated inode from the list
2919 * of such inodes stored on disk, because it is finally being cleaned up.
2921 int ext4_orphan_del(handle_t *handle, struct inode *inode)
2923 struct list_head *prev;
2924 struct ext4_inode_info *ei = EXT4_I(inode);
2925 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2927 struct ext4_iloc iloc;
2930 if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS))
2933 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2934 !inode_is_locked(inode));
2935 /* Do this quick check before taking global s_orphan_lock. */
2936 if (list_empty(&ei->i_orphan))
2940 /* Grab inode buffer early before taking global s_orphan_lock */
2941 err = ext4_reserve_inode_write(handle, inode, &iloc);
2944 mutex_lock(&sbi->s_orphan_lock);
2945 jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
2947 prev = ei->i_orphan.prev;
2948 list_del_init(&ei->i_orphan);
2950 /* If we're on an error path, we may not have a valid
2951 * transaction handle with which to update the orphan list on
2952 * disk, but we still need to remove the inode from the linked
2953 * list in memory. */
2954 if (!handle || err) {
2955 mutex_unlock(&sbi->s_orphan_lock);
2959 ino_next = NEXT_ORPHAN(inode);
2960 if (prev == &sbi->s_orphan) {
2961 jbd_debug(4, "superblock will point to %u\n", ino_next);
2962 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2963 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2965 mutex_unlock(&sbi->s_orphan_lock);
2968 sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
2969 mutex_unlock(&sbi->s_orphan_lock);
2970 err = ext4_handle_dirty_super(handle, inode->i_sb);
2972 struct ext4_iloc iloc2;
2973 struct inode *i_prev =
2974 &list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
2976 jbd_debug(4, "orphan inode %lu will point to %u\n",
2977 i_prev->i_ino, ino_next);
2978 err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
2980 mutex_unlock(&sbi->s_orphan_lock);
2983 NEXT_ORPHAN(i_prev) = ino_next;
2984 err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
2985 mutex_unlock(&sbi->s_orphan_lock);
2989 NEXT_ORPHAN(inode) = 0;
2990 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
2992 ext4_std_error(inode->i_sb, err);
3000 static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
3003 struct inode *inode;
3004 struct buffer_head *bh;
3005 struct ext4_dir_entry_2 *de;
3006 handle_t *handle = NULL;
3008 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3011 /* Initialize quotas before so that eventual writes go in
3012 * separate transaction */
3013 retval = dquot_initialize(dir);
3016 retval = dquot_initialize(d_inode(dentry));
3021 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3027 inode = d_inode(dentry);
3029 retval = -EFSCORRUPTED;
3030 if (le32_to_cpu(de->inode) != inode->i_ino)
3033 retval = -ENOTEMPTY;
3034 if (!ext4_empty_dir(inode))
3037 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3038 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3039 if (IS_ERR(handle)) {
3040 retval = PTR_ERR(handle);
3045 if (IS_DIRSYNC(dir))
3046 ext4_handle_sync(handle);
3048 retval = ext4_delete_entry(handle, dir, de, bh);
3051 if (!EXT4_DIR_LINK_EMPTY(inode))
3052 ext4_warning_inode(inode,
3053 "empty directory '%.*s' has too many links (%u)",
3054 dentry->d_name.len, dentry->d_name.name,
3056 inode_inc_iversion(inode);
3058 /* There's no need to set i_disksize: the fact that i_nlink is
3059 * zero will ensure that the right thing happens during any
3062 ext4_orphan_add(handle, inode);
3063 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
3064 ext4_mark_inode_dirty(handle, inode);
3065 ext4_dec_count(handle, dir);
3066 ext4_update_dx_flag(dir);
3067 ext4_mark_inode_dirty(handle, dir);
3069 #ifdef CONFIG_UNICODE
3070 /* VFS negative dentries are incompatible with Encoding and
3071 * Case-insensitiveness. Eventually we'll want avoid
3072 * invalidating the dentries here, alongside with returning the
3073 * negative dentries at ext4_lookup(), when it is better
3074 * supported by the VFS for the CI case.
3076 if (IS_CASEFOLDED(dir))
3077 d_invalidate(dentry);
3083 ext4_journal_stop(handle);
3087 static int ext4_unlink(struct inode *dir, struct dentry *dentry)
3090 struct inode *inode;
3091 struct buffer_head *bh;
3092 struct ext4_dir_entry_2 *de;
3093 handle_t *handle = NULL;
3095 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3098 trace_ext4_unlink_enter(dir, dentry);
3099 /* Initialize quotas before so that eventual writes go
3100 * in separate transaction */
3101 retval = dquot_initialize(dir);
3104 retval = dquot_initialize(d_inode(dentry));
3109 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3115 inode = d_inode(dentry);
3117 retval = -EFSCORRUPTED;
3118 if (le32_to_cpu(de->inode) != inode->i_ino)
3121 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3122 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3123 if (IS_ERR(handle)) {
3124 retval = PTR_ERR(handle);
3129 if (IS_DIRSYNC(dir))
3130 ext4_handle_sync(handle);
3132 if (inode->i_nlink == 0) {
3133 ext4_warning_inode(inode, "Deleting file '%.*s' with no links",
3134 dentry->d_name.len, dentry->d_name.name);
3135 set_nlink(inode, 1);
3137 retval = ext4_delete_entry(handle, dir, de, bh);
3140 dir->i_ctime = dir->i_mtime = current_time(dir);
3141 ext4_update_dx_flag(dir);
3142 ext4_mark_inode_dirty(handle, dir);
3144 if (!inode->i_nlink)
3145 ext4_orphan_add(handle, inode);
3146 inode->i_ctime = current_time(inode);
3147 ext4_mark_inode_dirty(handle, inode);
3149 #ifdef CONFIG_UNICODE
3150 /* VFS negative dentries are incompatible with Encoding and
3151 * Case-insensitiveness. Eventually we'll want avoid
3152 * invalidating the dentries here, alongside with returning the
3153 * negative dentries at ext4_lookup(), when it is better
3154 * supported by the VFS for the CI case.
3156 if (IS_CASEFOLDED(dir))
3157 d_invalidate(dentry);
3163 ext4_journal_stop(handle);
3164 trace_ext4_unlink_exit(dentry, retval);
3168 static int ext4_symlink(struct inode *dir,
3169 struct dentry *dentry, const char *symname)
3172 struct inode *inode;
3173 int err, len = strlen(symname);
3175 struct fscrypt_str disk_link;
3177 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3180 err = fscrypt_prepare_symlink(dir, symname, len, dir->i_sb->s_blocksize,
3185 err = dquot_initialize(dir);
3189 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3191 * For non-fast symlinks, we just allocate inode and put it on
3192 * orphan list in the first transaction => we need bitmap,
3193 * group descriptor, sb, inode block, quota blocks, and
3194 * possibly selinux xattr blocks.
3196 credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
3197 EXT4_XATTR_TRANS_BLOCKS;
3200 * Fast symlink. We have to add entry to directory
3201 * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
3202 * allocate new inode (bitmap, group descriptor, inode block,
3203 * quota blocks, sb is already counted in previous macros).
3205 credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3206 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3;
3209 inode = ext4_new_inode_start_handle(dir, S_IFLNK|S_IRWXUGO,
3210 &dentry->d_name, 0, NULL,
3211 EXT4_HT_DIR, credits);
3212 handle = ext4_journal_current_handle();
3213 if (IS_ERR(inode)) {
3215 ext4_journal_stop(handle);
3216 return PTR_ERR(inode);
3219 if (IS_ENCRYPTED(inode)) {
3220 err = fscrypt_encrypt_symlink(inode, symname, len, &disk_link);
3222 goto err_drop_inode;
3223 inode->i_op = &ext4_encrypted_symlink_inode_operations;
3226 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3227 if (!IS_ENCRYPTED(inode))
3228 inode->i_op = &ext4_symlink_inode_operations;
3229 inode_nohighmem(inode);
3230 ext4_set_aops(inode);
3232 * We cannot call page_symlink() with transaction started
3233 * because it calls into ext4_write_begin() which can wait
3234 * for transaction commit if we are running out of space
3235 * and thus we deadlock. So we have to stop transaction now
3236 * and restart it when symlink contents is written.
3238 * To keep fs consistent in case of crash, we have to put inode
3239 * to orphan list in the mean time.
3242 err = ext4_orphan_add(handle, inode);
3243 ext4_journal_stop(handle);
3246 goto err_drop_inode;
3247 err = __page_symlink(inode, disk_link.name, disk_link.len, 1);
3249 goto err_drop_inode;
3251 * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
3252 * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
3254 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3255 EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3256 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
3257 if (IS_ERR(handle)) {
3258 err = PTR_ERR(handle);
3260 goto err_drop_inode;
3262 set_nlink(inode, 1);
3263 err = ext4_orphan_del(handle, inode);
3265 goto err_drop_inode;
3267 /* clear the extent format for fast symlink */
3268 ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
3269 if (!IS_ENCRYPTED(inode)) {
3270 inode->i_op = &ext4_fast_symlink_inode_operations;
3271 inode->i_link = (char *)&EXT4_I(inode)->i_data;
3273 memcpy((char *)&EXT4_I(inode)->i_data, disk_link.name,
3275 inode->i_size = disk_link.len - 1;
3277 EXT4_I(inode)->i_disksize = inode->i_size;
3278 err = ext4_add_nondir(handle, dentry, inode);
3279 if (!err && IS_DIRSYNC(dir))
3280 ext4_handle_sync(handle);
3283 ext4_journal_stop(handle);
3284 goto out_free_encrypted_link;
3288 ext4_journal_stop(handle);
3290 unlock_new_inode(inode);
3292 out_free_encrypted_link:
3293 if (disk_link.name != (unsigned char *)symname)
3294 kfree(disk_link.name);
3298 static int ext4_link(struct dentry *old_dentry,
3299 struct inode *dir, struct dentry *dentry)
3302 struct inode *inode = d_inode(old_dentry);
3303 int err, retries = 0;
3305 if (inode->i_nlink >= EXT4_LINK_MAX)
3308 err = fscrypt_prepare_link(old_dentry, dir, dentry);
3312 if ((ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT)) &&
3313 (!projid_eq(EXT4_I(dir)->i_projid,
3314 EXT4_I(old_dentry->d_inode)->i_projid)))
3317 err = dquot_initialize(dir);
3322 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3323 (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3324 EXT4_INDEX_EXTRA_TRANS_BLOCKS) + 1);
3326 return PTR_ERR(handle);
3328 if (IS_DIRSYNC(dir))
3329 ext4_handle_sync(handle);
3331 inode->i_ctime = current_time(inode);
3332 ext4_inc_count(handle, inode);
3335 err = ext4_add_entry(handle, dentry, inode);
3337 ext4_mark_inode_dirty(handle, inode);
3338 /* this can happen only for tmpfile being
3339 * linked the first time
3341 if (inode->i_nlink == 1)
3342 ext4_orphan_del(handle, inode);
3343 d_instantiate(dentry, inode);
3348 ext4_journal_stop(handle);
3349 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
3356 * Try to find buffer head where contains the parent block.
3357 * It should be the inode block if it is inlined or the 1st block
3358 * if it is a normal dir.
3360 static struct buffer_head *ext4_get_first_dir_block(handle_t *handle,
3361 struct inode *inode,
3363 struct ext4_dir_entry_2 **parent_de,
3366 struct buffer_head *bh;
3368 if (!ext4_has_inline_data(inode)) {
3369 bh = ext4_read_dirblock(inode, 0, EITHER);
3371 *retval = PTR_ERR(bh);
3374 *parent_de = ext4_next_entry(
3375 (struct ext4_dir_entry_2 *)bh->b_data,
3376 inode->i_sb->s_blocksize);
3381 return ext4_get_first_inline_block(inode, parent_de, retval);
3384 struct ext4_renament {
3386 struct dentry *dentry;
3387 struct inode *inode;
3389 int dir_nlink_delta;
3391 /* entry for "dentry" */
3392 struct buffer_head *bh;
3393 struct ext4_dir_entry_2 *de;
3396 /* entry for ".." in inode if it's a directory */
3397 struct buffer_head *dir_bh;
3398 struct ext4_dir_entry_2 *parent_de;
3402 static int ext4_rename_dir_prepare(handle_t *handle, struct ext4_renament *ent)
3406 ent->dir_bh = ext4_get_first_dir_block(handle, ent->inode,
3407 &retval, &ent->parent_de,
3411 if (le32_to_cpu(ent->parent_de->inode) != ent->dir->i_ino)
3412 return -EFSCORRUPTED;
3413 BUFFER_TRACE(ent->dir_bh, "get_write_access");
3414 return ext4_journal_get_write_access(handle, ent->dir_bh);
3417 static int ext4_rename_dir_finish(handle_t *handle, struct ext4_renament *ent,
3422 ent->parent_de->inode = cpu_to_le32(dir_ino);
3423 BUFFER_TRACE(ent->dir_bh, "call ext4_handle_dirty_metadata");
3424 if (!ent->dir_inlined) {
3425 if (is_dx(ent->inode)) {
3426 retval = ext4_handle_dirty_dx_node(handle,
3430 retval = ext4_handle_dirty_dirent_node(handle,
3435 retval = ext4_mark_inode_dirty(handle, ent->inode);
3438 ext4_std_error(ent->dir->i_sb, retval);
3444 static int ext4_setent(handle_t *handle, struct ext4_renament *ent,
3445 unsigned ino, unsigned file_type)
3449 BUFFER_TRACE(ent->bh, "get write access");
3450 retval = ext4_journal_get_write_access(handle, ent->bh);
3453 ent->de->inode = cpu_to_le32(ino);
3454 if (ext4_has_feature_filetype(ent->dir->i_sb))
3455 ent->de->file_type = file_type;
3456 inode_inc_iversion(ent->dir);
3457 ent->dir->i_ctime = ent->dir->i_mtime =
3458 current_time(ent->dir);
3459 ext4_mark_inode_dirty(handle, ent->dir);
3460 BUFFER_TRACE(ent->bh, "call ext4_handle_dirty_metadata");
3461 if (!ent->inlined) {
3462 retval = ext4_handle_dirty_dirent_node(handle,
3464 if (unlikely(retval)) {
3465 ext4_std_error(ent->dir->i_sb, retval);
3475 static int ext4_find_delete_entry(handle_t *handle, struct inode *dir,
3476 const struct qstr *d_name)
3478 int retval = -ENOENT;
3479 struct buffer_head *bh;
3480 struct ext4_dir_entry_2 *de;
3482 bh = ext4_find_entry(dir, d_name, &de, NULL);
3486 retval = ext4_delete_entry(handle, dir, de, bh);
3492 static void ext4_rename_delete(handle_t *handle, struct ext4_renament *ent,
3497 * ent->de could have moved from under us during htree split, so make
3498 * sure that we are deleting the right entry. We might also be pointing
3499 * to a stale entry in the unused part of ent->bh so just checking inum
3500 * and the name isn't enough.
3502 if (le32_to_cpu(ent->de->inode) != ent->inode->i_ino ||
3503 ent->de->name_len != ent->dentry->d_name.len ||
3504 strncmp(ent->de->name, ent->dentry->d_name.name,
3505 ent->de->name_len) ||
3507 retval = ext4_find_delete_entry(handle, ent->dir,
3508 &ent->dentry->d_name);
3510 retval = ext4_delete_entry(handle, ent->dir, ent->de, ent->bh);
3511 if (retval == -ENOENT) {
3512 retval = ext4_find_delete_entry(handle, ent->dir,
3513 &ent->dentry->d_name);
3518 ext4_warning_inode(ent->dir,
3519 "Deleting old file: nlink %d, error=%d",
3520 ent->dir->i_nlink, retval);
3524 static void ext4_update_dir_count(handle_t *handle, struct ext4_renament *ent)
3526 if (ent->dir_nlink_delta) {
3527 if (ent->dir_nlink_delta == -1)
3528 ext4_dec_count(handle, ent->dir);
3530 ext4_inc_count(handle, ent->dir);
3531 ext4_mark_inode_dirty(handle, ent->dir);
3535 static struct inode *ext4_whiteout_for_rename(struct ext4_renament *ent,
3536 int credits, handle_t **h)
3543 * for inode block, sb block, group summaries,
3546 credits += (EXT4_MAXQUOTAS_TRANS_BLOCKS(ent->dir->i_sb) +
3547 EXT4_XATTR_TRANS_BLOCKS + 4);
3549 wh = ext4_new_inode_start_handle(ent->dir, S_IFCHR | WHITEOUT_MODE,
3550 &ent->dentry->d_name, 0, NULL,
3551 EXT4_HT_DIR, credits);
3553 handle = ext4_journal_current_handle();
3556 ext4_journal_stop(handle);
3557 if (PTR_ERR(wh) == -ENOSPC &&
3558 ext4_should_retry_alloc(ent->dir->i_sb, &retries))
3562 init_special_inode(wh, wh->i_mode, WHITEOUT_DEV);
3563 wh->i_op = &ext4_special_inode_operations;
3569 * Anybody can rename anything with this: the permission checks are left to the
3570 * higher-level routines.
3572 * n.b. old_{dentry,inode) refers to the source dentry/inode
3573 * while new_{dentry,inode) refers to the destination dentry/inode
3574 * This comes from rename(const char *oldpath, const char *newpath)
3576 static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
3577 struct inode *new_dir, struct dentry *new_dentry,
3580 handle_t *handle = NULL;
3581 struct ext4_renament old = {
3583 .dentry = old_dentry,
3584 .inode = d_inode(old_dentry),
3586 struct ext4_renament new = {
3588 .dentry = new_dentry,
3589 .inode = d_inode(new_dentry),
3593 struct inode *whiteout = NULL;
3597 if (new.inode && new.inode->i_nlink == 0) {
3598 EXT4_ERROR_INODE(new.inode,
3599 "target of rename is already freed");
3600 return -EFSCORRUPTED;
3603 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT)) &&
3604 (!projid_eq(EXT4_I(new_dir)->i_projid,
3605 EXT4_I(old_dentry->d_inode)->i_projid)))
3608 retval = dquot_initialize(old.dir);
3611 retval = dquot_initialize(new.dir);
3615 /* Initialize quotas before so that eventual writes go
3616 * in separate transaction */
3618 retval = dquot_initialize(new.inode);
3623 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de, NULL);
3625 return PTR_ERR(old.bh);
3627 * Check for inode number is _not_ due to possible IO errors.
3628 * We might rmdir the source, keep it as pwd of some process
3629 * and merrily kill the link to whatever was created under the
3630 * same name. Goodbye sticky bit ;-<
3633 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3636 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3637 &new.de, &new.inlined);
3638 if (IS_ERR(new.bh)) {
3639 retval = PTR_ERR(new.bh);
3649 if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC))
3650 ext4_alloc_da_blocks(old.inode);
3652 credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3653 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
3654 if (!(flags & RENAME_WHITEOUT)) {
3655 handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits);
3656 if (IS_ERR(handle)) {
3657 retval = PTR_ERR(handle);
3662 whiteout = ext4_whiteout_for_rename(&old, credits, &handle);
3663 if (IS_ERR(whiteout)) {
3664 retval = PTR_ERR(whiteout);
3670 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3671 ext4_handle_sync(handle);
3673 if (S_ISDIR(old.inode->i_mode)) {
3675 retval = -ENOTEMPTY;
3676 if (!ext4_empty_dir(new.inode))
3680 if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir))
3683 retval = ext4_rename_dir_prepare(handle, &old);
3688 * If we're renaming a file within an inline_data dir and adding or
3689 * setting the new dirent causes a conversion from inline_data to
3690 * extents/blockmap, we need to force the dirent delete code to
3691 * re-read the directory, or else we end up trying to delete a dirent
3692 * from what is now the extent tree root (or a block map).
3694 force_reread = (new.dir->i_ino == old.dir->i_ino &&
3695 ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA));
3697 old_file_type = old.de->file_type;
3700 * Do this before adding a new entry, so the old entry is sure
3701 * to be still pointing to the valid old entry.
3703 retval = ext4_setent(handle, &old, whiteout->i_ino,
3707 ext4_mark_inode_dirty(handle, whiteout);
3710 retval = ext4_add_entry(handle, new.dentry, old.inode);
3714 retval = ext4_setent(handle, &new,
3715 old.inode->i_ino, old_file_type);
3720 force_reread = !ext4_test_inode_flag(new.dir,
3721 EXT4_INODE_INLINE_DATA);
3724 * Like most other Unix systems, set the ctime for inodes on a
3727 old.inode->i_ctime = current_time(old.inode);
3728 ext4_mark_inode_dirty(handle, old.inode);
3734 ext4_rename_delete(handle, &old, force_reread);
3738 ext4_dec_count(handle, new.inode);
3739 new.inode->i_ctime = current_time(new.inode);
3741 old.dir->i_ctime = old.dir->i_mtime = current_time(old.dir);
3742 ext4_update_dx_flag(old.dir);
3744 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3748 ext4_dec_count(handle, old.dir);
3750 /* checked ext4_empty_dir above, can't have another
3751 * parent, ext4_dec_count() won't work for many-linked
3753 clear_nlink(new.inode);
3755 ext4_inc_count(handle, new.dir);
3756 ext4_update_dx_flag(new.dir);
3757 ext4_mark_inode_dirty(handle, new.dir);
3760 ext4_mark_inode_dirty(handle, old.dir);
3762 ext4_mark_inode_dirty(handle, new.inode);
3763 if (!new.inode->i_nlink)
3764 ext4_orphan_add(handle, new.inode);
3774 drop_nlink(whiteout);
3775 unlock_new_inode(whiteout);
3779 ext4_journal_stop(handle);
3783 static int ext4_cross_rename(struct inode *old_dir, struct dentry *old_dentry,
3784 struct inode *new_dir, struct dentry *new_dentry)
3786 handle_t *handle = NULL;
3787 struct ext4_renament old = {
3789 .dentry = old_dentry,
3790 .inode = d_inode(old_dentry),
3792 struct ext4_renament new = {
3794 .dentry = new_dentry,
3795 .inode = d_inode(new_dentry),
3799 struct timespec64 ctime;
3801 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT) &&
3802 !projid_eq(EXT4_I(new_dir)->i_projid,
3803 EXT4_I(old_dentry->d_inode)->i_projid)) ||
3804 (ext4_test_inode_flag(old_dir, EXT4_INODE_PROJINHERIT) &&
3805 !projid_eq(EXT4_I(old_dir)->i_projid,
3806 EXT4_I(new_dentry->d_inode)->i_projid)))
3809 retval = dquot_initialize(old.dir);
3812 retval = dquot_initialize(new.dir);
3816 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name,
3817 &old.de, &old.inlined);
3819 return PTR_ERR(old.bh);
3821 * Check for inode number is _not_ due to possible IO errors.
3822 * We might rmdir the source, keep it as pwd of some process
3823 * and merrily kill the link to whatever was created under the
3824 * same name. Goodbye sticky bit ;-<
3827 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3830 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3831 &new.de, &new.inlined);
3832 if (IS_ERR(new.bh)) {
3833 retval = PTR_ERR(new.bh);
3838 /* RENAME_EXCHANGE case: old *and* new must both exist */
3839 if (!new.bh || le32_to_cpu(new.de->inode) != new.inode->i_ino)
3842 handle = ext4_journal_start(old.dir, EXT4_HT_DIR,
3843 (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3844 2 * EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2));
3845 if (IS_ERR(handle)) {
3846 retval = PTR_ERR(handle);
3851 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3852 ext4_handle_sync(handle);
3854 if (S_ISDIR(old.inode->i_mode)) {
3856 retval = ext4_rename_dir_prepare(handle, &old);
3860 if (S_ISDIR(new.inode->i_mode)) {
3862 retval = ext4_rename_dir_prepare(handle, &new);
3868 * Other than the special case of overwriting a directory, parents'
3869 * nlink only needs to be modified if this is a cross directory rename.
3871 if (old.dir != new.dir && old.is_dir != new.is_dir) {
3872 old.dir_nlink_delta = old.is_dir ? -1 : 1;
3873 new.dir_nlink_delta = -old.dir_nlink_delta;
3875 if ((old.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(old.dir)) ||
3876 (new.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(new.dir)))
3880 new_file_type = new.de->file_type;
3881 retval = ext4_setent(handle, &new, old.inode->i_ino, old.de->file_type);
3885 retval = ext4_setent(handle, &old, new.inode->i_ino, new_file_type);
3890 * Like most other Unix systems, set the ctime for inodes on a
3893 ctime = current_time(old.inode);
3894 old.inode->i_ctime = ctime;
3895 new.inode->i_ctime = ctime;
3896 ext4_mark_inode_dirty(handle, old.inode);
3897 ext4_mark_inode_dirty(handle, new.inode);
3900 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3905 retval = ext4_rename_dir_finish(handle, &new, old.dir->i_ino);
3909 ext4_update_dir_count(handle, &old);
3910 ext4_update_dir_count(handle, &new);
3919 ext4_journal_stop(handle);
3923 static int ext4_rename2(struct inode *old_dir, struct dentry *old_dentry,
3924 struct inode *new_dir, struct dentry *new_dentry,
3929 if (unlikely(ext4_forced_shutdown(EXT4_SB(old_dir->i_sb))))
3932 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
3935 err = fscrypt_prepare_rename(old_dir, old_dentry, new_dir, new_dentry,
3940 if (flags & RENAME_EXCHANGE) {
3941 return ext4_cross_rename(old_dir, old_dentry,
3942 new_dir, new_dentry);
3945 return ext4_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
3949 * directories can handle most operations...
3951 const struct inode_operations ext4_dir_inode_operations = {
3952 .create = ext4_create,
3953 .lookup = ext4_lookup,
3955 .unlink = ext4_unlink,
3956 .symlink = ext4_symlink,
3957 .mkdir = ext4_mkdir,
3958 .rmdir = ext4_rmdir,
3959 .mknod = ext4_mknod,
3960 .tmpfile = ext4_tmpfile,
3961 .rename = ext4_rename2,
3962 .setattr = ext4_setattr,
3963 .getattr = ext4_getattr,
3964 .listxattr = ext4_listxattr,
3965 .get_acl = ext4_get_acl,
3966 .set_acl = ext4_set_acl,
3967 .fiemap = ext4_fiemap,
3970 const struct inode_operations ext4_special_inode_operations = {
3971 .setattr = ext4_setattr,
3972 .getattr = ext4_getattr,
3973 .listxattr = ext4_listxattr,
3974 .get_acl = ext4_get_acl,
3975 .set_acl = ext4_set_acl,