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