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>
39 #include "ext4_jbd2.h"
44 #include <trace/events/ext4.h>
46 * define how far ahead to read directories while searching them.
48 #define NAMEI_RA_CHUNKS 2
49 #define NAMEI_RA_BLOCKS 4
50 #define NAMEI_RA_SIZE (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
52 static struct buffer_head *ext4_append(handle_t *handle,
56 struct ext4_map_blocks map;
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;
70 * We're appending new directory block. Make sure the block is not
71 * allocated yet, otherwise we will end up corrupting the
74 err = ext4_map_blocks(NULL, inode, &map, 0);
78 EXT4_ERROR_INODE(inode, "Logical block already allocated");
79 return ERR_PTR(-EFSCORRUPTED);
82 bh = ext4_bread(handle, inode, *block, EXT4_GET_BLOCKS_CREATE);
85 inode->i_size += inode->i_sb->s_blocksize;
86 EXT4_I(inode)->i_disksize = inode->i_size;
87 BUFFER_TRACE(bh, "get_write_access");
88 err = ext4_journal_get_write_access(handle, bh);
91 ext4_std_error(inode->i_sb, err);
97 static int ext4_dx_csum_verify(struct inode *inode,
98 struct ext4_dir_entry *dirent);
101 * Hints to ext4_read_dirblock regarding whether we expect a directory
102 * block being read to be an index block, or a block containing
103 * directory entries (and if the latter, whether it was found via a
104 * logical block in an htree index block). This is used to control
105 * what sort of sanity checkinig ext4_read_dirblock() will do on the
106 * directory block read from the storage device. EITHER will means
107 * the caller doesn't know what kind of directory block will be read,
108 * so no specific verification will be done.
111 EITHER, INDEX, DIRENT, DIRENT_HTREE
114 #define ext4_read_dirblock(inode, block, type) \
115 __ext4_read_dirblock((inode), (block), (type), __func__, __LINE__)
117 static struct buffer_head *__ext4_read_dirblock(struct inode *inode,
119 dirblock_type_t type,
123 struct buffer_head *bh;
124 struct ext4_dir_entry *dirent;
127 bh = ext4_bread(NULL, inode, block, 0);
129 __ext4_warning(inode->i_sb, func, line,
130 "inode #%lu: lblock %lu: comm %s: "
131 "error %ld reading directory block",
132 inode->i_ino, (unsigned long)block,
133 current->comm, PTR_ERR(bh));
137 if (!bh && (type == INDEX || type == DIRENT_HTREE)) {
138 ext4_error_inode(inode, func, line, block,
139 "Directory hole found for htree %s block",
140 (type == INDEX) ? "index" : "leaf");
141 return ERR_PTR(-EFSCORRUPTED);
145 dirent = (struct ext4_dir_entry *) bh->b_data;
146 /* Determine whether or not we have an index block */
150 else if (ext4_rec_len_from_disk(dirent->rec_len,
151 inode->i_sb->s_blocksize) ==
152 inode->i_sb->s_blocksize)
155 if (!is_dx_block && type == INDEX) {
156 ext4_error_inode(inode, func, line, block,
157 "directory leaf block found instead of index block");
159 return ERR_PTR(-EFSCORRUPTED);
161 if (!ext4_has_metadata_csum(inode->i_sb) ||
166 * An empty leaf block can get mistaken for a index block; for
167 * this reason, we can only check the index checksum when the
168 * caller is sure it should be an index block.
170 if (is_dx_block && type == INDEX) {
171 if (ext4_dx_csum_verify(inode, dirent))
172 set_buffer_verified(bh);
174 ext4_error_inode(inode, func, line, block,
175 "Directory index failed checksum");
177 return ERR_PTR(-EFSBADCRC);
181 if (ext4_dirent_csum_verify(inode, dirent))
182 set_buffer_verified(bh);
184 ext4_error_inode(inode, func, line, block,
185 "Directory block failed checksum");
187 return ERR_PTR(-EFSBADCRC);
194 #define assert(test) J_ASSERT(test)
198 #define dxtrace(command) command
200 #define dxtrace(command)
224 * dx_root_info is laid out so that if it should somehow get overlaid by a
225 * dirent the two low bits of the hash version will be zero. Therefore, the
226 * hash version mod 4 should never be 0. Sincerely, the paranoia department.
231 struct fake_dirent dot;
233 struct fake_dirent dotdot;
237 __le32 reserved_zero;
239 u8 info_length; /* 8 */
244 struct dx_entry entries[0];
249 struct fake_dirent fake;
250 struct dx_entry entries[0];
256 struct buffer_head *bh;
257 struct dx_entry *entries;
269 * This goes at the end of each htree block.
273 __le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */
276 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry);
277 static void dx_set_block(struct dx_entry *entry, ext4_lblk_t value);
278 static inline unsigned dx_get_hash(struct dx_entry *entry);
279 static void dx_set_hash(struct dx_entry *entry, unsigned value);
280 static unsigned dx_get_count(struct dx_entry *entries);
281 static unsigned dx_get_limit(struct dx_entry *entries);
282 static void dx_set_count(struct dx_entry *entries, unsigned value);
283 static void dx_set_limit(struct dx_entry *entries, unsigned value);
284 static unsigned dx_root_limit(struct inode *dir, unsigned infosize);
285 static unsigned dx_node_limit(struct inode *dir);
286 static struct dx_frame *dx_probe(struct ext4_filename *fname,
288 struct dx_hash_info *hinfo,
289 struct dx_frame *frame);
290 static void dx_release(struct dx_frame *frames);
291 static int dx_make_map(struct inode *dir, struct buffer_head *bh,
292 struct dx_hash_info *hinfo,
293 struct dx_map_entry *map_tail);
294 static void dx_sort_map(struct dx_map_entry *map, unsigned count);
295 static struct ext4_dir_entry_2 *dx_move_dirents(char *from, char *to,
296 struct dx_map_entry *offsets, int count, unsigned blocksize);
297 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize);
298 static void dx_insert_block(struct dx_frame *frame,
299 u32 hash, ext4_lblk_t block);
300 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
301 struct dx_frame *frame,
302 struct dx_frame *frames,
304 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
305 struct ext4_filename *fname,
306 struct ext4_dir_entry_2 **res_dir);
307 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
308 struct inode *dir, struct inode *inode);
310 /* checksumming functions */
311 void initialize_dirent_tail(struct ext4_dir_entry_tail *t,
312 unsigned int blocksize)
314 memset(t, 0, sizeof(struct ext4_dir_entry_tail));
315 t->det_rec_len = ext4_rec_len_to_disk(
316 sizeof(struct ext4_dir_entry_tail), blocksize);
317 t->det_reserved_ft = EXT4_FT_DIR_CSUM;
320 /* Walk through a dirent block to find a checksum "dirent" at the tail */
321 static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode,
322 struct ext4_dir_entry *de)
324 struct ext4_dir_entry_tail *t;
327 struct ext4_dir_entry *d, *top;
330 top = (struct ext4_dir_entry *)(((void *)de) +
331 (EXT4_BLOCK_SIZE(inode->i_sb) -
332 sizeof(struct ext4_dir_entry_tail)));
333 while (d < top && d->rec_len)
334 d = (struct ext4_dir_entry *)(((void *)d) +
335 le16_to_cpu(d->rec_len));
340 t = (struct ext4_dir_entry_tail *)d;
342 t = EXT4_DIRENT_TAIL(de, EXT4_BLOCK_SIZE(inode->i_sb));
345 if (t->det_reserved_zero1 ||
346 le16_to_cpu(t->det_rec_len) != sizeof(struct ext4_dir_entry_tail) ||
347 t->det_reserved_zero2 ||
348 t->det_reserved_ft != EXT4_FT_DIR_CSUM)
354 static __le32 ext4_dirent_csum(struct inode *inode,
355 struct ext4_dir_entry *dirent, int size)
357 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
358 struct ext4_inode_info *ei = EXT4_I(inode);
361 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
362 return cpu_to_le32(csum);
365 #define warn_no_space_for_csum(inode) \
366 __warn_no_space_for_csum((inode), __func__, __LINE__)
368 static void __warn_no_space_for_csum(struct inode *inode, const char *func,
371 __ext4_warning_inode(inode, func, line,
372 "No space for directory leaf checksum. Please run e2fsck -D.");
375 int ext4_dirent_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent)
377 struct ext4_dir_entry_tail *t;
379 if (!ext4_has_metadata_csum(inode->i_sb))
382 t = get_dirent_tail(inode, dirent);
384 warn_no_space_for_csum(inode);
388 if (t->det_checksum != ext4_dirent_csum(inode, dirent,
389 (void *)t - (void *)dirent))
395 static void ext4_dirent_csum_set(struct inode *inode,
396 struct ext4_dir_entry *dirent)
398 struct ext4_dir_entry_tail *t;
400 if (!ext4_has_metadata_csum(inode->i_sb))
403 t = get_dirent_tail(inode, dirent);
405 warn_no_space_for_csum(inode);
409 t->det_checksum = ext4_dirent_csum(inode, dirent,
410 (void *)t - (void *)dirent);
413 int ext4_handle_dirty_dirent_node(handle_t *handle,
415 struct buffer_head *bh)
417 ext4_dirent_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
418 return ext4_handle_dirty_metadata(handle, inode, bh);
421 static struct dx_countlimit *get_dx_countlimit(struct inode *inode,
422 struct ext4_dir_entry *dirent,
425 struct ext4_dir_entry *dp;
426 struct dx_root_info *root;
429 if (le16_to_cpu(dirent->rec_len) == EXT4_BLOCK_SIZE(inode->i_sb))
431 else if (le16_to_cpu(dirent->rec_len) == 12) {
432 dp = (struct ext4_dir_entry *)(((void *)dirent) + 12);
433 if (le16_to_cpu(dp->rec_len) !=
434 EXT4_BLOCK_SIZE(inode->i_sb) - 12)
436 root = (struct dx_root_info *)(((void *)dp + 12));
437 if (root->reserved_zero ||
438 root->info_length != sizeof(struct dx_root_info))
445 *offset = count_offset;
446 return (struct dx_countlimit *)(((void *)dirent) + count_offset);
449 static __le32 ext4_dx_csum(struct inode *inode, struct ext4_dir_entry *dirent,
450 int count_offset, int count, struct dx_tail *t)
452 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
453 struct ext4_inode_info *ei = EXT4_I(inode);
456 __u32 dummy_csum = 0;
457 int offset = offsetof(struct dx_tail, dt_checksum);
459 size = count_offset + (count * sizeof(struct dx_entry));
460 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
461 csum = ext4_chksum(sbi, csum, (__u8 *)t, offset);
462 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
464 return cpu_to_le32(csum);
467 static int ext4_dx_csum_verify(struct inode *inode,
468 struct ext4_dir_entry *dirent)
470 struct dx_countlimit *c;
472 int count_offset, limit, count;
474 if (!ext4_has_metadata_csum(inode->i_sb))
477 c = get_dx_countlimit(inode, dirent, &count_offset);
479 EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
482 limit = le16_to_cpu(c->limit);
483 count = le16_to_cpu(c->count);
484 if (count_offset + (limit * sizeof(struct dx_entry)) >
485 EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
486 warn_no_space_for_csum(inode);
489 t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
491 if (t->dt_checksum != ext4_dx_csum(inode, dirent, count_offset,
497 static void ext4_dx_csum_set(struct inode *inode, struct ext4_dir_entry *dirent)
499 struct dx_countlimit *c;
501 int count_offset, limit, count;
503 if (!ext4_has_metadata_csum(inode->i_sb))
506 c = get_dx_countlimit(inode, dirent, &count_offset);
508 EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
511 limit = le16_to_cpu(c->limit);
512 count = le16_to_cpu(c->count);
513 if (count_offset + (limit * sizeof(struct dx_entry)) >
514 EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
515 warn_no_space_for_csum(inode);
518 t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
520 t->dt_checksum = ext4_dx_csum(inode, dirent, count_offset, count, t);
523 static inline int ext4_handle_dirty_dx_node(handle_t *handle,
525 struct buffer_head *bh)
527 ext4_dx_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
528 return ext4_handle_dirty_metadata(handle, inode, bh);
532 * p is at least 6 bytes before the end of page
534 static inline struct ext4_dir_entry_2 *
535 ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize)
537 return (struct ext4_dir_entry_2 *)((char *)p +
538 ext4_rec_len_from_disk(p->rec_len, blocksize));
542 * Future: use high four bits of block for coalesce-on-delete flags
543 * Mask them off for now.
546 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry)
548 return le32_to_cpu(entry->block) & 0x0fffffff;
551 static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value)
553 entry->block = cpu_to_le32(value);
556 static inline unsigned dx_get_hash(struct dx_entry *entry)
558 return le32_to_cpu(entry->hash);
561 static inline void dx_set_hash(struct dx_entry *entry, unsigned value)
563 entry->hash = cpu_to_le32(value);
566 static inline unsigned dx_get_count(struct dx_entry *entries)
568 return le16_to_cpu(((struct dx_countlimit *) entries)->count);
571 static inline unsigned dx_get_limit(struct dx_entry *entries)
573 return le16_to_cpu(((struct dx_countlimit *) entries)->limit);
576 static inline void dx_set_count(struct dx_entry *entries, unsigned value)
578 ((struct dx_countlimit *) entries)->count = cpu_to_le16(value);
581 static inline void dx_set_limit(struct dx_entry *entries, unsigned value)
583 ((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
586 static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize)
588 unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(1) -
589 EXT4_DIR_REC_LEN(2) - infosize;
591 if (ext4_has_metadata_csum(dir->i_sb))
592 entry_space -= sizeof(struct dx_tail);
593 return entry_space / sizeof(struct dx_entry);
596 static inline unsigned dx_node_limit(struct inode *dir)
598 unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0);
600 if (ext4_has_metadata_csum(dir->i_sb))
601 entry_space -= sizeof(struct dx_tail);
602 return entry_space / sizeof(struct dx_entry);
609 static void dx_show_index(char * label, struct dx_entry *entries)
611 int i, n = dx_get_count (entries);
612 printk(KERN_DEBUG "%s index", label);
613 for (i = 0; i < n; i++) {
614 printk(KERN_CONT " %x->%lu",
615 i ? dx_get_hash(entries + i) : 0,
616 (unsigned long)dx_get_block(entries + i));
618 printk(KERN_CONT "\n");
628 static struct stats dx_show_leaf(struct inode *dir,
629 struct dx_hash_info *hinfo,
630 struct ext4_dir_entry_2 *de,
631 int size, int show_names)
633 unsigned names = 0, space = 0;
634 char *base = (char *) de;
635 struct dx_hash_info h = *hinfo;
638 while ((char *) de < base + size)
644 #ifdef CONFIG_EXT4_FS_ENCRYPTION
647 struct fscrypt_str fname_crypto_str =
653 if (ext4_encrypted_inode(dir))
654 res = fscrypt_get_encryption_info(dir);
656 printk(KERN_WARNING "Error setting up"
657 " fname crypto: %d\n", res);
659 if (!fscrypt_has_encryption_key(dir)) {
660 /* Directory is not encrypted */
661 ext4fs_dirhash(de->name,
663 printk("%*.s:(U)%x.%u ", len,
665 (unsigned) ((char *) de
668 struct fscrypt_str de_name =
669 FSTR_INIT(name, len);
671 /* Directory is encrypted */
672 res = fscrypt_fname_alloc_buffer(
676 printk(KERN_WARNING "Error "
680 res = fscrypt_fname_disk_to_usr(dir,
684 printk(KERN_WARNING "Error "
685 "converting filename "
691 name = fname_crypto_str.name;
692 len = fname_crypto_str.len;
694 ext4fs_dirhash(de->name, de->name_len,
696 printk("%*.s:(E)%x.%u ", len, name,
697 h.hash, (unsigned) ((char *) de
699 fscrypt_fname_free_buffer(
703 int len = de->name_len;
704 char *name = de->name;
705 ext4fs_dirhash(de->name, de->name_len, &h);
706 printk("%*.s:%x.%u ", len, name, h.hash,
707 (unsigned) ((char *) de - base));
710 space += EXT4_DIR_REC_LEN(de->name_len);
713 de = ext4_next_entry(de, size);
715 printk(KERN_CONT "(%i)\n", names);
716 return (struct stats) { names, space, 1 };
719 struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir,
720 struct dx_entry *entries, int levels)
722 unsigned blocksize = dir->i_sb->s_blocksize;
723 unsigned count = dx_get_count(entries), names = 0, space = 0, i;
725 struct buffer_head *bh;
726 printk("%i indexed blocks...\n", count);
727 for (i = 0; i < count; i++, entries++)
729 ext4_lblk_t block = dx_get_block(entries);
730 ext4_lblk_t hash = i ? dx_get_hash(entries): 0;
731 u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash;
733 printk("%s%3u:%03u hash %8x/%8x ",levels?"":" ", i, block, hash, range);
734 bh = ext4_bread(NULL,dir, block, 0);
735 if (!bh || IS_ERR(bh))
738 dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1):
739 dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *)
740 bh->b_data, blocksize, 0);
741 names += stats.names;
742 space += stats.space;
743 bcount += stats.bcount;
747 printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n",
748 levels ? "" : " ", names, space/bcount,
749 (space/bcount)*100/blocksize);
750 return (struct stats) { names, space, bcount};
752 #endif /* DX_DEBUG */
755 * Probe for a directory leaf block to search.
757 * dx_probe can return ERR_BAD_DX_DIR, which means there was a format
758 * error in the directory index, and the caller should fall back to
759 * searching the directory normally. The callers of dx_probe **MUST**
760 * check for this error code, and make sure it never gets reflected
763 static struct dx_frame *
764 dx_probe(struct ext4_filename *fname, struct inode *dir,
765 struct dx_hash_info *hinfo, struct dx_frame *frame_in)
767 unsigned count, indirect, level, i;
768 struct dx_entry *at, *entries, *p, *q, *m;
769 struct dx_root *root;
770 struct dx_frame *frame = frame_in;
771 struct dx_frame *ret_err = ERR_PTR(ERR_BAD_DX_DIR);
774 ext4_lblk_t blocks[EXT4_HTREE_LEVEL];
776 memset(frame_in, 0, EXT4_HTREE_LEVEL * sizeof(frame_in[0]));
777 frame->bh = ext4_read_dirblock(dir, 0, INDEX);
778 if (IS_ERR(frame->bh))
779 return (struct dx_frame *) frame->bh;
781 root = (struct dx_root *) frame->bh->b_data;
782 if (root->info.hash_version != DX_HASH_TEA &&
783 root->info.hash_version != DX_HASH_HALF_MD4 &&
784 root->info.hash_version != DX_HASH_LEGACY) {
785 ext4_warning_inode(dir, "Unrecognised inode hash code %u",
786 root->info.hash_version);
790 hinfo = &fname->hinfo;
791 hinfo->hash_version = root->info.hash_version;
792 if (hinfo->hash_version <= DX_HASH_TEA)
793 hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
794 hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed;
795 if (fname && fname_name(fname))
796 ext4fs_dirhash(fname_name(fname), fname_len(fname), hinfo);
799 if (root->info.unused_flags & 1) {
800 ext4_warning_inode(dir, "Unimplemented hash flags: %#06x",
801 root->info.unused_flags);
805 indirect = root->info.indirect_levels;
806 if (indirect >= ext4_dir_htree_level(dir->i_sb)) {
807 ext4_warning(dir->i_sb,
808 "Directory (ino: %lu) htree depth %#06x exceed"
809 "supported value", dir->i_ino,
810 ext4_dir_htree_level(dir->i_sb));
811 if (ext4_dir_htree_level(dir->i_sb) < EXT4_HTREE_LEVEL) {
812 ext4_warning(dir->i_sb, "Enable large directory "
813 "feature to access it");
818 entries = (struct dx_entry *)(((char *)&root->info) +
819 root->info.info_length);
821 if (dx_get_limit(entries) != dx_root_limit(dir,
822 root->info.info_length)) {
823 ext4_warning_inode(dir, "dx entry: limit %u != root limit %u",
824 dx_get_limit(entries),
825 dx_root_limit(dir, root->info.info_length));
829 dxtrace(printk("Look up %x", hash));
833 count = dx_get_count(entries);
834 if (!count || count > dx_get_limit(entries)) {
835 ext4_warning_inode(dir,
836 "dx entry: count %u beyond limit %u",
837 count, dx_get_limit(entries));
842 q = entries + count - 1;
845 dxtrace(printk(KERN_CONT "."));
846 if (dx_get_hash(m) > hash)
852 if (0) { // linear search cross check
853 unsigned n = count - 1;
857 dxtrace(printk(KERN_CONT ","));
858 if (dx_get_hash(++at) > hash)
864 assert (at == p - 1);
868 dxtrace(printk(KERN_CONT " %x->%u\n",
869 at == entries ? 0 : dx_get_hash(at),
871 frame->entries = entries;
874 block = dx_get_block(at);
875 for (i = 0; i <= level; i++) {
876 if (blocks[i] == block) {
877 ext4_warning_inode(dir,
878 "dx entry: tree cycle block %u points back to block %u",
879 blocks[level], block);
883 if (++level > indirect)
885 blocks[level] = block;
887 frame->bh = ext4_read_dirblock(dir, block, INDEX);
888 if (IS_ERR(frame->bh)) {
889 ret_err = (struct dx_frame *) frame->bh;
894 entries = ((struct dx_node *) frame->bh->b_data)->entries;
896 if (dx_get_limit(entries) != dx_node_limit(dir)) {
897 ext4_warning_inode(dir,
898 "dx entry: limit %u != node limit %u",
899 dx_get_limit(entries), dx_node_limit(dir));
904 while (frame >= frame_in) {
909 if (ret_err == ERR_PTR(ERR_BAD_DX_DIR))
910 ext4_warning_inode(dir,
911 "Corrupt directory, running e2fsck is recommended");
915 static void dx_release(struct dx_frame *frames)
917 struct dx_root_info *info;
919 unsigned int indirect_levels;
921 if (frames[0].bh == NULL)
924 info = &((struct dx_root *)frames[0].bh->b_data)->info;
925 /* save local copy, "info" may be freed after brelse() */
926 indirect_levels = info->indirect_levels;
927 for (i = 0; i <= indirect_levels; i++) {
928 if (frames[i].bh == NULL)
930 brelse(frames[i].bh);
936 * This function increments the frame pointer to search the next leaf
937 * block, and reads in the necessary intervening nodes if the search
938 * should be necessary. Whether or not the search is necessary is
939 * controlled by the hash parameter. If the hash value is even, then
940 * the search is only continued if the next block starts with that
941 * hash value. This is used if we are searching for a specific file.
943 * If the hash value is HASH_NB_ALWAYS, then always go to the next block.
945 * This function returns 1 if the caller should continue to search,
946 * or 0 if it should not. If there is an error reading one of the
947 * index blocks, it will a negative error code.
949 * If start_hash is non-null, it will be filled in with the starting
950 * hash of the next page.
952 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
953 struct dx_frame *frame,
954 struct dx_frame *frames,
958 struct buffer_head *bh;
964 * Find the next leaf page by incrementing the frame pointer.
965 * If we run out of entries in the interior node, loop around and
966 * increment pointer in the parent node. When we break out of
967 * this loop, num_frames indicates the number of interior
968 * nodes need to be read.
971 if (++(p->at) < p->entries + dx_get_count(p->entries))
980 * If the hash is 1, then continue only if the next page has a
981 * continuation hash of any value. This is used for readdir
982 * handling. Otherwise, check to see if the hash matches the
983 * desired contiuation hash. If it doesn't, return since
984 * there's no point to read in the successive index pages.
986 bhash = dx_get_hash(p->at);
989 if ((hash & 1) == 0) {
990 if ((bhash & ~1) != hash)
994 * If the hash is HASH_NB_ALWAYS, we always go to the next
995 * block so no check is necessary
997 while (num_frames--) {
998 bh = ext4_read_dirblock(dir, dx_get_block(p->at), INDEX);
1004 p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
1011 * This function fills a red-black tree with information from a
1012 * directory block. It returns the number directory entries loaded
1013 * into the tree. If there is an error it is returned in err.
1015 static int htree_dirblock_to_tree(struct file *dir_file,
1016 struct inode *dir, ext4_lblk_t block,
1017 struct dx_hash_info *hinfo,
1018 __u32 start_hash, __u32 start_minor_hash)
1020 struct buffer_head *bh;
1021 struct ext4_dir_entry_2 *de, *top;
1022 int err = 0, count = 0;
1023 struct fscrypt_str fname_crypto_str = FSTR_INIT(NULL, 0), tmp_str;
1025 dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n",
1026 (unsigned long)block));
1027 bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
1031 de = (struct ext4_dir_entry_2 *) bh->b_data;
1032 top = (struct ext4_dir_entry_2 *) ((char *) de +
1033 dir->i_sb->s_blocksize -
1034 EXT4_DIR_REC_LEN(0));
1035 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1036 /* Check if the directory is encrypted */
1037 if (ext4_encrypted_inode(dir)) {
1038 err = fscrypt_get_encryption_info(dir);
1043 err = fscrypt_fname_alloc_buffer(dir, EXT4_NAME_LEN,
1051 for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) {
1052 if (ext4_check_dir_entry(dir, NULL, de, bh,
1053 bh->b_data, bh->b_size,
1054 (block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb))
1055 + ((char *)de - bh->b_data))) {
1056 /* silently ignore the rest of the block */
1059 ext4fs_dirhash(de->name, de->name_len, hinfo);
1060 if ((hinfo->hash < start_hash) ||
1061 ((hinfo->hash == start_hash) &&
1062 (hinfo->minor_hash < start_minor_hash)))
1066 if (!ext4_encrypted_inode(dir)) {
1067 tmp_str.name = de->name;
1068 tmp_str.len = de->name_len;
1069 err = ext4_htree_store_dirent(dir_file,
1070 hinfo->hash, hinfo->minor_hash, de,
1073 int save_len = fname_crypto_str.len;
1074 struct fscrypt_str de_name = FSTR_INIT(de->name,
1077 /* Directory is encrypted */
1078 err = fscrypt_fname_disk_to_usr(dir, hinfo->hash,
1079 hinfo->minor_hash, &de_name,
1085 err = ext4_htree_store_dirent(dir_file,
1086 hinfo->hash, hinfo->minor_hash, de,
1088 fname_crypto_str.len = save_len;
1098 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1099 fscrypt_fname_free_buffer(&fname_crypto_str);
1106 * This function fills a red-black tree with information from a
1107 * directory. We start scanning the directory in hash order, starting
1108 * at start_hash and start_minor_hash.
1110 * This function returns the number of entries inserted into the tree,
1111 * or a negative error code.
1113 int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
1114 __u32 start_minor_hash, __u32 *next_hash)
1116 struct dx_hash_info hinfo;
1117 struct ext4_dir_entry_2 *de;
1118 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1124 struct fscrypt_str tmp_str;
1126 dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n",
1127 start_hash, start_minor_hash));
1128 dir = file_inode(dir_file);
1129 if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) {
1130 hinfo.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
1131 if (hinfo.hash_version <= DX_HASH_TEA)
1132 hinfo.hash_version +=
1133 EXT4_SB(dir->i_sb)->s_hash_unsigned;
1134 hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
1135 if (ext4_has_inline_data(dir)) {
1136 int has_inline_data = 1;
1137 count = htree_inlinedir_to_tree(dir_file, dir, 0,
1141 if (has_inline_data) {
1146 count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo,
1147 start_hash, start_minor_hash);
1151 hinfo.hash = start_hash;
1152 hinfo.minor_hash = 0;
1153 frame = dx_probe(NULL, dir, &hinfo, frames);
1155 return PTR_ERR(frame);
1157 /* Add '.' and '..' from the htree header */
1158 if (!start_hash && !start_minor_hash) {
1159 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1160 tmp_str.name = de->name;
1161 tmp_str.len = de->name_len;
1162 err = ext4_htree_store_dirent(dir_file, 0, 0,
1168 if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) {
1169 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1170 de = ext4_next_entry(de, dir->i_sb->s_blocksize);
1171 tmp_str.name = de->name;
1172 tmp_str.len = de->name_len;
1173 err = ext4_htree_store_dirent(dir_file, 2, 0,
1181 if (fatal_signal_pending(current)) {
1186 block = dx_get_block(frame->at);
1187 ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
1188 start_hash, start_minor_hash);
1195 ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS,
1196 frame, frames, &hashval);
1197 *next_hash = hashval;
1203 * Stop if: (a) there are no more entries, or
1204 * (b) we have inserted at least one entry and the
1205 * next hash value is not a continuation
1208 (count && ((hashval & 1) == 0)))
1212 dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, "
1213 "next hash: %x\n", count, *next_hash));
1220 static inline int search_dirblock(struct buffer_head *bh,
1222 struct ext4_filename *fname,
1223 unsigned int offset,
1224 struct ext4_dir_entry_2 **res_dir)
1226 return ext4_search_dir(bh, bh->b_data, dir->i_sb->s_blocksize, dir,
1227 fname, offset, res_dir);
1231 * Directory block splitting, compacting
1235 * Create map of hash values, offsets, and sizes, stored at end of block.
1236 * Returns number of entries mapped.
1238 static int dx_make_map(struct inode *dir, struct buffer_head *bh,
1239 struct dx_hash_info *hinfo,
1240 struct dx_map_entry *map_tail)
1243 struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)bh->b_data;
1244 unsigned int buflen = bh->b_size;
1245 char *base = bh->b_data;
1246 struct dx_hash_info h = *hinfo;
1248 if (ext4_has_metadata_csum(dir->i_sb))
1249 buflen -= sizeof(struct ext4_dir_entry_tail);
1251 while ((char *) de < base + buflen) {
1252 if (ext4_check_dir_entry(dir, NULL, de, bh, base, buflen,
1253 ((char *)de) - base))
1254 return -EFSCORRUPTED;
1255 if (de->name_len && de->inode) {
1256 ext4fs_dirhash(de->name, de->name_len, &h);
1258 map_tail->hash = h.hash;
1259 map_tail->offs = ((char *) de - base)>>2;
1260 map_tail->size = le16_to_cpu(de->rec_len);
1264 de = ext4_next_entry(de, dir->i_sb->s_blocksize);
1269 /* Sort map by hash value */
1270 static void dx_sort_map (struct dx_map_entry *map, unsigned count)
1272 struct dx_map_entry *p, *q, *top = map + count - 1;
1274 /* Combsort until bubble sort doesn't suck */
1276 count = count*10/13;
1277 if (count - 9 < 2) /* 9, 10 -> 11 */
1279 for (p = top, q = p - count; q >= map; p--, q--)
1280 if (p->hash < q->hash)
1283 /* Garden variety bubble sort */
1288 if (q[1].hash >= q[0].hash)
1296 static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block)
1298 struct dx_entry *entries = frame->entries;
1299 struct dx_entry *old = frame->at, *new = old + 1;
1300 int count = dx_get_count(entries);
1302 assert(count < dx_get_limit(entries));
1303 assert(old < entries + count);
1304 memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
1305 dx_set_hash(new, hash);
1306 dx_set_block(new, block);
1307 dx_set_count(entries, count + 1);
1311 * Test whether a directory entry matches the filename being searched for.
1313 * Return: %true if the directory entry matches, otherwise %false.
1315 static inline bool ext4_match(const struct ext4_filename *fname,
1316 const struct ext4_dir_entry_2 *de)
1318 struct fscrypt_name f;
1323 f.usr_fname = fname->usr_fname;
1324 f.disk_name = fname->disk_name;
1325 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1326 f.crypto_buf = fname->crypto_buf;
1328 return fscrypt_match_name(&f, de->name, de->name_len);
1332 * Returns 0 if not found, -1 on failure, and 1 on success
1334 int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size,
1335 struct inode *dir, struct ext4_filename *fname,
1336 unsigned int offset, struct ext4_dir_entry_2 **res_dir)
1338 struct ext4_dir_entry_2 * de;
1342 de = (struct ext4_dir_entry_2 *)search_buf;
1343 dlimit = search_buf + buf_size;
1344 while ((char *) de < dlimit) {
1345 /* this code is executed quadratically often */
1346 /* do minimal checking `by hand' */
1347 if ((char *) de + de->name_len <= dlimit &&
1348 ext4_match(fname, de)) {
1349 /* found a match - just to be sure, do
1351 if (ext4_check_dir_entry(dir, NULL, de, bh, search_buf,
1357 /* prevent looping on a bad block */
1358 de_len = ext4_rec_len_from_disk(de->rec_len,
1359 dir->i_sb->s_blocksize);
1363 de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
1368 static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block,
1369 struct ext4_dir_entry *de)
1371 struct super_block *sb = dir->i_sb;
1377 if (de->inode == 0 &&
1378 ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) ==
1385 * __ext4_find_entry()
1387 * finds an entry in the specified directory with the wanted name. It
1388 * returns the cache buffer in which the entry was found, and the entry
1389 * itself (as a parameter - res_dir). It does NOT read the inode of the
1390 * entry - you'll have to do that yourself if you want to.
1392 * The returned buffer_head has ->b_count elevated. The caller is expected
1393 * to brelse() it when appropriate.
1395 static struct buffer_head *__ext4_find_entry(struct inode *dir,
1396 struct ext4_filename *fname,
1397 struct ext4_dir_entry_2 **res_dir,
1400 struct super_block *sb;
1401 struct buffer_head *bh_use[NAMEI_RA_SIZE];
1402 struct buffer_head *bh, *ret = NULL;
1403 ext4_lblk_t start, block;
1404 const u8 *name = fname->usr_fname->name;
1405 size_t ra_max = 0; /* Number of bh's in the readahead
1407 size_t ra_ptr = 0; /* Current index into readahead
1409 ext4_lblk_t nblocks;
1410 int i, namelen, retval;
1414 namelen = fname->usr_fname->len;
1415 if (namelen > EXT4_NAME_LEN)
1418 if (ext4_has_inline_data(dir)) {
1419 int has_inline_data = 1;
1420 ret = ext4_find_inline_entry(dir, fname, res_dir,
1423 *inlined = has_inline_data;
1424 if (has_inline_data)
1425 goto cleanup_and_exit;
1428 if ((namelen <= 2) && (name[0] == '.') &&
1429 (name[1] == '.' || name[1] == '\0')) {
1431 * "." or ".." will only be in the first block
1432 * NFS may look up ".."; "." should be handled by the VFS
1439 ret = ext4_dx_find_entry(dir, fname, res_dir);
1441 * On success, or if the error was file not found,
1442 * return. Otherwise, fall back to doing a search the
1443 * old fashioned way.
1445 if (!IS_ERR(ret) || PTR_ERR(ret) != ERR_BAD_DX_DIR)
1446 goto cleanup_and_exit;
1447 dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
1451 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1454 goto cleanup_and_exit;
1456 start = EXT4_I(dir)->i_dir_start_lookup;
1457 if (start >= nblocks)
1463 * We deal with the read-ahead logic here.
1466 if (ra_ptr >= ra_max) {
1467 /* Refill the readahead buffer */
1470 ra_max = start - block;
1472 ra_max = nblocks - block;
1473 ra_max = min(ra_max, ARRAY_SIZE(bh_use));
1474 retval = ext4_bread_batch(dir, block, ra_max,
1475 false /* wait */, bh_use);
1477 ret = ERR_PTR(retval);
1479 goto cleanup_and_exit;
1482 if ((bh = bh_use[ra_ptr++]) == NULL)
1485 if (!buffer_uptodate(bh)) {
1486 EXT4_ERROR_INODE(dir, "reading directory lblock %lu",
1487 (unsigned long) block);
1489 ret = ERR_PTR(-EIO);
1490 goto cleanup_and_exit;
1492 if (!buffer_verified(bh) &&
1493 !is_dx_internal_node(dir, block,
1494 (struct ext4_dir_entry *)bh->b_data) &&
1495 !ext4_dirent_csum_verify(dir,
1496 (struct ext4_dir_entry *)bh->b_data)) {
1497 EXT4_ERROR_INODE(dir, "checksumming directory "
1498 "block %lu", (unsigned long)block);
1500 ret = ERR_PTR(-EFSBADCRC);
1501 goto cleanup_and_exit;
1503 set_buffer_verified(bh);
1504 i = search_dirblock(bh, dir, fname,
1505 block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
1507 EXT4_I(dir)->i_dir_start_lookup = block;
1509 goto cleanup_and_exit;
1513 goto cleanup_and_exit;
1516 if (++block >= nblocks)
1518 } while (block != start);
1521 * If the directory has grown while we were searching, then
1522 * search the last part of the directory before giving up.
1525 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1526 if (block < nblocks) {
1532 /* Clean up the read-ahead blocks */
1533 for (; ra_ptr < ra_max; ra_ptr++)
1534 brelse(bh_use[ra_ptr]);
1538 static struct buffer_head *ext4_find_entry(struct inode *dir,
1539 const struct qstr *d_name,
1540 struct ext4_dir_entry_2 **res_dir,
1544 struct ext4_filename fname;
1545 struct buffer_head *bh;
1547 err = ext4_fname_setup_filename(dir, d_name, 1, &fname);
1551 return ERR_PTR(err);
1553 bh = __ext4_find_entry(dir, &fname, res_dir, inlined);
1555 ext4_fname_free_filename(&fname);
1559 static struct buffer_head *ext4_lookup_entry(struct inode *dir,
1560 struct dentry *dentry,
1561 struct ext4_dir_entry_2 **res_dir)
1564 struct ext4_filename fname;
1565 struct buffer_head *bh;
1567 err = ext4_fname_prepare_lookup(dir, dentry, &fname);
1571 return ERR_PTR(err);
1573 bh = __ext4_find_entry(dir, &fname, res_dir, NULL);
1575 ext4_fname_free_filename(&fname);
1579 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
1580 struct ext4_filename *fname,
1581 struct ext4_dir_entry_2 **res_dir)
1583 struct super_block * sb = dir->i_sb;
1584 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1585 struct buffer_head *bh;
1589 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1592 frame = dx_probe(fname, dir, NULL, frames);
1594 return (struct buffer_head *) frame;
1596 block = dx_get_block(frame->at);
1597 bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
1601 retval = search_dirblock(bh, dir, fname,
1602 block << EXT4_BLOCK_SIZE_BITS(sb),
1608 bh = ERR_PTR(ERR_BAD_DX_DIR);
1612 /* Check to see if we should continue to search */
1613 retval = ext4_htree_next_block(dir, fname->hinfo.hash, frame,
1616 ext4_warning_inode(dir,
1617 "error %d reading directory index block",
1619 bh = ERR_PTR(retval);
1622 } while (retval == 1);
1626 dxtrace(printk(KERN_DEBUG "%s not found\n", fname->usr_fname->name));
1632 static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
1634 struct inode *inode;
1635 struct ext4_dir_entry_2 *de;
1636 struct buffer_head *bh;
1638 if (dentry->d_name.len > EXT4_NAME_LEN)
1639 return ERR_PTR(-ENAMETOOLONG);
1641 bh = ext4_lookup_entry(dir, dentry, &de);
1643 return (struct dentry *) bh;
1646 __u32 ino = le32_to_cpu(de->inode);
1648 if (!ext4_valid_inum(dir->i_sb, ino)) {
1649 EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
1650 return ERR_PTR(-EFSCORRUPTED);
1652 if (unlikely(ino == dir->i_ino)) {
1653 EXT4_ERROR_INODE(dir, "'%pd' linked to parent dir",
1655 return ERR_PTR(-EFSCORRUPTED);
1657 inode = ext4_iget(dir->i_sb, ino, EXT4_IGET_NORMAL);
1658 if (inode == ERR_PTR(-ESTALE)) {
1659 EXT4_ERROR_INODE(dir,
1660 "deleted inode referenced: %u",
1662 return ERR_PTR(-EFSCORRUPTED);
1664 if (!IS_ERR(inode) && ext4_encrypted_inode(dir) &&
1665 (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
1666 !fscrypt_has_permitted_context(dir, inode)) {
1667 ext4_warning(inode->i_sb,
1668 "Inconsistent encryption contexts: %lu/%lu",
1669 dir->i_ino, inode->i_ino);
1671 return ERR_PTR(-EPERM);
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 (struct dentry *) 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;
1763 struct buffer_head *bh2;
1764 ext4_lblk_t newblock;
1766 struct dx_map_entry *map;
1767 char *data1 = (*bh)->b_data, *data2;
1768 unsigned split, move, size;
1769 struct ext4_dir_entry_2 *de = NULL, *de2;
1770 struct ext4_dir_entry_tail *t;
1774 if (ext4_has_metadata_csum(dir->i_sb))
1775 csum_size = sizeof(struct ext4_dir_entry_tail);
1777 bh2 = ext4_append(handle, dir, &newblock);
1781 return (struct ext4_dir_entry_2 *) bh2;
1784 BUFFER_TRACE(*bh, "get_write_access");
1785 err = ext4_journal_get_write_access(handle, *bh);
1789 BUFFER_TRACE(frame->bh, "get_write_access");
1790 err = ext4_journal_get_write_access(handle, frame->bh);
1794 data2 = bh2->b_data;
1796 /* create map in the end of data2 block */
1797 map = (struct dx_map_entry *) (data2 + blocksize);
1798 count = dx_make_map(dir, *bh, hinfo, map);
1804 dx_sort_map(map, count);
1805 /* Ensure that neither split block is over half full */
1808 for (i = count-1; i >= 0; i--) {
1809 /* is more than half of this entry in 2nd half of the block? */
1810 if (size + map[i].size/2 > blocksize/2)
1812 size += map[i].size;
1816 * map index at which we will split
1818 * If the sum of active entries didn't exceed half the block size, just
1819 * split it in half by count; each resulting block will have at least
1820 * half the space free.
1823 split = count - move;
1827 hash2 = map[split].hash;
1828 continued = hash2 == map[split - 1].hash;
1829 dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
1830 (unsigned long)dx_get_block(frame->at),
1831 hash2, split, count-split));
1833 /* Fancy dance to stay within two buffers */
1834 de2 = dx_move_dirents(data1, data2, map + split, count - split,
1836 de = dx_pack_dirents(data1, blocksize);
1837 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
1840 de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
1844 t = EXT4_DIRENT_TAIL(data2, blocksize);
1845 initialize_dirent_tail(t, blocksize);
1847 t = EXT4_DIRENT_TAIL(data1, blocksize);
1848 initialize_dirent_tail(t, blocksize);
1851 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,
1853 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,
1856 /* Which block gets the new entry? */
1857 if (hinfo->hash >= hash2) {
1861 dx_insert_block(frame, hash2 + continued, newblock);
1862 err = ext4_handle_dirty_dirent_node(handle, dir, bh2);
1865 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
1869 dxtrace(dx_show_index("frame", frame->entries));
1876 ext4_std_error(dir->i_sb, err);
1877 return ERR_PTR(err);
1880 int ext4_find_dest_de(struct inode *dir, struct inode *inode,
1881 struct buffer_head *bh,
1882 void *buf, int buf_size,
1883 struct ext4_filename *fname,
1884 struct ext4_dir_entry_2 **dest_de)
1886 struct ext4_dir_entry_2 *de;
1887 unsigned short reclen = EXT4_DIR_REC_LEN(fname_len(fname));
1889 unsigned int offset = 0;
1892 de = (struct ext4_dir_entry_2 *)buf;
1893 top = buf + buf_size - reclen;
1894 while ((char *) de <= top) {
1895 if (ext4_check_dir_entry(dir, NULL, de, bh,
1896 buf, buf_size, offset))
1897 return -EFSCORRUPTED;
1898 if (ext4_match(fname, de))
1900 nlen = EXT4_DIR_REC_LEN(de->name_len);
1901 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1902 if ((de->inode ? rlen - nlen : rlen) >= reclen)
1904 de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
1907 if ((char *) de > top)
1914 void ext4_insert_dentry(struct inode *inode,
1915 struct ext4_dir_entry_2 *de,
1917 struct ext4_filename *fname)
1922 nlen = EXT4_DIR_REC_LEN(de->name_len);
1923 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1925 struct ext4_dir_entry_2 *de1 =
1926 (struct ext4_dir_entry_2 *)((char *)de + nlen);
1927 de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size);
1928 de->rec_len = ext4_rec_len_to_disk(nlen, buf_size);
1931 de->file_type = EXT4_FT_UNKNOWN;
1932 de->inode = cpu_to_le32(inode->i_ino);
1933 ext4_set_de_type(inode->i_sb, de, inode->i_mode);
1934 de->name_len = fname_len(fname);
1935 memcpy(de->name, fname_name(fname), fname_len(fname));
1939 * Add a new entry into a directory (leaf) block. If de is non-NULL,
1940 * it points to a directory entry which is guaranteed to be large
1941 * enough for new directory entry. If de is NULL, then
1942 * add_dirent_to_buf will attempt search the directory block for
1943 * space. It will return -ENOSPC if no space is available, and -EIO
1944 * and -EEXIST if directory entry already exists.
1946 static int add_dirent_to_buf(handle_t *handle, struct ext4_filename *fname,
1948 struct inode *inode, struct ext4_dir_entry_2 *de,
1949 struct buffer_head *bh)
1951 unsigned int blocksize = dir->i_sb->s_blocksize;
1955 if (ext4_has_metadata_csum(inode->i_sb))
1956 csum_size = sizeof(struct ext4_dir_entry_tail);
1959 err = ext4_find_dest_de(dir, inode, bh, bh->b_data,
1960 blocksize - csum_size, fname, &de);
1964 BUFFER_TRACE(bh, "get_write_access");
1965 err = ext4_journal_get_write_access(handle, bh);
1967 ext4_std_error(dir->i_sb, err);
1971 /* By now the buffer is marked for journaling */
1972 ext4_insert_dentry(inode, de, blocksize, fname);
1975 * XXX shouldn't update any times until successful
1976 * completion of syscall, but too many callers depend
1979 * XXX similarly, too many callers depend on
1980 * ext4_new_inode() setting the times, but error
1981 * recovery deletes the inode, so the worst that can
1982 * happen is that the times are slightly out of date
1983 * and/or different from the directory change time.
1985 dir->i_mtime = dir->i_ctime = current_time(dir);
1986 ext4_update_dx_flag(dir);
1987 inode_inc_iversion(dir);
1988 ext4_mark_inode_dirty(handle, dir);
1989 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1990 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
1992 ext4_std_error(dir->i_sb, err);
1997 * This converts a one block unindexed directory to a 3 block indexed
1998 * directory, and adds the dentry to the indexed directory.
2000 static int make_indexed_dir(handle_t *handle, struct ext4_filename *fname,
2002 struct inode *inode, struct buffer_head *bh)
2004 struct buffer_head *bh2;
2005 struct dx_root *root;
2006 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
2007 struct dx_entry *entries;
2008 struct ext4_dir_entry_2 *de, *de2;
2009 struct ext4_dir_entry_tail *t;
2015 struct fake_dirent *fde;
2018 if (ext4_has_metadata_csum(inode->i_sb))
2019 csum_size = sizeof(struct ext4_dir_entry_tail);
2021 blocksize = dir->i_sb->s_blocksize;
2022 dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
2023 BUFFER_TRACE(bh, "get_write_access");
2024 retval = ext4_journal_get_write_access(handle, bh);
2026 ext4_std_error(dir->i_sb, retval);
2030 root = (struct dx_root *) bh->b_data;
2032 /* The 0th block becomes the root, move the dirents out */
2033 fde = &root->dotdot;
2034 de = (struct ext4_dir_entry_2 *)((char *)fde +
2035 ext4_rec_len_from_disk(fde->rec_len, blocksize));
2036 if ((char *) de >= (((char *) root) + blocksize)) {
2037 EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
2039 return -EFSCORRUPTED;
2041 len = ((char *) root) + (blocksize - csum_size) - (char *) de;
2043 /* Allocate new block for the 0th block's dirents */
2044 bh2 = ext4_append(handle, dir, &block);
2047 return PTR_ERR(bh2);
2049 ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
2050 data1 = bh2->b_data;
2052 memcpy (data1, de, len);
2053 de = (struct ext4_dir_entry_2 *) data1;
2055 while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top)
2057 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
2062 t = EXT4_DIRENT_TAIL(data1, blocksize);
2063 initialize_dirent_tail(t, blocksize);
2066 /* Initialize the root; the dot dirents already exist */
2067 de = (struct ext4_dir_entry_2 *) (&root->dotdot);
2068 de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
2070 memset (&root->info, 0, sizeof(root->info));
2071 root->info.info_length = sizeof(root->info);
2072 root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
2073 entries = root->entries;
2074 dx_set_block(entries, 1);
2075 dx_set_count(entries, 1);
2076 dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
2078 /* Initialize as for dx_probe */
2079 fname->hinfo.hash_version = root->info.hash_version;
2080 if (fname->hinfo.hash_version <= DX_HASH_TEA)
2081 fname->hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
2082 fname->hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
2083 ext4fs_dirhash(fname_name(fname), fname_len(fname), &fname->hinfo);
2085 memset(frames, 0, sizeof(frames));
2087 frame->entries = entries;
2088 frame->at = entries;
2091 retval = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2094 retval = ext4_handle_dirty_dirent_node(handle, dir, bh2);
2098 de = do_split(handle,dir, &bh2, frame, &fname->hinfo);
2100 retval = PTR_ERR(de);
2104 retval = add_dirent_to_buf(handle, fname, dir, inode, de, bh2);
2107 * Even if the block split failed, we have to properly write
2108 * out all the changes we did so far. Otherwise we can end up
2109 * with corrupted filesystem.
2112 ext4_mark_inode_dirty(handle, dir);
2121 * adds a file entry to the specified directory, using the same
2122 * semantics as ext4_find_entry(). It returns NULL if it failed.
2124 * NOTE!! The inode part of 'de' is left at 0 - which means you
2125 * may not sleep between calling this and putting something into
2126 * the entry, as someone else might have used it while you slept.
2128 static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
2129 struct inode *inode)
2131 struct inode *dir = d_inode(dentry->d_parent);
2132 struct buffer_head *bh = NULL;
2133 struct ext4_dir_entry_2 *de;
2134 struct ext4_dir_entry_tail *t;
2135 struct super_block *sb;
2136 struct ext4_filename fname;
2140 ext4_lblk_t block, blocks;
2143 if (ext4_has_metadata_csum(inode->i_sb))
2144 csum_size = sizeof(struct ext4_dir_entry_tail);
2147 blocksize = sb->s_blocksize;
2148 if (!dentry->d_name.len)
2151 if (fscrypt_is_nokey_name(dentry))
2154 retval = ext4_fname_setup_filename(dir, &dentry->d_name, 0, &fname);
2158 if (ext4_has_inline_data(dir)) {
2159 retval = ext4_try_add_inline_entry(handle, &fname, dir, inode);
2169 retval = ext4_dx_add_entry(handle, &fname, dir, inode);
2170 if (!retval || (retval != ERR_BAD_DX_DIR))
2172 /* Can we just ignore htree data? */
2173 if (ext4_has_metadata_csum(sb)) {
2174 EXT4_ERROR_INODE(dir,
2175 "Directory has corrupted htree index.");
2176 retval = -EFSCORRUPTED;
2179 ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
2181 ext4_mark_inode_dirty(handle, dir);
2183 blocks = dir->i_size >> sb->s_blocksize_bits;
2184 for (block = 0; block < blocks; block++) {
2185 bh = ext4_read_dirblock(dir, block, DIRENT);
2187 bh = ext4_bread(handle, dir, block,
2188 EXT4_GET_BLOCKS_CREATE);
2189 goto add_to_new_block;
2192 retval = PTR_ERR(bh);
2196 retval = add_dirent_to_buf(handle, &fname, dir, inode,
2198 if (retval != -ENOSPC)
2201 if (blocks == 1 && !dx_fallback &&
2202 ext4_has_feature_dir_index(sb)) {
2203 retval = make_indexed_dir(handle, &fname, dir,
2205 bh = NULL; /* make_indexed_dir releases bh */
2210 bh = ext4_append(handle, dir, &block);
2213 retval = PTR_ERR(bh);
2217 de = (struct ext4_dir_entry_2 *) bh->b_data;
2219 de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
2222 t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
2223 initialize_dirent_tail(t, blocksize);
2226 retval = add_dirent_to_buf(handle, &fname, dir, inode, de, bh);
2228 ext4_fname_free_filename(&fname);
2231 ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
2236 * Returns 0 for success, or a negative error value
2238 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
2239 struct inode *dir, struct inode *inode)
2241 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
2242 struct dx_entry *entries, *at;
2243 struct buffer_head *bh;
2244 struct super_block *sb = dir->i_sb;
2245 struct ext4_dir_entry_2 *de;
2251 frame = dx_probe(fname, dir, NULL, frames);
2253 return PTR_ERR(frame);
2254 entries = frame->entries;
2256 bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT_HTREE);
2263 BUFFER_TRACE(bh, "get_write_access");
2264 err = ext4_journal_get_write_access(handle, bh);
2268 err = add_dirent_to_buf(handle, fname, dir, inode, NULL, bh);
2273 /* Block full, should compress but for now just split */
2274 dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
2275 dx_get_count(entries), dx_get_limit(entries)));
2276 /* Need to split index? */
2277 if (dx_get_count(entries) == dx_get_limit(entries)) {
2278 ext4_lblk_t newblock;
2279 int levels = frame - frames + 1;
2280 unsigned int icount;
2282 struct dx_entry *entries2;
2283 struct dx_node *node2;
2284 struct buffer_head *bh2;
2286 while (frame > frames) {
2287 if (dx_get_count((frame - 1)->entries) <
2288 dx_get_limit((frame - 1)->entries)) {
2292 frame--; /* split higher index block */
2294 entries = frame->entries;
2297 if (add_level && levels == ext4_dir_htree_level(sb)) {
2298 ext4_warning(sb, "Directory (ino: %lu) index full, "
2299 "reach max htree level :%d",
2300 dir->i_ino, levels);
2301 if (ext4_dir_htree_level(sb) < EXT4_HTREE_LEVEL) {
2302 ext4_warning(sb, "Large directory feature is "
2303 "not enabled on this "
2309 icount = dx_get_count(entries);
2310 bh2 = ext4_append(handle, dir, &newblock);
2315 node2 = (struct dx_node *)(bh2->b_data);
2316 entries2 = node2->entries;
2317 memset(&node2->fake, 0, sizeof(struct fake_dirent));
2318 node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
2320 BUFFER_TRACE(frame->bh, "get_write_access");
2321 err = ext4_journal_get_write_access(handle, frame->bh);
2325 unsigned icount1 = icount/2, icount2 = icount - icount1;
2326 unsigned hash2 = dx_get_hash(entries + icount1);
2327 dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
2330 BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
2331 err = ext4_journal_get_write_access(handle,
2336 memcpy((char *) entries2, (char *) (entries + icount1),
2337 icount2 * sizeof(struct dx_entry));
2338 dx_set_count(entries, icount1);
2339 dx_set_count(entries2, icount2);
2340 dx_set_limit(entries2, dx_node_limit(dir));
2342 /* Which index block gets the new entry? */
2343 if (at - entries >= icount1) {
2344 frame->at = at = at - entries - icount1 + entries2;
2345 frame->entries = entries = entries2;
2346 swap(frame->bh, bh2);
2348 dx_insert_block((frame - 1), hash2, newblock);
2349 dxtrace(dx_show_index("node", frame->entries));
2350 dxtrace(dx_show_index("node",
2351 ((struct dx_node *) bh2->b_data)->entries));
2352 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2356 err = ext4_handle_dirty_dx_node(handle, dir,
2360 err = ext4_handle_dirty_dx_node(handle, dir,
2365 struct dx_root *dxroot;
2366 memcpy((char *) entries2, (char *) entries,
2367 icount * sizeof(struct dx_entry));
2368 dx_set_limit(entries2, dx_node_limit(dir));
2371 dx_set_count(entries, 1);
2372 dx_set_block(entries + 0, newblock);
2373 dxroot = (struct dx_root *)frames[0].bh->b_data;
2374 dxroot->info.indirect_levels += 1;
2375 dxtrace(printk(KERN_DEBUG
2376 "Creating %d level index...\n",
2377 dxroot->info.indirect_levels));
2378 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2381 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2387 de = do_split(handle, dir, &bh, frame, &fname->hinfo);
2392 err = add_dirent_to_buf(handle, fname, dir, inode, de, bh);
2396 ext4_std_error(dir->i_sb, err); /* this is a no-op if err == 0 */
2400 /* @restart is true means htree-path has been changed, we need to
2401 * repeat dx_probe() to find out valid htree-path
2403 if (restart && err == 0)
2409 * ext4_generic_delete_entry deletes a directory entry by merging it
2410 * with the previous entry
2412 int ext4_generic_delete_entry(handle_t *handle,
2414 struct ext4_dir_entry_2 *de_del,
2415 struct buffer_head *bh,
2420 struct ext4_dir_entry_2 *de, *pde;
2421 unsigned int blocksize = dir->i_sb->s_blocksize;
2426 de = (struct ext4_dir_entry_2 *)entry_buf;
2427 while (i < buf_size - csum_size) {
2428 if (ext4_check_dir_entry(dir, NULL, de, bh,
2429 entry_buf, buf_size, i))
2430 return -EFSCORRUPTED;
2433 pde->rec_len = ext4_rec_len_to_disk(
2434 ext4_rec_len_from_disk(pde->rec_len,
2436 ext4_rec_len_from_disk(de->rec_len,
2441 inode_inc_iversion(dir);
2444 i += ext4_rec_len_from_disk(de->rec_len, blocksize);
2446 de = ext4_next_entry(de, blocksize);
2451 static int ext4_delete_entry(handle_t *handle,
2453 struct ext4_dir_entry_2 *de_del,
2454 struct buffer_head *bh)
2456 int err, csum_size = 0;
2458 if (ext4_has_inline_data(dir)) {
2459 int has_inline_data = 1;
2460 err = ext4_delete_inline_entry(handle, dir, de_del, bh,
2462 if (has_inline_data)
2466 if (ext4_has_metadata_csum(dir->i_sb))
2467 csum_size = sizeof(struct ext4_dir_entry_tail);
2469 BUFFER_TRACE(bh, "get_write_access");
2470 err = ext4_journal_get_write_access(handle, bh);
2474 err = ext4_generic_delete_entry(handle, dir, de_del,
2476 dir->i_sb->s_blocksize, csum_size);
2480 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
2481 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
2488 ext4_std_error(dir->i_sb, err);
2493 * Set directory link count to 1 if nlinks > EXT4_LINK_MAX, or if nlinks == 2
2494 * since this indicates that nlinks count was previously 1 to avoid overflowing
2495 * the 16-bit i_links_count field on disk. Directories with i_nlink == 1 mean
2496 * that subdirectory link counts are not being maintained accurately.
2498 * The caller has already checked for i_nlink overflow in case the DIR_LINK
2499 * feature is not enabled and returned -EMLINK. The is_dx() check is a proxy
2500 * for checking S_ISDIR(inode) (since the INODE_INDEX feature will not be set
2501 * on regular files) and to avoid creating huge/slow non-HTREE directories.
2503 static void ext4_inc_count(handle_t *handle, struct inode *inode)
2507 (inode->i_nlink > EXT4_LINK_MAX || inode->i_nlink == 2))
2508 set_nlink(inode, 1);
2512 * If a directory had nlink == 1, then we should let it be 1. This indicates
2513 * directory has >EXT4_LINK_MAX subdirs.
2515 static void ext4_dec_count(handle_t *handle, struct inode *inode)
2517 if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
2522 static int ext4_add_nondir(handle_t *handle,
2523 struct dentry *dentry, struct inode *inode)
2525 int err = ext4_add_entry(handle, dentry, inode);
2527 ext4_mark_inode_dirty(handle, inode);
2528 d_instantiate_new(dentry, inode);
2532 unlock_new_inode(inode);
2538 * By the time this is called, we already have created
2539 * the directory cache entry for the new file, but it
2540 * is so far negative - it has no inode.
2542 * If the create succeeds, we fill in the inode information
2543 * with d_instantiate().
2545 static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2549 struct inode *inode;
2550 int err, credits, retries = 0;
2552 err = dquot_initialize(dir);
2556 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2557 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2559 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2560 NULL, EXT4_HT_DIR, credits);
2561 handle = ext4_journal_current_handle();
2562 err = PTR_ERR(inode);
2563 if (!IS_ERR(inode)) {
2564 inode->i_op = &ext4_file_inode_operations;
2565 inode->i_fop = &ext4_file_operations;
2566 ext4_set_aops(inode);
2567 err = ext4_add_nondir(handle, dentry, inode);
2568 if (!err && IS_DIRSYNC(dir))
2569 ext4_handle_sync(handle);
2572 ext4_journal_stop(handle);
2573 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2578 static int ext4_mknod(struct inode *dir, struct dentry *dentry,
2579 umode_t mode, dev_t rdev)
2582 struct inode *inode;
2583 int err, credits, retries = 0;
2585 err = dquot_initialize(dir);
2589 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2590 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2592 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2593 NULL, EXT4_HT_DIR, credits);
2594 handle = ext4_journal_current_handle();
2595 err = PTR_ERR(inode);
2596 if (!IS_ERR(inode)) {
2597 init_special_inode(inode, inode->i_mode, rdev);
2598 inode->i_op = &ext4_special_inode_operations;
2599 err = ext4_add_nondir(handle, dentry, inode);
2600 if (!err && IS_DIRSYNC(dir))
2601 ext4_handle_sync(handle);
2604 ext4_journal_stop(handle);
2605 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2610 static int ext4_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2613 struct inode *inode;
2614 int err, retries = 0;
2616 err = dquot_initialize(dir);
2621 inode = ext4_new_inode_start_handle(dir, mode,
2624 EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
2625 4 + EXT4_XATTR_TRANS_BLOCKS);
2626 handle = ext4_journal_current_handle();
2627 err = PTR_ERR(inode);
2628 if (!IS_ERR(inode)) {
2629 inode->i_op = &ext4_file_inode_operations;
2630 inode->i_fop = &ext4_file_operations;
2631 ext4_set_aops(inode);
2632 d_tmpfile(dentry, inode);
2633 err = ext4_orphan_add(handle, inode);
2635 goto err_unlock_inode;
2636 mark_inode_dirty(inode);
2637 unlock_new_inode(inode);
2640 ext4_journal_stop(handle);
2641 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2645 ext4_journal_stop(handle);
2646 unlock_new_inode(inode);
2650 struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode,
2651 struct ext4_dir_entry_2 *de,
2652 int blocksize, int csum_size,
2653 unsigned int parent_ino, int dotdot_real_len)
2655 de->inode = cpu_to_le32(inode->i_ino);
2657 de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
2659 strcpy(de->name, ".");
2660 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2662 de = ext4_next_entry(de, blocksize);
2663 de->inode = cpu_to_le32(parent_ino);
2665 if (!dotdot_real_len)
2666 de->rec_len = ext4_rec_len_to_disk(blocksize -
2667 (csum_size + EXT4_DIR_REC_LEN(1)),
2670 de->rec_len = ext4_rec_len_to_disk(
2671 EXT4_DIR_REC_LEN(de->name_len), blocksize);
2672 strcpy(de->name, "..");
2673 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2675 return ext4_next_entry(de, blocksize);
2678 static int ext4_init_new_dir(handle_t *handle, struct inode *dir,
2679 struct inode *inode)
2681 struct buffer_head *dir_block = NULL;
2682 struct ext4_dir_entry_2 *de;
2683 struct ext4_dir_entry_tail *t;
2684 ext4_lblk_t block = 0;
2685 unsigned int blocksize = dir->i_sb->s_blocksize;
2689 if (ext4_has_metadata_csum(dir->i_sb))
2690 csum_size = sizeof(struct ext4_dir_entry_tail);
2692 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2693 err = ext4_try_create_inline_dir(handle, dir, inode);
2694 if (err < 0 && err != -ENOSPC)
2701 dir_block = ext4_append(handle, inode, &block);
2702 if (IS_ERR(dir_block))
2703 return PTR_ERR(dir_block);
2704 de = (struct ext4_dir_entry_2 *)dir_block->b_data;
2705 ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0);
2706 set_nlink(inode, 2);
2708 t = EXT4_DIRENT_TAIL(dir_block->b_data, blocksize);
2709 initialize_dirent_tail(t, blocksize);
2712 BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
2713 err = ext4_handle_dirty_dirent_node(handle, inode, dir_block);
2716 set_buffer_verified(dir_block);
2722 static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2725 struct inode *inode;
2726 int err, credits, retries = 0;
2728 if (EXT4_DIR_LINK_MAX(dir))
2731 err = dquot_initialize(dir);
2735 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2736 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2738 inode = ext4_new_inode_start_handle(dir, S_IFDIR | mode,
2740 0, NULL, EXT4_HT_DIR, credits);
2741 handle = ext4_journal_current_handle();
2742 err = PTR_ERR(inode);
2746 inode->i_op = &ext4_dir_inode_operations;
2747 inode->i_fop = &ext4_dir_operations;
2748 err = ext4_init_new_dir(handle, dir, inode);
2750 goto out_clear_inode;
2751 err = ext4_mark_inode_dirty(handle, inode);
2753 err = ext4_add_entry(handle, dentry, inode);
2757 unlock_new_inode(inode);
2758 ext4_mark_inode_dirty(handle, inode);
2762 ext4_inc_count(handle, dir);
2763 ext4_update_dx_flag(dir);
2764 err = ext4_mark_inode_dirty(handle, dir);
2766 goto out_clear_inode;
2767 d_instantiate_new(dentry, inode);
2768 if (IS_DIRSYNC(dir))
2769 ext4_handle_sync(handle);
2773 ext4_journal_stop(handle);
2774 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2780 * routine to check that the specified directory is empty (for rmdir)
2782 bool ext4_empty_dir(struct inode *inode)
2784 unsigned int offset;
2785 struct buffer_head *bh;
2786 struct ext4_dir_entry_2 *de;
2787 struct super_block *sb;
2789 if (ext4_has_inline_data(inode)) {
2790 int has_inline_data = 1;
2793 ret = empty_inline_dir(inode, &has_inline_data);
2794 if (has_inline_data)
2799 if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2)) {
2800 EXT4_ERROR_INODE(inode, "invalid size");
2803 /* The first directory block must not be a hole,
2804 * so treat it as DIRENT_HTREE
2806 bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
2810 de = (struct ext4_dir_entry_2 *) bh->b_data;
2811 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2813 le32_to_cpu(de->inode) != inode->i_ino || strcmp(".", de->name)) {
2814 ext4_warning_inode(inode, "directory missing '.'");
2818 offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2819 de = ext4_next_entry(de, sb->s_blocksize);
2820 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2822 le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
2823 ext4_warning_inode(inode, "directory missing '..'");
2827 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2828 while (offset < inode->i_size) {
2829 if (!(offset & (sb->s_blocksize - 1))) {
2830 unsigned int lblock;
2832 lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
2833 bh = ext4_read_dirblock(inode, lblock, EITHER);
2835 offset += sb->s_blocksize;
2841 de = (struct ext4_dir_entry_2 *) (bh->b_data +
2842 (offset & (sb->s_blocksize - 1)));
2843 if (ext4_check_dir_entry(inode, NULL, de, bh,
2844 bh->b_data, bh->b_size, offset) ||
2845 le32_to_cpu(de->inode)) {
2849 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2856 * ext4_orphan_add() links an unlinked or truncated inode into a list of
2857 * such inodes, starting at the superblock, in case we crash before the
2858 * file is closed/deleted, or in case the inode truncate spans multiple
2859 * transactions and the last transaction is not recovered after a crash.
2861 * At filesystem recovery time, we walk this list deleting unlinked
2862 * inodes and truncating linked inodes in ext4_orphan_cleanup().
2864 * Orphan list manipulation functions must be called under i_mutex unless
2865 * we are just creating the inode or deleting it.
2867 int ext4_orphan_add(handle_t *handle, struct inode *inode)
2869 struct super_block *sb = inode->i_sb;
2870 struct ext4_sb_info *sbi = EXT4_SB(sb);
2871 struct ext4_iloc iloc;
2875 if (!sbi->s_journal || is_bad_inode(inode))
2878 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2879 !inode_is_locked(inode));
2881 * Exit early if inode already is on orphan list. This is a big speedup
2882 * since we don't have to contend on the global s_orphan_lock.
2884 if (!list_empty(&EXT4_I(inode)->i_orphan))
2888 * Orphan handling is only valid for files with data blocks
2889 * being truncated, or files being unlinked. Note that we either
2890 * hold i_mutex, or the inode can not be referenced from outside,
2891 * so i_nlink should not be bumped due to race
2893 J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
2894 S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
2896 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2897 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2901 err = ext4_reserve_inode_write(handle, inode, &iloc);
2905 mutex_lock(&sbi->s_orphan_lock);
2907 * Due to previous errors inode may be already a part of on-disk
2908 * orphan list. If so skip on-disk list modification.
2910 if (!NEXT_ORPHAN(inode) || NEXT_ORPHAN(inode) >
2911 (le32_to_cpu(sbi->s_es->s_inodes_count))) {
2912 /* Insert this inode at the head of the on-disk orphan list */
2913 NEXT_ORPHAN(inode) = le32_to_cpu(sbi->s_es->s_last_orphan);
2914 sbi->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
2917 list_add(&EXT4_I(inode)->i_orphan, &sbi->s_orphan);
2918 mutex_unlock(&sbi->s_orphan_lock);
2921 err = ext4_handle_dirty_super(handle, sb);
2922 rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
2927 * We have to remove inode from in-memory list if
2928 * addition to on disk orphan list failed. Stray orphan
2929 * list entries can cause panics at unmount time.
2931 mutex_lock(&sbi->s_orphan_lock);
2932 list_del_init(&EXT4_I(inode)->i_orphan);
2933 mutex_unlock(&sbi->s_orphan_lock);
2938 jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
2939 jbd_debug(4, "orphan inode %lu will point to %d\n",
2940 inode->i_ino, NEXT_ORPHAN(inode));
2942 ext4_std_error(sb, err);
2947 * ext4_orphan_del() removes an unlinked or truncated inode from the list
2948 * of such inodes stored on disk, because it is finally being cleaned up.
2950 int ext4_orphan_del(handle_t *handle, struct inode *inode)
2952 struct list_head *prev;
2953 struct ext4_inode_info *ei = EXT4_I(inode);
2954 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2956 struct ext4_iloc iloc;
2959 if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS))
2962 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2963 !inode_is_locked(inode));
2964 /* Do this quick check before taking global s_orphan_lock. */
2965 if (list_empty(&ei->i_orphan))
2969 /* Grab inode buffer early before taking global s_orphan_lock */
2970 err = ext4_reserve_inode_write(handle, inode, &iloc);
2973 mutex_lock(&sbi->s_orphan_lock);
2974 jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
2976 prev = ei->i_orphan.prev;
2977 list_del_init(&ei->i_orphan);
2979 /* If we're on an error path, we may not have a valid
2980 * transaction handle with which to update the orphan list on
2981 * disk, but we still need to remove the inode from the linked
2982 * list in memory. */
2983 if (!handle || err) {
2984 mutex_unlock(&sbi->s_orphan_lock);
2988 ino_next = NEXT_ORPHAN(inode);
2989 if (prev == &sbi->s_orphan) {
2990 jbd_debug(4, "superblock will point to %u\n", ino_next);
2991 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2992 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2994 mutex_unlock(&sbi->s_orphan_lock);
2997 sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
2998 mutex_unlock(&sbi->s_orphan_lock);
2999 err = ext4_handle_dirty_super(handle, inode->i_sb);
3001 struct ext4_iloc iloc2;
3002 struct inode *i_prev =
3003 &list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
3005 jbd_debug(4, "orphan inode %lu will point to %u\n",
3006 i_prev->i_ino, ino_next);
3007 err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
3009 mutex_unlock(&sbi->s_orphan_lock);
3012 NEXT_ORPHAN(i_prev) = ino_next;
3013 err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
3014 mutex_unlock(&sbi->s_orphan_lock);
3018 NEXT_ORPHAN(inode) = 0;
3019 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
3021 ext4_std_error(inode->i_sb, err);
3029 static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
3032 struct inode *inode;
3033 struct buffer_head *bh;
3034 struct ext4_dir_entry_2 *de;
3035 handle_t *handle = NULL;
3037 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3040 /* Initialize quotas before so that eventual writes go in
3041 * separate transaction */
3042 retval = dquot_initialize(dir);
3045 retval = dquot_initialize(d_inode(dentry));
3050 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3056 inode = d_inode(dentry);
3058 retval = -EFSCORRUPTED;
3059 if (le32_to_cpu(de->inode) != inode->i_ino)
3062 retval = -ENOTEMPTY;
3063 if (!ext4_empty_dir(inode))
3066 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3067 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3068 if (IS_ERR(handle)) {
3069 retval = PTR_ERR(handle);
3074 if (IS_DIRSYNC(dir))
3075 ext4_handle_sync(handle);
3077 retval = ext4_delete_entry(handle, dir, de, bh);
3080 if (!EXT4_DIR_LINK_EMPTY(inode))
3081 ext4_warning_inode(inode,
3082 "empty directory '%.*s' has too many links (%u)",
3083 dentry->d_name.len, dentry->d_name.name,
3085 inode_inc_iversion(inode);
3087 /* There's no need to set i_disksize: the fact that i_nlink is
3088 * zero will ensure that the right thing happens during any
3091 ext4_orphan_add(handle, inode);
3092 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
3093 ext4_mark_inode_dirty(handle, inode);
3094 ext4_dec_count(handle, dir);
3095 ext4_update_dx_flag(dir);
3096 ext4_mark_inode_dirty(handle, dir);
3101 ext4_journal_stop(handle);
3105 static int ext4_unlink(struct inode *dir, struct dentry *dentry)
3108 struct inode *inode;
3109 struct buffer_head *bh;
3110 struct ext4_dir_entry_2 *de;
3111 handle_t *handle = NULL;
3113 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3116 trace_ext4_unlink_enter(dir, dentry);
3117 /* Initialize quotas before so that eventual writes go
3118 * in separate transaction */
3119 retval = dquot_initialize(dir);
3122 retval = dquot_initialize(d_inode(dentry));
3127 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3133 inode = d_inode(dentry);
3135 retval = -EFSCORRUPTED;
3136 if (le32_to_cpu(de->inode) != inode->i_ino)
3139 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3140 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3141 if (IS_ERR(handle)) {
3142 retval = PTR_ERR(handle);
3147 if (IS_DIRSYNC(dir))
3148 ext4_handle_sync(handle);
3150 retval = ext4_delete_entry(handle, dir, de, bh);
3153 dir->i_ctime = dir->i_mtime = current_time(dir);
3154 ext4_update_dx_flag(dir);
3155 ext4_mark_inode_dirty(handle, dir);
3156 if (inode->i_nlink == 0)
3157 ext4_warning_inode(inode, "Deleting file '%.*s' with no links",
3158 dentry->d_name.len, dentry->d_name.name);
3161 if (!inode->i_nlink)
3162 ext4_orphan_add(handle, inode);
3163 inode->i_ctime = current_time(inode);
3164 ext4_mark_inode_dirty(handle, inode);
3169 ext4_journal_stop(handle);
3170 trace_ext4_unlink_exit(dentry, retval);
3174 static int ext4_symlink(struct inode *dir,
3175 struct dentry *dentry, const char *symname)
3178 struct inode *inode;
3179 int err, len = strlen(symname);
3181 struct fscrypt_str disk_link;
3183 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3186 err = fscrypt_prepare_symlink(dir, symname, len, dir->i_sb->s_blocksize,
3191 err = dquot_initialize(dir);
3195 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3197 * For non-fast symlinks, we just allocate inode and put it on
3198 * orphan list in the first transaction => we need bitmap,
3199 * group descriptor, sb, inode block, quota blocks, and
3200 * possibly selinux xattr blocks.
3202 credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
3203 EXT4_XATTR_TRANS_BLOCKS;
3206 * Fast symlink. We have to add entry to directory
3207 * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
3208 * allocate new inode (bitmap, group descriptor, inode block,
3209 * quota blocks, sb is already counted in previous macros).
3211 credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3212 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3;
3215 inode = ext4_new_inode_start_handle(dir, S_IFLNK|S_IRWXUGO,
3216 &dentry->d_name, 0, NULL,
3217 EXT4_HT_DIR, credits);
3218 handle = ext4_journal_current_handle();
3219 if (IS_ERR(inode)) {
3221 ext4_journal_stop(handle);
3222 return PTR_ERR(inode);
3225 if (IS_ENCRYPTED(inode)) {
3226 err = fscrypt_encrypt_symlink(inode, symname, len, &disk_link);
3228 goto err_drop_inode;
3229 inode->i_op = &ext4_encrypted_symlink_inode_operations;
3232 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3233 if (!IS_ENCRYPTED(inode))
3234 inode->i_op = &ext4_symlink_inode_operations;
3235 inode_nohighmem(inode);
3236 ext4_set_aops(inode);
3238 * We cannot call page_symlink() with transaction started
3239 * because it calls into ext4_write_begin() which can wait
3240 * for transaction commit if we are running out of space
3241 * and thus we deadlock. So we have to stop transaction now
3242 * and restart it when symlink contents is written.
3244 * To keep fs consistent in case of crash, we have to put inode
3245 * to orphan list in the mean time.
3248 err = ext4_orphan_add(handle, inode);
3249 ext4_journal_stop(handle);
3252 goto err_drop_inode;
3253 err = __page_symlink(inode, disk_link.name, disk_link.len, 1);
3255 goto err_drop_inode;
3257 * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
3258 * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
3260 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3261 EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3262 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
3263 if (IS_ERR(handle)) {
3264 err = PTR_ERR(handle);
3266 goto err_drop_inode;
3268 set_nlink(inode, 1);
3269 err = ext4_orphan_del(handle, inode);
3271 goto err_drop_inode;
3273 /* clear the extent format for fast symlink */
3274 ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
3275 if (!IS_ENCRYPTED(inode)) {
3276 inode->i_op = &ext4_fast_symlink_inode_operations;
3277 inode->i_link = (char *)&EXT4_I(inode)->i_data;
3279 memcpy((char *)&EXT4_I(inode)->i_data, disk_link.name,
3281 inode->i_size = disk_link.len - 1;
3283 EXT4_I(inode)->i_disksize = inode->i_size;
3284 err = ext4_add_nondir(handle, dentry, inode);
3285 if (!err && IS_DIRSYNC(dir))
3286 ext4_handle_sync(handle);
3289 ext4_journal_stop(handle);
3290 goto out_free_encrypted_link;
3294 ext4_journal_stop(handle);
3296 unlock_new_inode(inode);
3298 out_free_encrypted_link:
3299 if (disk_link.name != (unsigned char *)symname)
3300 kfree(disk_link.name);
3304 static int ext4_link(struct dentry *old_dentry,
3305 struct inode *dir, struct dentry *dentry)
3308 struct inode *inode = d_inode(old_dentry);
3309 int err, retries = 0;
3311 if (inode->i_nlink >= EXT4_LINK_MAX)
3314 err = fscrypt_prepare_link(old_dentry, dir, dentry);
3318 if ((ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT)) &&
3319 (!projid_eq(EXT4_I(dir)->i_projid,
3320 EXT4_I(old_dentry->d_inode)->i_projid)))
3323 err = dquot_initialize(dir);
3328 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3329 (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3330 EXT4_INDEX_EXTRA_TRANS_BLOCKS) + 1);
3332 return PTR_ERR(handle);
3334 if (IS_DIRSYNC(dir))
3335 ext4_handle_sync(handle);
3337 inode->i_ctime = current_time(inode);
3338 ext4_inc_count(handle, inode);
3341 err = ext4_add_entry(handle, dentry, inode);
3343 ext4_mark_inode_dirty(handle, inode);
3344 /* this can happen only for tmpfile being
3345 * linked the first time
3347 if (inode->i_nlink == 1)
3348 ext4_orphan_del(handle, inode);
3349 d_instantiate(dentry, inode);
3354 ext4_journal_stop(handle);
3355 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
3362 * Try to find buffer head where contains the parent block.
3363 * It should be the inode block if it is inlined or the 1st block
3364 * if it is a normal dir.
3366 static struct buffer_head *ext4_get_first_dir_block(handle_t *handle,
3367 struct inode *inode,
3369 struct ext4_dir_entry_2 **parent_de,
3372 struct buffer_head *bh;
3374 if (!ext4_has_inline_data(inode)) {
3375 struct ext4_dir_entry_2 *de;
3376 unsigned int offset;
3378 /* The first directory block must not be a hole, so
3379 * treat it as DIRENT_HTREE
3381 bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
3383 *retval = PTR_ERR(bh);
3387 de = (struct ext4_dir_entry_2 *) bh->b_data;
3388 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data,
3390 le32_to_cpu(de->inode) != inode->i_ino ||
3391 strcmp(".", de->name)) {
3392 EXT4_ERROR_INODE(inode, "directory missing '.'");
3394 *retval = -EFSCORRUPTED;
3397 offset = ext4_rec_len_from_disk(de->rec_len,
3398 inode->i_sb->s_blocksize);
3399 de = ext4_next_entry(de, inode->i_sb->s_blocksize);
3400 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data,
3401 bh->b_size, offset) ||
3402 le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
3403 EXT4_ERROR_INODE(inode, "directory missing '..'");
3405 *retval = -EFSCORRUPTED;
3414 return ext4_get_first_inline_block(inode, parent_de, retval);
3417 struct ext4_renament {
3419 struct dentry *dentry;
3420 struct inode *inode;
3422 int dir_nlink_delta;
3424 /* entry for "dentry" */
3425 struct buffer_head *bh;
3426 struct ext4_dir_entry_2 *de;
3429 /* entry for ".." in inode if it's a directory */
3430 struct buffer_head *dir_bh;
3431 struct ext4_dir_entry_2 *parent_de;
3435 static int ext4_rename_dir_prepare(handle_t *handle, struct ext4_renament *ent)
3439 ent->dir_bh = ext4_get_first_dir_block(handle, ent->inode,
3440 &retval, &ent->parent_de,
3444 if (le32_to_cpu(ent->parent_de->inode) != ent->dir->i_ino)
3445 return -EFSCORRUPTED;
3446 BUFFER_TRACE(ent->dir_bh, "get_write_access");
3447 return ext4_journal_get_write_access(handle, ent->dir_bh);
3450 static int ext4_rename_dir_finish(handle_t *handle, struct ext4_renament *ent,
3455 ent->parent_de->inode = cpu_to_le32(dir_ino);
3456 BUFFER_TRACE(ent->dir_bh, "call ext4_handle_dirty_metadata");
3457 if (!ent->dir_inlined) {
3458 if (is_dx(ent->inode)) {
3459 retval = ext4_handle_dirty_dx_node(handle,
3463 retval = ext4_handle_dirty_dirent_node(handle,
3468 retval = ext4_mark_inode_dirty(handle, ent->inode);
3471 ext4_std_error(ent->dir->i_sb, retval);
3477 static int ext4_setent(handle_t *handle, struct ext4_renament *ent,
3478 unsigned ino, unsigned file_type)
3482 BUFFER_TRACE(ent->bh, "get write access");
3483 retval = ext4_journal_get_write_access(handle, ent->bh);
3486 ent->de->inode = cpu_to_le32(ino);
3487 if (ext4_has_feature_filetype(ent->dir->i_sb))
3488 ent->de->file_type = file_type;
3489 inode_inc_iversion(ent->dir);
3490 ent->dir->i_ctime = ent->dir->i_mtime =
3491 current_time(ent->dir);
3492 ext4_mark_inode_dirty(handle, ent->dir);
3493 BUFFER_TRACE(ent->bh, "call ext4_handle_dirty_metadata");
3494 if (!ent->inlined) {
3495 retval = ext4_handle_dirty_dirent_node(handle,
3497 if (unlikely(retval)) {
3498 ext4_std_error(ent->dir->i_sb, retval);
3506 static void ext4_resetent(handle_t *handle, struct ext4_renament *ent,
3507 unsigned ino, unsigned file_type)
3509 struct ext4_renament old = *ent;
3513 * old->de could have moved from under us during make indexed dir,
3514 * so the old->de may no longer valid and need to find it again
3515 * before reset old inode info.
3517 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de,
3520 retval = PTR_ERR(old.bh);
3524 ext4_std_error(old.dir->i_sb, retval);
3528 ext4_setent(handle, &old, ino, file_type);
3532 static int ext4_find_delete_entry(handle_t *handle, struct inode *dir,
3533 const struct qstr *d_name)
3535 int retval = -ENOENT;
3536 struct buffer_head *bh;
3537 struct ext4_dir_entry_2 *de;
3539 bh = ext4_find_entry(dir, d_name, &de, NULL);
3543 retval = ext4_delete_entry(handle, dir, de, bh);
3549 static void ext4_rename_delete(handle_t *handle, struct ext4_renament *ent,
3554 * ent->de could have moved from under us during htree split, so make
3555 * sure that we are deleting the right entry. We might also be pointing
3556 * to a stale entry in the unused part of ent->bh so just checking inum
3557 * and the name isn't enough.
3559 if (le32_to_cpu(ent->de->inode) != ent->inode->i_ino ||
3560 ent->de->name_len != ent->dentry->d_name.len ||
3561 strncmp(ent->de->name, ent->dentry->d_name.name,
3562 ent->de->name_len) ||
3564 retval = ext4_find_delete_entry(handle, ent->dir,
3565 &ent->dentry->d_name);
3567 retval = ext4_delete_entry(handle, ent->dir, ent->de, ent->bh);
3568 if (retval == -ENOENT) {
3569 retval = ext4_find_delete_entry(handle, ent->dir,
3570 &ent->dentry->d_name);
3575 ext4_warning_inode(ent->dir,
3576 "Deleting old file: nlink %d, error=%d",
3577 ent->dir->i_nlink, retval);
3581 static void ext4_update_dir_count(handle_t *handle, struct ext4_renament *ent)
3583 if (ent->dir_nlink_delta) {
3584 if (ent->dir_nlink_delta == -1)
3585 ext4_dec_count(handle, ent->dir);
3587 ext4_inc_count(handle, ent->dir);
3588 ext4_mark_inode_dirty(handle, ent->dir);
3592 static struct inode *ext4_whiteout_for_rename(struct ext4_renament *ent,
3593 int credits, handle_t **h)
3600 * for inode block, sb block, group summaries,
3603 credits += (EXT4_MAXQUOTAS_TRANS_BLOCKS(ent->dir->i_sb) +
3604 EXT4_XATTR_TRANS_BLOCKS + 4);
3606 wh = ext4_new_inode_start_handle(ent->dir, S_IFCHR | WHITEOUT_MODE,
3607 &ent->dentry->d_name, 0, NULL,
3608 EXT4_HT_DIR, credits);
3610 handle = ext4_journal_current_handle();
3613 ext4_journal_stop(handle);
3614 if (PTR_ERR(wh) == -ENOSPC &&
3615 ext4_should_retry_alloc(ent->dir->i_sb, &retries))
3619 init_special_inode(wh, wh->i_mode, WHITEOUT_DEV);
3620 wh->i_op = &ext4_special_inode_operations;
3626 * Anybody can rename anything with this: the permission checks are left to the
3627 * higher-level routines.
3629 * n.b. old_{dentry,inode) refers to the source dentry/inode
3630 * while new_{dentry,inode) refers to the destination dentry/inode
3631 * This comes from rename(const char *oldpath, const char *newpath)
3633 static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
3634 struct inode *new_dir, struct dentry *new_dentry,
3637 handle_t *handle = NULL;
3638 struct ext4_renament old = {
3640 .dentry = old_dentry,
3641 .inode = d_inode(old_dentry),
3643 struct ext4_renament new = {
3645 .dentry = new_dentry,
3646 .inode = d_inode(new_dentry),
3650 struct inode *whiteout = NULL;
3654 if (new.inode && new.inode->i_nlink == 0) {
3655 EXT4_ERROR_INODE(new.inode,
3656 "target of rename is already freed");
3657 return -EFSCORRUPTED;
3660 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT)) &&
3661 (!projid_eq(EXT4_I(new_dir)->i_projid,
3662 EXT4_I(old_dentry->d_inode)->i_projid)))
3665 retval = dquot_initialize(old.dir);
3668 retval = dquot_initialize(new.dir);
3672 /* Initialize quotas before so that eventual writes go
3673 * in separate transaction */
3675 retval = dquot_initialize(new.inode);
3680 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de,
3683 return PTR_ERR(old.bh);
3685 * Check for inode number is _not_ due to possible IO errors.
3686 * We might rmdir the source, keep it as pwd of some process
3687 * and merrily kill the link to whatever was created under the
3688 * same name. Goodbye sticky bit ;-<
3691 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3694 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3695 &new.de, &new.inlined);
3696 if (IS_ERR(new.bh)) {
3697 retval = PTR_ERR(new.bh);
3707 if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC))
3708 ext4_alloc_da_blocks(old.inode);
3710 credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3711 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
3712 if (!(flags & RENAME_WHITEOUT)) {
3713 handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits);
3714 if (IS_ERR(handle)) {
3715 retval = PTR_ERR(handle);
3719 whiteout = ext4_whiteout_for_rename(&old, credits, &handle);
3720 if (IS_ERR(whiteout)) {
3721 retval = PTR_ERR(whiteout);
3726 old_file_type = old.de->file_type;
3727 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3728 ext4_handle_sync(handle);
3730 if (S_ISDIR(old.inode->i_mode)) {
3732 retval = -ENOTEMPTY;
3733 if (!ext4_empty_dir(new.inode))
3737 if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir))
3740 retval = ext4_rename_dir_prepare(handle, &old);
3745 * If we're renaming a file within an inline_data dir and adding or
3746 * setting the new dirent causes a conversion from inline_data to
3747 * extents/blockmap, we need to force the dirent delete code to
3748 * re-read the directory, or else we end up trying to delete a dirent
3749 * from what is now the extent tree root (or a block map).
3751 force_reread = (new.dir->i_ino == old.dir->i_ino &&
3752 ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA));
3756 * Do this before adding a new entry, so the old entry is sure
3757 * to be still pointing to the valid old entry.
3759 retval = ext4_setent(handle, &old, whiteout->i_ino,
3763 ext4_mark_inode_dirty(handle, whiteout);
3766 retval = ext4_add_entry(handle, new.dentry, old.inode);
3770 retval = ext4_setent(handle, &new,
3771 old.inode->i_ino, old_file_type);
3776 force_reread = !ext4_test_inode_flag(new.dir,
3777 EXT4_INODE_INLINE_DATA);
3780 * Like most other Unix systems, set the ctime for inodes on a
3783 old.inode->i_ctime = current_time(old.inode);
3784 ext4_mark_inode_dirty(handle, old.inode);
3790 ext4_rename_delete(handle, &old, force_reread);
3794 ext4_dec_count(handle, new.inode);
3795 new.inode->i_ctime = current_time(new.inode);
3797 old.dir->i_ctime = old.dir->i_mtime = current_time(old.dir);
3798 ext4_update_dx_flag(old.dir);
3800 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3804 ext4_dec_count(handle, old.dir);
3806 /* checked ext4_empty_dir above, can't have another
3807 * parent, ext4_dec_count() won't work for many-linked
3809 clear_nlink(new.inode);
3811 ext4_inc_count(handle, new.dir);
3812 ext4_update_dx_flag(new.dir);
3813 ext4_mark_inode_dirty(handle, new.dir);
3816 ext4_mark_inode_dirty(handle, old.dir);
3818 ext4_mark_inode_dirty(handle, new.inode);
3819 if (!new.inode->i_nlink)
3820 ext4_orphan_add(handle, new.inode);
3827 ext4_resetent(handle, &old,
3828 old.inode->i_ino, old_file_type);
3829 drop_nlink(whiteout);
3830 ext4_orphan_add(handle, whiteout);
3832 unlock_new_inode(whiteout);
3833 ext4_journal_stop(handle);
3836 ext4_journal_stop(handle);
3845 static int ext4_cross_rename(struct inode *old_dir, struct dentry *old_dentry,
3846 struct inode *new_dir, struct dentry *new_dentry)
3848 handle_t *handle = NULL;
3849 struct ext4_renament old = {
3851 .dentry = old_dentry,
3852 .inode = d_inode(old_dentry),
3854 struct ext4_renament new = {
3856 .dentry = new_dentry,
3857 .inode = d_inode(new_dentry),
3861 struct timespec64 ctime;
3863 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT) &&
3864 !projid_eq(EXT4_I(new_dir)->i_projid,
3865 EXT4_I(old_dentry->d_inode)->i_projid)) ||
3866 (ext4_test_inode_flag(old_dir, EXT4_INODE_PROJINHERIT) &&
3867 !projid_eq(EXT4_I(old_dir)->i_projid,
3868 EXT4_I(new_dentry->d_inode)->i_projid)))
3871 retval = dquot_initialize(old.dir);
3874 retval = dquot_initialize(old.inode);
3877 retval = dquot_initialize(new.dir);
3881 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name,
3882 &old.de, &old.inlined);
3884 return PTR_ERR(old.bh);
3886 * Check for inode number is _not_ due to possible IO errors.
3887 * We might rmdir the source, keep it as pwd of some process
3888 * and merrily kill the link to whatever was created under the
3889 * same name. Goodbye sticky bit ;-<
3892 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3895 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3896 &new.de, &new.inlined);
3897 if (IS_ERR(new.bh)) {
3898 retval = PTR_ERR(new.bh);
3903 /* RENAME_EXCHANGE case: old *and* new must both exist */
3904 if (!new.bh || le32_to_cpu(new.de->inode) != new.inode->i_ino)
3907 handle = ext4_journal_start(old.dir, EXT4_HT_DIR,
3908 (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3909 2 * EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2));
3910 if (IS_ERR(handle)) {
3911 retval = PTR_ERR(handle);
3916 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3917 ext4_handle_sync(handle);
3919 if (S_ISDIR(old.inode->i_mode)) {
3921 retval = ext4_rename_dir_prepare(handle, &old);
3925 if (S_ISDIR(new.inode->i_mode)) {
3927 retval = ext4_rename_dir_prepare(handle, &new);
3933 * Other than the special case of overwriting a directory, parents'
3934 * nlink only needs to be modified if this is a cross directory rename.
3936 if (old.dir != new.dir && old.is_dir != new.is_dir) {
3937 old.dir_nlink_delta = old.is_dir ? -1 : 1;
3938 new.dir_nlink_delta = -old.dir_nlink_delta;
3940 if ((old.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(old.dir)) ||
3941 (new.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(new.dir)))
3945 new_file_type = new.de->file_type;
3946 retval = ext4_setent(handle, &new, old.inode->i_ino, old.de->file_type);
3950 retval = ext4_setent(handle, &old, new.inode->i_ino, new_file_type);
3955 * Like most other Unix systems, set the ctime for inodes on a
3958 ctime = current_time(old.inode);
3959 old.inode->i_ctime = ctime;
3960 new.inode->i_ctime = ctime;
3961 ext4_mark_inode_dirty(handle, old.inode);
3962 ext4_mark_inode_dirty(handle, new.inode);
3965 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3970 retval = ext4_rename_dir_finish(handle, &new, old.dir->i_ino);
3974 ext4_update_dir_count(handle, &old);
3975 ext4_update_dir_count(handle, &new);
3984 ext4_journal_stop(handle);
3988 static int ext4_rename2(struct inode *old_dir, struct dentry *old_dentry,
3989 struct inode *new_dir, struct dentry *new_dentry,
3994 if (unlikely(ext4_forced_shutdown(EXT4_SB(old_dir->i_sb))))
3997 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4000 err = fscrypt_prepare_rename(old_dir, old_dentry, new_dir, new_dentry,
4005 if (flags & RENAME_EXCHANGE) {
4006 return ext4_cross_rename(old_dir, old_dentry,
4007 new_dir, new_dentry);
4010 return ext4_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
4014 * directories can handle most operations...
4016 const struct inode_operations ext4_dir_inode_operations = {
4017 .create = ext4_create,
4018 .lookup = ext4_lookup,
4020 .unlink = ext4_unlink,
4021 .symlink = ext4_symlink,
4022 .mkdir = ext4_mkdir,
4023 .rmdir = ext4_rmdir,
4024 .mknod = ext4_mknod,
4025 .tmpfile = ext4_tmpfile,
4026 .rename = ext4_rename2,
4027 .setattr = ext4_setattr,
4028 .getattr = ext4_getattr,
4029 .listxattr = ext4_listxattr,
4030 .get_acl = ext4_get_acl,
4031 .set_acl = ext4_set_acl,
4032 .fiemap = ext4_fiemap,
4035 const struct inode_operations ext4_special_inode_operations = {
4036 .setattr = ext4_setattr,
4037 .getattr = ext4_getattr,
4038 .listxattr = ext4_listxattr,
4039 .get_acl = ext4_get_acl,
4040 .set_acl = ext4_set_acl,