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