1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * linux/fs/ext4/dir.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/dir.c 13 * 14 * Copyright (C) 1991, 1992 Linus Torvalds 15 * 16 * ext4 directory handling functions 17 * 18 * Big-endian to little-endian byte-swapping/bitmaps by 19 * David S. Miller (davem@caip.rutgers.edu), 1995 20 * 21 * Hash Tree Directory indexing (c) 2001 Daniel Phillips 22 * 23 */ 24 25 #include <linux/fs.h> 26 #include <linux/buffer_head.h> 27 #include <linux/filelock.h> 28 #include <linux/slab.h> 29 #include <linux/iversion.h> 30 #include <linux/unicode.h> 31 #include "ext4.h" 32 #include "xattr.h" 33 34 static int ext4_dx_readdir(struct file *, struct dir_context *); 35 36 /** 37 * is_dx_dir() - check if a directory is using htree indexing 38 * @inode: directory inode 39 * 40 * Check if the given dir-inode refers to an htree-indexed directory 41 * (or a directory which could potentially get converted to use htree 42 * indexing). 43 * 44 * Return 1 if it is a dx dir, 0 if not 45 */ 46 static int is_dx_dir(struct inode *inode) 47 { 48 struct super_block *sb = inode->i_sb; 49 50 if (ext4_has_feature_dir_index(inode->i_sb) && 51 ((ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) || 52 ((inode->i_size >> sb->s_blocksize_bits) == 1) || 53 ext4_has_inline_data(inode))) 54 return 1; 55 56 return 0; 57 } 58 59 static bool is_fake_dir_entry(struct ext4_dir_entry_2 *de) 60 { 61 /* Check if . or .. , or skip if namelen is 0 */ 62 if ((de->name_len > 0) && (de->name_len <= 2) && (de->name[0] == '.') && 63 (de->name[1] == '.' || de->name[1] == '\0')) 64 return true; 65 /* Check if this is a csum entry */ 66 if (de->file_type == EXT4_FT_DIR_CSUM) 67 return true; 68 return false; 69 } 70 71 /* 72 * Return 0 if the directory entry is OK, and 1 if there is a problem 73 * 74 * Note: this is the opposite of what ext2 and ext3 historically returned... 75 * 76 * bh passed here can be an inode block or a dir data block, depending 77 * on the inode inline data flag. 78 */ 79 int __ext4_check_dir_entry(const char *function, unsigned int line, 80 struct inode *dir, struct file *filp, 81 struct ext4_dir_entry_2 *de, 82 struct buffer_head *bh, char *buf, int size, 83 unsigned int offset) 84 { 85 const char *error_msg = NULL; 86 const int rlen = ext4_rec_len_from_disk(de->rec_len, 87 dir->i_sb->s_blocksize); 88 const int next_offset = ((char *) de - buf) + rlen; 89 bool fake = is_fake_dir_entry(de); 90 bool has_csum = ext4_has_feature_metadata_csum(dir->i_sb); 91 92 if (unlikely(rlen < ext4_dir_rec_len(1, fake ? NULL : dir))) 93 error_msg = "rec_len is smaller than minimal"; 94 else if (unlikely(rlen % 4 != 0)) 95 error_msg = "rec_len % 4 != 0"; 96 else if (unlikely(rlen < ext4_dir_rec_len(de->name_len, 97 fake ? NULL : dir))) 98 error_msg = "rec_len is too small for name_len"; 99 else if (unlikely(next_offset > size)) 100 error_msg = "directory entry overrun"; 101 else if (unlikely(next_offset > size - ext4_dir_rec_len(1, 102 has_csum ? NULL : dir) && 103 next_offset != size)) 104 error_msg = "directory entry too close to block end"; 105 else if (unlikely(le32_to_cpu(de->inode) > 106 le32_to_cpu(EXT4_SB(dir->i_sb)->s_es->s_inodes_count))) 107 error_msg = "inode out of bounds"; 108 else if (unlikely(next_offset == size && de->name_len == 1 && 109 de->name[0] == '.')) 110 error_msg = "'.' directory cannot be the last in data block"; 111 else 112 return 0; 113 114 if (filp) 115 ext4_error_file(filp, function, line, bh->b_blocknr, 116 "bad entry in directory: %s - offset=%u, " 117 "inode=%u, rec_len=%d, size=%d fake=%d", 118 error_msg, offset, le32_to_cpu(de->inode), 119 rlen, size, fake); 120 else 121 ext4_error_inode(dir, function, line, bh->b_blocknr, 122 "bad entry in directory: %s - offset=%u, " 123 "inode=%u, rec_len=%d, size=%d fake=%d", 124 error_msg, offset, le32_to_cpu(de->inode), 125 rlen, size, fake); 126 127 return 1; 128 } 129 130 static int ext4_readdir(struct file *file, struct dir_context *ctx) 131 { 132 unsigned int offset; 133 int i; 134 struct ext4_dir_entry_2 *de; 135 int err; 136 struct inode *inode = file_inode(file); 137 struct super_block *sb = inode->i_sb; 138 struct buffer_head *bh = NULL; 139 struct fscrypt_str fstr = FSTR_INIT(NULL, 0); 140 struct dir_private_info *info = file->private_data; 141 142 err = fscrypt_prepare_readdir(inode); 143 if (err) 144 return err; 145 146 if (is_dx_dir(inode)) { 147 err = ext4_dx_readdir(file, ctx); 148 if (err != ERR_BAD_DX_DIR) 149 return err; 150 151 /* Can we just clear INDEX flag to ignore htree information? */ 152 if (!ext4_has_feature_metadata_csum(sb)) { 153 /* 154 * We don't set the inode dirty flag since it's not 155 * critical that it gets flushed back to the disk. 156 */ 157 ext4_clear_inode_flag(inode, EXT4_INODE_INDEX); 158 } 159 } 160 161 if (ext4_has_inline_data(inode)) { 162 int has_inline_data = 1; 163 err = ext4_read_inline_dir(file, ctx, 164 &has_inline_data); 165 if (has_inline_data) 166 return err; 167 } 168 169 if (IS_ENCRYPTED(inode)) { 170 err = fscrypt_fname_alloc_buffer(EXT4_NAME_LEN, &fstr); 171 if (err < 0) 172 return err; 173 } 174 175 while (ctx->pos < inode->i_size) { 176 struct ext4_map_blocks map; 177 178 if (fatal_signal_pending(current)) { 179 err = -ERESTARTSYS; 180 goto errout; 181 } 182 cond_resched(); 183 offset = ctx->pos & (sb->s_blocksize - 1); 184 map.m_lblk = ctx->pos >> EXT4_BLOCK_SIZE_BITS(sb); 185 map.m_len = 1; 186 err = ext4_map_blocks(NULL, inode, &map, 0); 187 if (err == 0) { 188 /* m_len should never be zero but let's avoid 189 * an infinite loop if it somehow is */ 190 if (map.m_len == 0) 191 map.m_len = 1; 192 ctx->pos += map.m_len * sb->s_blocksize; 193 continue; 194 } 195 if (err > 0) { 196 pgoff_t index = map.m_pblk << inode->i_blkbits >> 197 PAGE_SHIFT; 198 if (!ra_has_index(&file->f_ra, index)) 199 page_cache_sync_readahead( 200 sb->s_bdev->bd_mapping, 201 &file->f_ra, file, index, 202 1 << EXT4_SB(sb)->s_min_folio_order); 203 file->f_ra.prev_pos = (loff_t)index << PAGE_SHIFT; 204 bh = ext4_bread(NULL, inode, map.m_lblk, 0); 205 if (IS_ERR(bh)) { 206 err = PTR_ERR(bh); 207 bh = NULL; 208 goto errout; 209 } 210 } 211 212 if (!bh) { 213 /* corrupt size? Maybe no more blocks to read */ 214 if (ctx->pos > inode->i_blocks << 9) 215 break; 216 ctx->pos += sb->s_blocksize - offset; 217 continue; 218 } 219 220 /* Check the checksum */ 221 if (!buffer_verified(bh) && 222 !ext4_dirblock_csum_verify(inode, bh)) { 223 EXT4_ERROR_FILE(file, 0, "directory fails checksum " 224 "at offset %llu", 225 (unsigned long long)ctx->pos); 226 ctx->pos += sb->s_blocksize - offset; 227 brelse(bh); 228 bh = NULL; 229 continue; 230 } 231 set_buffer_verified(bh); 232 233 /* If the dir block has changed since the last call to 234 * readdir(2), then we might be pointing to an invalid 235 * dirent right now. Scan from the start of the block 236 * to make sure. */ 237 if (!inode_eq_iversion(inode, info->cookie)) { 238 for (i = 0; i < sb->s_blocksize && i < offset; ) { 239 de = (struct ext4_dir_entry_2 *) 240 (bh->b_data + i); 241 /* It's too expensive to do a full 242 * dirent test each time round this 243 * loop, but we do have to test at 244 * least that it is non-zero. A 245 * failure will be detected in the 246 * dirent test below. */ 247 if (ext4_rec_len_from_disk(de->rec_len, 248 sb->s_blocksize) < ext4_dir_rec_len(1, 249 inode)) 250 break; 251 i += ext4_rec_len_from_disk(de->rec_len, 252 sb->s_blocksize); 253 } 254 offset = i; 255 ctx->pos = (ctx->pos & ~(sb->s_blocksize - 1)) 256 | offset; 257 info->cookie = inode_query_iversion(inode); 258 } 259 260 while (ctx->pos < inode->i_size 261 && offset < sb->s_blocksize) { 262 de = (struct ext4_dir_entry_2 *) (bh->b_data + offset); 263 if (ext4_check_dir_entry(inode, file, de, bh, 264 bh->b_data, bh->b_size, 265 offset)) { 266 /* 267 * On error, skip to the next block 268 */ 269 ctx->pos = (ctx->pos | 270 (sb->s_blocksize - 1)) + 1; 271 break; 272 } 273 offset += ext4_rec_len_from_disk(de->rec_len, 274 sb->s_blocksize); 275 if (le32_to_cpu(de->inode)) { 276 if (!IS_ENCRYPTED(inode)) { 277 if (!dir_emit(ctx, de->name, 278 de->name_len, 279 le32_to_cpu(de->inode), 280 get_dtype(sb, de->file_type))) 281 goto done; 282 } else { 283 int save_len = fstr.len; 284 struct fscrypt_str de_name = 285 FSTR_INIT(de->name, 286 de->name_len); 287 u32 hash; 288 u32 minor_hash; 289 290 if (IS_CASEFOLDED(inode)) { 291 hash = EXT4_DIRENT_HASH(de); 292 minor_hash = EXT4_DIRENT_MINOR_HASH(de); 293 } else { 294 hash = 0; 295 minor_hash = 0; 296 } 297 298 /* Directory is encrypted */ 299 err = fscrypt_fname_disk_to_usr(inode, 300 hash, minor_hash, &de_name, &fstr); 301 de_name = fstr; 302 fstr.len = save_len; 303 if (err) 304 goto errout; 305 if (!dir_emit(ctx, 306 de_name.name, de_name.len, 307 le32_to_cpu(de->inode), 308 get_dtype(sb, de->file_type))) 309 goto done; 310 } 311 } 312 ctx->pos += ext4_rec_len_from_disk(de->rec_len, 313 sb->s_blocksize); 314 } 315 if ((ctx->pos < inode->i_size) && !dir_relax_shared(inode)) 316 goto done; 317 brelse(bh); 318 bh = NULL; 319 } 320 done: 321 err = 0; 322 errout: 323 fscrypt_fname_free_buffer(&fstr); 324 brelse(bh); 325 return err; 326 } 327 328 static inline int is_32bit_api(void) 329 { 330 #ifdef CONFIG_COMPAT 331 return in_compat_syscall(); 332 #else 333 return (BITS_PER_LONG == 32); 334 #endif 335 } 336 337 /* 338 * These functions convert from the major/minor hash to an f_pos 339 * value for dx directories 340 * 341 * Upper layer (for example NFS) should specify FMODE_32BITHASH or 342 * FMODE_64BITHASH explicitly. On the other hand, we allow ext4 to be mounted 343 * directly on both 32-bit and 64-bit nodes, under such case, neither 344 * FMODE_32BITHASH nor FMODE_64BITHASH is specified. 345 */ 346 static inline loff_t hash2pos(struct file *filp, __u32 major, __u32 minor) 347 { 348 if ((filp->f_mode & FMODE_32BITHASH) || 349 (!(filp->f_mode & FMODE_64BITHASH) && is_32bit_api())) 350 return major >> 1; 351 else 352 return ((__u64)(major >> 1) << 32) | (__u64)minor; 353 } 354 355 static inline __u32 pos2maj_hash(struct file *filp, loff_t pos) 356 { 357 if ((filp->f_mode & FMODE_32BITHASH) || 358 (!(filp->f_mode & FMODE_64BITHASH) && is_32bit_api())) 359 return (pos << 1) & 0xffffffff; 360 else 361 return ((pos >> 32) << 1) & 0xffffffff; 362 } 363 364 static inline __u32 pos2min_hash(struct file *filp, loff_t pos) 365 { 366 if ((filp->f_mode & FMODE_32BITHASH) || 367 (!(filp->f_mode & FMODE_64BITHASH) && is_32bit_api())) 368 return 0; 369 else 370 return pos & 0xffffffff; 371 } 372 373 /* 374 * Return 32- or 64-bit end-of-file for dx directories 375 */ 376 static inline loff_t ext4_get_htree_eof(struct file *filp) 377 { 378 if ((filp->f_mode & FMODE_32BITHASH) || 379 (!(filp->f_mode & FMODE_64BITHASH) && is_32bit_api())) 380 return EXT4_HTREE_EOF_32BIT; 381 else 382 return EXT4_HTREE_EOF_64BIT; 383 } 384 385 386 /* 387 * ext4_dir_llseek() calls generic_file_llseek_size to handle htree 388 * directories, where the "offset" is in terms of the filename hash 389 * value instead of the byte offset. 390 * 391 * Because we may return a 64-bit hash that is well beyond offset limits, 392 * we need to pass the max hash as the maximum allowable offset in 393 * the htree directory case. 394 * 395 * For non-htree, ext4_llseek already chooses the proper max offset. 396 */ 397 static loff_t ext4_dir_llseek(struct file *file, loff_t offset, int whence) 398 { 399 struct inode *inode = file->f_mapping->host; 400 struct dir_private_info *info = file->private_data; 401 int dx_dir = is_dx_dir(inode); 402 loff_t ret, htree_max = ext4_get_htree_eof(file); 403 404 if (likely(dx_dir)) 405 ret = generic_file_llseek_size(file, offset, whence, 406 htree_max, htree_max); 407 else 408 ret = ext4_llseek(file, offset, whence); 409 info->cookie = inode_peek_iversion(inode) - 1; 410 return ret; 411 } 412 413 /* 414 * This structure holds the nodes of the red-black tree used to store 415 * the directory entry in hash order. 416 */ 417 struct fname { 418 __u32 hash; 419 __u32 minor_hash; 420 struct rb_node rb_hash; 421 struct fname *next; 422 __u32 inode; 423 __u8 name_len; 424 __u8 file_type; 425 char name[] __counted_by(name_len); 426 }; 427 428 /* 429 * This function implements a non-recursive way of freeing all of the 430 * nodes in the red-black tree. 431 */ 432 static void free_rb_tree_fname(struct rb_root *root) 433 { 434 struct fname *fname, *next; 435 436 rbtree_postorder_for_each_entry_safe(fname, next, root, rb_hash) 437 while (fname) { 438 struct fname *old = fname; 439 fname = fname->next; 440 kfree(old); 441 } 442 443 *root = RB_ROOT; 444 } 445 446 static void ext4_htree_init_dir_info(struct file *filp, loff_t pos) 447 { 448 struct dir_private_info *p = filp->private_data; 449 450 if (is_dx_dir(file_inode(filp)) && !p->initialized) { 451 p->curr_hash = pos2maj_hash(filp, pos); 452 p->curr_minor_hash = pos2min_hash(filp, pos); 453 p->initialized = true; 454 } 455 } 456 457 void ext4_htree_free_dir_info(struct dir_private_info *p) 458 { 459 free_rb_tree_fname(&p->root); 460 kfree(p); 461 } 462 463 /* 464 * Given a directory entry, enter it into the fname rb tree. 465 * 466 * When filename encryption is enabled, the dirent will hold the 467 * encrypted filename, while the htree will hold decrypted filename. 468 * The decrypted filename is passed in via ent_name. parameter. 469 */ 470 int ext4_htree_store_dirent(struct file *dir_file, __u32 hash, 471 __u32 minor_hash, 472 struct ext4_dir_entry_2 *dirent, 473 struct fscrypt_str *ent_name) 474 { 475 struct rb_node **p, *parent = NULL; 476 struct fname *fname, *new_fn; 477 struct dir_private_info *info; 478 479 info = dir_file->private_data; 480 p = &info->root.rb_node; 481 482 /* Create and allocate the fname structure */ 483 new_fn = kzalloc(struct_size(new_fn, name, ent_name->len + 1), 484 GFP_KERNEL); 485 if (!new_fn) 486 return -ENOMEM; 487 new_fn->hash = hash; 488 new_fn->minor_hash = minor_hash; 489 new_fn->inode = le32_to_cpu(dirent->inode); 490 new_fn->name_len = ent_name->len; 491 new_fn->file_type = dirent->file_type; 492 memcpy(new_fn->name, ent_name->name, ent_name->len); 493 494 while (*p) { 495 parent = *p; 496 fname = rb_entry(parent, struct fname, rb_hash); 497 498 /* 499 * If the hash and minor hash match up, then we put 500 * them on a linked list. This rarely happens... 501 */ 502 if ((new_fn->hash == fname->hash) && 503 (new_fn->minor_hash == fname->minor_hash)) { 504 new_fn->next = fname->next; 505 fname->next = new_fn; 506 return 0; 507 } 508 509 if (new_fn->hash < fname->hash) 510 p = &(*p)->rb_left; 511 else if (new_fn->hash > fname->hash) 512 p = &(*p)->rb_right; 513 else if (new_fn->minor_hash < fname->minor_hash) 514 p = &(*p)->rb_left; 515 else /* if (new_fn->minor_hash > fname->minor_hash) */ 516 p = &(*p)->rb_right; 517 } 518 519 rb_link_node(&new_fn->rb_hash, parent, p); 520 rb_insert_color(&new_fn->rb_hash, &info->root); 521 return 0; 522 } 523 524 525 526 /* 527 * This is a helper function for ext4_dx_readdir. It calls filldir 528 * for all entries on the fname linked list. (Normally there is only 529 * one entry on the linked list, unless there are 62 bit hash collisions.) 530 */ 531 static int call_filldir(struct file *file, struct dir_context *ctx, 532 struct fname *fname) 533 { 534 struct dir_private_info *info = file->private_data; 535 struct inode *inode = file_inode(file); 536 struct super_block *sb = inode->i_sb; 537 538 if (!fname) { 539 ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: comm %s: " 540 "called with null fname?!?", __func__, __LINE__, 541 inode->i_ino, current->comm); 542 return 0; 543 } 544 ctx->pos = hash2pos(file, fname->hash, fname->minor_hash); 545 while (fname) { 546 if (!dir_emit(ctx, fname->name, 547 fname->name_len, 548 fname->inode, 549 get_dtype(sb, fname->file_type))) { 550 info->extra_fname = fname; 551 return 1; 552 } 553 fname = fname->next; 554 } 555 return 0; 556 } 557 558 static int ext4_dx_readdir(struct file *file, struct dir_context *ctx) 559 { 560 struct dir_private_info *info = file->private_data; 561 struct inode *inode = file_inode(file); 562 struct fname *fname; 563 int ret = 0; 564 565 ext4_htree_init_dir_info(file, ctx->pos); 566 567 if (ctx->pos == ext4_get_htree_eof(file)) 568 return 0; /* EOF */ 569 570 /* Some one has messed with f_pos; reset the world */ 571 if (info->last_pos != ctx->pos) { 572 free_rb_tree_fname(&info->root); 573 info->curr_node = NULL; 574 info->extra_fname = NULL; 575 info->curr_hash = pos2maj_hash(file, ctx->pos); 576 info->curr_minor_hash = pos2min_hash(file, ctx->pos); 577 } 578 579 /* 580 * If there are any leftover names on the hash collision 581 * chain, return them first. 582 */ 583 if (info->extra_fname) { 584 if (call_filldir(file, ctx, info->extra_fname)) 585 goto finished; 586 info->extra_fname = NULL; 587 goto next_node; 588 } else if (!info->curr_node) 589 info->curr_node = rb_first(&info->root); 590 591 while (1) { 592 /* 593 * Fill the rbtree if we have no more entries, 594 * or the inode has changed since we last read in the 595 * cached entries. 596 */ 597 if ((!info->curr_node) || 598 !inode_eq_iversion(inode, info->cookie)) { 599 info->curr_node = NULL; 600 free_rb_tree_fname(&info->root); 601 info->cookie = inode_query_iversion(inode); 602 ret = ext4_htree_fill_tree(file, info->curr_hash, 603 info->curr_minor_hash, 604 &info->next_hash); 605 if (ret < 0) 606 goto finished; 607 if (ret == 0) { 608 ctx->pos = ext4_get_htree_eof(file); 609 break; 610 } 611 info->curr_node = rb_first(&info->root); 612 } 613 614 fname = rb_entry(info->curr_node, struct fname, rb_hash); 615 info->curr_hash = fname->hash; 616 info->curr_minor_hash = fname->minor_hash; 617 if (call_filldir(file, ctx, fname)) 618 break; 619 next_node: 620 info->curr_node = rb_next(info->curr_node); 621 if (info->curr_node) { 622 fname = rb_entry(info->curr_node, struct fname, 623 rb_hash); 624 info->curr_hash = fname->hash; 625 info->curr_minor_hash = fname->minor_hash; 626 } else { 627 if (info->next_hash == ~0) { 628 ctx->pos = ext4_get_htree_eof(file); 629 break; 630 } 631 info->curr_hash = info->next_hash; 632 info->curr_minor_hash = 0; 633 } 634 } 635 finished: 636 info->last_pos = ctx->pos; 637 return ret < 0 ? ret : 0; 638 } 639 640 static int ext4_release_dir(struct inode *inode, struct file *filp) 641 { 642 if (filp->private_data) 643 ext4_htree_free_dir_info(filp->private_data); 644 645 return 0; 646 } 647 648 int ext4_check_all_de(struct inode *dir, struct buffer_head *bh, void *buf, 649 int buf_size) 650 { 651 struct ext4_dir_entry_2 *de; 652 int rlen; 653 unsigned int offset = 0; 654 char *top; 655 656 de = buf; 657 top = buf + buf_size; 658 while ((char *) de < top) { 659 if (ext4_check_dir_entry(dir, NULL, de, bh, 660 buf, buf_size, offset)) 661 return -EFSCORRUPTED; 662 rlen = ext4_rec_len_from_disk(de->rec_len, buf_size); 663 de = (struct ext4_dir_entry_2 *)((char *)de + rlen); 664 offset += rlen; 665 } 666 if ((char *) de > top) 667 return -EFSCORRUPTED; 668 669 return 0; 670 } 671 672 static int ext4_dir_open(struct inode *inode, struct file *file) 673 { 674 struct dir_private_info *info; 675 676 info = kzalloc(sizeof(*info), GFP_KERNEL); 677 if (!info) 678 return -ENOMEM; 679 file->private_data = info; 680 return 0; 681 } 682 683 const struct file_operations ext4_dir_operations = { 684 .open = ext4_dir_open, 685 .llseek = ext4_dir_llseek, 686 .read = generic_read_dir, 687 .iterate_shared = ext4_readdir, 688 .unlocked_ioctl = ext4_ioctl, 689 #ifdef CONFIG_COMPAT 690 .compat_ioctl = ext4_compat_ioctl, 691 #endif 692 .fsync = ext4_sync_file, 693 .release = ext4_release_dir, 694 .setlease = generic_setlease, 695 }; 696