Linux Audio

Check our new training course

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