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>
38 #include "ext4_jbd2.h"
43 #include <trace/events/ext4.h>
45 * define how far ahead to read directories while searching them.
47 #define NAMEI_RA_CHUNKS 2
48 #define NAMEI_RA_BLOCKS 4
49 #define NAMEI_RA_SIZE (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
51 static struct buffer_head *ext4_append(handle_t *handle,
55 struct ext4_map_blocks map;
56 struct buffer_head *bh;
59 if (unlikely(EXT4_SB(inode->i_sb)->s_max_dir_size_kb &&
60 ((inode->i_size >> 10) >=
61 EXT4_SB(inode->i_sb)->s_max_dir_size_kb)))
62 return ERR_PTR(-ENOSPC);
64 *block = inode->i_size >> inode->i_sb->s_blocksize_bits;
69 * We're appending new directory block. Make sure the block is not
70 * allocated yet, otherwise we will end up corrupting the
73 err = ext4_map_blocks(NULL, inode, &map, 0);
77 EXT4_ERROR_INODE(inode, "Logical block already allocated");
78 return ERR_PTR(-EFSCORRUPTED);
81 bh = ext4_bread(handle, inode, *block, EXT4_GET_BLOCKS_CREATE);
84 inode->i_size += inode->i_sb->s_blocksize;
85 EXT4_I(inode)->i_disksize = inode->i_size;
86 BUFFER_TRACE(bh, "get_write_access");
87 err = ext4_journal_get_write_access(handle, bh);
90 ext4_std_error(inode->i_sb, err);
96 static int ext4_dx_csum_verify(struct inode *inode,
97 struct ext4_dir_entry *dirent);
100 * Hints to ext4_read_dirblock regarding whether we expect a directory
101 * block being read to be an index block, or a block containing
102 * directory entries (and if the latter, whether it was found via a
103 * logical block in an htree index block). This is used to control
104 * what sort of sanity checkinig ext4_read_dirblock() will do on the
105 * directory block read from the storage device. EITHER will means
106 * the caller doesn't know what kind of directory block will be read,
107 * so no specific verification will be done.
110 EITHER, INDEX, DIRENT, DIRENT_HTREE
113 #define ext4_read_dirblock(inode, block, type) \
114 __ext4_read_dirblock((inode), (block), (type), __func__, __LINE__)
116 static struct buffer_head *__ext4_read_dirblock(struct inode *inode,
118 dirblock_type_t type,
122 struct buffer_head *bh;
123 struct ext4_dir_entry *dirent;
126 bh = ext4_bread(NULL, inode, block, 0);
128 __ext4_warning(inode->i_sb, func, line,
129 "inode #%lu: lblock %lu: comm %s: "
130 "error %ld reading directory block",
131 inode->i_ino, (unsigned long)block,
132 current->comm, PTR_ERR(bh));
136 if (!bh && (type == INDEX || type == DIRENT_HTREE)) {
137 ext4_error_inode(inode, func, line, block,
138 "Directory hole found for htree %s block",
139 (type == INDEX) ? "index" : "leaf");
140 return ERR_PTR(-EFSCORRUPTED);
144 dirent = (struct ext4_dir_entry *) bh->b_data;
145 /* Determine whether or not we have an index block */
149 else if (ext4_rec_len_from_disk(dirent->rec_len,
150 inode->i_sb->s_blocksize) ==
151 inode->i_sb->s_blocksize)
154 if (!is_dx_block && type == INDEX) {
155 ext4_error_inode(inode, func, line, block,
156 "directory leaf block found instead of index block");
158 return ERR_PTR(-EFSCORRUPTED);
160 if (!ext4_has_metadata_csum(inode->i_sb) ||
165 * An empty leaf block can get mistaken for a index block; for
166 * this reason, we can only check the index checksum when the
167 * caller is sure it should be an index block.
169 if (is_dx_block && type == INDEX) {
170 if (ext4_dx_csum_verify(inode, dirent))
171 set_buffer_verified(bh);
173 ext4_error_inode(inode, func, line, block,
174 "Directory index failed checksum");
176 return ERR_PTR(-EFSBADCRC);
180 if (ext4_dirent_csum_verify(inode, dirent))
181 set_buffer_verified(bh);
183 ext4_error_inode(inode, func, line, block,
184 "Directory block failed checksum");
186 return ERR_PTR(-EFSBADCRC);
193 #define assert(test) J_ASSERT(test)
197 #define dxtrace(command) command
199 #define dxtrace(command)
223 * dx_root_info is laid out so that if it should somehow get overlaid by a
224 * dirent the two low bits of the hash version will be zero. Therefore, the
225 * hash version mod 4 should never be 0. Sincerely, the paranoia department.
230 struct fake_dirent dot;
232 struct fake_dirent dotdot;
236 __le32 reserved_zero;
238 u8 info_length; /* 8 */
243 struct dx_entry entries[0];
248 struct fake_dirent fake;
249 struct dx_entry entries[0];
255 struct buffer_head *bh;
256 struct dx_entry *entries;
268 * This goes at the end of each htree block.
272 __le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */
275 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry);
276 static void dx_set_block(struct dx_entry *entry, ext4_lblk_t value);
277 static inline unsigned dx_get_hash(struct dx_entry *entry);
278 static void dx_set_hash(struct dx_entry *entry, unsigned value);
279 static unsigned dx_get_count(struct dx_entry *entries);
280 static unsigned dx_get_limit(struct dx_entry *entries);
281 static void dx_set_count(struct dx_entry *entries, unsigned value);
282 static void dx_set_limit(struct dx_entry *entries, unsigned value);
283 static unsigned dx_root_limit(struct inode *dir, unsigned infosize);
284 static unsigned dx_node_limit(struct inode *dir);
285 static struct dx_frame *dx_probe(struct ext4_filename *fname,
287 struct dx_hash_info *hinfo,
288 struct dx_frame *frame);
289 static void dx_release(struct dx_frame *frames);
290 static int dx_make_map(struct inode *dir, struct buffer_head *bh,
291 struct dx_hash_info *hinfo,
292 struct dx_map_entry *map_tail);
293 static void dx_sort_map(struct dx_map_entry *map, unsigned count);
294 static struct ext4_dir_entry_2 *dx_move_dirents(char *from, char *to,
295 struct dx_map_entry *offsets, int count, unsigned blocksize);
296 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize);
297 static void dx_insert_block(struct dx_frame *frame,
298 u32 hash, ext4_lblk_t block);
299 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
300 struct dx_frame *frame,
301 struct dx_frame *frames,
303 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
304 struct ext4_filename *fname,
305 struct ext4_dir_entry_2 **res_dir);
306 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
307 struct inode *dir, struct inode *inode);
309 /* checksumming functions */
310 void initialize_dirent_tail(struct ext4_dir_entry_tail *t,
311 unsigned int blocksize)
313 memset(t, 0, sizeof(struct ext4_dir_entry_tail));
314 t->det_rec_len = ext4_rec_len_to_disk(
315 sizeof(struct ext4_dir_entry_tail), blocksize);
316 t->det_reserved_ft = EXT4_FT_DIR_CSUM;
319 /* Walk through a dirent block to find a checksum "dirent" at the tail */
320 static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode,
321 struct ext4_dir_entry *de)
323 struct ext4_dir_entry_tail *t;
324 int blocksize = EXT4_BLOCK_SIZE(inode->i_sb);
327 struct ext4_dir_entry *d, *top;
330 top = (struct ext4_dir_entry *)(((void *)de) +
331 (blocksize - sizeof(struct ext4_dir_entry_tail)));
332 while (d < top && ext4_rec_len_from_disk(d->rec_len, blocksize))
333 d = (struct ext4_dir_entry *)(((void *)d) +
334 ext4_rec_len_from_disk(d->rec_len, blocksize));
339 t = (struct ext4_dir_entry_tail *)d;
341 t = EXT4_DIRENT_TAIL(de, EXT4_BLOCK_SIZE(inode->i_sb));
344 if (t->det_reserved_zero1 ||
345 (ext4_rec_len_from_disk(t->det_rec_len, blocksize) !=
346 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;
428 int blocksize = EXT4_BLOCK_SIZE(inode->i_sb);
429 unsigned int rlen = ext4_rec_len_from_disk(dirent->rec_len, blocksize);
431 if (rlen == blocksize)
433 else if (rlen == 12) {
434 dp = (struct ext4_dir_entry *)(((void *)dirent) + 12);
435 if (ext4_rec_len_from_disk(dp->rec_len, blocksize) != blocksize - 12)
437 root = (struct dx_root_info *)(((void *)dp + 12));
438 if (root->reserved_zero ||
439 root->info_length != sizeof(struct dx_root_info))
446 *offset = count_offset;
447 return (struct dx_countlimit *)(((void *)dirent) + count_offset);
450 static __le32 ext4_dx_csum(struct inode *inode, struct ext4_dir_entry *dirent,
451 int count_offset, int count, struct dx_tail *t)
453 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
454 struct ext4_inode_info *ei = EXT4_I(inode);
457 __u32 dummy_csum = 0;
458 int offset = offsetof(struct dx_tail, dt_checksum);
460 size = count_offset + (count * sizeof(struct dx_entry));
461 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
462 csum = ext4_chksum(sbi, csum, (__u8 *)t, offset);
463 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
465 return cpu_to_le32(csum);
468 static int ext4_dx_csum_verify(struct inode *inode,
469 struct ext4_dir_entry *dirent)
471 struct dx_countlimit *c;
473 int count_offset, limit, count;
475 if (!ext4_has_metadata_csum(inode->i_sb))
478 c = get_dx_countlimit(inode, dirent, &count_offset);
480 EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
483 limit = le16_to_cpu(c->limit);
484 count = le16_to_cpu(c->count);
485 if (count_offset + (limit * sizeof(struct dx_entry)) >
486 EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
487 warn_no_space_for_csum(inode);
490 t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
492 if (t->dt_checksum != ext4_dx_csum(inode, dirent, count_offset,
498 static void ext4_dx_csum_set(struct inode *inode, struct ext4_dir_entry *dirent)
500 struct dx_countlimit *c;
502 int count_offset, limit, count;
504 if (!ext4_has_metadata_csum(inode->i_sb))
507 c = get_dx_countlimit(inode, dirent, &count_offset);
509 EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
512 limit = le16_to_cpu(c->limit);
513 count = le16_to_cpu(c->count);
514 if (count_offset + (limit * sizeof(struct dx_entry)) >
515 EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
516 warn_no_space_for_csum(inode);
519 t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
521 t->dt_checksum = ext4_dx_csum(inode, dirent, count_offset, count, t);
524 static inline int ext4_handle_dirty_dx_node(handle_t *handle,
526 struct buffer_head *bh)
528 ext4_dx_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
529 return ext4_handle_dirty_metadata(handle, inode, bh);
533 * p is at least 6 bytes before the end of page
535 static inline struct ext4_dir_entry_2 *
536 ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize)
538 return (struct ext4_dir_entry_2 *)((char *)p +
539 ext4_rec_len_from_disk(p->rec_len, blocksize));
543 * Future: use high four bits of block for coalesce-on-delete flags
544 * Mask them off for now.
547 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry)
549 return le32_to_cpu(entry->block) & 0x0fffffff;
552 static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value)
554 entry->block = cpu_to_le32(value);
557 static inline unsigned dx_get_hash(struct dx_entry *entry)
559 return le32_to_cpu(entry->hash);
562 static inline void dx_set_hash(struct dx_entry *entry, unsigned value)
564 entry->hash = cpu_to_le32(value);
567 static inline unsigned dx_get_count(struct dx_entry *entries)
569 return le16_to_cpu(((struct dx_countlimit *) entries)->count);
572 static inline unsigned dx_get_limit(struct dx_entry *entries)
574 return le16_to_cpu(((struct dx_countlimit *) entries)->limit);
577 static inline void dx_set_count(struct dx_entry *entries, unsigned value)
579 ((struct dx_countlimit *) entries)->count = cpu_to_le16(value);
582 static inline void dx_set_limit(struct dx_entry *entries, unsigned value)
584 ((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
587 static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize)
589 unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(1) -
590 EXT4_DIR_REC_LEN(2) - infosize;
592 if (ext4_has_metadata_csum(dir->i_sb))
593 entry_space -= sizeof(struct dx_tail);
594 return entry_space / sizeof(struct dx_entry);
597 static inline unsigned dx_node_limit(struct inode *dir)
599 unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0);
601 if (ext4_has_metadata_csum(dir->i_sb))
602 entry_space -= sizeof(struct dx_tail);
603 return entry_space / sizeof(struct dx_entry);
610 static void dx_show_index(char * label, struct dx_entry *entries)
612 int i, n = dx_get_count (entries);
613 printk(KERN_DEBUG "%s index", label);
614 for (i = 0; i < n; i++) {
615 printk(KERN_CONT " %x->%lu",
616 i ? dx_get_hash(entries + i) : 0,
617 (unsigned long)dx_get_block(entries + i));
619 printk(KERN_CONT "\n");
629 static struct stats dx_show_leaf(struct inode *dir,
630 struct dx_hash_info *hinfo,
631 struct ext4_dir_entry_2 *de,
632 int size, int show_names)
634 unsigned names = 0, space = 0;
635 char *base = (char *) de;
636 struct dx_hash_info h = *hinfo;
639 while ((char *) de < base + size)
645 #ifdef CONFIG_EXT4_FS_ENCRYPTION
648 struct fscrypt_str fname_crypto_str =
654 if (ext4_encrypted_inode(dir))
655 res = fscrypt_get_encryption_info(dir);
657 printk(KERN_WARNING "Error setting up"
658 " fname crypto: %d\n", res);
660 if (!fscrypt_has_encryption_key(dir)) {
661 /* Directory is not encrypted */
662 ext4fs_dirhash(de->name,
664 printk("%*.s:(U)%x.%u ", len,
666 (unsigned) ((char *) de
669 struct fscrypt_str de_name =
670 FSTR_INIT(name, len);
672 /* Directory is encrypted */
673 res = fscrypt_fname_alloc_buffer(
677 printk(KERN_WARNING "Error "
681 res = fscrypt_fname_disk_to_usr(dir,
685 printk(KERN_WARNING "Error "
686 "converting filename "
692 name = fname_crypto_str.name;
693 len = fname_crypto_str.len;
695 ext4fs_dirhash(de->name, de->name_len,
697 printk("%*.s:(E)%x.%u ", len, name,
698 h.hash, (unsigned) ((char *) de
700 fscrypt_fname_free_buffer(
704 int len = de->name_len;
705 char *name = de->name;
706 ext4fs_dirhash(de->name, de->name_len, &h);
707 printk("%*.s:%x.%u ", len, name, h.hash,
708 (unsigned) ((char *) de - base));
711 space += EXT4_DIR_REC_LEN(de->name_len);
714 de = ext4_next_entry(de, size);
716 printk(KERN_CONT "(%i)\n", names);
717 return (struct stats) { names, space, 1 };
720 struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir,
721 struct dx_entry *entries, int levels)
723 unsigned blocksize = dir->i_sb->s_blocksize;
724 unsigned count = dx_get_count(entries), names = 0, space = 0, i;
726 struct buffer_head *bh;
727 printk("%i indexed blocks...\n", count);
728 for (i = 0; i < count; i++, entries++)
730 ext4_lblk_t block = dx_get_block(entries);
731 ext4_lblk_t hash = i ? dx_get_hash(entries): 0;
732 u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash;
734 printk("%s%3u:%03u hash %8x/%8x ",levels?"":" ", i, block, hash, range);
735 bh = ext4_bread(NULL,dir, block, 0);
736 if (!bh || IS_ERR(bh))
739 dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1):
740 dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *)
741 bh->b_data, blocksize, 0);
742 names += stats.names;
743 space += stats.space;
744 bcount += stats.bcount;
748 printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n",
749 levels ? "" : " ", names, space/bcount,
750 (space/bcount)*100/blocksize);
751 return (struct stats) { names, space, bcount};
753 #endif /* DX_DEBUG */
756 * Probe for a directory leaf block to search.
758 * dx_probe can return ERR_BAD_DX_DIR, which means there was a format
759 * error in the directory index, and the caller should fall back to
760 * searching the directory normally. The callers of dx_probe **MUST**
761 * check for this error code, and make sure it never gets reflected
764 static struct dx_frame *
765 dx_probe(struct ext4_filename *fname, struct inode *dir,
766 struct dx_hash_info *hinfo, struct dx_frame *frame_in)
768 unsigned count, indirect, level, i;
769 struct dx_entry *at, *entries, *p, *q, *m;
770 struct dx_root *root;
771 struct dx_frame *frame = frame_in;
772 struct dx_frame *ret_err = ERR_PTR(ERR_BAD_DX_DIR);
775 ext4_lblk_t blocks[EXT4_HTREE_LEVEL];
777 memset(frame_in, 0, EXT4_HTREE_LEVEL * sizeof(frame_in[0]));
778 frame->bh = ext4_read_dirblock(dir, 0, INDEX);
779 if (IS_ERR(frame->bh))
780 return (struct dx_frame *) frame->bh;
782 root = (struct dx_root *) frame->bh->b_data;
783 if (root->info.hash_version != DX_HASH_TEA &&
784 root->info.hash_version != DX_HASH_HALF_MD4 &&
785 root->info.hash_version != DX_HASH_LEGACY) {
786 ext4_warning_inode(dir, "Unrecognised inode hash code %u",
787 root->info.hash_version);
791 hinfo = &fname->hinfo;
792 hinfo->hash_version = root->info.hash_version;
793 if (hinfo->hash_version <= DX_HASH_TEA)
794 hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
795 hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed;
796 if (fname && fname_name(fname))
797 ext4fs_dirhash(fname_name(fname), fname_len(fname), hinfo);
800 if (root->info.unused_flags & 1) {
801 ext4_warning_inode(dir, "Unimplemented hash flags: %#06x",
802 root->info.unused_flags);
806 indirect = root->info.indirect_levels;
807 if (indirect >= ext4_dir_htree_level(dir->i_sb)) {
808 ext4_warning(dir->i_sb,
809 "Directory (ino: %lu) htree depth %#06x exceed"
810 "supported value", dir->i_ino,
811 ext4_dir_htree_level(dir->i_sb));
812 if (ext4_dir_htree_level(dir->i_sb) < EXT4_HTREE_LEVEL) {
813 ext4_warning(dir->i_sb, "Enable large directory "
814 "feature to access it");
819 entries = (struct dx_entry *)(((char *)&root->info) +
820 root->info.info_length);
822 if (dx_get_limit(entries) != dx_root_limit(dir,
823 root->info.info_length)) {
824 ext4_warning_inode(dir, "dx entry: limit %u != root limit %u",
825 dx_get_limit(entries),
826 dx_root_limit(dir, root->info.info_length));
830 dxtrace(printk("Look up %x", hash));
834 count = dx_get_count(entries);
835 if (!count || count > dx_get_limit(entries)) {
836 ext4_warning_inode(dir,
837 "dx entry: count %u beyond limit %u",
838 count, dx_get_limit(entries));
843 q = entries + count - 1;
846 dxtrace(printk(KERN_CONT "."));
847 if (dx_get_hash(m) > hash)
853 if (0) { // linear search cross check
854 unsigned n = count - 1;
858 dxtrace(printk(KERN_CONT ","));
859 if (dx_get_hash(++at) > hash)
865 assert (at == p - 1);
869 dxtrace(printk(KERN_CONT " %x->%u\n",
870 at == entries ? 0 : dx_get_hash(at),
872 frame->entries = entries;
875 block = dx_get_block(at);
876 for (i = 0; i <= level; i++) {
877 if (blocks[i] == block) {
878 ext4_warning_inode(dir,
879 "dx entry: tree cycle block %u points back to block %u",
880 blocks[level], block);
884 if (++level > indirect)
886 blocks[level] = block;
888 frame->bh = ext4_read_dirblock(dir, block, INDEX);
889 if (IS_ERR(frame->bh)) {
890 ret_err = (struct dx_frame *) frame->bh;
895 entries = ((struct dx_node *) frame->bh->b_data)->entries;
897 if (dx_get_limit(entries) != dx_node_limit(dir)) {
898 ext4_warning_inode(dir,
899 "dx entry: limit %u != node limit %u",
900 dx_get_limit(entries), dx_node_limit(dir));
905 while (frame >= frame_in) {
910 if (ret_err == ERR_PTR(ERR_BAD_DX_DIR))
911 ext4_warning_inode(dir,
912 "Corrupt directory, running e2fsck is recommended");
916 static void dx_release(struct dx_frame *frames)
918 struct dx_root_info *info;
920 unsigned int indirect_levels;
922 if (frames[0].bh == NULL)
925 info = &((struct dx_root *)frames[0].bh->b_data)->info;
926 /* save local copy, "info" may be freed after brelse() */
927 indirect_levels = info->indirect_levels;
928 for (i = 0; i <= indirect_levels; i++) {
929 if (frames[i].bh == NULL)
931 brelse(frames[i].bh);
937 * This function increments the frame pointer to search the next leaf
938 * block, and reads in the necessary intervening nodes if the search
939 * should be necessary. Whether or not the search is necessary is
940 * controlled by the hash parameter. If the hash value is even, then
941 * the search is only continued if the next block starts with that
942 * hash value. This is used if we are searching for a specific file.
944 * If the hash value is HASH_NB_ALWAYS, then always go to the next block.
946 * This function returns 1 if the caller should continue to search,
947 * or 0 if it should not. If there is an error reading one of the
948 * index blocks, it will a negative error code.
950 * If start_hash is non-null, it will be filled in with the starting
951 * hash of the next page.
953 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
954 struct dx_frame *frame,
955 struct dx_frame *frames,
959 struct buffer_head *bh;
965 * Find the next leaf page by incrementing the frame pointer.
966 * If we run out of entries in the interior node, loop around and
967 * increment pointer in the parent node. When we break out of
968 * this loop, num_frames indicates the number of interior
969 * nodes need to be read.
972 if (++(p->at) < p->entries + dx_get_count(p->entries))
981 * If the hash is 1, then continue only if the next page has a
982 * continuation hash of any value. This is used for readdir
983 * handling. Otherwise, check to see if the hash matches the
984 * desired contiuation hash. If it doesn't, return since
985 * there's no point to read in the successive index pages.
987 bhash = dx_get_hash(p->at);
990 if ((hash & 1) == 0) {
991 if ((bhash & ~1) != hash)
995 * If the hash is HASH_NB_ALWAYS, we always go to the next
996 * block so no check is necessary
998 while (num_frames--) {
999 bh = ext4_read_dirblock(dir, dx_get_block(p->at), INDEX);
1005 p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
1012 * This function fills a red-black tree with information from a
1013 * directory block. It returns the number directory entries loaded
1014 * into the tree. If there is an error it is returned in err.
1016 static int htree_dirblock_to_tree(struct file *dir_file,
1017 struct inode *dir, ext4_lblk_t block,
1018 struct dx_hash_info *hinfo,
1019 __u32 start_hash, __u32 start_minor_hash)
1021 struct buffer_head *bh;
1022 struct ext4_dir_entry_2 *de, *top;
1023 int err = 0, count = 0;
1024 struct fscrypt_str fname_crypto_str = FSTR_INIT(NULL, 0), tmp_str;
1026 dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n",
1027 (unsigned long)block));
1028 bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
1032 de = (struct ext4_dir_entry_2 *) bh->b_data;
1033 top = (struct ext4_dir_entry_2 *) ((char *) de +
1034 dir->i_sb->s_blocksize -
1035 EXT4_DIR_REC_LEN(0));
1036 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1037 /* Check if the directory is encrypted */
1038 if (ext4_encrypted_inode(dir)) {
1039 err = fscrypt_get_encryption_info(dir);
1044 err = fscrypt_fname_alloc_buffer(dir, EXT4_NAME_LEN,
1052 for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) {
1053 if (ext4_check_dir_entry(dir, NULL, de, bh,
1054 bh->b_data, bh->b_size,
1055 (block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb))
1056 + ((char *)de - bh->b_data))) {
1057 /* silently ignore the rest of the block */
1060 ext4fs_dirhash(de->name, de->name_len, hinfo);
1061 if ((hinfo->hash < start_hash) ||
1062 ((hinfo->hash == start_hash) &&
1063 (hinfo->minor_hash < start_minor_hash)))
1067 if (!ext4_encrypted_inode(dir)) {
1068 tmp_str.name = de->name;
1069 tmp_str.len = de->name_len;
1070 err = ext4_htree_store_dirent(dir_file,
1071 hinfo->hash, hinfo->minor_hash, de,
1074 int save_len = fname_crypto_str.len;
1075 struct fscrypt_str de_name = FSTR_INIT(de->name,
1078 /* Directory is encrypted */
1079 err = fscrypt_fname_disk_to_usr(dir, hinfo->hash,
1080 hinfo->minor_hash, &de_name,
1086 err = ext4_htree_store_dirent(dir_file,
1087 hinfo->hash, hinfo->minor_hash, de,
1089 fname_crypto_str.len = save_len;
1099 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1100 fscrypt_fname_free_buffer(&fname_crypto_str);
1107 * This function fills a red-black tree with information from a
1108 * directory. We start scanning the directory in hash order, starting
1109 * at start_hash and start_minor_hash.
1111 * This function returns the number of entries inserted into the tree,
1112 * or a negative error code.
1114 int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
1115 __u32 start_minor_hash, __u32 *next_hash)
1117 struct dx_hash_info hinfo;
1118 struct ext4_dir_entry_2 *de;
1119 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1125 struct fscrypt_str tmp_str;
1127 dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n",
1128 start_hash, start_minor_hash));
1129 dir = file_inode(dir_file);
1130 if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) {
1131 hinfo.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
1132 if (hinfo.hash_version <= DX_HASH_TEA)
1133 hinfo.hash_version +=
1134 EXT4_SB(dir->i_sb)->s_hash_unsigned;
1135 hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
1136 if (ext4_has_inline_data(dir)) {
1137 int has_inline_data = 1;
1138 count = htree_inlinedir_to_tree(dir_file, dir, 0,
1142 if (has_inline_data) {
1147 count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo,
1148 start_hash, start_minor_hash);
1152 hinfo.hash = start_hash;
1153 hinfo.minor_hash = 0;
1154 frame = dx_probe(NULL, dir, &hinfo, frames);
1156 return PTR_ERR(frame);
1158 /* Add '.' and '..' from the htree header */
1159 if (!start_hash && !start_minor_hash) {
1160 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1161 tmp_str.name = de->name;
1162 tmp_str.len = de->name_len;
1163 err = ext4_htree_store_dirent(dir_file, 0, 0,
1169 if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) {
1170 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1171 de = ext4_next_entry(de, dir->i_sb->s_blocksize);
1172 tmp_str.name = de->name;
1173 tmp_str.len = de->name_len;
1174 err = ext4_htree_store_dirent(dir_file, 2, 0,
1182 if (fatal_signal_pending(current)) {
1187 block = dx_get_block(frame->at);
1188 ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
1189 start_hash, start_minor_hash);
1196 ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS,
1197 frame, frames, &hashval);
1198 *next_hash = hashval;
1204 * Stop if: (a) there are no more entries, or
1205 * (b) we have inserted at least one entry and the
1206 * next hash value is not a continuation
1209 (count && ((hashval & 1) == 0)))
1213 dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, "
1214 "next hash: %x\n", count, *next_hash));
1221 static inline int search_dirblock(struct buffer_head *bh,
1223 struct ext4_filename *fname,
1224 unsigned int offset,
1225 struct ext4_dir_entry_2 **res_dir)
1227 return ext4_search_dir(bh, bh->b_data, dir->i_sb->s_blocksize, dir,
1228 fname, offset, res_dir);
1232 * Directory block splitting, compacting
1236 * Create map of hash values, offsets, and sizes, stored at end of block.
1237 * Returns number of entries mapped.
1239 static int dx_make_map(struct inode *dir, struct buffer_head *bh,
1240 struct dx_hash_info *hinfo,
1241 struct dx_map_entry *map_tail)
1244 struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)bh->b_data;
1245 unsigned int buflen = bh->b_size;
1246 char *base = bh->b_data;
1247 struct dx_hash_info h = *hinfo;
1248 int blocksize = EXT4_BLOCK_SIZE(dir->i_sb);
1250 if (ext4_has_metadata_csum(dir->i_sb))
1251 buflen -= sizeof(struct ext4_dir_entry_tail);
1253 while ((char *) de < base + buflen) {
1254 if (ext4_check_dir_entry(dir, NULL, de, bh, base, buflen,
1255 ((char *)de) - base))
1256 return -EFSCORRUPTED;
1257 if (de->name_len && de->inode) {
1258 ext4fs_dirhash(de->name, de->name_len, &h);
1260 map_tail->hash = h.hash;
1261 map_tail->offs = ((char *) de - base)>>2;
1262 map_tail->size = ext4_rec_len_from_disk(de->rec_len,
1267 de = ext4_next_entry(de, blocksize);
1272 /* Sort map by hash value */
1273 static void dx_sort_map (struct dx_map_entry *map, unsigned count)
1275 struct dx_map_entry *p, *q, *top = map + count - 1;
1277 /* Combsort until bubble sort doesn't suck */
1279 count = count*10/13;
1280 if (count - 9 < 2) /* 9, 10 -> 11 */
1282 for (p = top, q = p - count; q >= map; p--, q--)
1283 if (p->hash < q->hash)
1286 /* Garden variety bubble sort */
1291 if (q[1].hash >= q[0].hash)
1299 static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block)
1301 struct dx_entry *entries = frame->entries;
1302 struct dx_entry *old = frame->at, *new = old + 1;
1303 int count = dx_get_count(entries);
1305 assert(count < dx_get_limit(entries));
1306 assert(old < entries + count);
1307 memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
1308 dx_set_hash(new, hash);
1309 dx_set_block(new, block);
1310 dx_set_count(entries, count + 1);
1314 * Test whether a directory entry matches the filename being searched for.
1316 * Return: %true if the directory entry matches, otherwise %false.
1318 static inline bool ext4_match(const struct ext4_filename *fname,
1319 const struct ext4_dir_entry_2 *de)
1321 struct fscrypt_name f;
1326 f.usr_fname = fname->usr_fname;
1327 f.disk_name = fname->disk_name;
1328 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1329 f.crypto_buf = fname->crypto_buf;
1331 return fscrypt_match_name(&f, de->name, de->name_len);
1335 * Returns 0 if not found, -1 on failure, and 1 on success
1337 int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size,
1338 struct inode *dir, struct ext4_filename *fname,
1339 unsigned int offset, struct ext4_dir_entry_2 **res_dir)
1341 struct ext4_dir_entry_2 * de;
1345 de = (struct ext4_dir_entry_2 *)search_buf;
1346 dlimit = search_buf + buf_size;
1347 while ((char *) de < dlimit) {
1348 /* this code is executed quadratically often */
1349 /* do minimal checking `by hand' */
1350 if ((char *) de + de->name_len <= dlimit &&
1351 ext4_match(fname, de)) {
1352 /* found a match - just to be sure, do
1354 if (ext4_check_dir_entry(dir, NULL, de, bh, search_buf,
1360 /* prevent looping on a bad block */
1361 de_len = ext4_rec_len_from_disk(de->rec_len,
1362 dir->i_sb->s_blocksize);
1366 de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
1371 static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block,
1372 struct ext4_dir_entry *de)
1374 struct super_block *sb = dir->i_sb;
1380 if (de->inode == 0 &&
1381 ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) ==
1390 * finds an entry in the specified directory with the wanted name. It
1391 * returns the cache buffer in which the entry was found, and the entry
1392 * itself (as a parameter - res_dir). It does NOT read the inode of the
1393 * entry - you'll have to do that yourself if you want to.
1395 * The returned buffer_head has ->b_count elevated. The caller is expected
1396 * to brelse() it when appropriate.
1398 static struct buffer_head * ext4_find_entry (struct inode *dir,
1399 const struct qstr *d_name,
1400 struct ext4_dir_entry_2 **res_dir,
1403 struct super_block *sb;
1404 struct buffer_head *bh_use[NAMEI_RA_SIZE];
1405 struct buffer_head *bh, *ret = NULL;
1406 ext4_lblk_t start, block;
1407 const u8 *name = d_name->name;
1408 size_t ra_max = 0; /* Number of bh's in the readahead
1410 size_t ra_ptr = 0; /* Current index into readahead
1412 ext4_lblk_t nblocks;
1413 int i, namelen, retval;
1414 struct ext4_filename fname;
1418 namelen = d_name->len;
1419 if (namelen > EXT4_NAME_LEN)
1422 retval = ext4_fname_setup_filename(dir, d_name, 1, &fname);
1423 if (retval == -ENOENT)
1426 return ERR_PTR(retval);
1428 if (ext4_has_inline_data(dir)) {
1429 int has_inline_data = 1;
1430 ret = ext4_find_inline_entry(dir, &fname, res_dir,
1433 *inlined = has_inline_data;
1434 if (has_inline_data)
1435 goto cleanup_and_exit;
1438 if ((namelen <= 2) && (name[0] == '.') &&
1439 (name[1] == '.' || name[1] == '\0')) {
1441 * "." or ".." will only be in the first block
1442 * NFS may look up ".."; "." should be handled by the VFS
1449 ret = ext4_dx_find_entry(dir, &fname, res_dir);
1451 * On success, or if the error was file not found,
1452 * return. Otherwise, fall back to doing a search the
1453 * old fashioned way.
1455 if (!IS_ERR(ret) || PTR_ERR(ret) != ERR_BAD_DX_DIR)
1456 goto cleanup_and_exit;
1457 dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
1461 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1464 goto cleanup_and_exit;
1466 start = EXT4_I(dir)->i_dir_start_lookup;
1467 if (start >= nblocks)
1473 * We deal with the read-ahead logic here.
1476 if (ra_ptr >= ra_max) {
1477 /* Refill the readahead buffer */
1480 ra_max = start - block;
1482 ra_max = nblocks - block;
1483 ra_max = min(ra_max, ARRAY_SIZE(bh_use));
1484 retval = ext4_bread_batch(dir, block, ra_max,
1485 false /* wait */, bh_use);
1487 ret = ERR_PTR(retval);
1489 goto cleanup_and_exit;
1492 if ((bh = bh_use[ra_ptr++]) == NULL)
1495 if (!buffer_uptodate(bh)) {
1496 EXT4_ERROR_INODE(dir, "reading directory lblock %lu",
1497 (unsigned long) block);
1499 ret = ERR_PTR(-EIO);
1500 goto cleanup_and_exit;
1502 if (!buffer_verified(bh) &&
1503 !is_dx_internal_node(dir, block,
1504 (struct ext4_dir_entry *)bh->b_data) &&
1505 !ext4_dirent_csum_verify(dir,
1506 (struct ext4_dir_entry *)bh->b_data)) {
1507 EXT4_ERROR_INODE(dir, "checksumming directory "
1508 "block %lu", (unsigned long)block);
1510 ret = ERR_PTR(-EFSBADCRC);
1511 goto cleanup_and_exit;
1513 set_buffer_verified(bh);
1514 i = search_dirblock(bh, dir, &fname,
1515 block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
1517 EXT4_I(dir)->i_dir_start_lookup = block;
1519 goto cleanup_and_exit;
1523 goto cleanup_and_exit;
1526 if (++block >= nblocks)
1528 } while (block != start);
1531 * If the directory has grown while we were searching, then
1532 * search the last part of the directory before giving up.
1535 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1536 if (block < nblocks) {
1542 /* Clean up the read-ahead blocks */
1543 for (; ra_ptr < ra_max; ra_ptr++)
1544 brelse(bh_use[ra_ptr]);
1545 ext4_fname_free_filename(&fname);
1549 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
1550 struct ext4_filename *fname,
1551 struct ext4_dir_entry_2 **res_dir)
1553 struct super_block * sb = dir->i_sb;
1554 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1555 struct buffer_head *bh;
1559 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1562 frame = dx_probe(fname, dir, NULL, frames);
1564 return (struct buffer_head *) frame;
1566 block = dx_get_block(frame->at);
1567 bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
1571 retval = search_dirblock(bh, dir, fname,
1572 block << EXT4_BLOCK_SIZE_BITS(sb),
1578 bh = ERR_PTR(ERR_BAD_DX_DIR);
1582 /* Check to see if we should continue to search */
1583 retval = ext4_htree_next_block(dir, fname->hinfo.hash, frame,
1586 ext4_warning_inode(dir,
1587 "error %d reading directory index block",
1589 bh = ERR_PTR(retval);
1592 } while (retval == 1);
1596 dxtrace(printk(KERN_DEBUG "%s not found\n", fname->usr_fname->name));
1602 static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
1604 struct inode *inode;
1605 struct ext4_dir_entry_2 *de;
1606 struct buffer_head *bh;
1608 if (ext4_encrypted_inode(dir)) {
1609 int res = fscrypt_get_encryption_info(dir);
1612 * DCACHE_ENCRYPTED_WITH_KEY is set if the dentry is
1613 * created while the directory was encrypted and we
1614 * have access to the key.
1616 if (fscrypt_has_encryption_key(dir))
1617 fscrypt_set_encrypted_dentry(dentry);
1618 fscrypt_set_d_op(dentry);
1619 if (res && res != -ENOKEY)
1620 return ERR_PTR(res);
1623 if (dentry->d_name.len > EXT4_NAME_LEN)
1624 return ERR_PTR(-ENAMETOOLONG);
1626 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
1628 return (struct dentry *) bh;
1631 __u32 ino = le32_to_cpu(de->inode);
1633 if (!ext4_valid_inum(dir->i_sb, ino)) {
1634 EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
1635 return ERR_PTR(-EFSCORRUPTED);
1637 if (unlikely(ino == dir->i_ino)) {
1638 EXT4_ERROR_INODE(dir, "'%pd' linked to parent dir",
1640 return ERR_PTR(-EFSCORRUPTED);
1642 inode = ext4_iget(dir->i_sb, ino, EXT4_IGET_NORMAL);
1643 if (inode == ERR_PTR(-ESTALE)) {
1644 EXT4_ERROR_INODE(dir,
1645 "deleted inode referenced: %u",
1647 return ERR_PTR(-EFSCORRUPTED);
1649 if (!IS_ERR(inode) && ext4_encrypted_inode(dir) &&
1650 (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
1651 !fscrypt_has_permitted_context(dir, inode)) {
1652 ext4_warning(inode->i_sb,
1653 "Inconsistent encryption contexts: %lu/%lu",
1654 dir->i_ino, inode->i_ino);
1656 return ERR_PTR(-EPERM);
1659 return d_splice_alias(inode, dentry);
1663 struct dentry *ext4_get_parent(struct dentry *child)
1666 static const struct qstr dotdot = QSTR_INIT("..", 2);
1667 struct ext4_dir_entry_2 * de;
1668 struct buffer_head *bh;
1670 bh = ext4_find_entry(d_inode(child), &dotdot, &de, NULL);
1672 return (struct dentry *) bh;
1674 return ERR_PTR(-ENOENT);
1675 ino = le32_to_cpu(de->inode);
1678 if (!ext4_valid_inum(child->d_sb, ino)) {
1679 EXT4_ERROR_INODE(d_inode(child),
1680 "bad parent inode number: %u", ino);
1681 return ERR_PTR(-EFSCORRUPTED);
1684 return d_obtain_alias(ext4_iget(child->d_sb, ino, EXT4_IGET_NORMAL));
1688 * Move count entries from end of map between two memory locations.
1689 * Returns pointer to last entry moved.
1691 static struct ext4_dir_entry_2 *
1692 dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count,
1695 unsigned rec_len = 0;
1698 struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
1699 (from + (map->offs<<2));
1700 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1701 memcpy (to, de, rec_len);
1702 ((struct ext4_dir_entry_2 *) to)->rec_len =
1703 ext4_rec_len_to_disk(rec_len, blocksize);
1708 return (struct ext4_dir_entry_2 *) (to - rec_len);
1712 * Compact each dir entry in the range to the minimal rec_len.
1713 * Returns pointer to last entry in range.
1715 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize)
1717 struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
1718 unsigned rec_len = 0;
1721 while ((char*)de < base + blocksize) {
1722 next = ext4_next_entry(de, blocksize);
1723 if (de->inode && de->name_len) {
1724 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1726 memmove(to, de, rec_len);
1727 to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
1729 to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
1737 * Split a full leaf block to make room for a new dir entry.
1738 * Allocate a new block, and move entries so that they are approx. equally full.
1739 * Returns pointer to de in block into which the new entry will be inserted.
1741 static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
1742 struct buffer_head **bh,struct dx_frame *frame,
1743 struct dx_hash_info *hinfo)
1745 unsigned blocksize = dir->i_sb->s_blocksize;
1748 struct buffer_head *bh2;
1749 ext4_lblk_t newblock;
1751 struct dx_map_entry *map;
1752 char *data1 = (*bh)->b_data, *data2;
1753 unsigned split, move, size;
1754 struct ext4_dir_entry_2 *de = NULL, *de2;
1755 struct ext4_dir_entry_tail *t;
1759 if (ext4_has_metadata_csum(dir->i_sb))
1760 csum_size = sizeof(struct ext4_dir_entry_tail);
1762 bh2 = ext4_append(handle, dir, &newblock);
1766 return (struct ext4_dir_entry_2 *) bh2;
1769 BUFFER_TRACE(*bh, "get_write_access");
1770 err = ext4_journal_get_write_access(handle, *bh);
1774 BUFFER_TRACE(frame->bh, "get_write_access");
1775 err = ext4_journal_get_write_access(handle, frame->bh);
1779 data2 = bh2->b_data;
1781 /* create map in the end of data2 block */
1782 map = (struct dx_map_entry *) (data2 + blocksize);
1783 count = dx_make_map(dir, *bh, hinfo, map);
1789 dx_sort_map(map, count);
1790 /* Ensure that neither split block is over half full */
1793 for (i = count-1; i >= 0; i--) {
1794 /* is more than half of this entry in 2nd half of the block? */
1795 if (size + map[i].size/2 > blocksize/2)
1797 size += map[i].size;
1801 * map index at which we will split
1803 * If the sum of active entries didn't exceed half the block size, just
1804 * split it in half by count; each resulting block will have at least
1805 * half the space free.
1808 split = count - move;
1812 hash2 = map[split].hash;
1813 continued = hash2 == map[split - 1].hash;
1814 dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
1815 (unsigned long)dx_get_block(frame->at),
1816 hash2, split, count-split));
1818 /* Fancy dance to stay within two buffers */
1819 de2 = dx_move_dirents(data1, data2, map + split, count - split,
1821 de = dx_pack_dirents(data1, blocksize);
1822 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
1825 de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
1829 t = EXT4_DIRENT_TAIL(data2, blocksize);
1830 initialize_dirent_tail(t, blocksize);
1832 t = EXT4_DIRENT_TAIL(data1, blocksize);
1833 initialize_dirent_tail(t, blocksize);
1836 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,
1838 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,
1841 /* Which block gets the new entry? */
1842 if (hinfo->hash >= hash2) {
1846 dx_insert_block(frame, hash2 + continued, newblock);
1847 err = ext4_handle_dirty_dirent_node(handle, dir, bh2);
1850 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
1854 dxtrace(dx_show_index("frame", frame->entries));
1861 ext4_std_error(dir->i_sb, err);
1862 return ERR_PTR(err);
1865 int ext4_find_dest_de(struct inode *dir, struct inode *inode,
1866 struct buffer_head *bh,
1867 void *buf, int buf_size,
1868 struct ext4_filename *fname,
1869 struct ext4_dir_entry_2 **dest_de)
1871 struct ext4_dir_entry_2 *de;
1872 unsigned short reclen = EXT4_DIR_REC_LEN(fname_len(fname));
1874 unsigned int offset = 0;
1877 de = (struct ext4_dir_entry_2 *)buf;
1878 top = buf + buf_size - reclen;
1879 while ((char *) de <= top) {
1880 if (ext4_check_dir_entry(dir, NULL, de, bh,
1881 buf, buf_size, offset))
1882 return -EFSCORRUPTED;
1883 if (ext4_match(fname, de))
1885 nlen = EXT4_DIR_REC_LEN(de->name_len);
1886 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1887 if ((de->inode ? rlen - nlen : rlen) >= reclen)
1889 de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
1892 if ((char *) de > top)
1899 void ext4_insert_dentry(struct inode *inode,
1900 struct ext4_dir_entry_2 *de,
1902 struct ext4_filename *fname)
1907 nlen = EXT4_DIR_REC_LEN(de->name_len);
1908 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1910 struct ext4_dir_entry_2 *de1 =
1911 (struct ext4_dir_entry_2 *)((char *)de + nlen);
1912 de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size);
1913 de->rec_len = ext4_rec_len_to_disk(nlen, buf_size);
1916 de->file_type = EXT4_FT_UNKNOWN;
1917 de->inode = cpu_to_le32(inode->i_ino);
1918 ext4_set_de_type(inode->i_sb, de, inode->i_mode);
1919 de->name_len = fname_len(fname);
1920 memcpy(de->name, fname_name(fname), fname_len(fname));
1924 * Add a new entry into a directory (leaf) block. If de is non-NULL,
1925 * it points to a directory entry which is guaranteed to be large
1926 * enough for new directory entry. If de is NULL, then
1927 * add_dirent_to_buf will attempt search the directory block for
1928 * space. It will return -ENOSPC if no space is available, and -EIO
1929 * and -EEXIST if directory entry already exists.
1931 static int add_dirent_to_buf(handle_t *handle, struct ext4_filename *fname,
1933 struct inode *inode, struct ext4_dir_entry_2 *de,
1934 struct buffer_head *bh)
1936 unsigned int blocksize = dir->i_sb->s_blocksize;
1940 if (ext4_has_metadata_csum(inode->i_sb))
1941 csum_size = sizeof(struct ext4_dir_entry_tail);
1944 err = ext4_find_dest_de(dir, inode, bh, bh->b_data,
1945 blocksize - csum_size, fname, &de);
1949 BUFFER_TRACE(bh, "get_write_access");
1950 err = ext4_journal_get_write_access(handle, bh);
1952 ext4_std_error(dir->i_sb, err);
1956 /* By now the buffer is marked for journaling */
1957 ext4_insert_dentry(inode, de, blocksize, fname);
1960 * XXX shouldn't update any times until successful
1961 * completion of syscall, but too many callers depend
1964 * XXX similarly, too many callers depend on
1965 * ext4_new_inode() setting the times, but error
1966 * recovery deletes the inode, so the worst that can
1967 * happen is that the times are slightly out of date
1968 * and/or different from the directory change time.
1970 dir->i_mtime = dir->i_ctime = current_time(dir);
1971 ext4_update_dx_flag(dir);
1972 inode_inc_iversion(dir);
1973 ext4_mark_inode_dirty(handle, dir);
1974 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1975 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
1977 ext4_std_error(dir->i_sb, err);
1982 * This converts a one block unindexed directory to a 3 block indexed
1983 * directory, and adds the dentry to the indexed directory.
1985 static int make_indexed_dir(handle_t *handle, struct ext4_filename *fname,
1987 struct inode *inode, struct buffer_head *bh)
1989 struct buffer_head *bh2;
1990 struct dx_root *root;
1991 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1992 struct dx_entry *entries;
1993 struct ext4_dir_entry_2 *de, *de2;
1994 struct ext4_dir_entry_tail *t;
2000 struct fake_dirent *fde;
2003 if (ext4_has_metadata_csum(inode->i_sb))
2004 csum_size = sizeof(struct ext4_dir_entry_tail);
2006 blocksize = dir->i_sb->s_blocksize;
2007 dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
2008 BUFFER_TRACE(bh, "get_write_access");
2009 retval = ext4_journal_get_write_access(handle, bh);
2011 ext4_std_error(dir->i_sb, retval);
2015 root = (struct dx_root *) bh->b_data;
2017 /* The 0th block becomes the root, move the dirents out */
2018 fde = &root->dotdot;
2019 de = (struct ext4_dir_entry_2 *)((char *)fde +
2020 ext4_rec_len_from_disk(fde->rec_len, blocksize));
2021 if ((char *) de >= (((char *) root) + blocksize)) {
2022 EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
2024 return -EFSCORRUPTED;
2026 len = ((char *) root) + (blocksize - csum_size) - (char *) de;
2028 /* Allocate new block for the 0th block's dirents */
2029 bh2 = ext4_append(handle, dir, &block);
2032 return PTR_ERR(bh2);
2034 ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
2035 data1 = bh2->b_data;
2037 memcpy (data1, de, len);
2038 de = (struct ext4_dir_entry_2 *) data1;
2040 while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top)
2042 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
2047 t = EXT4_DIRENT_TAIL(data1, blocksize);
2048 initialize_dirent_tail(t, blocksize);
2051 /* Initialize the root; the dot dirents already exist */
2052 de = (struct ext4_dir_entry_2 *) (&root->dotdot);
2053 de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
2055 memset (&root->info, 0, sizeof(root->info));
2056 root->info.info_length = sizeof(root->info);
2057 root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
2058 entries = root->entries;
2059 dx_set_block(entries, 1);
2060 dx_set_count(entries, 1);
2061 dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
2063 /* Initialize as for dx_probe */
2064 fname->hinfo.hash_version = root->info.hash_version;
2065 if (fname->hinfo.hash_version <= DX_HASH_TEA)
2066 fname->hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
2067 fname->hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
2068 ext4fs_dirhash(fname_name(fname), fname_len(fname), &fname->hinfo);
2070 memset(frames, 0, sizeof(frames));
2072 frame->entries = entries;
2073 frame->at = entries;
2076 retval = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2079 retval = ext4_handle_dirty_dirent_node(handle, dir, bh2);
2083 de = do_split(handle,dir, &bh2, frame, &fname->hinfo);
2085 retval = PTR_ERR(de);
2089 retval = add_dirent_to_buf(handle, fname, dir, inode, de, bh2);
2092 * Even if the block split failed, we have to properly write
2093 * out all the changes we did so far. Otherwise we can end up
2094 * with corrupted filesystem.
2097 ext4_mark_inode_dirty(handle, dir);
2106 * adds a file entry to the specified directory, using the same
2107 * semantics as ext4_find_entry(). It returns NULL if it failed.
2109 * NOTE!! The inode part of 'de' is left at 0 - which means you
2110 * may not sleep between calling this and putting something into
2111 * the entry, as someone else might have used it while you slept.
2113 static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
2114 struct inode *inode)
2116 struct inode *dir = d_inode(dentry->d_parent);
2117 struct buffer_head *bh = NULL;
2118 struct ext4_dir_entry_2 *de;
2119 struct ext4_dir_entry_tail *t;
2120 struct super_block *sb;
2121 struct ext4_filename fname;
2125 ext4_lblk_t block, blocks;
2128 if (ext4_has_metadata_csum(inode->i_sb))
2129 csum_size = sizeof(struct ext4_dir_entry_tail);
2132 blocksize = sb->s_blocksize;
2133 if (!dentry->d_name.len)
2136 retval = ext4_fname_setup_filename(dir, &dentry->d_name, 0, &fname);
2140 if (ext4_has_inline_data(dir)) {
2141 retval = ext4_try_add_inline_entry(handle, &fname, dir, inode);
2151 retval = ext4_dx_add_entry(handle, &fname, dir, inode);
2152 if (!retval || (retval != ERR_BAD_DX_DIR))
2154 /* Can we just ignore htree data? */
2155 if (ext4_has_metadata_csum(sb)) {
2156 EXT4_ERROR_INODE(dir,
2157 "Directory has corrupted htree index.");
2158 retval = -EFSCORRUPTED;
2161 ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
2163 ext4_mark_inode_dirty(handle, dir);
2165 blocks = dir->i_size >> sb->s_blocksize_bits;
2166 for (block = 0; block < blocks; block++) {
2167 bh = ext4_read_dirblock(dir, block, DIRENT);
2169 bh = ext4_bread(handle, dir, block,
2170 EXT4_GET_BLOCKS_CREATE);
2171 goto add_to_new_block;
2174 retval = PTR_ERR(bh);
2178 retval = add_dirent_to_buf(handle, &fname, dir, inode,
2180 if (retval != -ENOSPC)
2183 if (blocks == 1 && !dx_fallback &&
2184 ext4_has_feature_dir_index(sb)) {
2185 retval = make_indexed_dir(handle, &fname, dir,
2187 bh = NULL; /* make_indexed_dir releases bh */
2192 bh = ext4_append(handle, dir, &block);
2195 retval = PTR_ERR(bh);
2199 de = (struct ext4_dir_entry_2 *) bh->b_data;
2201 de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
2204 t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
2205 initialize_dirent_tail(t, blocksize);
2208 retval = add_dirent_to_buf(handle, &fname, dir, inode, de, bh);
2210 ext4_fname_free_filename(&fname);
2213 ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
2218 * Returns 0 for success, or a negative error value
2220 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
2221 struct inode *dir, struct inode *inode)
2223 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
2224 struct dx_entry *entries, *at;
2225 struct buffer_head *bh;
2226 struct super_block *sb = dir->i_sb;
2227 struct ext4_dir_entry_2 *de;
2233 frame = dx_probe(fname, dir, NULL, frames);
2235 return PTR_ERR(frame);
2236 entries = frame->entries;
2238 bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT_HTREE);
2245 BUFFER_TRACE(bh, "get_write_access");
2246 err = ext4_journal_get_write_access(handle, bh);
2250 err = add_dirent_to_buf(handle, fname, dir, inode, NULL, bh);
2255 /* Block full, should compress but for now just split */
2256 dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
2257 dx_get_count(entries), dx_get_limit(entries)));
2258 /* Need to split index? */
2259 if (dx_get_count(entries) == dx_get_limit(entries)) {
2260 ext4_lblk_t newblock;
2261 int levels = frame - frames + 1;
2262 unsigned int icount;
2264 struct dx_entry *entries2;
2265 struct dx_node *node2;
2266 struct buffer_head *bh2;
2268 while (frame > frames) {
2269 if (dx_get_count((frame - 1)->entries) <
2270 dx_get_limit((frame - 1)->entries)) {
2274 frame--; /* split higher index block */
2276 entries = frame->entries;
2279 if (add_level && levels == ext4_dir_htree_level(sb)) {
2280 ext4_warning(sb, "Directory (ino: %lu) index full, "
2281 "reach max htree level :%d",
2282 dir->i_ino, levels);
2283 if (ext4_dir_htree_level(sb) < EXT4_HTREE_LEVEL) {
2284 ext4_warning(sb, "Large directory feature is "
2285 "not enabled on this "
2291 icount = dx_get_count(entries);
2292 bh2 = ext4_append(handle, dir, &newblock);
2297 node2 = (struct dx_node *)(bh2->b_data);
2298 entries2 = node2->entries;
2299 memset(&node2->fake, 0, sizeof(struct fake_dirent));
2300 node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
2302 BUFFER_TRACE(frame->bh, "get_write_access");
2303 err = ext4_journal_get_write_access(handle, frame->bh);
2307 unsigned icount1 = icount/2, icount2 = icount - icount1;
2308 unsigned hash2 = dx_get_hash(entries + icount1);
2309 dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
2312 BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
2313 err = ext4_journal_get_write_access(handle,
2318 memcpy((char *) entries2, (char *) (entries + icount1),
2319 icount2 * sizeof(struct dx_entry));
2320 dx_set_count(entries, icount1);
2321 dx_set_count(entries2, icount2);
2322 dx_set_limit(entries2, dx_node_limit(dir));
2324 /* Which index block gets the new entry? */
2325 if (at - entries >= icount1) {
2326 frame->at = at = at - entries - icount1 + entries2;
2327 frame->entries = entries = entries2;
2328 swap(frame->bh, bh2);
2330 dx_insert_block((frame - 1), hash2, newblock);
2331 dxtrace(dx_show_index("node", frame->entries));
2332 dxtrace(dx_show_index("node",
2333 ((struct dx_node *) bh2->b_data)->entries));
2334 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2338 err = ext4_handle_dirty_dx_node(handle, dir,
2342 err = ext4_handle_dirty_dx_node(handle, dir,
2347 struct dx_root *dxroot;
2348 memcpy((char *) entries2, (char *) entries,
2349 icount * sizeof(struct dx_entry));
2350 dx_set_limit(entries2, dx_node_limit(dir));
2353 dx_set_count(entries, 1);
2354 dx_set_block(entries + 0, newblock);
2355 dxroot = (struct dx_root *)frames[0].bh->b_data;
2356 dxroot->info.indirect_levels += 1;
2357 dxtrace(printk(KERN_DEBUG
2358 "Creating %d level index...\n",
2359 dxroot->info.indirect_levels));
2360 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2363 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2369 de = do_split(handle, dir, &bh, frame, &fname->hinfo);
2374 err = add_dirent_to_buf(handle, fname, dir, inode, de, bh);
2378 ext4_std_error(dir->i_sb, err); /* this is a no-op if err == 0 */
2382 /* @restart is true means htree-path has been changed, we need to
2383 * repeat dx_probe() to find out valid htree-path
2385 if (restart && err == 0)
2391 * ext4_generic_delete_entry deletes a directory entry by merging it
2392 * with the previous entry
2394 int ext4_generic_delete_entry(handle_t *handle,
2396 struct ext4_dir_entry_2 *de_del,
2397 struct buffer_head *bh,
2402 struct ext4_dir_entry_2 *de, *pde;
2403 unsigned int blocksize = dir->i_sb->s_blocksize;
2408 de = (struct ext4_dir_entry_2 *)entry_buf;
2409 while (i < buf_size - csum_size) {
2410 if (ext4_check_dir_entry(dir, NULL, de, bh,
2411 entry_buf, buf_size, i))
2412 return -EFSCORRUPTED;
2415 pde->rec_len = ext4_rec_len_to_disk(
2416 ext4_rec_len_from_disk(pde->rec_len,
2418 ext4_rec_len_from_disk(de->rec_len,
2423 inode_inc_iversion(dir);
2426 i += ext4_rec_len_from_disk(de->rec_len, blocksize);
2428 de = ext4_next_entry(de, blocksize);
2433 static int ext4_delete_entry(handle_t *handle,
2435 struct ext4_dir_entry_2 *de_del,
2436 struct buffer_head *bh)
2438 int err, csum_size = 0;
2440 if (ext4_has_inline_data(dir)) {
2441 int has_inline_data = 1;
2442 err = ext4_delete_inline_entry(handle, dir, de_del, bh,
2444 if (has_inline_data)
2448 if (ext4_has_metadata_csum(dir->i_sb))
2449 csum_size = sizeof(struct ext4_dir_entry_tail);
2451 BUFFER_TRACE(bh, "get_write_access");
2452 err = ext4_journal_get_write_access(handle, bh);
2456 err = ext4_generic_delete_entry(handle, dir, de_del,
2458 dir->i_sb->s_blocksize, csum_size);
2462 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
2463 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
2470 ext4_std_error(dir->i_sb, err);
2475 * Set directory link count to 1 if nlinks > EXT4_LINK_MAX, or if nlinks == 2
2476 * since this indicates that nlinks count was previously 1 to avoid overflowing
2477 * the 16-bit i_links_count field on disk. Directories with i_nlink == 1 mean
2478 * that subdirectory link counts are not being maintained accurately.
2480 * The caller has already checked for i_nlink overflow in case the DIR_LINK
2481 * feature is not enabled and returned -EMLINK. The is_dx() check is a proxy
2482 * for checking S_ISDIR(inode) (since the INODE_INDEX feature will not be set
2483 * on regular files) and to avoid creating huge/slow non-HTREE directories.
2485 static void ext4_inc_count(handle_t *handle, struct inode *inode)
2489 (inode->i_nlink > EXT4_LINK_MAX || inode->i_nlink == 2))
2490 set_nlink(inode, 1);
2494 * If a directory had nlink == 1, then we should let it be 1. This indicates
2495 * directory has >EXT4_LINK_MAX subdirs.
2497 static void ext4_dec_count(handle_t *handle, struct inode *inode)
2499 if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
2504 static int ext4_add_nondir(handle_t *handle,
2505 struct dentry *dentry, struct inode *inode)
2507 int err = ext4_add_entry(handle, dentry, inode);
2509 ext4_mark_inode_dirty(handle, inode);
2510 d_instantiate_new(dentry, inode);
2514 unlock_new_inode(inode);
2520 * By the time this is called, we already have created
2521 * the directory cache entry for the new file, but it
2522 * is so far negative - it has no inode.
2524 * If the create succeeds, we fill in the inode information
2525 * with d_instantiate().
2527 static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2531 struct inode *inode;
2532 int err, credits, retries = 0;
2534 err = dquot_initialize(dir);
2538 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2539 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2541 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2542 NULL, EXT4_HT_DIR, credits);
2543 handle = ext4_journal_current_handle();
2544 err = PTR_ERR(inode);
2545 if (!IS_ERR(inode)) {
2546 inode->i_op = &ext4_file_inode_operations;
2547 inode->i_fop = &ext4_file_operations;
2548 ext4_set_aops(inode);
2549 err = ext4_add_nondir(handle, dentry, inode);
2550 if (!err && IS_DIRSYNC(dir))
2551 ext4_handle_sync(handle);
2554 ext4_journal_stop(handle);
2555 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2560 static int ext4_mknod(struct inode *dir, struct dentry *dentry,
2561 umode_t mode, dev_t rdev)
2564 struct inode *inode;
2565 int err, credits, retries = 0;
2567 err = dquot_initialize(dir);
2571 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2572 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2574 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2575 NULL, EXT4_HT_DIR, credits);
2576 handle = ext4_journal_current_handle();
2577 err = PTR_ERR(inode);
2578 if (!IS_ERR(inode)) {
2579 init_special_inode(inode, inode->i_mode, rdev);
2580 inode->i_op = &ext4_special_inode_operations;
2581 err = ext4_add_nondir(handle, dentry, inode);
2582 if (!err && IS_DIRSYNC(dir))
2583 ext4_handle_sync(handle);
2586 ext4_journal_stop(handle);
2587 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2592 static int ext4_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2595 struct inode *inode;
2596 int err, retries = 0;
2598 err = dquot_initialize(dir);
2603 inode = ext4_new_inode_start_handle(dir, mode,
2606 EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
2607 4 + EXT4_XATTR_TRANS_BLOCKS);
2608 handle = ext4_journal_current_handle();
2609 err = PTR_ERR(inode);
2610 if (!IS_ERR(inode)) {
2611 inode->i_op = &ext4_file_inode_operations;
2612 inode->i_fop = &ext4_file_operations;
2613 ext4_set_aops(inode);
2614 d_tmpfile(dentry, inode);
2615 err = ext4_orphan_add(handle, inode);
2617 goto err_unlock_inode;
2618 mark_inode_dirty(inode);
2619 unlock_new_inode(inode);
2622 ext4_journal_stop(handle);
2623 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2627 ext4_journal_stop(handle);
2628 unlock_new_inode(inode);
2632 struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode,
2633 struct ext4_dir_entry_2 *de,
2634 int blocksize, int csum_size,
2635 unsigned int parent_ino, int dotdot_real_len)
2637 de->inode = cpu_to_le32(inode->i_ino);
2639 de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
2641 strcpy(de->name, ".");
2642 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2644 de = ext4_next_entry(de, blocksize);
2645 de->inode = cpu_to_le32(parent_ino);
2647 if (!dotdot_real_len)
2648 de->rec_len = ext4_rec_len_to_disk(blocksize -
2649 (csum_size + EXT4_DIR_REC_LEN(1)),
2652 de->rec_len = ext4_rec_len_to_disk(
2653 EXT4_DIR_REC_LEN(de->name_len), blocksize);
2654 strcpy(de->name, "..");
2655 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2657 return ext4_next_entry(de, blocksize);
2660 static int ext4_init_new_dir(handle_t *handle, struct inode *dir,
2661 struct inode *inode)
2663 struct buffer_head *dir_block = NULL;
2664 struct ext4_dir_entry_2 *de;
2665 struct ext4_dir_entry_tail *t;
2666 ext4_lblk_t block = 0;
2667 unsigned int blocksize = dir->i_sb->s_blocksize;
2671 if (ext4_has_metadata_csum(dir->i_sb))
2672 csum_size = sizeof(struct ext4_dir_entry_tail);
2674 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2675 err = ext4_try_create_inline_dir(handle, dir, inode);
2676 if (err < 0 && err != -ENOSPC)
2683 dir_block = ext4_append(handle, inode, &block);
2684 if (IS_ERR(dir_block))
2685 return PTR_ERR(dir_block);
2686 de = (struct ext4_dir_entry_2 *)dir_block->b_data;
2687 ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0);
2688 set_nlink(inode, 2);
2690 t = EXT4_DIRENT_TAIL(dir_block->b_data, blocksize);
2691 initialize_dirent_tail(t, blocksize);
2694 BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
2695 err = ext4_handle_dirty_dirent_node(handle, inode, dir_block);
2698 set_buffer_verified(dir_block);
2704 static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2707 struct inode *inode;
2708 int err, credits, retries = 0;
2710 if (EXT4_DIR_LINK_MAX(dir))
2713 err = dquot_initialize(dir);
2717 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2718 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2720 inode = ext4_new_inode_start_handle(dir, S_IFDIR | mode,
2722 0, NULL, EXT4_HT_DIR, credits);
2723 handle = ext4_journal_current_handle();
2724 err = PTR_ERR(inode);
2728 inode->i_op = &ext4_dir_inode_operations;
2729 inode->i_fop = &ext4_dir_operations;
2730 err = ext4_init_new_dir(handle, dir, inode);
2732 goto out_clear_inode;
2733 err = ext4_mark_inode_dirty(handle, inode);
2735 err = ext4_add_entry(handle, dentry, inode);
2739 unlock_new_inode(inode);
2740 ext4_mark_inode_dirty(handle, inode);
2744 ext4_inc_count(handle, dir);
2745 ext4_update_dx_flag(dir);
2746 err = ext4_mark_inode_dirty(handle, dir);
2748 goto out_clear_inode;
2749 d_instantiate_new(dentry, inode);
2750 if (IS_DIRSYNC(dir))
2751 ext4_handle_sync(handle);
2755 ext4_journal_stop(handle);
2756 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2762 * routine to check that the specified directory is empty (for rmdir)
2764 bool ext4_empty_dir(struct inode *inode)
2766 unsigned int offset;
2767 struct buffer_head *bh;
2768 struct ext4_dir_entry_2 *de;
2769 struct super_block *sb;
2771 if (ext4_has_inline_data(inode)) {
2772 int has_inline_data = 1;
2775 ret = empty_inline_dir(inode, &has_inline_data);
2776 if (has_inline_data)
2781 if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2)) {
2782 EXT4_ERROR_INODE(inode, "invalid size");
2785 /* The first directory block must not be a hole,
2786 * so treat it as DIRENT_HTREE
2788 bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
2792 de = (struct ext4_dir_entry_2 *) bh->b_data;
2793 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2795 le32_to_cpu(de->inode) != inode->i_ino || strcmp(".", de->name)) {
2796 ext4_warning_inode(inode, "directory missing '.'");
2800 offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2801 de = ext4_next_entry(de, sb->s_blocksize);
2802 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2804 le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
2805 ext4_warning_inode(inode, "directory missing '..'");
2809 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2810 while (offset < inode->i_size) {
2811 if (!(offset & (sb->s_blocksize - 1))) {
2812 unsigned int lblock;
2814 lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
2815 bh = ext4_read_dirblock(inode, lblock, EITHER);
2817 offset += sb->s_blocksize;
2823 de = (struct ext4_dir_entry_2 *) (bh->b_data +
2824 (offset & (sb->s_blocksize - 1)));
2825 if (ext4_check_dir_entry(inode, NULL, de, bh,
2826 bh->b_data, bh->b_size, offset) ||
2827 le32_to_cpu(de->inode)) {
2831 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2838 * ext4_orphan_add() links an unlinked or truncated inode into a list of
2839 * such inodes, starting at the superblock, in case we crash before the
2840 * file is closed/deleted, or in case the inode truncate spans multiple
2841 * transactions and the last transaction is not recovered after a crash.
2843 * At filesystem recovery time, we walk this list deleting unlinked
2844 * inodes and truncating linked inodes in ext4_orphan_cleanup().
2846 * Orphan list manipulation functions must be called under i_mutex unless
2847 * we are just creating the inode or deleting it.
2849 int ext4_orphan_add(handle_t *handle, struct inode *inode)
2851 struct super_block *sb = inode->i_sb;
2852 struct ext4_sb_info *sbi = EXT4_SB(sb);
2853 struct ext4_iloc iloc;
2857 if (!sbi->s_journal || is_bad_inode(inode))
2860 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2861 !inode_is_locked(inode));
2863 * Exit early if inode already is on orphan list. This is a big speedup
2864 * since we don't have to contend on the global s_orphan_lock.
2866 if (!list_empty(&EXT4_I(inode)->i_orphan))
2870 * Orphan handling is only valid for files with data blocks
2871 * being truncated, or files being unlinked. Note that we either
2872 * hold i_mutex, or the inode can not be referenced from outside,
2873 * so i_nlink should not be bumped due to race
2875 J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
2876 S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
2878 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2879 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2883 err = ext4_reserve_inode_write(handle, inode, &iloc);
2887 mutex_lock(&sbi->s_orphan_lock);
2889 * Due to previous errors inode may be already a part of on-disk
2890 * orphan list. If so skip on-disk list modification.
2892 if (!NEXT_ORPHAN(inode) || NEXT_ORPHAN(inode) >
2893 (le32_to_cpu(sbi->s_es->s_inodes_count))) {
2894 /* Insert this inode at the head of the on-disk orphan list */
2895 NEXT_ORPHAN(inode) = le32_to_cpu(sbi->s_es->s_last_orphan);
2896 sbi->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
2899 list_add(&EXT4_I(inode)->i_orphan, &sbi->s_orphan);
2900 mutex_unlock(&sbi->s_orphan_lock);
2903 err = ext4_handle_dirty_super(handle, sb);
2904 rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
2909 * We have to remove inode from in-memory list if
2910 * addition to on disk orphan list failed. Stray orphan
2911 * list entries can cause panics at unmount time.
2913 mutex_lock(&sbi->s_orphan_lock);
2914 list_del_init(&EXT4_I(inode)->i_orphan);
2915 mutex_unlock(&sbi->s_orphan_lock);
2920 jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
2921 jbd_debug(4, "orphan inode %lu will point to %d\n",
2922 inode->i_ino, NEXT_ORPHAN(inode));
2924 ext4_std_error(sb, err);
2929 * ext4_orphan_del() removes an unlinked or truncated inode from the list
2930 * of such inodes stored on disk, because it is finally being cleaned up.
2932 int ext4_orphan_del(handle_t *handle, struct inode *inode)
2934 struct list_head *prev;
2935 struct ext4_inode_info *ei = EXT4_I(inode);
2936 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2938 struct ext4_iloc iloc;
2941 if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS))
2944 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2945 !inode_is_locked(inode));
2946 /* Do this quick check before taking global s_orphan_lock. */
2947 if (list_empty(&ei->i_orphan))
2951 /* Grab inode buffer early before taking global s_orphan_lock */
2952 err = ext4_reserve_inode_write(handle, inode, &iloc);
2955 mutex_lock(&sbi->s_orphan_lock);
2956 jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
2958 prev = ei->i_orphan.prev;
2959 list_del_init(&ei->i_orphan);
2961 /* If we're on an error path, we may not have a valid
2962 * transaction handle with which to update the orphan list on
2963 * disk, but we still need to remove the inode from the linked
2964 * list in memory. */
2965 if (!handle || err) {
2966 mutex_unlock(&sbi->s_orphan_lock);
2970 ino_next = NEXT_ORPHAN(inode);
2971 if (prev == &sbi->s_orphan) {
2972 jbd_debug(4, "superblock will point to %u\n", ino_next);
2973 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2974 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2976 mutex_unlock(&sbi->s_orphan_lock);
2979 sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
2980 mutex_unlock(&sbi->s_orphan_lock);
2981 err = ext4_handle_dirty_super(handle, inode->i_sb);
2983 struct ext4_iloc iloc2;
2984 struct inode *i_prev =
2985 &list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
2987 jbd_debug(4, "orphan inode %lu will point to %u\n",
2988 i_prev->i_ino, ino_next);
2989 err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
2991 mutex_unlock(&sbi->s_orphan_lock);
2994 NEXT_ORPHAN(i_prev) = ino_next;
2995 err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
2996 mutex_unlock(&sbi->s_orphan_lock);
3000 NEXT_ORPHAN(inode) = 0;
3001 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
3003 ext4_std_error(inode->i_sb, err);
3011 static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
3014 struct inode *inode;
3015 struct buffer_head *bh;
3016 struct ext4_dir_entry_2 *de;
3017 handle_t *handle = NULL;
3019 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3022 /* Initialize quotas before so that eventual writes go in
3023 * separate transaction */
3024 retval = dquot_initialize(dir);
3027 retval = dquot_initialize(d_inode(dentry));
3032 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3038 inode = d_inode(dentry);
3040 retval = -EFSCORRUPTED;
3041 if (le32_to_cpu(de->inode) != inode->i_ino)
3044 retval = -ENOTEMPTY;
3045 if (!ext4_empty_dir(inode))
3048 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3049 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3050 if (IS_ERR(handle)) {
3051 retval = PTR_ERR(handle);
3056 if (IS_DIRSYNC(dir))
3057 ext4_handle_sync(handle);
3059 retval = ext4_delete_entry(handle, dir, de, bh);
3062 if (!EXT4_DIR_LINK_EMPTY(inode))
3063 ext4_warning_inode(inode,
3064 "empty directory '%.*s' has too many links (%u)",
3065 dentry->d_name.len, dentry->d_name.name,
3069 /* There's no need to set i_disksize: the fact that i_nlink is
3070 * zero will ensure that the right thing happens during any
3073 ext4_orphan_add(handle, inode);
3074 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
3075 ext4_mark_inode_dirty(handle, inode);
3076 ext4_dec_count(handle, dir);
3077 ext4_update_dx_flag(dir);
3078 ext4_mark_inode_dirty(handle, dir);
3083 ext4_journal_stop(handle);
3087 static int ext4_unlink(struct inode *dir, struct dentry *dentry)
3090 struct inode *inode;
3091 struct buffer_head *bh;
3092 struct ext4_dir_entry_2 *de;
3093 handle_t *handle = NULL;
3095 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3098 trace_ext4_unlink_enter(dir, dentry);
3099 /* Initialize quotas before so that eventual writes go
3100 * in separate transaction */
3101 retval = dquot_initialize(dir);
3104 retval = dquot_initialize(d_inode(dentry));
3109 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3115 inode = d_inode(dentry);
3117 retval = -EFSCORRUPTED;
3118 if (le32_to_cpu(de->inode) != inode->i_ino)
3121 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3122 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3123 if (IS_ERR(handle)) {
3124 retval = PTR_ERR(handle);
3129 if (IS_DIRSYNC(dir))
3130 ext4_handle_sync(handle);
3132 retval = ext4_delete_entry(handle, dir, de, bh);
3135 dir->i_ctime = dir->i_mtime = current_time(dir);
3136 ext4_update_dx_flag(dir);
3137 ext4_mark_inode_dirty(handle, dir);
3138 if (inode->i_nlink == 0)
3139 ext4_warning_inode(inode, "Deleting file '%.*s' with no links",
3140 dentry->d_name.len, dentry->d_name.name);
3143 if (!inode->i_nlink)
3144 ext4_orphan_add(handle, inode);
3145 inode->i_ctime = current_time(inode);
3146 ext4_mark_inode_dirty(handle, inode);
3151 ext4_journal_stop(handle);
3152 trace_ext4_unlink_exit(dentry, retval);
3156 static int ext4_symlink(struct inode *dir,
3157 struct dentry *dentry, const char *symname)
3160 struct inode *inode;
3161 int err, len = strlen(symname);
3163 bool encryption_required;
3164 struct fscrypt_str disk_link;
3165 struct fscrypt_symlink_data *sd = NULL;
3167 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3170 disk_link.len = len + 1;
3171 disk_link.name = (char *) symname;
3173 encryption_required = (ext4_encrypted_inode(dir) ||
3174 DUMMY_ENCRYPTION_ENABLED(EXT4_SB(dir->i_sb)));
3175 if (encryption_required) {
3176 err = fscrypt_get_encryption_info(dir);
3179 if (!fscrypt_has_encryption_key(dir))
3181 disk_link.len = (fscrypt_fname_encrypted_size(dir, len) +
3182 sizeof(struct fscrypt_symlink_data));
3183 sd = kzalloc(disk_link.len, GFP_KERNEL);
3188 if (disk_link.len > dir->i_sb->s_blocksize) {
3189 err = -ENAMETOOLONG;
3193 err = dquot_initialize(dir);
3197 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3199 * For non-fast symlinks, we just allocate inode and put it on
3200 * orphan list in the first transaction => we need bitmap,
3201 * group descriptor, sb, inode block, quota blocks, and
3202 * possibly selinux xattr blocks.
3204 credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
3205 EXT4_XATTR_TRANS_BLOCKS;
3208 * Fast symlink. We have to add entry to directory
3209 * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
3210 * allocate new inode (bitmap, group descriptor, inode block,
3211 * quota blocks, sb is already counted in previous macros).
3213 credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3214 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3;
3217 inode = ext4_new_inode_start_handle(dir, S_IFLNK|S_IRWXUGO,
3218 &dentry->d_name, 0, NULL,
3219 EXT4_HT_DIR, credits);
3220 handle = ext4_journal_current_handle();
3221 if (IS_ERR(inode)) {
3223 ext4_journal_stop(handle);
3224 err = PTR_ERR(inode);
3228 if (encryption_required) {
3230 struct fscrypt_str ostr =
3231 FSTR_INIT(sd->encrypted_path, disk_link.len);
3233 istr.name = (const unsigned char *) symname;
3235 err = fscrypt_fname_usr_to_disk(inode, &istr, &ostr);
3237 goto err_drop_inode;
3238 sd->len = cpu_to_le16(ostr.len);
3239 disk_link.name = (char *) sd;
3240 inode->i_op = &ext4_encrypted_symlink_inode_operations;
3243 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3244 if (!encryption_required)
3245 inode->i_op = &ext4_symlink_inode_operations;
3246 inode_nohighmem(inode);
3247 ext4_set_aops(inode);
3249 * We cannot call page_symlink() with transaction started
3250 * because it calls into ext4_write_begin() which can wait
3251 * for transaction commit if we are running out of space
3252 * and thus we deadlock. So we have to stop transaction now
3253 * and restart it when symlink contents is written.
3255 * To keep fs consistent in case of crash, we have to put inode
3256 * to orphan list in the mean time.
3259 err = ext4_orphan_add(handle, inode);
3260 ext4_journal_stop(handle);
3263 goto err_drop_inode;
3264 err = __page_symlink(inode, disk_link.name, disk_link.len, 1);
3266 goto err_drop_inode;
3268 * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
3269 * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
3271 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3272 EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3273 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
3274 if (IS_ERR(handle)) {
3275 err = PTR_ERR(handle);
3277 goto err_drop_inode;
3279 set_nlink(inode, 1);
3280 err = ext4_orphan_del(handle, inode);
3282 goto err_drop_inode;
3284 /* clear the extent format for fast symlink */
3285 ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
3286 if (!encryption_required) {
3287 inode->i_op = &ext4_fast_symlink_inode_operations;
3288 inode->i_link = (char *)&EXT4_I(inode)->i_data;
3290 memcpy((char *)&EXT4_I(inode)->i_data, disk_link.name,
3292 inode->i_size = disk_link.len - 1;
3294 EXT4_I(inode)->i_disksize = inode->i_size;
3295 err = ext4_add_nondir(handle, dentry, inode);
3296 if (!err && IS_DIRSYNC(dir))
3297 ext4_handle_sync(handle);
3300 ext4_journal_stop(handle);
3305 ext4_journal_stop(handle);
3307 unlock_new_inode(inode);
3314 static int ext4_link(struct dentry *old_dentry,
3315 struct inode *dir, struct dentry *dentry)
3318 struct inode *inode = d_inode(old_dentry);
3319 int err, retries = 0;
3321 if (inode->i_nlink >= EXT4_LINK_MAX)
3323 if (ext4_encrypted_inode(dir) &&
3324 !fscrypt_has_permitted_context(dir, inode))
3327 if ((ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT)) &&
3328 (!projid_eq(EXT4_I(dir)->i_projid,
3329 EXT4_I(old_dentry->d_inode)->i_projid)))
3332 err = dquot_initialize(dir);
3337 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3338 (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3339 EXT4_INDEX_EXTRA_TRANS_BLOCKS) + 1);
3341 return PTR_ERR(handle);
3343 if (IS_DIRSYNC(dir))
3344 ext4_handle_sync(handle);
3346 inode->i_ctime = current_time(inode);
3347 ext4_inc_count(handle, inode);
3350 err = ext4_add_entry(handle, dentry, inode);
3352 ext4_mark_inode_dirty(handle, inode);
3353 /* this can happen only for tmpfile being
3354 * linked the first time
3356 if (inode->i_nlink == 1)
3357 ext4_orphan_del(handle, inode);
3358 d_instantiate(dentry, inode);
3363 ext4_journal_stop(handle);
3364 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
3371 * Try to find buffer head where contains the parent block.
3372 * It should be the inode block if it is inlined or the 1st block
3373 * if it is a normal dir.
3375 static struct buffer_head *ext4_get_first_dir_block(handle_t *handle,
3376 struct inode *inode,
3378 struct ext4_dir_entry_2 **parent_de,
3381 struct buffer_head *bh;
3383 if (!ext4_has_inline_data(inode)) {
3384 struct ext4_dir_entry_2 *de;
3385 unsigned int offset;
3387 /* The first directory block must not be a hole, so
3388 * treat it as DIRENT_HTREE
3390 bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
3392 *retval = PTR_ERR(bh);
3396 de = (struct ext4_dir_entry_2 *) bh->b_data;
3397 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data,
3399 le32_to_cpu(de->inode) != inode->i_ino ||
3400 strcmp(".", de->name)) {
3401 EXT4_ERROR_INODE(inode, "directory missing '.'");
3403 *retval = -EFSCORRUPTED;
3406 offset = ext4_rec_len_from_disk(de->rec_len,
3407 inode->i_sb->s_blocksize);
3408 de = ext4_next_entry(de, inode->i_sb->s_blocksize);
3409 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data,
3410 bh->b_size, offset) ||
3411 le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
3412 EXT4_ERROR_INODE(inode, "directory missing '..'");
3414 *retval = -EFSCORRUPTED;
3423 return ext4_get_first_inline_block(inode, parent_de, retval);
3426 struct ext4_renament {
3428 struct dentry *dentry;
3429 struct inode *inode;
3431 int dir_nlink_delta;
3433 /* entry for "dentry" */
3434 struct buffer_head *bh;
3435 struct ext4_dir_entry_2 *de;
3438 /* entry for ".." in inode if it's a directory */
3439 struct buffer_head *dir_bh;
3440 struct ext4_dir_entry_2 *parent_de;
3444 static int ext4_rename_dir_prepare(handle_t *handle, struct ext4_renament *ent)
3448 ent->dir_bh = ext4_get_first_dir_block(handle, ent->inode,
3449 &retval, &ent->parent_de,
3453 if (le32_to_cpu(ent->parent_de->inode) != ent->dir->i_ino)
3454 return -EFSCORRUPTED;
3455 BUFFER_TRACE(ent->dir_bh, "get_write_access");
3456 return ext4_journal_get_write_access(handle, ent->dir_bh);
3459 static int ext4_rename_dir_finish(handle_t *handle, struct ext4_renament *ent,
3464 ent->parent_de->inode = cpu_to_le32(dir_ino);
3465 BUFFER_TRACE(ent->dir_bh, "call ext4_handle_dirty_metadata");
3466 if (!ent->dir_inlined) {
3467 if (is_dx(ent->inode)) {
3468 retval = ext4_handle_dirty_dx_node(handle,
3472 retval = ext4_handle_dirty_dirent_node(handle,
3477 retval = ext4_mark_inode_dirty(handle, ent->inode);
3480 ext4_std_error(ent->dir->i_sb, retval);
3486 static int ext4_setent(handle_t *handle, struct ext4_renament *ent,
3487 unsigned ino, unsigned file_type)
3491 BUFFER_TRACE(ent->bh, "get write access");
3492 retval = ext4_journal_get_write_access(handle, ent->bh);
3495 ent->de->inode = cpu_to_le32(ino);
3496 if (ext4_has_feature_filetype(ent->dir->i_sb))
3497 ent->de->file_type = file_type;
3498 ent->dir->i_version++;
3499 ent->dir->i_ctime = ent->dir->i_mtime =
3500 current_time(ent->dir);
3501 ext4_mark_inode_dirty(handle, ent->dir);
3502 BUFFER_TRACE(ent->bh, "call ext4_handle_dirty_metadata");
3503 if (!ent->inlined) {
3504 retval = ext4_handle_dirty_dirent_node(handle,
3506 if (unlikely(retval)) {
3507 ext4_std_error(ent->dir->i_sb, retval);
3515 static void ext4_resetent(handle_t *handle, struct ext4_renament *ent,
3516 unsigned ino, unsigned file_type)
3518 struct ext4_renament old = *ent;
3522 * old->de could have moved from under us during make indexed dir,
3523 * so the old->de may no longer valid and need to find it again
3524 * before reset old inode info.
3526 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de,
3529 retval = PTR_ERR(old.bh);
3533 ext4_std_error(old.dir->i_sb, retval);
3537 ext4_setent(handle, &old, ino, file_type);
3541 static int ext4_find_delete_entry(handle_t *handle, struct inode *dir,
3542 const struct qstr *d_name)
3544 int retval = -ENOENT;
3545 struct buffer_head *bh;
3546 struct ext4_dir_entry_2 *de;
3548 bh = ext4_find_entry(dir, d_name, &de, NULL);
3552 retval = ext4_delete_entry(handle, dir, de, bh);
3558 static void ext4_rename_delete(handle_t *handle, struct ext4_renament *ent,
3563 * ent->de could have moved from under us during htree split, so make
3564 * sure that we are deleting the right entry. We might also be pointing
3565 * to a stale entry in the unused part of ent->bh so just checking inum
3566 * and the name isn't enough.
3568 if (le32_to_cpu(ent->de->inode) != ent->inode->i_ino ||
3569 ent->de->name_len != ent->dentry->d_name.len ||
3570 strncmp(ent->de->name, ent->dentry->d_name.name,
3571 ent->de->name_len) ||
3573 retval = ext4_find_delete_entry(handle, ent->dir,
3574 &ent->dentry->d_name);
3576 retval = ext4_delete_entry(handle, ent->dir, ent->de, ent->bh);
3577 if (retval == -ENOENT) {
3578 retval = ext4_find_delete_entry(handle, ent->dir,
3579 &ent->dentry->d_name);
3584 ext4_warning_inode(ent->dir,
3585 "Deleting old file: nlink %d, error=%d",
3586 ent->dir->i_nlink, retval);
3590 static void ext4_update_dir_count(handle_t *handle, struct ext4_renament *ent)
3592 if (ent->dir_nlink_delta) {
3593 if (ent->dir_nlink_delta == -1)
3594 ext4_dec_count(handle, ent->dir);
3596 ext4_inc_count(handle, ent->dir);
3597 ext4_mark_inode_dirty(handle, ent->dir);
3601 static struct inode *ext4_whiteout_for_rename(struct ext4_renament *ent,
3602 int credits, handle_t **h)
3609 * for inode block, sb block, group summaries,
3612 credits += (EXT4_MAXQUOTAS_TRANS_BLOCKS(ent->dir->i_sb) +
3613 EXT4_XATTR_TRANS_BLOCKS + 4);
3615 wh = ext4_new_inode_start_handle(ent->dir, S_IFCHR | WHITEOUT_MODE,
3616 &ent->dentry->d_name, 0, NULL,
3617 EXT4_HT_DIR, credits);
3619 handle = ext4_journal_current_handle();
3622 ext4_journal_stop(handle);
3623 if (PTR_ERR(wh) == -ENOSPC &&
3624 ext4_should_retry_alloc(ent->dir->i_sb, &retries))
3628 init_special_inode(wh, wh->i_mode, WHITEOUT_DEV);
3629 wh->i_op = &ext4_special_inode_operations;
3635 * Anybody can rename anything with this: the permission checks are left to the
3636 * higher-level routines.
3638 * n.b. old_{dentry,inode) refers to the source dentry/inode
3639 * while new_{dentry,inode) refers to the destination dentry/inode
3640 * This comes from rename(const char *oldpath, const char *newpath)
3642 static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
3643 struct inode *new_dir, struct dentry *new_dentry,
3646 handle_t *handle = NULL;
3647 struct ext4_renament old = {
3649 .dentry = old_dentry,
3650 .inode = d_inode(old_dentry),
3652 struct ext4_renament new = {
3654 .dentry = new_dentry,
3655 .inode = d_inode(new_dentry),
3659 struct inode *whiteout = NULL;
3663 if (new.inode && new.inode->i_nlink == 0) {
3664 EXT4_ERROR_INODE(new.inode,
3665 "target of rename is already freed");
3666 return -EFSCORRUPTED;
3669 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT)) &&
3670 (!projid_eq(EXT4_I(new_dir)->i_projid,
3671 EXT4_I(old_dentry->d_inode)->i_projid)))
3674 if ((ext4_encrypted_inode(old_dir) &&
3675 !fscrypt_has_encryption_key(old_dir)) ||
3676 (ext4_encrypted_inode(new_dir) &&
3677 !fscrypt_has_encryption_key(new_dir)))
3680 retval = dquot_initialize(old.dir);
3683 retval = dquot_initialize(new.dir);
3687 /* Initialize quotas before so that eventual writes go
3688 * in separate transaction */
3690 retval = dquot_initialize(new.inode);
3695 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de,
3698 return PTR_ERR(old.bh);
3700 * Check for inode number is _not_ due to possible IO errors.
3701 * We might rmdir the source, keep it as pwd of some process
3702 * and merrily kill the link to whatever was created under the
3703 * same name. Goodbye sticky bit ;-<
3706 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3709 if ((old.dir != new.dir) &&
3710 ext4_encrypted_inode(new.dir) &&
3711 !fscrypt_has_permitted_context(new.dir, old.inode)) {
3716 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3717 &new.de, &new.inlined);
3718 if (IS_ERR(new.bh)) {
3719 retval = PTR_ERR(new.bh);
3729 if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC))
3730 ext4_alloc_da_blocks(old.inode);
3732 credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3733 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
3734 if (!(flags & RENAME_WHITEOUT)) {
3735 handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits);
3736 if (IS_ERR(handle)) {
3737 retval = PTR_ERR(handle);
3741 whiteout = ext4_whiteout_for_rename(&old, credits, &handle);
3742 if (IS_ERR(whiteout)) {
3743 retval = PTR_ERR(whiteout);
3748 old_file_type = old.de->file_type;
3749 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3750 ext4_handle_sync(handle);
3752 if (S_ISDIR(old.inode->i_mode)) {
3754 retval = -ENOTEMPTY;
3755 if (!ext4_empty_dir(new.inode))
3759 if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir))
3762 retval = ext4_rename_dir_prepare(handle, &old);
3767 * If we're renaming a file within an inline_data dir and adding or
3768 * setting the new dirent causes a conversion from inline_data to
3769 * extents/blockmap, we need to force the dirent delete code to
3770 * re-read the directory, or else we end up trying to delete a dirent
3771 * from what is now the extent tree root (or a block map).
3773 force_reread = (new.dir->i_ino == old.dir->i_ino &&
3774 ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA));
3778 * Do this before adding a new entry, so the old entry is sure
3779 * to be still pointing to the valid old entry.
3781 retval = ext4_setent(handle, &old, whiteout->i_ino,
3785 ext4_mark_inode_dirty(handle, whiteout);
3788 retval = ext4_add_entry(handle, new.dentry, old.inode);
3792 retval = ext4_setent(handle, &new,
3793 old.inode->i_ino, old_file_type);
3798 force_reread = !ext4_test_inode_flag(new.dir,
3799 EXT4_INODE_INLINE_DATA);
3802 * Like most other Unix systems, set the ctime for inodes on a
3805 old.inode->i_ctime = current_time(old.inode);
3806 ext4_mark_inode_dirty(handle, old.inode);
3812 ext4_rename_delete(handle, &old, force_reread);
3816 ext4_dec_count(handle, new.inode);
3817 new.inode->i_ctime = current_time(new.inode);
3819 old.dir->i_ctime = old.dir->i_mtime = current_time(old.dir);
3820 ext4_update_dx_flag(old.dir);
3822 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3826 ext4_dec_count(handle, old.dir);
3828 /* checked ext4_empty_dir above, can't have another
3829 * parent, ext4_dec_count() won't work for many-linked
3831 clear_nlink(new.inode);
3833 ext4_inc_count(handle, new.dir);
3834 ext4_update_dx_flag(new.dir);
3835 ext4_mark_inode_dirty(handle, new.dir);
3838 ext4_mark_inode_dirty(handle, old.dir);
3840 ext4_mark_inode_dirty(handle, new.inode);
3841 if (!new.inode->i_nlink)
3842 ext4_orphan_add(handle, new.inode);
3849 ext4_resetent(handle, &old,
3850 old.inode->i_ino, old_file_type);
3851 drop_nlink(whiteout);
3852 ext4_orphan_add(handle, whiteout);
3854 unlock_new_inode(whiteout);
3855 ext4_journal_stop(handle);
3858 ext4_journal_stop(handle);
3867 static int ext4_cross_rename(struct inode *old_dir, struct dentry *old_dentry,
3868 struct inode *new_dir, struct dentry *new_dentry)
3870 handle_t *handle = NULL;
3871 struct ext4_renament old = {
3873 .dentry = old_dentry,
3874 .inode = d_inode(old_dentry),
3876 struct ext4_renament new = {
3878 .dentry = new_dentry,
3879 .inode = d_inode(new_dentry),
3883 struct timespec ctime;
3885 if ((ext4_encrypted_inode(old_dir) &&
3886 !fscrypt_has_encryption_key(old_dir)) ||
3887 (ext4_encrypted_inode(new_dir) &&
3888 !fscrypt_has_encryption_key(new_dir)))
3891 if ((ext4_encrypted_inode(old_dir) ||
3892 ext4_encrypted_inode(new_dir)) &&
3893 (old_dir != new_dir) &&
3894 (!fscrypt_has_permitted_context(new_dir, old.inode) ||
3895 !fscrypt_has_permitted_context(old_dir, new.inode)))
3898 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT) &&
3899 !projid_eq(EXT4_I(new_dir)->i_projid,
3900 EXT4_I(old_dentry->d_inode)->i_projid)) ||
3901 (ext4_test_inode_flag(old_dir, EXT4_INODE_PROJINHERIT) &&
3902 !projid_eq(EXT4_I(old_dir)->i_projid,
3903 EXT4_I(new_dentry->d_inode)->i_projid)))
3906 retval = dquot_initialize(old.dir);
3909 retval = dquot_initialize(old.inode);
3912 retval = dquot_initialize(new.dir);
3916 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name,
3917 &old.de, &old.inlined);
3919 return PTR_ERR(old.bh);
3921 * Check for inode number is _not_ due to possible IO errors.
3922 * We might rmdir the source, keep it as pwd of some process
3923 * and merrily kill the link to whatever was created under the
3924 * same name. Goodbye sticky bit ;-<
3927 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3930 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3931 &new.de, &new.inlined);
3932 if (IS_ERR(new.bh)) {
3933 retval = PTR_ERR(new.bh);
3938 /* RENAME_EXCHANGE case: old *and* new must both exist */
3939 if (!new.bh || le32_to_cpu(new.de->inode) != new.inode->i_ino)
3942 handle = ext4_journal_start(old.dir, EXT4_HT_DIR,
3943 (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3944 2 * EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2));
3945 if (IS_ERR(handle)) {
3946 retval = PTR_ERR(handle);
3951 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3952 ext4_handle_sync(handle);
3954 if (S_ISDIR(old.inode->i_mode)) {
3956 retval = ext4_rename_dir_prepare(handle, &old);
3960 if (S_ISDIR(new.inode->i_mode)) {
3962 retval = ext4_rename_dir_prepare(handle, &new);
3968 * Other than the special case of overwriting a directory, parents'
3969 * nlink only needs to be modified if this is a cross directory rename.
3971 if (old.dir != new.dir && old.is_dir != new.is_dir) {
3972 old.dir_nlink_delta = old.is_dir ? -1 : 1;
3973 new.dir_nlink_delta = -old.dir_nlink_delta;
3975 if ((old.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(old.dir)) ||
3976 (new.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(new.dir)))
3980 new_file_type = new.de->file_type;
3981 retval = ext4_setent(handle, &new, old.inode->i_ino, old.de->file_type);
3985 retval = ext4_setent(handle, &old, new.inode->i_ino, new_file_type);
3990 * Like most other Unix systems, set the ctime for inodes on a
3993 ctime = current_time(old.inode);
3994 old.inode->i_ctime = ctime;
3995 new.inode->i_ctime = ctime;
3996 ext4_mark_inode_dirty(handle, old.inode);
3997 ext4_mark_inode_dirty(handle, new.inode);
4000 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
4005 retval = ext4_rename_dir_finish(handle, &new, old.dir->i_ino);
4009 ext4_update_dir_count(handle, &old);
4010 ext4_update_dir_count(handle, &new);
4019 ext4_journal_stop(handle);
4023 static int ext4_rename2(struct inode *old_dir, struct dentry *old_dentry,
4024 struct inode *new_dir, struct dentry *new_dentry,
4027 if (unlikely(ext4_forced_shutdown(EXT4_SB(old_dir->i_sb))))
4030 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4033 if (flags & RENAME_EXCHANGE) {
4034 return ext4_cross_rename(old_dir, old_dentry,
4035 new_dir, new_dentry);
4038 return ext4_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
4042 * directories can handle most operations...
4044 const struct inode_operations ext4_dir_inode_operations = {
4045 .create = ext4_create,
4046 .lookup = ext4_lookup,
4048 .unlink = ext4_unlink,
4049 .symlink = ext4_symlink,
4050 .mkdir = ext4_mkdir,
4051 .rmdir = ext4_rmdir,
4052 .mknod = ext4_mknod,
4053 .tmpfile = ext4_tmpfile,
4054 .rename = ext4_rename2,
4055 .setattr = ext4_setattr,
4056 .getattr = ext4_getattr,
4057 .listxattr = ext4_listxattr,
4058 .get_acl = ext4_get_acl,
4059 .set_acl = ext4_set_acl,
4060 .fiemap = ext4_fiemap,
4063 const struct inode_operations ext4_special_inode_operations = {
4064 .setattr = ext4_setattr,
4065 .getattr = ext4_getattr,
4066 .listxattr = ext4_listxattr,
4067 .get_acl = ext4_get_acl,
4068 .set_acl = ext4_set_acl,