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