blob: 37cc47a65cae256623a62ab75b28e9ec8bcab4a2 [file] [log] [blame]
xjb04a4022021-11-25 15:01:52 +08001// SPDX-License-Identifier: GPL-2.0
2/*
3 * linux/fs/ext4/namei.c
4 *
5 * Copyright (C) 1992, 1993, 1994, 1995
6 * Remy Card (card@masi.ibp.fr)
7 * Laboratoire MASI - Institut Blaise Pascal
8 * Universite Pierre et Marie Curie (Paris VI)
9 *
10 * from
11 *
12 * linux/fs/minix/namei.c
13 *
14 * Copyright (C) 1991, 1992 Linus Torvalds
15 *
16 * Big-endian to little-endian byte-swapping/bitmaps by
17 * David S. Miller (davem@caip.rutgers.edu), 1995
18 * Directory entry file type support and forward compatibility hooks
19 * for B-tree directories by Theodore Ts'o (tytso@mit.edu), 1998
20 * Hash Tree Directory indexing (c)
21 * Daniel Phillips, 2001
22 * Hash Tree Directory indexing porting
23 * Christopher Li, 2002
24 * Hash Tree Directory indexing cleanup
25 * Theodore Ts'o, 2002
26 */
27
28#include <linux/fs.h>
29#include <linux/pagemap.h>
30#include <linux/time.h>
31#include <linux/fcntl.h>
32#include <linux/stat.h>
33#include <linux/string.h>
34#include <linux/quotaops.h>
35#include <linux/buffer_head.h>
36#include <linux/bio.h>
37#include <linux/iversion.h>
38#include <linux/unicode.h>
39#include "ext4.h"
40#include "ext4_jbd2.h"
41
42#include "xattr.h"
43#include "acl.h"
44
45#include <trace/events/ext4.h>
46/*
47 * define how far ahead to read directories while searching them.
48 */
49#define NAMEI_RA_CHUNKS 2
50#define NAMEI_RA_BLOCKS 4
51#define NAMEI_RA_SIZE (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
52
53static struct buffer_head *ext4_append(handle_t *handle,
54 struct inode *inode,
55 ext4_lblk_t *block)
56{
57 struct buffer_head *bh;
58 int err;
59
60 if (unlikely(EXT4_SB(inode->i_sb)->s_max_dir_size_kb &&
61 ((inode->i_size >> 10) >=
62 EXT4_SB(inode->i_sb)->s_max_dir_size_kb)))
63 return ERR_PTR(-ENOSPC);
64
65 *block = inode->i_size >> inode->i_sb->s_blocksize_bits;
66
67 bh = ext4_bread(handle, inode, *block, EXT4_GET_BLOCKS_CREATE);
68 if (IS_ERR(bh))
69 return bh;
70 inode->i_size += inode->i_sb->s_blocksize;
71 EXT4_I(inode)->i_disksize = inode->i_size;
72 BUFFER_TRACE(bh, "get_write_access");
73 err = ext4_journal_get_write_access(handle, bh);
74 if (err) {
75 brelse(bh);
76 ext4_std_error(inode->i_sb, err);
77 return ERR_PTR(err);
78 }
79 return bh;
80}
81
82static int ext4_dx_csum_verify(struct inode *inode,
83 struct ext4_dir_entry *dirent);
84
85/*
86 * Hints to ext4_read_dirblock regarding whether we expect a directory
87 * block being read to be an index block, or a block containing
88 * directory entries (and if the latter, whether it was found via a
89 * logical block in an htree index block). This is used to control
90 * what sort of sanity checkinig ext4_read_dirblock() will do on the
91 * directory block read from the storage device. EITHER will means
92 * the caller doesn't know what kind of directory block will be read,
93 * so no specific verification will be done.
94 */
95typedef enum {
96 EITHER, INDEX, DIRENT, DIRENT_HTREE
97} dirblock_type_t;
98
99#define ext4_read_dirblock(inode, block, type) \
100 __ext4_read_dirblock((inode), (block), (type), __func__, __LINE__)
101
102static struct buffer_head *__ext4_read_dirblock(struct inode *inode,
103 ext4_lblk_t block,
104 dirblock_type_t type,
105 const char *func,
106 unsigned int line)
107{
108 struct buffer_head *bh;
109 struct ext4_dir_entry *dirent;
110 int is_dx_block = 0;
111
112 bh = ext4_bread(NULL, inode, block, 0);
113 if (IS_ERR(bh)) {
114 __ext4_warning(inode->i_sb, func, line,
115 "inode #%lu: lblock %lu: comm %s: "
116 "error %ld reading directory block",
117 inode->i_ino, (unsigned long)block,
118 current->comm, PTR_ERR(bh));
119
120 return bh;
121 }
122 if (!bh && (type == INDEX || type == DIRENT_HTREE)) {
123 ext4_error_inode(inode, func, line, block,
124 "Directory hole found for htree %s block",
125 (type == INDEX) ? "index" : "leaf");
126 return ERR_PTR(-EFSCORRUPTED);
127 }
128 if (!bh)
129 return NULL;
130 dirent = (struct ext4_dir_entry *) bh->b_data;
131 /* Determine whether or not we have an index block */
132 if (is_dx(inode)) {
133 if (block == 0)
134 is_dx_block = 1;
135 else if (ext4_rec_len_from_disk(dirent->rec_len,
136 inode->i_sb->s_blocksize) ==
137 inode->i_sb->s_blocksize)
138 is_dx_block = 1;
139 }
140 if (!is_dx_block && type == INDEX) {
141 ext4_error_inode(inode, func, line, block,
142 "directory leaf block found instead of index block");
143 brelse(bh);
144 return ERR_PTR(-EFSCORRUPTED);
145 }
146 if (!ext4_has_metadata_csum(inode->i_sb) ||
147 buffer_verified(bh))
148 return bh;
149
150 /*
151 * An empty leaf block can get mistaken for a index block; for
152 * this reason, we can only check the index checksum when the
153 * caller is sure it should be an index block.
154 */
155 if (is_dx_block && type == INDEX) {
156 if (ext4_dx_csum_verify(inode, dirent))
157 set_buffer_verified(bh);
158 else {
159 ext4_error_inode(inode, func, line, block,
160 "Directory index failed checksum");
161 brelse(bh);
162 return ERR_PTR(-EFSBADCRC);
163 }
164 }
165 if (!is_dx_block) {
166 if (ext4_dirent_csum_verify(inode, dirent))
167 set_buffer_verified(bh);
168 else {
169 ext4_error_inode(inode, func, line, block,
170 "Directory block failed checksum");
171 brelse(bh);
172 return ERR_PTR(-EFSBADCRC);
173 }
174 }
175 return bh;
176}
177
178#ifndef assert
179#define assert(test) J_ASSERT(test)
180#endif
181
182#ifdef DX_DEBUG
183#define dxtrace(command) command
184#else
185#define dxtrace(command)
186#endif
187
188struct fake_dirent
189{
190 __le32 inode;
191 __le16 rec_len;
192 u8 name_len;
193 u8 file_type;
194};
195
196struct dx_countlimit
197{
198 __le16 limit;
199 __le16 count;
200};
201
202struct dx_entry
203{
204 __le32 hash;
205 __le32 block;
206};
207
208/*
209 * dx_root_info is laid out so that if it should somehow get overlaid by a
210 * dirent the two low bits of the hash version will be zero. Therefore, the
211 * hash version mod 4 should never be 0. Sincerely, the paranoia department.
212 */
213
214struct dx_root
215{
216 struct fake_dirent dot;
217 char dot_name[4];
218 struct fake_dirent dotdot;
219 char dotdot_name[4];
220 struct dx_root_info
221 {
222 __le32 reserved_zero;
223 u8 hash_version;
224 u8 info_length; /* 8 */
225 u8 indirect_levels;
226 u8 unused_flags;
227 }
228 info;
229 struct dx_entry entries[0];
230};
231
232struct dx_node
233{
234 struct fake_dirent fake;
235 struct dx_entry entries[0];
236};
237
238
239struct dx_frame
240{
241 struct buffer_head *bh;
242 struct dx_entry *entries;
243 struct dx_entry *at;
244};
245
246struct dx_map_entry
247{
248 u32 hash;
249 u16 offs;
250 u16 size;
251};
252
253/*
254 * This goes at the end of each htree block.
255 */
256struct dx_tail {
257 u32 dt_reserved;
258 __le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */
259};
260
261static inline ext4_lblk_t dx_get_block(struct dx_entry *entry);
262static void dx_set_block(struct dx_entry *entry, ext4_lblk_t value);
263static inline unsigned dx_get_hash(struct dx_entry *entry);
264static void dx_set_hash(struct dx_entry *entry, unsigned value);
265static unsigned dx_get_count(struct dx_entry *entries);
266static unsigned dx_get_limit(struct dx_entry *entries);
267static void dx_set_count(struct dx_entry *entries, unsigned value);
268static void dx_set_limit(struct dx_entry *entries, unsigned value);
269static unsigned dx_root_limit(struct inode *dir, unsigned infosize);
270static unsigned dx_node_limit(struct inode *dir);
271static struct dx_frame *dx_probe(struct ext4_filename *fname,
272 struct inode *dir,
273 struct dx_hash_info *hinfo,
274 struct dx_frame *frame);
275static void dx_release(struct dx_frame *frames);
276static int dx_make_map(struct inode *dir, struct ext4_dir_entry_2 *de,
277 unsigned blocksize, struct dx_hash_info *hinfo,
278 struct dx_map_entry map[]);
279static void dx_sort_map(struct dx_map_entry *map, unsigned count);
280static struct ext4_dir_entry_2 *dx_move_dirents(char *from, char *to,
281 struct dx_map_entry *offsets, int count, unsigned blocksize);
282static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize);
283static void dx_insert_block(struct dx_frame *frame,
284 u32 hash, ext4_lblk_t block);
285static int ext4_htree_next_block(struct inode *dir, __u32 hash,
286 struct dx_frame *frame,
287 struct dx_frame *frames,
288 __u32 *start_hash);
289static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
290 struct ext4_filename *fname,
291 struct ext4_dir_entry_2 **res_dir);
292static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
293 struct inode *dir, struct inode *inode);
294
295/* checksumming functions */
296void initialize_dirent_tail(struct ext4_dir_entry_tail *t,
297 unsigned int blocksize)
298{
299 memset(t, 0, sizeof(struct ext4_dir_entry_tail));
300 t->det_rec_len = ext4_rec_len_to_disk(
301 sizeof(struct ext4_dir_entry_tail), blocksize);
302 t->det_reserved_ft = EXT4_FT_DIR_CSUM;
303}
304
305/* Walk through a dirent block to find a checksum "dirent" at the tail */
306static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode,
307 struct ext4_dir_entry *de)
308{
309 struct ext4_dir_entry_tail *t;
310
311#ifdef PARANOID
312 struct ext4_dir_entry *d, *top;
313
314 d = de;
315 top = (struct ext4_dir_entry *)(((void *)de) +
316 (EXT4_BLOCK_SIZE(inode->i_sb) -
317 sizeof(struct ext4_dir_entry_tail)));
318 while (d < top && d->rec_len)
319 d = (struct ext4_dir_entry *)(((void *)d) +
320 le16_to_cpu(d->rec_len));
321
322 if (d != top)
323 return NULL;
324
325 t = (struct ext4_dir_entry_tail *)d;
326#else
327 t = EXT4_DIRENT_TAIL(de, EXT4_BLOCK_SIZE(inode->i_sb));
328#endif
329
330 if (t->det_reserved_zero1 ||
331 le16_to_cpu(t->det_rec_len) != sizeof(struct ext4_dir_entry_tail) ||
332 t->det_reserved_zero2 ||
333 t->det_reserved_ft != EXT4_FT_DIR_CSUM)
334 return NULL;
335
336 return t;
337}
338
339static __le32 ext4_dirent_csum(struct inode *inode,
340 struct ext4_dir_entry *dirent, int size)
341{
342 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
343 struct ext4_inode_info *ei = EXT4_I(inode);
344 __u32 csum;
345
346 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
347 return cpu_to_le32(csum);
348}
349
350#define warn_no_space_for_csum(inode) \
351 __warn_no_space_for_csum((inode), __func__, __LINE__)
352
353static void __warn_no_space_for_csum(struct inode *inode, const char *func,
354 unsigned int line)
355{
356 __ext4_warning_inode(inode, func, line,
357 "No space for directory leaf checksum. Please run e2fsck -D.");
358}
359
360int ext4_dirent_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent)
361{
362 struct ext4_dir_entry_tail *t;
363
364 if (!ext4_has_metadata_csum(inode->i_sb))
365 return 1;
366
367 t = get_dirent_tail(inode, dirent);
368 if (!t) {
369 warn_no_space_for_csum(inode);
370 return 0;
371 }
372
373 if (t->det_checksum != ext4_dirent_csum(inode, dirent,
374 (void *)t - (void *)dirent))
375 return 0;
376
377 return 1;
378}
379
380static void ext4_dirent_csum_set(struct inode *inode,
381 struct ext4_dir_entry *dirent)
382{
383 struct ext4_dir_entry_tail *t;
384
385 if (!ext4_has_metadata_csum(inode->i_sb))
386 return;
387
388 t = get_dirent_tail(inode, dirent);
389 if (!t) {
390 warn_no_space_for_csum(inode);
391 return;
392 }
393
394 t->det_checksum = ext4_dirent_csum(inode, dirent,
395 (void *)t - (void *)dirent);
396}
397
398int ext4_handle_dirty_dirent_node(handle_t *handle,
399 struct inode *inode,
400 struct buffer_head *bh)
401{
402 ext4_dirent_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
403 return ext4_handle_dirty_metadata(handle, inode, bh);
404}
405
406static struct dx_countlimit *get_dx_countlimit(struct inode *inode,
407 struct ext4_dir_entry *dirent,
408 int *offset)
409{
410 struct ext4_dir_entry *dp;
411 struct dx_root_info *root;
412 int count_offset;
413
414 if (le16_to_cpu(dirent->rec_len) == EXT4_BLOCK_SIZE(inode->i_sb))
415 count_offset = 8;
416 else if (le16_to_cpu(dirent->rec_len) == 12) {
417 dp = (struct ext4_dir_entry *)(((void *)dirent) + 12);
418 if (le16_to_cpu(dp->rec_len) !=
419 EXT4_BLOCK_SIZE(inode->i_sb) - 12)
420 return NULL;
421 root = (struct dx_root_info *)(((void *)dp + 12));
422 if (root->reserved_zero ||
423 root->info_length != sizeof(struct dx_root_info))
424 return NULL;
425 count_offset = 32;
426 } else
427 return NULL;
428
429 if (offset)
430 *offset = count_offset;
431 return (struct dx_countlimit *)(((void *)dirent) + count_offset);
432}
433
434static __le32 ext4_dx_csum(struct inode *inode, struct ext4_dir_entry *dirent,
435 int count_offset, int count, struct dx_tail *t)
436{
437 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
438 struct ext4_inode_info *ei = EXT4_I(inode);
439 __u32 csum;
440 int size;
441 __u32 dummy_csum = 0;
442 int offset = offsetof(struct dx_tail, dt_checksum);
443
444 size = count_offset + (count * sizeof(struct dx_entry));
445 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
446 csum = ext4_chksum(sbi, csum, (__u8 *)t, offset);
447 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
448
449 return cpu_to_le32(csum);
450}
451
452static int ext4_dx_csum_verify(struct inode *inode,
453 struct ext4_dir_entry *dirent)
454{
455 struct dx_countlimit *c;
456 struct dx_tail *t;
457 int count_offset, limit, count;
458
459 if (!ext4_has_metadata_csum(inode->i_sb))
460 return 1;
461
462 c = get_dx_countlimit(inode, dirent, &count_offset);
463 if (!c) {
464 EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
465 return 0;
466 }
467 limit = le16_to_cpu(c->limit);
468 count = le16_to_cpu(c->count);
469 if (count_offset + (limit * sizeof(struct dx_entry)) >
470 EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
471 warn_no_space_for_csum(inode);
472 return 0;
473 }
474 t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
475
476 if (t->dt_checksum != ext4_dx_csum(inode, dirent, count_offset,
477 count, t))
478 return 0;
479 return 1;
480}
481
482static void ext4_dx_csum_set(struct inode *inode, struct ext4_dir_entry *dirent)
483{
484 struct dx_countlimit *c;
485 struct dx_tail *t;
486 int count_offset, limit, count;
487
488 if (!ext4_has_metadata_csum(inode->i_sb))
489 return;
490
491 c = get_dx_countlimit(inode, dirent, &count_offset);
492 if (!c) {
493 EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
494 return;
495 }
496 limit = le16_to_cpu(c->limit);
497 count = le16_to_cpu(c->count);
498 if (count_offset + (limit * sizeof(struct dx_entry)) >
499 EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
500 warn_no_space_for_csum(inode);
501 return;
502 }
503 t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
504
505 t->dt_checksum = ext4_dx_csum(inode, dirent, count_offset, count, t);
506}
507
508static inline int ext4_handle_dirty_dx_node(handle_t *handle,
509 struct inode *inode,
510 struct buffer_head *bh)
511{
512 ext4_dx_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
513 return ext4_handle_dirty_metadata(handle, inode, bh);
514}
515
516/*
517 * p is at least 6 bytes before the end of page
518 */
519static inline struct ext4_dir_entry_2 *
520ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize)
521{
522 return (struct ext4_dir_entry_2 *)((char *)p +
523 ext4_rec_len_from_disk(p->rec_len, blocksize));
524}
525
526/*
527 * Future: use high four bits of block for coalesce-on-delete flags
528 * Mask them off for now.
529 */
530
531static inline ext4_lblk_t dx_get_block(struct dx_entry *entry)
532{
533 return le32_to_cpu(entry->block) & 0x0fffffff;
534}
535
536static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value)
537{
538 entry->block = cpu_to_le32(value);
539}
540
541static inline unsigned dx_get_hash(struct dx_entry *entry)
542{
543 return le32_to_cpu(entry->hash);
544}
545
546static inline void dx_set_hash(struct dx_entry *entry, unsigned value)
547{
548 entry->hash = cpu_to_le32(value);
549}
550
551static inline unsigned dx_get_count(struct dx_entry *entries)
552{
553 return le16_to_cpu(((struct dx_countlimit *) entries)->count);
554}
555
556static inline unsigned dx_get_limit(struct dx_entry *entries)
557{
558 return le16_to_cpu(((struct dx_countlimit *) entries)->limit);
559}
560
561static inline void dx_set_count(struct dx_entry *entries, unsigned value)
562{
563 ((struct dx_countlimit *) entries)->count = cpu_to_le16(value);
564}
565
566static inline void dx_set_limit(struct dx_entry *entries, unsigned value)
567{
568 ((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
569}
570
571static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize)
572{
573 unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(1) -
574 EXT4_DIR_REC_LEN(2) - infosize;
575
576 if (ext4_has_metadata_csum(dir->i_sb))
577 entry_space -= sizeof(struct dx_tail);
578 return entry_space / sizeof(struct dx_entry);
579}
580
581static inline unsigned dx_node_limit(struct inode *dir)
582{
583 unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0);
584
585 if (ext4_has_metadata_csum(dir->i_sb))
586 entry_space -= sizeof(struct dx_tail);
587 return entry_space / sizeof(struct dx_entry);
588}
589
590/*
591 * Debug
592 */
593#ifdef DX_DEBUG
594static void dx_show_index(char * label, struct dx_entry *entries)
595{
596 int i, n = dx_get_count (entries);
597 printk(KERN_DEBUG "%s index", label);
598 for (i = 0; i < n; i++) {
599 printk(KERN_CONT " %x->%lu",
600 i ? dx_get_hash(entries + i) : 0,
601 (unsigned long)dx_get_block(entries + i));
602 }
603 printk(KERN_CONT "\n");
604}
605
606struct stats
607{
608 unsigned names;
609 unsigned space;
610 unsigned bcount;
611};
612
613static struct stats dx_show_leaf(struct inode *dir,
614 struct dx_hash_info *hinfo,
615 struct ext4_dir_entry_2 *de,
616 int size, int show_names)
617{
618 unsigned names = 0, space = 0;
619 char *base = (char *) de;
620 struct dx_hash_info h = *hinfo;
621
622 printk("names: ");
623 while ((char *) de < base + size)
624 {
625 if (de->inode)
626 {
627 if (show_names)
628 {
629#ifdef CONFIG_FS_ENCRYPTION
630 int len;
631 char *name;
632 struct fscrypt_str fname_crypto_str =
633 FSTR_INIT(NULL, 0);
634 int res = 0;
635
636 name = de->name;
637 len = de->name_len;
638 if (IS_ENCRYPTED(dir))
639 res = fscrypt_get_encryption_info(dir);
640 if (res) {
641 printk(KERN_WARNING "Error setting up"
642 " fname crypto: %d\n", res);
643 }
644 if (!fscrypt_has_encryption_key(dir)) {
645 /* Directory is not encrypted */
646 ext4fs_dirhash(dir, de->name,
647 de->name_len, &h);
648 printk("%*.s:(U)%x.%u ", len,
649 name, h.hash,
650 (unsigned) ((char *) de
651 - base));
652 } else {
653 struct fscrypt_str de_name =
654 FSTR_INIT(name, len);
655
656 /* Directory is encrypted */
657 res = fscrypt_fname_alloc_buffer(
658 dir, len,
659 &fname_crypto_str);
660 if (res)
661 printk(KERN_WARNING "Error "
662 "allocating crypto "
663 "buffer--skipping "
664 "crypto\n");
665 res = fscrypt_fname_disk_to_usr(dir,
666 0, 0, &de_name,
667 &fname_crypto_str);
668 if (res) {
669 printk(KERN_WARNING "Error "
670 "converting filename "
671 "from disk to usr"
672 "\n");
673 name = "??";
674 len = 2;
675 } else {
676 name = fname_crypto_str.name;
677 len = fname_crypto_str.len;
678 }
679 ext4fs_dirhash(dir, de->name,
680 de->name_len, &h);
681 printk("%*.s:(E)%x.%u ", len, name,
682 h.hash, (unsigned) ((char *) de
683 - base));
684 fscrypt_fname_free_buffer(
685 &fname_crypto_str);
686 }
687#else
688 int len = de->name_len;
689 char *name = de->name;
690 ext4fs_dirhash(dir, de->name, de->name_len, &h);
691 printk("%*.s:%x.%u ", len, name, h.hash,
692 (unsigned) ((char *) de - base));
693#endif
694 }
695 space += EXT4_DIR_REC_LEN(de->name_len);
696 names++;
697 }
698 de = ext4_next_entry(de, size);
699 }
700 printk(KERN_CONT "(%i)\n", names);
701 return (struct stats) { names, space, 1 };
702}
703
704struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir,
705 struct dx_entry *entries, int levels)
706{
707 unsigned blocksize = dir->i_sb->s_blocksize;
708 unsigned count = dx_get_count(entries), names = 0, space = 0, i;
709 unsigned bcount = 0;
710 struct buffer_head *bh;
711 printk("%i indexed blocks...\n", count);
712 for (i = 0; i < count; i++, entries++)
713 {
714 ext4_lblk_t block = dx_get_block(entries);
715 ext4_lblk_t hash = i ? dx_get_hash(entries): 0;
716 u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash;
717 struct stats stats;
718 printk("%s%3u:%03u hash %8x/%8x ",levels?"":" ", i, block, hash, range);
719 bh = ext4_bread(NULL,dir, block, 0);
720 if (!bh || IS_ERR(bh))
721 continue;
722 stats = levels?
723 dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1):
724 dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *)
725 bh->b_data, blocksize, 0);
726 names += stats.names;
727 space += stats.space;
728 bcount += stats.bcount;
729 brelse(bh);
730 }
731 if (bcount)
732 printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n",
733 levels ? "" : " ", names, space/bcount,
734 (space/bcount)*100/blocksize);
735 return (struct stats) { names, space, bcount};
736}
737#endif /* DX_DEBUG */
738
739/*
740 * Probe for a directory leaf block to search.
741 *
742 * dx_probe can return ERR_BAD_DX_DIR, which means there was a format
743 * error in the directory index, and the caller should fall back to
744 * searching the directory normally. The callers of dx_probe **MUST**
745 * check for this error code, and make sure it never gets reflected
746 * back to userspace.
747 */
748static struct dx_frame *
749dx_probe(struct ext4_filename *fname, struct inode *dir,
750 struct dx_hash_info *hinfo, struct dx_frame *frame_in)
751{
752 unsigned count, indirect;
753 struct dx_entry *at, *entries, *p, *q, *m;
754 struct dx_root *root;
755 struct dx_frame *frame = frame_in;
756 struct dx_frame *ret_err = ERR_PTR(ERR_BAD_DX_DIR);
757 u32 hash;
758
759 memset(frame_in, 0, EXT4_HTREE_LEVEL * sizeof(frame_in[0]));
760 frame->bh = ext4_read_dirblock(dir, 0, INDEX);
761 if (IS_ERR(frame->bh))
762 return (struct dx_frame *) frame->bh;
763
764 root = (struct dx_root *) frame->bh->b_data;
765 if (root->info.hash_version != DX_HASH_TEA &&
766 root->info.hash_version != DX_HASH_HALF_MD4 &&
767 root->info.hash_version != DX_HASH_LEGACY) {
768 ext4_warning_inode(dir, "Unrecognised inode hash code %u",
769 root->info.hash_version);
770 goto fail;
771 }
772 if (fname)
773 hinfo = &fname->hinfo;
774 hinfo->hash_version = root->info.hash_version;
775 if (hinfo->hash_version <= DX_HASH_TEA)
776 hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
777 hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed;
778 if (fname && fname_name(fname))
779 ext4fs_dirhash(dir, fname_name(fname), fname_len(fname), hinfo);
780 hash = hinfo->hash;
781
782 if (root->info.unused_flags & 1) {
783 ext4_warning_inode(dir, "Unimplemented hash flags: %#06x",
784 root->info.unused_flags);
785 goto fail;
786 }
787
788 indirect = root->info.indirect_levels;
789 if (indirect >= ext4_dir_htree_level(dir->i_sb)) {
790 ext4_warning(dir->i_sb,
791 "Directory (ino: %lu) htree depth %#06x exceed"
792 "supported value", dir->i_ino,
793 ext4_dir_htree_level(dir->i_sb));
794 if (ext4_dir_htree_level(dir->i_sb) < EXT4_HTREE_LEVEL) {
795 ext4_warning(dir->i_sb, "Enable large directory "
796 "feature to access it");
797 }
798 goto fail;
799 }
800
801 entries = (struct dx_entry *)(((char *)&root->info) +
802 root->info.info_length);
803
804 if (dx_get_limit(entries) != dx_root_limit(dir,
805 root->info.info_length)) {
806 ext4_warning_inode(dir, "dx entry: limit %u != root limit %u",
807 dx_get_limit(entries),
808 dx_root_limit(dir, root->info.info_length));
809 goto fail;
810 }
811
812 dxtrace(printk("Look up %x", hash));
813 while (1) {
814 count = dx_get_count(entries);
815 if (!count || count > dx_get_limit(entries)) {
816 ext4_warning_inode(dir,
817 "dx entry: count %u beyond limit %u",
818 count, dx_get_limit(entries));
819 goto fail;
820 }
821
822 p = entries + 1;
823 q = entries + count - 1;
824 while (p <= q) {
825 m = p + (q - p) / 2;
826 dxtrace(printk(KERN_CONT "."));
827 if (dx_get_hash(m) > hash)
828 q = m - 1;
829 else
830 p = m + 1;
831 }
832
833 if (0) { // linear search cross check
834 unsigned n = count - 1;
835 at = entries;
836 while (n--)
837 {
838 dxtrace(printk(KERN_CONT ","));
839 if (dx_get_hash(++at) > hash)
840 {
841 at--;
842 break;
843 }
844 }
845 assert (at == p - 1);
846 }
847
848 at = p - 1;
849 dxtrace(printk(KERN_CONT " %x->%u\n",
850 at == entries ? 0 : dx_get_hash(at),
851 dx_get_block(at)));
852 frame->entries = entries;
853 frame->at = at;
854 if (!indirect--)
855 return frame;
856 frame++;
857 frame->bh = ext4_read_dirblock(dir, dx_get_block(at), INDEX);
858 if (IS_ERR(frame->bh)) {
859 ret_err = (struct dx_frame *) frame->bh;
860 frame->bh = NULL;
861 goto fail;
862 }
863 entries = ((struct dx_node *) frame->bh->b_data)->entries;
864
865 if (dx_get_limit(entries) != dx_node_limit(dir)) {
866 ext4_warning_inode(dir,
867 "dx entry: limit %u != node limit %u",
868 dx_get_limit(entries), dx_node_limit(dir));
869 goto fail;
870 }
871 }
872fail:
873 while (frame >= frame_in) {
874 brelse(frame->bh);
875 frame--;
876 }
877
878 if (ret_err == ERR_PTR(ERR_BAD_DX_DIR))
879 ext4_warning_inode(dir,
880 "Corrupt directory, running e2fsck is recommended");
881 return ret_err;
882}
883
884static void dx_release(struct dx_frame *frames)
885{
886 struct dx_root_info *info;
887 int i;
888 unsigned int indirect_levels;
889
890 if (frames[0].bh == NULL)
891 return;
892
893 info = &((struct dx_root *)frames[0].bh->b_data)->info;
894 /* save local copy, "info" may be freed after brelse() */
895 indirect_levels = info->indirect_levels;
896 for (i = 0; i <= indirect_levels; i++) {
897 if (frames[i].bh == NULL)
898 break;
899 brelse(frames[i].bh);
900 frames[i].bh = NULL;
901 }
902}
903
904/*
905 * This function increments the frame pointer to search the next leaf
906 * block, and reads in the necessary intervening nodes if the search
907 * should be necessary. Whether or not the search is necessary is
908 * controlled by the hash parameter. If the hash value is even, then
909 * the search is only continued if the next block starts with that
910 * hash value. This is used if we are searching for a specific file.
911 *
912 * If the hash value is HASH_NB_ALWAYS, then always go to the next block.
913 *
914 * This function returns 1 if the caller should continue to search,
915 * or 0 if it should not. If there is an error reading one of the
916 * index blocks, it will a negative error code.
917 *
918 * If start_hash is non-null, it will be filled in with the starting
919 * hash of the next page.
920 */
921static int ext4_htree_next_block(struct inode *dir, __u32 hash,
922 struct dx_frame *frame,
923 struct dx_frame *frames,
924 __u32 *start_hash)
925{
926 struct dx_frame *p;
927 struct buffer_head *bh;
928 int num_frames = 0;
929 __u32 bhash;
930
931 p = frame;
932 /*
933 * Find the next leaf page by incrementing the frame pointer.
934 * If we run out of entries in the interior node, loop around and
935 * increment pointer in the parent node. When we break out of
936 * this loop, num_frames indicates the number of interior
937 * nodes need to be read.
938 */
939 while (1) {
940 if (++(p->at) < p->entries + dx_get_count(p->entries))
941 break;
942 if (p == frames)
943 return 0;
944 num_frames++;
945 p--;
946 }
947
948 /*
949 * If the hash is 1, then continue only if the next page has a
950 * continuation hash of any value. This is used for readdir
951 * handling. Otherwise, check to see if the hash matches the
952 * desired contiuation hash. If it doesn't, return since
953 * there's no point to read in the successive index pages.
954 */
955 bhash = dx_get_hash(p->at);
956 if (start_hash)
957 *start_hash = bhash;
958 if ((hash & 1) == 0) {
959 if ((bhash & ~1) != hash)
960 return 0;
961 }
962 /*
963 * If the hash is HASH_NB_ALWAYS, we always go to the next
964 * block so no check is necessary
965 */
966 while (num_frames--) {
967 bh = ext4_read_dirblock(dir, dx_get_block(p->at), INDEX);
968 if (IS_ERR(bh))
969 return PTR_ERR(bh);
970 p++;
971 brelse(p->bh);
972 p->bh = bh;
973 p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
974 }
975 return 1;
976}
977
978
979/*
980 * This function fills a red-black tree with information from a
981 * directory block. It returns the number directory entries loaded
982 * into the tree. If there is an error it is returned in err.
983 */
984static int htree_dirblock_to_tree(struct file *dir_file,
985 struct inode *dir, ext4_lblk_t block,
986 struct dx_hash_info *hinfo,
987 __u32 start_hash, __u32 start_minor_hash)
988{
989 struct buffer_head *bh;
990 struct ext4_dir_entry_2 *de, *top;
991 int err = 0, count = 0;
992 struct fscrypt_str fname_crypto_str = FSTR_INIT(NULL, 0), tmp_str;
993
994 dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n",
995 (unsigned long)block));
996 bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
997 if (IS_ERR(bh))
998 return PTR_ERR(bh);
999
1000 de = (struct ext4_dir_entry_2 *) bh->b_data;
1001 top = (struct ext4_dir_entry_2 *) ((char *) de +
1002 dir->i_sb->s_blocksize -
1003 EXT4_DIR_REC_LEN(0));
1004#ifdef CONFIG_FS_ENCRYPTION
1005 /* Check if the directory is encrypted */
1006 if (IS_ENCRYPTED(dir)) {
1007 err = fscrypt_get_encryption_info(dir);
1008 if (err < 0) {
1009 brelse(bh);
1010 return err;
1011 }
1012 err = fscrypt_fname_alloc_buffer(dir, EXT4_NAME_LEN,
1013 &fname_crypto_str);
1014 if (err < 0) {
1015 brelse(bh);
1016 return err;
1017 }
1018 }
1019#endif
1020 for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) {
1021 if (ext4_check_dir_entry(dir, NULL, de, bh,
1022 bh->b_data, bh->b_size,
1023 (block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb))
1024 + ((char *)de - bh->b_data))) {
1025 /* silently ignore the rest of the block */
1026 break;
1027 }
1028 ext4fs_dirhash(dir, de->name, de->name_len, hinfo);
1029 if ((hinfo->hash < start_hash) ||
1030 ((hinfo->hash == start_hash) &&
1031 (hinfo->minor_hash < start_minor_hash)))
1032 continue;
1033 if (de->inode == 0)
1034 continue;
1035 if (!IS_ENCRYPTED(dir)) {
1036 tmp_str.name = de->name;
1037 tmp_str.len = de->name_len;
1038 err = ext4_htree_store_dirent(dir_file,
1039 hinfo->hash, hinfo->minor_hash, de,
1040 &tmp_str);
1041 } else {
1042 int save_len = fname_crypto_str.len;
1043 struct fscrypt_str de_name = FSTR_INIT(de->name,
1044 de->name_len);
1045
1046 /* Directory is encrypted */
1047 err = fscrypt_fname_disk_to_usr(dir, hinfo->hash,
1048 hinfo->minor_hash, &de_name,
1049 &fname_crypto_str);
1050 if (err) {
1051 count = err;
1052 goto errout;
1053 }
1054 err = ext4_htree_store_dirent(dir_file,
1055 hinfo->hash, hinfo->minor_hash, de,
1056 &fname_crypto_str);
1057 fname_crypto_str.len = save_len;
1058 }
1059 if (err != 0) {
1060 count = err;
1061 goto errout;
1062 }
1063 count++;
1064 }
1065errout:
1066 brelse(bh);
1067#ifdef CONFIG_FS_ENCRYPTION
1068 fscrypt_fname_free_buffer(&fname_crypto_str);
1069#endif
1070 return count;
1071}
1072
1073
1074/*
1075 * This function fills a red-black tree with information from a
1076 * directory. We start scanning the directory in hash order, starting
1077 * at start_hash and start_minor_hash.
1078 *
1079 * This function returns the number of entries inserted into the tree,
1080 * or a negative error code.
1081 */
1082int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
1083 __u32 start_minor_hash, __u32 *next_hash)
1084{
1085 struct dx_hash_info hinfo;
1086 struct ext4_dir_entry_2 *de;
1087 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1088 struct inode *dir;
1089 ext4_lblk_t block;
1090 int count = 0;
1091 int ret, err;
1092 __u32 hashval;
1093 struct fscrypt_str tmp_str;
1094
1095 dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n",
1096 start_hash, start_minor_hash));
1097 dir = file_inode(dir_file);
1098 if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) {
1099 hinfo.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
1100 if (hinfo.hash_version <= DX_HASH_TEA)
1101 hinfo.hash_version +=
1102 EXT4_SB(dir->i_sb)->s_hash_unsigned;
1103 hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
1104 if (ext4_has_inline_data(dir)) {
1105 int has_inline_data = 1;
1106 count = htree_inlinedir_to_tree(dir_file, dir, 0,
1107 &hinfo, start_hash,
1108 start_minor_hash,
1109 &has_inline_data);
1110 if (has_inline_data) {
1111 *next_hash = ~0;
1112 return count;
1113 }
1114 }
1115 count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo,
1116 start_hash, start_minor_hash);
1117 *next_hash = ~0;
1118 return count;
1119 }
1120 hinfo.hash = start_hash;
1121 hinfo.minor_hash = 0;
1122 frame = dx_probe(NULL, dir, &hinfo, frames);
1123 if (IS_ERR(frame))
1124 return PTR_ERR(frame);
1125
1126 /* Add '.' and '..' from the htree header */
1127 if (!start_hash && !start_minor_hash) {
1128 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1129 tmp_str.name = de->name;
1130 tmp_str.len = de->name_len;
1131 err = ext4_htree_store_dirent(dir_file, 0, 0,
1132 de, &tmp_str);
1133 if (err != 0)
1134 goto errout;
1135 count++;
1136 }
1137 if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) {
1138 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1139 de = ext4_next_entry(de, dir->i_sb->s_blocksize);
1140 tmp_str.name = de->name;
1141 tmp_str.len = de->name_len;
1142 err = ext4_htree_store_dirent(dir_file, 2, 0,
1143 de, &tmp_str);
1144 if (err != 0)
1145 goto errout;
1146 count++;
1147 }
1148
1149 while (1) {
1150 if (fatal_signal_pending(current)) {
1151 err = -ERESTARTSYS;
1152 goto errout;
1153 }
1154 cond_resched();
1155 block = dx_get_block(frame->at);
1156 ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
1157 start_hash, start_minor_hash);
1158 if (ret < 0) {
1159 err = ret;
1160 goto errout;
1161 }
1162 count += ret;
1163 hashval = ~0;
1164 ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS,
1165 frame, frames, &hashval);
1166 *next_hash = hashval;
1167 if (ret < 0) {
1168 err = ret;
1169 goto errout;
1170 }
1171 /*
1172 * Stop if: (a) there are no more entries, or
1173 * (b) we have inserted at least one entry and the
1174 * next hash value is not a continuation
1175 */
1176 if ((ret == 0) ||
1177 (count && ((hashval & 1) == 0)))
1178 break;
1179 }
1180 dx_release(frames);
1181 dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, "
1182 "next hash: %x\n", count, *next_hash));
1183 return count;
1184errout:
1185 dx_release(frames);
1186 return (err);
1187}
1188
1189static inline int search_dirblock(struct buffer_head *bh,
1190 struct inode *dir,
1191 struct ext4_filename *fname,
1192 unsigned int offset,
1193 struct ext4_dir_entry_2 **res_dir)
1194{
1195 return ext4_search_dir(bh, bh->b_data, dir->i_sb->s_blocksize, dir,
1196 fname, offset, res_dir);
1197}
1198
1199/*
1200 * Directory block splitting, compacting
1201 */
1202
1203/*
1204 * Create map of hash values, offsets, and sizes, stored at end of block.
1205 * Returns number of entries mapped.
1206 */
1207static int dx_make_map(struct inode *dir, struct ext4_dir_entry_2 *de,
1208 unsigned blocksize, struct dx_hash_info *hinfo,
1209 struct dx_map_entry *map_tail)
1210{
1211 int count = 0;
1212 char *base = (char *) de;
1213 struct dx_hash_info h = *hinfo;
1214
1215 while ((char *) de < base + blocksize) {
1216 if (de->name_len && de->inode) {
1217 ext4fs_dirhash(dir, de->name, de->name_len, &h);
1218 map_tail--;
1219 map_tail->hash = h.hash;
1220 map_tail->offs = ((char *) de - base)>>2;
1221 map_tail->size = le16_to_cpu(de->rec_len);
1222 count++;
1223 cond_resched();
1224 }
1225 /* XXX: do we need to check rec_len == 0 case? -Chris */
1226 de = ext4_next_entry(de, blocksize);
1227 }
1228 return count;
1229}
1230
1231/* Sort map by hash value */
1232static void dx_sort_map (struct dx_map_entry *map, unsigned count)
1233{
1234 struct dx_map_entry *p, *q, *top = map + count - 1;
1235 int more;
1236 /* Combsort until bubble sort doesn't suck */
1237 while (count > 2) {
1238 count = count*10/13;
1239 if (count - 9 < 2) /* 9, 10 -> 11 */
1240 count = 11;
1241 for (p = top, q = p - count; q >= map; p--, q--)
1242 if (p->hash < q->hash)
1243 swap(*p, *q);
1244 }
1245 /* Garden variety bubble sort */
1246 do {
1247 more = 0;
1248 q = top;
1249 while (q-- > map) {
1250 if (q[1].hash >= q[0].hash)
1251 continue;
1252 swap(*(q+1), *q);
1253 more = 1;
1254 }
1255 } while(more);
1256}
1257
1258static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block)
1259{
1260 struct dx_entry *entries = frame->entries;
1261 struct dx_entry *old = frame->at, *new = old + 1;
1262 int count = dx_get_count(entries);
1263
1264 assert(count < dx_get_limit(entries));
1265 assert(old < entries + count);
1266 memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
1267 dx_set_hash(new, hash);
1268 dx_set_block(new, block);
1269 dx_set_count(entries, count + 1);
1270}
1271
1272#ifdef CONFIG_UNICODE
1273/*
1274 * Test whether a case-insensitive directory entry matches the filename
1275 * being searched for. If quick is set, assume the name being looked up
1276 * is already in the casefolded form.
1277 *
1278 * Returns: 0 if the directory entry matches, more than 0 if it
1279 * doesn't match or less than zero on error.
1280 */
1281int ext4_ci_compare(const struct inode *parent, const struct qstr *name,
1282 const struct qstr *entry, bool quick)
1283{
1284 const struct ext4_sb_info *sbi = EXT4_SB(parent->i_sb);
1285 const struct unicode_map *um = sbi->s_encoding;
1286 int ret;
1287
1288 if (quick)
1289 ret = utf8_strncasecmp_folded(um, name, entry);
1290 else
1291 ret = utf8_strncasecmp(um, name, entry);
1292
1293 if (ret < 0) {
1294 /* Handle invalid character sequence as either an error
1295 * or as an opaque byte sequence.
1296 */
1297 if (ext4_has_strict_mode(sbi))
1298 return -EINVAL;
1299
1300 if (name->len != entry->len)
1301 return 1;
1302
1303 return !!memcmp(name->name, entry->name, name->len);
1304 }
1305
1306 return ret;
1307}
1308
1309void ext4_fname_setup_ci_filename(struct inode *dir, const struct qstr *iname,
1310 struct fscrypt_str *cf_name)
1311{
1312 int len;
1313
1314 if (!IS_CASEFOLDED(dir) || !EXT4_SB(dir->i_sb)->s_encoding) {
1315 cf_name->name = NULL;
1316 return;
1317 }
1318
1319 cf_name->name = kmalloc(EXT4_NAME_LEN, GFP_NOFS);
1320 if (!cf_name->name)
1321 return;
1322
1323 len = utf8_casefold(EXT4_SB(dir->i_sb)->s_encoding,
1324 iname, cf_name->name,
1325 EXT4_NAME_LEN);
1326 if (len <= 0) {
1327 kfree(cf_name->name);
1328 cf_name->name = NULL;
1329 return;
1330 }
1331 cf_name->len = (unsigned) len;
1332
1333}
1334#endif
1335
1336/*
1337 * Test whether a directory entry matches the filename being searched for.
1338 *
1339 * Return: %true if the directory entry matches, otherwise %false.
1340 */
1341static inline bool ext4_match(const struct inode *parent,
1342 const struct ext4_filename *fname,
1343 const struct ext4_dir_entry_2 *de)
1344{
1345 struct fscrypt_name f;
1346#ifdef CONFIG_UNICODE
1347 const struct qstr entry = {.name = de->name, .len = de->name_len};
1348#endif
1349
1350 if (!de->inode)
1351 return false;
1352
1353 f.usr_fname = fname->usr_fname;
1354 f.disk_name = fname->disk_name;
1355#ifdef CONFIG_FS_ENCRYPTION
1356 f.crypto_buf = fname->crypto_buf;
1357#endif
1358
1359#ifdef CONFIG_UNICODE
1360 if (EXT4_SB(parent->i_sb)->s_encoding && IS_CASEFOLDED(parent)) {
1361 if (fname->cf_name.name) {
1362 struct qstr cf = {.name = fname->cf_name.name,
1363 .len = fname->cf_name.len};
1364 return !ext4_ci_compare(parent, &cf, &entry, true);
1365 }
1366 return !ext4_ci_compare(parent, fname->usr_fname, &entry,
1367 false);
1368 }
1369#endif
1370
1371 return fscrypt_match_name(&f, de->name, de->name_len);
1372}
1373
1374/*
1375 * Returns 0 if not found, -1 on failure, and 1 on success
1376 */
1377int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size,
1378 struct inode *dir, struct ext4_filename *fname,
1379 unsigned int offset, struct ext4_dir_entry_2 **res_dir)
1380{
1381 struct ext4_dir_entry_2 * de;
1382 char * dlimit;
1383 int de_len;
1384
1385 de = (struct ext4_dir_entry_2 *)search_buf;
1386 dlimit = search_buf + buf_size;
1387 while ((char *) de < dlimit) {
1388 /* this code is executed quadratically often */
1389 /* do minimal checking `by hand' */
1390 if ((char *) de + de->name_len <= dlimit &&
1391 ext4_match(dir, fname, de)) {
1392 /* found a match - just to be sure, do
1393 * a full check */
1394 if (ext4_check_dir_entry(dir, NULL, de, bh, bh->b_data,
1395 bh->b_size, offset))
1396 return -1;
1397 *res_dir = de;
1398 return 1;
1399 }
1400 /* prevent looping on a bad block */
1401 de_len = ext4_rec_len_from_disk(de->rec_len,
1402 dir->i_sb->s_blocksize);
1403 if (de_len <= 0)
1404 return -1;
1405 offset += de_len;
1406 de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
1407 }
1408 return 0;
1409}
1410
1411static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block,
1412 struct ext4_dir_entry *de)
1413{
1414 struct super_block *sb = dir->i_sb;
1415
1416 if (!is_dx(dir))
1417 return 0;
1418 if (block == 0)
1419 return 1;
1420 if (de->inode == 0 &&
1421 ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) ==
1422 sb->s_blocksize)
1423 return 1;
1424 return 0;
1425}
1426
1427/*
1428 * __ext4_find_entry()
1429 *
1430 * finds an entry in the specified directory with the wanted name. It
1431 * returns the cache buffer in which the entry was found, and the entry
1432 * itself (as a parameter - res_dir). It does NOT read the inode of the
1433 * entry - you'll have to do that yourself if you want to.
1434 *
1435 * The returned buffer_head has ->b_count elevated. The caller is expected
1436 * to brelse() it when appropriate.
1437 */
1438static struct buffer_head *__ext4_find_entry(struct inode *dir,
1439 struct ext4_filename *fname,
1440 struct ext4_dir_entry_2 **res_dir,
1441 int *inlined)
1442{
1443 struct super_block *sb;
1444 struct buffer_head *bh_use[NAMEI_RA_SIZE];
1445 struct buffer_head *bh, *ret = NULL;
1446 ext4_lblk_t start, block;
1447 const u8 *name = fname->usr_fname->name;
1448 size_t ra_max = 0; /* Number of bh's in the readahead
1449 buffer, bh_use[] */
1450 size_t ra_ptr = 0; /* Current index into readahead
1451 buffer */
1452 ext4_lblk_t nblocks;
1453 int i, namelen, retval;
1454
1455 *res_dir = NULL;
1456 sb = dir->i_sb;
1457 namelen = fname->usr_fname->len;
1458 if (namelen > EXT4_NAME_LEN)
1459 return NULL;
1460
1461 if (ext4_has_inline_data(dir)) {
1462 int has_inline_data = 1;
1463 ret = ext4_find_inline_entry(dir, fname, res_dir,
1464 &has_inline_data);
1465 if (has_inline_data) {
1466 if (inlined)
1467 *inlined = 1;
1468 goto cleanup_and_exit;
1469 }
1470 }
1471
1472 if ((namelen <= 2) && (name[0] == '.') &&
1473 (name[1] == '.' || name[1] == '\0')) {
1474 /*
1475 * "." or ".." will only be in the first block
1476 * NFS may look up ".."; "." should be handled by the VFS
1477 */
1478 block = start = 0;
1479 nblocks = 1;
1480 goto restart;
1481 }
1482 if (is_dx(dir)) {
1483 ret = ext4_dx_find_entry(dir, fname, res_dir);
1484 /*
1485 * On success, or if the error was file not found,
1486 * return. Otherwise, fall back to doing a search the
1487 * old fashioned way.
1488 */
1489 if (!IS_ERR(ret) || PTR_ERR(ret) != ERR_BAD_DX_DIR)
1490 goto cleanup_and_exit;
1491 dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
1492 "falling back\n"));
1493 ret = NULL;
1494 }
1495 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1496 if (!nblocks) {
1497 ret = NULL;
1498 goto cleanup_and_exit;
1499 }
1500 start = EXT4_I(dir)->i_dir_start_lookup;
1501 if (start >= nblocks)
1502 start = 0;
1503 block = start;
1504restart:
1505 do {
1506 /*
1507 * We deal with the read-ahead logic here.
1508 */
1509 if (ra_ptr >= ra_max) {
1510 /* Refill the readahead buffer */
1511 ra_ptr = 0;
1512 if (block < start)
1513 ra_max = start - block;
1514 else
1515 ra_max = nblocks - block;
1516 ra_max = min(ra_max, ARRAY_SIZE(bh_use));
1517 retval = ext4_bread_batch(dir, block, ra_max,
1518 false /* wait */, bh_use);
1519 if (retval) {
1520 ret = ERR_PTR(retval);
1521 ra_max = 0;
1522 goto cleanup_and_exit;
1523 }
1524 }
1525 if ((bh = bh_use[ra_ptr++]) == NULL)
1526 goto next;
1527 wait_on_buffer(bh);
1528 if (!buffer_uptodate(bh)) {
1529 EXT4_ERROR_INODE(dir, "reading directory lblock %lu",
1530 (unsigned long) block);
1531 brelse(bh);
1532 ret = ERR_PTR(-EIO);
1533 goto cleanup_and_exit;
1534 }
1535 if (!buffer_verified(bh) &&
1536 !is_dx_internal_node(dir, block,
1537 (struct ext4_dir_entry *)bh->b_data) &&
1538 !ext4_dirent_csum_verify(dir,
1539 (struct ext4_dir_entry *)bh->b_data)) {
1540 EXT4_ERROR_INODE(dir, "checksumming directory "
1541 "block %lu", (unsigned long)block);
1542 brelse(bh);
1543 ret = ERR_PTR(-EFSBADCRC);
1544 goto cleanup_and_exit;
1545 }
1546 set_buffer_verified(bh);
1547 i = search_dirblock(bh, dir, fname,
1548 block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
1549 if (i == 1) {
1550 EXT4_I(dir)->i_dir_start_lookup = block;
1551 ret = bh;
1552 goto cleanup_and_exit;
1553 } else {
1554 brelse(bh);
1555 if (i < 0)
1556 goto cleanup_and_exit;
1557 }
1558 next:
1559 if (++block >= nblocks)
1560 block = 0;
1561 } while (block != start);
1562
1563 /*
1564 * If the directory has grown while we were searching, then
1565 * search the last part of the directory before giving up.
1566 */
1567 block = nblocks;
1568 nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1569 if (block < nblocks) {
1570 start = 0;
1571 goto restart;
1572 }
1573
1574cleanup_and_exit:
1575 /* Clean up the read-ahead blocks */
1576 for (; ra_ptr < ra_max; ra_ptr++)
1577 brelse(bh_use[ra_ptr]);
1578 return ret;
1579}
1580
1581static struct buffer_head *ext4_find_entry(struct inode *dir,
1582 const struct qstr *d_name,
1583 struct ext4_dir_entry_2 **res_dir,
1584 int *inlined)
1585{
1586 int err;
1587 struct ext4_filename fname;
1588 struct buffer_head *bh;
1589
1590 err = ext4_fname_setup_filename(dir, d_name, 1, &fname);
1591 if (err == -ENOENT)
1592 return NULL;
1593 if (err)
1594 return ERR_PTR(err);
1595
1596 bh = __ext4_find_entry(dir, &fname, res_dir, inlined);
1597
1598 ext4_fname_free_filename(&fname);
1599 return bh;
1600}
1601
1602static struct buffer_head *ext4_lookup_entry(struct inode *dir,
1603 struct dentry *dentry,
1604 struct ext4_dir_entry_2 **res_dir)
1605{
1606 int err;
1607 struct ext4_filename fname;
1608 struct buffer_head *bh;
1609
1610 err = ext4_fname_prepare_lookup(dir, dentry, &fname);
1611 if (err == -ENOENT)
1612 return NULL;
1613 if (err)
1614 return ERR_PTR(err);
1615
1616 bh = __ext4_find_entry(dir, &fname, res_dir, NULL);
1617
1618 ext4_fname_free_filename(&fname);
1619 return bh;
1620}
1621
1622static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
1623 struct ext4_filename *fname,
1624 struct ext4_dir_entry_2 **res_dir)
1625{
1626 struct super_block * sb = dir->i_sb;
1627 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1628 struct buffer_head *bh;
1629 ext4_lblk_t block;
1630 int retval;
1631
1632#ifdef CONFIG_FS_ENCRYPTION
1633 *res_dir = NULL;
1634#endif
1635 frame = dx_probe(fname, dir, NULL, frames);
1636 if (IS_ERR(frame))
1637 return (struct buffer_head *) frame;
1638 do {
1639 block = dx_get_block(frame->at);
1640 bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
1641 if (IS_ERR(bh))
1642 goto errout;
1643
1644 retval = search_dirblock(bh, dir, fname,
1645 block << EXT4_BLOCK_SIZE_BITS(sb),
1646 res_dir);
1647 if (retval == 1)
1648 goto success;
1649 brelse(bh);
1650 if (retval == -1) {
1651 bh = ERR_PTR(ERR_BAD_DX_DIR);
1652 goto errout;
1653 }
1654
1655 /* Check to see if we should continue to search */
1656 retval = ext4_htree_next_block(dir, fname->hinfo.hash, frame,
1657 frames, NULL);
1658 if (retval < 0) {
1659 ext4_warning_inode(dir,
1660 "error %d reading directory index block",
1661 retval);
1662 bh = ERR_PTR(retval);
1663 goto errout;
1664 }
1665 } while (retval == 1);
1666
1667 bh = NULL;
1668errout:
1669 dxtrace(printk(KERN_DEBUG "%s not found\n", fname->usr_fname->name));
1670success:
1671 dx_release(frames);
1672 return bh;
1673}
1674
1675static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
1676{
1677 struct inode *inode;
1678 struct ext4_dir_entry_2 *de;
1679 struct buffer_head *bh;
1680
1681 if (dentry->d_name.len > EXT4_NAME_LEN)
1682 return ERR_PTR(-ENAMETOOLONG);
1683
1684 bh = ext4_lookup_entry(dir, dentry, &de);
1685 if (IS_ERR(bh))
1686 return (struct dentry *) bh;
1687 inode = NULL;
1688 if (bh) {
1689 __u32 ino = le32_to_cpu(de->inode);
1690 brelse(bh);
1691 if (!ext4_valid_inum(dir->i_sb, ino)) {
1692 EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
1693 return ERR_PTR(-EFSCORRUPTED);
1694 }
1695 if (unlikely(ino == dir->i_ino)) {
1696 EXT4_ERROR_INODE(dir, "'%pd' linked to parent dir",
1697 dentry);
1698 return ERR_PTR(-EFSCORRUPTED);
1699 }
1700 inode = ext4_iget(dir->i_sb, ino, EXT4_IGET_NORMAL);
1701 if (inode == ERR_PTR(-ESTALE)) {
1702 EXT4_ERROR_INODE(dir,
1703 "deleted inode referenced: %u",
1704 ino);
1705 return ERR_PTR(-EFSCORRUPTED);
1706 }
1707 if (!IS_ERR(inode) && IS_ENCRYPTED(dir) &&
1708 (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
1709 !fscrypt_has_permitted_context(dir, inode)) {
1710 ext4_warning(inode->i_sb,
1711 "Inconsistent encryption contexts: %lu/%lu",
1712 dir->i_ino, inode->i_ino);
1713 iput(inode);
1714 return ERR_PTR(-EPERM);
1715 }
1716 }
1717
1718#ifdef CONFIG_UNICODE
1719 if (!inode && IS_CASEFOLDED(dir)) {
1720 /* Eventually we want to call d_add_ci(dentry, NULL)
1721 * for negative dentries in the encoding case as
1722 * well. For now, prevent the negative dentry
1723 * from being cached.
1724 */
1725 return NULL;
1726 }
1727#endif
1728 return d_splice_alias(inode, dentry);
1729}
1730
1731
1732struct dentry *ext4_get_parent(struct dentry *child)
1733{
1734 __u32 ino;
1735 static const struct qstr dotdot = QSTR_INIT("..", 2);
1736 struct ext4_dir_entry_2 * de;
1737 struct buffer_head *bh;
1738
1739 bh = ext4_find_entry(d_inode(child), &dotdot, &de, NULL);
1740 if (IS_ERR(bh))
1741 return (struct dentry *) bh;
1742 if (!bh)
1743 return ERR_PTR(-ENOENT);
1744 ino = le32_to_cpu(de->inode);
1745 brelse(bh);
1746
1747 if (!ext4_valid_inum(child->d_sb, ino)) {
1748 EXT4_ERROR_INODE(d_inode(child),
1749 "bad parent inode number: %u", ino);
1750 return ERR_PTR(-EFSCORRUPTED);
1751 }
1752
1753 return d_obtain_alias(ext4_iget(child->d_sb, ino, EXT4_IGET_NORMAL));
1754}
1755
1756/*
1757 * Move count entries from end of map between two memory locations.
1758 * Returns pointer to last entry moved.
1759 */
1760static struct ext4_dir_entry_2 *
1761dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count,
1762 unsigned blocksize)
1763{
1764 unsigned rec_len = 0;
1765
1766 while (count--) {
1767 struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
1768 (from + (map->offs<<2));
1769 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1770 memcpy (to, de, rec_len);
1771 ((struct ext4_dir_entry_2 *) to)->rec_len =
1772 ext4_rec_len_to_disk(rec_len, blocksize);
1773 de->inode = 0;
1774 map++;
1775 to += rec_len;
1776 }
1777 return (struct ext4_dir_entry_2 *) (to - rec_len);
1778}
1779
1780/*
1781 * Compact each dir entry in the range to the minimal rec_len.
1782 * Returns pointer to last entry in range.
1783 */
1784static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize)
1785{
1786 struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
1787 unsigned rec_len = 0;
1788
1789 prev = to = de;
1790 while ((char*)de < base + blocksize) {
1791 next = ext4_next_entry(de, blocksize);
1792 if (de->inode && de->name_len) {
1793 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1794 if (de > to)
1795 memmove(to, de, rec_len);
1796 to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
1797 prev = to;
1798 to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
1799 }
1800 de = next;
1801 }
1802 return prev;
1803}
1804
1805/*
1806 * Split a full leaf block to make room for a new dir entry.
1807 * Allocate a new block, and move entries so that they are approx. equally full.
1808 * Returns pointer to de in block into which the new entry will be inserted.
1809 */
1810static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
1811 struct buffer_head **bh,struct dx_frame *frame,
1812 struct dx_hash_info *hinfo)
1813{
1814 unsigned blocksize = dir->i_sb->s_blocksize;
1815 unsigned count, continued;
1816 struct buffer_head *bh2;
1817 ext4_lblk_t newblock;
1818 u32 hash2;
1819 struct dx_map_entry *map;
1820 char *data1 = (*bh)->b_data, *data2;
1821 unsigned split, move, size;
1822 struct ext4_dir_entry_2 *de = NULL, *de2;
1823 struct ext4_dir_entry_tail *t;
1824 int csum_size = 0;
1825 int err = 0, i;
1826
1827 if (ext4_has_metadata_csum(dir->i_sb))
1828 csum_size = sizeof(struct ext4_dir_entry_tail);
1829
1830 bh2 = ext4_append(handle, dir, &newblock);
1831 if (IS_ERR(bh2)) {
1832 brelse(*bh);
1833 *bh = NULL;
1834 return (struct ext4_dir_entry_2 *) bh2;
1835 }
1836
1837 BUFFER_TRACE(*bh, "get_write_access");
1838 err = ext4_journal_get_write_access(handle, *bh);
1839 if (err)
1840 goto journal_error;
1841
1842 BUFFER_TRACE(frame->bh, "get_write_access");
1843 err = ext4_journal_get_write_access(handle, frame->bh);
1844 if (err)
1845 goto journal_error;
1846
1847 data2 = bh2->b_data;
1848
1849 /* create map in the end of data2 block */
1850 map = (struct dx_map_entry *) (data2 + blocksize);
1851 count = dx_make_map(dir, (struct ext4_dir_entry_2 *) data1,
1852 blocksize, hinfo, map);
1853 map -= count;
1854 dx_sort_map(map, count);
1855 /* Split the existing block in the middle, size-wise */
1856 size = 0;
1857 move = 0;
1858 for (i = count-1; i >= 0; i--) {
1859 /* is more than half of this entry in 2nd half of the block? */
1860 if (size + map[i].size/2 > blocksize/2)
1861 break;
1862 size += map[i].size;
1863 move++;
1864 }
1865 /* map index at which we will split */
1866 split = count - move;
1867 hash2 = map[split].hash;
1868 continued = hash2 == map[split - 1].hash;
1869 dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
1870 (unsigned long)dx_get_block(frame->at),
1871 hash2, split, count-split));
1872
1873 /* Fancy dance to stay within two buffers */
1874 de2 = dx_move_dirents(data1, data2, map + split, count - split,
1875 blocksize);
1876 de = dx_pack_dirents(data1, blocksize);
1877 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
1878 (char *) de,
1879 blocksize);
1880 de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
1881 (char *) de2,
1882 blocksize);
1883 if (csum_size) {
1884 t = EXT4_DIRENT_TAIL(data2, blocksize);
1885 initialize_dirent_tail(t, blocksize);
1886
1887 t = EXT4_DIRENT_TAIL(data1, blocksize);
1888 initialize_dirent_tail(t, blocksize);
1889 }
1890
1891 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,
1892 blocksize, 1));
1893 dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,
1894 blocksize, 1));
1895
1896 /* Which block gets the new entry? */
1897 if (hinfo->hash >= hash2) {
1898 swap(*bh, bh2);
1899 de = de2;
1900 }
1901 dx_insert_block(frame, hash2 + continued, newblock);
1902 err = ext4_handle_dirty_dirent_node(handle, dir, bh2);
1903 if (err)
1904 goto journal_error;
1905 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
1906 if (err)
1907 goto journal_error;
1908 brelse(bh2);
1909 dxtrace(dx_show_index("frame", frame->entries));
1910 return de;
1911
1912journal_error:
1913 brelse(*bh);
1914 brelse(bh2);
1915 *bh = NULL;
1916 ext4_std_error(dir->i_sb, err);
1917 return ERR_PTR(err);
1918}
1919
1920int ext4_find_dest_de(struct inode *dir, struct inode *inode,
1921 struct buffer_head *bh,
1922 void *buf, int buf_size,
1923 struct ext4_filename *fname,
1924 struct ext4_dir_entry_2 **dest_de)
1925{
1926 struct ext4_dir_entry_2 *de;
1927 unsigned short reclen = EXT4_DIR_REC_LEN(fname_len(fname));
1928 int nlen, rlen;
1929 unsigned int offset = 0;
1930 char *top;
1931
1932 de = (struct ext4_dir_entry_2 *)buf;
1933 top = buf + buf_size - reclen;
1934 while ((char *) de <= top) {
1935 if (ext4_check_dir_entry(dir, NULL, de, bh,
1936 buf, buf_size, offset))
1937 return -EFSCORRUPTED;
1938 if (ext4_match(dir, fname, de))
1939 return -EEXIST;
1940 nlen = EXT4_DIR_REC_LEN(de->name_len);
1941 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1942 if ((de->inode ? rlen - nlen : rlen) >= reclen)
1943 break;
1944 de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
1945 offset += rlen;
1946 }
1947 if ((char *) de > top)
1948 return -ENOSPC;
1949
1950 *dest_de = de;
1951 return 0;
1952}
1953
1954void ext4_insert_dentry(struct inode *inode,
1955 struct ext4_dir_entry_2 *de,
1956 int buf_size,
1957 struct ext4_filename *fname)
1958{
1959
1960 int nlen, rlen;
1961
1962 nlen = EXT4_DIR_REC_LEN(de->name_len);
1963 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1964 if (de->inode) {
1965 struct ext4_dir_entry_2 *de1 =
1966 (struct ext4_dir_entry_2 *)((char *)de + nlen);
1967 de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size);
1968 de->rec_len = ext4_rec_len_to_disk(nlen, buf_size);
1969 de = de1;
1970 }
1971 de->file_type = EXT4_FT_UNKNOWN;
1972 de->inode = cpu_to_le32(inode->i_ino);
1973 ext4_set_de_type(inode->i_sb, de, inode->i_mode);
1974 de->name_len = fname_len(fname);
1975 memcpy(de->name, fname_name(fname), fname_len(fname));
1976}
1977
1978/*
1979 * Add a new entry into a directory (leaf) block. If de is non-NULL,
1980 * it points to a directory entry which is guaranteed to be large
1981 * enough for new directory entry. If de is NULL, then
1982 * add_dirent_to_buf will attempt search the directory block for
1983 * space. It will return -ENOSPC if no space is available, and -EIO
1984 * and -EEXIST if directory entry already exists.
1985 */
1986static int add_dirent_to_buf(handle_t *handle, struct ext4_filename *fname,
1987 struct inode *dir,
1988 struct inode *inode, struct ext4_dir_entry_2 *de,
1989 struct buffer_head *bh)
1990{
1991 unsigned int blocksize = dir->i_sb->s_blocksize;
1992 int csum_size = 0;
1993 int err;
1994
1995 if (ext4_has_metadata_csum(inode->i_sb))
1996 csum_size = sizeof(struct ext4_dir_entry_tail);
1997
1998 if (!de) {
1999 err = ext4_find_dest_de(dir, inode, bh, bh->b_data,
2000 blocksize - csum_size, fname, &de);
2001 if (err)
2002 return err;
2003 }
2004 BUFFER_TRACE(bh, "get_write_access");
2005 err = ext4_journal_get_write_access(handle, bh);
2006 if (err) {
2007 ext4_std_error(dir->i_sb, err);
2008 return err;
2009 }
2010
2011 /* By now the buffer is marked for journaling */
2012 ext4_insert_dentry(inode, de, blocksize, fname);
2013
2014 /*
2015 * XXX shouldn't update any times until successful
2016 * completion of syscall, but too many callers depend
2017 * on this.
2018 *
2019 * XXX similarly, too many callers depend on
2020 * ext4_new_inode() setting the times, but error
2021 * recovery deletes the inode, so the worst that can
2022 * happen is that the times are slightly out of date
2023 * and/or different from the directory change time.
2024 */
2025 dir->i_mtime = dir->i_ctime = current_time(dir);
2026 ext4_update_dx_flag(dir);
2027 inode_inc_iversion(dir);
2028 ext4_mark_inode_dirty(handle, dir);
2029 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
2030 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
2031 if (err)
2032 ext4_std_error(dir->i_sb, err);
2033 return 0;
2034}
2035
2036/*
2037 * This converts a one block unindexed directory to a 3 block indexed
2038 * directory, and adds the dentry to the indexed directory.
2039 */
2040static int make_indexed_dir(handle_t *handle, struct ext4_filename *fname,
2041 struct inode *dir,
2042 struct inode *inode, struct buffer_head *bh)
2043{
2044 struct buffer_head *bh2;
2045 struct dx_root *root;
2046 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
2047 struct dx_entry *entries;
2048 struct ext4_dir_entry_2 *de, *de2;
2049 struct ext4_dir_entry_tail *t;
2050 char *data1, *top;
2051 unsigned len;
2052 int retval;
2053 unsigned blocksize;
2054 ext4_lblk_t block;
2055 struct fake_dirent *fde;
2056 int csum_size = 0;
2057
2058 if (ext4_has_metadata_csum(inode->i_sb))
2059 csum_size = sizeof(struct ext4_dir_entry_tail);
2060
2061 blocksize = dir->i_sb->s_blocksize;
2062 dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
2063 BUFFER_TRACE(bh, "get_write_access");
2064 retval = ext4_journal_get_write_access(handle, bh);
2065 if (retval) {
2066 ext4_std_error(dir->i_sb, retval);
2067 brelse(bh);
2068 return retval;
2069 }
2070 root = (struct dx_root *) bh->b_data;
2071
2072 /* The 0th block becomes the root, move the dirents out */
2073 fde = &root->dotdot;
2074 de = (struct ext4_dir_entry_2 *)((char *)fde +
2075 ext4_rec_len_from_disk(fde->rec_len, blocksize));
2076 if ((char *) de >= (((char *) root) + blocksize)) {
2077 EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
2078 brelse(bh);
2079 return -EFSCORRUPTED;
2080 }
2081 len = ((char *) root) + (blocksize - csum_size) - (char *) de;
2082
2083 /* Allocate new block for the 0th block's dirents */
2084 bh2 = ext4_append(handle, dir, &block);
2085 if (IS_ERR(bh2)) {
2086 brelse(bh);
2087 return PTR_ERR(bh2);
2088 }
2089 ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
2090 data1 = bh2->b_data;
2091
2092 memcpy (data1, de, len);
2093 de = (struct ext4_dir_entry_2 *) data1;
2094 top = data1 + len;
2095 while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top)
2096 de = de2;
2097 de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
2098 (char *) de,
2099 blocksize);
2100
2101 if (csum_size) {
2102 t = EXT4_DIRENT_TAIL(data1, blocksize);
2103 initialize_dirent_tail(t, blocksize);
2104 }
2105
2106 /* Initialize the root; the dot dirents already exist */
2107 de = (struct ext4_dir_entry_2 *) (&root->dotdot);
2108 de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
2109 blocksize);
2110 memset (&root->info, 0, sizeof(root->info));
2111 root->info.info_length = sizeof(root->info);
2112 root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
2113 entries = root->entries;
2114 dx_set_block(entries, 1);
2115 dx_set_count(entries, 1);
2116 dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
2117
2118 /* Initialize as for dx_probe */
2119 fname->hinfo.hash_version = root->info.hash_version;
2120 if (fname->hinfo.hash_version <= DX_HASH_TEA)
2121 fname->hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
2122 fname->hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
2123 ext4fs_dirhash(dir, fname_name(fname), fname_len(fname), &fname->hinfo);
2124
2125 memset(frames, 0, sizeof(frames));
2126 frame = frames;
2127 frame->entries = entries;
2128 frame->at = entries;
2129 frame->bh = bh;
2130
2131 retval = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2132 if (retval)
2133 goto out_frames;
2134 retval = ext4_handle_dirty_dirent_node(handle, dir, bh2);
2135 if (retval)
2136 goto out_frames;
2137
2138 de = do_split(handle,dir, &bh2, frame, &fname->hinfo);
2139 if (IS_ERR(de)) {
2140 retval = PTR_ERR(de);
2141 goto out_frames;
2142 }
2143
2144 retval = add_dirent_to_buf(handle, fname, dir, inode, de, bh2);
2145out_frames:
2146 /*
2147 * Even if the block split failed, we have to properly write
2148 * out all the changes we did so far. Otherwise we can end up
2149 * with corrupted filesystem.
2150 */
2151 if (retval)
2152 ext4_mark_inode_dirty(handle, dir);
2153 dx_release(frames);
2154 brelse(bh2);
2155 return retval;
2156}
2157
2158/*
2159 * ext4_add_entry()
2160 *
2161 * adds a file entry to the specified directory, using the same
2162 * semantics as ext4_find_entry(). It returns NULL if it failed.
2163 *
2164 * NOTE!! The inode part of 'de' is left at 0 - which means you
2165 * may not sleep between calling this and putting something into
2166 * the entry, as someone else might have used it while you slept.
2167 */
2168static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
2169 struct inode *inode)
2170{
2171 struct inode *dir = d_inode(dentry->d_parent);
2172 struct buffer_head *bh = NULL;
2173 struct ext4_dir_entry_2 *de;
2174 struct ext4_dir_entry_tail *t;
2175 struct super_block *sb;
2176 struct ext4_sb_info *sbi;
2177 struct ext4_filename fname;
2178 int retval;
2179 int dx_fallback=0;
2180 unsigned blocksize;
2181 ext4_lblk_t block, blocks;
2182 int csum_size = 0;
2183
2184 if (ext4_has_metadata_csum(inode->i_sb))
2185 csum_size = sizeof(struct ext4_dir_entry_tail);
2186
2187 sb = dir->i_sb;
2188 sbi = EXT4_SB(sb);
2189 blocksize = sb->s_blocksize;
2190 if (!dentry->d_name.len)
2191 return -EINVAL;
2192
2193#ifdef CONFIG_UNICODE
2194 if (ext4_has_strict_mode(sbi) && IS_CASEFOLDED(dir) &&
2195 sbi->s_encoding && utf8_validate(sbi->s_encoding, &dentry->d_name))
2196 return -EINVAL;
2197#endif
2198
2199 retval = ext4_fname_setup_filename(dir, &dentry->d_name, 0, &fname);
2200 if (retval)
2201 return retval;
2202
2203 if (ext4_has_inline_data(dir)) {
2204 retval = ext4_try_add_inline_entry(handle, &fname, dir, inode);
2205 if (retval < 0)
2206 goto out;
2207 if (retval == 1) {
2208 retval = 0;
2209 goto out;
2210 }
2211 }
2212
2213 if (is_dx(dir)) {
2214 retval = ext4_dx_add_entry(handle, &fname, dir, inode);
2215 if (!retval || (retval != ERR_BAD_DX_DIR))
2216 goto out;
2217 ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
2218 dx_fallback++;
2219 ext4_mark_inode_dirty(handle, dir);
2220 }
2221 blocks = dir->i_size >> sb->s_blocksize_bits;
2222 for (block = 0; block < blocks; block++) {
2223 bh = ext4_read_dirblock(dir, block, DIRENT);
2224 if (bh == NULL) {
2225 bh = ext4_bread(handle, dir, block,
2226 EXT4_GET_BLOCKS_CREATE);
2227 goto add_to_new_block;
2228 }
2229 if (IS_ERR(bh)) {
2230 retval = PTR_ERR(bh);
2231 bh = NULL;
2232 goto out;
2233 }
2234 retval = add_dirent_to_buf(handle, &fname, dir, inode,
2235 NULL, bh);
2236 if (retval != -ENOSPC)
2237 goto out;
2238
2239 if (blocks == 1 && !dx_fallback &&
2240 ext4_has_feature_dir_index(sb)) {
2241 retval = make_indexed_dir(handle, &fname, dir,
2242 inode, bh);
2243 bh = NULL; /* make_indexed_dir releases bh */
2244 goto out;
2245 }
2246 brelse(bh);
2247 }
2248 bh = ext4_append(handle, dir, &block);
2249add_to_new_block:
2250 if (IS_ERR(bh)) {
2251 retval = PTR_ERR(bh);
2252 bh = NULL;
2253 goto out;
2254 }
2255 de = (struct ext4_dir_entry_2 *) bh->b_data;
2256 de->inode = 0;
2257 de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
2258
2259 if (csum_size) {
2260 t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
2261 initialize_dirent_tail(t, blocksize);
2262 }
2263
2264 retval = add_dirent_to_buf(handle, &fname, dir, inode, de, bh);
2265out:
2266 ext4_fname_free_filename(&fname);
2267 brelse(bh);
2268 if (retval == 0)
2269 ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
2270 return retval;
2271}
2272
2273/*
2274 * Returns 0 for success, or a negative error value
2275 */
2276static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
2277 struct inode *dir, struct inode *inode)
2278{
2279 struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
2280 struct dx_entry *entries, *at;
2281 struct buffer_head *bh;
2282 struct super_block *sb = dir->i_sb;
2283 struct ext4_dir_entry_2 *de;
2284 int restart;
2285 int err;
2286
2287again:
2288 restart = 0;
2289 frame = dx_probe(fname, dir, NULL, frames);
2290 if (IS_ERR(frame))
2291 return PTR_ERR(frame);
2292 entries = frame->entries;
2293 at = frame->at;
2294 bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT_HTREE);
2295 if (IS_ERR(bh)) {
2296 err = PTR_ERR(bh);
2297 bh = NULL;
2298 goto cleanup;
2299 }
2300
2301 BUFFER_TRACE(bh, "get_write_access");
2302 err = ext4_journal_get_write_access(handle, bh);
2303 if (err)
2304 goto journal_error;
2305
2306 err = add_dirent_to_buf(handle, fname, dir, inode, NULL, bh);
2307 if (err != -ENOSPC)
2308 goto cleanup;
2309
2310 err = 0;
2311 /* Block full, should compress but for now just split */
2312 dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
2313 dx_get_count(entries), dx_get_limit(entries)));
2314 /* Need to split index? */
2315 if (dx_get_count(entries) == dx_get_limit(entries)) {
2316 ext4_lblk_t newblock;
2317 int levels = frame - frames + 1;
2318 unsigned int icount;
2319 int add_level = 1;
2320 struct dx_entry *entries2;
2321 struct dx_node *node2;
2322 struct buffer_head *bh2;
2323
2324 while (frame > frames) {
2325 if (dx_get_count((frame - 1)->entries) <
2326 dx_get_limit((frame - 1)->entries)) {
2327 add_level = 0;
2328 break;
2329 }
2330 frame--; /* split higher index block */
2331 at = frame->at;
2332 entries = frame->entries;
2333 restart = 1;
2334 }
2335 if (add_level && levels == ext4_dir_htree_level(sb)) {
2336 ext4_warning(sb, "Directory (ino: %lu) index full, "
2337 "reach max htree level :%d",
2338 dir->i_ino, levels);
2339 if (ext4_dir_htree_level(sb) < EXT4_HTREE_LEVEL) {
2340 ext4_warning(sb, "Large directory feature is "
2341 "not enabled on this "
2342 "filesystem");
2343 }
2344 err = -ENOSPC;
2345 goto cleanup;
2346 }
2347 icount = dx_get_count(entries);
2348 bh2 = ext4_append(handle, dir, &newblock);
2349 if (IS_ERR(bh2)) {
2350 err = PTR_ERR(bh2);
2351 goto cleanup;
2352 }
2353 node2 = (struct dx_node *)(bh2->b_data);
2354 entries2 = node2->entries;
2355 memset(&node2->fake, 0, sizeof(struct fake_dirent));
2356 node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
2357 sb->s_blocksize);
2358 BUFFER_TRACE(frame->bh, "get_write_access");
2359 err = ext4_journal_get_write_access(handle, frame->bh);
2360 if (err)
2361 goto journal_error;
2362 if (!add_level) {
2363 unsigned icount1 = icount/2, icount2 = icount - icount1;
2364 unsigned hash2 = dx_get_hash(entries + icount1);
2365 dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
2366 icount1, icount2));
2367
2368 BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
2369 err = ext4_journal_get_write_access(handle,
2370 (frame - 1)->bh);
2371 if (err)
2372 goto journal_error;
2373
2374 memcpy((char *) entries2, (char *) (entries + icount1),
2375 icount2 * sizeof(struct dx_entry));
2376 dx_set_count(entries, icount1);
2377 dx_set_count(entries2, icount2);
2378 dx_set_limit(entries2, dx_node_limit(dir));
2379
2380 /* Which index block gets the new entry? */
2381 if (at - entries >= icount1) {
2382 frame->at = at = at - entries - icount1 + entries2;
2383 frame->entries = entries = entries2;
2384 swap(frame->bh, bh2);
2385 }
2386 dx_insert_block((frame - 1), hash2, newblock);
2387 dxtrace(dx_show_index("node", frame->entries));
2388 dxtrace(dx_show_index("node",
2389 ((struct dx_node *) bh2->b_data)->entries));
2390 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2391 if (err)
2392 goto journal_error;
2393 brelse (bh2);
2394 err = ext4_handle_dirty_dx_node(handle, dir,
2395 (frame - 1)->bh);
2396 if (err)
2397 goto journal_error;
2398 if (restart) {
2399 err = ext4_handle_dirty_dx_node(handle, dir,
2400 frame->bh);
2401 goto journal_error;
2402 }
2403 } else {
2404 struct dx_root *dxroot;
2405 memcpy((char *) entries2, (char *) entries,
2406 icount * sizeof(struct dx_entry));
2407 dx_set_limit(entries2, dx_node_limit(dir));
2408
2409 /* Set up root */
2410 dx_set_count(entries, 1);
2411 dx_set_block(entries + 0, newblock);
2412 dxroot = (struct dx_root *)frames[0].bh->b_data;
2413 dxroot->info.indirect_levels += 1;
2414 dxtrace(printk(KERN_DEBUG
2415 "Creating %d level index...\n",
2416 dxroot->info.indirect_levels));
2417 err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2418 if (err)
2419 goto journal_error;
2420 err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2421 brelse(bh2);
2422 restart = 1;
2423 goto journal_error;
2424 }
2425 }
2426 de = do_split(handle, dir, &bh, frame, &fname->hinfo);
2427 if (IS_ERR(de)) {
2428 err = PTR_ERR(de);
2429 goto cleanup;
2430 }
2431 err = add_dirent_to_buf(handle, fname, dir, inode, de, bh);
2432 goto cleanup;
2433
2434journal_error:
2435 ext4_std_error(dir->i_sb, err); /* this is a no-op if err == 0 */
2436cleanup:
2437 brelse(bh);
2438 dx_release(frames);
2439 /* @restart is true means htree-path has been changed, we need to
2440 * repeat dx_probe() to find out valid htree-path
2441 */
2442 if (restart && err == 0)
2443 goto again;
2444 return err;
2445}
2446
2447/*
2448 * ext4_generic_delete_entry deletes a directory entry by merging it
2449 * with the previous entry
2450 */
2451int ext4_generic_delete_entry(handle_t *handle,
2452 struct inode *dir,
2453 struct ext4_dir_entry_2 *de_del,
2454 struct buffer_head *bh,
2455 void *entry_buf,
2456 int buf_size,
2457 int csum_size)
2458{
2459 struct ext4_dir_entry_2 *de, *pde;
2460 unsigned int blocksize = dir->i_sb->s_blocksize;
2461 int i;
2462
2463 i = 0;
2464 pde = NULL;
2465 de = (struct ext4_dir_entry_2 *)entry_buf;
2466 while (i < buf_size - csum_size) {
2467 if (ext4_check_dir_entry(dir, NULL, de, bh,
2468 bh->b_data, bh->b_size, i))
2469 return -EFSCORRUPTED;
2470 if (de == de_del) {
2471 if (pde)
2472 pde->rec_len = ext4_rec_len_to_disk(
2473 ext4_rec_len_from_disk(pde->rec_len,
2474 blocksize) +
2475 ext4_rec_len_from_disk(de->rec_len,
2476 blocksize),
2477 blocksize);
2478 else
2479 de->inode = 0;
2480 inode_inc_iversion(dir);
2481 return 0;
2482 }
2483 i += ext4_rec_len_from_disk(de->rec_len, blocksize);
2484 pde = de;
2485 de = ext4_next_entry(de, blocksize);
2486 }
2487 return -ENOENT;
2488}
2489
2490static int ext4_delete_entry(handle_t *handle,
2491 struct inode *dir,
2492 struct ext4_dir_entry_2 *de_del,
2493 struct buffer_head *bh)
2494{
2495 int err, csum_size = 0;
2496
2497 if (ext4_has_inline_data(dir)) {
2498 int has_inline_data = 1;
2499 err = ext4_delete_inline_entry(handle, dir, de_del, bh,
2500 &has_inline_data);
2501 if (has_inline_data)
2502 return err;
2503 }
2504
2505 if (ext4_has_metadata_csum(dir->i_sb))
2506 csum_size = sizeof(struct ext4_dir_entry_tail);
2507
2508 BUFFER_TRACE(bh, "get_write_access");
2509 err = ext4_journal_get_write_access(handle, bh);
2510 if (unlikely(err))
2511 goto out;
2512
2513 err = ext4_generic_delete_entry(handle, dir, de_del,
2514 bh, bh->b_data,
2515 dir->i_sb->s_blocksize, csum_size);
2516 if (err)
2517 goto out;
2518
2519 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
2520 err = ext4_handle_dirty_dirent_node(handle, dir, bh);
2521 if (unlikely(err))
2522 goto out;
2523
2524 return 0;
2525out:
2526 if (err != -ENOENT)
2527 ext4_std_error(dir->i_sb, err);
2528 return err;
2529}
2530
2531/*
2532 * Set directory link count to 1 if nlinks > EXT4_LINK_MAX, or if nlinks == 2
2533 * since this indicates that nlinks count was previously 1 to avoid overflowing
2534 * the 16-bit i_links_count field on disk. Directories with i_nlink == 1 mean
2535 * that subdirectory link counts are not being maintained accurately.
2536 *
2537 * The caller has already checked for i_nlink overflow in case the DIR_LINK
2538 * feature is not enabled and returned -EMLINK. The is_dx() check is a proxy
2539 * for checking S_ISDIR(inode) (since the INODE_INDEX feature will not be set
2540 * on regular files) and to avoid creating huge/slow non-HTREE directories.
2541 */
2542static void ext4_inc_count(handle_t *handle, struct inode *inode)
2543{
2544 inc_nlink(inode);
2545 if (is_dx(inode) &&
2546 (inode->i_nlink > EXT4_LINK_MAX || inode->i_nlink == 2))
2547 set_nlink(inode, 1);
2548}
2549
2550/*
2551 * If a directory had nlink == 1, then we should let it be 1. This indicates
2552 * directory has >EXT4_LINK_MAX subdirs.
2553 */
2554static void ext4_dec_count(handle_t *handle, struct inode *inode)
2555{
2556 if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
2557 drop_nlink(inode);
2558}
2559
2560
2561static int ext4_add_nondir(handle_t *handle,
2562 struct dentry *dentry, struct inode *inode)
2563{
2564 int err = ext4_add_entry(handle, dentry, inode);
2565 if (!err) {
2566 ext4_mark_inode_dirty(handle, inode);
2567 d_instantiate_new(dentry, inode);
2568 return 0;
2569 }
2570 drop_nlink(inode);
2571 unlock_new_inode(inode);
2572 iput(inode);
2573 return err;
2574}
2575
2576/*
2577 * By the time this is called, we already have created
2578 * the directory cache entry for the new file, but it
2579 * is so far negative - it has no inode.
2580 *
2581 * If the create succeeds, we fill in the inode information
2582 * with d_instantiate().
2583 */
2584static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2585 bool excl)
2586{
2587 handle_t *handle;
2588 struct inode *inode;
2589 int err, credits, retries = 0;
2590
2591 err = dquot_initialize(dir);
2592 if (err)
2593 return err;
2594
2595 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2596 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2597retry:
2598 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2599 NULL, EXT4_HT_DIR, credits);
2600 handle = ext4_journal_current_handle();
2601 err = PTR_ERR(inode);
2602 if (!IS_ERR(inode)) {
2603 inode->i_op = &ext4_file_inode_operations;
2604 inode->i_fop = &ext4_file_operations;
2605 ext4_set_aops(inode);
2606 err = ext4_add_nondir(handle, dentry, inode);
2607 if (!err && IS_DIRSYNC(dir))
2608 ext4_handle_sync(handle);
2609 }
2610 if (handle)
2611 ext4_journal_stop(handle);
2612 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2613 goto retry;
2614 return err;
2615}
2616
2617static int ext4_mknod(struct inode *dir, struct dentry *dentry,
2618 umode_t mode, dev_t rdev)
2619{
2620 handle_t *handle;
2621 struct inode *inode;
2622 int err, credits, retries = 0;
2623
2624 err = dquot_initialize(dir);
2625 if (err)
2626 return err;
2627
2628 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2629 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2630retry:
2631 inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2632 NULL, EXT4_HT_DIR, credits);
2633 handle = ext4_journal_current_handle();
2634 err = PTR_ERR(inode);
2635 if (!IS_ERR(inode)) {
2636 init_special_inode(inode, inode->i_mode, rdev);
2637 inode->i_op = &ext4_special_inode_operations;
2638 err = ext4_add_nondir(handle, dentry, inode);
2639 if (!err && IS_DIRSYNC(dir))
2640 ext4_handle_sync(handle);
2641 }
2642 if (handle)
2643 ext4_journal_stop(handle);
2644 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2645 goto retry;
2646 return err;
2647}
2648
2649static int ext4_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2650{
2651 handle_t *handle;
2652 struct inode *inode;
2653 int err, retries = 0;
2654
2655 err = dquot_initialize(dir);
2656 if (err)
2657 return err;
2658
2659retry:
2660 inode = ext4_new_inode_start_handle(dir, mode,
2661 NULL, 0, NULL,
2662 EXT4_HT_DIR,
2663 EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
2664 4 + EXT4_XATTR_TRANS_BLOCKS);
2665 handle = ext4_journal_current_handle();
2666 err = PTR_ERR(inode);
2667 if (!IS_ERR(inode)) {
2668 inode->i_op = &ext4_file_inode_operations;
2669 inode->i_fop = &ext4_file_operations;
2670 ext4_set_aops(inode);
2671 d_tmpfile(dentry, inode);
2672 err = ext4_orphan_add(handle, inode);
2673 if (err)
2674 goto err_unlock_inode;
2675 mark_inode_dirty(inode);
2676 unlock_new_inode(inode);
2677 }
2678 if (handle)
2679 ext4_journal_stop(handle);
2680 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2681 goto retry;
2682 return err;
2683err_unlock_inode:
2684 ext4_journal_stop(handle);
2685 unlock_new_inode(inode);
2686 return err;
2687}
2688
2689struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode,
2690 struct ext4_dir_entry_2 *de,
2691 int blocksize, int csum_size,
2692 unsigned int parent_ino, int dotdot_real_len)
2693{
2694 de->inode = cpu_to_le32(inode->i_ino);
2695 de->name_len = 1;
2696 de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
2697 blocksize);
2698 strcpy(de->name, ".");
2699 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2700
2701 de = ext4_next_entry(de, blocksize);
2702 de->inode = cpu_to_le32(parent_ino);
2703 de->name_len = 2;
2704 if (!dotdot_real_len)
2705 de->rec_len = ext4_rec_len_to_disk(blocksize -
2706 (csum_size + EXT4_DIR_REC_LEN(1)),
2707 blocksize);
2708 else
2709 de->rec_len = ext4_rec_len_to_disk(
2710 EXT4_DIR_REC_LEN(de->name_len), blocksize);
2711 strcpy(de->name, "..");
2712 ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2713
2714 return ext4_next_entry(de, blocksize);
2715}
2716
2717static int ext4_init_new_dir(handle_t *handle, struct inode *dir,
2718 struct inode *inode)
2719{
2720 struct buffer_head *dir_block = NULL;
2721 struct ext4_dir_entry_2 *de;
2722 struct ext4_dir_entry_tail *t;
2723 ext4_lblk_t block = 0;
2724 unsigned int blocksize = dir->i_sb->s_blocksize;
2725 int csum_size = 0;
2726 int err;
2727
2728 if (ext4_has_metadata_csum(dir->i_sb))
2729 csum_size = sizeof(struct ext4_dir_entry_tail);
2730
2731 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2732 err = ext4_try_create_inline_dir(handle, dir, inode);
2733 if (err < 0 && err != -ENOSPC)
2734 goto out;
2735 if (!err)
2736 goto out;
2737 }
2738
2739 inode->i_size = 0;
2740 dir_block = ext4_append(handle, inode, &block);
2741 if (IS_ERR(dir_block))
2742 return PTR_ERR(dir_block);
2743 de = (struct ext4_dir_entry_2 *)dir_block->b_data;
2744 ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0);
2745 set_nlink(inode, 2);
2746 if (csum_size) {
2747 t = EXT4_DIRENT_TAIL(dir_block->b_data, blocksize);
2748 initialize_dirent_tail(t, blocksize);
2749 }
2750
2751 BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
2752 err = ext4_handle_dirty_dirent_node(handle, inode, dir_block);
2753 if (err)
2754 goto out;
2755 set_buffer_verified(dir_block);
2756out:
2757 brelse(dir_block);
2758 return err;
2759}
2760
2761static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2762{
2763 handle_t *handle;
2764 struct inode *inode;
2765 int err, credits, retries = 0;
2766
2767 if (EXT4_DIR_LINK_MAX(dir))
2768 return -EMLINK;
2769
2770 err = dquot_initialize(dir);
2771 if (err)
2772 return err;
2773
2774 credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2775 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2776retry:
2777 inode = ext4_new_inode_start_handle(dir, S_IFDIR | mode,
2778 &dentry->d_name,
2779 0, NULL, EXT4_HT_DIR, credits);
2780 handle = ext4_journal_current_handle();
2781 err = PTR_ERR(inode);
2782 if (IS_ERR(inode))
2783 goto out_stop;
2784
2785 inode->i_op = &ext4_dir_inode_operations;
2786 inode->i_fop = &ext4_dir_operations;
2787 err = ext4_init_new_dir(handle, dir, inode);
2788 if (err)
2789 goto out_clear_inode;
2790 err = ext4_mark_inode_dirty(handle, inode);
2791 if (!err)
2792 err = ext4_add_entry(handle, dentry, inode);
2793 if (err) {
2794out_clear_inode:
2795 clear_nlink(inode);
2796 unlock_new_inode(inode);
2797 ext4_mark_inode_dirty(handle, inode);
2798 iput(inode);
2799 goto out_stop;
2800 }
2801 ext4_inc_count(handle, dir);
2802 ext4_update_dx_flag(dir);
2803 err = ext4_mark_inode_dirty(handle, dir);
2804 if (err)
2805 goto out_clear_inode;
2806 d_instantiate_new(dentry, inode);
2807 if (IS_DIRSYNC(dir))
2808 ext4_handle_sync(handle);
2809
2810out_stop:
2811 if (handle)
2812 ext4_journal_stop(handle);
2813 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2814 goto retry;
2815 return err;
2816}
2817
2818/*
2819 * routine to check that the specified directory is empty (for rmdir)
2820 */
2821bool ext4_empty_dir(struct inode *inode)
2822{
2823 unsigned int offset;
2824 struct buffer_head *bh;
2825 struct ext4_dir_entry_2 *de;
2826 struct super_block *sb;
2827
2828 if (ext4_has_inline_data(inode)) {
2829 int has_inline_data = 1;
2830 int ret;
2831
2832 ret = empty_inline_dir(inode, &has_inline_data);
2833 if (has_inline_data)
2834 return ret;
2835 }
2836
2837 sb = inode->i_sb;
2838 if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2)) {
2839 EXT4_ERROR_INODE(inode, "invalid size");
2840 return true;
2841 }
2842 /* The first directory block must not be a hole,
2843 * so treat it as DIRENT_HTREE
2844 */
2845 bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
2846 if (IS_ERR(bh))
2847 return true;
2848
2849 de = (struct ext4_dir_entry_2 *) bh->b_data;
2850 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2851 0) ||
2852 le32_to_cpu(de->inode) != inode->i_ino || strcmp(".", de->name)) {
2853 ext4_warning_inode(inode, "directory missing '.'");
2854 brelse(bh);
2855 return true;
2856 }
2857 offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2858 de = ext4_next_entry(de, sb->s_blocksize);
2859 if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2860 offset) ||
2861 le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
2862 ext4_warning_inode(inode, "directory missing '..'");
2863 brelse(bh);
2864 return true;
2865 }
2866 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2867 while (offset < inode->i_size) {
2868 if (!(offset & (sb->s_blocksize - 1))) {
2869 unsigned int lblock;
2870 brelse(bh);
2871 lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
2872 bh = ext4_read_dirblock(inode, lblock, EITHER);
2873 if (bh == NULL) {
2874 offset += sb->s_blocksize;
2875 continue;
2876 }
2877 if (IS_ERR(bh))
2878 return true;
2879 }
2880 de = (struct ext4_dir_entry_2 *) (bh->b_data +
2881 (offset & (sb->s_blocksize - 1)));
2882 if (ext4_check_dir_entry(inode, NULL, de, bh,
2883 bh->b_data, bh->b_size, offset)) {
2884 offset = (offset | (sb->s_blocksize - 1)) + 1;
2885 continue;
2886 }
2887 if (le32_to_cpu(de->inode)) {
2888 brelse(bh);
2889 return false;
2890 }
2891 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2892 }
2893 brelse(bh);
2894 return true;
2895}
2896
2897/*
2898 * ext4_orphan_add() links an unlinked or truncated inode into a list of
2899 * such inodes, starting at the superblock, in case we crash before the
2900 * file is closed/deleted, or in case the inode truncate spans multiple
2901 * transactions and the last transaction is not recovered after a crash.
2902 *
2903 * At filesystem recovery time, we walk this list deleting unlinked
2904 * inodes and truncating linked inodes in ext4_orphan_cleanup().
2905 *
2906 * Orphan list manipulation functions must be called under i_mutex unless
2907 * we are just creating the inode or deleting it.
2908 */
2909int ext4_orphan_add(handle_t *handle, struct inode *inode)
2910{
2911 struct super_block *sb = inode->i_sb;
2912 struct ext4_sb_info *sbi = EXT4_SB(sb);
2913 struct ext4_iloc iloc;
2914 int err = 0, rc;
2915 bool dirty = false;
2916
2917 if (!sbi->s_journal || is_bad_inode(inode))
2918 return 0;
2919
2920 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2921 !inode_is_locked(inode));
2922 /*
2923 * Exit early if inode already is on orphan list. This is a big speedup
2924 * since we don't have to contend on the global s_orphan_lock.
2925 */
2926 if (!list_empty(&EXT4_I(inode)->i_orphan))
2927 return 0;
2928
2929 /*
2930 * Orphan handling is only valid for files with data blocks
2931 * being truncated, or files being unlinked. Note that we either
2932 * hold i_mutex, or the inode can not be referenced from outside,
2933 * so i_nlink should not be bumped due to race
2934 */
2935 J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
2936 S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
2937
2938 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2939 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2940 if (err)
2941 goto out;
2942
2943 err = ext4_reserve_inode_write(handle, inode, &iloc);
2944 if (err)
2945 goto out;
2946
2947 mutex_lock(&sbi->s_orphan_lock);
2948 /*
2949 * Due to previous errors inode may be already a part of on-disk
2950 * orphan list. If so skip on-disk list modification.
2951 */
2952 if (!NEXT_ORPHAN(inode) || NEXT_ORPHAN(inode) >
2953 (le32_to_cpu(sbi->s_es->s_inodes_count))) {
2954 /* Insert this inode at the head of the on-disk orphan list */
2955 NEXT_ORPHAN(inode) = le32_to_cpu(sbi->s_es->s_last_orphan);
2956 sbi->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
2957 dirty = true;
2958 }
2959 list_add(&EXT4_I(inode)->i_orphan, &sbi->s_orphan);
2960 mutex_unlock(&sbi->s_orphan_lock);
2961
2962 if (dirty) {
2963 err = ext4_handle_dirty_super(handle, sb);
2964 rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
2965 if (!err)
2966 err = rc;
2967 if (err) {
2968 /*
2969 * We have to remove inode from in-memory list if
2970 * addition to on disk orphan list failed. Stray orphan
2971 * list entries can cause panics at unmount time.
2972 */
2973 mutex_lock(&sbi->s_orphan_lock);
2974 list_del_init(&EXT4_I(inode)->i_orphan);
2975 mutex_unlock(&sbi->s_orphan_lock);
2976 }
2977 } else
2978 brelse(iloc.bh);
2979
2980 jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
2981 jbd_debug(4, "orphan inode %lu will point to %d\n",
2982 inode->i_ino, NEXT_ORPHAN(inode));
2983out:
2984 ext4_std_error(sb, err);
2985 return err;
2986}
2987
2988/*
2989 * ext4_orphan_del() removes an unlinked or truncated inode from the list
2990 * of such inodes stored on disk, because it is finally being cleaned up.
2991 */
2992int ext4_orphan_del(handle_t *handle, struct inode *inode)
2993{
2994 struct list_head *prev;
2995 struct ext4_inode_info *ei = EXT4_I(inode);
2996 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2997 __u32 ino_next;
2998 struct ext4_iloc iloc;
2999 int err = 0;
3000
3001 if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS))
3002 return 0;
3003
3004 WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
3005 !inode_is_locked(inode));
3006 /* Do this quick check before taking global s_orphan_lock. */
3007 if (list_empty(&ei->i_orphan))
3008 return 0;
3009
3010 if (handle) {
3011 /* Grab inode buffer early before taking global s_orphan_lock */
3012 err = ext4_reserve_inode_write(handle, inode, &iloc);
3013 }
3014
3015 mutex_lock(&sbi->s_orphan_lock);
3016 jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
3017
3018 prev = ei->i_orphan.prev;
3019 list_del_init(&ei->i_orphan);
3020
3021 /* If we're on an error path, we may not have a valid
3022 * transaction handle with which to update the orphan list on
3023 * disk, but we still need to remove the inode from the linked
3024 * list in memory. */
3025 if (!handle || err) {
3026 mutex_unlock(&sbi->s_orphan_lock);
3027 goto out_err;
3028 }
3029
3030 ino_next = NEXT_ORPHAN(inode);
3031 if (prev == &sbi->s_orphan) {
3032 jbd_debug(4, "superblock will point to %u\n", ino_next);
3033 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
3034 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
3035 if (err) {
3036 mutex_unlock(&sbi->s_orphan_lock);
3037 goto out_brelse;
3038 }
3039 sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
3040 mutex_unlock(&sbi->s_orphan_lock);
3041 err = ext4_handle_dirty_super(handle, inode->i_sb);
3042 } else {
3043 struct ext4_iloc iloc2;
3044 struct inode *i_prev =
3045 &list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
3046
3047 jbd_debug(4, "orphan inode %lu will point to %u\n",
3048 i_prev->i_ino, ino_next);
3049 err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
3050 if (err) {
3051 mutex_unlock(&sbi->s_orphan_lock);
3052 goto out_brelse;
3053 }
3054 NEXT_ORPHAN(i_prev) = ino_next;
3055 err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
3056 mutex_unlock(&sbi->s_orphan_lock);
3057 }
3058 if (err)
3059 goto out_brelse;
3060 NEXT_ORPHAN(inode) = 0;
3061 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
3062out_err:
3063 ext4_std_error(inode->i_sb, err);
3064 return err;
3065
3066out_brelse:
3067 brelse(iloc.bh);
3068 goto out_err;
3069}
3070
3071static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
3072{
3073 int retval;
3074 struct inode *inode;
3075 struct buffer_head *bh;
3076 struct ext4_dir_entry_2 *de;
3077 handle_t *handle = NULL;
3078
3079 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3080 return -EIO;
3081
3082 /* Initialize quotas before so that eventual writes go in
3083 * separate transaction */
3084 retval = dquot_initialize(dir);
3085 if (retval)
3086 return retval;
3087 retval = dquot_initialize(d_inode(dentry));
3088 if (retval)
3089 return retval;
3090
3091 retval = -ENOENT;
3092 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3093 if (IS_ERR(bh))
3094 return PTR_ERR(bh);
3095 if (!bh)
3096 goto end_rmdir;
3097
3098 inode = d_inode(dentry);
3099
3100 retval = -EFSCORRUPTED;
3101 if (le32_to_cpu(de->inode) != inode->i_ino)
3102 goto end_rmdir;
3103
3104 retval = -ENOTEMPTY;
3105 if (!ext4_empty_dir(inode))
3106 goto end_rmdir;
3107
3108 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3109 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3110 if (IS_ERR(handle)) {
3111 retval = PTR_ERR(handle);
3112 handle = NULL;
3113 goto end_rmdir;
3114 }
3115
3116 if (IS_DIRSYNC(dir))
3117 ext4_handle_sync(handle);
3118
3119 retval = ext4_delete_entry(handle, dir, de, bh);
3120 if (retval)
3121 goto end_rmdir;
3122 if (!EXT4_DIR_LINK_EMPTY(inode))
3123 ext4_warning_inode(inode,
3124 "empty directory '%.*s' has too many links (%u)",
3125 dentry->d_name.len, dentry->d_name.name,
3126 inode->i_nlink);
3127 inode_inc_iversion(inode);
3128 clear_nlink(inode);
3129 /* There's no need to set i_disksize: the fact that i_nlink is
3130 * zero will ensure that the right thing happens during any
3131 * recovery. */
3132 inode->i_size = 0;
3133 ext4_orphan_add(handle, inode);
3134 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
3135 ext4_mark_inode_dirty(handle, inode);
3136 ext4_dec_count(handle, dir);
3137 ext4_update_dx_flag(dir);
3138 ext4_mark_inode_dirty(handle, dir);
3139
3140#ifdef CONFIG_UNICODE
3141 /* VFS negative dentries are incompatible with Encoding and
3142 * Case-insensitiveness. Eventually we'll want avoid
3143 * invalidating the dentries here, alongside with returning the
3144 * negative dentries at ext4_lookup(), when it is better
3145 * supported by the VFS for the CI case.
3146 */
3147 if (IS_CASEFOLDED(dir))
3148 d_invalidate(dentry);
3149#endif
3150
3151end_rmdir:
3152 brelse(bh);
3153 if (handle)
3154 ext4_journal_stop(handle);
3155 return retval;
3156}
3157
3158static int ext4_unlink(struct inode *dir, struct dentry *dentry)
3159{
3160 int retval;
3161 struct inode *inode;
3162 struct buffer_head *bh;
3163 struct ext4_dir_entry_2 *de;
3164 handle_t *handle = NULL;
3165
3166 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3167 return -EIO;
3168
3169 trace_ext4_unlink_enter(dir, dentry);
3170 /* Initialize quotas before so that eventual writes go
3171 * in separate transaction */
3172 retval = dquot_initialize(dir);
3173 if (retval)
3174 return retval;
3175 retval = dquot_initialize(d_inode(dentry));
3176 if (retval)
3177 return retval;
3178
3179 retval = -ENOENT;
3180 bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3181 if (IS_ERR(bh))
3182 return PTR_ERR(bh);
3183 if (!bh)
3184 goto end_unlink;
3185
3186 inode = d_inode(dentry);
3187
3188 retval = -EFSCORRUPTED;
3189 if (le32_to_cpu(de->inode) != inode->i_ino)
3190 goto end_unlink;
3191
3192 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3193 EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3194 if (IS_ERR(handle)) {
3195 retval = PTR_ERR(handle);
3196 handle = NULL;
3197 goto end_unlink;
3198 }
3199
3200 if (IS_DIRSYNC(dir))
3201 ext4_handle_sync(handle);
3202
3203 retval = ext4_delete_entry(handle, dir, de, bh);
3204 if (retval)
3205 goto end_unlink;
3206 dir->i_ctime = dir->i_mtime = current_time(dir);
3207 ext4_update_dx_flag(dir);
3208 ext4_mark_inode_dirty(handle, dir);
3209 if (inode->i_nlink == 0)
3210 ext4_warning_inode(inode, "Deleting file '%.*s' with no links",
3211 dentry->d_name.len, dentry->d_name.name);
3212 else
3213 drop_nlink(inode);
3214 if (!inode->i_nlink)
3215 ext4_orphan_add(handle, inode);
3216 inode->i_ctime = current_time(inode);
3217 ext4_mark_inode_dirty(handle, inode);
3218
3219#ifdef CONFIG_UNICODE
3220 /* VFS negative dentries are incompatible with Encoding and
3221 * Case-insensitiveness. Eventually we'll want avoid
3222 * invalidating the dentries here, alongside with returning the
3223 * negative dentries at ext4_lookup(), when it is better
3224 * supported by the VFS for the CI case.
3225 */
3226 if (IS_CASEFOLDED(dir))
3227 d_invalidate(dentry);
3228#endif
3229
3230end_unlink:
3231 brelse(bh);
3232 if (handle)
3233 ext4_journal_stop(handle);
3234 trace_ext4_unlink_exit(dentry, retval);
3235 return retval;
3236}
3237
3238static int ext4_symlink(struct inode *dir,
3239 struct dentry *dentry, const char *symname)
3240{
3241 handle_t *handle;
3242 struct inode *inode;
3243 int err, len = strlen(symname);
3244 int credits;
3245 struct fscrypt_str disk_link;
3246
3247 if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3248 return -EIO;
3249
3250 err = fscrypt_prepare_symlink(dir, symname, len, dir->i_sb->s_blocksize,
3251 &disk_link);
3252 if (err)
3253 return err;
3254
3255 err = dquot_initialize(dir);
3256 if (err)
3257 return err;
3258
3259 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3260 /*
3261 * For non-fast symlinks, we just allocate inode and put it on
3262 * orphan list in the first transaction => we need bitmap,
3263 * group descriptor, sb, inode block, quota blocks, and
3264 * possibly selinux xattr blocks.
3265 */
3266 credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
3267 EXT4_XATTR_TRANS_BLOCKS;
3268 } else {
3269 /*
3270 * Fast symlink. We have to add entry to directory
3271 * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
3272 * allocate new inode (bitmap, group descriptor, inode block,
3273 * quota blocks, sb is already counted in previous macros).
3274 */
3275 credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3276 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3;
3277 }
3278
3279 inode = ext4_new_inode_start_handle(dir, S_IFLNK|S_IRWXUGO,
3280 &dentry->d_name, 0, NULL,
3281 EXT4_HT_DIR, credits);
3282 handle = ext4_journal_current_handle();
3283 if (IS_ERR(inode)) {
3284 if (handle)
3285 ext4_journal_stop(handle);
3286 return PTR_ERR(inode);
3287 }
3288
3289 if (IS_ENCRYPTED(inode)) {
3290 err = fscrypt_encrypt_symlink(inode, symname, len, &disk_link);
3291 if (err)
3292 goto err_drop_inode;
3293 inode->i_op = &ext4_encrypted_symlink_inode_operations;
3294 }
3295
3296 if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3297 if (!IS_ENCRYPTED(inode))
3298 inode->i_op = &ext4_symlink_inode_operations;
3299 inode_nohighmem(inode);
3300 ext4_set_aops(inode);
3301 /*
3302 * We cannot call page_symlink() with transaction started
3303 * because it calls into ext4_write_begin() which can wait
3304 * for transaction commit if we are running out of space
3305 * and thus we deadlock. So we have to stop transaction now
3306 * and restart it when symlink contents is written.
3307 *
3308 * To keep fs consistent in case of crash, we have to put inode
3309 * to orphan list in the mean time.
3310 */
3311 drop_nlink(inode);
3312 err = ext4_orphan_add(handle, inode);
3313 ext4_journal_stop(handle);
3314 handle = NULL;
3315 if (err)
3316 goto err_drop_inode;
3317 err = __page_symlink(inode, disk_link.name, disk_link.len, 1);
3318 if (err)
3319 goto err_drop_inode;
3320 /*
3321 * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
3322 * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
3323 */
3324 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3325 EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3326 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
3327 if (IS_ERR(handle)) {
3328 err = PTR_ERR(handle);
3329 handle = NULL;
3330 goto err_drop_inode;
3331 }
3332 set_nlink(inode, 1);
3333 err = ext4_orphan_del(handle, inode);
3334 if (err)
3335 goto err_drop_inode;
3336 } else {
3337 /* clear the extent format for fast symlink */
3338 ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
3339 if (!IS_ENCRYPTED(inode)) {
3340 inode->i_op = &ext4_fast_symlink_inode_operations;
3341 inode->i_link = (char *)&EXT4_I(inode)->i_data;
3342 }
3343 memcpy((char *)&EXT4_I(inode)->i_data, disk_link.name,
3344 disk_link.len);
3345 inode->i_size = disk_link.len - 1;
3346 }
3347 EXT4_I(inode)->i_disksize = inode->i_size;
3348 err = ext4_add_nondir(handle, dentry, inode);
3349 if (!err && IS_DIRSYNC(dir))
3350 ext4_handle_sync(handle);
3351
3352 if (handle)
3353 ext4_journal_stop(handle);
3354 goto out_free_encrypted_link;
3355
3356err_drop_inode:
3357 if (handle)
3358 ext4_journal_stop(handle);
3359 clear_nlink(inode);
3360 unlock_new_inode(inode);
3361 iput(inode);
3362out_free_encrypted_link:
3363 if (disk_link.name != (unsigned char *)symname)
3364 kfree(disk_link.name);
3365 return err;
3366}
3367
3368static int ext4_link(struct dentry *old_dentry,
3369 struct inode *dir, struct dentry *dentry)
3370{
3371 handle_t *handle;
3372 struct inode *inode = d_inode(old_dentry);
3373 int err, retries = 0;
3374
3375 if (inode->i_nlink >= EXT4_LINK_MAX)
3376 return -EMLINK;
3377
3378 err = fscrypt_prepare_link(old_dentry, dir, dentry);
3379 if (err)
3380 return err;
3381
3382 if ((ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT)) &&
3383 (!projid_eq(EXT4_I(dir)->i_projid,
3384 EXT4_I(old_dentry->d_inode)->i_projid)))
3385 return -EXDEV;
3386
3387 err = dquot_initialize(dir);
3388 if (err)
3389 return err;
3390
3391retry:
3392 handle = ext4_journal_start(dir, EXT4_HT_DIR,
3393 (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3394 EXT4_INDEX_EXTRA_TRANS_BLOCKS) + 1);
3395 if (IS_ERR(handle))
3396 return PTR_ERR(handle);
3397
3398 if (IS_DIRSYNC(dir))
3399 ext4_handle_sync(handle);
3400
3401 inode->i_ctime = current_time(inode);
3402 ext4_inc_count(handle, inode);
3403 ihold(inode);
3404
3405 err = ext4_add_entry(handle, dentry, inode);
3406 if (!err) {
3407 ext4_mark_inode_dirty(handle, inode);
3408 /* this can happen only for tmpfile being
3409 * linked the first time
3410 */
3411 if (inode->i_nlink == 1)
3412 ext4_orphan_del(handle, inode);
3413 d_instantiate(dentry, inode);
3414 } else {
3415 drop_nlink(inode);
3416 iput(inode);
3417 }
3418 ext4_journal_stop(handle);
3419 if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
3420 goto retry;
3421 return err;
3422}
3423
3424
3425/*
3426 * Try to find buffer head where contains the parent block.
3427 * It should be the inode block if it is inlined or the 1st block
3428 * if it is a normal dir.
3429 */
3430static struct buffer_head *ext4_get_first_dir_block(handle_t *handle,
3431 struct inode *inode,
3432 int *retval,
3433 struct ext4_dir_entry_2 **parent_de,
3434 int *inlined)
3435{
3436 struct buffer_head *bh;
3437
3438 if (!ext4_has_inline_data(inode)) {
3439 /* The first directory block must not be a hole, so
3440 * treat it as DIRENT_HTREE
3441 */
3442 bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
3443 if (IS_ERR(bh)) {
3444 *retval = PTR_ERR(bh);
3445 return NULL;
3446 }
3447 *parent_de = ext4_next_entry(
3448 (struct ext4_dir_entry_2 *)bh->b_data,
3449 inode->i_sb->s_blocksize);
3450 return bh;
3451 }
3452
3453 *inlined = 1;
3454 return ext4_get_first_inline_block(inode, parent_de, retval);
3455}
3456
3457struct ext4_renament {
3458 struct inode *dir;
3459 struct dentry *dentry;
3460 struct inode *inode;
3461 bool is_dir;
3462 int dir_nlink_delta;
3463
3464 /* entry for "dentry" */
3465 struct buffer_head *bh;
3466 struct ext4_dir_entry_2 *de;
3467 int inlined;
3468
3469 /* entry for ".." in inode if it's a directory */
3470 struct buffer_head *dir_bh;
3471 struct ext4_dir_entry_2 *parent_de;
3472 int dir_inlined;
3473};
3474
3475static int ext4_rename_dir_prepare(handle_t *handle, struct ext4_renament *ent)
3476{
3477 int retval;
3478
3479 ent->dir_bh = ext4_get_first_dir_block(handle, ent->inode,
3480 &retval, &ent->parent_de,
3481 &ent->dir_inlined);
3482 if (!ent->dir_bh)
3483 return retval;
3484 if (le32_to_cpu(ent->parent_de->inode) != ent->dir->i_ino)
3485 return -EFSCORRUPTED;
3486 BUFFER_TRACE(ent->dir_bh, "get_write_access");
3487 return ext4_journal_get_write_access(handle, ent->dir_bh);
3488}
3489
3490static int ext4_rename_dir_finish(handle_t *handle, struct ext4_renament *ent,
3491 unsigned dir_ino)
3492{
3493 int retval;
3494
3495 ent->parent_de->inode = cpu_to_le32(dir_ino);
3496 BUFFER_TRACE(ent->dir_bh, "call ext4_handle_dirty_metadata");
3497 if (!ent->dir_inlined) {
3498 if (is_dx(ent->inode)) {
3499 retval = ext4_handle_dirty_dx_node(handle,
3500 ent->inode,
3501 ent->dir_bh);
3502 } else {
3503 retval = ext4_handle_dirty_dirent_node(handle,
3504 ent->inode,
3505 ent->dir_bh);
3506 }
3507 } else {
3508 retval = ext4_mark_inode_dirty(handle, ent->inode);
3509 }
3510 if (retval) {
3511 ext4_std_error(ent->dir->i_sb, retval);
3512 return retval;
3513 }
3514 return 0;
3515}
3516
3517static int ext4_setent(handle_t *handle, struct ext4_renament *ent,
3518 unsigned ino, unsigned file_type)
3519{
3520 int retval;
3521
3522 BUFFER_TRACE(ent->bh, "get write access");
3523 retval = ext4_journal_get_write_access(handle, ent->bh);
3524 if (retval)
3525 return retval;
3526 ent->de->inode = cpu_to_le32(ino);
3527 if (ext4_has_feature_filetype(ent->dir->i_sb))
3528 ent->de->file_type = file_type;
3529 inode_inc_iversion(ent->dir);
3530 ent->dir->i_ctime = ent->dir->i_mtime =
3531 current_time(ent->dir);
3532 ext4_mark_inode_dirty(handle, ent->dir);
3533 BUFFER_TRACE(ent->bh, "call ext4_handle_dirty_metadata");
3534 if (!ent->inlined) {
3535 retval = ext4_handle_dirty_dirent_node(handle,
3536 ent->dir, ent->bh);
3537 if (unlikely(retval)) {
3538 ext4_std_error(ent->dir->i_sb, retval);
3539 return retval;
3540 }
3541 }
3542 brelse(ent->bh);
3543 ent->bh = NULL;
3544
3545 return 0;
3546}
3547
3548static int ext4_find_delete_entry(handle_t *handle, struct inode *dir,
3549 const struct qstr *d_name)
3550{
3551 int retval = -ENOENT;
3552 struct buffer_head *bh;
3553 struct ext4_dir_entry_2 *de;
3554
3555 bh = ext4_find_entry(dir, d_name, &de, NULL);
3556 if (IS_ERR(bh))
3557 return PTR_ERR(bh);
3558 if (bh) {
3559 retval = ext4_delete_entry(handle, dir, de, bh);
3560 brelse(bh);
3561 }
3562 return retval;
3563}
3564
3565static void ext4_rename_delete(handle_t *handle, struct ext4_renament *ent,
3566 int force_reread)
3567{
3568 int retval;
3569 /*
3570 * ent->de could have moved from under us during htree split, so make
3571 * sure that we are deleting the right entry. We might also be pointing
3572 * to a stale entry in the unused part of ent->bh so just checking inum
3573 * and the name isn't enough.
3574 */
3575 if (le32_to_cpu(ent->de->inode) != ent->inode->i_ino ||
3576 ent->de->name_len != ent->dentry->d_name.len ||
3577 strncmp(ent->de->name, ent->dentry->d_name.name,
3578 ent->de->name_len) ||
3579 force_reread) {
3580 retval = ext4_find_delete_entry(handle, ent->dir,
3581 &ent->dentry->d_name);
3582 } else {
3583 retval = ext4_delete_entry(handle, ent->dir, ent->de, ent->bh);
3584 if (retval == -ENOENT) {
3585 retval = ext4_find_delete_entry(handle, ent->dir,
3586 &ent->dentry->d_name);
3587 }
3588 }
3589
3590 if (retval) {
3591 ext4_warning_inode(ent->dir,
3592 "Deleting old file: nlink %d, error=%d",
3593 ent->dir->i_nlink, retval);
3594 }
3595}
3596
3597static void ext4_update_dir_count(handle_t *handle, struct ext4_renament *ent)
3598{
3599 if (ent->dir_nlink_delta) {
3600 if (ent->dir_nlink_delta == -1)
3601 ext4_dec_count(handle, ent->dir);
3602 else
3603 ext4_inc_count(handle, ent->dir);
3604 ext4_mark_inode_dirty(handle, ent->dir);
3605 }
3606}
3607
3608static struct inode *ext4_whiteout_for_rename(struct ext4_renament *ent,
3609 int credits, handle_t **h)
3610{
3611 struct inode *wh;
3612 handle_t *handle;
3613 int retries = 0;
3614
3615 /*
3616 * for inode block, sb block, group summaries,
3617 * and inode bitmap
3618 */
3619 credits += (EXT4_MAXQUOTAS_TRANS_BLOCKS(ent->dir->i_sb) +
3620 EXT4_XATTR_TRANS_BLOCKS + 4);
3621retry:
3622 wh = ext4_new_inode_start_handle(ent->dir, S_IFCHR | WHITEOUT_MODE,
3623 &ent->dentry->d_name, 0, NULL,
3624 EXT4_HT_DIR, credits);
3625
3626 handle = ext4_journal_current_handle();
3627 if (IS_ERR(wh)) {
3628 if (handle)
3629 ext4_journal_stop(handle);
3630 if (PTR_ERR(wh) == -ENOSPC &&
3631 ext4_should_retry_alloc(ent->dir->i_sb, &retries))
3632 goto retry;
3633 } else {
3634 *h = handle;
3635 init_special_inode(wh, wh->i_mode, WHITEOUT_DEV);
3636 wh->i_op = &ext4_special_inode_operations;
3637 }
3638 return wh;
3639}
3640
3641/*
3642 * Anybody can rename anything with this: the permission checks are left to the
3643 * higher-level routines.
3644 *
3645 * n.b. old_{dentry,inode) refers to the source dentry/inode
3646 * while new_{dentry,inode) refers to the destination dentry/inode
3647 * This comes from rename(const char *oldpath, const char *newpath)
3648 */
3649static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
3650 struct inode *new_dir, struct dentry *new_dentry,
3651 unsigned int flags)
3652{
3653 handle_t *handle = NULL;
3654 struct ext4_renament old = {
3655 .dir = old_dir,
3656 .dentry = old_dentry,
3657 .inode = d_inode(old_dentry),
3658 };
3659 struct ext4_renament new = {
3660 .dir = new_dir,
3661 .dentry = new_dentry,
3662 .inode = d_inode(new_dentry),
3663 };
3664 int force_reread;
3665 int retval;
3666 struct inode *whiteout = NULL;
3667 int credits;
3668 u8 old_file_type;
3669
3670 if (new.inode && new.inode->i_nlink == 0) {
3671 EXT4_ERROR_INODE(new.inode,
3672 "target of rename is already freed");
3673 return -EFSCORRUPTED;
3674 }
3675
3676 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT)) &&
3677 (!projid_eq(EXT4_I(new_dir)->i_projid,
3678 EXT4_I(old_dentry->d_inode)->i_projid)))
3679 return -EXDEV;
3680
3681 retval = dquot_initialize(old.dir);
3682 if (retval)
3683 return retval;
3684 retval = dquot_initialize(new.dir);
3685 if (retval)
3686 return retval;
3687
3688 /* Initialize quotas before so that eventual writes go
3689 * in separate transaction */
3690 if (new.inode) {
3691 retval = dquot_initialize(new.inode);
3692 if (retval)
3693 return retval;
3694 }
3695
3696 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de, NULL);
3697 if (IS_ERR(old.bh))
3698 return PTR_ERR(old.bh);
3699 /*
3700 * Check for inode number is _not_ due to possible IO errors.
3701 * We might rmdir the source, keep it as pwd of some process
3702 * and merrily kill the link to whatever was created under the
3703 * same name. Goodbye sticky bit ;-<
3704 */
3705 retval = -ENOENT;
3706 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3707 goto end_rename;
3708
3709 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3710 &new.de, &new.inlined);
3711 if (IS_ERR(new.bh)) {
3712 retval = PTR_ERR(new.bh);
3713 new.bh = NULL;
3714 goto end_rename;
3715 }
3716 if (new.bh) {
3717 if (!new.inode) {
3718 brelse(new.bh);
3719 new.bh = NULL;
3720 }
3721 }
3722 if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC))
3723 ext4_alloc_da_blocks(old.inode);
3724
3725 credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3726 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
3727 if (!(flags & RENAME_WHITEOUT)) {
3728 handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits);
3729 if (IS_ERR(handle)) {
3730 retval = PTR_ERR(handle);
3731 handle = NULL;
3732 goto end_rename;
3733 }
3734 } else {
3735 whiteout = ext4_whiteout_for_rename(&old, credits, &handle);
3736 if (IS_ERR(whiteout)) {
3737 retval = PTR_ERR(whiteout);
3738 whiteout = NULL;
3739 goto end_rename;
3740 }
3741 }
3742
3743 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3744 ext4_handle_sync(handle);
3745
3746 if (S_ISDIR(old.inode->i_mode)) {
3747 if (new.inode) {
3748 retval = -ENOTEMPTY;
3749 if (!ext4_empty_dir(new.inode))
3750 goto end_rename;
3751 } else {
3752 retval = -EMLINK;
3753 if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir))
3754 goto end_rename;
3755 }
3756 retval = ext4_rename_dir_prepare(handle, &old);
3757 if (retval)
3758 goto end_rename;
3759 }
3760 /*
3761 * If we're renaming a file within an inline_data dir and adding or
3762 * setting the new dirent causes a conversion from inline_data to
3763 * extents/blockmap, we need to force the dirent delete code to
3764 * re-read the directory, or else we end up trying to delete a dirent
3765 * from what is now the extent tree root (or a block map).
3766 */
3767 force_reread = (new.dir->i_ino == old.dir->i_ino &&
3768 ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA));
3769
3770 old_file_type = old.de->file_type;
3771 if (whiteout) {
3772 /*
3773 * Do this before adding a new entry, so the old entry is sure
3774 * to be still pointing to the valid old entry.
3775 */
3776 retval = ext4_setent(handle, &old, whiteout->i_ino,
3777 EXT4_FT_CHRDEV);
3778 if (retval)
3779 goto end_rename;
3780 ext4_mark_inode_dirty(handle, whiteout);
3781 }
3782 if (!new.bh) {
3783 retval = ext4_add_entry(handle, new.dentry, old.inode);
3784 if (retval)
3785 goto end_rename;
3786 } else {
3787 retval = ext4_setent(handle, &new,
3788 old.inode->i_ino, old_file_type);
3789 if (retval)
3790 goto end_rename;
3791 }
3792 if (force_reread)
3793 force_reread = !ext4_test_inode_flag(new.dir,
3794 EXT4_INODE_INLINE_DATA);
3795
3796 /*
3797 * Like most other Unix systems, set the ctime for inodes on a
3798 * rename.
3799 */
3800 old.inode->i_ctime = current_time(old.inode);
3801 ext4_mark_inode_dirty(handle, old.inode);
3802
3803 if (!whiteout) {
3804 /*
3805 * ok, that's it
3806 */
3807 ext4_rename_delete(handle, &old, force_reread);
3808 }
3809
3810 if (new.inode) {
3811 ext4_dec_count(handle, new.inode);
3812 new.inode->i_ctime = current_time(new.inode);
3813 }
3814 old.dir->i_ctime = old.dir->i_mtime = current_time(old.dir);
3815 ext4_update_dx_flag(old.dir);
3816 if (old.dir_bh) {
3817 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3818 if (retval)
3819 goto end_rename;
3820
3821 ext4_dec_count(handle, old.dir);
3822 if (new.inode) {
3823 /* checked ext4_empty_dir above, can't have another
3824 * parent, ext4_dec_count() won't work for many-linked
3825 * dirs */
3826 clear_nlink(new.inode);
3827 } else {
3828 ext4_inc_count(handle, new.dir);
3829 ext4_update_dx_flag(new.dir);
3830 ext4_mark_inode_dirty(handle, new.dir);
3831 }
3832 }
3833 ext4_mark_inode_dirty(handle, old.dir);
3834 if (new.inode) {
3835 ext4_mark_inode_dirty(handle, new.inode);
3836 if (!new.inode->i_nlink)
3837 ext4_orphan_add(handle, new.inode);
3838 }
3839 retval = 0;
3840
3841end_rename:
3842 brelse(old.dir_bh);
3843 brelse(old.bh);
3844 brelse(new.bh);
3845 if (whiteout) {
3846 if (retval)
3847 drop_nlink(whiteout);
3848 unlock_new_inode(whiteout);
3849 iput(whiteout);
3850 }
3851 if (handle)
3852 ext4_journal_stop(handle);
3853 return retval;
3854}
3855
3856static int ext4_cross_rename(struct inode *old_dir, struct dentry *old_dentry,
3857 struct inode *new_dir, struct dentry *new_dentry)
3858{
3859 handle_t *handle = NULL;
3860 struct ext4_renament old = {
3861 .dir = old_dir,
3862 .dentry = old_dentry,
3863 .inode = d_inode(old_dentry),
3864 };
3865 struct ext4_renament new = {
3866 .dir = new_dir,
3867 .dentry = new_dentry,
3868 .inode = d_inode(new_dentry),
3869 };
3870 u8 new_file_type;
3871 int retval;
3872 struct timespec64 ctime;
3873
3874 if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT) &&
3875 !projid_eq(EXT4_I(new_dir)->i_projid,
3876 EXT4_I(old_dentry->d_inode)->i_projid)) ||
3877 (ext4_test_inode_flag(old_dir, EXT4_INODE_PROJINHERIT) &&
3878 !projid_eq(EXT4_I(old_dir)->i_projid,
3879 EXT4_I(new_dentry->d_inode)->i_projid)))
3880 return -EXDEV;
3881
3882 retval = dquot_initialize(old.dir);
3883 if (retval)
3884 return retval;
3885 retval = dquot_initialize(new.dir);
3886 if (retval)
3887 return retval;
3888
3889 old.bh = ext4_find_entry(old.dir, &old.dentry->d_name,
3890 &old.de, &old.inlined);
3891 if (IS_ERR(old.bh))
3892 return PTR_ERR(old.bh);
3893 /*
3894 * Check for inode number is _not_ due to possible IO errors.
3895 * We might rmdir the source, keep it as pwd of some process
3896 * and merrily kill the link to whatever was created under the
3897 * same name. Goodbye sticky bit ;-<
3898 */
3899 retval = -ENOENT;
3900 if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3901 goto end_rename;
3902
3903 new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3904 &new.de, &new.inlined);
3905 if (IS_ERR(new.bh)) {
3906 retval = PTR_ERR(new.bh);
3907 new.bh = NULL;
3908 goto end_rename;
3909 }
3910
3911 /* RENAME_EXCHANGE case: old *and* new must both exist */
3912 if (!new.bh || le32_to_cpu(new.de->inode) != new.inode->i_ino)
3913 goto end_rename;
3914
3915 handle = ext4_journal_start(old.dir, EXT4_HT_DIR,
3916 (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3917 2 * EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2));
3918 if (IS_ERR(handle)) {
3919 retval = PTR_ERR(handle);
3920 handle = NULL;
3921 goto end_rename;
3922 }
3923
3924 if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3925 ext4_handle_sync(handle);
3926
3927 if (S_ISDIR(old.inode->i_mode)) {
3928 old.is_dir = true;
3929 retval = ext4_rename_dir_prepare(handle, &old);
3930 if (retval)
3931 goto end_rename;
3932 }
3933 if (S_ISDIR(new.inode->i_mode)) {
3934 new.is_dir = true;
3935 retval = ext4_rename_dir_prepare(handle, &new);
3936 if (retval)
3937 goto end_rename;
3938 }
3939
3940 /*
3941 * Other than the special case of overwriting a directory, parents'
3942 * nlink only needs to be modified if this is a cross directory rename.
3943 */
3944 if (old.dir != new.dir && old.is_dir != new.is_dir) {
3945 old.dir_nlink_delta = old.is_dir ? -1 : 1;
3946 new.dir_nlink_delta = -old.dir_nlink_delta;
3947 retval = -EMLINK;
3948 if ((old.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(old.dir)) ||
3949 (new.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(new.dir)))
3950 goto end_rename;
3951 }
3952
3953 new_file_type = new.de->file_type;
3954 retval = ext4_setent(handle, &new, old.inode->i_ino, old.de->file_type);
3955 if (retval)
3956 goto end_rename;
3957
3958 retval = ext4_setent(handle, &old, new.inode->i_ino, new_file_type);
3959 if (retval)
3960 goto end_rename;
3961
3962 /*
3963 * Like most other Unix systems, set the ctime for inodes on a
3964 * rename.
3965 */
3966 ctime = current_time(old.inode);
3967 old.inode->i_ctime = ctime;
3968 new.inode->i_ctime = ctime;
3969 ext4_mark_inode_dirty(handle, old.inode);
3970 ext4_mark_inode_dirty(handle, new.inode);
3971
3972 if (old.dir_bh) {
3973 retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3974 if (retval)
3975 goto end_rename;
3976 }
3977 if (new.dir_bh) {
3978 retval = ext4_rename_dir_finish(handle, &new, old.dir->i_ino);
3979 if (retval)
3980 goto end_rename;
3981 }
3982 ext4_update_dir_count(handle, &old);
3983 ext4_update_dir_count(handle, &new);
3984 retval = 0;
3985
3986end_rename:
3987 brelse(old.dir_bh);
3988 brelse(new.dir_bh);
3989 brelse(old.bh);
3990 brelse(new.bh);
3991 if (handle)
3992 ext4_journal_stop(handle);
3993 return retval;
3994}
3995
3996static int ext4_rename2(struct inode *old_dir, struct dentry *old_dentry,
3997 struct inode *new_dir, struct dentry *new_dentry,
3998 unsigned int flags)
3999{
4000 int err;
4001
4002 if (unlikely(ext4_forced_shutdown(EXT4_SB(old_dir->i_sb))))
4003 return -EIO;
4004
4005 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4006 return -EINVAL;
4007
4008 err = fscrypt_prepare_rename(old_dir, old_dentry, new_dir, new_dentry,
4009 flags);
4010 if (err)
4011 return err;
4012
4013 if (flags & RENAME_EXCHANGE) {
4014 return ext4_cross_rename(old_dir, old_dentry,
4015 new_dir, new_dentry);
4016 }
4017
4018 return ext4_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
4019}
4020
4021/*
4022 * directories can handle most operations...
4023 */
4024const struct inode_operations ext4_dir_inode_operations = {
4025 .create = ext4_create,
4026 .lookup = ext4_lookup,
4027 .link = ext4_link,
4028 .unlink = ext4_unlink,
4029 .symlink = ext4_symlink,
4030 .mkdir = ext4_mkdir,
4031 .rmdir = ext4_rmdir,
4032 .mknod = ext4_mknod,
4033 .tmpfile = ext4_tmpfile,
4034 .rename = ext4_rename2,
4035 .setattr = ext4_setattr,
4036 .getattr = ext4_getattr,
4037 .listxattr = ext4_listxattr,
4038 .get_acl = ext4_get_acl,
4039 .set_acl = ext4_set_acl,
4040 .fiemap = ext4_fiemap,
4041};
4042
4043const struct inode_operations ext4_special_inode_operations = {
4044 .setattr = ext4_setattr,
4045 .getattr = ext4_getattr,
4046 .listxattr = ext4_listxattr,
4047 .get_acl = ext4_get_acl,
4048 .set_acl = ext4_set_acl,
4049};