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