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