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;
326 struct ext4_dir_entry *d, *top;
329 top = (struct ext4_dir_entry *)(((void *)de) +
330 (EXT4_BLOCK_SIZE(inode->i_sb) -
331 sizeof(struct ext4_dir_entry_tail)));
332 while (d < top && d->rec_len)
333 d = (struct ext4_dir_entry *)(((void *)d) +
334 le16_to_cpu(d->rec_len));
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 le16_to_cpu(t->det_rec_len) != sizeof(struct ext4_dir_entry_tail) ||
346 t->det_reserved_zero2 ||
347 t->det_reserved_ft != EXT4_FT_DIR_CSUM)
353 static __le32 ext4_dirent_csum(struct inode *inode,
354 struct ext4_dir_entry *dirent, int size)
356 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
357 struct ext4_inode_info *ei = EXT4_I(inode);
360 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
361 return cpu_to_le32(csum);
364 #define warn_no_space_for_csum(inode) \
365 __warn_no_space_for_csum((inode), __func__, __LINE__)
367 static void __warn_no_space_for_csum(struct inode *inode, const char *func,
370 __ext4_warning_inode(inode, func, line,
371 "No space for directory leaf checksum. Please run e2fsck -D.");
374 int ext4_dirent_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent)
376 struct ext4_dir_entry_tail *t;
378 if (!ext4_has_metadata_csum(inode->i_sb))
381 t = get_dirent_tail(inode, dirent);
383 warn_no_space_for_csum(inode);
387 if (t->det_checksum != ext4_dirent_csum(inode, dirent,
388 (void *)t - (void *)dirent))
394 static void ext4_dirent_csum_set(struct inode *inode,
395 struct ext4_dir_entry *dirent)
397 struct ext4_dir_entry_tail *t;
399 if (!ext4_has_metadata_csum(inode->i_sb))
402 t = get_dirent_tail(inode, dirent);
404 warn_no_space_for_csum(inode);
408 t->det_checksum = ext4_dirent_csum(inode, dirent,
409 (void *)t - (void *)dirent);
412 int ext4_handle_dirty_dirent_node(handle_t *handle,
414 struct buffer_head *bh)
416 ext4_dirent_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
417 return ext4_handle_dirty_metadata(handle, inode, bh);
420 static struct dx_countlimit *get_dx_countlimit(struct inode *inode,
421 struct ext4_dir_entry *dirent,
424 struct ext4_dir_entry *dp;
425 struct dx_root_info *root;
428 if (le16_to_cpu(dirent->rec_len) == EXT4_BLOCK_SIZE(inode->i_sb))
430 else if (le16_to_cpu(dirent->rec_len) == 12) {
431 dp = (struct ext4_dir_entry *)(((void *)dirent) + 12);
432 if (le16_to_cpu(dp->rec_len) !=
433 EXT4_BLOCK_SIZE(inode->i_sb) - 12)
435 root = (struct dx_root_info *)(((void *)dp + 12));
436 if (root->reserved_zero ||
437 root->info_length != sizeof(struct dx_root_info))
444 *offset = count_offset;
445 return (struct dx_countlimit *)(((void *)dirent) + count_offset);
448 static __le32 ext4_dx_csum(struct inode *inode, struct ext4_dir_entry *dirent,
449 int count_offset, int count, struct dx_tail *t)
451 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
452 struct ext4_inode_info *ei = EXT4_I(inode);
455 __u32 dummy_csum = 0;
456 int offset = offsetof(struct dx_tail, dt_checksum);
458 size = count_offset + (count * sizeof(struct dx_entry));
459 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
460 csum = ext4_chksum(sbi, csum, (__u8 *)t, offset);
461 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
463 return cpu_to_le32(csum);
466 static int ext4_dx_csum_verify(struct inode *inode,
467 struct ext4_dir_entry *dirent)
469 struct dx_countlimit *c;
471 int count_offset, limit, count;
473 if (!ext4_has_metadata_csum(inode->i_sb))
476 c = get_dx_countlimit(inode, dirent, &count_offset);
478 EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
481 limit = le16_to_cpu(c->limit);
482 count = le16_to_cpu(c->count);
483 if (count_offset + (limit * sizeof(struct dx_entry)) >
484 EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
485 warn_no_space_for_csum(inode);
488 t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
490 if (t->dt_checksum != ext4_dx_csum(inode, dirent, count_offset,
496 static void ext4_dx_csum_set(struct inode *inode, struct ext4_dir_entry *dirent)
498 struct dx_countlimit *c;
500 int count_offset, limit, count;
502 if (!ext4_has_metadata_csum(inode->i_sb))
505 c = get_dx_countlimit(inode, dirent, &count_offset);
507 EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
510 limit = le16_to_cpu(c->limit);
511 count = le16_to_cpu(c->count);
512 if (count_offset + (limit * sizeof(struct dx_entry)) >
513 EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
514 warn_no_space_for_csum(inode);
517 t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
519 t->dt_checksum = ext4_dx_csum(inode, dirent, count_offset, count, t);
522 static inline int ext4_handle_dirty_dx_node(handle_t *handle,
524 struct buffer_head *bh)
526 ext4_dx_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
527 return ext4_handle_dirty_metadata(handle, inode, bh);
531 * p is at least 6 bytes before the end of page
533 static inline struct ext4_dir_entry_2 *
534 ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize)
536 return (struct ext4_dir_entry_2 *)((char *)p +
537 ext4_rec_len_from_disk(p->rec_len, blocksize));
541 * Future: use high four bits of block for coalesce-on-delete flags
542 * Mask them off for now.
545 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry)
547 return le32_to_cpu(entry->block) & 0x0fffffff;
550 static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value)
552 entry->block = cpu_to_le32(value);
555 static inline unsigned dx_get_hash(struct dx_entry *entry)
557 return le32_to_cpu(entry->hash);
560 static inline void dx_set_hash(struct dx_entry *entry, unsigned value)
562 entry->hash = cpu_to_le32(value);
565 static inline unsigned dx_get_count(struct dx_entry *entries)
567 return le16_to_cpu(((struct dx_countlimit *) entries)->count);
570 static inline unsigned dx_get_limit(struct dx_entry *entries)
572 return le16_to_cpu(((struct dx_countlimit *) entries)->limit);
575 static inline void dx_set_count(struct dx_entry *entries, unsigned value)
577 ((struct dx_countlimit *) entries)->count = cpu_to_le16(value);
580 static inline void dx_set_limit(struct dx_entry *entries, unsigned value)
582 ((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
585 static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize)
587 unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(1) -
588 EXT4_DIR_REC_LEN(2) - infosize;
590 if (ext4_has_metadata_csum(dir->i_sb))
591 entry_space -= sizeof(struct dx_tail);
592 return entry_space / sizeof(struct dx_entry);
595 static inline unsigned dx_node_limit(struct inode *dir)
597 unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0);
599 if (ext4_has_metadata_csum(dir->i_sb))
600 entry_space -= sizeof(struct dx_tail);
601 return entry_space / sizeof(struct dx_entry);
608 static void dx_show_index(char * label, struct dx_entry *entries)
610 int i, n = dx_get_count (entries);
611 printk(KERN_DEBUG "%s index", label);
612 for (i = 0; i < n; i++) {
613 printk(KERN_CONT " %x->%lu",
614 i ? dx_get_hash(entries + i) : 0,
615 (unsigned long)dx_get_block(entries + i));
617 printk(KERN_CONT "\n");
627 static struct stats dx_show_leaf(struct inode *dir,
628 struct dx_hash_info *hinfo,
629 struct ext4_dir_entry_2 *de,
630 int size, int show_names)
632 unsigned names = 0, space = 0;
633 char *base = (char *) de;
634 struct dx_hash_info h = *hinfo;
637 while ((char *) de < base + size)
643 #ifdef CONFIG_EXT4_FS_ENCRYPTION
646 struct fscrypt_str fname_crypto_str =
652 if (ext4_encrypted_inode(dir))
653 res = fscrypt_get_encryption_info(dir);
655 printk(KERN_WARNING "Error setting up"
656 " fname crypto: %d\n", res);
658 if (!fscrypt_has_encryption_key(dir)) {
659 /* Directory is not encrypted */
660 ext4fs_dirhash(de->name,
662 printk("%*.s:(U)%x.%u ", len,
664 (unsigned) ((char *) de
667 struct fscrypt_str de_name =
668 FSTR_INIT(name, len);
670 /* Directory is encrypted */
671 res = fscrypt_fname_alloc_buffer(
675 printk(KERN_WARNING "Error "
679 res = fscrypt_fname_disk_to_usr(dir,
683 printk(KERN_WARNING "Error "
684 "converting filename "
690 name = fname_crypto_str.name;
691 len = fname_crypto_str.len;
693 ext4fs_dirhash(de->name, de->name_len,
695 printk("%*.s:(E)%x.%u ", len, name,
696 h.hash, (unsigned) ((char *) de
698 fscrypt_fname_free_buffer(
702 int len = de->name_len;
703 char *name = de->name;
704 ext4fs_dirhash(de->name, de->name_len, &h);
705 printk("%*.s:%x.%u ", len, name, h.hash,
706 (unsigned) ((char *) de - base));
709 space += EXT4_DIR_REC_LEN(de->name_len);
712 de = ext4_next_entry(de, size);
714 printk(KERN_CONT "(%i)\n", names);
715 return (struct stats) { names, space, 1 };
718 struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir,
719 struct dx_entry *entries, int levels)
721 unsigned blocksize = dir->i_sb->s_blocksize;
722 unsigned count = dx_get_count(entries), names = 0, space = 0, i;
724 struct buffer_head *bh;
725 printk("%i indexed blocks...\n", count);
726 for (i = 0; i < count; i++, entries++)
728 ext4_lblk_t block = dx_get_block(entries);
729 ext4_lblk_t hash = i ? dx_get_hash(entries): 0;
730 u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash;
732 printk("%s%3u:%03u hash %8x/%8x ",levels?"":" ", i, block, hash, range);
733 bh = ext4_bread(NULL,dir, block, 0);
734 if (!bh || IS_ERR(bh))
737 dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1):
738 dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *)
739 bh->b_data, blocksize, 0);
740 names += stats.names;
741 space += stats.space;
742 bcount += stats.bcount;
746 printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n",
747 levels ? "" : " ", names, space/bcount,
748 (space/bcount)*100/blocksize);
749 return (struct stats) { names, space, bcount};
751 #endif /* DX_DEBUG */
754 * Probe for a directory leaf block to search.
756 * dx_probe can return ERR_BAD_DX_DIR, which means there was a format
757 * error in the directory index, and the caller should fall back to
758 * searching the directory normally. The callers of dx_probe **MUST**
759 * check for this error code, and make sure it never gets reflected
762 static struct dx_frame *
763 dx_probe(struct ext4_filename *fname, struct inode *dir,
764 struct dx_hash_info *hinfo, struct dx_frame *frame_in)
766 unsigned count, indirect, level, i;
767 struct dx_entry *at, *entries, *p, *q, *m;
768 struct dx_root *root;
769 struct dx_frame *frame = frame_in;
770 struct dx_frame *ret_err = ERR_PTR(ERR_BAD_DX_DIR);
773 ext4_lblk_t blocks[EXT4_HTREE_LEVEL];
775 memset(frame_in, 0, EXT4_HTREE_LEVEL * sizeof(frame_in[0]));
776 frame->bh = ext4_read_dirblock(dir, 0, INDEX);
777 if (IS_ERR(frame->bh))
778 return (struct dx_frame *) frame->bh;
780 root = (struct dx_root *) frame->bh->b_data;
781 if (root->info.hash_version != DX_HASH_TEA &&
782 root->info.hash_version != DX_HASH_HALF_MD4 &&
783 root->info.hash_version != DX_HASH_LEGACY) {
784 ext4_warning_inode(dir, "Unrecognised inode hash code %u",
785 root->info.hash_version);
789 hinfo = &fname->hinfo;
790 hinfo->hash_version = root->info.hash_version;
791 if (hinfo->hash_version <= DX_HASH_TEA)
792 hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
793 hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed;
794 if (fname && fname_name(fname))
795 ext4fs_dirhash(fname_name(fname), fname_len(fname), hinfo);
798 if (root->info.unused_flags & 1) {
799 ext4_warning_inode(dir, "Unimplemented hash flags: %#06x",
800 root->info.unused_flags);
804 indirect = root->info.indirect_levels;
805 if (indirect >= ext4_dir_htree_level(dir->i_sb)) {
806 ext4_warning(dir->i_sb,
807 "Directory (ino: %lu) htree depth %#06x exceed"
808 "supported value", dir->i_ino,
809 ext4_dir_htree_level(dir->i_sb));
810 if (ext4_dir_htree_level(dir->i_sb) < EXT4_HTREE_LEVEL) {
811 ext4_warning(dir->i_sb, "Enable large directory "
812 "feature to access it");
817 entries = (struct dx_entry *)(((char *)&root->info) +
818 root->info.info_length);
820 if (dx_get_limit(entries) != dx_root_limit(dir,
821 root->info.info_length)) {
822 ext4_warning_inode(dir, "dx entry: limit %u != root limit %u",
823 dx_get_limit(entries),
824 dx_root_limit(dir, root->info.info_length));
828 dxtrace(printk("Look up %x", hash));
832 count = dx_get_count(entries);
833 if (!count || count > dx_get_limit(entries)) {
834 ext4_warning_inode(dir,
835 "dx entry: count %u beyond limit %u",
836 count, dx_get_limit(entries));
841 q = entries + count - 1;
844 dxtrace(printk(KERN_CONT "."));
845 if (dx_get_hash(m) > hash)
851 if (0) { // linear search cross check
852 unsigned n = count - 1;
856 dxtrace(printk(KERN_CONT ","));
857 if (dx_get_hash(++at) > hash)
863 assert (at == p - 1);
867 dxtrace(printk(KERN_CONT " %x->%u\n",
868 at == entries ? 0 : dx_get_hash(at),
870 frame->entries = entries;
873 block = dx_get_block(at);
874 for (i = 0; i <= level; i++) {
875 if (blocks[i] == block) {
876 ext4_warning_inode(dir,
877 "dx entry: tree cycle block %u points back to block %u",
878 blocks[level], block);
882 if (++level > indirect)
884 blocks[level] = block;
886 frame->bh = ext4_read_dirblock(dir, block, INDEX);
887 if (IS_ERR(frame->bh)) {
888 ret_err = (struct dx_frame *) frame->bh;
893 entries = ((struct dx_node *) frame->bh->b_data)->entries;
895 if (dx_get_limit(entries) != dx_node_limit(dir)) {
896 ext4_warning_inode(dir,
897 "dx entry: limit %u != node limit %u",
898 dx_get_limit(entries), dx_node_limit(dir));
903 while (frame >= frame_in) {
908 if (ret_err == ERR_PTR(ERR_BAD_DX_DIR))
909 ext4_warning_inode(dir,
910 "Corrupt directory, running e2fsck is recommended");
914 static void dx_release(struct dx_frame *frames)
916 struct dx_root_info *info;
918 unsigned int indirect_levels;
920 if (frames[0].bh == NULL)
923 info = &((struct dx_root *)frames[0].bh->b_data)->info;
924 /* save local copy, "info" may be freed after brelse() */
925 indirect_levels = info->indirect_levels;
926 for (i = 0; i <= indirect_levels; i++) {
927 if (frames[i].bh == NULL)
929 brelse(frames[i].bh);
935 * This function increments the frame pointer to search the next leaf
936 * block, and reads in the necessary intervening nodes if the search
937 * should be necessary. Whether or not the search is necessary is
938 * controlled by the hash parameter. If the hash value is even, then
939 * the search is only continued if the next block starts with that
940 * hash value. This is used if we are searching for a specific file.
942 * If the hash value is HASH_NB_ALWAYS, then always go to the next block.
944 * This function returns 1 if the caller should continue to search,
945 * or 0 if it should not. If there is an error reading one of the
946 * index blocks, it will a negative error code.
948 * If start_hash is non-null, it will be filled in with the starting
949 * hash of the next page.
951 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
952 struct dx_frame *frame,
953 struct dx_frame *frames,
957 struct buffer_head *bh;
963 * Find the next leaf page by incrementing the frame pointer.
964 * If we run out of entries in the interior node, loop around and
965 * increment pointer in the parent node. When we break out of
966 * this loop, num_frames indicates the number of interior
967 * nodes need to be read.
970 if (++(p->at) < p->entries + dx_get_count(p->entries))
979 * If the hash is 1, then continue only if the next page has a
980 * continuation hash of any value. This is used for readdir
981 * handling. Otherwise, check to see if the hash matches the
982 * desired contiuation hash. If it doesn't, return since
983 * there's no point to read in the successive index pages.
985 bhash = dx_get_hash(p->at);
988 if ((hash & 1) == 0) {
989 if ((bhash & ~1) != hash)
993 * If the hash is HASH_NB_ALWAYS, we always go to the next
994 * block so no check is necessary
996 while (num_frames--) {
997 bh = ext4_read_dirblock(dir, dx_get_block(p->at), INDEX);
1003 p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
1010 * This function fills a red-black tree with information from a
1011 * directory block. It returns the number directory entries loaded
1012 * into the tree. If there is an error it is returned in err.
1014 static int htree_dirblock_to_tree(struct file *dir_file,
1015 struct inode *dir, ext4_lblk_t block,
1016 struct dx_hash_info *hinfo,
1017 __u32 start_hash, __u32 start_minor_hash)
1019 struct buffer_head *bh;
1020 struct ext4_dir_entry_2 *de, *top;
1021 int err = 0, count = 0;
1022 struct fscrypt_str fname_crypto_str = FSTR_INIT(NULL, 0), tmp_str;
1024 dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n",
1025 (unsigned long)block));
1026 bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
1030 de = (struct ext4_dir_entry_2 *) bh->b_data;
1031 top = (struct ext4_dir_entry_2 *) ((char *) de +
1032 dir->i_sb->s_blocksize -
1033 EXT4_DIR_REC_LEN(0));
1034 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1035 /* Check if the directory is encrypted */
1036 if (ext4_encrypted_inode(dir)) {
1037 err = fscrypt_get_encryption_info(dir);
1042 err = fscrypt_fname_alloc_buffer(dir, EXT4_NAME_LEN,
1050 for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) {
1051 if (ext4_check_dir_entry(dir, NULL, de, bh,
1052 bh->b_data, bh->b_size,
1053 (block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb))
1054 + ((char *)de - bh->b_data))) {
1055 /* silently ignore the rest of the block */
1058 ext4fs_dirhash(de->name, de->name_len, hinfo);
1059 if ((hinfo->hash < start_hash) ||
1060 ((hinfo->hash == start_hash) &&
1061 (hinfo->minor_hash < start_minor_hash)))
1065 if (!ext4_encrypted_inode(dir)) {
1066 tmp_str.name = de->name;
1067 tmp_str.len = de->name_len;
1068 err = ext4_htree_store_dirent(dir_file,
1069 hinfo->hash, hinfo->minor_hash, de,
1072 int save_len = fname_crypto_str.len;
1073 struct fscrypt_str de_name = FSTR_INIT(de->name,
1076 /* Directory is encrypted */
1077 err = fscrypt_fname_disk_to_usr(dir, hinfo->hash,
1078 hinfo->minor_hash, &de_name,
1084 err = ext4_htree_store_dirent(dir_file,
1085 hinfo->hash, hinfo->minor_hash, de,
1087 fname_crypto_str.len = save_len;
1097 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1098 fscrypt_fname_free_buffer(&fname_crypto_str);
1105 * This function fills a red-black tree with information from a
1106 * directory. We start scanning the directory in hash order, starting
1107 * at start_hash and start_minor_hash.
1109 * This function returns the number of entries inserted into the tree,
1110 * or a negative error code.
1112 int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
1113 __u32 start_minor_hash, __u32 *next_hash)
1115 struct dx_hash_info hinfo;
1116 struct ext4_dir_entry_2 *de;
1117 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1123 struct fscrypt_str tmp_str;
1125 dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n",
1126 start_hash, start_minor_hash));
1127 dir = file_inode(dir_file);
1128 if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) {
1129 hinfo.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
1130 if (hinfo.hash_version <= DX_HASH_TEA)
1131 hinfo.hash_version +=
1132 EXT4_SB(dir->i_sb)->s_hash_unsigned;
1133 hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
1134 if (ext4_has_inline_data(dir)) {
1135 int has_inline_data = 1;
1136 count = htree_inlinedir_to_tree(dir_file, dir, 0,
1140 if (has_inline_data) {
1145 count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo,
1146 start_hash, start_minor_hash);
1150 hinfo.hash = start_hash;
1151 hinfo.minor_hash = 0;
1152 frame = dx_probe(NULL, dir, &hinfo, frames);
1154 return PTR_ERR(frame);
1156 /* Add '.' and '..' from the htree header */
1157 if (!start_hash && !start_minor_hash) {
1158 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1159 tmp_str.name = de->name;
1160 tmp_str.len = de->name_len;
1161 err = ext4_htree_store_dirent(dir_file, 0, 0,
1167 if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) {
1168 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1169 de = ext4_next_entry(de, dir->i_sb->s_blocksize);
1170 tmp_str.name = de->name;
1171 tmp_str.len = de->name_len;
1172 err = ext4_htree_store_dirent(dir_file, 2, 0,
1180 if (fatal_signal_pending(current)) {
1185 block = dx_get_block(frame->at);
1186 ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
1187 start_hash, start_minor_hash);
1194 ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS,
1195 frame, frames, &hashval);
1196 *next_hash = hashval;
1202 * Stop if: (a) there are no more entries, or
1203 * (b) we have inserted at least one entry and the
1204 * next hash value is not a continuation
1207 (count && ((hashval & 1) == 0)))
1211 dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, "
1212 "next hash: %x\n", count, *next_hash));
1219 static inline int search_dirblock(struct buffer_head *bh,
1221 struct ext4_filename *fname,
1222 unsigned int offset,
1223 struct ext4_dir_entry_2 **res_dir)
1225 return ext4_search_dir(bh, bh->b_data, dir->i_sb->s_blocksize, dir,
1226 fname, offset, res_dir);
1230 * Directory block splitting, compacting
1234 * Create map of hash values, offsets, and sizes, stored at end of block.
1235 * Returns number of entries mapped.
1237 static int dx_make_map(struct inode *dir, struct buffer_head *bh,
1238 struct dx_hash_info *hinfo,
1239 struct dx_map_entry *map_tail)
1242 struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)bh->b_data;
1243 unsigned int buflen = bh->b_size;
1244 char *base = bh->b_data;
1245 struct dx_hash_info h = *hinfo;
1247 if (ext4_has_metadata_csum(dir->i_sb))
1248 buflen -= sizeof(struct ext4_dir_entry_tail);
1250 while ((char *) de < base + buflen) {
1251 if (ext4_check_dir_entry(dir, NULL, de, bh, base, buflen,
1252 ((char *)de) - base))
1253 return -EFSCORRUPTED;
1254 if (de->name_len && de->inode) {
1255 ext4fs_dirhash(de->name, de->name_len, &h);
1257 map_tail->hash = h.hash;
1258 map_tail->offs = ((char *) de - base)>>2;
1259 map_tail->size = le16_to_cpu(de->rec_len);
1263 de = ext4_next_entry(de, dir->i_sb->s_blocksize);
1268 /* Sort map by hash value */
1269 static void dx_sort_map (struct dx_map_entry *map, unsigned count)
1271 struct dx_map_entry *p, *q, *top = map + count - 1;
1273 /* Combsort until bubble sort doesn't suck */
1275 count = count*10/13;
1276 if (count - 9 < 2) /* 9, 10 -> 11 */
1278 for (p = top, q = p - count; q >= map; p--, q--)
1279 if (p->hash < q->hash)
1282 /* Garden variety bubble sort */
1287 if (q[1].hash >= q[0].hash)
1295 static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block)
1297 struct dx_entry *entries = frame->entries;
1298 struct dx_entry *old = frame->at, *new = old + 1;
1299 int count = dx_get_count(entries);
1301 assert(count < dx_get_limit(entries));
1302 assert(old < entries + count);
1303 memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
1304 dx_set_hash(new, hash);
1305 dx_set_block(new, block);
1306 dx_set_count(entries, count + 1);
1310 * Test whether a directory entry matches the filename being searched for.
1312 * Return: %true if the directory entry matches, otherwise %false.
1314 static inline bool ext4_match(const struct ext4_filename *fname,
1315 const struct ext4_dir_entry_2 *de)
1317 struct fscrypt_name f;
1322 f.usr_fname = fname->usr_fname;
1323 f.disk_name = fname->disk_name;
1324 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1325 f.crypto_buf = fname->crypto_buf;
1327 return fscrypt_match_name(&f, de->name, de->name_len);
1331 * Returns 0 if not found, -1 on failure, and 1 on success
1333 int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size,
1334 struct inode *dir, struct ext4_filename *fname,
1335 unsigned int offset, struct ext4_dir_entry_2 **res_dir)
1337 struct ext4_dir_entry_2 * de;
1341 de = (struct ext4_dir_entry_2 *)search_buf;
1342 dlimit = search_buf + buf_size;
1343 while ((char *) de < dlimit) {
1344 /* this code is executed quadratically often */
1345 /* do minimal checking `by hand' */
1346 if ((char *) de + de->name_len <= dlimit &&
1347 ext4_match(fname, de)) {
1348 /* found a match - just to be sure, do
1350 if (ext4_check_dir_entry(dir, NULL, de, bh, search_buf,
1356 /* prevent looping on a bad block */
1357 de_len = ext4_rec_len_from_disk(de->rec_len,
1358 dir->i_sb->s_blocksize);
1362 de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
1367 static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block,
1368 struct ext4_dir_entry *de)
1370 struct super_block *sb = dir->i_sb;
1376 if (de->inode == 0 &&
1377 ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) ==
1386 * finds an entry in the specified directory with the wanted name. It
1387 * returns the cache buffer in which the entry was found, and the entry
1388 * itself (as a parameter - res_dir). It does NOT read the inode of the
1389 * entry - you'll have to do that yourself if you want to.
1391 * The returned buffer_head has ->b_count elevated. The caller is expected
1392 * to brelse() it when appropriate.
1394 static struct buffer_head * ext4_find_entry (struct inode *dir,
1395 const struct qstr *d_name,
1396 struct ext4_dir_entry_2 **res_dir,
1399 struct super_block *sb;
1400 struct buffer_head *bh_use[NAMEI_RA_SIZE];
1401 struct buffer_head *bh, *ret = NULL;
1402 ext4_lblk_t start, block;
1403 const u8 *name = d_name->name;
1404 size_t ra_max = 0; /* Number of bh's in the readahead
1406 size_t ra_ptr = 0; /* Current index into readahead
1408 ext4_lblk_t nblocks;
1409 int i, namelen, retval;
1410 struct ext4_filename fname;
1414 namelen = d_name->len;
1415 if (namelen > EXT4_NAME_LEN)
1418 retval = ext4_fname_setup_filename(dir, d_name, 1, &fname);
1419 if (retval == -ENOENT)
1422 return ERR_PTR(retval);
1424 if (ext4_has_inline_data(dir)) {
1425 int has_inline_data = 1;
1426 ret = ext4_find_inline_entry(dir, &fname, res_dir,
1429 *inlined = has_inline_data;
1430 if (has_inline_data)
1431 goto cleanup_and_exit;
1434 if ((namelen <= 2) && (name[0] == '.') &&
1435 (name[1] == '.' || name[1] == '\0')) {
1437 * "." or ".." will only be in the first block
1438 * NFS may look up ".."; "." should be handled by the VFS
1445 ret = ext4_dx_find_entry(dir, &fname, res_dir);
1447 * On success, or if the error was file not found,
1448 * return. Otherwise, fall back to doing a search the
1449 * old fashioned way.
1451 if (!IS_ERR(ret) || PTR_ERR(ret) != ERR_BAD_DX_DIR)
1452 goto cleanup_and_exit;
1453 dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
1457 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1460 goto cleanup_and_exit;
1462 start = EXT4_I(dir)->i_dir_start_lookup;
1463 if (start >= nblocks)
1469 * We deal with the read-ahead logic here.
1472 if (ra_ptr >= ra_max) {
1473 /* Refill the readahead buffer */
1476 ra_max = start - block;
1478 ra_max = nblocks - block;
1479 ra_max = min(ra_max, ARRAY_SIZE(bh_use));
1480 retval = ext4_bread_batch(dir, block, ra_max,
1481 false /* wait */, bh_use);
1483 ret = ERR_PTR(retval);
1485 goto cleanup_and_exit;
1488 if ((bh = bh_use[ra_ptr++]) == NULL)
1491 if (!buffer_uptodate(bh)) {
1492 EXT4_ERROR_INODE(dir, "reading directory lblock %lu",
1493 (unsigned long) block);
1495 ret = ERR_PTR(-EIO);
1496 goto cleanup_and_exit;
1498 if (!buffer_verified(bh) &&
1499 !is_dx_internal_node(dir, block,
1500 (struct ext4_dir_entry *)bh->b_data) &&
1501 !ext4_dirent_csum_verify(dir,
1502 (struct ext4_dir_entry *)bh->b_data)) {
1503 EXT4_ERROR_INODE(dir, "checksumming directory "
1504 "block %lu", (unsigned long)block);
1506 ret = ERR_PTR(-EFSBADCRC);
1507 goto cleanup_and_exit;
1509 set_buffer_verified(bh);
1510 i = search_dirblock(bh, dir, &fname,
1511 block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
1513 EXT4_I(dir)->i_dir_start_lookup = block;
1515 goto cleanup_and_exit;
1519 goto cleanup_and_exit;
1522 if (++block >= nblocks)
1524 } while (block != start);
1527 * If the directory has grown while we were searching, then
1528 * search the last part of the directory before giving up.
1531 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1532 if (block < nblocks) {
1538 /* Clean up the read-ahead blocks */
1539 for (; ra_ptr < ra_max; ra_ptr++)
1540 brelse(bh_use[ra_ptr]);
1541 ext4_fname_free_filename(&fname);
1545 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
1546 struct ext4_filename *fname,
1547 struct ext4_dir_entry_2 **res_dir)
1549 struct super_block * sb = dir->i_sb;
1550 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1551 struct buffer_head *bh;
1555 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1558 frame = dx_probe(fname, dir, NULL, frames);
1560 return (struct buffer_head *) frame;
1562 block = dx_get_block(frame->at);
1563 bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
1567 retval = search_dirblock(bh, dir, fname,
1568 block << EXT4_BLOCK_SIZE_BITS(sb),
1574 bh = ERR_PTR(ERR_BAD_DX_DIR);
1578 /* Check to see if we should continue to search */
1579 retval = ext4_htree_next_block(dir, fname->hinfo.hash, frame,
1582 ext4_warning_inode(dir,
1583 "error %d reading directory index block",
1585 bh = ERR_PTR(retval);
1588 } while (retval == 1);
1592 dxtrace(printk(KERN_DEBUG "%s not found\n", fname->usr_fname->name));
1598 static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
1600 struct inode *inode;
1601 struct ext4_dir_entry_2 *de;
1602 struct buffer_head *bh;
1604 if (ext4_encrypted_inode(dir)) {
1605 int res = fscrypt_get_encryption_info(dir);
1608 * DCACHE_ENCRYPTED_WITH_KEY is set if the dentry is
1609 * created while the directory was encrypted and we
1610 * have access to the key.
1612 if (fscrypt_has_encryption_key(dir))
1613 fscrypt_set_encrypted_dentry(dentry);
1614 fscrypt_set_d_op(dentry);
1615 if (res && res != -ENOKEY)
1616 return ERR_PTR(res);
1619 if (dentry->d_name.len > EXT4_NAME_LEN)
1620 return ERR_PTR(-ENAMETOOLONG);
1622 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
1624 return (struct dentry *) bh;
1627 __u32 ino = le32_to_cpu(de->inode);
1629 if (!ext4_valid_inum(dir->i_sb, ino)) {
1630 EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
1631 return ERR_PTR(-EFSCORRUPTED);
1633 if (unlikely(ino == dir->i_ino)) {
1634 EXT4_ERROR_INODE(dir, "'%pd' linked to parent dir",
1636 return ERR_PTR(-EFSCORRUPTED);
1638 inode = ext4_iget(dir->i_sb, ino, EXT4_IGET_NORMAL);
1639 if (inode == ERR_PTR(-ESTALE)) {
1640 EXT4_ERROR_INODE(dir,
1641 "deleted inode referenced: %u",
1643 return ERR_PTR(-EFSCORRUPTED);
1645 if (!IS_ERR(inode) && ext4_encrypted_inode(dir) &&
1646 (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
1647 !fscrypt_has_permitted_context(dir, inode)) {
1648 ext4_warning(inode->i_sb,
1649 "Inconsistent encryption contexts: %lu/%lu",
1650 dir->i_ino, inode->i_ino);
1652 return ERR_PTR(-EPERM);
1655 return d_splice_alias(inode, dentry);
1659 struct dentry *ext4_get_parent(struct dentry *child)
1662 static const struct qstr dotdot = QSTR_INIT("..", 2);
1663 struct ext4_dir_entry_2 * de;
1664 struct buffer_head *bh;
1666 bh = ext4_find_entry(d_inode(child), &dotdot, &de, NULL);
1668 return (struct dentry *) bh;
1670 return ERR_PTR(-ENOENT);
1671 ino = le32_to_cpu(de->inode);
1674 if (!ext4_valid_inum(child->d_sb, ino)) {
1675 EXT4_ERROR_INODE(d_inode(child),
1676 "bad parent inode number: %u", ino);
1677 return ERR_PTR(-EFSCORRUPTED);
1680 return d_obtain_alias(ext4_iget(child->d_sb, ino, EXT4_IGET_NORMAL));
1684 * Move count entries from end of map between two memory locations.
1685 * Returns pointer to last entry moved.
1687 static struct ext4_dir_entry_2 *
1688 dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count,
1691 unsigned rec_len = 0;
1694 struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
1695 (from + (map->offs<<2));
1696 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1697 memcpy (to, de, rec_len);
1698 ((struct ext4_dir_entry_2 *) to)->rec_len =
1699 ext4_rec_len_to_disk(rec_len, blocksize);
1704 return (struct ext4_dir_entry_2 *) (to - rec_len);
1708 * Compact each dir entry in the range to the minimal rec_len.
1709 * Returns pointer to last entry in range.
1711 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize)
1713 struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
1714 unsigned rec_len = 0;
1717 while ((char*)de < base + blocksize) {
1718 next = ext4_next_entry(de, blocksize);
1719 if (de->inode && de->name_len) {
1720 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1722 memmove(to, de, rec_len);
1723 to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
1725 to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
1733 * Split a full leaf block to make room for a new dir entry.
1734 * Allocate a new block, and move entries so that they are approx. equally full.
1735 * Returns pointer to de in block into which the new entry will be inserted.
1737 static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
1738 struct buffer_head **bh,struct dx_frame *frame,
1739 struct dx_hash_info *hinfo)
1741 unsigned blocksize = dir->i_sb->s_blocksize;
1744 struct buffer_head *bh2;
1745 ext4_lblk_t newblock;
1747 struct dx_map_entry *map;
1748 char *data1 = (*bh)->b_data, *data2;
1749 unsigned split, move, size;
1750 struct ext4_dir_entry_2 *de = NULL, *de2;
1751 struct ext4_dir_entry_tail *t;
1755 if (ext4_has_metadata_csum(dir->i_sb))
1756 csum_size = sizeof(struct ext4_dir_entry_tail);
1758 bh2 = ext4_append(handle, dir, &newblock);
1762 return (struct ext4_dir_entry_2 *) bh2;
1765 BUFFER_TRACE(*bh, "get_write_access");
1766 err = ext4_journal_get_write_access(handle, *bh);
1770 BUFFER_TRACE(frame->bh, "get_write_access");
1771 err = ext4_journal_get_write_access(handle, frame->bh);
1775 data2 = bh2->b_data;
1777 /* create map in the end of data2 block */
1778 map = (struct dx_map_entry *) (data2 + blocksize);
1779 count = dx_make_map(dir, *bh, hinfo, map);
1785 dx_sort_map(map, count);
1786 /* Ensure that neither split block is over half full */
1789 for (i = count-1; i >= 0; i--) {
1790 /* is more than half of this entry in 2nd half of the block? */
1791 if (size + map[i].size/2 > blocksize/2)
1793 size += map[i].size;
1797 * map index at which we will split
1799 * If the sum of active entries didn't exceed half the block size, just
1800 * split it in half by count; each resulting block will have at least
1801 * half the space free.
1804 split = count - move;
1808 hash2 = map[split].hash;
1809 continued = hash2 == map[split - 1].hash;
1810 dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
1811 (unsigned long)dx_get_block(frame->at),
1812 hash2, split, count-split));
1814 /* Fancy dance to stay within two buffers */
1815 de2 = dx_move_dirents(data1, data2, map + split, count - split,
1817 de = dx_pack_dirents(data1, blocksize);
1818 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
1821 de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
1825 t = EXT4_DIRENT_TAIL(data2, blocksize);
1826 initialize_dirent_tail(t, blocksize);
1828 t = EXT4_DIRENT_TAIL(data1, blocksize);
1829 initialize_dirent_tail(t, blocksize);
1832 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,
1834 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,
1837 /* Which block gets the new entry? */
1838 if (hinfo->hash >= hash2) {
1842 dx_insert_block(frame, hash2 + continued, newblock);
1843 err = ext4_handle_dirty_dirent_node(handle, dir, bh2);
1846 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
1850 dxtrace(dx_show_index("frame", frame->entries));
1857 ext4_std_error(dir->i_sb, err);
1858 return ERR_PTR(err);
1861 int ext4_find_dest_de(struct inode *dir, struct inode *inode,
1862 struct buffer_head *bh,
1863 void *buf, int buf_size,
1864 struct ext4_filename *fname,
1865 struct ext4_dir_entry_2 **dest_de)
1867 struct ext4_dir_entry_2 *de;
1868 unsigned short reclen = EXT4_DIR_REC_LEN(fname_len(fname));
1870 unsigned int offset = 0;
1873 de = (struct ext4_dir_entry_2 *)buf;
1874 top = buf + buf_size - reclen;
1875 while ((char *) de <= top) {
1876 if (ext4_check_dir_entry(dir, NULL, de, bh,
1877 buf, buf_size, offset))
1878 return -EFSCORRUPTED;
1879 if (ext4_match(fname, de))
1881 nlen = EXT4_DIR_REC_LEN(de->name_len);
1882 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1883 if ((de->inode ? rlen - nlen : rlen) >= reclen)
1885 de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
1888 if ((char *) de > top)
1895 void ext4_insert_dentry(struct inode *inode,
1896 struct ext4_dir_entry_2 *de,
1898 struct ext4_filename *fname)
1903 nlen = EXT4_DIR_REC_LEN(de->name_len);
1904 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1906 struct ext4_dir_entry_2 *de1 =
1907 (struct ext4_dir_entry_2 *)((char *)de + nlen);
1908 de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size);
1909 de->rec_len = ext4_rec_len_to_disk(nlen, buf_size);
1912 de->file_type = EXT4_FT_UNKNOWN;
1913 de->inode = cpu_to_le32(inode->i_ino);
1914 ext4_set_de_type(inode->i_sb, de, inode->i_mode);
1915 de->name_len = fname_len(fname);
1916 memcpy(de->name, fname_name(fname), fname_len(fname));
1920 * Add a new entry into a directory (leaf) block. If de is non-NULL,
1921 * it points to a directory entry which is guaranteed to be large
1922 * enough for new directory entry. If de is NULL, then
1923 * add_dirent_to_buf will attempt search the directory block for
1924 * space. It will return -ENOSPC if no space is available, and -EIO
1925 * and -EEXIST if directory entry already exists.
1927 static int add_dirent_to_buf(handle_t *handle, struct ext4_filename *fname,
1929 struct inode *inode, struct ext4_dir_entry_2 *de,
1930 struct buffer_head *bh)
1932 unsigned int blocksize = dir->i_sb->s_blocksize;
1936 if (ext4_has_metadata_csum(inode->i_sb))
1937 csum_size = sizeof(struct ext4_dir_entry_tail);
1940 err = ext4_find_dest_de(dir, inode, bh, bh->b_data,
1941 blocksize - csum_size, fname, &de);
1945 BUFFER_TRACE(bh, "get_write_access");
1946 err = ext4_journal_get_write_access(handle, bh);
1948 ext4_std_error(dir->i_sb, err);
1952 /* By now the buffer is marked for journaling */
1953 ext4_insert_dentry(inode, de, blocksize, fname);
1956 * XXX shouldn't update any times until successful
1957 * completion of syscall, but too many callers depend
1960 * XXX similarly, too many callers depend on
1961 * ext4_new_inode() setting the times, but error
1962 * recovery deletes the inode, so the worst that can
1963 * happen is that the times are slightly out of date
1964 * and/or different from the directory change time.
1966 dir->i_mtime = dir->i_ctime = current_time(dir);
1967 ext4_update_dx_flag(dir);
1968 inode_inc_iversion(dir);
1969 ext4_mark_inode_dirty(handle, dir);
1970 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1971 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
1973 ext4_std_error(dir->i_sb, err);
1978 * This converts a one block unindexed directory to a 3 block indexed
1979 * directory, and adds the dentry to the indexed directory.
1981 static int make_indexed_dir(handle_t *handle, struct ext4_filename *fname,
1983 struct inode *inode, struct buffer_head *bh)
1985 struct buffer_head *bh2;
1986 struct dx_root *root;
1987 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1988 struct dx_entry *entries;
1989 struct ext4_dir_entry_2 *de, *de2;
1990 struct ext4_dir_entry_tail *t;
1996 struct fake_dirent *fde;
1999 if (ext4_has_metadata_csum(inode->i_sb))
2000 csum_size = sizeof(struct ext4_dir_entry_tail);
2002 blocksize = dir->i_sb->s_blocksize;
2003 dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
2004 BUFFER_TRACE(bh, "get_write_access");
2005 retval = ext4_journal_get_write_access(handle, bh);
2007 ext4_std_error(dir->i_sb, retval);
2011 root = (struct dx_root *) bh->b_data;
2013 /* The 0th block becomes the root, move the dirents out */
2014 fde = &root->dotdot;
2015 de = (struct ext4_dir_entry_2 *)((char *)fde +
2016 ext4_rec_len_from_disk(fde->rec_len, blocksize));
2017 if ((char *) de >= (((char *) root) + blocksize)) {
2018 EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
2020 return -EFSCORRUPTED;
2022 len = ((char *) root) + (blocksize - csum_size) - (char *) de;
2024 /* Allocate new block for the 0th block's dirents */
2025 bh2 = ext4_append(handle, dir, &block);
2028 return PTR_ERR(bh2);
2030 ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
2031 data1 = bh2->b_data;
2033 memcpy (data1, de, len);
2034 de = (struct ext4_dir_entry_2 *) data1;
2036 while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top)
2038 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
2043 t = EXT4_DIRENT_TAIL(data1, blocksize);
2044 initialize_dirent_tail(t, blocksize);
2047 /* Initialize the root; the dot dirents already exist */
2048 de = (struct ext4_dir_entry_2 *) (&root->dotdot);
2049 de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
2051 memset (&root->info, 0, sizeof(root->info));
2052 root->info.info_length = sizeof(root->info);
2053 root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
2054 entries = root->entries;
2055 dx_set_block(entries, 1);
2056 dx_set_count(entries, 1);
2057 dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
2059 /* Initialize as for dx_probe */
2060 fname->hinfo.hash_version = root->info.hash_version;
2061 if (fname->hinfo.hash_version <= DX_HASH_TEA)
2062 fname->hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
2063 fname->hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
2064 ext4fs_dirhash(fname_name(fname), fname_len(fname), &fname->hinfo);
2066 memset(frames, 0, sizeof(frames));
2068 frame->entries = entries;
2069 frame->at = entries;
2072 retval = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2075 retval = ext4_handle_dirty_dirent_node(handle, dir, bh2);
2079 de = do_split(handle,dir, &bh2, frame, &fname->hinfo);
2081 retval = PTR_ERR(de);
2085 retval = add_dirent_to_buf(handle, fname, dir, inode, de, bh2);
2088 * Even if the block split failed, we have to properly write
2089 * out all the changes we did so far. Otherwise we can end up
2090 * with corrupted filesystem.
2093 ext4_mark_inode_dirty(handle, dir);
2102 * adds a file entry to the specified directory, using the same
2103 * semantics as ext4_find_entry(). It returns NULL if it failed.
2105 * NOTE!! The inode part of 'de' is left at 0 - which means you
2106 * may not sleep between calling this and putting something into
2107 * the entry, as someone else might have used it while you slept.
2109 static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
2110 struct inode *inode)
2112 struct inode *dir = d_inode(dentry->d_parent);
2113 struct buffer_head *bh = NULL;
2114 struct ext4_dir_entry_2 *de;
2115 struct ext4_dir_entry_tail *t;
2116 struct super_block *sb;
2117 struct ext4_filename fname;
2121 ext4_lblk_t block, blocks;
2124 if (ext4_has_metadata_csum(inode->i_sb))
2125 csum_size = sizeof(struct ext4_dir_entry_tail);
2128 blocksize = sb->s_blocksize;
2129 if (!dentry->d_name.len)
2132 retval = ext4_fname_setup_filename(dir, &dentry->d_name, 0, &fname);
2136 if (ext4_has_inline_data(dir)) {
2137 retval = ext4_try_add_inline_entry(handle, &fname, dir, inode);
2147 retval = ext4_dx_add_entry(handle, &fname, dir, inode);
2148 if (!retval || (retval != ERR_BAD_DX_DIR))
2150 /* Can we just ignore htree data? */
2151 if (ext4_has_metadata_csum(sb)) {
2152 EXT4_ERROR_INODE(dir,
2153 "Directory has corrupted htree index.");
2154 retval = -EFSCORRUPTED;
2157 ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
2159 ext4_mark_inode_dirty(handle, dir);
2161 blocks = dir->i_size >> sb->s_blocksize_bits;
2162 for (block = 0; block < blocks; block++) {
2163 bh = ext4_read_dirblock(dir, block, DIRENT);
2165 bh = ext4_bread(handle, dir, block,
2166 EXT4_GET_BLOCKS_CREATE);
2167 goto add_to_new_block;
2170 retval = PTR_ERR(bh);
2174 retval = add_dirent_to_buf(handle, &fname, dir, inode,
2176 if (retval != -ENOSPC)
2179 if (blocks == 1 && !dx_fallback &&
2180 ext4_has_feature_dir_index(sb)) {
2181 retval = make_indexed_dir(handle, &fname, dir,
2183 bh = NULL; /* make_indexed_dir releases bh */
2188 bh = ext4_append(handle, dir, &block);
2191 retval = PTR_ERR(bh);
2195 de = (struct ext4_dir_entry_2 *) bh->b_data;
2197 de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
2200 t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
2201 initialize_dirent_tail(t, blocksize);
2204 retval = add_dirent_to_buf(handle, &fname, dir, inode, de, bh);
2206 ext4_fname_free_filename(&fname);
2209 ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
2214 * Returns 0 for success, or a negative error value
2216 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
2217 struct inode *dir, struct inode *inode)
2219 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
2220 struct dx_entry *entries, *at;
2221 struct buffer_head *bh;
2222 struct super_block *sb = dir->i_sb;
2223 struct ext4_dir_entry_2 *de;
2229 frame = dx_probe(fname, dir, NULL, frames);
2231 return PTR_ERR(frame);
2232 entries = frame->entries;
2234 bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT_HTREE);
2241 BUFFER_TRACE(bh, "get_write_access");
2242 err = ext4_journal_get_write_access(handle, bh);
2246 err = add_dirent_to_buf(handle, fname, dir, inode, NULL, bh);
2251 /* Block full, should compress but for now just split */
2252 dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
2253 dx_get_count(entries), dx_get_limit(entries)));
2254 /* Need to split index? */
2255 if (dx_get_count(entries) == dx_get_limit(entries)) {
2256 ext4_lblk_t newblock;
2257 int levels = frame - frames + 1;
2258 unsigned int icount;
2260 struct dx_entry *entries2;
2261 struct dx_node *node2;
2262 struct buffer_head *bh2;
2264 while (frame > frames) {
2265 if (dx_get_count((frame - 1)->entries) <
2266 dx_get_limit((frame - 1)->entries)) {
2270 frame--; /* split higher index block */
2272 entries = frame->entries;
2275 if (add_level && levels == ext4_dir_htree_level(sb)) {
2276 ext4_warning(sb, "Directory (ino: %lu) index full, "
2277 "reach max htree level :%d",
2278 dir->i_ino, levels);
2279 if (ext4_dir_htree_level(sb) < EXT4_HTREE_LEVEL) {
2280 ext4_warning(sb, "Large directory feature is "
2281 "not enabled on this "
2287 icount = dx_get_count(entries);
2288 bh2 = ext4_append(handle, dir, &newblock);
2293 node2 = (struct dx_node *)(bh2->b_data);
2294 entries2 = node2->entries;
2295 memset(&node2->fake, 0, sizeof(struct fake_dirent));
2296 node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
2298 BUFFER_TRACE(frame->bh, "get_write_access");
2299 err = ext4_journal_get_write_access(handle, frame->bh);
2303 unsigned icount1 = icount/2, icount2 = icount - icount1;
2304 unsigned hash2 = dx_get_hash(entries + icount1);
2305 dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
2308 BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
2309 err = ext4_journal_get_write_access(handle,
2314 memcpy((char *) entries2, (char *) (entries + icount1),
2315 icount2 * sizeof(struct dx_entry));
2316 dx_set_count(entries, icount1);
2317 dx_set_count(entries2, icount2);
2318 dx_set_limit(entries2, dx_node_limit(dir));
2320 /* Which index block gets the new entry? */
2321 if (at - entries >= icount1) {
2322 frame->at = at = at - entries - icount1 + entries2;
2323 frame->entries = entries = entries2;
2324 swap(frame->bh, bh2);
2326 dx_insert_block((frame - 1), hash2, newblock);
2327 dxtrace(dx_show_index("node", frame->entries));
2328 dxtrace(dx_show_index("node",
2329 ((struct dx_node *) bh2->b_data)->entries));
2330 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2334 err = ext4_handle_dirty_dx_node(handle, dir,
2338 err = ext4_handle_dirty_dx_node(handle, dir,
2343 struct dx_root *dxroot;
2344 memcpy((char *) entries2, (char *) entries,
2345 icount * sizeof(struct dx_entry));
2346 dx_set_limit(entries2, dx_node_limit(dir));
2349 dx_set_count(entries, 1);
2350 dx_set_block(entries + 0, newblock);
2351 dxroot = (struct dx_root *)frames[0].bh->b_data;
2352 dxroot->info.indirect_levels += 1;
2353 dxtrace(printk(KERN_DEBUG
2354 "Creating %d level index...\n",
2355 dxroot->info.indirect_levels));
2356 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2359 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2365 de = do_split(handle, dir, &bh, frame, &fname->hinfo);
2370 err = add_dirent_to_buf(handle, fname, dir, inode, de, bh);
2374 ext4_std_error(dir->i_sb, err); /* this is a no-op if err == 0 */
2378 /* @restart is true means htree-path has been changed, we need to
2379 * repeat dx_probe() to find out valid htree-path
2381 if (restart && err == 0)
2387 * ext4_generic_delete_entry deletes a directory entry by merging it
2388 * with the previous entry
2390 int ext4_generic_delete_entry(handle_t *handle,
2392 struct ext4_dir_entry_2 *de_del,
2393 struct buffer_head *bh,
2398 struct ext4_dir_entry_2 *de, *pde;
2399 unsigned int blocksize = dir->i_sb->s_blocksize;
2404 de = (struct ext4_dir_entry_2 *)entry_buf;
2405 while (i < buf_size - csum_size) {
2406 if (ext4_check_dir_entry(dir, NULL, de, bh,
2407 entry_buf, buf_size, i))
2408 return -EFSCORRUPTED;
2411 pde->rec_len = ext4_rec_len_to_disk(
2412 ext4_rec_len_from_disk(pde->rec_len,
2414 ext4_rec_len_from_disk(de->rec_len,
2419 inode_inc_iversion(dir);
2422 i += ext4_rec_len_from_disk(de->rec_len, blocksize);
2424 de = ext4_next_entry(de, blocksize);
2429 static int ext4_delete_entry(handle_t *handle,
2431 struct ext4_dir_entry_2 *de_del,
2432 struct buffer_head *bh)
2434 int err, csum_size = 0;
2436 if (ext4_has_inline_data(dir)) {
2437 int has_inline_data = 1;
2438 err = ext4_delete_inline_entry(handle, dir, de_del, bh,
2440 if (has_inline_data)
2444 if (ext4_has_metadata_csum(dir->i_sb))
2445 csum_size = sizeof(struct ext4_dir_entry_tail);
2447 BUFFER_TRACE(bh, "get_write_access");
2448 err = ext4_journal_get_write_access(handle, bh);
2452 err = ext4_generic_delete_entry(handle, dir, de_del,
2454 dir->i_sb->s_blocksize, csum_size);
2458 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
2459 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
2466 ext4_std_error(dir->i_sb, err);
2471 * Set directory link count to 1 if nlinks > EXT4_LINK_MAX, or if nlinks == 2
2472 * since this indicates that nlinks count was previously 1 to avoid overflowing
2473 * the 16-bit i_links_count field on disk. Directories with i_nlink == 1 mean
2474 * that subdirectory link counts are not being maintained accurately.
2476 * The caller has already checked for i_nlink overflow in case the DIR_LINK
2477 * feature is not enabled and returned -EMLINK. The is_dx() check is a proxy
2478 * for checking S_ISDIR(inode) (since the INODE_INDEX feature will not be set
2479 * on regular files) and to avoid creating huge/slow non-HTREE directories.
2481 static void ext4_inc_count(handle_t *handle, struct inode *inode)
2485 (inode->i_nlink > EXT4_LINK_MAX || inode->i_nlink == 2))
2486 set_nlink(inode, 1);
2490 * If a directory had nlink == 1, then we should let it be 1. This indicates
2491 * directory has >EXT4_LINK_MAX subdirs.
2493 static void ext4_dec_count(handle_t *handle, struct inode *inode)
2495 if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
2500 static int ext4_add_nondir(handle_t *handle,
2501 struct dentry *dentry, struct inode *inode)
2503 int err = ext4_add_entry(handle, dentry, inode);
2505 ext4_mark_inode_dirty(handle, inode);
2506 d_instantiate_new(dentry, inode);
2510 unlock_new_inode(inode);
2516 * By the time this is called, we already have created
2517 * the directory cache entry for the new file, but it
2518 * is so far negative - it has no inode.
2520 * If the create succeeds, we fill in the inode information
2521 * with d_instantiate().
2523 static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2527 struct inode *inode;
2528 int err, credits, retries = 0;
2530 err = dquot_initialize(dir);
2534 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2535 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2537 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2538 NULL, EXT4_HT_DIR, credits);
2539 handle = ext4_journal_current_handle();
2540 err = PTR_ERR(inode);
2541 if (!IS_ERR(inode)) {
2542 inode->i_op = &ext4_file_inode_operations;
2543 inode->i_fop = &ext4_file_operations;
2544 ext4_set_aops(inode);
2545 err = ext4_add_nondir(handle, dentry, inode);
2546 if (!err && IS_DIRSYNC(dir))
2547 ext4_handle_sync(handle);
2550 ext4_journal_stop(handle);
2551 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2556 static int ext4_mknod(struct inode *dir, struct dentry *dentry,
2557 umode_t mode, dev_t rdev)
2560 struct inode *inode;
2561 int err, credits, retries = 0;
2563 err = dquot_initialize(dir);
2567 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2568 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2570 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2571 NULL, EXT4_HT_DIR, credits);
2572 handle = ext4_journal_current_handle();
2573 err = PTR_ERR(inode);
2574 if (!IS_ERR(inode)) {
2575 init_special_inode(inode, inode->i_mode, rdev);
2576 inode->i_op = &ext4_special_inode_operations;
2577 err = ext4_add_nondir(handle, dentry, inode);
2578 if (!err && IS_DIRSYNC(dir))
2579 ext4_handle_sync(handle);
2582 ext4_journal_stop(handle);
2583 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2588 static int ext4_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2591 struct inode *inode;
2592 int err, retries = 0;
2594 err = dquot_initialize(dir);
2599 inode = ext4_new_inode_start_handle(dir, mode,
2602 EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
2603 4 + EXT4_XATTR_TRANS_BLOCKS);
2604 handle = ext4_journal_current_handle();
2605 err = PTR_ERR(inode);
2606 if (!IS_ERR(inode)) {
2607 inode->i_op = &ext4_file_inode_operations;
2608 inode->i_fop = &ext4_file_operations;
2609 ext4_set_aops(inode);
2610 d_tmpfile(dentry, inode);
2611 err = ext4_orphan_add(handle, inode);
2613 goto err_unlock_inode;
2614 mark_inode_dirty(inode);
2615 unlock_new_inode(inode);
2618 ext4_journal_stop(handle);
2619 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2623 ext4_journal_stop(handle);
2624 unlock_new_inode(inode);
2628 struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode,
2629 struct ext4_dir_entry_2 *de,
2630 int blocksize, int csum_size,
2631 unsigned int parent_ino, int dotdot_real_len)
2633 de->inode = cpu_to_le32(inode->i_ino);
2635 de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
2637 strcpy(de->name, ".");
2638 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2640 de = ext4_next_entry(de, blocksize);
2641 de->inode = cpu_to_le32(parent_ino);
2643 if (!dotdot_real_len)
2644 de->rec_len = ext4_rec_len_to_disk(blocksize -
2645 (csum_size + EXT4_DIR_REC_LEN(1)),
2648 de->rec_len = ext4_rec_len_to_disk(
2649 EXT4_DIR_REC_LEN(de->name_len), blocksize);
2650 strcpy(de->name, "..");
2651 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2653 return ext4_next_entry(de, blocksize);
2656 static int ext4_init_new_dir(handle_t *handle, struct inode *dir,
2657 struct inode *inode)
2659 struct buffer_head *dir_block = NULL;
2660 struct ext4_dir_entry_2 *de;
2661 struct ext4_dir_entry_tail *t;
2662 ext4_lblk_t block = 0;
2663 unsigned int blocksize = dir->i_sb->s_blocksize;
2667 if (ext4_has_metadata_csum(dir->i_sb))
2668 csum_size = sizeof(struct ext4_dir_entry_tail);
2670 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2671 err = ext4_try_create_inline_dir(handle, dir, inode);
2672 if (err < 0 && err != -ENOSPC)
2679 dir_block = ext4_append(handle, inode, &block);
2680 if (IS_ERR(dir_block))
2681 return PTR_ERR(dir_block);
2682 de = (struct ext4_dir_entry_2 *)dir_block->b_data;
2683 ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0);
2684 set_nlink(inode, 2);
2686 t = EXT4_DIRENT_TAIL(dir_block->b_data, blocksize);
2687 initialize_dirent_tail(t, blocksize);
2690 BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
2691 err = ext4_handle_dirty_dirent_node(handle, inode, dir_block);
2694 set_buffer_verified(dir_block);
2700 static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2703 struct inode *inode;
2704 int err, credits, retries = 0;
2706 if (EXT4_DIR_LINK_MAX(dir))
2709 err = dquot_initialize(dir);
2713 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2714 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2716 inode = ext4_new_inode_start_handle(dir, S_IFDIR | mode,
2718 0, NULL, EXT4_HT_DIR, credits);
2719 handle = ext4_journal_current_handle();
2720 err = PTR_ERR(inode);
2724 inode->i_op = &ext4_dir_inode_operations;
2725 inode->i_fop = &ext4_dir_operations;
2726 err = ext4_init_new_dir(handle, dir, inode);
2728 goto out_clear_inode;
2729 err = ext4_mark_inode_dirty(handle, inode);
2731 err = ext4_add_entry(handle, dentry, inode);
2735 unlock_new_inode(inode);
2736 ext4_mark_inode_dirty(handle, inode);
2740 ext4_inc_count(handle, dir);
2741 ext4_update_dx_flag(dir);
2742 err = ext4_mark_inode_dirty(handle, dir);
2744 goto out_clear_inode;
2745 d_instantiate_new(dentry, inode);
2746 if (IS_DIRSYNC(dir))
2747 ext4_handle_sync(handle);
2751 ext4_journal_stop(handle);
2752 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2758 * routine to check that the specified directory is empty (for rmdir)
2760 bool ext4_empty_dir(struct inode *inode)
2762 unsigned int offset;
2763 struct buffer_head *bh;
2764 struct ext4_dir_entry_2 *de;
2765 struct super_block *sb;
2767 if (ext4_has_inline_data(inode)) {
2768 int has_inline_data = 1;
2771 ret = empty_inline_dir(inode, &has_inline_data);
2772 if (has_inline_data)
2777 if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2)) {
2778 EXT4_ERROR_INODE(inode, "invalid size");
2781 /* The first directory block must not be a hole,
2782 * so treat it as DIRENT_HTREE
2784 bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
2788 de = (struct ext4_dir_entry_2 *) bh->b_data;
2789 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2791 le32_to_cpu(de->inode) != inode->i_ino || strcmp(".", de->name)) {
2792 ext4_warning_inode(inode, "directory missing '.'");
2796 offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2797 de = ext4_next_entry(de, sb->s_blocksize);
2798 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2800 le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
2801 ext4_warning_inode(inode, "directory missing '..'");
2805 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2806 while (offset < inode->i_size) {
2807 if (!(offset & (sb->s_blocksize - 1))) {
2808 unsigned int lblock;
2810 lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
2811 bh = ext4_read_dirblock(inode, lblock, EITHER);
2813 offset += sb->s_blocksize;
2819 de = (struct ext4_dir_entry_2 *) (bh->b_data +
2820 (offset & (sb->s_blocksize - 1)));
2821 if (ext4_check_dir_entry(inode, NULL, de, bh,
2822 bh->b_data, bh->b_size, offset) ||
2823 le32_to_cpu(de->inode)) {
2827 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2834 * ext4_orphan_add() links an unlinked or truncated inode into a list of
2835 * such inodes, starting at the superblock, in case we crash before the
2836 * file is closed/deleted, or in case the inode truncate spans multiple
2837 * transactions and the last transaction is not recovered after a crash.
2839 * At filesystem recovery time, we walk this list deleting unlinked
2840 * inodes and truncating linked inodes in ext4_orphan_cleanup().
2842 * Orphan list manipulation functions must be called under i_mutex unless
2843 * we are just creating the inode or deleting it.
2845 int ext4_orphan_add(handle_t *handle, struct inode *inode)
2847 struct super_block *sb = inode->i_sb;
2848 struct ext4_sb_info *sbi = EXT4_SB(sb);
2849 struct ext4_iloc iloc;
2853 if (!sbi->s_journal || is_bad_inode(inode))
2856 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2857 !inode_is_locked(inode));
2859 * Exit early if inode already is on orphan list. This is a big speedup
2860 * since we don't have to contend on the global s_orphan_lock.
2862 if (!list_empty(&EXT4_I(inode)->i_orphan))
2866 * Orphan handling is only valid for files with data blocks
2867 * being truncated, or files being unlinked. Note that we either
2868 * hold i_mutex, or the inode can not be referenced from outside,
2869 * so i_nlink should not be bumped due to race
2871 J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
2872 S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
2874 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2875 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2879 err = ext4_reserve_inode_write(handle, inode, &iloc);
2883 mutex_lock(&sbi->s_orphan_lock);
2885 * Due to previous errors inode may be already a part of on-disk
2886 * orphan list. If so skip on-disk list modification.
2888 if (!NEXT_ORPHAN(inode) || NEXT_ORPHAN(inode) >
2889 (le32_to_cpu(sbi->s_es->s_inodes_count))) {
2890 /* Insert this inode at the head of the on-disk orphan list */
2891 NEXT_ORPHAN(inode) = le32_to_cpu(sbi->s_es->s_last_orphan);
2892 sbi->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
2895 list_add(&EXT4_I(inode)->i_orphan, &sbi->s_orphan);
2896 mutex_unlock(&sbi->s_orphan_lock);
2899 err = ext4_handle_dirty_super(handle, sb);
2900 rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
2905 * We have to remove inode from in-memory list if
2906 * addition to on disk orphan list failed. Stray orphan
2907 * list entries can cause panics at unmount time.
2909 mutex_lock(&sbi->s_orphan_lock);
2910 list_del_init(&EXT4_I(inode)->i_orphan);
2911 mutex_unlock(&sbi->s_orphan_lock);
2916 jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
2917 jbd_debug(4, "orphan inode %lu will point to %d\n",
2918 inode->i_ino, NEXT_ORPHAN(inode));
2920 ext4_std_error(sb, err);
2925 * ext4_orphan_del() removes an unlinked or truncated inode from the list
2926 * of such inodes stored on disk, because it is finally being cleaned up.
2928 int ext4_orphan_del(handle_t *handle, struct inode *inode)
2930 struct list_head *prev;
2931 struct ext4_inode_info *ei = EXT4_I(inode);
2932 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2934 struct ext4_iloc iloc;
2937 if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS))
2940 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2941 !inode_is_locked(inode));
2942 /* Do this quick check before taking global s_orphan_lock. */
2943 if (list_empty(&ei->i_orphan))
2947 /* Grab inode buffer early before taking global s_orphan_lock */
2948 err = ext4_reserve_inode_write(handle, inode, &iloc);
2951 mutex_lock(&sbi->s_orphan_lock);
2952 jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
2954 prev = ei->i_orphan.prev;
2955 list_del_init(&ei->i_orphan);
2957 /* If we're on an error path, we may not have a valid
2958 * transaction handle with which to update the orphan list on
2959 * disk, but we still need to remove the inode from the linked
2960 * list in memory. */
2961 if (!handle || err) {
2962 mutex_unlock(&sbi->s_orphan_lock);
2966 ino_next = NEXT_ORPHAN(inode);
2967 if (prev == &sbi->s_orphan) {
2968 jbd_debug(4, "superblock will point to %u\n", ino_next);
2969 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2970 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2972 mutex_unlock(&sbi->s_orphan_lock);
2975 sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
2976 mutex_unlock(&sbi->s_orphan_lock);
2977 err = ext4_handle_dirty_super(handle, inode->i_sb);
2979 struct ext4_iloc iloc2;
2980 struct inode *i_prev =
2981 &list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
2983 jbd_debug(4, "orphan inode %lu will point to %u\n",
2984 i_prev->i_ino, ino_next);
2985 err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
2987 mutex_unlock(&sbi->s_orphan_lock);
2990 NEXT_ORPHAN(i_prev) = ino_next;
2991 err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
2992 mutex_unlock(&sbi->s_orphan_lock);
2996 NEXT_ORPHAN(inode) = 0;
2997 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
2999 ext4_std_error(inode->i_sb, err);
3007 static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
3010 struct inode *inode;
3011 struct buffer_head *bh;
3012 struct ext4_dir_entry_2 *de;
3013 handle_t *handle = NULL;
3015 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3018 /* Initialize quotas before so that eventual writes go in
3019 * separate transaction */
3020 retval = dquot_initialize(dir);
3023 retval = dquot_initialize(d_inode(dentry));
3028 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3034 inode = d_inode(dentry);
3036 retval = -EFSCORRUPTED;
3037 if (le32_to_cpu(de->inode) != inode->i_ino)
3040 retval = -ENOTEMPTY;
3041 if (!ext4_empty_dir(inode))
3044 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3045 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3046 if (IS_ERR(handle)) {
3047 retval = PTR_ERR(handle);
3052 if (IS_DIRSYNC(dir))
3053 ext4_handle_sync(handle);
3055 retval = ext4_delete_entry(handle, dir, de, bh);
3058 if (!EXT4_DIR_LINK_EMPTY(inode))
3059 ext4_warning_inode(inode,
3060 "empty directory '%.*s' has too many links (%u)",
3061 dentry->d_name.len, dentry->d_name.name,
3065 /* There's no need to set i_disksize: the fact that i_nlink is
3066 * zero will ensure that the right thing happens during any
3069 ext4_orphan_add(handle, inode);
3070 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
3071 ext4_mark_inode_dirty(handle, inode);
3072 ext4_dec_count(handle, dir);
3073 ext4_update_dx_flag(dir);
3074 ext4_mark_inode_dirty(handle, dir);
3079 ext4_journal_stop(handle);
3083 static int ext4_unlink(struct inode *dir, struct dentry *dentry)
3086 struct inode *inode;
3087 struct buffer_head *bh;
3088 struct ext4_dir_entry_2 *de;
3089 handle_t *handle = NULL;
3091 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3094 trace_ext4_unlink_enter(dir, dentry);
3095 /* Initialize quotas before so that eventual writes go
3096 * in separate transaction */
3097 retval = dquot_initialize(dir);
3100 retval = dquot_initialize(d_inode(dentry));
3105 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3111 inode = d_inode(dentry);
3113 retval = -EFSCORRUPTED;
3114 if (le32_to_cpu(de->inode) != inode->i_ino)
3117 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3118 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3119 if (IS_ERR(handle)) {
3120 retval = PTR_ERR(handle);
3125 if (IS_DIRSYNC(dir))
3126 ext4_handle_sync(handle);
3128 retval = ext4_delete_entry(handle, dir, de, bh);
3131 dir->i_ctime = dir->i_mtime = current_time(dir);
3132 ext4_update_dx_flag(dir);
3133 ext4_mark_inode_dirty(handle, dir);
3134 if (inode->i_nlink == 0)
3135 ext4_warning_inode(inode, "Deleting file '%.*s' with no links",
3136 dentry->d_name.len, dentry->d_name.name);
3139 if (!inode->i_nlink)
3140 ext4_orphan_add(handle, inode);
3141 inode->i_ctime = current_time(inode);
3142 ext4_mark_inode_dirty(handle, inode);
3147 ext4_journal_stop(handle);
3148 trace_ext4_unlink_exit(dentry, retval);
3152 static int ext4_symlink(struct inode *dir,
3153 struct dentry *dentry, const char *symname)
3156 struct inode *inode;
3157 int err, len = strlen(symname);
3159 bool encryption_required;
3160 struct fscrypt_str disk_link;
3161 struct fscrypt_symlink_data *sd = NULL;
3163 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3166 disk_link.len = len + 1;
3167 disk_link.name = (char *) symname;
3169 encryption_required = (ext4_encrypted_inode(dir) ||
3170 DUMMY_ENCRYPTION_ENABLED(EXT4_SB(dir->i_sb)));
3171 if (encryption_required) {
3172 err = fscrypt_get_encryption_info(dir);
3175 if (!fscrypt_has_encryption_key(dir))
3177 disk_link.len = (fscrypt_fname_encrypted_size(dir, len) +
3178 sizeof(struct fscrypt_symlink_data));
3179 sd = kzalloc(disk_link.len, GFP_KERNEL);
3184 if (disk_link.len > dir->i_sb->s_blocksize) {
3185 err = -ENAMETOOLONG;
3189 err = dquot_initialize(dir);
3193 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3195 * For non-fast symlinks, we just allocate inode and put it on
3196 * orphan list in the first transaction => we need bitmap,
3197 * group descriptor, sb, inode block, quota blocks, and
3198 * possibly selinux xattr blocks.
3200 credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
3201 EXT4_XATTR_TRANS_BLOCKS;
3204 * Fast symlink. We have to add entry to directory
3205 * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
3206 * allocate new inode (bitmap, group descriptor, inode block,
3207 * quota blocks, sb is already counted in previous macros).
3209 credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3210 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3;
3213 inode = ext4_new_inode_start_handle(dir, S_IFLNK|S_IRWXUGO,
3214 &dentry->d_name, 0, NULL,
3215 EXT4_HT_DIR, credits);
3216 handle = ext4_journal_current_handle();
3217 if (IS_ERR(inode)) {
3219 ext4_journal_stop(handle);
3220 err = PTR_ERR(inode);
3224 if (encryption_required) {
3226 struct fscrypt_str ostr =
3227 FSTR_INIT(sd->encrypted_path, disk_link.len);
3229 istr.name = (const unsigned char *) symname;
3231 err = fscrypt_fname_usr_to_disk(inode, &istr, &ostr);
3233 goto err_drop_inode;
3234 sd->len = cpu_to_le16(ostr.len);
3235 disk_link.name = (char *) sd;
3236 inode->i_op = &ext4_encrypted_symlink_inode_operations;
3239 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3240 if (!encryption_required)
3241 inode->i_op = &ext4_symlink_inode_operations;
3242 inode_nohighmem(inode);
3243 ext4_set_aops(inode);
3245 * We cannot call page_symlink() with transaction started
3246 * because it calls into ext4_write_begin() which can wait
3247 * for transaction commit if we are running out of space
3248 * and thus we deadlock. So we have to stop transaction now
3249 * and restart it when symlink contents is written.
3251 * To keep fs consistent in case of crash, we have to put inode
3252 * to orphan list in the mean time.
3255 err = ext4_orphan_add(handle, inode);
3256 ext4_journal_stop(handle);
3259 goto err_drop_inode;
3260 err = __page_symlink(inode, disk_link.name, disk_link.len, 1);
3262 goto err_drop_inode;
3264 * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
3265 * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
3267 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3268 EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3269 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
3270 if (IS_ERR(handle)) {
3271 err = PTR_ERR(handle);
3273 goto err_drop_inode;
3275 set_nlink(inode, 1);
3276 err = ext4_orphan_del(handle, inode);
3278 goto err_drop_inode;
3280 /* clear the extent format for fast symlink */
3281 ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
3282 if (!encryption_required) {
3283 inode->i_op = &ext4_fast_symlink_inode_operations;
3284 inode->i_link = (char *)&EXT4_I(inode)->i_data;
3286 memcpy((char *)&EXT4_I(inode)->i_data, disk_link.name,
3288 inode->i_size = disk_link.len - 1;
3290 EXT4_I(inode)->i_disksize = inode->i_size;
3291 err = ext4_add_nondir(handle, dentry, inode);
3292 if (!err && IS_DIRSYNC(dir))
3293 ext4_handle_sync(handle);
3296 ext4_journal_stop(handle);
3301 ext4_journal_stop(handle);
3303 unlock_new_inode(inode);
3310 static int ext4_link(struct dentry *old_dentry,
3311 struct inode *dir, struct dentry *dentry)
3314 struct inode *inode = d_inode(old_dentry);
3315 int err, retries = 0;
3317 if (inode->i_nlink >= EXT4_LINK_MAX)
3319 if (ext4_encrypted_inode(dir) &&
3320 !fscrypt_has_permitted_context(dir, inode))
3323 if ((ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT)) &&
3324 (!projid_eq(EXT4_I(dir)->i_projid,
3325 EXT4_I(old_dentry->d_inode)->i_projid)))
3328 err = dquot_initialize(dir);
3333 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3334 (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3335 EXT4_INDEX_EXTRA_TRANS_BLOCKS) + 1);
3337 return PTR_ERR(handle);
3339 if (IS_DIRSYNC(dir))
3340 ext4_handle_sync(handle);
3342 inode->i_ctime = current_time(inode);
3343 ext4_inc_count(handle, inode);
3346 err = ext4_add_entry(handle, dentry, inode);
3348 ext4_mark_inode_dirty(handle, inode);
3349 /* this can happen only for tmpfile being
3350 * linked the first time
3352 if (inode->i_nlink == 1)
3353 ext4_orphan_del(handle, inode);
3354 d_instantiate(dentry, inode);
3359 ext4_journal_stop(handle);
3360 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
3367 * Try to find buffer head where contains the parent block.
3368 * It should be the inode block if it is inlined or the 1st block
3369 * if it is a normal dir.
3371 static struct buffer_head *ext4_get_first_dir_block(handle_t *handle,
3372 struct inode *inode,
3374 struct ext4_dir_entry_2 **parent_de,
3377 struct buffer_head *bh;
3379 if (!ext4_has_inline_data(inode)) {
3380 struct ext4_dir_entry_2 *de;
3381 unsigned int offset;
3383 /* The first directory block must not be a hole, so
3384 * treat it as DIRENT_HTREE
3386 bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
3388 *retval = PTR_ERR(bh);
3392 de = (struct ext4_dir_entry_2 *) bh->b_data;
3393 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data,
3395 le32_to_cpu(de->inode) != inode->i_ino ||
3396 strcmp(".", de->name)) {
3397 EXT4_ERROR_INODE(inode, "directory missing '.'");
3399 *retval = -EFSCORRUPTED;
3402 offset = ext4_rec_len_from_disk(de->rec_len,
3403 inode->i_sb->s_blocksize);
3404 de = ext4_next_entry(de, inode->i_sb->s_blocksize);
3405 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data,
3406 bh->b_size, offset) ||
3407 le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
3408 EXT4_ERROR_INODE(inode, "directory missing '..'");
3410 *retval = -EFSCORRUPTED;
3419 return ext4_get_first_inline_block(inode, parent_de, retval);
3422 struct ext4_renament {
3424 struct dentry *dentry;
3425 struct inode *inode;
3427 int dir_nlink_delta;
3429 /* entry for "dentry" */
3430 struct buffer_head *bh;
3431 struct ext4_dir_entry_2 *de;
3434 /* entry for ".." in inode if it's a directory */
3435 struct buffer_head *dir_bh;
3436 struct ext4_dir_entry_2 *parent_de;
3440 static int ext4_rename_dir_prepare(handle_t *handle, struct ext4_renament *ent)
3444 ent->dir_bh = ext4_get_first_dir_block(handle, ent->inode,
3445 &retval, &ent->parent_de,
3449 if (le32_to_cpu(ent->parent_de->inode) != ent->dir->i_ino)
3450 return -EFSCORRUPTED;
3451 BUFFER_TRACE(ent->dir_bh, "get_write_access");
3452 return ext4_journal_get_write_access(handle, ent->dir_bh);
3455 static int ext4_rename_dir_finish(handle_t *handle, struct ext4_renament *ent,
3460 ent->parent_de->inode = cpu_to_le32(dir_ino);
3461 BUFFER_TRACE(ent->dir_bh, "call ext4_handle_dirty_metadata");
3462 if (!ent->dir_inlined) {
3463 if (is_dx(ent->inode)) {
3464 retval = ext4_handle_dirty_dx_node(handle,
3468 retval = ext4_handle_dirty_dirent_node(handle,
3473 retval = ext4_mark_inode_dirty(handle, ent->inode);
3476 ext4_std_error(ent->dir->i_sb, retval);
3482 static int ext4_setent(handle_t *handle, struct ext4_renament *ent,
3483 unsigned ino, unsigned file_type)
3487 BUFFER_TRACE(ent->bh, "get write access");
3488 retval = ext4_journal_get_write_access(handle, ent->bh);
3491 ent->de->inode = cpu_to_le32(ino);
3492 if (ext4_has_feature_filetype(ent->dir->i_sb))
3493 ent->de->file_type = file_type;
3494 ent->dir->i_version++;
3495 ent->dir->i_ctime = ent->dir->i_mtime =
3496 current_time(ent->dir);
3497 ext4_mark_inode_dirty(handle, ent->dir);
3498 BUFFER_TRACE(ent->bh, "call ext4_handle_dirty_metadata");
3499 if (!ent->inlined) {
3500 retval = ext4_handle_dirty_dirent_node(handle,
3502 if (unlikely(retval)) {
3503 ext4_std_error(ent->dir->i_sb, retval);
3511 static void ext4_resetent(handle_t *handle, struct ext4_renament *ent,
3512 unsigned ino, unsigned file_type)
3514 struct ext4_renament old = *ent;
3518 * old->de could have moved from under us during make indexed dir,
3519 * so the old->de may no longer valid and need to find it again
3520 * before reset old inode info.
3522 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de,
3525 retval = PTR_ERR(old.bh);
3529 ext4_std_error(old.dir->i_sb, retval);
3533 ext4_setent(handle, &old, ino, file_type);
3537 static int ext4_find_delete_entry(handle_t *handle, struct inode *dir,
3538 const struct qstr *d_name)
3540 int retval = -ENOENT;
3541 struct buffer_head *bh;
3542 struct ext4_dir_entry_2 *de;
3544 bh = ext4_find_entry(dir, d_name, &de, NULL);
3548 retval = ext4_delete_entry(handle, dir, de, bh);
3554 static void ext4_rename_delete(handle_t *handle, struct ext4_renament *ent,
3559 * ent->de could have moved from under us during htree split, so make
3560 * sure that we are deleting the right entry. We might also be pointing
3561 * to a stale entry in the unused part of ent->bh so just checking inum
3562 * and the name isn't enough.
3564 if (le32_to_cpu(ent->de->inode) != ent->inode->i_ino ||
3565 ent->de->name_len != ent->dentry->d_name.len ||
3566 strncmp(ent->de->name, ent->dentry->d_name.name,
3567 ent->de->name_len) ||
3569 retval = ext4_find_delete_entry(handle, ent->dir,
3570 &ent->dentry->d_name);
3572 retval = ext4_delete_entry(handle, ent->dir, ent->de, ent->bh);
3573 if (retval == -ENOENT) {
3574 retval = ext4_find_delete_entry(handle, ent->dir,
3575 &ent->dentry->d_name);
3580 ext4_warning_inode(ent->dir,
3581 "Deleting old file: nlink %d, error=%d",
3582 ent->dir->i_nlink, retval);
3586 static void ext4_update_dir_count(handle_t *handle, struct ext4_renament *ent)
3588 if (ent->dir_nlink_delta) {
3589 if (ent->dir_nlink_delta == -1)
3590 ext4_dec_count(handle, ent->dir);
3592 ext4_inc_count(handle, ent->dir);
3593 ext4_mark_inode_dirty(handle, ent->dir);
3597 static struct inode *ext4_whiteout_for_rename(struct ext4_renament *ent,
3598 int credits, handle_t **h)
3605 * for inode block, sb block, group summaries,
3608 credits += (EXT4_MAXQUOTAS_TRANS_BLOCKS(ent->dir->i_sb) +
3609 EXT4_XATTR_TRANS_BLOCKS + 4);
3611 wh = ext4_new_inode_start_handle(ent->dir, S_IFCHR | WHITEOUT_MODE,
3612 &ent->dentry->d_name, 0, NULL,
3613 EXT4_HT_DIR, credits);
3615 handle = ext4_journal_current_handle();
3618 ext4_journal_stop(handle);
3619 if (PTR_ERR(wh) == -ENOSPC &&
3620 ext4_should_retry_alloc(ent->dir->i_sb, &retries))
3624 init_special_inode(wh, wh->i_mode, WHITEOUT_DEV);
3625 wh->i_op = &ext4_special_inode_operations;
3631 * Anybody can rename anything with this: the permission checks are left to the
3632 * higher-level routines.
3634 * n.b. old_{dentry,inode) refers to the source dentry/inode
3635 * while new_{dentry,inode) refers to the destination dentry/inode
3636 * This comes from rename(const char *oldpath, const char *newpath)
3638 static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
3639 struct inode *new_dir, struct dentry *new_dentry,
3642 handle_t *handle = NULL;
3643 struct ext4_renament old = {
3645 .dentry = old_dentry,
3646 .inode = d_inode(old_dentry),
3648 struct ext4_renament new = {
3650 .dentry = new_dentry,
3651 .inode = d_inode(new_dentry),
3655 struct inode *whiteout = NULL;
3659 if (new.inode && new.inode->i_nlink == 0) {
3660 EXT4_ERROR_INODE(new.inode,
3661 "target of rename is already freed");
3662 return -EFSCORRUPTED;
3665 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT)) &&
3666 (!projid_eq(EXT4_I(new_dir)->i_projid,
3667 EXT4_I(old_dentry->d_inode)->i_projid)))
3670 if ((ext4_encrypted_inode(old_dir) &&
3671 !fscrypt_has_encryption_key(old_dir)) ||
3672 (ext4_encrypted_inode(new_dir) &&
3673 !fscrypt_has_encryption_key(new_dir)))
3676 retval = dquot_initialize(old.dir);
3679 retval = dquot_initialize(new.dir);
3683 /* Initialize quotas before so that eventual writes go
3684 * in separate transaction */
3686 retval = dquot_initialize(new.inode);
3691 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de,
3694 return PTR_ERR(old.bh);
3696 * Check for inode number is _not_ due to possible IO errors.
3697 * We might rmdir the source, keep it as pwd of some process
3698 * and merrily kill the link to whatever was created under the
3699 * same name. Goodbye sticky bit ;-<
3702 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3705 if ((old.dir != new.dir) &&
3706 ext4_encrypted_inode(new.dir) &&
3707 !fscrypt_has_permitted_context(new.dir, old.inode)) {
3712 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3713 &new.de, &new.inlined);
3714 if (IS_ERR(new.bh)) {
3715 retval = PTR_ERR(new.bh);
3725 if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC))
3726 ext4_alloc_da_blocks(old.inode);
3728 credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3729 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
3730 if (!(flags & RENAME_WHITEOUT)) {
3731 handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits);
3732 if (IS_ERR(handle)) {
3733 retval = PTR_ERR(handle);
3737 whiteout = ext4_whiteout_for_rename(&old, credits, &handle);
3738 if (IS_ERR(whiteout)) {
3739 retval = PTR_ERR(whiteout);
3744 old_file_type = old.de->file_type;
3745 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3746 ext4_handle_sync(handle);
3748 if (S_ISDIR(old.inode->i_mode)) {
3750 retval = -ENOTEMPTY;
3751 if (!ext4_empty_dir(new.inode))
3755 if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir))
3758 retval = ext4_rename_dir_prepare(handle, &old);
3763 * If we're renaming a file within an inline_data dir and adding or
3764 * setting the new dirent causes a conversion from inline_data to
3765 * extents/blockmap, we need to force the dirent delete code to
3766 * re-read the directory, or else we end up trying to delete a dirent
3767 * from what is now the extent tree root (or a block map).
3769 force_reread = (new.dir->i_ino == old.dir->i_ino &&
3770 ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA));
3774 * Do this before adding a new entry, so the old entry is sure
3775 * to be still pointing to the valid old entry.
3777 retval = ext4_setent(handle, &old, whiteout->i_ino,
3781 ext4_mark_inode_dirty(handle, whiteout);
3784 retval = ext4_add_entry(handle, new.dentry, old.inode);
3788 retval = ext4_setent(handle, &new,
3789 old.inode->i_ino, old_file_type);
3794 force_reread = !ext4_test_inode_flag(new.dir,
3795 EXT4_INODE_INLINE_DATA);
3798 * Like most other Unix systems, set the ctime for inodes on a
3801 old.inode->i_ctime = current_time(old.inode);
3802 ext4_mark_inode_dirty(handle, old.inode);
3808 ext4_rename_delete(handle, &old, force_reread);
3812 ext4_dec_count(handle, new.inode);
3813 new.inode->i_ctime = current_time(new.inode);
3815 old.dir->i_ctime = old.dir->i_mtime = current_time(old.dir);
3816 ext4_update_dx_flag(old.dir);
3818 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3822 ext4_dec_count(handle, old.dir);
3824 /* checked ext4_empty_dir above, can't have another
3825 * parent, ext4_dec_count() won't work for many-linked
3827 clear_nlink(new.inode);
3829 ext4_inc_count(handle, new.dir);
3830 ext4_update_dx_flag(new.dir);
3831 ext4_mark_inode_dirty(handle, new.dir);
3834 ext4_mark_inode_dirty(handle, old.dir);
3836 ext4_mark_inode_dirty(handle, new.inode);
3837 if (!new.inode->i_nlink)
3838 ext4_orphan_add(handle, new.inode);
3845 ext4_resetent(handle, &old,
3846 old.inode->i_ino, old_file_type);
3847 drop_nlink(whiteout);
3848 ext4_orphan_add(handle, whiteout);
3850 unlock_new_inode(whiteout);
3851 ext4_journal_stop(handle);
3854 ext4_journal_stop(handle);
3863 static int ext4_cross_rename(struct inode *old_dir, struct dentry *old_dentry,
3864 struct inode *new_dir, struct dentry *new_dentry)
3866 handle_t *handle = NULL;
3867 struct ext4_renament old = {
3869 .dentry = old_dentry,
3870 .inode = d_inode(old_dentry),
3872 struct ext4_renament new = {
3874 .dentry = new_dentry,
3875 .inode = d_inode(new_dentry),
3879 struct timespec ctime;
3881 if ((ext4_encrypted_inode(old_dir) &&
3882 !fscrypt_has_encryption_key(old_dir)) ||
3883 (ext4_encrypted_inode(new_dir) &&
3884 !fscrypt_has_encryption_key(new_dir)))
3887 if ((ext4_encrypted_inode(old_dir) ||
3888 ext4_encrypted_inode(new_dir)) &&
3889 (old_dir != new_dir) &&
3890 (!fscrypt_has_permitted_context(new_dir, old.inode) ||
3891 !fscrypt_has_permitted_context(old_dir, new.inode)))
3894 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT) &&
3895 !projid_eq(EXT4_I(new_dir)->i_projid,
3896 EXT4_I(old_dentry->d_inode)->i_projid)) ||
3897 (ext4_test_inode_flag(old_dir, EXT4_INODE_PROJINHERIT) &&
3898 !projid_eq(EXT4_I(old_dir)->i_projid,
3899 EXT4_I(new_dentry->d_inode)->i_projid)))
3902 retval = dquot_initialize(old.dir);
3905 retval = dquot_initialize(old.inode);
3908 retval = dquot_initialize(new.dir);
3912 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name,
3913 &old.de, &old.inlined);
3915 return PTR_ERR(old.bh);
3917 * Check for inode number is _not_ due to possible IO errors.
3918 * We might rmdir the source, keep it as pwd of some process
3919 * and merrily kill the link to whatever was created under the
3920 * same name. Goodbye sticky bit ;-<
3923 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3926 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3927 &new.de, &new.inlined);
3928 if (IS_ERR(new.bh)) {
3929 retval = PTR_ERR(new.bh);
3934 /* RENAME_EXCHANGE case: old *and* new must both exist */
3935 if (!new.bh || le32_to_cpu(new.de->inode) != new.inode->i_ino)
3938 handle = ext4_journal_start(old.dir, EXT4_HT_DIR,
3939 (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3940 2 * EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2));
3941 if (IS_ERR(handle)) {
3942 retval = PTR_ERR(handle);
3947 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3948 ext4_handle_sync(handle);
3950 if (S_ISDIR(old.inode->i_mode)) {
3952 retval = ext4_rename_dir_prepare(handle, &old);
3956 if (S_ISDIR(new.inode->i_mode)) {
3958 retval = ext4_rename_dir_prepare(handle, &new);
3964 * Other than the special case of overwriting a directory, parents'
3965 * nlink only needs to be modified if this is a cross directory rename.
3967 if (old.dir != new.dir && old.is_dir != new.is_dir) {
3968 old.dir_nlink_delta = old.is_dir ? -1 : 1;
3969 new.dir_nlink_delta = -old.dir_nlink_delta;
3971 if ((old.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(old.dir)) ||
3972 (new.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(new.dir)))
3976 new_file_type = new.de->file_type;
3977 retval = ext4_setent(handle, &new, old.inode->i_ino, old.de->file_type);
3981 retval = ext4_setent(handle, &old, new.inode->i_ino, new_file_type);
3986 * Like most other Unix systems, set the ctime for inodes on a
3989 ctime = current_time(old.inode);
3990 old.inode->i_ctime = ctime;
3991 new.inode->i_ctime = ctime;
3992 ext4_mark_inode_dirty(handle, old.inode);
3993 ext4_mark_inode_dirty(handle, new.inode);
3996 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
4001 retval = ext4_rename_dir_finish(handle, &new, old.dir->i_ino);
4005 ext4_update_dir_count(handle, &old);
4006 ext4_update_dir_count(handle, &new);
4015 ext4_journal_stop(handle);
4019 static int ext4_rename2(struct inode *old_dir, struct dentry *old_dentry,
4020 struct inode *new_dir, struct dentry *new_dentry,
4023 if (unlikely(ext4_forced_shutdown(EXT4_SB(old_dir->i_sb))))
4026 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4029 if (flags & RENAME_EXCHANGE) {
4030 return ext4_cross_rename(old_dir, old_dentry,
4031 new_dir, new_dentry);
4034 return ext4_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
4038 * directories can handle most operations...
4040 const struct inode_operations ext4_dir_inode_operations = {
4041 .create = ext4_create,
4042 .lookup = ext4_lookup,
4044 .unlink = ext4_unlink,
4045 .symlink = ext4_symlink,
4046 .mkdir = ext4_mkdir,
4047 .rmdir = ext4_rmdir,
4048 .mknod = ext4_mknod,
4049 .tmpfile = ext4_tmpfile,
4050 .rename = ext4_rename2,
4051 .setattr = ext4_setattr,
4052 .getattr = ext4_getattr,
4053 .listxattr = ext4_listxattr,
4054 .get_acl = ext4_get_acl,
4055 .set_acl = ext4_set_acl,
4056 .fiemap = ext4_fiemap,
4059 const struct inode_operations ext4_special_inode_operations = {
4060 .setattr = ext4_setattr,
4061 .getattr = ext4_getattr,
4062 .listxattr = ext4_listxattr,
4063 .get_acl = ext4_get_acl,
4064 .set_acl = ext4_set_acl,