2 * linux/fs/ext4/namei.c
4 * Copyright (C) 1992, 1993, 1994, 1995
5 * Remy Card (card@masi.ibp.fr)
6 * Laboratoire MASI - Institut Blaise Pascal
7 * Universite Pierre et Marie Curie (Paris VI)
11 * linux/fs/minix/namei.c
13 * Copyright (C) 1991, 1992 Linus Torvalds
15 * Big-endian to little-endian byte-swapping/bitmaps by
16 * David S. Miller (davem@caip.rutgers.edu), 1995
17 * Directory entry file type support and forward compatibility hooks
18 * for B-tree directories by Theodore Ts'o (tytso@mit.edu), 1998
19 * Hash Tree Directory indexing (c)
20 * Daniel Phillips, 2001
21 * Hash Tree Directory indexing porting
22 * Christopher Li, 2002
23 * Hash Tree Directory indexing cleanup
28 #include <linux/pagemap.h>
29 #include <linux/time.h>
30 #include <linux/fcntl.h>
31 #include <linux/stat.h>
32 #include <linux/string.h>
33 #include <linux/quotaops.h>
34 #include <linux/buffer_head.h>
35 #include <linux/bio.h>
37 #include "ext4_jbd2.h"
42 #include <trace/events/ext4.h>
44 * define how far ahead to read directories while searching them.
46 #define NAMEI_RA_CHUNKS 2
47 #define NAMEI_RA_BLOCKS 4
48 #define NAMEI_RA_SIZE (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
50 static struct buffer_head *ext4_append(handle_t *handle,
54 struct buffer_head *bh;
57 if (unlikely(EXT4_SB(inode->i_sb)->s_max_dir_size_kb &&
58 ((inode->i_size >> 10) >=
59 EXT4_SB(inode->i_sb)->s_max_dir_size_kb)))
60 return ERR_PTR(-ENOSPC);
62 *block = inode->i_size >> inode->i_sb->s_blocksize_bits;
64 bh = ext4_bread(handle, inode, *block, EXT4_GET_BLOCKS_CREATE);
67 inode->i_size += inode->i_sb->s_blocksize;
68 EXT4_I(inode)->i_disksize = inode->i_size;
69 BUFFER_TRACE(bh, "get_write_access");
70 err = ext4_journal_get_write_access(handle, bh);
73 ext4_std_error(inode->i_sb, err);
79 static int ext4_dx_csum_verify(struct inode *inode,
80 struct ext4_dir_entry *dirent);
83 * Hints to ext4_read_dirblock regarding whether we expect a directory
84 * block being read to be an index block, or a block containing
85 * directory entries (and if the latter, whether it was found via a
86 * logical block in an htree index block). This is used to control
87 * what sort of sanity checkinig ext4_read_dirblock() will do on the
88 * directory block read from the storage device. EITHER will means
89 * the caller doesn't know what kind of directory block will be read,
90 * so no specific verification will be done.
93 EITHER, INDEX, DIRENT, DIRENT_HTREE
96 #define ext4_read_dirblock(inode, block, type) \
97 __ext4_read_dirblock((inode), (block), (type), __func__, __LINE__)
99 static struct buffer_head *__ext4_read_dirblock(struct inode *inode,
101 dirblock_type_t type,
105 struct buffer_head *bh;
106 struct ext4_dir_entry *dirent;
109 bh = ext4_bread(NULL, inode, block, 0);
111 __ext4_warning(inode->i_sb, func, line,
112 "inode #%lu: lblock %lu: comm %s: "
113 "error %ld reading directory block",
114 inode->i_ino, (unsigned long)block,
115 current->comm, PTR_ERR(bh));
119 if (!bh && (type == INDEX || type == DIRENT_HTREE)) {
120 ext4_error_inode(inode, func, line, block,
121 "Directory hole found for htree %s block",
122 (type == INDEX) ? "index" : "leaf");
123 return ERR_PTR(-EFSCORRUPTED);
127 dirent = (struct ext4_dir_entry *) bh->b_data;
128 /* Determine whether or not we have an index block */
132 else if (ext4_rec_len_from_disk(dirent->rec_len,
133 inode->i_sb->s_blocksize) ==
134 inode->i_sb->s_blocksize)
137 if (!is_dx_block && type == INDEX) {
138 ext4_error_inode(inode, func, line, block,
139 "directory leaf block found instead of index block");
141 return ERR_PTR(-EFSCORRUPTED);
143 if (!ext4_has_metadata_csum(inode->i_sb) ||
148 * An empty leaf block can get mistaken for a index block; for
149 * this reason, we can only check the index checksum when the
150 * caller is sure it should be an index block.
152 if (is_dx_block && type == INDEX) {
153 if (ext4_dx_csum_verify(inode, dirent))
154 set_buffer_verified(bh);
156 ext4_error_inode(inode, func, line, block,
157 "Directory index failed checksum");
159 return ERR_PTR(-EFSBADCRC);
163 if (ext4_dirent_csum_verify(inode, dirent))
164 set_buffer_verified(bh);
166 ext4_error_inode(inode, func, line, block,
167 "Directory block failed checksum");
169 return ERR_PTR(-EFSBADCRC);
176 #define assert(test) J_ASSERT(test)
180 #define dxtrace(command) command
182 #define dxtrace(command)
206 * dx_root_info is laid out so that if it should somehow get overlaid by a
207 * dirent the two low bits of the hash version will be zero. Therefore, the
208 * hash version mod 4 should never be 0. Sincerely, the paranoia department.
213 struct fake_dirent dot;
215 struct fake_dirent dotdot;
219 __le32 reserved_zero;
221 u8 info_length; /* 8 */
226 struct dx_entry entries[0];
231 struct fake_dirent fake;
232 struct dx_entry entries[0];
238 struct buffer_head *bh;
239 struct dx_entry *entries;
251 * This goes at the end of each htree block.
255 __le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */
258 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry);
259 static void dx_set_block(struct dx_entry *entry, ext4_lblk_t value);
260 static inline unsigned dx_get_hash(struct dx_entry *entry);
261 static void dx_set_hash(struct dx_entry *entry, unsigned value);
262 static unsigned dx_get_count(struct dx_entry *entries);
263 static unsigned dx_get_limit(struct dx_entry *entries);
264 static void dx_set_count(struct dx_entry *entries, unsigned value);
265 static void dx_set_limit(struct dx_entry *entries, unsigned value);
266 static unsigned dx_root_limit(struct inode *dir, unsigned infosize);
267 static unsigned dx_node_limit(struct inode *dir);
268 static struct dx_frame *dx_probe(struct ext4_filename *fname,
270 struct dx_hash_info *hinfo,
271 struct dx_frame *frame);
272 static void dx_release(struct dx_frame *frames);
273 static int dx_make_map(struct inode *dir, struct ext4_dir_entry_2 *de,
274 unsigned blocksize, struct dx_hash_info *hinfo,
275 struct dx_map_entry map[]);
276 static void dx_sort_map(struct dx_map_entry *map, unsigned count);
277 static struct ext4_dir_entry_2 *dx_move_dirents(char *from, char *to,
278 struct dx_map_entry *offsets, int count, unsigned blocksize);
279 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize);
280 static void dx_insert_block(struct dx_frame *frame,
281 u32 hash, ext4_lblk_t block);
282 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
283 struct dx_frame *frame,
284 struct dx_frame *frames,
286 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
287 struct ext4_filename *fname,
288 struct ext4_dir_entry_2 **res_dir);
289 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
290 struct inode *dir, struct inode *inode);
292 /* checksumming functions */
293 void initialize_dirent_tail(struct ext4_dir_entry_tail *t,
294 unsigned int blocksize)
296 memset(t, 0, sizeof(struct ext4_dir_entry_tail));
297 t->det_rec_len = ext4_rec_len_to_disk(
298 sizeof(struct ext4_dir_entry_tail), blocksize);
299 t->det_reserved_ft = EXT4_FT_DIR_CSUM;
302 /* Walk through a dirent block to find a checksum "dirent" at the tail */
303 static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode,
304 struct ext4_dir_entry *de)
306 struct ext4_dir_entry_tail *t;
309 struct ext4_dir_entry *d, *top;
312 top = (struct ext4_dir_entry *)(((void *)de) +
313 (EXT4_BLOCK_SIZE(inode->i_sb) -
314 sizeof(struct ext4_dir_entry_tail)));
315 while (d < top && d->rec_len)
316 d = (struct ext4_dir_entry *)(((void *)d) +
317 le16_to_cpu(d->rec_len));
322 t = (struct ext4_dir_entry_tail *)d;
324 t = EXT4_DIRENT_TAIL(de, EXT4_BLOCK_SIZE(inode->i_sb));
327 if (t->det_reserved_zero1 ||
328 le16_to_cpu(t->det_rec_len) != sizeof(struct ext4_dir_entry_tail) ||
329 t->det_reserved_zero2 ||
330 t->det_reserved_ft != EXT4_FT_DIR_CSUM)
336 static __le32 ext4_dirent_csum(struct inode *inode,
337 struct ext4_dir_entry *dirent, int size)
339 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
340 struct ext4_inode_info *ei = EXT4_I(inode);
343 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
344 return cpu_to_le32(csum);
347 #define warn_no_space_for_csum(inode) \
348 __warn_no_space_for_csum((inode), __func__, __LINE__)
350 static void __warn_no_space_for_csum(struct inode *inode, const char *func,
353 __ext4_warning_inode(inode, func, line,
354 "No space for directory leaf checksum. Please run e2fsck -D.");
357 int ext4_dirent_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent)
359 struct ext4_dir_entry_tail *t;
361 if (!ext4_has_metadata_csum(inode->i_sb))
364 t = get_dirent_tail(inode, dirent);
366 warn_no_space_for_csum(inode);
370 if (t->det_checksum != ext4_dirent_csum(inode, dirent,
371 (void *)t - (void *)dirent))
377 static void ext4_dirent_csum_set(struct inode *inode,
378 struct ext4_dir_entry *dirent)
380 struct ext4_dir_entry_tail *t;
382 if (!ext4_has_metadata_csum(inode->i_sb))
385 t = get_dirent_tail(inode, dirent);
387 warn_no_space_for_csum(inode);
391 t->det_checksum = ext4_dirent_csum(inode, dirent,
392 (void *)t - (void *)dirent);
395 int ext4_handle_dirty_dirent_node(handle_t *handle,
397 struct buffer_head *bh)
399 ext4_dirent_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
400 return ext4_handle_dirty_metadata(handle, inode, bh);
403 static struct dx_countlimit *get_dx_countlimit(struct inode *inode,
404 struct ext4_dir_entry *dirent,
407 struct ext4_dir_entry *dp;
408 struct dx_root_info *root;
411 if (le16_to_cpu(dirent->rec_len) == EXT4_BLOCK_SIZE(inode->i_sb))
413 else if (le16_to_cpu(dirent->rec_len) == 12) {
414 dp = (struct ext4_dir_entry *)(((void *)dirent) + 12);
415 if (le16_to_cpu(dp->rec_len) !=
416 EXT4_BLOCK_SIZE(inode->i_sb) - 12)
418 root = (struct dx_root_info *)(((void *)dp + 12));
419 if (root->reserved_zero ||
420 root->info_length != sizeof(struct dx_root_info))
427 *offset = count_offset;
428 return (struct dx_countlimit *)(((void *)dirent) + count_offset);
431 static __le32 ext4_dx_csum(struct inode *inode, struct ext4_dir_entry *dirent,
432 int count_offset, int count, struct dx_tail *t)
434 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
435 struct ext4_inode_info *ei = EXT4_I(inode);
438 __u32 dummy_csum = 0;
439 int offset = offsetof(struct dx_tail, dt_checksum);
441 size = count_offset + (count * sizeof(struct dx_entry));
442 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
443 csum = ext4_chksum(sbi, csum, (__u8 *)t, offset);
444 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
446 return cpu_to_le32(csum);
449 static int ext4_dx_csum_verify(struct inode *inode,
450 struct ext4_dir_entry *dirent)
452 struct dx_countlimit *c;
454 int count_offset, limit, count;
456 if (!ext4_has_metadata_csum(inode->i_sb))
459 c = get_dx_countlimit(inode, dirent, &count_offset);
461 EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
464 limit = le16_to_cpu(c->limit);
465 count = le16_to_cpu(c->count);
466 if (count_offset + (limit * sizeof(struct dx_entry)) >
467 EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
468 warn_no_space_for_csum(inode);
471 t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
473 if (t->dt_checksum != ext4_dx_csum(inode, dirent, count_offset,
479 static void ext4_dx_csum_set(struct inode *inode, struct ext4_dir_entry *dirent)
481 struct dx_countlimit *c;
483 int count_offset, limit, count;
485 if (!ext4_has_metadata_csum(inode->i_sb))
488 c = get_dx_countlimit(inode, dirent, &count_offset);
490 EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
493 limit = le16_to_cpu(c->limit);
494 count = le16_to_cpu(c->count);
495 if (count_offset + (limit * sizeof(struct dx_entry)) >
496 EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
497 warn_no_space_for_csum(inode);
500 t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
502 t->dt_checksum = ext4_dx_csum(inode, dirent, count_offset, count, t);
505 static inline int ext4_handle_dirty_dx_node(handle_t *handle,
507 struct buffer_head *bh)
509 ext4_dx_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
510 return ext4_handle_dirty_metadata(handle, inode, bh);
514 * p is at least 6 bytes before the end of page
516 static inline struct ext4_dir_entry_2 *
517 ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize)
519 return (struct ext4_dir_entry_2 *)((char *)p +
520 ext4_rec_len_from_disk(p->rec_len, blocksize));
524 * Future: use high four bits of block for coalesce-on-delete flags
525 * Mask them off for now.
528 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry)
530 return le32_to_cpu(entry->block) & 0x00ffffff;
533 static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value)
535 entry->block = cpu_to_le32(value);
538 static inline unsigned dx_get_hash(struct dx_entry *entry)
540 return le32_to_cpu(entry->hash);
543 static inline void dx_set_hash(struct dx_entry *entry, unsigned value)
545 entry->hash = cpu_to_le32(value);
548 static inline unsigned dx_get_count(struct dx_entry *entries)
550 return le16_to_cpu(((struct dx_countlimit *) entries)->count);
553 static inline unsigned dx_get_limit(struct dx_entry *entries)
555 return le16_to_cpu(((struct dx_countlimit *) entries)->limit);
558 static inline void dx_set_count(struct dx_entry *entries, unsigned value)
560 ((struct dx_countlimit *) entries)->count = cpu_to_le16(value);
563 static inline void dx_set_limit(struct dx_entry *entries, unsigned value)
565 ((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
568 static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize)
570 unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(1) -
571 EXT4_DIR_REC_LEN(2) - infosize;
573 if (ext4_has_metadata_csum(dir->i_sb))
574 entry_space -= sizeof(struct dx_tail);
575 return entry_space / sizeof(struct dx_entry);
578 static inline unsigned dx_node_limit(struct inode *dir)
580 unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0);
582 if (ext4_has_metadata_csum(dir->i_sb))
583 entry_space -= sizeof(struct dx_tail);
584 return entry_space / sizeof(struct dx_entry);
591 static void dx_show_index(char * label, struct dx_entry *entries)
593 int i, n = dx_get_count (entries);
594 printk(KERN_DEBUG "%s index", label);
595 for (i = 0; i < n; i++) {
596 printk(KERN_CONT " %x->%lu",
597 i ? dx_get_hash(entries + i) : 0,
598 (unsigned long)dx_get_block(entries + i));
600 printk(KERN_CONT "\n");
610 static struct stats dx_show_leaf(struct inode *dir,
611 struct dx_hash_info *hinfo,
612 struct ext4_dir_entry_2 *de,
613 int size, int show_names)
615 unsigned names = 0, space = 0;
616 char *base = (char *) de;
617 struct dx_hash_info h = *hinfo;
620 while ((char *) de < base + size)
626 #ifdef CONFIG_EXT4_FS_ENCRYPTION
629 struct fscrypt_str fname_crypto_str =
635 if (ext4_encrypted_inode(dir))
636 res = fscrypt_get_encryption_info(dir);
638 printk(KERN_WARNING "Error setting up"
639 " fname crypto: %d\n", res);
641 if (!fscrypt_has_encryption_key(dir)) {
642 /* Directory is not encrypted */
643 ext4fs_dirhash(de->name,
645 printk("%*.s:(U)%x.%u ", len,
647 (unsigned) ((char *) de
650 struct fscrypt_str de_name =
651 FSTR_INIT(name, len);
653 /* Directory is encrypted */
654 res = fscrypt_fname_alloc_buffer(
658 printk(KERN_WARNING "Error "
662 res = fscrypt_fname_disk_to_usr(dir,
666 printk(KERN_WARNING "Error "
667 "converting filename "
673 name = fname_crypto_str.name;
674 len = fname_crypto_str.len;
676 ext4fs_dirhash(de->name, de->name_len,
678 printk("%*.s:(E)%x.%u ", len, name,
679 h.hash, (unsigned) ((char *) de
681 fscrypt_fname_free_buffer(
685 int len = de->name_len;
686 char *name = de->name;
687 ext4fs_dirhash(de->name, de->name_len, &h);
688 printk("%*.s:%x.%u ", len, name, h.hash,
689 (unsigned) ((char *) de - base));
692 space += EXT4_DIR_REC_LEN(de->name_len);
695 de = ext4_next_entry(de, size);
697 printk(KERN_CONT "(%i)\n", names);
698 return (struct stats) { names, space, 1 };
701 struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir,
702 struct dx_entry *entries, int levels)
704 unsigned blocksize = dir->i_sb->s_blocksize;
705 unsigned count = dx_get_count(entries), names = 0, space = 0, i;
707 struct buffer_head *bh;
708 printk("%i indexed blocks...\n", count);
709 for (i = 0; i < count; i++, entries++)
711 ext4_lblk_t block = dx_get_block(entries);
712 ext4_lblk_t hash = i ? dx_get_hash(entries): 0;
713 u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash;
715 printk("%s%3u:%03u hash %8x/%8x ",levels?"":" ", i, block, hash, range);
716 bh = ext4_bread(NULL,dir, block, 0);
717 if (!bh || IS_ERR(bh))
720 dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1):
721 dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *)
722 bh->b_data, blocksize, 0);
723 names += stats.names;
724 space += stats.space;
725 bcount += stats.bcount;
729 printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n",
730 levels ? "" : " ", names, space/bcount,
731 (space/bcount)*100/blocksize);
732 return (struct stats) { names, space, bcount};
734 #endif /* DX_DEBUG */
737 * Probe for a directory leaf block to search.
739 * dx_probe can return ERR_BAD_DX_DIR, which means there was a format
740 * error in the directory index, and the caller should fall back to
741 * searching the directory normally. The callers of dx_probe **MUST**
742 * check for this error code, and make sure it never gets reflected
745 static struct dx_frame *
746 dx_probe(struct ext4_filename *fname, struct inode *dir,
747 struct dx_hash_info *hinfo, struct dx_frame *frame_in)
749 unsigned count, indirect;
750 struct dx_entry *at, *entries, *p, *q, *m;
751 struct dx_root *root;
752 struct dx_frame *frame = frame_in;
753 struct dx_frame *ret_err = ERR_PTR(ERR_BAD_DX_DIR);
756 frame->bh = ext4_read_dirblock(dir, 0, INDEX);
757 if (IS_ERR(frame->bh))
758 return (struct dx_frame *) frame->bh;
760 root = (struct dx_root *) frame->bh->b_data;
761 if (root->info.hash_version != DX_HASH_TEA &&
762 root->info.hash_version != DX_HASH_HALF_MD4 &&
763 root->info.hash_version != DX_HASH_LEGACY) {
764 ext4_warning_inode(dir, "Unrecognised inode hash code %u",
765 root->info.hash_version);
769 hinfo = &fname->hinfo;
770 hinfo->hash_version = root->info.hash_version;
771 if (hinfo->hash_version <= DX_HASH_TEA)
772 hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
773 hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed;
774 if (fname && fname_name(fname))
775 ext4fs_dirhash(fname_name(fname), fname_len(fname), hinfo);
778 if (root->info.unused_flags & 1) {
779 ext4_warning_inode(dir, "Unimplemented hash flags: %#06x",
780 root->info.unused_flags);
784 indirect = root->info.indirect_levels;
786 ext4_warning_inode(dir, "Unimplemented hash depth: %#06x",
787 root->info.indirect_levels);
791 entries = (struct dx_entry *)(((char *)&root->info) +
792 root->info.info_length);
794 if (dx_get_limit(entries) != dx_root_limit(dir,
795 root->info.info_length)) {
796 ext4_warning_inode(dir, "dx entry: limit %u != root limit %u",
797 dx_get_limit(entries),
798 dx_root_limit(dir, root->info.info_length));
802 dxtrace(printk("Look up %x", hash));
804 count = dx_get_count(entries);
805 if (!count || count > dx_get_limit(entries)) {
806 ext4_warning_inode(dir,
807 "dx entry: count %u beyond limit %u",
808 count, dx_get_limit(entries));
813 q = entries + count - 1;
816 dxtrace(printk(KERN_CONT "."));
817 if (dx_get_hash(m) > hash)
823 if (0) { // linear search cross check
824 unsigned n = count - 1;
828 dxtrace(printk(KERN_CONT ","));
829 if (dx_get_hash(++at) > hash)
835 assert (at == p - 1);
839 dxtrace(printk(KERN_CONT " %x->%u\n",
840 at == entries ? 0 : dx_get_hash(at),
842 frame->entries = entries;
847 frame->bh = ext4_read_dirblock(dir, dx_get_block(at), INDEX);
848 if (IS_ERR(frame->bh)) {
849 ret_err = (struct dx_frame *) frame->bh;
853 entries = ((struct dx_node *) frame->bh->b_data)->entries;
855 if (dx_get_limit(entries) != dx_node_limit(dir)) {
856 ext4_warning_inode(dir,
857 "dx entry: limit %u != node limit %u",
858 dx_get_limit(entries), dx_node_limit(dir));
863 while (frame >= frame_in) {
868 if (ret_err == ERR_PTR(ERR_BAD_DX_DIR))
869 ext4_warning_inode(dir,
870 "Corrupt directory, running e2fsck is recommended");
874 static void dx_release(struct dx_frame *frames)
876 if (frames[0].bh == NULL)
879 if (((struct dx_root *)frames[0].bh->b_data)->info.indirect_levels)
880 brelse(frames[1].bh);
881 brelse(frames[0].bh);
885 * This function increments the frame pointer to search the next leaf
886 * block, and reads in the necessary intervening nodes if the search
887 * should be necessary. Whether or not the search is necessary is
888 * controlled by the hash parameter. If the hash value is even, then
889 * the search is only continued if the next block starts with that
890 * hash value. This is used if we are searching for a specific file.
892 * If the hash value is HASH_NB_ALWAYS, then always go to the next block.
894 * This function returns 1 if the caller should continue to search,
895 * or 0 if it should not. If there is an error reading one of the
896 * index blocks, it will a negative error code.
898 * If start_hash is non-null, it will be filled in with the starting
899 * hash of the next page.
901 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
902 struct dx_frame *frame,
903 struct dx_frame *frames,
907 struct buffer_head *bh;
913 * Find the next leaf page by incrementing the frame pointer.
914 * If we run out of entries in the interior node, loop around and
915 * increment pointer in the parent node. When we break out of
916 * this loop, num_frames indicates the number of interior
917 * nodes need to be read.
920 if (++(p->at) < p->entries + dx_get_count(p->entries))
929 * If the hash is 1, then continue only if the next page has a
930 * continuation hash of any value. This is used for readdir
931 * handling. Otherwise, check to see if the hash matches the
932 * desired contiuation hash. If it doesn't, return since
933 * there's no point to read in the successive index pages.
935 bhash = dx_get_hash(p->at);
938 if ((hash & 1) == 0) {
939 if ((bhash & ~1) != hash)
943 * If the hash is HASH_NB_ALWAYS, we always go to the next
944 * block so no check is necessary
946 while (num_frames--) {
947 bh = ext4_read_dirblock(dir, dx_get_block(p->at), INDEX);
953 p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
960 * This function fills a red-black tree with information from a
961 * directory block. It returns the number directory entries loaded
962 * into the tree. If there is an error it is returned in err.
964 static int htree_dirblock_to_tree(struct file *dir_file,
965 struct inode *dir, ext4_lblk_t block,
966 struct dx_hash_info *hinfo,
967 __u32 start_hash, __u32 start_minor_hash)
969 struct buffer_head *bh;
970 struct ext4_dir_entry_2 *de, *top;
971 int err = 0, count = 0;
972 struct fscrypt_str fname_crypto_str = FSTR_INIT(NULL, 0), tmp_str;
974 dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n",
975 (unsigned long)block));
976 bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
980 de = (struct ext4_dir_entry_2 *) bh->b_data;
981 top = (struct ext4_dir_entry_2 *) ((char *) de +
982 dir->i_sb->s_blocksize -
983 EXT4_DIR_REC_LEN(0));
984 #ifdef CONFIG_EXT4_FS_ENCRYPTION
985 /* Check if the directory is encrypted */
986 if (ext4_encrypted_inode(dir)) {
987 err = fscrypt_get_encryption_info(dir);
992 err = fscrypt_fname_alloc_buffer(dir, EXT4_NAME_LEN,
1000 for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) {
1001 if (ext4_check_dir_entry(dir, NULL, de, bh,
1002 bh->b_data, bh->b_size,
1003 (block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb))
1004 + ((char *)de - bh->b_data))) {
1005 /* silently ignore the rest of the block */
1008 ext4fs_dirhash(de->name, de->name_len, hinfo);
1009 if ((hinfo->hash < start_hash) ||
1010 ((hinfo->hash == start_hash) &&
1011 (hinfo->minor_hash < start_minor_hash)))
1015 if (!ext4_encrypted_inode(dir)) {
1016 tmp_str.name = de->name;
1017 tmp_str.len = de->name_len;
1018 err = ext4_htree_store_dirent(dir_file,
1019 hinfo->hash, hinfo->minor_hash, de,
1022 int save_len = fname_crypto_str.len;
1023 struct fscrypt_str de_name = FSTR_INIT(de->name,
1026 /* Directory is encrypted */
1027 err = fscrypt_fname_disk_to_usr(dir, hinfo->hash,
1028 hinfo->minor_hash, &de_name,
1034 err = ext4_htree_store_dirent(dir_file,
1035 hinfo->hash, hinfo->minor_hash, de,
1037 fname_crypto_str.len = save_len;
1047 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1048 fscrypt_fname_free_buffer(&fname_crypto_str);
1055 * This function fills a red-black tree with information from a
1056 * directory. We start scanning the directory in hash order, starting
1057 * at start_hash and start_minor_hash.
1059 * This function returns the number of entries inserted into the tree,
1060 * or a negative error code.
1062 int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
1063 __u32 start_minor_hash, __u32 *next_hash)
1065 struct dx_hash_info hinfo;
1066 struct ext4_dir_entry_2 *de;
1067 struct dx_frame frames[2], *frame;
1073 struct fscrypt_str tmp_str;
1075 dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n",
1076 start_hash, start_minor_hash));
1077 dir = file_inode(dir_file);
1078 if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) {
1079 hinfo.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
1080 if (hinfo.hash_version <= DX_HASH_TEA)
1081 hinfo.hash_version +=
1082 EXT4_SB(dir->i_sb)->s_hash_unsigned;
1083 hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
1084 if (ext4_has_inline_data(dir)) {
1085 int has_inline_data = 1;
1086 count = htree_inlinedir_to_tree(dir_file, dir, 0,
1090 if (has_inline_data) {
1095 count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo,
1096 start_hash, start_minor_hash);
1100 hinfo.hash = start_hash;
1101 hinfo.minor_hash = 0;
1102 frame = dx_probe(NULL, dir, &hinfo, frames);
1104 return PTR_ERR(frame);
1106 /* Add '.' and '..' from the htree header */
1107 if (!start_hash && !start_minor_hash) {
1108 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1109 tmp_str.name = de->name;
1110 tmp_str.len = de->name_len;
1111 err = ext4_htree_store_dirent(dir_file, 0, 0,
1117 if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) {
1118 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1119 de = ext4_next_entry(de, dir->i_sb->s_blocksize);
1120 tmp_str.name = de->name;
1121 tmp_str.len = de->name_len;
1122 err = ext4_htree_store_dirent(dir_file, 2, 0,
1130 if (fatal_signal_pending(current)) {
1135 block = dx_get_block(frame->at);
1136 ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
1137 start_hash, start_minor_hash);
1144 ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS,
1145 frame, frames, &hashval);
1146 *next_hash = hashval;
1152 * Stop if: (a) there are no more entries, or
1153 * (b) we have inserted at least one entry and the
1154 * next hash value is not a continuation
1157 (count && ((hashval & 1) == 0)))
1161 dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, "
1162 "next hash: %x\n", count, *next_hash));
1169 static inline int search_dirblock(struct buffer_head *bh,
1171 struct ext4_filename *fname,
1172 const struct qstr *d_name,
1173 unsigned int offset,
1174 struct ext4_dir_entry_2 **res_dir)
1176 return ext4_search_dir(bh, bh->b_data, dir->i_sb->s_blocksize, dir,
1177 fname, d_name, offset, res_dir);
1181 * Directory block splitting, compacting
1185 * Create map of hash values, offsets, and sizes, stored at end of block.
1186 * Returns number of entries mapped.
1188 static int dx_make_map(struct inode *dir, struct ext4_dir_entry_2 *de,
1189 unsigned blocksize, struct dx_hash_info *hinfo,
1190 struct dx_map_entry *map_tail)
1193 char *base = (char *) de;
1194 struct dx_hash_info h = *hinfo;
1196 while ((char *) de < base + blocksize) {
1197 if (de->name_len && de->inode) {
1198 ext4fs_dirhash(de->name, de->name_len, &h);
1200 map_tail->hash = h.hash;
1201 map_tail->offs = ((char *) de - base)>>2;
1202 map_tail->size = le16_to_cpu(de->rec_len);
1206 /* XXX: do we need to check rec_len == 0 case? -Chris */
1207 de = ext4_next_entry(de, blocksize);
1212 /* Sort map by hash value */
1213 static void dx_sort_map (struct dx_map_entry *map, unsigned count)
1215 struct dx_map_entry *p, *q, *top = map + count - 1;
1217 /* Combsort until bubble sort doesn't suck */
1219 count = count*10/13;
1220 if (count - 9 < 2) /* 9, 10 -> 11 */
1222 for (p = top, q = p - count; q >= map; p--, q--)
1223 if (p->hash < q->hash)
1226 /* Garden variety bubble sort */
1231 if (q[1].hash >= q[0].hash)
1239 static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block)
1241 struct dx_entry *entries = frame->entries;
1242 struct dx_entry *old = frame->at, *new = old + 1;
1243 int count = dx_get_count(entries);
1245 assert(count < dx_get_limit(entries));
1246 assert(old < entries + count);
1247 memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
1248 dx_set_hash(new, hash);
1249 dx_set_block(new, block);
1250 dx_set_count(entries, count + 1);
1254 * Test whether a directory entry matches the filename being searched for.
1256 * Return: %true if the directory entry matches, otherwise %false.
1258 static inline bool ext4_match(const struct ext4_filename *fname,
1259 const struct ext4_dir_entry_2 *de)
1261 const void *name = fname_name(fname);
1262 u32 len = fname_len(fname);
1267 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1268 if (unlikely(!name)) {
1269 if (fname->usr_fname->name[0] == '_') {
1271 if (de->name_len <= 32)
1273 ret = memcmp(de->name + ((de->name_len - 17) & ~15),
1274 fname->crypto_buf.name + 8, 16);
1275 return (ret == 0) ? 1 : 0;
1277 name = fname->crypto_buf.name;
1278 len = fname->crypto_buf.len;
1281 if (de->name_len != len)
1283 return (memcmp(de->name, name, len) == 0) ? 1 : 0;
1287 * Returns 0 if not found, -1 on failure, and 1 on success
1289 int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size,
1290 struct inode *dir, struct ext4_filename *fname,
1291 const struct qstr *d_name,
1292 unsigned int offset, struct ext4_dir_entry_2 **res_dir)
1294 struct ext4_dir_entry_2 * de;
1298 de = (struct ext4_dir_entry_2 *)search_buf;
1299 dlimit = search_buf + buf_size;
1300 while ((char *) de < dlimit) {
1301 /* this code is executed quadratically often */
1302 /* do minimal checking `by hand' */
1303 if ((char *) de + de->name_len <= dlimit &&
1304 ext4_match(fname, de)) {
1305 /* found a match - just to be sure, do
1307 if (ext4_check_dir_entry(dir, NULL, de, bh, search_buf,
1313 /* prevent looping on a bad block */
1314 de_len = ext4_rec_len_from_disk(de->rec_len,
1315 dir->i_sb->s_blocksize);
1319 de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
1324 static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block,
1325 struct ext4_dir_entry *de)
1327 struct super_block *sb = dir->i_sb;
1333 if (de->inode == 0 &&
1334 ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) ==
1343 * finds an entry in the specified directory with the wanted name. It
1344 * returns the cache buffer in which the entry was found, and the entry
1345 * itself (as a parameter - res_dir). It does NOT read the inode of the
1346 * entry - you'll have to do that yourself if you want to.
1348 * The returned buffer_head has ->b_count elevated. The caller is expected
1349 * to brelse() it when appropriate.
1351 static struct buffer_head * ext4_find_entry (struct inode *dir,
1352 const struct qstr *d_name,
1353 struct ext4_dir_entry_2 **res_dir,
1356 struct super_block *sb;
1357 struct buffer_head *bh_use[NAMEI_RA_SIZE];
1358 struct buffer_head *bh, *ret = NULL;
1359 ext4_lblk_t start, block, b;
1360 const u8 *name = d_name->name;
1361 int ra_max = 0; /* Number of bh's in the readahead
1363 int ra_ptr = 0; /* Current index into readahead
1366 ext4_lblk_t nblocks;
1367 int i, namelen, retval;
1368 struct ext4_filename fname;
1372 namelen = d_name->len;
1373 if (namelen > EXT4_NAME_LEN)
1376 retval = ext4_fname_setup_filename(dir, d_name, 1, &fname);
1377 if (retval == -ENOENT)
1380 return ERR_PTR(retval);
1382 if (ext4_has_inline_data(dir)) {
1383 int has_inline_data = 1;
1384 ret = ext4_find_inline_entry(dir, &fname, d_name, res_dir,
1386 if (has_inline_data) {
1389 goto cleanup_and_exit;
1393 if ((namelen <= 2) && (name[0] == '.') &&
1394 (name[1] == '.' || name[1] == '\0')) {
1396 * "." or ".." will only be in the first block
1397 * NFS may look up ".."; "." should be handled by the VFS
1404 ret = ext4_dx_find_entry(dir, &fname, res_dir);
1406 * On success, or if the error was file not found,
1407 * return. Otherwise, fall back to doing a search the
1408 * old fashioned way.
1410 if (!IS_ERR(ret) || PTR_ERR(ret) != ERR_BAD_DX_DIR)
1411 goto cleanup_and_exit;
1412 dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
1416 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1419 goto cleanup_and_exit;
1421 start = EXT4_I(dir)->i_dir_start_lookup;
1422 if (start >= nblocks)
1428 * We deal with the read-ahead logic here.
1431 if (ra_ptr >= ra_max) {
1432 /* Refill the readahead buffer */
1435 for (ra_max = 0; ra_max < NAMEI_RA_SIZE; ra_max++) {
1437 * Terminate if we reach the end of the
1438 * directory and must wrap, or if our
1439 * search has finished at this block.
1441 if (b >= nblocks || (num && block == start)) {
1442 bh_use[ra_max] = NULL;
1446 bh = ext4_getblk(NULL, dir, b++, 0);
1450 goto cleanup_and_exit;
1454 bh_use[ra_max] = bh;
1456 ll_rw_block(REQ_OP_READ,
1457 REQ_META | REQ_PRIO,
1461 if ((bh = bh_use[ra_ptr++]) == NULL)
1464 if (!buffer_uptodate(bh)) {
1465 /* read error, skip block & hope for the best */
1466 EXT4_ERROR_INODE(dir, "reading directory lblock %lu",
1467 (unsigned long) block);
1471 if (!buffer_verified(bh) &&
1472 !is_dx_internal_node(dir, block,
1473 (struct ext4_dir_entry *)bh->b_data) &&
1474 !ext4_dirent_csum_verify(dir,
1475 (struct ext4_dir_entry *)bh->b_data)) {
1476 EXT4_ERROR_INODE(dir, "checksumming directory "
1477 "block %lu", (unsigned long)block);
1481 set_buffer_verified(bh);
1482 i = search_dirblock(bh, dir, &fname, d_name,
1483 block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
1485 EXT4_I(dir)->i_dir_start_lookup = block;
1487 goto cleanup_and_exit;
1491 goto cleanup_and_exit;
1494 if (++block >= nblocks)
1496 } while (block != start);
1499 * If the directory has grown while we were searching, then
1500 * search the last part of the directory before giving up.
1503 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1504 if (block < nblocks) {
1510 /* Clean up the read-ahead blocks */
1511 for (; ra_ptr < ra_max; ra_ptr++)
1512 brelse(bh_use[ra_ptr]);
1513 ext4_fname_free_filename(&fname);
1517 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
1518 struct ext4_filename *fname,
1519 struct ext4_dir_entry_2 **res_dir)
1521 struct super_block * sb = dir->i_sb;
1522 struct dx_frame frames[2], *frame;
1523 const struct qstr *d_name = fname->usr_fname;
1524 struct buffer_head *bh;
1528 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1531 frame = dx_probe(fname, dir, NULL, frames);
1533 return (struct buffer_head *) frame;
1535 block = dx_get_block(frame->at);
1536 bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
1540 retval = search_dirblock(bh, dir, fname, d_name,
1541 block << EXT4_BLOCK_SIZE_BITS(sb),
1547 bh = ERR_PTR(ERR_BAD_DX_DIR);
1551 /* Check to see if we should continue to search */
1552 retval = ext4_htree_next_block(dir, fname->hinfo.hash, frame,
1555 ext4_warning_inode(dir,
1556 "error %d reading directory index block",
1558 bh = ERR_PTR(retval);
1561 } while (retval == 1);
1565 dxtrace(printk(KERN_DEBUG "%s not found\n", d_name->name));
1571 static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
1573 struct inode *inode;
1574 struct ext4_dir_entry_2 *de;
1575 struct buffer_head *bh;
1577 if (ext4_encrypted_inode(dir)) {
1578 int res = fscrypt_get_encryption_info(dir);
1581 * DCACHE_ENCRYPTED_WITH_KEY is set if the dentry is
1582 * created while the directory was encrypted and we
1583 * have access to the key.
1585 if (fscrypt_has_encryption_key(dir))
1586 fscrypt_set_encrypted_dentry(dentry);
1587 fscrypt_set_d_op(dentry);
1588 if (res && res != -ENOKEY)
1589 return ERR_PTR(res);
1592 if (dentry->d_name.len > EXT4_NAME_LEN)
1593 return ERR_PTR(-ENAMETOOLONG);
1595 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
1597 return (struct dentry *) bh;
1600 __u32 ino = le32_to_cpu(de->inode);
1602 if (!ext4_valid_inum(dir->i_sb, ino)) {
1603 EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
1604 return ERR_PTR(-EFSCORRUPTED);
1606 if (unlikely(ino == dir->i_ino)) {
1607 EXT4_ERROR_INODE(dir, "'%pd' linked to parent dir",
1609 return ERR_PTR(-EFSCORRUPTED);
1611 inode = ext4_iget(dir->i_sb, ino, EXT4_IGET_NORMAL);
1612 if (inode == ERR_PTR(-ESTALE)) {
1613 EXT4_ERROR_INODE(dir,
1614 "deleted inode referenced: %u",
1616 return ERR_PTR(-EFSCORRUPTED);
1618 if (!IS_ERR(inode) && ext4_encrypted_inode(dir) &&
1619 (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
1620 !fscrypt_has_permitted_context(dir, inode)) {
1621 int nokey = ext4_encrypted_inode(inode) &&
1622 !fscrypt_has_encryption_key(inode);
1625 return ERR_PTR(-ENOKEY);
1627 ext4_warning(inode->i_sb,
1628 "Inconsistent encryption contexts: %lu/%lu",
1629 (unsigned long) dir->i_ino,
1630 (unsigned long) inode->i_ino);
1632 return ERR_PTR(-EPERM);
1635 return d_splice_alias(inode, dentry);
1639 struct dentry *ext4_get_parent(struct dentry *child)
1642 static const struct qstr dotdot = QSTR_INIT("..", 2);
1643 struct ext4_dir_entry_2 * de;
1644 struct buffer_head *bh;
1646 bh = ext4_find_entry(d_inode(child), &dotdot, &de, NULL);
1648 return (struct dentry *) bh;
1650 return ERR_PTR(-ENOENT);
1651 ino = le32_to_cpu(de->inode);
1654 if (!ext4_valid_inum(child->d_sb, ino)) {
1655 EXT4_ERROR_INODE(d_inode(child),
1656 "bad parent inode number: %u", ino);
1657 return ERR_PTR(-EFSCORRUPTED);
1660 return d_obtain_alias(ext4_iget(child->d_sb, ino, EXT4_IGET_NORMAL));
1664 * Move count entries from end of map between two memory locations.
1665 * Returns pointer to last entry moved.
1667 static struct ext4_dir_entry_2 *
1668 dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count,
1671 unsigned rec_len = 0;
1674 struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
1675 (from + (map->offs<<2));
1676 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1677 memcpy (to, de, rec_len);
1678 ((struct ext4_dir_entry_2 *) to)->rec_len =
1679 ext4_rec_len_to_disk(rec_len, blocksize);
1684 return (struct ext4_dir_entry_2 *) (to - rec_len);
1688 * Compact each dir entry in the range to the minimal rec_len.
1689 * Returns pointer to last entry in range.
1691 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize)
1693 struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
1694 unsigned rec_len = 0;
1697 while ((char*)de < base + blocksize) {
1698 next = ext4_next_entry(de, blocksize);
1699 if (de->inode && de->name_len) {
1700 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1702 memmove(to, de, rec_len);
1703 to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
1705 to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
1713 * Split a full leaf block to make room for a new dir entry.
1714 * Allocate a new block, and move entries so that they are approx. equally full.
1715 * Returns pointer to de in block into which the new entry will be inserted.
1717 static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
1718 struct buffer_head **bh,struct dx_frame *frame,
1719 struct dx_hash_info *hinfo)
1721 unsigned blocksize = dir->i_sb->s_blocksize;
1722 unsigned count, continued;
1723 struct buffer_head *bh2;
1724 ext4_lblk_t newblock;
1726 struct dx_map_entry *map;
1727 char *data1 = (*bh)->b_data, *data2;
1728 unsigned split, move, size;
1729 struct ext4_dir_entry_2 *de = NULL, *de2;
1730 struct ext4_dir_entry_tail *t;
1734 if (ext4_has_metadata_csum(dir->i_sb))
1735 csum_size = sizeof(struct ext4_dir_entry_tail);
1737 bh2 = ext4_append(handle, dir, &newblock);
1741 return (struct ext4_dir_entry_2 *) bh2;
1744 BUFFER_TRACE(*bh, "get_write_access");
1745 err = ext4_journal_get_write_access(handle, *bh);
1749 BUFFER_TRACE(frame->bh, "get_write_access");
1750 err = ext4_journal_get_write_access(handle, frame->bh);
1754 data2 = bh2->b_data;
1756 /* create map in the end of data2 block */
1757 map = (struct dx_map_entry *) (data2 + blocksize);
1758 count = dx_make_map(dir, (struct ext4_dir_entry_2 *) data1,
1759 blocksize, hinfo, map);
1761 dx_sort_map(map, count);
1762 /* Ensure that neither split block is over half full */
1765 for (i = count-1; i >= 0; i--) {
1766 /* is more than half of this entry in 2nd half of the block? */
1767 if (size + map[i].size/2 > blocksize/2)
1769 size += map[i].size;
1773 * map index at which we will split
1775 * If the sum of active entries didn't exceed half the block size, just
1776 * split it in half by count; each resulting block will have at least
1777 * half the space free.
1780 split = count - move;
1784 hash2 = map[split].hash;
1785 continued = hash2 == map[split - 1].hash;
1786 dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
1787 (unsigned long)dx_get_block(frame->at),
1788 hash2, split, count-split));
1790 /* Fancy dance to stay within two buffers */
1791 de2 = dx_move_dirents(data1, data2, map + split, count - split,
1793 de = dx_pack_dirents(data1, blocksize);
1794 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
1797 de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
1801 t = EXT4_DIRENT_TAIL(data2, blocksize);
1802 initialize_dirent_tail(t, blocksize);
1804 t = EXT4_DIRENT_TAIL(data1, blocksize);
1805 initialize_dirent_tail(t, blocksize);
1808 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,
1810 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,
1813 /* Which block gets the new entry? */
1814 if (hinfo->hash >= hash2) {
1818 dx_insert_block(frame, hash2 + continued, newblock);
1819 err = ext4_handle_dirty_dirent_node(handle, dir, bh2);
1822 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
1826 dxtrace(dx_show_index("frame", frame->entries));
1833 ext4_std_error(dir->i_sb, err);
1834 return ERR_PTR(err);
1837 int ext4_find_dest_de(struct inode *dir, struct inode *inode,
1838 struct buffer_head *bh,
1839 void *buf, int buf_size,
1840 struct ext4_filename *fname,
1841 struct ext4_dir_entry_2 **dest_de)
1843 struct ext4_dir_entry_2 *de;
1844 unsigned short reclen = EXT4_DIR_REC_LEN(fname_len(fname));
1846 unsigned int offset = 0;
1849 de = (struct ext4_dir_entry_2 *)buf;
1850 top = buf + buf_size - reclen;
1851 while ((char *) de <= top) {
1852 if (ext4_check_dir_entry(dir, NULL, de, bh,
1853 buf, buf_size, offset))
1854 return -EFSCORRUPTED;
1855 if (ext4_match(fname, de))
1857 nlen = EXT4_DIR_REC_LEN(de->name_len);
1858 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1859 if ((de->inode ? rlen - nlen : rlen) >= reclen)
1861 de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
1864 if ((char *) de > top)
1871 int ext4_insert_dentry(struct inode *dir,
1872 struct inode *inode,
1873 struct ext4_dir_entry_2 *de,
1875 struct ext4_filename *fname)
1880 nlen = EXT4_DIR_REC_LEN(de->name_len);
1881 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1883 struct ext4_dir_entry_2 *de1 =
1884 (struct ext4_dir_entry_2 *)((char *)de + nlen);
1885 de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size);
1886 de->rec_len = ext4_rec_len_to_disk(nlen, buf_size);
1889 de->file_type = EXT4_FT_UNKNOWN;
1890 de->inode = cpu_to_le32(inode->i_ino);
1891 ext4_set_de_type(inode->i_sb, de, inode->i_mode);
1892 de->name_len = fname_len(fname);
1893 memcpy(de->name, fname_name(fname), fname_len(fname));
1898 * Add a new entry into a directory (leaf) block. If de is non-NULL,
1899 * it points to a directory entry which is guaranteed to be large
1900 * enough for new directory entry. If de is NULL, then
1901 * add_dirent_to_buf will attempt search the directory block for
1902 * space. It will return -ENOSPC if no space is available, and -EIO
1903 * and -EEXIST if directory entry already exists.
1905 static int add_dirent_to_buf(handle_t *handle, struct ext4_filename *fname,
1907 struct inode *inode, struct ext4_dir_entry_2 *de,
1908 struct buffer_head *bh)
1910 unsigned int blocksize = dir->i_sb->s_blocksize;
1914 if (ext4_has_metadata_csum(inode->i_sb))
1915 csum_size = sizeof(struct ext4_dir_entry_tail);
1918 err = ext4_find_dest_de(dir, inode, bh, bh->b_data,
1919 blocksize - csum_size, fname, &de);
1923 BUFFER_TRACE(bh, "get_write_access");
1924 err = ext4_journal_get_write_access(handle, bh);
1926 ext4_std_error(dir->i_sb, err);
1930 /* By now the buffer is marked for journaling. Due to crypto operations,
1931 * the following function call may fail */
1932 err = ext4_insert_dentry(dir, inode, de, blocksize, fname);
1937 * XXX shouldn't update any times until successful
1938 * completion of syscall, but too many callers depend
1941 * XXX similarly, too many callers depend on
1942 * ext4_new_inode() setting the times, but error
1943 * recovery deletes the inode, so the worst that can
1944 * happen is that the times are slightly out of date
1945 * and/or different from the directory change time.
1947 dir->i_mtime = dir->i_ctime = ext4_current_time(dir);
1948 ext4_update_dx_flag(dir);
1950 ext4_mark_inode_dirty(handle, dir);
1951 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1952 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
1954 ext4_std_error(dir->i_sb, err);
1959 * This converts a one block unindexed directory to a 3 block indexed
1960 * directory, and adds the dentry to the indexed directory.
1962 static int make_indexed_dir(handle_t *handle, struct ext4_filename *fname,
1964 struct inode *inode, struct buffer_head *bh)
1966 struct buffer_head *bh2;
1967 struct dx_root *root;
1968 struct dx_frame frames[2], *frame;
1969 struct dx_entry *entries;
1970 struct ext4_dir_entry_2 *de, *de2;
1971 struct ext4_dir_entry_tail *t;
1977 struct fake_dirent *fde;
1980 if (ext4_has_metadata_csum(inode->i_sb))
1981 csum_size = sizeof(struct ext4_dir_entry_tail);
1983 blocksize = dir->i_sb->s_blocksize;
1984 dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
1985 BUFFER_TRACE(bh, "get_write_access");
1986 retval = ext4_journal_get_write_access(handle, bh);
1988 ext4_std_error(dir->i_sb, retval);
1992 root = (struct dx_root *) bh->b_data;
1994 /* The 0th block becomes the root, move the dirents out */
1995 fde = &root->dotdot;
1996 de = (struct ext4_dir_entry_2 *)((char *)fde +
1997 ext4_rec_len_from_disk(fde->rec_len, blocksize));
1998 if ((char *) de >= (((char *) root) + blocksize)) {
1999 EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
2001 return -EFSCORRUPTED;
2003 len = ((char *) root) + (blocksize - csum_size) - (char *) de;
2005 /* Allocate new block for the 0th block's dirents */
2006 bh2 = ext4_append(handle, dir, &block);
2009 return PTR_ERR(bh2);
2011 ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
2012 data1 = bh2->b_data;
2014 memcpy (data1, de, len);
2015 de = (struct ext4_dir_entry_2 *) data1;
2017 while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top)
2019 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
2024 t = EXT4_DIRENT_TAIL(data1, blocksize);
2025 initialize_dirent_tail(t, blocksize);
2028 /* Initialize the root; the dot dirents already exist */
2029 de = (struct ext4_dir_entry_2 *) (&root->dotdot);
2030 de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
2032 memset (&root->info, 0, sizeof(root->info));
2033 root->info.info_length = sizeof(root->info);
2034 root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
2035 entries = root->entries;
2036 dx_set_block(entries, 1);
2037 dx_set_count(entries, 1);
2038 dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
2040 /* Initialize as for dx_probe */
2041 fname->hinfo.hash_version = root->info.hash_version;
2042 if (fname->hinfo.hash_version <= DX_HASH_TEA)
2043 fname->hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
2044 fname->hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
2045 ext4fs_dirhash(fname_name(fname), fname_len(fname), &fname->hinfo);
2047 memset(frames, 0, sizeof(frames));
2049 frame->entries = entries;
2050 frame->at = entries;
2053 retval = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2056 retval = ext4_handle_dirty_dirent_node(handle, dir, bh2);
2060 de = do_split(handle,dir, &bh2, frame, &fname->hinfo);
2062 retval = PTR_ERR(de);
2066 retval = add_dirent_to_buf(handle, fname, dir, inode, de, bh2);
2069 * Even if the block split failed, we have to properly write
2070 * out all the changes we did so far. Otherwise we can end up
2071 * with corrupted filesystem.
2074 ext4_mark_inode_dirty(handle, dir);
2083 * adds a file entry to the specified directory, using the same
2084 * semantics as ext4_find_entry(). It returns NULL if it failed.
2086 * NOTE!! The inode part of 'de' is left at 0 - which means you
2087 * may not sleep between calling this and putting something into
2088 * the entry, as someone else might have used it while you slept.
2090 static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
2091 struct inode *inode)
2093 struct inode *dir = d_inode(dentry->d_parent);
2094 struct buffer_head *bh = NULL;
2095 struct ext4_dir_entry_2 *de;
2096 struct ext4_dir_entry_tail *t;
2097 struct super_block *sb;
2098 struct ext4_filename fname;
2102 ext4_lblk_t block, blocks;
2105 if (ext4_has_metadata_csum(inode->i_sb))
2106 csum_size = sizeof(struct ext4_dir_entry_tail);
2109 blocksize = sb->s_blocksize;
2110 if (!dentry->d_name.len)
2113 retval = ext4_fname_setup_filename(dir, &dentry->d_name, 0, &fname);
2117 if (ext4_has_inline_data(dir)) {
2118 retval = ext4_try_add_inline_entry(handle, &fname, dir, inode);
2128 retval = ext4_dx_add_entry(handle, &fname, dir, inode);
2129 if (!retval || (retval != ERR_BAD_DX_DIR))
2131 /* Can we just ignore htree data? */
2132 if (ext4_has_metadata_csum(sb)) {
2133 EXT4_ERROR_INODE(dir,
2134 "Directory has corrupted htree index.");
2135 retval = -EFSCORRUPTED;
2138 ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
2140 ext4_mark_inode_dirty(handle, dir);
2142 blocks = dir->i_size >> sb->s_blocksize_bits;
2143 for (block = 0; block < blocks; block++) {
2144 bh = ext4_read_dirblock(dir, block, DIRENT);
2146 bh = ext4_bread(handle, dir, block,
2147 EXT4_GET_BLOCKS_CREATE);
2148 goto add_to_new_block;
2151 retval = PTR_ERR(bh);
2155 retval = add_dirent_to_buf(handle, &fname, dir, inode,
2157 if (retval != -ENOSPC)
2160 if (blocks == 1 && !dx_fallback &&
2161 ext4_has_feature_dir_index(sb)) {
2162 retval = make_indexed_dir(handle, &fname, dir,
2164 bh = NULL; /* make_indexed_dir releases bh */
2169 bh = ext4_append(handle, dir, &block);
2172 retval = PTR_ERR(bh);
2176 de = (struct ext4_dir_entry_2 *) bh->b_data;
2178 de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
2181 t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
2182 initialize_dirent_tail(t, blocksize);
2185 retval = add_dirent_to_buf(handle, &fname, dir, inode, de, bh);
2187 ext4_fname_free_filename(&fname);
2190 ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
2195 * Returns 0 for success, or a negative error value
2197 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
2198 struct inode *dir, struct inode *inode)
2200 struct dx_frame frames[2], *frame;
2201 struct dx_entry *entries, *at;
2202 struct buffer_head *bh;
2203 struct super_block *sb = dir->i_sb;
2204 struct ext4_dir_entry_2 *de;
2207 frame = dx_probe(fname, dir, NULL, frames);
2209 return PTR_ERR(frame);
2210 entries = frame->entries;
2212 bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT_HTREE);
2219 BUFFER_TRACE(bh, "get_write_access");
2220 err = ext4_journal_get_write_access(handle, bh);
2224 err = add_dirent_to_buf(handle, fname, dir, inode, NULL, bh);
2228 /* Block full, should compress but for now just split */
2229 dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
2230 dx_get_count(entries), dx_get_limit(entries)));
2231 /* Need to split index? */
2232 if (dx_get_count(entries) == dx_get_limit(entries)) {
2233 ext4_lblk_t newblock;
2234 unsigned icount = dx_get_count(entries);
2235 int levels = frame - frames;
2236 struct dx_entry *entries2;
2237 struct dx_node *node2;
2238 struct buffer_head *bh2;
2240 if (levels && (dx_get_count(frames->entries) ==
2241 dx_get_limit(frames->entries))) {
2242 ext4_warning_inode(dir, "Directory index full!");
2246 bh2 = ext4_append(handle, dir, &newblock);
2251 node2 = (struct dx_node *)(bh2->b_data);
2252 entries2 = node2->entries;
2253 memset(&node2->fake, 0, sizeof(struct fake_dirent));
2254 node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
2256 BUFFER_TRACE(frame->bh, "get_write_access");
2257 err = ext4_journal_get_write_access(handle, frame->bh);
2261 unsigned icount1 = icount/2, icount2 = icount - icount1;
2262 unsigned hash2 = dx_get_hash(entries + icount1);
2263 dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
2266 BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
2267 err = ext4_journal_get_write_access(handle,
2272 memcpy((char *) entries2, (char *) (entries + icount1),
2273 icount2 * sizeof(struct dx_entry));
2274 dx_set_count(entries, icount1);
2275 dx_set_count(entries2, icount2);
2276 dx_set_limit(entries2, dx_node_limit(dir));
2278 /* Which index block gets the new entry? */
2279 if (at - entries >= icount1) {
2280 frame->at = at = at - entries - icount1 + entries2;
2281 frame->entries = entries = entries2;
2282 swap(frame->bh, bh2);
2284 dx_insert_block(frames + 0, hash2, newblock);
2285 dxtrace(dx_show_index("node", frames[1].entries));
2286 dxtrace(dx_show_index("node",
2287 ((struct dx_node *) bh2->b_data)->entries));
2288 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2293 dxtrace(printk(KERN_DEBUG
2294 "Creating second level index...\n"));
2295 memcpy((char *) entries2, (char *) entries,
2296 icount * sizeof(struct dx_entry));
2297 dx_set_limit(entries2, dx_node_limit(dir));
2300 dx_set_count(entries, 1);
2301 dx_set_block(entries + 0, newblock);
2302 ((struct dx_root *) frames[0].bh->b_data)->info.indirect_levels = 1;
2304 /* Add new access path frame */
2306 frame->at = at = at - entries + entries2;
2307 frame->entries = entries = entries2;
2309 err = ext4_journal_get_write_access(handle,
2314 err = ext4_handle_dirty_dx_node(handle, dir, frames[0].bh);
2316 ext4_std_error(inode->i_sb, err);
2320 de = do_split(handle, dir, &bh, frame, &fname->hinfo);
2325 err = add_dirent_to_buf(handle, fname, dir, inode, de, bh);
2329 ext4_std_error(dir->i_sb, err);
2337 * ext4_generic_delete_entry deletes a directory entry by merging it
2338 * with the previous entry
2340 int ext4_generic_delete_entry(handle_t *handle,
2342 struct ext4_dir_entry_2 *de_del,
2343 struct buffer_head *bh,
2348 struct ext4_dir_entry_2 *de, *pde;
2349 unsigned int blocksize = dir->i_sb->s_blocksize;
2354 de = (struct ext4_dir_entry_2 *)entry_buf;
2355 while (i < buf_size - csum_size) {
2356 if (ext4_check_dir_entry(dir, NULL, de, bh,
2357 entry_buf, buf_size, i))
2358 return -EFSCORRUPTED;
2361 pde->rec_len = ext4_rec_len_to_disk(
2362 ext4_rec_len_from_disk(pde->rec_len,
2364 ext4_rec_len_from_disk(de->rec_len,
2372 i += ext4_rec_len_from_disk(de->rec_len, blocksize);
2374 de = ext4_next_entry(de, blocksize);
2379 static int ext4_delete_entry(handle_t *handle,
2381 struct ext4_dir_entry_2 *de_del,
2382 struct buffer_head *bh)
2384 int err, csum_size = 0;
2386 if (ext4_has_inline_data(dir)) {
2387 int has_inline_data = 1;
2388 err = ext4_delete_inline_entry(handle, dir, de_del, bh,
2390 if (has_inline_data)
2394 if (ext4_has_metadata_csum(dir->i_sb))
2395 csum_size = sizeof(struct ext4_dir_entry_tail);
2397 BUFFER_TRACE(bh, "get_write_access");
2398 err = ext4_journal_get_write_access(handle, bh);
2402 err = ext4_generic_delete_entry(handle, dir, de_del,
2404 dir->i_sb->s_blocksize, csum_size);
2408 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
2409 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
2416 ext4_std_error(dir->i_sb, err);
2421 * DIR_NLINK feature is set if 1) nlinks > EXT4_LINK_MAX or 2) nlinks == 2,
2422 * since this indicates that nlinks count was previously 1.
2424 static void ext4_inc_count(handle_t *handle, struct inode *inode)
2427 if (is_dx(inode) && inode->i_nlink > 1) {
2428 /* limit is 16-bit i_links_count */
2429 if (inode->i_nlink >= EXT4_LINK_MAX || inode->i_nlink == 2) {
2430 set_nlink(inode, 1);
2431 ext4_set_feature_dir_nlink(inode->i_sb);
2437 * If a directory had nlink == 1, then we should let it be 1. This indicates
2438 * directory has >EXT4_LINK_MAX subdirs.
2440 static void ext4_dec_count(handle_t *handle, struct inode *inode)
2442 if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
2447 static int ext4_add_nondir(handle_t *handle,
2448 struct dentry *dentry, struct inode *inode)
2450 int err = ext4_add_entry(handle, dentry, inode);
2452 ext4_mark_inode_dirty(handle, inode);
2453 d_instantiate_new(dentry, inode);
2457 unlock_new_inode(inode);
2463 * By the time this is called, we already have created
2464 * the directory cache entry for the new file, but it
2465 * is so far negative - it has no inode.
2467 * If the create succeeds, we fill in the inode information
2468 * with d_instantiate().
2470 static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2474 struct inode *inode;
2475 int err, credits, retries = 0;
2477 err = dquot_initialize(dir);
2481 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2482 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2484 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2485 NULL, EXT4_HT_DIR, credits);
2486 handle = ext4_journal_current_handle();
2487 err = PTR_ERR(inode);
2488 if (!IS_ERR(inode)) {
2489 inode->i_op = &ext4_file_inode_operations;
2490 inode->i_fop = &ext4_file_operations;
2491 ext4_set_aops(inode);
2492 err = ext4_add_nondir(handle, dentry, inode);
2493 if (!err && IS_DIRSYNC(dir))
2494 ext4_handle_sync(handle);
2497 ext4_journal_stop(handle);
2498 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2503 static int ext4_mknod(struct inode *dir, struct dentry *dentry,
2504 umode_t mode, dev_t rdev)
2507 struct inode *inode;
2508 int err, credits, retries = 0;
2510 err = dquot_initialize(dir);
2514 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2515 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2517 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2518 NULL, EXT4_HT_DIR, credits);
2519 handle = ext4_journal_current_handle();
2520 err = PTR_ERR(inode);
2521 if (!IS_ERR(inode)) {
2522 init_special_inode(inode, inode->i_mode, rdev);
2523 inode->i_op = &ext4_special_inode_operations;
2524 err = ext4_add_nondir(handle, dentry, inode);
2525 if (!err && IS_DIRSYNC(dir))
2526 ext4_handle_sync(handle);
2529 ext4_journal_stop(handle);
2530 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2535 static int ext4_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2538 struct inode *inode;
2539 int err, retries = 0;
2541 err = dquot_initialize(dir);
2546 inode = ext4_new_inode_start_handle(dir, mode,
2549 EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
2550 4 + EXT4_XATTR_TRANS_BLOCKS);
2551 handle = ext4_journal_current_handle();
2552 err = PTR_ERR(inode);
2553 if (!IS_ERR(inode)) {
2554 inode->i_op = &ext4_file_inode_operations;
2555 inode->i_fop = &ext4_file_operations;
2556 ext4_set_aops(inode);
2557 d_tmpfile(dentry, inode);
2558 err = ext4_orphan_add(handle, inode);
2560 goto err_unlock_inode;
2561 mark_inode_dirty(inode);
2562 unlock_new_inode(inode);
2565 ext4_journal_stop(handle);
2566 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2570 ext4_journal_stop(handle);
2571 unlock_new_inode(inode);
2575 struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode,
2576 struct ext4_dir_entry_2 *de,
2577 int blocksize, int csum_size,
2578 unsigned int parent_ino, int dotdot_real_len)
2580 de->inode = cpu_to_le32(inode->i_ino);
2582 de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
2584 strcpy(de->name, ".");
2585 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2587 de = ext4_next_entry(de, blocksize);
2588 de->inode = cpu_to_le32(parent_ino);
2590 if (!dotdot_real_len)
2591 de->rec_len = ext4_rec_len_to_disk(blocksize -
2592 (csum_size + EXT4_DIR_REC_LEN(1)),
2595 de->rec_len = ext4_rec_len_to_disk(
2596 EXT4_DIR_REC_LEN(de->name_len), blocksize);
2597 strcpy(de->name, "..");
2598 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2600 return ext4_next_entry(de, blocksize);
2603 static int ext4_init_new_dir(handle_t *handle, struct inode *dir,
2604 struct inode *inode)
2606 struct buffer_head *dir_block = NULL;
2607 struct ext4_dir_entry_2 *de;
2608 struct ext4_dir_entry_tail *t;
2609 ext4_lblk_t block = 0;
2610 unsigned int blocksize = dir->i_sb->s_blocksize;
2614 if (ext4_has_metadata_csum(dir->i_sb))
2615 csum_size = sizeof(struct ext4_dir_entry_tail);
2617 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2618 err = ext4_try_create_inline_dir(handle, dir, inode);
2619 if (err < 0 && err != -ENOSPC)
2626 dir_block = ext4_append(handle, inode, &block);
2627 if (IS_ERR(dir_block))
2628 return PTR_ERR(dir_block);
2629 de = (struct ext4_dir_entry_2 *)dir_block->b_data;
2630 ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0);
2631 set_nlink(inode, 2);
2633 t = EXT4_DIRENT_TAIL(dir_block->b_data, blocksize);
2634 initialize_dirent_tail(t, blocksize);
2637 BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
2638 err = ext4_handle_dirty_dirent_node(handle, inode, dir_block);
2641 set_buffer_verified(dir_block);
2647 static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2650 struct inode *inode;
2651 int err, credits, retries = 0;
2653 if (EXT4_DIR_LINK_MAX(dir))
2656 err = dquot_initialize(dir);
2660 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2661 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2663 inode = ext4_new_inode_start_handle(dir, S_IFDIR | mode,
2665 0, NULL, EXT4_HT_DIR, credits);
2666 handle = ext4_journal_current_handle();
2667 err = PTR_ERR(inode);
2671 inode->i_op = &ext4_dir_inode_operations;
2672 inode->i_fop = &ext4_dir_operations;
2673 err = ext4_init_new_dir(handle, dir, inode);
2675 goto out_clear_inode;
2676 err = ext4_mark_inode_dirty(handle, inode);
2678 err = ext4_add_entry(handle, dentry, inode);
2682 unlock_new_inode(inode);
2683 ext4_mark_inode_dirty(handle, inode);
2687 ext4_inc_count(handle, dir);
2688 ext4_update_dx_flag(dir);
2689 err = ext4_mark_inode_dirty(handle, dir);
2691 goto out_clear_inode;
2692 d_instantiate_new(dentry, inode);
2693 if (IS_DIRSYNC(dir))
2694 ext4_handle_sync(handle);
2698 ext4_journal_stop(handle);
2699 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2705 * routine to check that the specified directory is empty (for rmdir)
2707 bool ext4_empty_dir(struct inode *inode)
2709 unsigned int offset;
2710 struct buffer_head *bh;
2711 struct ext4_dir_entry_2 *de;
2712 struct super_block *sb;
2714 if (ext4_has_inline_data(inode)) {
2715 int has_inline_data = 1;
2718 ret = empty_inline_dir(inode, &has_inline_data);
2719 if (has_inline_data)
2724 if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2)) {
2725 EXT4_ERROR_INODE(inode, "invalid size");
2728 /* The first directory block must not be a hole,
2729 * so treat it as DIRENT_HTREE
2731 bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
2735 de = (struct ext4_dir_entry_2 *) bh->b_data;
2736 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2738 le32_to_cpu(de->inode) != inode->i_ino || strcmp(".", de->name)) {
2739 ext4_warning_inode(inode, "directory missing '.'");
2743 offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2744 de = ext4_next_entry(de, sb->s_blocksize);
2745 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2747 le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
2748 ext4_warning_inode(inode, "directory missing '..'");
2752 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2753 while (offset < inode->i_size) {
2754 if (!(offset & (sb->s_blocksize - 1))) {
2755 unsigned int lblock;
2757 lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
2758 bh = ext4_read_dirblock(inode, lblock, EITHER);
2760 offset += sb->s_blocksize;
2766 de = (struct ext4_dir_entry_2 *) (bh->b_data +
2767 (offset & (sb->s_blocksize - 1)));
2768 if (ext4_check_dir_entry(inode, NULL, de, bh,
2769 bh->b_data, bh->b_size, offset)) {
2770 offset = (offset | (sb->s_blocksize - 1)) + 1;
2773 if (le32_to_cpu(de->inode)) {
2777 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2784 * ext4_orphan_add() links an unlinked or truncated inode into a list of
2785 * such inodes, starting at the superblock, in case we crash before the
2786 * file is closed/deleted, or in case the inode truncate spans multiple
2787 * transactions and the last transaction is not recovered after a crash.
2789 * At filesystem recovery time, we walk this list deleting unlinked
2790 * inodes and truncating linked inodes in ext4_orphan_cleanup().
2792 * Orphan list manipulation functions must be called under i_mutex unless
2793 * we are just creating the inode or deleting it.
2795 int ext4_orphan_add(handle_t *handle, struct inode *inode)
2797 struct super_block *sb = inode->i_sb;
2798 struct ext4_sb_info *sbi = EXT4_SB(sb);
2799 struct ext4_iloc iloc;
2803 if (!sbi->s_journal || is_bad_inode(inode))
2806 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2807 !inode_is_locked(inode));
2809 * Exit early if inode already is on orphan list. This is a big speedup
2810 * since we don't have to contend on the global s_orphan_lock.
2812 if (!list_empty(&EXT4_I(inode)->i_orphan))
2816 * Orphan handling is only valid for files with data blocks
2817 * being truncated, or files being unlinked. Note that we either
2818 * hold i_mutex, or the inode can not be referenced from outside,
2819 * so i_nlink should not be bumped due to race
2821 J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
2822 S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
2824 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2825 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2829 err = ext4_reserve_inode_write(handle, inode, &iloc);
2833 mutex_lock(&sbi->s_orphan_lock);
2835 * Due to previous errors inode may be already a part of on-disk
2836 * orphan list. If so skip on-disk list modification.
2838 if (!NEXT_ORPHAN(inode) || NEXT_ORPHAN(inode) >
2839 (le32_to_cpu(sbi->s_es->s_inodes_count))) {
2840 /* Insert this inode at the head of the on-disk orphan list */
2841 NEXT_ORPHAN(inode) = le32_to_cpu(sbi->s_es->s_last_orphan);
2842 sbi->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
2845 list_add(&EXT4_I(inode)->i_orphan, &sbi->s_orphan);
2846 mutex_unlock(&sbi->s_orphan_lock);
2849 err = ext4_handle_dirty_super(handle, sb);
2850 rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
2855 * We have to remove inode from in-memory list if
2856 * addition to on disk orphan list failed. Stray orphan
2857 * list entries can cause panics at unmount time.
2859 mutex_lock(&sbi->s_orphan_lock);
2860 list_del_init(&EXT4_I(inode)->i_orphan);
2861 mutex_unlock(&sbi->s_orphan_lock);
2866 jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
2867 jbd_debug(4, "orphan inode %lu will point to %d\n",
2868 inode->i_ino, NEXT_ORPHAN(inode));
2870 ext4_std_error(sb, err);
2875 * ext4_orphan_del() removes an unlinked or truncated inode from the list
2876 * of such inodes stored on disk, because it is finally being cleaned up.
2878 int ext4_orphan_del(handle_t *handle, struct inode *inode)
2880 struct list_head *prev;
2881 struct ext4_inode_info *ei = EXT4_I(inode);
2882 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2884 struct ext4_iloc iloc;
2887 if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS))
2890 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2891 !inode_is_locked(inode));
2892 /* Do this quick check before taking global s_orphan_lock. */
2893 if (list_empty(&ei->i_orphan))
2897 /* Grab inode buffer early before taking global s_orphan_lock */
2898 err = ext4_reserve_inode_write(handle, inode, &iloc);
2901 mutex_lock(&sbi->s_orphan_lock);
2902 jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
2904 prev = ei->i_orphan.prev;
2905 list_del_init(&ei->i_orphan);
2907 /* If we're on an error path, we may not have a valid
2908 * transaction handle with which to update the orphan list on
2909 * disk, but we still need to remove the inode from the linked
2910 * list in memory. */
2911 if (!handle || err) {
2912 mutex_unlock(&sbi->s_orphan_lock);
2916 ino_next = NEXT_ORPHAN(inode);
2917 if (prev == &sbi->s_orphan) {
2918 jbd_debug(4, "superblock will point to %u\n", ino_next);
2919 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2920 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2922 mutex_unlock(&sbi->s_orphan_lock);
2925 sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
2926 mutex_unlock(&sbi->s_orphan_lock);
2927 err = ext4_handle_dirty_super(handle, inode->i_sb);
2929 struct ext4_iloc iloc2;
2930 struct inode *i_prev =
2931 &list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
2933 jbd_debug(4, "orphan inode %lu will point to %u\n",
2934 i_prev->i_ino, ino_next);
2935 err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
2937 mutex_unlock(&sbi->s_orphan_lock);
2940 NEXT_ORPHAN(i_prev) = ino_next;
2941 err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
2942 mutex_unlock(&sbi->s_orphan_lock);
2946 NEXT_ORPHAN(inode) = 0;
2947 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
2949 ext4_std_error(inode->i_sb, err);
2957 static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
2960 struct inode *inode;
2961 struct buffer_head *bh;
2962 struct ext4_dir_entry_2 *de;
2963 handle_t *handle = NULL;
2965 /* Initialize quotas before so that eventual writes go in
2966 * separate transaction */
2967 retval = dquot_initialize(dir);
2970 retval = dquot_initialize(d_inode(dentry));
2975 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
2981 inode = d_inode(dentry);
2983 retval = -EFSCORRUPTED;
2984 if (le32_to_cpu(de->inode) != inode->i_ino)
2987 retval = -ENOTEMPTY;
2988 if (!ext4_empty_dir(inode))
2991 handle = ext4_journal_start(dir, EXT4_HT_DIR,
2992 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
2993 if (IS_ERR(handle)) {
2994 retval = PTR_ERR(handle);
2999 if (IS_DIRSYNC(dir))
3000 ext4_handle_sync(handle);
3002 retval = ext4_delete_entry(handle, dir, de, bh);
3005 if (!EXT4_DIR_LINK_EMPTY(inode))
3006 ext4_warning_inode(inode,
3007 "empty directory '%.*s' has too many links (%u)",
3008 dentry->d_name.len, dentry->d_name.name,
3012 /* There's no need to set i_disksize: the fact that i_nlink is
3013 * zero will ensure that the right thing happens during any
3016 ext4_orphan_add(handle, inode);
3017 inode->i_ctime = dir->i_ctime = dir->i_mtime = ext4_current_time(inode);
3018 ext4_mark_inode_dirty(handle, inode);
3019 ext4_dec_count(handle, dir);
3020 ext4_update_dx_flag(dir);
3021 ext4_mark_inode_dirty(handle, dir);
3026 ext4_journal_stop(handle);
3030 static int ext4_unlink(struct inode *dir, struct dentry *dentry)
3033 struct inode *inode;
3034 struct buffer_head *bh;
3035 struct ext4_dir_entry_2 *de;
3036 handle_t *handle = NULL;
3038 trace_ext4_unlink_enter(dir, dentry);
3039 /* Initialize quotas before so that eventual writes go
3040 * in separate transaction */
3041 retval = dquot_initialize(dir);
3044 retval = dquot_initialize(d_inode(dentry));
3049 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3055 inode = d_inode(dentry);
3057 retval = -EFSCORRUPTED;
3058 if (le32_to_cpu(de->inode) != inode->i_ino)
3061 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3062 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3063 if (IS_ERR(handle)) {
3064 retval = PTR_ERR(handle);
3069 if (IS_DIRSYNC(dir))
3070 ext4_handle_sync(handle);
3072 retval = ext4_delete_entry(handle, dir, de, bh);
3075 dir->i_ctime = dir->i_mtime = ext4_current_time(dir);
3076 ext4_update_dx_flag(dir);
3077 ext4_mark_inode_dirty(handle, dir);
3078 if (inode->i_nlink == 0)
3079 ext4_warning_inode(inode, "Deleting file '%.*s' with no links",
3080 dentry->d_name.len, dentry->d_name.name);
3083 if (!inode->i_nlink)
3084 ext4_orphan_add(handle, inode);
3085 inode->i_ctime = ext4_current_time(inode);
3086 ext4_mark_inode_dirty(handle, inode);
3091 ext4_journal_stop(handle);
3092 trace_ext4_unlink_exit(dentry, retval);
3096 static int ext4_symlink(struct inode *dir,
3097 struct dentry *dentry, const char *symname)
3100 struct inode *inode;
3101 int err, len = strlen(symname);
3103 bool encryption_required;
3104 struct fscrypt_str disk_link;
3105 struct fscrypt_symlink_data *sd = NULL;
3107 disk_link.len = len + 1;
3108 disk_link.name = (char *) symname;
3110 encryption_required = (ext4_encrypted_inode(dir) ||
3111 DUMMY_ENCRYPTION_ENABLED(EXT4_SB(dir->i_sb)));
3112 if (encryption_required) {
3113 err = fscrypt_get_encryption_info(dir);
3116 if (!fscrypt_has_encryption_key(dir))
3118 disk_link.len = (fscrypt_fname_encrypted_size(dir, len) +
3119 sizeof(struct fscrypt_symlink_data));
3120 sd = kzalloc(disk_link.len, GFP_KERNEL);
3125 if (disk_link.len > dir->i_sb->s_blocksize) {
3126 err = -ENAMETOOLONG;
3130 err = dquot_initialize(dir);
3134 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3136 * For non-fast symlinks, we just allocate inode and put it on
3137 * orphan list in the first transaction => we need bitmap,
3138 * group descriptor, sb, inode block, quota blocks, and
3139 * possibly selinux xattr blocks.
3141 credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
3142 EXT4_XATTR_TRANS_BLOCKS;
3145 * Fast symlink. We have to add entry to directory
3146 * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
3147 * allocate new inode (bitmap, group descriptor, inode block,
3148 * quota blocks, sb is already counted in previous macros).
3150 credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3151 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3;
3154 inode = ext4_new_inode_start_handle(dir, S_IFLNK|S_IRWXUGO,
3155 &dentry->d_name, 0, NULL,
3156 EXT4_HT_DIR, credits);
3157 handle = ext4_journal_current_handle();
3158 if (IS_ERR(inode)) {
3160 ext4_journal_stop(handle);
3161 err = PTR_ERR(inode);
3165 if (encryption_required) {
3167 struct fscrypt_str ostr =
3168 FSTR_INIT(sd->encrypted_path, disk_link.len);
3170 istr.name = (const unsigned char *) symname;
3172 err = fscrypt_fname_usr_to_disk(inode, &istr, &ostr);
3174 goto err_drop_inode;
3175 sd->len = cpu_to_le16(ostr.len);
3176 disk_link.name = (char *) sd;
3177 inode->i_op = &ext4_encrypted_symlink_inode_operations;
3180 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3181 if (!encryption_required)
3182 inode->i_op = &ext4_symlink_inode_operations;
3183 inode_nohighmem(inode);
3184 ext4_set_aops(inode);
3186 * We cannot call page_symlink() with transaction started
3187 * because it calls into ext4_write_begin() which can wait
3188 * for transaction commit if we are running out of space
3189 * and thus we deadlock. So we have to stop transaction now
3190 * and restart it when symlink contents is written.
3192 * To keep fs consistent in case of crash, we have to put inode
3193 * to orphan list in the mean time.
3196 err = ext4_orphan_add(handle, inode);
3197 ext4_journal_stop(handle);
3200 goto err_drop_inode;
3201 err = __page_symlink(inode, disk_link.name, disk_link.len, 1);
3203 goto err_drop_inode;
3205 * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
3206 * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
3208 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3209 EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3210 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
3211 if (IS_ERR(handle)) {
3212 err = PTR_ERR(handle);
3214 goto err_drop_inode;
3216 set_nlink(inode, 1);
3217 err = ext4_orphan_del(handle, inode);
3219 goto err_drop_inode;
3221 /* clear the extent format for fast symlink */
3222 ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
3223 if (!encryption_required) {
3224 inode->i_op = &ext4_fast_symlink_inode_operations;
3225 inode->i_link = (char *)&EXT4_I(inode)->i_data;
3227 memcpy((char *)&EXT4_I(inode)->i_data, disk_link.name,
3229 inode->i_size = disk_link.len - 1;
3231 EXT4_I(inode)->i_disksize = inode->i_size;
3232 err = ext4_add_nondir(handle, dentry, inode);
3233 if (!err && IS_DIRSYNC(dir))
3234 ext4_handle_sync(handle);
3237 ext4_journal_stop(handle);
3242 ext4_journal_stop(handle);
3244 unlock_new_inode(inode);
3251 static int ext4_link(struct dentry *old_dentry,
3252 struct inode *dir, struct dentry *dentry)
3255 struct inode *inode = d_inode(old_dentry);
3256 int err, retries = 0;
3258 if (inode->i_nlink >= EXT4_LINK_MAX)
3260 if (ext4_encrypted_inode(dir) &&
3261 !fscrypt_has_permitted_context(dir, inode))
3264 if ((ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT)) &&
3265 (!projid_eq(EXT4_I(dir)->i_projid,
3266 EXT4_I(old_dentry->d_inode)->i_projid)))
3269 err = dquot_initialize(dir);
3274 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3275 (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3276 EXT4_INDEX_EXTRA_TRANS_BLOCKS) + 1);
3278 return PTR_ERR(handle);
3280 if (IS_DIRSYNC(dir))
3281 ext4_handle_sync(handle);
3283 inode->i_ctime = ext4_current_time(inode);
3284 ext4_inc_count(handle, inode);
3287 err = ext4_add_entry(handle, dentry, inode);
3289 ext4_mark_inode_dirty(handle, inode);
3290 /* this can happen only for tmpfile being
3291 * linked the first time
3293 if (inode->i_nlink == 1)
3294 ext4_orphan_del(handle, inode);
3295 d_instantiate(dentry, inode);
3300 ext4_journal_stop(handle);
3301 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
3308 * Try to find buffer head where contains the parent block.
3309 * It should be the inode block if it is inlined or the 1st block
3310 * if it is a normal dir.
3312 static struct buffer_head *ext4_get_first_dir_block(handle_t *handle,
3313 struct inode *inode,
3315 struct ext4_dir_entry_2 **parent_de,
3318 struct buffer_head *bh;
3320 if (!ext4_has_inline_data(inode)) {
3321 /* The first directory block must not be a hole, so
3322 * treat it as DIRENT_HTREE
3324 bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
3326 *retval = PTR_ERR(bh);
3329 *parent_de = ext4_next_entry(
3330 (struct ext4_dir_entry_2 *)bh->b_data,
3331 inode->i_sb->s_blocksize);
3336 return ext4_get_first_inline_block(inode, parent_de, retval);
3339 struct ext4_renament {
3341 struct dentry *dentry;
3342 struct inode *inode;
3344 int dir_nlink_delta;
3346 /* entry for "dentry" */
3347 struct buffer_head *bh;
3348 struct ext4_dir_entry_2 *de;
3351 /* entry for ".." in inode if it's a directory */
3352 struct buffer_head *dir_bh;
3353 struct ext4_dir_entry_2 *parent_de;
3357 static int ext4_rename_dir_prepare(handle_t *handle, struct ext4_renament *ent)
3361 ent->dir_bh = ext4_get_first_dir_block(handle, ent->inode,
3362 &retval, &ent->parent_de,
3366 if (le32_to_cpu(ent->parent_de->inode) != ent->dir->i_ino)
3367 return -EFSCORRUPTED;
3368 BUFFER_TRACE(ent->dir_bh, "get_write_access");
3369 return ext4_journal_get_write_access(handle, ent->dir_bh);
3372 static int ext4_rename_dir_finish(handle_t *handle, struct ext4_renament *ent,
3377 ent->parent_de->inode = cpu_to_le32(dir_ino);
3378 BUFFER_TRACE(ent->dir_bh, "call ext4_handle_dirty_metadata");
3379 if (!ent->dir_inlined) {
3380 if (is_dx(ent->inode)) {
3381 retval = ext4_handle_dirty_dx_node(handle,
3385 retval = ext4_handle_dirty_dirent_node(handle,
3390 retval = ext4_mark_inode_dirty(handle, ent->inode);
3393 ext4_std_error(ent->dir->i_sb, retval);
3399 static int ext4_setent(handle_t *handle, struct ext4_renament *ent,
3400 unsigned ino, unsigned file_type)
3404 BUFFER_TRACE(ent->bh, "get write access");
3405 retval = ext4_journal_get_write_access(handle, ent->bh);
3408 ent->de->inode = cpu_to_le32(ino);
3409 if (ext4_has_feature_filetype(ent->dir->i_sb))
3410 ent->de->file_type = file_type;
3411 ent->dir->i_version++;
3412 ent->dir->i_ctime = ent->dir->i_mtime =
3413 ext4_current_time(ent->dir);
3414 ext4_mark_inode_dirty(handle, ent->dir);
3415 BUFFER_TRACE(ent->bh, "call ext4_handle_dirty_metadata");
3416 if (!ent->inlined) {
3417 retval = ext4_handle_dirty_dirent_node(handle,
3419 if (unlikely(retval)) {
3420 ext4_std_error(ent->dir->i_sb, retval);
3428 static void ext4_resetent(handle_t *handle, struct ext4_renament *ent,
3429 unsigned ino, unsigned file_type)
3431 struct ext4_renament old = *ent;
3435 * old->de could have moved from under us during make indexed dir,
3436 * so the old->de may no longer valid and need to find it again
3437 * before reset old inode info.
3439 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de, NULL);
3441 retval = PTR_ERR(old.bh);
3445 ext4_std_error(old.dir->i_sb, retval);
3449 ext4_setent(handle, &old, ino, file_type);
3453 static int ext4_find_delete_entry(handle_t *handle, struct inode *dir,
3454 const struct qstr *d_name)
3456 int retval = -ENOENT;
3457 struct buffer_head *bh;
3458 struct ext4_dir_entry_2 *de;
3460 bh = ext4_find_entry(dir, d_name, &de, NULL);
3464 retval = ext4_delete_entry(handle, dir, de, bh);
3470 static void ext4_rename_delete(handle_t *handle, struct ext4_renament *ent,
3475 * ent->de could have moved from under us during htree split, so make
3476 * sure that we are deleting the right entry. We might also be pointing
3477 * to a stale entry in the unused part of ent->bh so just checking inum
3478 * and the name isn't enough.
3480 if (le32_to_cpu(ent->de->inode) != ent->inode->i_ino ||
3481 ent->de->name_len != ent->dentry->d_name.len ||
3482 strncmp(ent->de->name, ent->dentry->d_name.name,
3483 ent->de->name_len) ||
3485 retval = ext4_find_delete_entry(handle, ent->dir,
3486 &ent->dentry->d_name);
3488 retval = ext4_delete_entry(handle, ent->dir, ent->de, ent->bh);
3489 if (retval == -ENOENT) {
3490 retval = ext4_find_delete_entry(handle, ent->dir,
3491 &ent->dentry->d_name);
3496 ext4_warning_inode(ent->dir,
3497 "Deleting old file: nlink %d, error=%d",
3498 ent->dir->i_nlink, retval);
3502 static void ext4_update_dir_count(handle_t *handle, struct ext4_renament *ent)
3504 if (ent->dir_nlink_delta) {
3505 if (ent->dir_nlink_delta == -1)
3506 ext4_dec_count(handle, ent->dir);
3508 ext4_inc_count(handle, ent->dir);
3509 ext4_mark_inode_dirty(handle, ent->dir);
3513 static struct inode *ext4_whiteout_for_rename(struct ext4_renament *ent,
3514 int credits, handle_t **h)
3521 * for inode block, sb block, group summaries,
3524 credits += (EXT4_MAXQUOTAS_TRANS_BLOCKS(ent->dir->i_sb) +
3525 EXT4_XATTR_TRANS_BLOCKS + 4);
3527 wh = ext4_new_inode_start_handle(ent->dir, S_IFCHR | WHITEOUT_MODE,
3528 &ent->dentry->d_name, 0, NULL,
3529 EXT4_HT_DIR, credits);
3531 handle = ext4_journal_current_handle();
3534 ext4_journal_stop(handle);
3535 if (PTR_ERR(wh) == -ENOSPC &&
3536 ext4_should_retry_alloc(ent->dir->i_sb, &retries))
3540 init_special_inode(wh, wh->i_mode, WHITEOUT_DEV);
3541 wh->i_op = &ext4_special_inode_operations;
3547 * Anybody can rename anything with this: the permission checks are left to the
3548 * higher-level routines.
3550 * n.b. old_{dentry,inode) refers to the source dentry/inode
3551 * while new_{dentry,inode) refers to the destination dentry/inode
3552 * This comes from rename(const char *oldpath, const char *newpath)
3554 static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
3555 struct inode *new_dir, struct dentry *new_dentry,
3558 handle_t *handle = NULL;
3559 struct ext4_renament old = {
3561 .dentry = old_dentry,
3562 .inode = d_inode(old_dentry),
3564 struct ext4_renament new = {
3566 .dentry = new_dentry,
3567 .inode = d_inode(new_dentry),
3571 struct inode *whiteout = NULL;
3575 if (new.inode && new.inode->i_nlink == 0) {
3576 EXT4_ERROR_INODE(new.inode,
3577 "target of rename is already freed");
3578 return -EFSCORRUPTED;
3581 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT)) &&
3582 (!projid_eq(EXT4_I(new_dir)->i_projid,
3583 EXT4_I(old_dentry->d_inode)->i_projid)))
3586 if ((ext4_encrypted_inode(old_dir) &&
3587 !fscrypt_has_encryption_key(old_dir)) ||
3588 (ext4_encrypted_inode(new_dir) &&
3589 !fscrypt_has_encryption_key(new_dir)))
3592 retval = dquot_initialize(old.dir);
3595 retval = dquot_initialize(new.dir);
3599 /* Initialize quotas before so that eventual writes go
3600 * in separate transaction */
3602 retval = dquot_initialize(new.inode);
3607 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de, NULL);
3609 return PTR_ERR(old.bh);
3611 * Check for inode number is _not_ due to possible IO errors.
3612 * We might rmdir the source, keep it as pwd of some process
3613 * and merrily kill the link to whatever was created under the
3614 * same name. Goodbye sticky bit ;-<
3617 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3620 if ((old.dir != new.dir) &&
3621 ext4_encrypted_inode(new.dir) &&
3622 !fscrypt_has_permitted_context(new.dir, old.inode)) {
3627 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3628 &new.de, &new.inlined);
3629 if (IS_ERR(new.bh)) {
3630 retval = PTR_ERR(new.bh);
3640 if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC))
3641 ext4_alloc_da_blocks(old.inode);
3643 credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3644 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
3645 if (!(flags & RENAME_WHITEOUT)) {
3646 handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits);
3647 if (IS_ERR(handle)) {
3648 retval = PTR_ERR(handle);
3652 whiteout = ext4_whiteout_for_rename(&old, credits, &handle);
3653 if (IS_ERR(whiteout)) {
3654 retval = PTR_ERR(whiteout);
3659 old_file_type = old.de->file_type;
3660 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3661 ext4_handle_sync(handle);
3663 if (S_ISDIR(old.inode->i_mode)) {
3665 retval = -ENOTEMPTY;
3666 if (!ext4_empty_dir(new.inode))
3670 if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir))
3673 retval = ext4_rename_dir_prepare(handle, &old);
3678 * If we're renaming a file within an inline_data dir and adding or
3679 * setting the new dirent causes a conversion from inline_data to
3680 * extents/blockmap, we need to force the dirent delete code to
3681 * re-read the directory, or else we end up trying to delete a dirent
3682 * from what is now the extent tree root (or a block map).
3684 force_reread = (new.dir->i_ino == old.dir->i_ino &&
3685 ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA));
3689 * Do this before adding a new entry, so the old entry is sure
3690 * to be still pointing to the valid old entry.
3692 retval = ext4_setent(handle, &old, whiteout->i_ino,
3696 ext4_mark_inode_dirty(handle, whiteout);
3699 retval = ext4_add_entry(handle, new.dentry, old.inode);
3703 retval = ext4_setent(handle, &new,
3704 old.inode->i_ino, old_file_type);
3709 force_reread = !ext4_test_inode_flag(new.dir,
3710 EXT4_INODE_INLINE_DATA);
3713 * Like most other Unix systems, set the ctime for inodes on a
3716 old.inode->i_ctime = ext4_current_time(old.inode);
3717 ext4_mark_inode_dirty(handle, old.inode);
3723 ext4_rename_delete(handle, &old, force_reread);
3727 ext4_dec_count(handle, new.inode);
3728 new.inode->i_ctime = ext4_current_time(new.inode);
3730 old.dir->i_ctime = old.dir->i_mtime = ext4_current_time(old.dir);
3731 ext4_update_dx_flag(old.dir);
3733 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3737 ext4_dec_count(handle, old.dir);
3739 /* checked ext4_empty_dir above, can't have another
3740 * parent, ext4_dec_count() won't work for many-linked
3742 clear_nlink(new.inode);
3744 ext4_inc_count(handle, new.dir);
3745 ext4_update_dx_flag(new.dir);
3746 ext4_mark_inode_dirty(handle, new.dir);
3749 ext4_mark_inode_dirty(handle, old.dir);
3751 ext4_mark_inode_dirty(handle, new.inode);
3752 if (!new.inode->i_nlink)
3753 ext4_orphan_add(handle, new.inode);
3760 ext4_resetent(handle, &old,
3761 old.inode->i_ino, old_file_type);
3762 drop_nlink(whiteout);
3763 ext4_orphan_add(handle, whiteout);
3765 unlock_new_inode(whiteout);
3766 ext4_journal_stop(handle);
3769 ext4_journal_stop(handle);
3778 static int ext4_cross_rename(struct inode *old_dir, struct dentry *old_dentry,
3779 struct inode *new_dir, struct dentry *new_dentry)
3781 handle_t *handle = NULL;
3782 struct ext4_renament old = {
3784 .dentry = old_dentry,
3785 .inode = d_inode(old_dentry),
3787 struct ext4_renament new = {
3789 .dentry = new_dentry,
3790 .inode = d_inode(new_dentry),
3795 if ((ext4_encrypted_inode(old_dir) &&
3796 !fscrypt_has_encryption_key(old_dir)) ||
3797 (ext4_encrypted_inode(new_dir) &&
3798 !fscrypt_has_encryption_key(new_dir)))
3801 if ((ext4_encrypted_inode(old_dir) ||
3802 ext4_encrypted_inode(new_dir)) &&
3803 (old_dir != new_dir) &&
3804 (!fscrypt_has_permitted_context(new_dir, old.inode) ||
3805 !fscrypt_has_permitted_context(old_dir, new.inode)))
3808 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT) &&
3809 !projid_eq(EXT4_I(new_dir)->i_projid,
3810 EXT4_I(old_dentry->d_inode)->i_projid)) ||
3811 (ext4_test_inode_flag(old_dir, EXT4_INODE_PROJINHERIT) &&
3812 !projid_eq(EXT4_I(old_dir)->i_projid,
3813 EXT4_I(new_dentry->d_inode)->i_projid)))
3816 retval = dquot_initialize(old.dir);
3819 retval = dquot_initialize(new.dir);
3823 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name,
3824 &old.de, &old.inlined);
3826 return PTR_ERR(old.bh);
3828 * Check for inode number is _not_ due to possible IO errors.
3829 * We might rmdir the source, keep it as pwd of some process
3830 * and merrily kill the link to whatever was created under the
3831 * same name. Goodbye sticky bit ;-<
3834 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3837 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3838 &new.de, &new.inlined);
3839 if (IS_ERR(new.bh)) {
3840 retval = PTR_ERR(new.bh);
3845 /* RENAME_EXCHANGE case: old *and* new must both exist */
3846 if (!new.bh || le32_to_cpu(new.de->inode) != new.inode->i_ino)
3849 handle = ext4_journal_start(old.dir, EXT4_HT_DIR,
3850 (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3851 2 * EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2));
3852 if (IS_ERR(handle)) {
3853 retval = PTR_ERR(handle);
3858 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3859 ext4_handle_sync(handle);
3861 if (S_ISDIR(old.inode->i_mode)) {
3863 retval = ext4_rename_dir_prepare(handle, &old);
3867 if (S_ISDIR(new.inode->i_mode)) {
3869 retval = ext4_rename_dir_prepare(handle, &new);
3875 * Other than the special case of overwriting a directory, parents'
3876 * nlink only needs to be modified if this is a cross directory rename.
3878 if (old.dir != new.dir && old.is_dir != new.is_dir) {
3879 old.dir_nlink_delta = old.is_dir ? -1 : 1;
3880 new.dir_nlink_delta = -old.dir_nlink_delta;
3882 if ((old.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(old.dir)) ||
3883 (new.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(new.dir)))
3887 new_file_type = new.de->file_type;
3888 retval = ext4_setent(handle, &new, old.inode->i_ino, old.de->file_type);
3892 retval = ext4_setent(handle, &old, new.inode->i_ino, new_file_type);
3897 * Like most other Unix systems, set the ctime for inodes on a
3900 old.inode->i_ctime = ext4_current_time(old.inode);
3901 new.inode->i_ctime = ext4_current_time(new.inode);
3902 ext4_mark_inode_dirty(handle, old.inode);
3903 ext4_mark_inode_dirty(handle, new.inode);
3906 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3911 retval = ext4_rename_dir_finish(handle, &new, old.dir->i_ino);
3915 ext4_update_dir_count(handle, &old);
3916 ext4_update_dir_count(handle, &new);
3925 ext4_journal_stop(handle);
3929 static int ext4_rename2(struct inode *old_dir, struct dentry *old_dentry,
3930 struct inode *new_dir, struct dentry *new_dentry,
3933 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
3936 if (flags & RENAME_EXCHANGE) {
3937 return ext4_cross_rename(old_dir, old_dentry,
3938 new_dir, new_dentry);
3941 return ext4_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
3945 * directories can handle most operations...
3947 const struct inode_operations ext4_dir_inode_operations = {
3948 .create = ext4_create,
3949 .lookup = ext4_lookup,
3951 .unlink = ext4_unlink,
3952 .symlink = ext4_symlink,
3953 .mkdir = ext4_mkdir,
3954 .rmdir = ext4_rmdir,
3955 .mknod = ext4_mknod,
3956 .tmpfile = ext4_tmpfile,
3957 .rename = ext4_rename2,
3958 .setattr = ext4_setattr,
3959 .listxattr = ext4_listxattr,
3960 .get_acl = ext4_get_acl,
3961 .set_acl = ext4_set_acl,
3962 .fiemap = ext4_fiemap,
3965 const struct inode_operations ext4_special_inode_operations = {
3966 .setattr = ext4_setattr,
3967 .listxattr = ext4_listxattr,
3968 .get_acl = ext4_get_acl,
3969 .set_acl = ext4_set_acl,