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