xref: /linux/fs/ntfs3/inode.c (revision 1cf2704242180351d156fb48c334b319ae6b0759)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *
4  * Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
5  *
6  */
7 
8 #include <linux/buffer_head.h>
9 #include <linux/fs.h>
10 #include <linux/mpage.h>
11 #include <linux/namei.h>
12 #include <linux/nls.h>
13 #include <linux/uio.h>
14 #include <linux/writeback.h>
15 
16 #include "debug.h"
17 #include "ntfs.h"
18 #include "ntfs_fs.h"
19 
20 /*
21  * ntfs_read_mft - Read record and parses MFT.
22  */
23 static struct inode *ntfs_read_mft(struct inode *inode,
24 				   const struct cpu_str *name,
25 				   const struct MFT_REF *ref)
26 {
27 	int err = 0;
28 	struct ntfs_inode *ni = ntfs_i(inode);
29 	struct super_block *sb = inode->i_sb;
30 	struct ntfs_sb_info *sbi = sb->s_fs_info;
31 	mode_t mode = 0;
32 	struct ATTR_STD_INFO5 *std5 = NULL;
33 	struct ATTR_LIST_ENTRY *le;
34 	struct ATTRIB *attr;
35 	bool is_match = false;
36 	bool is_root = false;
37 	bool is_dir;
38 	unsigned long ino = inode->i_ino;
39 	u32 rp_fa = 0, asize, t32;
40 	u16 roff, rsize, names = 0;
41 	const struct ATTR_FILE_NAME *fname = NULL;
42 	const struct INDEX_ROOT *root;
43 	struct REPARSE_DATA_BUFFER rp; // 0x18 bytes
44 	u64 t64;
45 	struct MFT_REC *rec;
46 	struct runs_tree *run;
47 	struct timespec64 ts;
48 
49 	inode->i_op = NULL;
50 	/* Setup 'uid' and 'gid' */
51 	inode->i_uid = sbi->options->fs_uid;
52 	inode->i_gid = sbi->options->fs_gid;
53 
54 	err = mi_init(&ni->mi, sbi, ino);
55 	if (err)
56 		goto out;
57 
58 	if (!sbi->mft.ni && ino == MFT_REC_MFT && !sb->s_root) {
59 		t64 = sbi->mft.lbo >> sbi->cluster_bits;
60 		t32 = bytes_to_cluster(sbi, MFT_REC_VOL * sbi->record_size);
61 		sbi->mft.ni = ni;
62 		init_rwsem(&ni->file.run_lock);
63 
64 		if (!run_add_entry(&ni->file.run, 0, t64, t32, true)) {
65 			err = -ENOMEM;
66 			goto out;
67 		}
68 	}
69 
70 	err = mi_read(&ni->mi, ino == MFT_REC_MFT);
71 
72 	if (err)
73 		goto out;
74 
75 	rec = ni->mi.mrec;
76 
77 	if (sbi->flags & NTFS_FLAGS_LOG_REPLAYING) {
78 		;
79 	} else if (ref->seq != rec->seq) {
80 		err = -EINVAL;
81 		ntfs_err(sb, "MFT: r=%lx, expect seq=%x instead of %x!", ino,
82 			 le16_to_cpu(ref->seq), le16_to_cpu(rec->seq));
83 		goto out;
84 	} else if (!is_rec_inuse(rec)) {
85 		err = -ESTALE;
86 		ntfs_err(sb, "Inode r=%x is not in use!", (u32)ino);
87 		goto out;
88 	}
89 
90 	if (le32_to_cpu(rec->total) != sbi->record_size) {
91 		/* Bad inode? */
92 		err = -EINVAL;
93 		goto out;
94 	}
95 
96 	if (!is_rec_base(rec)) {
97 		err = -EINVAL;
98 		goto out;
99 	}
100 
101 	/* Record should contain $I30 root. */
102 	is_dir = rec->flags & RECORD_FLAG_DIR;
103 
104 	/* MFT_REC_MFT is not a dir */
105 	if (is_dir && ino == MFT_REC_MFT) {
106 		err = -EINVAL;
107 		goto out;
108 	}
109 
110 	inode->i_generation = le16_to_cpu(rec->seq);
111 
112 	/* Enumerate all struct Attributes MFT. */
113 	le = NULL;
114 	attr = NULL;
115 
116 	/*
117 	 * To reduce tab pressure use goto instead of
118 	 * while( (attr = ni_enum_attr_ex(ni, attr, &le, NULL) ))
119 	 */
120 next_attr:
121 	run = NULL;
122 	err = -EINVAL;
123 	attr = ni_enum_attr_ex(ni, attr, &le, NULL);
124 	if (!attr)
125 		goto end_enum;
126 
127 	if (le && le->vcn) {
128 		/* This is non primary attribute segment. Ignore if not MFT. */
129 		if (ino != MFT_REC_MFT || attr->type != ATTR_DATA)
130 			goto next_attr;
131 
132 		run = &ni->file.run;
133 		asize = le32_to_cpu(attr->size);
134 		goto attr_unpack_run;
135 	}
136 
137 	roff = attr->non_res ? 0 : le16_to_cpu(attr->res.data_off);
138 	rsize = attr->non_res ? 0 : le32_to_cpu(attr->res.data_size);
139 	asize = le32_to_cpu(attr->size);
140 
141 	/*
142 	 * Really this check was done in 'ni_enum_attr_ex' -> ... 'mi_enum_attr'.
143 	 * There not critical to check this case again
144 	 */
145 	if (attr->name_len &&
146 	    sizeof(short) * attr->name_len + le16_to_cpu(attr->name_off) >
147 		    asize)
148 		goto out;
149 
150 	if (attr->non_res) {
151 		t64 = le64_to_cpu(attr->nres.alloc_size);
152 		if (le64_to_cpu(attr->nres.data_size) > t64 ||
153 		    le64_to_cpu(attr->nres.valid_size) > t64)
154 			goto out;
155 	}
156 
157 	switch (attr->type) {
158 	case ATTR_STD:
159 		if (attr->non_res ||
160 		    asize < sizeof(struct ATTR_STD_INFO) + roff ||
161 		    rsize < sizeof(struct ATTR_STD_INFO))
162 			goto out;
163 
164 		if (std5)
165 			goto next_attr;
166 
167 		std5 = Add2Ptr(attr, roff);
168 
169 #ifdef STATX_BTIME
170 		nt2kernel(std5->cr_time, &ni->i_crtime);
171 #endif
172 		nt2kernel(std5->a_time, &ts);
173 		inode_set_atime_to_ts(inode, ts);
174 		nt2kernel(std5->c_time, &ts);
175 		inode_set_ctime_to_ts(inode, ts);
176 		nt2kernel(std5->m_time, &ts);
177 		inode_set_mtime_to_ts(inode, ts);
178 
179 		ni->std_fa = std5->fa;
180 
181 		if (asize >= sizeof(struct ATTR_STD_INFO5) + roff &&
182 		    rsize >= sizeof(struct ATTR_STD_INFO5))
183 			ni->std_security_id = std5->security_id;
184 		goto next_attr;
185 
186 	case ATTR_LIST:
187 		if (attr->name_len || le || ino == MFT_REC_LOG)
188 			goto out;
189 
190 		err = ntfs_load_attr_list(ni, attr);
191 		if (err)
192 			goto out;
193 
194 		le = NULL;
195 		attr = NULL;
196 		goto next_attr;
197 
198 	case ATTR_NAME:
199 		if (attr->non_res || asize < SIZEOF_ATTRIBUTE_FILENAME + roff ||
200 		    rsize < SIZEOF_ATTRIBUTE_FILENAME)
201 			goto out;
202 
203 		fname = Add2Ptr(attr, roff);
204 		if (fname->type == FILE_NAME_DOS)
205 			goto next_attr;
206 
207 		names += 1;
208 		if (name && name->len == fname->name_len &&
209 		    !ntfs_cmp_names_cpu(name, (struct le_str *)&fname->name_len,
210 					NULL, false))
211 			is_match = true;
212 
213 		goto next_attr;
214 
215 	case ATTR_DATA:
216 		if (is_dir) {
217 			/* Ignore data attribute in dir record. */
218 			goto next_attr;
219 		}
220 
221 		if (ino == MFT_REC_BADCLUST && !attr->non_res)
222 			goto next_attr;
223 
224 		if (attr->name_len &&
225 		    ((ino != MFT_REC_BADCLUST || !attr->non_res ||
226 		      attr->name_len != ARRAY_SIZE(BAD_NAME) ||
227 		      memcmp(attr_name(attr), BAD_NAME, sizeof(BAD_NAME))) &&
228 		     (ino != MFT_REC_SECURE || !attr->non_res ||
229 		      attr->name_len != ARRAY_SIZE(SDS_NAME) ||
230 		      memcmp(attr_name(attr), SDS_NAME, sizeof(SDS_NAME))))) {
231 			/* File contains stream attribute. Ignore it. */
232 			goto next_attr;
233 		}
234 
235 		if (is_attr_sparsed(attr))
236 			ni->std_fa |= FILE_ATTRIBUTE_SPARSE_FILE;
237 		else
238 			ni->std_fa &= ~FILE_ATTRIBUTE_SPARSE_FILE;
239 
240 		if (is_attr_compressed(attr))
241 			ni->std_fa |= FILE_ATTRIBUTE_COMPRESSED;
242 		else
243 			ni->std_fa &= ~FILE_ATTRIBUTE_COMPRESSED;
244 
245 		if (is_attr_encrypted(attr))
246 			ni->std_fa |= FILE_ATTRIBUTE_ENCRYPTED;
247 		else
248 			ni->std_fa &= ~FILE_ATTRIBUTE_ENCRYPTED;
249 
250 		if (!attr->non_res) {
251 			ni->i_valid = inode->i_size = rsize;
252 			inode_set_bytes(inode, rsize);
253 		}
254 
255 		mode = S_IFREG | (0777 & sbi->options->fs_fmask_inv);
256 
257 		if (!attr->non_res) {
258 			ni->ni_flags |= NI_FLAG_RESIDENT;
259 			goto next_attr;
260 		}
261 
262 		inode_set_bytes(inode, attr_ondisk_size(attr));
263 
264 		ni->i_valid = le64_to_cpu(attr->nres.valid_size);
265 		inode->i_size = le64_to_cpu(attr->nres.data_size);
266 		if (!attr->nres.alloc_size)
267 			goto next_attr;
268 
269 		run = ino == MFT_REC_BITMAP ? &sbi->used.bitmap.run :
270 					      &ni->file.run;
271 		break;
272 
273 	case ATTR_ROOT:
274 		if (attr->non_res)
275 			goto out;
276 
277 		root = Add2Ptr(attr, roff);
278 
279 		if (attr->name_len != ARRAY_SIZE(I30_NAME) ||
280 		    memcmp(attr_name(attr), I30_NAME, sizeof(I30_NAME)))
281 			goto next_attr;
282 
283 		if (root->type != ATTR_NAME ||
284 		    root->rule != NTFS_COLLATION_TYPE_FILENAME)
285 			goto out;
286 
287 		if (!is_dir)
288 			goto next_attr;
289 
290 		is_root = true;
291 		ni->ni_flags |= NI_FLAG_DIR;
292 
293 		err = indx_init(&ni->dir, sbi, attr, INDEX_MUTEX_I30);
294 		if (err)
295 			goto out;
296 
297 		mode = sb->s_root ?
298 			       (S_IFDIR | (0777 & sbi->options->fs_dmask_inv)) :
299 			       (S_IFDIR | 0777);
300 		goto next_attr;
301 
302 	case ATTR_ALLOC:
303 		if (!is_root || attr->name_len != ARRAY_SIZE(I30_NAME) ||
304 		    memcmp(attr_name(attr), I30_NAME, sizeof(I30_NAME)))
305 			goto next_attr;
306 
307 		inode->i_size = le64_to_cpu(attr->nres.data_size);
308 		ni->i_valid = le64_to_cpu(attr->nres.valid_size);
309 		inode_set_bytes(inode, le64_to_cpu(attr->nres.alloc_size));
310 
311 		run = &ni->dir.alloc_run;
312 		break;
313 
314 	case ATTR_BITMAP:
315 		if (ino == MFT_REC_MFT) {
316 			if (!attr->non_res)
317 				goto out;
318 #ifndef CONFIG_NTFS3_64BIT_CLUSTER
319 			/* 0x20000000 = 2^32 / 8 */
320 			if (le64_to_cpu(attr->nres.alloc_size) >= 0x20000000)
321 				goto out;
322 #endif
323 			run = &sbi->mft.bitmap.run;
324 			break;
325 		} else if (is_dir && attr->name_len == ARRAY_SIZE(I30_NAME) &&
326 			   !memcmp(attr_name(attr), I30_NAME,
327 				   sizeof(I30_NAME)) &&
328 			   attr->non_res) {
329 			run = &ni->dir.bitmap_run;
330 			break;
331 		}
332 		goto next_attr;
333 
334 	case ATTR_REPARSE:
335 		if (attr->name_len)
336 			goto next_attr;
337 
338 		rp_fa = ni_parse_reparse(ni, attr, &rp);
339 		switch (rp_fa) {
340 		case REPARSE_LINK:
341 			/*
342 			 * Normal symlink.
343 			 * Assume one unicode symbol == one utf8.
344 			 */
345 			inode->i_size = le16_to_cpu(rp.SymbolicLinkReparseBuffer
346 							    .PrintNameLength) /
347 					sizeof(u16);
348 			ni->i_valid = inode->i_size;
349 			/* Clear directory bit. */
350 			if (ni->ni_flags & NI_FLAG_DIR) {
351 				indx_clear(&ni->dir);
352 				memset(&ni->dir, 0, sizeof(ni->dir));
353 				ni->ni_flags &= ~NI_FLAG_DIR;
354 			} else {
355 				run_close(&ni->file.run);
356 			}
357 			mode = S_IFLNK | 0777;
358 			is_dir = false;
359 			if (attr->non_res) {
360 				run = &ni->file.run;
361 				goto attr_unpack_run; // Double break.
362 			}
363 			break;
364 
365 		case REPARSE_COMPRESSED:
366 			break;
367 
368 		case REPARSE_DEDUPLICATED:
369 			break;
370 		}
371 		goto next_attr;
372 
373 	case ATTR_EA_INFO:
374 		if (!attr->name_len &&
375 		    resident_data_ex(attr, sizeof(struct EA_INFO))) {
376 			ni->ni_flags |= NI_FLAG_EA;
377 			/*
378 			 * ntfs_get_wsl_perm updates inode->i_uid, inode->i_gid, inode->i_mode
379 			 */
380 			inode->i_mode = mode;
381 			ntfs_get_wsl_perm(inode);
382 			mode = inode->i_mode;
383 		}
384 		goto next_attr;
385 
386 	default:
387 		goto next_attr;
388 	}
389 
390 attr_unpack_run:
391 	roff = le16_to_cpu(attr->nres.run_off);
392 
393 	if (roff > asize) {
394 		err = -EINVAL;
395 		goto out;
396 	}
397 
398 	t64 = le64_to_cpu(attr->nres.svcn);
399 
400 	err = run_unpack_ex(run, sbi, ino, t64, le64_to_cpu(attr->nres.evcn),
401 			    t64, Add2Ptr(attr, roff), asize - roff);
402 	if (err < 0)
403 		goto out;
404 	err = 0;
405 	goto next_attr;
406 
407 end_enum:
408 
409 	if (!std5)
410 		goto out;
411 
412 	if (!is_match && name) {
413 		err = -ENOENT;
414 		goto out;
415 	}
416 
417 	if (std5->fa & FILE_ATTRIBUTE_READONLY)
418 		mode &= ~0222;
419 
420 	if (!names) {
421 		err = -EINVAL;
422 		goto out;
423 	}
424 
425 	if (names != le16_to_cpu(rec->hard_links)) {
426 		/* Correct minor error on the fly. Do not mark inode as dirty. */
427 		ntfs_inode_warn(inode, "Correct links count -> %u.", names);
428 		rec->hard_links = cpu_to_le16(names);
429 		ni->mi.dirty = true;
430 	}
431 
432 	set_nlink(inode, names);
433 
434 	if (S_ISDIR(mode)) {
435 		ni->std_fa |= FILE_ATTRIBUTE_DIRECTORY;
436 
437 		/*
438 		 * Dot and dot-dot should be included in count but was not
439 		 * included in enumeration.
440 		 * Usually a hard links to directories are disabled.
441 		 */
442 		inode->i_op = &ntfs_dir_inode_operations;
443 		if (is_legacy_ntfs(inode->i_sb))
444 			inode->i_fop = &ntfs_legacy_dir_operations;
445 		else
446 			inode->i_fop = &ntfs_dir_operations;
447 		ni->i_valid = 0;
448 	} else if (S_ISLNK(mode)) {
449 		ni->std_fa &= ~FILE_ATTRIBUTE_DIRECTORY;
450 		inode->i_op = &ntfs_link_inode_operations;
451 		inode->i_fop = NULL;
452 		inode_nohighmem(inode);
453 	} else if (S_ISREG(mode)) {
454 		ni->std_fa &= ~FILE_ATTRIBUTE_DIRECTORY;
455 		inode->i_op = &ntfs_file_inode_operations;
456 		if (is_legacy_ntfs(inode->i_sb))
457 			inode->i_fop = &ntfs_legacy_file_operations;
458 		else
459 			inode->i_fop = &ntfs_file_operations;
460 		inode->i_mapping->a_ops = is_compressed(ni) ? &ntfs_aops_cmpr :
461 							      &ntfs_aops;
462 		if (ino != MFT_REC_MFT)
463 			init_rwsem(&ni->file.run_lock);
464 	} else if (S_ISCHR(mode) || S_ISBLK(mode) || S_ISFIFO(mode) ||
465 		   S_ISSOCK(mode)) {
466 		inode->i_op = &ntfs_special_inode_operations;
467 		init_special_inode(inode, mode, inode->i_rdev);
468 	} else if (fname && fname->home.low == cpu_to_le32(MFT_REC_EXTEND) &&
469 		   fname->home.seq == cpu_to_le16(MFT_REC_EXTEND)) {
470 		/* Records in $Extend are not a files or general directories. */
471 		inode->i_op = &ntfs_file_inode_operations;
472 	} else {
473 		err = -EINVAL;
474 		goto out;
475 	}
476 
477 	if ((sbi->options->sys_immutable &&
478 	     (std5->fa & FILE_ATTRIBUTE_SYSTEM)) &&
479 	    !S_ISFIFO(mode) && !S_ISSOCK(mode) && !S_ISLNK(mode)) {
480 		inode->i_flags |= S_IMMUTABLE;
481 	} else {
482 		inode->i_flags &= ~S_IMMUTABLE;
483 	}
484 
485 	inode->i_mode = mode;
486 	if (!(ni->ni_flags & NI_FLAG_EA)) {
487 		/* If no xattr then no security (stored in xattr). */
488 		inode->i_flags |= S_NOSEC;
489 	}
490 
491 	if (ino == MFT_REC_MFT && !sb->s_root)
492 		sbi->mft.ni = NULL;
493 
494 	unlock_new_inode(inode);
495 
496 	return inode;
497 
498 out:
499 	if (ino == MFT_REC_MFT && !sb->s_root)
500 		sbi->mft.ni = NULL;
501 
502 	iget_failed(inode);
503 	return ERR_PTR(err);
504 }
505 
506 /*
507  * ntfs_test_inode
508  *
509  * Return: 1 if match.
510  */
511 static int ntfs_test_inode(struct inode *inode, void *data)
512 {
513 	struct MFT_REF *ref = data;
514 
515 	return ino_get(ref) == inode->i_ino;
516 }
517 
518 static int ntfs_set_inode(struct inode *inode, void *data)
519 {
520 	const struct MFT_REF *ref = data;
521 
522 	inode->i_ino = ino_get(ref);
523 	return 0;
524 }
525 
526 struct inode *ntfs_iget5(struct super_block *sb, const struct MFT_REF *ref,
527 			 const struct cpu_str *name)
528 {
529 	struct inode *inode;
530 
531 	inode = iget5_locked(sb, ino_get(ref), ntfs_test_inode, ntfs_set_inode,
532 			     (void *)ref);
533 	if (unlikely(!inode))
534 		return ERR_PTR(-ENOMEM);
535 
536 	/* If this is a freshly allocated inode, need to read it now. */
537 	if (inode->i_state & I_NEW)
538 		inode = ntfs_read_mft(inode, name, ref);
539 	else if (ref->seq != ntfs_i(inode)->mi.mrec->seq) {
540 		/* Inode overlaps? */
541 		_ntfs_bad_inode(inode);
542 	}
543 
544 	if (IS_ERR(inode) && name)
545 		ntfs_set_state(sb->s_fs_info, NTFS_DIRTY_ERROR);
546 
547 	return inode;
548 }
549 
550 enum get_block_ctx {
551 	GET_BLOCK_GENERAL = 0,
552 	GET_BLOCK_WRITE_BEGIN = 1,
553 	GET_BLOCK_DIRECT_IO_R = 2,
554 	GET_BLOCK_DIRECT_IO_W = 3,
555 	GET_BLOCK_BMAP = 4,
556 };
557 
558 static noinline int ntfs_get_block_vbo(struct inode *inode, u64 vbo,
559 				       struct buffer_head *bh, int create,
560 				       enum get_block_ctx ctx)
561 {
562 	struct super_block *sb = inode->i_sb;
563 	struct ntfs_sb_info *sbi = sb->s_fs_info;
564 	struct ntfs_inode *ni = ntfs_i(inode);
565 	struct folio *folio = bh->b_folio;
566 	u8 cluster_bits = sbi->cluster_bits;
567 	u32 block_size = sb->s_blocksize;
568 	u64 bytes, lbo, valid;
569 	u32 off;
570 	int err;
571 	CLST vcn, lcn, len;
572 	bool new;
573 
574 	/* Clear previous state. */
575 	clear_buffer_new(bh);
576 	clear_buffer_uptodate(bh);
577 
578 	if (is_resident(ni)) {
579 		ni_lock(ni);
580 		err = attr_data_read_resident(ni, &folio->page);
581 		ni_unlock(ni);
582 
583 		if (!err)
584 			set_buffer_uptodate(bh);
585 		bh->b_size = block_size;
586 		return err;
587 	}
588 
589 	vcn = vbo >> cluster_bits;
590 	off = vbo & sbi->cluster_mask;
591 	new = false;
592 
593 	err = attr_data_get_block(ni, vcn, 1, &lcn, &len, create ? &new : NULL,
594 				  create && sbi->cluster_size > PAGE_SIZE);
595 	if (err)
596 		goto out;
597 
598 	if (!len)
599 		return 0;
600 
601 	bytes = ((u64)len << cluster_bits) - off;
602 
603 	if (lcn == SPARSE_LCN) {
604 		if (!create) {
605 			if (bh->b_size > bytes)
606 				bh->b_size = bytes;
607 			return 0;
608 		}
609 		WARN_ON(1);
610 	}
611 
612 	if (new)
613 		set_buffer_new(bh);
614 
615 	lbo = ((u64)lcn << cluster_bits) + off;
616 
617 	set_buffer_mapped(bh);
618 	bh->b_bdev = sb->s_bdev;
619 	bh->b_blocknr = lbo >> sb->s_blocksize_bits;
620 
621 	valid = ni->i_valid;
622 
623 	if (ctx == GET_BLOCK_DIRECT_IO_W) {
624 		/* ntfs_direct_IO will update ni->i_valid. */
625 		if (vbo >= valid)
626 			set_buffer_new(bh);
627 	} else if (create) {
628 		/* Normal write. */
629 		if (bytes > bh->b_size)
630 			bytes = bh->b_size;
631 
632 		if (vbo >= valid)
633 			set_buffer_new(bh);
634 
635 		if (vbo + bytes > valid) {
636 			ni->i_valid = vbo + bytes;
637 			mark_inode_dirty(inode);
638 		}
639 	} else if (vbo >= valid) {
640 		/* Read out of valid data. */
641 		clear_buffer_mapped(bh);
642 	} else if (vbo + bytes <= valid) {
643 		/* Normal read. */
644 	} else if (vbo + block_size <= valid) {
645 		/* Normal short read. */
646 		bytes = block_size;
647 	} else {
648 		/*
649 		 * Read across valid size: vbo < valid && valid < vbo + block_size
650 		 */
651 		bytes = block_size;
652 
653 		if (folio) {
654 			u32 voff = valid - vbo;
655 
656 			bh->b_size = block_size;
657 			off = vbo & (PAGE_SIZE - 1);
658 			folio_set_bh(bh, folio, off);
659 
660 			if (bh_read(bh, 0) < 0) {
661 				err = -EIO;
662 				goto out;
663 			}
664 			folio_zero_segment(folio, off + voff, off + block_size);
665 		}
666 	}
667 
668 	if (bh->b_size > bytes)
669 		bh->b_size = bytes;
670 
671 #ifndef __LP64__
672 	if (ctx == GET_BLOCK_DIRECT_IO_W || ctx == GET_BLOCK_DIRECT_IO_R) {
673 		static_assert(sizeof(size_t) < sizeof(loff_t));
674 		if (bytes > 0x40000000u)
675 			bh->b_size = 0x40000000u;
676 	}
677 #endif
678 
679 	return 0;
680 
681 out:
682 	return err;
683 }
684 
685 int ntfs_get_block(struct inode *inode, sector_t vbn,
686 		   struct buffer_head *bh_result, int create)
687 {
688 	return ntfs_get_block_vbo(inode, (u64)vbn << inode->i_blkbits,
689 				  bh_result, create, GET_BLOCK_GENERAL);
690 }
691 
692 static int ntfs_get_block_bmap(struct inode *inode, sector_t vsn,
693 			       struct buffer_head *bh_result, int create)
694 {
695 	return ntfs_get_block_vbo(inode,
696 				  (u64)vsn << inode->i_sb->s_blocksize_bits,
697 				  bh_result, create, GET_BLOCK_BMAP);
698 }
699 
700 static sector_t ntfs_bmap(struct address_space *mapping, sector_t block)
701 {
702 	return generic_block_bmap(mapping, block, ntfs_get_block_bmap);
703 }
704 
705 static int ntfs_read_folio(struct file *file, struct folio *folio)
706 {
707 	struct page *page = &folio->page;
708 	int err;
709 	struct address_space *mapping = page->mapping;
710 	struct inode *inode = mapping->host;
711 	struct ntfs_inode *ni = ntfs_i(inode);
712 
713 	if (is_resident(ni)) {
714 		ni_lock(ni);
715 		err = attr_data_read_resident(ni, page);
716 		ni_unlock(ni);
717 		if (err != E_NTFS_NONRESIDENT) {
718 			unlock_page(page);
719 			return err;
720 		}
721 	}
722 
723 	if (is_compressed(ni)) {
724 		ni_lock(ni);
725 		err = ni_readpage_cmpr(ni, page);
726 		ni_unlock(ni);
727 		return err;
728 	}
729 
730 	/* Normal + sparse files. */
731 	return mpage_read_folio(folio, ntfs_get_block);
732 }
733 
734 static void ntfs_readahead(struct readahead_control *rac)
735 {
736 	struct address_space *mapping = rac->mapping;
737 	struct inode *inode = mapping->host;
738 	struct ntfs_inode *ni = ntfs_i(inode);
739 	u64 valid;
740 	loff_t pos;
741 
742 	if (is_resident(ni)) {
743 		/* No readahead for resident. */
744 		return;
745 	}
746 
747 	if (is_compressed(ni)) {
748 		/* No readahead for compressed. */
749 		return;
750 	}
751 
752 	valid = ni->i_valid;
753 	pos = readahead_pos(rac);
754 
755 	if (valid < i_size_read(inode) && pos <= valid &&
756 	    valid < pos + readahead_length(rac)) {
757 		/* Range cross 'valid'. Read it page by page. */
758 		return;
759 	}
760 
761 	mpage_readahead(rac, ntfs_get_block);
762 }
763 
764 static int ntfs_get_block_direct_IO_R(struct inode *inode, sector_t iblock,
765 				      struct buffer_head *bh_result, int create)
766 {
767 	return ntfs_get_block_vbo(inode, (u64)iblock << inode->i_blkbits,
768 				  bh_result, create, GET_BLOCK_DIRECT_IO_R);
769 }
770 
771 static int ntfs_get_block_direct_IO_W(struct inode *inode, sector_t iblock,
772 				      struct buffer_head *bh_result, int create)
773 {
774 	return ntfs_get_block_vbo(inode, (u64)iblock << inode->i_blkbits,
775 				  bh_result, create, GET_BLOCK_DIRECT_IO_W);
776 }
777 
778 static ssize_t ntfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
779 {
780 	struct file *file = iocb->ki_filp;
781 	struct address_space *mapping = file->f_mapping;
782 	struct inode *inode = mapping->host;
783 	struct ntfs_inode *ni = ntfs_i(inode);
784 	loff_t vbo = iocb->ki_pos;
785 	loff_t end;
786 	int wr = iov_iter_rw(iter) & WRITE;
787 	size_t iter_count = iov_iter_count(iter);
788 	loff_t valid;
789 	ssize_t ret;
790 
791 	if (is_resident(ni)) {
792 		/* Switch to buffered write. */
793 		ret = 0;
794 		goto out;
795 	}
796 
797 	ret = blockdev_direct_IO(iocb, inode, iter,
798 				 wr ? ntfs_get_block_direct_IO_W :
799 				      ntfs_get_block_direct_IO_R);
800 
801 	if (ret > 0)
802 		end = vbo + ret;
803 	else if (wr && ret == -EIOCBQUEUED)
804 		end = vbo + iter_count;
805 	else
806 		goto out;
807 
808 	valid = ni->i_valid;
809 	if (wr) {
810 		if (end > valid && !S_ISBLK(inode->i_mode)) {
811 			ni->i_valid = end;
812 			mark_inode_dirty(inode);
813 		}
814 	} else if (vbo < valid && valid < end) {
815 		/* Fix page. */
816 		iov_iter_revert(iter, end - valid);
817 		iov_iter_zero(end - valid, iter);
818 	}
819 
820 out:
821 	return ret;
822 }
823 
824 int ntfs_set_size(struct inode *inode, u64 new_size)
825 {
826 	struct super_block *sb = inode->i_sb;
827 	struct ntfs_sb_info *sbi = sb->s_fs_info;
828 	struct ntfs_inode *ni = ntfs_i(inode);
829 	int err;
830 
831 	/* Check for maximum file size. */
832 	if (is_sparsed(ni) || is_compressed(ni)) {
833 		if (new_size > sbi->maxbytes_sparse) {
834 			err = -EFBIG;
835 			goto out;
836 		}
837 	} else if (new_size > sbi->maxbytes) {
838 		err = -EFBIG;
839 		goto out;
840 	}
841 
842 	ni_lock(ni);
843 	down_write(&ni->file.run_lock);
844 
845 	err = attr_set_size(ni, ATTR_DATA, NULL, 0, &ni->file.run, new_size,
846 			    &ni->i_valid, true, NULL);
847 
848 	up_write(&ni->file.run_lock);
849 	ni_unlock(ni);
850 
851 	mark_inode_dirty(inode);
852 
853 out:
854 	return err;
855 }
856 
857 static int ntfs_resident_writepage(struct folio *folio,
858 				   struct writeback_control *wbc, void *data)
859 {
860 	struct address_space *mapping = data;
861 	struct inode *inode = mapping->host;
862 	struct ntfs_inode *ni = ntfs_i(inode);
863 	int ret;
864 
865 	if (unlikely(ntfs3_forced_shutdown(inode->i_sb)))
866 		return -EIO;
867 
868 	ni_lock(ni);
869 	ret = attr_data_write_resident(ni, &folio->page);
870 	ni_unlock(ni);
871 
872 	if (ret != E_NTFS_NONRESIDENT)
873 		folio_unlock(folio);
874 	mapping_set_error(mapping, ret);
875 	return ret;
876 }
877 
878 static int ntfs_writepages(struct address_space *mapping,
879 			   struct writeback_control *wbc)
880 {
881 	struct inode *inode = mapping->host;
882 
883 	if (unlikely(ntfs3_forced_shutdown(inode->i_sb)))
884 		return -EIO;
885 
886 	if (is_resident(ntfs_i(inode)))
887 		return write_cache_pages(mapping, wbc, ntfs_resident_writepage,
888 					 mapping);
889 	return mpage_writepages(mapping, wbc, ntfs_get_block);
890 }
891 
892 static int ntfs_get_block_write_begin(struct inode *inode, sector_t vbn,
893 				      struct buffer_head *bh_result, int create)
894 {
895 	return ntfs_get_block_vbo(inode, (u64)vbn << inode->i_blkbits,
896 				  bh_result, create, GET_BLOCK_WRITE_BEGIN);
897 }
898 
899 int ntfs_write_begin(struct file *file, struct address_space *mapping,
900 		     loff_t pos, u32 len, struct page **pagep, void **fsdata)
901 {
902 	int err;
903 	struct inode *inode = mapping->host;
904 	struct ntfs_inode *ni = ntfs_i(inode);
905 
906 	if (unlikely(ntfs3_forced_shutdown(inode->i_sb)))
907 		return -EIO;
908 
909 	*pagep = NULL;
910 	if (is_resident(ni)) {
911 		struct page *page =
912 			grab_cache_page_write_begin(mapping, pos >> PAGE_SHIFT);
913 
914 		if (!page) {
915 			err = -ENOMEM;
916 			goto out;
917 		}
918 
919 		ni_lock(ni);
920 		err = attr_data_read_resident(ni, page);
921 		ni_unlock(ni);
922 
923 		if (!err) {
924 			*pagep = page;
925 			goto out;
926 		}
927 		unlock_page(page);
928 		put_page(page);
929 
930 		if (err != E_NTFS_NONRESIDENT)
931 			goto out;
932 	}
933 
934 	err = block_write_begin(mapping, pos, len, pagep,
935 				ntfs_get_block_write_begin);
936 
937 out:
938 	return err;
939 }
940 
941 /*
942  * ntfs_write_end - Address_space_operations::write_end.
943  */
944 int ntfs_write_end(struct file *file, struct address_space *mapping, loff_t pos,
945 		   u32 len, u32 copied, struct page *page, void *fsdata)
946 {
947 	struct inode *inode = mapping->host;
948 	struct ntfs_inode *ni = ntfs_i(inode);
949 	u64 valid = ni->i_valid;
950 	bool dirty = false;
951 	int err;
952 
953 	if (is_resident(ni)) {
954 		ni_lock(ni);
955 		err = attr_data_write_resident(ni, page);
956 		ni_unlock(ni);
957 		if (!err) {
958 			dirty = true;
959 			/* Clear any buffers in page. */
960 			if (page_has_buffers(page)) {
961 				struct buffer_head *head, *bh;
962 
963 				bh = head = page_buffers(page);
964 				do {
965 					clear_buffer_dirty(bh);
966 					clear_buffer_mapped(bh);
967 					set_buffer_uptodate(bh);
968 				} while (head != (bh = bh->b_this_page));
969 			}
970 			SetPageUptodate(page);
971 			err = copied;
972 		}
973 		unlock_page(page);
974 		put_page(page);
975 	} else {
976 		err = generic_write_end(file, mapping, pos, len, copied, page,
977 					fsdata);
978 	}
979 
980 	if (err >= 0) {
981 		if (!(ni->std_fa & FILE_ATTRIBUTE_ARCHIVE)) {
982 			inode_set_mtime_to_ts(inode,
983 					      inode_set_ctime_current(inode));
984 			ni->std_fa |= FILE_ATTRIBUTE_ARCHIVE;
985 			dirty = true;
986 		}
987 
988 		if (valid != ni->i_valid) {
989 			/* ni->i_valid is changed in ntfs_get_block_vbo. */
990 			dirty = true;
991 		}
992 
993 		if (pos + err > inode->i_size) {
994 			i_size_write(inode, pos + err);
995 			dirty = true;
996 		}
997 
998 		if (dirty)
999 			mark_inode_dirty(inode);
1000 	}
1001 
1002 	return err;
1003 }
1004 
1005 int reset_log_file(struct inode *inode)
1006 {
1007 	int err;
1008 	loff_t pos = 0;
1009 	u32 log_size = inode->i_size;
1010 	struct address_space *mapping = inode->i_mapping;
1011 
1012 	for (;;) {
1013 		u32 len;
1014 		void *kaddr;
1015 		struct page *page;
1016 
1017 		len = pos + PAGE_SIZE > log_size ? (log_size - pos) : PAGE_SIZE;
1018 
1019 		err = block_write_begin(mapping, pos, len, &page,
1020 					ntfs_get_block_write_begin);
1021 		if (err)
1022 			goto out;
1023 
1024 		kaddr = kmap_atomic(page);
1025 		memset(kaddr, -1, len);
1026 		kunmap_atomic(kaddr);
1027 		flush_dcache_page(page);
1028 
1029 		err = block_write_end(NULL, mapping, pos, len, len, page, NULL);
1030 		if (err < 0)
1031 			goto out;
1032 		pos += len;
1033 
1034 		if (pos >= log_size)
1035 			break;
1036 		balance_dirty_pages_ratelimited(mapping);
1037 	}
1038 out:
1039 	mark_inode_dirty_sync(inode);
1040 
1041 	return err;
1042 }
1043 
1044 int ntfs3_write_inode(struct inode *inode, struct writeback_control *wbc)
1045 {
1046 	return _ni_write_inode(inode, wbc->sync_mode == WB_SYNC_ALL);
1047 }
1048 
1049 int ntfs_sync_inode(struct inode *inode)
1050 {
1051 	return _ni_write_inode(inode, 1);
1052 }
1053 
1054 /*
1055  * writeback_inode - Helper function for ntfs_flush_inodes().
1056  *
1057  * This writes both the inode and the file data blocks, waiting
1058  * for in flight data blocks before the start of the call.  It
1059  * does not wait for any io started during the call.
1060  */
1061 static int writeback_inode(struct inode *inode)
1062 {
1063 	int ret = sync_inode_metadata(inode, 0);
1064 
1065 	if (!ret)
1066 		ret = filemap_fdatawrite(inode->i_mapping);
1067 	return ret;
1068 }
1069 
1070 /*
1071  * ntfs_flush_inodes
1072  *
1073  * Write data and metadata corresponding to i1 and i2.  The io is
1074  * started but we do not wait for any of it to finish.
1075  *
1076  * filemap_flush() is used for the block device, so if there is a dirty
1077  * page for a block already in flight, we will not wait and start the
1078  * io over again.
1079  */
1080 int ntfs_flush_inodes(struct super_block *sb, struct inode *i1,
1081 		      struct inode *i2)
1082 {
1083 	int ret = 0;
1084 
1085 	if (i1)
1086 		ret = writeback_inode(i1);
1087 	if (!ret && i2)
1088 		ret = writeback_inode(i2);
1089 	if (!ret)
1090 		ret = sync_blockdev_nowait(sb->s_bdev);
1091 	return ret;
1092 }
1093 
1094 int inode_write_data(struct inode *inode, const void *data, size_t bytes)
1095 {
1096 	pgoff_t idx;
1097 
1098 	/* Write non resident data. */
1099 	for (idx = 0; bytes; idx++) {
1100 		size_t op = bytes > PAGE_SIZE ? PAGE_SIZE : bytes;
1101 		struct page *page = ntfs_map_page(inode->i_mapping, idx);
1102 
1103 		if (IS_ERR(page))
1104 			return PTR_ERR(page);
1105 
1106 		lock_page(page);
1107 		WARN_ON(!PageUptodate(page));
1108 		ClearPageUptodate(page);
1109 
1110 		memcpy(page_address(page), data, op);
1111 
1112 		flush_dcache_page(page);
1113 		SetPageUptodate(page);
1114 		unlock_page(page);
1115 
1116 		ntfs_unmap_page(page);
1117 
1118 		bytes -= op;
1119 		data = Add2Ptr(data, PAGE_SIZE);
1120 	}
1121 	return 0;
1122 }
1123 
1124 /*
1125  * ntfs_reparse_bytes
1126  *
1127  * Number of bytes for REPARSE_DATA_BUFFER(IO_REPARSE_TAG_SYMLINK)
1128  * for unicode string of @uni_len length.
1129  */
1130 static inline u32 ntfs_reparse_bytes(u32 uni_len)
1131 {
1132 	/* Header + unicode string + decorated unicode string. */
1133 	return sizeof(short) * (2 * uni_len + 4) +
1134 	       offsetof(struct REPARSE_DATA_BUFFER,
1135 			SymbolicLinkReparseBuffer.PathBuffer);
1136 }
1137 
1138 static struct REPARSE_DATA_BUFFER *
1139 ntfs_create_reparse_buffer(struct ntfs_sb_info *sbi, const char *symname,
1140 			   u32 size, u16 *nsize)
1141 {
1142 	int i, err;
1143 	struct REPARSE_DATA_BUFFER *rp;
1144 	__le16 *rp_name;
1145 	typeof(rp->SymbolicLinkReparseBuffer) *rs;
1146 
1147 	rp = kzalloc(ntfs_reparse_bytes(2 * size + 2), GFP_NOFS);
1148 	if (!rp)
1149 		return ERR_PTR(-ENOMEM);
1150 
1151 	rs = &rp->SymbolicLinkReparseBuffer;
1152 	rp_name = rs->PathBuffer;
1153 
1154 	/* Convert link name to UTF-16. */
1155 	err = ntfs_nls_to_utf16(sbi, symname, size,
1156 				(struct cpu_str *)(rp_name - 1), 2 * size,
1157 				UTF16_LITTLE_ENDIAN);
1158 	if (err < 0)
1159 		goto out;
1160 
1161 	/* err = the length of unicode name of symlink. */
1162 	*nsize = ntfs_reparse_bytes(err);
1163 
1164 	if (*nsize > sbi->reparse.max_size) {
1165 		err = -EFBIG;
1166 		goto out;
1167 	}
1168 
1169 	/* Translate Linux '/' into Windows '\'. */
1170 	for (i = 0; i < err; i++) {
1171 		if (rp_name[i] == cpu_to_le16('/'))
1172 			rp_name[i] = cpu_to_le16('\\');
1173 	}
1174 
1175 	rp->ReparseTag = IO_REPARSE_TAG_SYMLINK;
1176 	rp->ReparseDataLength =
1177 		cpu_to_le16(*nsize - offsetof(struct REPARSE_DATA_BUFFER,
1178 					      SymbolicLinkReparseBuffer));
1179 
1180 	/* PrintName + SubstituteName. */
1181 	rs->SubstituteNameOffset = cpu_to_le16(sizeof(short) * err);
1182 	rs->SubstituteNameLength = cpu_to_le16(sizeof(short) * err + 8);
1183 	rs->PrintNameLength = rs->SubstituteNameOffset;
1184 
1185 	/*
1186 	 * TODO: Use relative path if possible to allow Windows to
1187 	 * parse this path.
1188 	 * 0-absolute path 1- relative path (SYMLINK_FLAG_RELATIVE).
1189 	 */
1190 	rs->Flags = 0;
1191 
1192 	memmove(rp_name + err + 4, rp_name, sizeof(short) * err);
1193 
1194 	/* Decorate SubstituteName. */
1195 	rp_name += err;
1196 	rp_name[0] = cpu_to_le16('\\');
1197 	rp_name[1] = cpu_to_le16('?');
1198 	rp_name[2] = cpu_to_le16('?');
1199 	rp_name[3] = cpu_to_le16('\\');
1200 
1201 	return rp;
1202 out:
1203 	kfree(rp);
1204 	return ERR_PTR(err);
1205 }
1206 
1207 /*
1208  * ntfs_create_inode
1209  *
1210  * Helper function for:
1211  * - ntfs_create
1212  * - ntfs_mknod
1213  * - ntfs_symlink
1214  * - ntfs_mkdir
1215  * - ntfs_atomic_open
1216  *
1217  * NOTE: if fnd != NULL (ntfs_atomic_open) then @dir is locked
1218  */
1219 struct inode *ntfs_create_inode(struct mnt_idmap *idmap, struct inode *dir,
1220 				struct dentry *dentry,
1221 				const struct cpu_str *uni, umode_t mode,
1222 				dev_t dev, const char *symname, u32 size,
1223 				struct ntfs_fnd *fnd)
1224 {
1225 	int err;
1226 	struct super_block *sb = dir->i_sb;
1227 	struct ntfs_sb_info *sbi = sb->s_fs_info;
1228 	const struct qstr *name = &dentry->d_name;
1229 	CLST ino = 0;
1230 	struct ntfs_inode *dir_ni = ntfs_i(dir);
1231 	struct ntfs_inode *ni = NULL;
1232 	struct inode *inode = NULL;
1233 	struct ATTRIB *attr;
1234 	struct ATTR_STD_INFO5 *std5;
1235 	struct ATTR_FILE_NAME *fname;
1236 	struct MFT_REC *rec;
1237 	u32 asize, dsize, sd_size;
1238 	enum FILE_ATTRIBUTE fa;
1239 	__le32 security_id = SECURITY_ID_INVALID;
1240 	CLST vcn;
1241 	const void *sd;
1242 	u16 t16, nsize = 0, aid = 0;
1243 	struct INDEX_ROOT *root, *dir_root;
1244 	struct NTFS_DE *e, *new_de = NULL;
1245 	struct REPARSE_DATA_BUFFER *rp = NULL;
1246 	bool rp_inserted = false;
1247 
1248 	if (!fnd)
1249 		ni_lock_dir(dir_ni);
1250 
1251 	dir_root = indx_get_root(&dir_ni->dir, dir_ni, NULL, NULL);
1252 	if (!dir_root) {
1253 		err = -EINVAL;
1254 		goto out1;
1255 	}
1256 
1257 	if (S_ISDIR(mode)) {
1258 		/* Use parent's directory attributes. */
1259 		fa = dir_ni->std_fa | FILE_ATTRIBUTE_DIRECTORY |
1260 		     FILE_ATTRIBUTE_ARCHIVE;
1261 		/*
1262 		 * By default child directory inherits parent attributes.
1263 		 * Root directory is hidden + system.
1264 		 * Make an exception for children in root.
1265 		 */
1266 		if (dir->i_ino == MFT_REC_ROOT)
1267 			fa &= ~(FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM);
1268 	} else if (S_ISLNK(mode)) {
1269 		/* It is good idea that link should be the same type (file/dir) as target */
1270 		fa = FILE_ATTRIBUTE_REPARSE_POINT;
1271 
1272 		/*
1273 		 * Linux: there are dir/file/symlink and so on.
1274 		 * NTFS: symlinks are "dir + reparse" or "file + reparse"
1275 		 * It is good idea to create:
1276 		 * dir + reparse if 'symname' points to directory
1277 		 * or
1278 		 * file + reparse if 'symname' points to file
1279 		 * Unfortunately kern_path hangs if symname contains 'dir'.
1280 		 */
1281 
1282 		/*
1283 		 *	struct path path;
1284 		 *
1285 		 *	if (!kern_path(symname, LOOKUP_FOLLOW, &path)){
1286 		 *		struct inode *target = d_inode(path.dentry);
1287 		 *
1288 		 *		if (S_ISDIR(target->i_mode))
1289 		 *			fa |= FILE_ATTRIBUTE_DIRECTORY;
1290 		 *		// if ( target->i_sb == sb ){
1291 		 *		//	use relative path?
1292 		 *		// }
1293 		 *		path_put(&path);
1294 		 *	}
1295 		 */
1296 	} else if (S_ISREG(mode)) {
1297 		if (sbi->options->sparse) {
1298 			/* Sparsed regular file, cause option 'sparse'. */
1299 			fa = FILE_ATTRIBUTE_SPARSE_FILE |
1300 			     FILE_ATTRIBUTE_ARCHIVE;
1301 		} else if (dir_ni->std_fa & FILE_ATTRIBUTE_COMPRESSED) {
1302 			/* Compressed regular file, if parent is compressed. */
1303 			fa = FILE_ATTRIBUTE_COMPRESSED | FILE_ATTRIBUTE_ARCHIVE;
1304 		} else {
1305 			/* Regular file, default attributes. */
1306 			fa = FILE_ATTRIBUTE_ARCHIVE;
1307 		}
1308 	} else {
1309 		fa = FILE_ATTRIBUTE_ARCHIVE;
1310 	}
1311 
1312 	/* If option "hide_dot_files" then set hidden attribute for dot files. */
1313 	if (sbi->options->hide_dot_files && name->name[0] == '.')
1314 		fa |= FILE_ATTRIBUTE_HIDDEN;
1315 
1316 	if (!(mode & 0222))
1317 		fa |= FILE_ATTRIBUTE_READONLY;
1318 
1319 	/* Allocate PATH_MAX bytes. */
1320 	new_de = __getname();
1321 	if (!new_de) {
1322 		err = -ENOMEM;
1323 		goto out1;
1324 	}
1325 
1326 	if (unlikely(ntfs3_forced_shutdown(sb))) {
1327 		err = -EIO;
1328 		goto out2;
1329 	}
1330 
1331 	/* Mark rw ntfs as dirty. it will be cleared at umount. */
1332 	ntfs_set_state(sbi, NTFS_DIRTY_DIRTY);
1333 
1334 	/* Step 1: allocate and fill new mft record. */
1335 	err = ntfs_look_free_mft(sbi, &ino, false, NULL, NULL);
1336 	if (err)
1337 		goto out2;
1338 
1339 	ni = ntfs_new_inode(sbi, ino, S_ISDIR(mode) ? RECORD_FLAG_DIR : 0);
1340 	if (IS_ERR(ni)) {
1341 		err = PTR_ERR(ni);
1342 		ni = NULL;
1343 		goto out3;
1344 	}
1345 	inode = &ni->vfs_inode;
1346 	inode_init_owner(idmap, inode, dir, mode);
1347 	mode = inode->i_mode;
1348 
1349 	ni->i_crtime = current_time(inode);
1350 
1351 	rec = ni->mi.mrec;
1352 	rec->hard_links = cpu_to_le16(1);
1353 	attr = Add2Ptr(rec, le16_to_cpu(rec->attr_off));
1354 
1355 	/* Get default security id. */
1356 	sd = s_default_security;
1357 	sd_size = sizeof(s_default_security);
1358 
1359 	if (is_ntfs3(sbi)) {
1360 		security_id = dir_ni->std_security_id;
1361 		if (le32_to_cpu(security_id) < SECURITY_ID_FIRST) {
1362 			security_id = sbi->security.def_security_id;
1363 
1364 			if (security_id == SECURITY_ID_INVALID &&
1365 			    !ntfs_insert_security(sbi, sd, sd_size,
1366 						  &security_id, NULL))
1367 				sbi->security.def_security_id = security_id;
1368 		}
1369 	}
1370 
1371 	/* Insert standard info. */
1372 	std5 = Add2Ptr(attr, SIZEOF_RESIDENT);
1373 
1374 	if (security_id == SECURITY_ID_INVALID) {
1375 		dsize = sizeof(struct ATTR_STD_INFO);
1376 	} else {
1377 		dsize = sizeof(struct ATTR_STD_INFO5);
1378 		std5->security_id = security_id;
1379 		ni->std_security_id = security_id;
1380 	}
1381 	asize = SIZEOF_RESIDENT + dsize;
1382 
1383 	attr->type = ATTR_STD;
1384 	attr->size = cpu_to_le32(asize);
1385 	attr->id = cpu_to_le16(aid++);
1386 	attr->res.data_off = SIZEOF_RESIDENT_LE;
1387 	attr->res.data_size = cpu_to_le32(dsize);
1388 
1389 	std5->cr_time = std5->m_time = std5->c_time = std5->a_time =
1390 		kernel2nt(&ni->i_crtime);
1391 
1392 	std5->fa = ni->std_fa = fa;
1393 
1394 	attr = Add2Ptr(attr, asize);
1395 
1396 	/* Insert file name. */
1397 	err = fill_name_de(sbi, new_de, name, uni);
1398 	if (err)
1399 		goto out4;
1400 
1401 	mi_get_ref(&ni->mi, &new_de->ref);
1402 
1403 	fname = (struct ATTR_FILE_NAME *)(new_de + 1);
1404 
1405 	if (sbi->options->windows_names &&
1406 	    !valid_windows_name(sbi, (struct le_str *)&fname->name_len)) {
1407 		err = -EINVAL;
1408 		goto out4;
1409 	}
1410 
1411 	mi_get_ref(&dir_ni->mi, &fname->home);
1412 	fname->dup.cr_time = fname->dup.m_time = fname->dup.c_time =
1413 		fname->dup.a_time = std5->cr_time;
1414 	fname->dup.alloc_size = fname->dup.data_size = 0;
1415 	fname->dup.fa = std5->fa;
1416 	fname->dup.ea_size = fname->dup.reparse = 0;
1417 
1418 	dsize = le16_to_cpu(new_de->key_size);
1419 	asize = ALIGN(SIZEOF_RESIDENT + dsize, 8);
1420 
1421 	attr->type = ATTR_NAME;
1422 	attr->size = cpu_to_le32(asize);
1423 	attr->res.data_off = SIZEOF_RESIDENT_LE;
1424 	attr->res.flags = RESIDENT_FLAG_INDEXED;
1425 	attr->id = cpu_to_le16(aid++);
1426 	attr->res.data_size = cpu_to_le32(dsize);
1427 	memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), fname, dsize);
1428 
1429 	attr = Add2Ptr(attr, asize);
1430 
1431 	if (security_id == SECURITY_ID_INVALID) {
1432 		/* Insert security attribute. */
1433 		asize = SIZEOF_RESIDENT + ALIGN(sd_size, 8);
1434 
1435 		attr->type = ATTR_SECURE;
1436 		attr->size = cpu_to_le32(asize);
1437 		attr->id = cpu_to_le16(aid++);
1438 		attr->res.data_off = SIZEOF_RESIDENT_LE;
1439 		attr->res.data_size = cpu_to_le32(sd_size);
1440 		memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), sd, sd_size);
1441 
1442 		attr = Add2Ptr(attr, asize);
1443 	}
1444 
1445 	attr->id = cpu_to_le16(aid++);
1446 	if (fa & FILE_ATTRIBUTE_DIRECTORY) {
1447 		/*
1448 		 * Regular directory or symlink to directory.
1449 		 * Create root attribute.
1450 		 */
1451 		dsize = sizeof(struct INDEX_ROOT) + sizeof(struct NTFS_DE);
1452 		asize = sizeof(I30_NAME) + SIZEOF_RESIDENT + dsize;
1453 
1454 		attr->type = ATTR_ROOT;
1455 		attr->size = cpu_to_le32(asize);
1456 
1457 		attr->name_len = ARRAY_SIZE(I30_NAME);
1458 		attr->name_off = SIZEOF_RESIDENT_LE;
1459 		attr->res.data_off =
1460 			cpu_to_le16(sizeof(I30_NAME) + SIZEOF_RESIDENT);
1461 		attr->res.data_size = cpu_to_le32(dsize);
1462 		memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), I30_NAME,
1463 		       sizeof(I30_NAME));
1464 
1465 		root = Add2Ptr(attr, sizeof(I30_NAME) + SIZEOF_RESIDENT);
1466 		memcpy(root, dir_root, offsetof(struct INDEX_ROOT, ihdr));
1467 		root->ihdr.de_off = cpu_to_le32(sizeof(struct INDEX_HDR));
1468 		root->ihdr.used = cpu_to_le32(sizeof(struct INDEX_HDR) +
1469 					      sizeof(struct NTFS_DE));
1470 		root->ihdr.total = root->ihdr.used;
1471 
1472 		e = Add2Ptr(root, sizeof(struct INDEX_ROOT));
1473 		e->size = cpu_to_le16(sizeof(struct NTFS_DE));
1474 		e->flags = NTFS_IE_LAST;
1475 	} else if (S_ISLNK(mode)) {
1476 		/*
1477 		 * Symlink to file.
1478 		 * Create empty resident data attribute.
1479 		 */
1480 		asize = SIZEOF_RESIDENT;
1481 
1482 		/* Insert empty ATTR_DATA */
1483 		attr->type = ATTR_DATA;
1484 		attr->size = cpu_to_le32(SIZEOF_RESIDENT);
1485 		attr->name_off = SIZEOF_RESIDENT_LE;
1486 		attr->res.data_off = SIZEOF_RESIDENT_LE;
1487 	} else if (S_ISREG(mode)) {
1488 		/*
1489 		 * Regular file. Create empty non resident data attribute.
1490 		 */
1491 		attr->type = ATTR_DATA;
1492 		attr->non_res = 1;
1493 		attr->nres.evcn = cpu_to_le64(-1ll);
1494 		if (fa & FILE_ATTRIBUTE_SPARSE_FILE) {
1495 			attr->size = cpu_to_le32(SIZEOF_NONRESIDENT_EX + 8);
1496 			attr->name_off = SIZEOF_NONRESIDENT_EX_LE;
1497 			attr->flags = ATTR_FLAG_SPARSED;
1498 			asize = SIZEOF_NONRESIDENT_EX + 8;
1499 		} else if (fa & FILE_ATTRIBUTE_COMPRESSED) {
1500 			attr->size = cpu_to_le32(SIZEOF_NONRESIDENT_EX + 8);
1501 			attr->name_off = SIZEOF_NONRESIDENT_EX_LE;
1502 			attr->flags = ATTR_FLAG_COMPRESSED;
1503 			attr->nres.c_unit = COMPRESSION_UNIT;
1504 			asize = SIZEOF_NONRESIDENT_EX + 8;
1505 		} else {
1506 			attr->size = cpu_to_le32(SIZEOF_NONRESIDENT + 8);
1507 			attr->name_off = SIZEOF_NONRESIDENT_LE;
1508 			asize = SIZEOF_NONRESIDENT + 8;
1509 		}
1510 		attr->nres.run_off = attr->name_off;
1511 	} else {
1512 		/*
1513 		 * Node. Create empty resident data attribute.
1514 		 */
1515 		attr->type = ATTR_DATA;
1516 		attr->size = cpu_to_le32(SIZEOF_RESIDENT);
1517 		attr->name_off = SIZEOF_RESIDENT_LE;
1518 		if (fa & FILE_ATTRIBUTE_SPARSE_FILE)
1519 			attr->flags = ATTR_FLAG_SPARSED;
1520 		else if (fa & FILE_ATTRIBUTE_COMPRESSED)
1521 			attr->flags = ATTR_FLAG_COMPRESSED;
1522 		attr->res.data_off = SIZEOF_RESIDENT_LE;
1523 		asize = SIZEOF_RESIDENT;
1524 		ni->ni_flags |= NI_FLAG_RESIDENT;
1525 	}
1526 
1527 	if (S_ISDIR(mode)) {
1528 		ni->ni_flags |= NI_FLAG_DIR;
1529 		err = indx_init(&ni->dir, sbi, attr, INDEX_MUTEX_I30);
1530 		if (err)
1531 			goto out4;
1532 	} else if (S_ISLNK(mode)) {
1533 		rp = ntfs_create_reparse_buffer(sbi, symname, size, &nsize);
1534 
1535 		if (IS_ERR(rp)) {
1536 			err = PTR_ERR(rp);
1537 			rp = NULL;
1538 			goto out4;
1539 		}
1540 
1541 		/*
1542 		 * Insert ATTR_REPARSE.
1543 		 */
1544 		attr = Add2Ptr(attr, asize);
1545 		attr->type = ATTR_REPARSE;
1546 		attr->id = cpu_to_le16(aid++);
1547 
1548 		/* Resident or non resident? */
1549 		asize = ALIGN(SIZEOF_RESIDENT + nsize, 8);
1550 		t16 = PtrOffset(rec, attr);
1551 
1552 		/*
1553 		 * Below function 'ntfs_save_wsl_perm' requires 0x78 bytes.
1554 		 * It is good idea to keep extened attributes resident.
1555 		 */
1556 		if (asize + t16 + 0x78 + 8 > sbi->record_size) {
1557 			CLST alen;
1558 			CLST clst = bytes_to_cluster(sbi, nsize);
1559 
1560 			/* Bytes per runs. */
1561 			t16 = sbi->record_size - t16 - SIZEOF_NONRESIDENT;
1562 
1563 			attr->non_res = 1;
1564 			attr->nres.evcn = cpu_to_le64(clst - 1);
1565 			attr->name_off = SIZEOF_NONRESIDENT_LE;
1566 			attr->nres.run_off = attr->name_off;
1567 			attr->nres.data_size = cpu_to_le64(nsize);
1568 			attr->nres.valid_size = attr->nres.data_size;
1569 			attr->nres.alloc_size =
1570 				cpu_to_le64(ntfs_up_cluster(sbi, nsize));
1571 
1572 			err = attr_allocate_clusters(sbi, &ni->file.run, 0, 0,
1573 						     clst, NULL, ALLOCATE_DEF,
1574 						     &alen, 0, NULL, NULL);
1575 			if (err)
1576 				goto out5;
1577 
1578 			err = run_pack(&ni->file.run, 0, clst,
1579 				       Add2Ptr(attr, SIZEOF_NONRESIDENT), t16,
1580 				       &vcn);
1581 			if (err < 0)
1582 				goto out5;
1583 
1584 			if (vcn != clst) {
1585 				err = -EINVAL;
1586 				goto out5;
1587 			}
1588 
1589 			asize = SIZEOF_NONRESIDENT + ALIGN(err, 8);
1590 			/* Write non resident data. */
1591 			err = ntfs_sb_write_run(sbi, &ni->file.run, 0, rp,
1592 						nsize, 0);
1593 			if (err)
1594 				goto out5;
1595 		} else {
1596 			attr->res.data_off = SIZEOF_RESIDENT_LE;
1597 			attr->res.data_size = cpu_to_le32(nsize);
1598 			memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), rp, nsize);
1599 		}
1600 		/* Size of symlink equals the length of input string. */
1601 		inode->i_size = size;
1602 
1603 		attr->size = cpu_to_le32(asize);
1604 
1605 		err = ntfs_insert_reparse(sbi, IO_REPARSE_TAG_SYMLINK,
1606 					  &new_de->ref);
1607 		if (err)
1608 			goto out5;
1609 
1610 		rp_inserted = true;
1611 	}
1612 
1613 	attr = Add2Ptr(attr, asize);
1614 	attr->type = ATTR_END;
1615 
1616 	rec->used = cpu_to_le32(PtrOffset(rec, attr) + 8);
1617 	rec->next_attr_id = cpu_to_le16(aid);
1618 
1619 	inode->i_generation = le16_to_cpu(rec->seq);
1620 
1621 	if (S_ISDIR(mode)) {
1622 		inode->i_op = &ntfs_dir_inode_operations;
1623 		if (is_legacy_ntfs(inode->i_sb))
1624 			inode->i_fop = &ntfs_legacy_dir_operations;
1625 		else
1626 			inode->i_fop = &ntfs_dir_operations;
1627 	} else if (S_ISLNK(mode)) {
1628 		inode->i_op = &ntfs_link_inode_operations;
1629 		inode->i_fop = NULL;
1630 		inode->i_mapping->a_ops = &ntfs_aops;
1631 		inode->i_size = size;
1632 		inode_nohighmem(inode);
1633 	} else if (S_ISREG(mode)) {
1634 		inode->i_op = &ntfs_file_inode_operations;
1635 		if (is_legacy_ntfs(inode->i_sb))
1636 			inode->i_fop = &ntfs_legacy_file_operations;
1637 		else
1638 			inode->i_fop = &ntfs_file_operations;
1639 		inode->i_mapping->a_ops = is_compressed(ni) ? &ntfs_aops_cmpr :
1640 							      &ntfs_aops;
1641 		init_rwsem(&ni->file.run_lock);
1642 	} else {
1643 		inode->i_op = &ntfs_special_inode_operations;
1644 		init_special_inode(inode, mode, dev);
1645 	}
1646 
1647 #ifdef CONFIG_NTFS3_FS_POSIX_ACL
1648 	if (!S_ISLNK(mode) && (sb->s_flags & SB_POSIXACL)) {
1649 		err = ntfs_init_acl(idmap, inode, dir);
1650 		if (err)
1651 			goto out5;
1652 	} else
1653 #endif
1654 	{
1655 		inode->i_flags |= S_NOSEC;
1656 	}
1657 
1658 	/*
1659 	 * ntfs_init_acl and ntfs_save_wsl_perm update extended attribute.
1660 	 * The packed size of extended attribute is stored in direntry too.
1661 	 * 'fname' here points to inside new_de.
1662 	 */
1663 	ntfs_save_wsl_perm(inode, &fname->dup.ea_size);
1664 
1665 	/*
1666 	 * update ea_size in file_name attribute too.
1667 	 * Use ni_find_attr cause layout of MFT record may be changed
1668 	 * in ntfs_init_acl and ntfs_save_wsl_perm.
1669 	 */
1670 	attr = ni_find_attr(ni, NULL, NULL, ATTR_NAME, NULL, 0, NULL, NULL);
1671 	if (attr) {
1672 		struct ATTR_FILE_NAME *fn;
1673 
1674 		fn = resident_data_ex(attr, SIZEOF_ATTRIBUTE_FILENAME);
1675 		if (fn)
1676 			fn->dup.ea_size = fname->dup.ea_size;
1677 	}
1678 
1679 	/* We do not need to update parent directory later */
1680 	ni->ni_flags &= ~NI_FLAG_UPDATE_PARENT;
1681 
1682 	/* Step 2: Add new name in index. */
1683 	err = indx_insert_entry(&dir_ni->dir, dir_ni, new_de, sbi, fnd, 0);
1684 	if (err)
1685 		goto out6;
1686 
1687 	/*
1688 	 * Call 'd_instantiate' after inode->i_op is set
1689 	 * but before finish_open.
1690 	 */
1691 	d_instantiate(dentry, inode);
1692 
1693 	/* Set original time. inode times (i_ctime) may be changed in ntfs_init_acl. */
1694 	inode_set_atime_to_ts(inode, ni->i_crtime);
1695 	inode_set_ctime_to_ts(inode, ni->i_crtime);
1696 	inode_set_mtime_to_ts(inode, ni->i_crtime);
1697 	inode_set_mtime_to_ts(dir, ni->i_crtime);
1698 	inode_set_ctime_to_ts(dir, ni->i_crtime);
1699 
1700 	mark_inode_dirty(dir);
1701 	mark_inode_dirty(inode);
1702 
1703 	/* Normal exit. */
1704 	goto out2;
1705 
1706 out6:
1707 	if (rp_inserted)
1708 		ntfs_remove_reparse(sbi, IO_REPARSE_TAG_SYMLINK, &new_de->ref);
1709 
1710 out5:
1711 	if (!S_ISDIR(mode))
1712 		run_deallocate(sbi, &ni->file.run, false);
1713 
1714 out4:
1715 	clear_rec_inuse(rec);
1716 	clear_nlink(inode);
1717 	ni->mi.dirty = false;
1718 	discard_new_inode(inode);
1719 out3:
1720 	ntfs_mark_rec_free(sbi, ino, false);
1721 
1722 out2:
1723 	__putname(new_de);
1724 	kfree(rp);
1725 
1726 out1:
1727 	if (!fnd)
1728 		ni_unlock(dir_ni);
1729 
1730 	if (err)
1731 		return ERR_PTR(err);
1732 
1733 	unlock_new_inode(inode);
1734 
1735 	return inode;
1736 }
1737 
1738 int ntfs_link_inode(struct inode *inode, struct dentry *dentry)
1739 {
1740 	int err;
1741 	struct ntfs_inode *ni = ntfs_i(inode);
1742 	struct ntfs_sb_info *sbi = inode->i_sb->s_fs_info;
1743 	struct NTFS_DE *de;
1744 
1745 	/* Allocate PATH_MAX bytes. */
1746 	de = __getname();
1747 	if (!de)
1748 		return -ENOMEM;
1749 
1750 	/* Mark rw ntfs as dirty. It will be cleared at umount. */
1751 	ntfs_set_state(sbi, NTFS_DIRTY_DIRTY);
1752 
1753 	/* Construct 'de'. */
1754 	err = fill_name_de(sbi, de, &dentry->d_name, NULL);
1755 	if (err)
1756 		goto out;
1757 
1758 	err = ni_add_name(ntfs_i(d_inode(dentry->d_parent)), ni, de);
1759 out:
1760 	__putname(de);
1761 	return err;
1762 }
1763 
1764 /*
1765  * ntfs_unlink_inode
1766  *
1767  * inode_operations::unlink
1768  * inode_operations::rmdir
1769  */
1770 int ntfs_unlink_inode(struct inode *dir, const struct dentry *dentry)
1771 {
1772 	int err;
1773 	struct ntfs_sb_info *sbi = dir->i_sb->s_fs_info;
1774 	struct inode *inode = d_inode(dentry);
1775 	struct ntfs_inode *ni = ntfs_i(inode);
1776 	struct ntfs_inode *dir_ni = ntfs_i(dir);
1777 	struct NTFS_DE *de, *de2 = NULL;
1778 	int undo_remove;
1779 
1780 	if (ntfs_is_meta_file(sbi, ni->mi.rno))
1781 		return -EINVAL;
1782 
1783 	/* Allocate PATH_MAX bytes. */
1784 	de = __getname();
1785 	if (!de)
1786 		return -ENOMEM;
1787 
1788 	ni_lock(ni);
1789 
1790 	if (S_ISDIR(inode->i_mode) && !dir_is_empty(inode)) {
1791 		err = -ENOTEMPTY;
1792 		goto out;
1793 	}
1794 
1795 	err = fill_name_de(sbi, de, &dentry->d_name, NULL);
1796 	if (err < 0)
1797 		goto out;
1798 
1799 	undo_remove = 0;
1800 	err = ni_remove_name(dir_ni, ni, de, &de2, &undo_remove);
1801 
1802 	if (!err) {
1803 		drop_nlink(inode);
1804 		inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
1805 		mark_inode_dirty(dir);
1806 		inode_set_ctime_to_ts(inode, inode_get_ctime(dir));
1807 		if (inode->i_nlink)
1808 			mark_inode_dirty(inode);
1809 	} else if (!ni_remove_name_undo(dir_ni, ni, de, de2, undo_remove)) {
1810 		_ntfs_bad_inode(inode);
1811 	} else {
1812 		if (ni_is_dirty(dir))
1813 			mark_inode_dirty(dir);
1814 		if (ni_is_dirty(inode))
1815 			mark_inode_dirty(inode);
1816 	}
1817 
1818 out:
1819 	ni_unlock(ni);
1820 	__putname(de);
1821 	return err;
1822 }
1823 
1824 void ntfs_evict_inode(struct inode *inode)
1825 {
1826 	truncate_inode_pages_final(&inode->i_data);
1827 
1828 	invalidate_inode_buffers(inode);
1829 	clear_inode(inode);
1830 
1831 	ni_clear(ntfs_i(inode));
1832 }
1833 
1834 /*
1835  * ntfs_translate_junction
1836  *
1837  * Translate a Windows junction target to the Linux equivalent.
1838  * On junctions, targets are always absolute (they include the drive
1839  * letter). We have no way of knowing if the target is for the current
1840  * mounted device or not so we just assume it is.
1841  */
1842 static int ntfs_translate_junction(const struct super_block *sb,
1843 				   const struct dentry *link_de, char *target,
1844 				   int target_len, int target_max)
1845 {
1846 	int tl_len, err = target_len;
1847 	char *link_path_buffer = NULL, *link_path;
1848 	char *translated = NULL;
1849 	char *target_start;
1850 	int copy_len;
1851 
1852 	link_path_buffer = kmalloc(PATH_MAX, GFP_NOFS);
1853 	if (!link_path_buffer) {
1854 		err = -ENOMEM;
1855 		goto out;
1856 	}
1857 	/* Get link path, relative to mount point */
1858 	link_path = dentry_path_raw(link_de, link_path_buffer, PATH_MAX);
1859 	if (IS_ERR(link_path)) {
1860 		ntfs_err(sb, "Error getting link path");
1861 		err = -EINVAL;
1862 		goto out;
1863 	}
1864 
1865 	translated = kmalloc(PATH_MAX, GFP_NOFS);
1866 	if (!translated) {
1867 		err = -ENOMEM;
1868 		goto out;
1869 	}
1870 
1871 	/* Make translated path a relative path to mount point */
1872 	strcpy(translated, "./");
1873 	++link_path; /* Skip leading / */
1874 	for (tl_len = sizeof("./") - 1; *link_path; ++link_path) {
1875 		if (*link_path == '/') {
1876 			if (PATH_MAX - tl_len < sizeof("../")) {
1877 				ntfs_err(sb,
1878 					 "Link path %s has too many components",
1879 					 link_path);
1880 				err = -EINVAL;
1881 				goto out;
1882 			}
1883 			strcpy(translated + tl_len, "../");
1884 			tl_len += sizeof("../") - 1;
1885 		}
1886 	}
1887 
1888 	/* Skip drive letter */
1889 	target_start = target;
1890 	while (*target_start && *target_start != ':')
1891 		++target_start;
1892 
1893 	if (!*target_start) {
1894 		ntfs_err(sb, "Link target (%s) missing drive separator",
1895 			 target);
1896 		err = -EINVAL;
1897 		goto out;
1898 	}
1899 
1900 	/* Skip drive separator and leading /, if exists */
1901 	target_start += 1 + (target_start[1] == '/');
1902 	copy_len = target_len - (target_start - target);
1903 
1904 	if (PATH_MAX - tl_len <= copy_len) {
1905 		ntfs_err(sb, "Link target %s too large for buffer (%d <= %d)",
1906 			 target_start, PATH_MAX - tl_len, copy_len);
1907 		err = -EINVAL;
1908 		goto out;
1909 	}
1910 
1911 	/* translated path has a trailing / and target_start does not */
1912 	strcpy(translated + tl_len, target_start);
1913 	tl_len += copy_len;
1914 	if (target_max <= tl_len) {
1915 		ntfs_err(sb, "Target path %s too large for buffer (%d <= %d)",
1916 			 translated, target_max, tl_len);
1917 		err = -EINVAL;
1918 		goto out;
1919 	}
1920 	strcpy(target, translated);
1921 	err = tl_len;
1922 
1923 out:
1924 	kfree(link_path_buffer);
1925 	kfree(translated);
1926 	return err;
1927 }
1928 
1929 static noinline int ntfs_readlink_hlp(const struct dentry *link_de,
1930 				      struct inode *inode, char *buffer,
1931 				      int buflen)
1932 {
1933 	int i, err = -EINVAL;
1934 	struct ntfs_inode *ni = ntfs_i(inode);
1935 	struct super_block *sb = inode->i_sb;
1936 	struct ntfs_sb_info *sbi = sb->s_fs_info;
1937 	u64 size;
1938 	u16 ulen = 0;
1939 	void *to_free = NULL;
1940 	struct REPARSE_DATA_BUFFER *rp;
1941 	const __le16 *uname;
1942 	struct ATTRIB *attr;
1943 
1944 	/* Reparse data present. Try to parse it. */
1945 	static_assert(!offsetof(struct REPARSE_DATA_BUFFER, ReparseTag));
1946 	static_assert(sizeof(u32) == sizeof(rp->ReparseTag));
1947 
1948 	*buffer = 0;
1949 
1950 	attr = ni_find_attr(ni, NULL, NULL, ATTR_REPARSE, NULL, 0, NULL, NULL);
1951 	if (!attr)
1952 		goto out;
1953 
1954 	if (!attr->non_res) {
1955 		rp = resident_data_ex(attr, sizeof(struct REPARSE_DATA_BUFFER));
1956 		if (!rp)
1957 			goto out;
1958 		size = le32_to_cpu(attr->res.data_size);
1959 	} else {
1960 		size = le64_to_cpu(attr->nres.data_size);
1961 		rp = NULL;
1962 	}
1963 
1964 	if (size > sbi->reparse.max_size || size <= sizeof(u32))
1965 		goto out;
1966 
1967 	if (!rp) {
1968 		rp = kmalloc(size, GFP_NOFS);
1969 		if (!rp) {
1970 			err = -ENOMEM;
1971 			goto out;
1972 		}
1973 		to_free = rp;
1974 		/* Read into temporal buffer. */
1975 		err = ntfs_read_run_nb(sbi, &ni->file.run, 0, rp, size, NULL);
1976 		if (err)
1977 			goto out;
1978 	}
1979 
1980 	/* Microsoft Tag. */
1981 	switch (rp->ReparseTag) {
1982 	case IO_REPARSE_TAG_MOUNT_POINT:
1983 		/* Mount points and junctions. */
1984 		/* Can we use 'Rp->MountPointReparseBuffer.PrintNameLength'? */
1985 		if (size <= offsetof(struct REPARSE_DATA_BUFFER,
1986 				     MountPointReparseBuffer.PathBuffer))
1987 			goto out;
1988 		uname = Add2Ptr(rp,
1989 				offsetof(struct REPARSE_DATA_BUFFER,
1990 					 MountPointReparseBuffer.PathBuffer) +
1991 					le16_to_cpu(rp->MountPointReparseBuffer
1992 							    .PrintNameOffset));
1993 		ulen = le16_to_cpu(rp->MountPointReparseBuffer.PrintNameLength);
1994 		break;
1995 
1996 	case IO_REPARSE_TAG_SYMLINK:
1997 		/* FolderSymbolicLink */
1998 		/* Can we use 'Rp->SymbolicLinkReparseBuffer.PrintNameLength'? */
1999 		if (size <= offsetof(struct REPARSE_DATA_BUFFER,
2000 				     SymbolicLinkReparseBuffer.PathBuffer))
2001 			goto out;
2002 		uname = Add2Ptr(
2003 			rp, offsetof(struct REPARSE_DATA_BUFFER,
2004 				     SymbolicLinkReparseBuffer.PathBuffer) +
2005 				    le16_to_cpu(rp->SymbolicLinkReparseBuffer
2006 							.PrintNameOffset));
2007 		ulen = le16_to_cpu(
2008 			rp->SymbolicLinkReparseBuffer.PrintNameLength);
2009 		break;
2010 
2011 	case IO_REPARSE_TAG_CLOUD:
2012 	case IO_REPARSE_TAG_CLOUD_1:
2013 	case IO_REPARSE_TAG_CLOUD_2:
2014 	case IO_REPARSE_TAG_CLOUD_3:
2015 	case IO_REPARSE_TAG_CLOUD_4:
2016 	case IO_REPARSE_TAG_CLOUD_5:
2017 	case IO_REPARSE_TAG_CLOUD_6:
2018 	case IO_REPARSE_TAG_CLOUD_7:
2019 	case IO_REPARSE_TAG_CLOUD_8:
2020 	case IO_REPARSE_TAG_CLOUD_9:
2021 	case IO_REPARSE_TAG_CLOUD_A:
2022 	case IO_REPARSE_TAG_CLOUD_B:
2023 	case IO_REPARSE_TAG_CLOUD_C:
2024 	case IO_REPARSE_TAG_CLOUD_D:
2025 	case IO_REPARSE_TAG_CLOUD_E:
2026 	case IO_REPARSE_TAG_CLOUD_F:
2027 		err = sizeof("OneDrive") - 1;
2028 		if (err > buflen)
2029 			err = buflen;
2030 		memcpy(buffer, "OneDrive", err);
2031 		goto out;
2032 
2033 	default:
2034 		if (IsReparseTagMicrosoft(rp->ReparseTag)) {
2035 			/* Unknown Microsoft Tag. */
2036 			goto out;
2037 		}
2038 		if (!IsReparseTagNameSurrogate(rp->ReparseTag) ||
2039 		    size <= sizeof(struct REPARSE_POINT)) {
2040 			goto out;
2041 		}
2042 
2043 		/* Users tag. */
2044 		uname = Add2Ptr(rp, sizeof(struct REPARSE_POINT));
2045 		ulen = le16_to_cpu(rp->ReparseDataLength) -
2046 		       sizeof(struct REPARSE_POINT);
2047 	}
2048 
2049 	/* Convert nlen from bytes to UNICODE chars. */
2050 	ulen >>= 1;
2051 
2052 	/* Check that name is available. */
2053 	if (!ulen || uname + ulen > (__le16 *)Add2Ptr(rp, size))
2054 		goto out;
2055 
2056 	/* If name is already zero terminated then truncate it now. */
2057 	if (!uname[ulen - 1])
2058 		ulen -= 1;
2059 
2060 	err = ntfs_utf16_to_nls(sbi, uname, ulen, buffer, buflen);
2061 
2062 	if (err < 0)
2063 		goto out;
2064 
2065 	/* Translate Windows '\' into Linux '/'. */
2066 	for (i = 0; i < err; i++) {
2067 		if (buffer[i] == '\\')
2068 			buffer[i] = '/';
2069 	}
2070 
2071 	/* Always set last zero. */
2072 	buffer[err] = 0;
2073 
2074 	/* If this is a junction, translate the link target. */
2075 	if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
2076 		err = ntfs_translate_junction(sb, link_de, buffer, err, buflen);
2077 
2078 out:
2079 	kfree(to_free);
2080 	return err;
2081 }
2082 
2083 static const char *ntfs_get_link(struct dentry *de, struct inode *inode,
2084 				 struct delayed_call *done)
2085 {
2086 	int err;
2087 	char *ret;
2088 
2089 	if (!de)
2090 		return ERR_PTR(-ECHILD);
2091 
2092 	ret = kmalloc(PAGE_SIZE, GFP_NOFS);
2093 	if (!ret)
2094 		return ERR_PTR(-ENOMEM);
2095 
2096 	err = ntfs_readlink_hlp(de, inode, ret, PAGE_SIZE);
2097 	if (err < 0) {
2098 		kfree(ret);
2099 		return ERR_PTR(err);
2100 	}
2101 
2102 	set_delayed_call(done, kfree_link, ret);
2103 
2104 	return ret;
2105 }
2106 
2107 // clang-format off
2108 const struct inode_operations ntfs_link_inode_operations = {
2109 	.get_link	= ntfs_get_link,
2110 	.setattr	= ntfs3_setattr,
2111 	.listxattr	= ntfs_listxattr,
2112 };
2113 
2114 const struct address_space_operations ntfs_aops = {
2115 	.read_folio	= ntfs_read_folio,
2116 	.readahead	= ntfs_readahead,
2117 	.writepages	= ntfs_writepages,
2118 	.write_begin	= ntfs_write_begin,
2119 	.write_end	= ntfs_write_end,
2120 	.direct_IO	= ntfs_direct_IO,
2121 	.bmap		= ntfs_bmap,
2122 	.dirty_folio	= block_dirty_folio,
2123 	.migrate_folio	= buffer_migrate_folio,
2124 	.invalidate_folio = block_invalidate_folio,
2125 };
2126 
2127 const struct address_space_operations ntfs_aops_cmpr = {
2128 	.read_folio	= ntfs_read_folio,
2129 	.readahead	= ntfs_readahead,
2130 };
2131 // clang-format on
2132