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