1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2017-2018 HUAWEI, Inc.
4 * https://www.huawei.com/
5 * Copyright (C) 2022, Alibaba Cloud
9 static int erofs_fill_dentries(struct inode *dir, struct dir_context *ctx,
10 void *dentry_blk, struct erofs_dirent *de,
11 unsigned int nameoff, unsigned int maxsize)
13 const struct erofs_dirent *end = dentry_blk + nameoff;
17 unsigned int de_namelen;
20 d_type = fs_ftype_to_dtype(de->file_type);
22 nameoff = le16_to_cpu(de->nameoff);
23 de_name = (char *)dentry_blk + nameoff;
25 /* the last dirent in the block? */
27 de_namelen = strnlen(de_name, maxsize - nameoff);
29 de_namelen = le16_to_cpu(de[1].nameoff) - nameoff;
31 /* a corrupted entry is found */
32 if (nameoff + de_namelen > maxsize ||
33 de_namelen > EROFS_NAME_LEN) {
34 erofs_err(dir->i_sb, "bogus dirent @ nid %llu",
40 if (!dir_emit(ctx, de_name, de_namelen,
41 le64_to_cpu(de->nid), d_type))
44 ctx->pos += sizeof(struct erofs_dirent);
49 static int erofs_readdir(struct file *f, struct dir_context *ctx)
51 struct inode *dir = file_inode(f);
52 struct erofs_buf buf = __EROFS_BUF_INITIALIZER;
53 struct super_block *sb = dir->i_sb;
54 unsigned long bsz = sb->s_blocksize;
55 const size_t dirsize = i_size_read(dir);
56 unsigned int i = erofs_blknr(sb, ctx->pos);
57 unsigned int ofs = erofs_blkoff(sb, ctx->pos);
62 while (ctx->pos < dirsize) {
63 struct erofs_dirent *de;
64 unsigned int nameoff, maxsize;
66 de = erofs_bread(&buf, i, EROFS_KMAP);
68 erofs_err(sb, "fail to readdir of logical block %u of nid %llu",
69 i, EROFS_I(dir)->nid);
74 nameoff = le16_to_cpu(de->nameoff);
75 if (nameoff < sizeof(struct erofs_dirent) || nameoff >= bsz) {
76 erofs_err(sb, "invalid de[0].nameoff %u @ nid %llu",
77 nameoff, EROFS_I(dir)->nid);
82 maxsize = min_t(unsigned int, dirsize - ctx->pos + ofs, bsz);
84 /* search dirents at the arbitrary position */
88 ofs = roundup(ofs, sizeof(struct erofs_dirent));
89 ctx->pos = erofs_pos(sb, i) + ofs;
94 err = erofs_fill_dentries(dir, ctx, de, (void *)de + ofs,
99 ctx->pos = erofs_pos(sb, i) + maxsize;
103 erofs_put_metabuf(&buf);
104 return err < 0 ? err : 0;
107 const struct file_operations erofs_dir_fops = {
108 .llseek = generic_file_llseek,
109 .read = generic_read_dir,
110 .iterate_shared = erofs_readdir,