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