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