xref: /linux/fs/ntfs3/fsntfs.c (revision dc83d18cdd90482c70fa4320160bba70ec5c9ef8)
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/blkdev.h>
9 #include <linux/buffer_head.h>
10 #include <linux/fs.h>
11 #include <linux/kernel.h>
12 #include <linux/nls.h>
13 
14 #include "debug.h"
15 #include "ntfs.h"
16 #include "ntfs_fs.h"
17 
18 // clang-format off
19 const struct cpu_str NAME_MFT = {
20 	4, 0, { '$', 'M', 'F', 'T' },
21 };
22 const struct cpu_str NAME_MIRROR = {
23 	8, 0, { '$', 'M', 'F', 'T', 'M', 'i', 'r', 'r' },
24 };
25 const struct cpu_str NAME_LOGFILE = {
26 	8, 0, { '$', 'L', 'o', 'g', 'F', 'i', 'l', 'e' },
27 };
28 const struct cpu_str NAME_VOLUME = {
29 	7, 0, { '$', 'V', 'o', 'l', 'u', 'm', 'e' },
30 };
31 const struct cpu_str NAME_ATTRDEF = {
32 	8, 0, { '$', 'A', 't', 't', 'r', 'D', 'e', 'f' },
33 };
34 const struct cpu_str NAME_ROOT = {
35 	1, 0, { '.' },
36 };
37 const struct cpu_str NAME_BITMAP = {
38 	7, 0, { '$', 'B', 'i', 't', 'm', 'a', 'p' },
39 };
40 const struct cpu_str NAME_BOOT = {
41 	5, 0, { '$', 'B', 'o', 'o', 't' },
42 };
43 const struct cpu_str NAME_BADCLUS = {
44 	8, 0, { '$', 'B', 'a', 'd', 'C', 'l', 'u', 's' },
45 };
46 const struct cpu_str NAME_QUOTA = {
47 	6, 0, { '$', 'Q', 'u', 'o', 't', 'a' },
48 };
49 const struct cpu_str NAME_SECURE = {
50 	7, 0, { '$', 'S', 'e', 'c', 'u', 'r', 'e' },
51 };
52 const struct cpu_str NAME_UPCASE = {
53 	7, 0, { '$', 'U', 'p', 'C', 'a', 's', 'e' },
54 };
55 const struct cpu_str NAME_EXTEND = {
56 	7, 0, { '$', 'E', 'x', 't', 'e', 'n', 'd' },
57 };
58 const struct cpu_str NAME_OBJID = {
59 	6, 0, { '$', 'O', 'b', 'j', 'I', 'd' },
60 };
61 const struct cpu_str NAME_REPARSE = {
62 	8, 0, { '$', 'R', 'e', 'p', 'a', 'r', 's', 'e' },
63 };
64 const struct cpu_str NAME_USNJRNL = {
65 	8, 0, { '$', 'U', 's', 'n', 'J', 'r', 'n', 'l' },
66 };
67 const __le16 BAD_NAME[4] = {
68 	cpu_to_le16('$'), cpu_to_le16('B'), cpu_to_le16('a'), cpu_to_le16('d'),
69 };
70 const __le16 I30_NAME[4] = {
71 	cpu_to_le16('$'), cpu_to_le16('I'), cpu_to_le16('3'), cpu_to_le16('0'),
72 };
73 const __le16 SII_NAME[4] = {
74 	cpu_to_le16('$'), cpu_to_le16('S'), cpu_to_le16('I'), cpu_to_le16('I'),
75 };
76 const __le16 SDH_NAME[4] = {
77 	cpu_to_le16('$'), cpu_to_le16('S'), cpu_to_le16('D'), cpu_to_le16('H'),
78 };
79 const __le16 SDS_NAME[4] = {
80 	cpu_to_le16('$'), cpu_to_le16('S'), cpu_to_le16('D'), cpu_to_le16('S'),
81 };
82 const __le16 SO_NAME[2] = {
83 	cpu_to_le16('$'), cpu_to_le16('O'),
84 };
85 const __le16 SQ_NAME[2] = {
86 	cpu_to_le16('$'), cpu_to_le16('Q'),
87 };
88 const __le16 SR_NAME[2] = {
89 	cpu_to_le16('$'), cpu_to_le16('R'),
90 };
91 const __le16 QUERY_STREAMS[13] = {
92   cpu_to_le16('q'), cpu_to_le16('u'), cpu_to_le16('e'), cpu_to_le16('r'),
93   cpu_to_le16('y'), cpu_to_le16('_'), cpu_to_le16('s'), cpu_to_le16('t'),
94   cpu_to_le16('r'), cpu_to_le16('e'), cpu_to_le16('a'), cpu_to_le16('m'),
95   cpu_to_le16('s'),
96 };
97 
98 
99 #ifdef CONFIG_NTFS3_LZX_XPRESS
100 const __le16 WOF_NAME[17] = {
101 	cpu_to_le16('W'), cpu_to_le16('o'), cpu_to_le16('f'), cpu_to_le16('C'),
102 	cpu_to_le16('o'), cpu_to_le16('m'), cpu_to_le16('p'), cpu_to_le16('r'),
103 	cpu_to_le16('e'), cpu_to_le16('s'), cpu_to_le16('s'), cpu_to_le16('e'),
104 	cpu_to_le16('d'), cpu_to_le16('D'), cpu_to_le16('a'), cpu_to_le16('t'),
105 	cpu_to_le16('a'),
106 };
107 #endif
108 
109 static const __le16 CON_NAME[3] = {
110 	cpu_to_le16('C'), cpu_to_le16('O'), cpu_to_le16('N'),
111 };
112 
113 static const __le16 NUL_NAME[3] = {
114 	cpu_to_le16('N'), cpu_to_le16('U'), cpu_to_le16('L'),
115 };
116 
117 static const __le16 AUX_NAME[3] = {
118 	cpu_to_le16('A'), cpu_to_le16('U'), cpu_to_le16('X'),
119 };
120 
121 static const __le16 PRN_NAME[3] = {
122 	cpu_to_le16('P'), cpu_to_le16('R'), cpu_to_le16('N'),
123 };
124 
125 static const __le16 COM_NAME[3] = {
126 	cpu_to_le16('C'), cpu_to_le16('O'), cpu_to_le16('M'),
127 };
128 
129 static const __le16 LPT_NAME[3] = {
130 	cpu_to_le16('L'), cpu_to_le16('P'), cpu_to_le16('T'),
131 };
132 // clang-format on
133 
134 /*
135  * ntfs_fix_pre_write - Insert fixups into @rhdr before writing to disk.
136  */
ntfs_fix_pre_write(struct NTFS_RECORD_HEADER * rhdr,size_t bytes)137 bool ntfs_fix_pre_write(struct NTFS_RECORD_HEADER *rhdr, size_t bytes)
138 {
139 	u16 *fixup, *ptr;
140 	u16 sample;
141 	u16 fo = le16_to_cpu(rhdr->fix_off);
142 	u16 fn = le16_to_cpu(rhdr->fix_num);
143 
144 	if ((fo & 1) || fo + fn * sizeof(short) > SECTOR_SIZE || !fn-- ||
145 	    fn * SECTOR_SIZE > bytes) {
146 		return false;
147 	}
148 
149 	/* Get fixup pointer. */
150 	fixup = Add2Ptr(rhdr, fo);
151 
152 	if (*fixup >= 0x7FFF)
153 		*fixup = 1;
154 	else
155 		*fixup += 1;
156 
157 	sample = *fixup;
158 
159 	ptr = Add2Ptr(rhdr, SECTOR_SIZE - sizeof(short));
160 
161 	while (fn--) {
162 		*++fixup = *ptr;
163 		*ptr = sample;
164 		ptr += SECTOR_SIZE / sizeof(short);
165 	}
166 	return true;
167 }
168 
169 /*
170  * ntfs_fix_post_read - Remove fixups after reading from disk.
171  *
172  * Return: < 0 if error, 0 if ok, 1 if need to update fixups.
173  */
ntfs_fix_post_read(struct NTFS_RECORD_HEADER * rhdr,size_t bytes,bool simple)174 int ntfs_fix_post_read(struct NTFS_RECORD_HEADER *rhdr, size_t bytes,
175 		       bool simple)
176 {
177 	int ret;
178 	u16 *fixup, *ptr;
179 	u16 sample, fo, fn;
180 
181 	fo = le16_to_cpu(rhdr->fix_off);
182 	fn = simple ? ((bytes >> SECTOR_SHIFT) + 1) :
183 		      le16_to_cpu(rhdr->fix_num);
184 
185 	/* Check errors. */
186 	if ((fo & 1) || fo + fn * sizeof(short) > SECTOR_SIZE || !fn-- ||
187 	    fn * SECTOR_SIZE > bytes) {
188 		return -E_NTFS_CORRUPT;
189 	}
190 
191 	/* Get fixup pointer. */
192 	fixup = Add2Ptr(rhdr, fo);
193 	sample = *fixup;
194 	ptr = Add2Ptr(rhdr, SECTOR_SIZE - sizeof(short));
195 	ret = 0;
196 
197 	while (fn--) {
198 		/* Test current word. */
199 		if (*ptr != sample) {
200 			/* Fixup does not match! Is it serious error? */
201 			ret = -E_NTFS_FIXUP;
202 		}
203 
204 		/* Replace fixup. */
205 		*ptr = *++fixup;
206 		ptr += SECTOR_SIZE / sizeof(short);
207 	}
208 
209 	return ret;
210 }
211 
212 /*
213  * ntfs_extend_init - Load $Extend file.
214  */
ntfs_extend_init(struct ntfs_sb_info * sbi)215 int ntfs_extend_init(struct ntfs_sb_info *sbi)
216 {
217 	int err;
218 	struct super_block *sb = sbi->sb;
219 	struct inode *inode, *inode2;
220 	struct MFT_REF ref;
221 
222 	if (sbi->volume.major_ver < 3) {
223 		ntfs_notice(sb, "Skip $Extend 'cause NTFS version");
224 		return 0;
225 	}
226 
227 	ref.low = cpu_to_le32(MFT_REC_EXTEND);
228 	ref.high = 0;
229 	ref.seq = cpu_to_le16(MFT_REC_EXTEND);
230 	inode = ntfs_iget5(sb, &ref, &NAME_EXTEND);
231 	if (IS_ERR(inode)) {
232 		err = PTR_ERR(inode);
233 		ntfs_err(sb, "Failed to load $Extend (%d).", err);
234 		inode = NULL;
235 		goto out;
236 	}
237 
238 	/* If ntfs_iget5() reads from disk it never returns bad inode. */
239 	if (!S_ISDIR(inode->i_mode)) {
240 		err = -EINVAL;
241 		goto out;
242 	}
243 
244 	/* Try to find $ObjId */
245 	inode2 = dir_search(inode, &NAME_OBJID);
246 	if (inode2 && !IS_ERR(inode2)) {
247 		if (is_bad_inode(inode2)) {
248 			iput(inode2);
249 		} else {
250 			sbi->objid.ni = ntfs_i(inode2);
251 			sbi->objid_no = inode2->i_ino;
252 		}
253 	}
254 
255 	/* Try to find $Quota */
256 	inode2 = dir_search(inode, &NAME_QUOTA);
257 	if (inode2 && !IS_ERR(inode2)) {
258 		sbi->quota_no = inode2->i_ino;
259 		iput(inode2);
260 	}
261 
262 	/* Try to find $Reparse */
263 	inode2 = dir_search(inode, &NAME_REPARSE);
264 	if (inode2 && !IS_ERR(inode2)) {
265 		sbi->reparse.ni = ntfs_i(inode2);
266 		sbi->reparse_no = inode2->i_ino;
267 	}
268 
269 	/* Try to find $UsnJrnl */
270 	inode2 = dir_search(inode, &NAME_USNJRNL);
271 	if (inode2 && !IS_ERR(inode2)) {
272 		sbi->usn_jrnl_no = inode2->i_ino;
273 		iput(inode2);
274 	}
275 
276 	err = 0;
277 out:
278 	iput(inode);
279 	return err;
280 }
281 
ntfs_loadlog_and_replay(struct ntfs_inode * ni,struct ntfs_sb_info * sbi)282 int ntfs_loadlog_and_replay(struct ntfs_inode *ni, struct ntfs_sb_info *sbi)
283 {
284 	int err = 0;
285 	struct super_block *sb = sbi->sb;
286 	bool initialized = false;
287 	struct MFT_REF ref;
288 	struct inode *inode;
289 
290 	/* Check for 4GB. */
291 	if (ni->vfs_inode.i_size >= 0x100000000ull) {
292 		ntfs_err(sb, "\x24LogFile is large than 4G.");
293 		err = -EINVAL;
294 		goto out;
295 	}
296 
297 	sbi->flags |= NTFS_FLAGS_LOG_REPLAYING;
298 
299 	ref.low = cpu_to_le32(MFT_REC_MFT);
300 	ref.high = 0;
301 	ref.seq = cpu_to_le16(1);
302 
303 	inode = ntfs_iget5(sb, &ref, NULL);
304 
305 	if (IS_ERR(inode))
306 		inode = NULL;
307 
308 	if (!inode) {
309 		/* Try to use MFT copy. */
310 		u64 t64 = sbi->mft.lbo;
311 
312 		sbi->mft.lbo = sbi->mft.lbo2;
313 		inode = ntfs_iget5(sb, &ref, NULL);
314 		sbi->mft.lbo = t64;
315 		if (IS_ERR(inode))
316 			inode = NULL;
317 	}
318 
319 	if (!inode) {
320 		err = -EINVAL;
321 		ntfs_err(sb, "Failed to load $MFT.");
322 		goto out;
323 	}
324 
325 	sbi->mft.ni = ntfs_i(inode);
326 
327 	/* LogFile should not contains attribute list. */
328 	err = ni_load_all_mi(sbi->mft.ni);
329 	if (!err)
330 		err = log_replay(ni, &initialized);
331 
332 	iput(inode);
333 	sbi->mft.ni = NULL;
334 
335 	sync_blockdev(sb->s_bdev);
336 	invalidate_bdev(sb->s_bdev);
337 
338 	if (sbi->flags & NTFS_FLAGS_NEED_REPLAY) {
339 		err = 0;
340 		goto out;
341 	}
342 
343 	if (sb_rdonly(sb) || !initialized)
344 		goto out;
345 
346 	/* Fill LogFile by '-1' if it is initialized. */
347 	err = ntfs_bio_fill_1(sbi, &ni->file.run);
348 
349 out:
350 	sbi->flags &= ~NTFS_FLAGS_LOG_REPLAYING;
351 
352 	return err;
353 }
354 
355 /*
356  * ntfs_look_for_free_space - Look for a free space in bitmap.
357  */
ntfs_look_for_free_space(struct ntfs_sb_info * sbi,CLST lcn,CLST len,CLST * new_lcn,CLST * new_len,enum ALLOCATE_OPT opt)358 int ntfs_look_for_free_space(struct ntfs_sb_info *sbi, CLST lcn, CLST len,
359 			     CLST *new_lcn, CLST *new_len,
360 			     enum ALLOCATE_OPT opt)
361 {
362 	int err;
363 	CLST alen;
364 	struct super_block *sb = sbi->sb;
365 	size_t alcn, zlen, zeroes, zlcn, zlen2, ztrim, new_zlen;
366 	struct wnd_bitmap *wnd = &sbi->used.bitmap;
367 
368 	down_write_nested(&wnd->rw_lock, BITMAP_MUTEX_CLUSTERS);
369 	if (opt & ALLOCATE_MFT) {
370 		zlen = wnd_zone_len(wnd);
371 
372 		if (!zlen) {
373 			err = ntfs_refresh_zone(sbi);
374 			if (err)
375 				goto up_write;
376 
377 			zlen = wnd_zone_len(wnd);
378 		}
379 
380 		if (!zlen) {
381 			ntfs_err(sbi->sb, "no free space to extend mft");
382 			err = -ENOSPC;
383 			goto up_write;
384 		}
385 
386 		lcn = wnd_zone_bit(wnd);
387 		alen = min_t(CLST, len, zlen);
388 
389 		wnd_zone_set(wnd, lcn + alen, zlen - alen);
390 
391 		err = wnd_set_used(wnd, lcn, alen);
392 		if (err)
393 			goto up_write;
394 
395 		alcn = lcn;
396 		goto space_found;
397 	}
398 	/*
399 	 * 'Cause cluster 0 is always used this value means that we should use
400 	 * cached value of 'next_free_lcn' to improve performance.
401 	 */
402 	if (!lcn)
403 		lcn = sbi->used.next_free_lcn;
404 
405 	if (lcn >= wnd->nbits)
406 		lcn = 0;
407 
408 	alen = wnd_find(wnd, len, lcn, BITMAP_FIND_MARK_AS_USED, &alcn);
409 	if (alen)
410 		goto space_found;
411 
412 	/* Try to use clusters from MftZone. */
413 	zlen = wnd_zone_len(wnd);
414 	zeroes = wnd_zeroes(wnd);
415 
416 	/* Check too big request */
417 	if (len > zeroes + zlen || zlen <= NTFS_MIN_MFT_ZONE) {
418 		err = -ENOSPC;
419 		goto up_write;
420 	}
421 
422 	/* How many clusters to cat from zone. */
423 	zlcn = wnd_zone_bit(wnd);
424 	zlen2 = zlen >> 1;
425 	ztrim = clamp_val(len, zlen2, zlen);
426 	new_zlen = max_t(size_t, zlen - ztrim, NTFS_MIN_MFT_ZONE);
427 
428 	wnd_zone_set(wnd, zlcn, new_zlen);
429 
430 	/* Allocate continues clusters. */
431 	alen = wnd_find(wnd, len, 0,
432 			BITMAP_FIND_MARK_AS_USED | BITMAP_FIND_FULL, &alcn);
433 	if (!alen) {
434 		err = -ENOSPC;
435 		goto up_write;
436 	}
437 
438 space_found:
439 	err = 0;
440 	*new_len = alen;
441 	*new_lcn = alcn;
442 
443 	ntfs_unmap_meta(sb, alcn, alen);
444 
445 	/* Set hint for next requests. */
446 	if (!(opt & ALLOCATE_MFT))
447 		sbi->used.next_free_lcn = alcn + alen;
448 up_write:
449 	up_write(&wnd->rw_lock);
450 	return err;
451 }
452 
453 /*
454  * ntfs_check_free_space
455  *
456  * Check if it is possible to allocate 'clen' clusters and 'mlen' Mft records
457  */
ntfs_check_free_space(struct ntfs_sb_info * sbi,CLST clen,CLST mlen,bool da)458 bool ntfs_check_free_space(struct ntfs_sb_info *sbi, CLST clen, CLST mlen,
459 			   bool da)
460 {
461 	size_t free, zlen, avail;
462 	struct wnd_bitmap *wnd;
463 	CLST da_clusters = ntfs_get_da(sbi);
464 
465 	wnd = &sbi->used.bitmap;
466 	down_read_nested(&wnd->rw_lock, BITMAP_MUTEX_CLUSTERS);
467 	free = wnd_zeroes(wnd);
468 
469 	if (free >= da_clusters) {
470 		free -= da_clusters;
471 	} else {
472 		free = 0;
473 	}
474 
475 	zlen = min_t(size_t, NTFS_MIN_MFT_ZONE, wnd_zone_len(wnd));
476 	up_read(&wnd->rw_lock);
477 
478 	if (free < zlen + clen) {
479 		return false;
480 	}
481 
482 	avail = free - (zlen + clen);
483 
484 	/*
485 	 * When delalloc is active then keep in mind some reserved space.
486 	 * The worst case: 1 mft record per each ~500 clusters.
487 	 */
488 	if (da) {
489 		/* 1 mft record per each 1024 clusters. */
490 		mlen += da_clusters >> 10;
491 	}
492 
493 	if (mlen || !avail) {
494 		wnd = &sbi->mft.bitmap;
495 		down_read_nested(&wnd->rw_lock, BITMAP_MUTEX_MFT);
496 		free = wnd_zeroes(wnd);
497 		zlen = wnd_zone_len(wnd);
498 		up_read(&wnd->rw_lock);
499 
500 		if (free < zlen + mlen &&
501 		    avail < bytes_to_cluster(sbi, mlen << sbi->record_bits)) {
502 			return false;
503 		}
504 	}
505 
506 	return true;
507 }
508 
509 /*
510  * ntfs_extend_mft - Allocate additional MFT records.
511  *
512  * sbi->mft.bitmap is locked for write.
513  *
514  * NOTE: recursive:
515  *	ntfs_look_free_mft ->
516  *	ntfs_extend_mft ->
517  *	attr_set_size ->
518  *	ni_insert_nonresident ->
519  *	ni_insert_attr ->
520  *	ni_ins_attr_ext ->
521  *	ntfs_look_free_mft ->
522  *	ntfs_extend_mft
523  *
524  * To avoid recursive always allocate space for two new MFT records
525  * see attrib.c: "at least two MFT to avoid recursive loop".
526  */
ntfs_extend_mft(struct ntfs_sb_info * sbi)527 static int ntfs_extend_mft(struct ntfs_sb_info *sbi)
528 {
529 	int err;
530 	struct ntfs_inode *ni = sbi->mft.ni;
531 	size_t new_mft_total;
532 	u64 new_mft_bytes, new_bitmap_bytes;
533 	struct ATTRIB *attr;
534 	struct wnd_bitmap *wnd = &sbi->mft.bitmap;
535 
536 	new_mft_total = ALIGN(wnd->nbits + NTFS_MFT_INCREASE_STEP, 128);
537 	new_mft_bytes = (u64)new_mft_total << sbi->record_bits;
538 
539 	/* Step 1: Resize $MFT::DATA. */
540 	down_write(&ni->file.run_lock);
541 	err = attr_set_size_ex(ni, ATTR_DATA, NULL, 0, &ni->file.run,
542 			       new_mft_bytes, NULL, false, &attr, false);
543 
544 	if (err) {
545 		up_write(&ni->file.run_lock);
546 		goto out;
547 	}
548 
549 	attr->nres.valid_size = attr->nres.data_size;
550 	new_mft_total = le64_to_cpu(attr->nres.alloc_size) >> sbi->record_bits;
551 	ni->mi.dirty = true;
552 
553 	/* Step 2: Resize $MFT::BITMAP. */
554 	new_bitmap_bytes = ntfs3_bitmap_size(new_mft_total);
555 
556 	err = attr_set_size(ni, ATTR_BITMAP, NULL, 0, &sbi->mft.bitmap.run,
557 			    new_bitmap_bytes, &new_bitmap_bytes, true);
558 
559 	/* Refresh MFT Zone if necessary. */
560 	down_write_nested(&sbi->used.bitmap.rw_lock, BITMAP_MUTEX_CLUSTERS);
561 
562 	ntfs_refresh_zone(sbi);
563 
564 	up_write(&sbi->used.bitmap.rw_lock);
565 	up_write(&ni->file.run_lock);
566 
567 	if (err)
568 		goto out;
569 
570 	err = wnd_extend(wnd, new_mft_total);
571 
572 	if (err)
573 		goto out;
574 
575 	ntfs_clear_mft_tail(sbi, sbi->mft.used, new_mft_total);
576 
577 	err = _ni_write_inode(&ni->vfs_inode, 0);
578 out:
579 	return err;
580 }
581 
582 /*
583  * ntfs_look_free_mft - Look for a free MFT record.
584  */
ntfs_look_free_mft(struct ntfs_sb_info * sbi,CLST * rno,bool mft,struct ntfs_inode * ni,struct mft_inode ** mi)585 int ntfs_look_free_mft(struct ntfs_sb_info *sbi, CLST *rno, bool mft,
586 		       struct ntfs_inode *ni, struct mft_inode **mi)
587 {
588 	int err = 0;
589 	size_t zbit, zlen, from, to, fr;
590 	size_t mft_total;
591 	struct MFT_REF ref;
592 	struct super_block *sb = sbi->sb;
593 	struct wnd_bitmap *wnd = &sbi->mft.bitmap;
594 	u32 ir;
595 
596 	static_assert(sizeof(sbi->mft.reserved_bitmap) * 8 >=
597 		      MFT_REC_FREE - MFT_REC_RESERVED);
598 
599 	if (!mft)
600 		down_write_nested(&wnd->rw_lock, BITMAP_MUTEX_MFT);
601 
602 	zlen = wnd_zone_len(wnd);
603 
604 	/* Always reserve space for MFT. */
605 	if (zlen) {
606 		if (mft) {
607 			zbit = wnd_zone_bit(wnd);
608 			*rno = zbit;
609 			wnd_zone_set(wnd, zbit + 1, zlen - 1);
610 		}
611 		goto found;
612 	}
613 
614 	/* No MFT zone. Find the nearest to '0' free MFT. */
615 	if (!wnd_find(wnd, 1, MFT_REC_FREE, 0, &zbit)) {
616 		/* Resize MFT */
617 		mft_total = wnd->nbits;
618 
619 		err = ntfs_extend_mft(sbi);
620 		if (!err) {
621 			zbit = mft_total;
622 			goto reserve_mft;
623 		}
624 
625 		if (!mft || MFT_REC_FREE == sbi->mft.next_reserved)
626 			goto out;
627 
628 		err = 0;
629 
630 		/*
631 		 * Look for free record reserved area [11-16) ==
632 		 * [MFT_REC_RESERVED, MFT_REC_FREE ) MFT bitmap always
633 		 * marks it as used.
634 		 */
635 		if (!sbi->mft.reserved_bitmap) {
636 			/* Once per session create internal bitmap for 5 bits. */
637 			sbi->mft.reserved_bitmap = 0xFF;
638 
639 			ref.high = 0;
640 			for (ir = MFT_REC_RESERVED; ir < MFT_REC_FREE; ir++) {
641 				struct inode *i;
642 				struct ntfs_inode *ni;
643 				struct MFT_REC *mrec;
644 
645 				ref.low = cpu_to_le32(ir);
646 				ref.seq = cpu_to_le16(ir);
647 
648 				i = ntfs_iget5(sb, &ref, NULL);
649 				if (IS_ERR(i)) {
650 next:
651 					ntfs_notice(
652 						sb,
653 						"Invalid reserved record %x",
654 						ref.low);
655 					continue;
656 				}
657 				if (is_bad_inode(i)) {
658 					iput(i);
659 					goto next;
660 				}
661 
662 				ni = ntfs_i(i);
663 
664 				mrec = ni->mi.mrec;
665 
666 				if (!is_rec_base(mrec))
667 					goto next;
668 
669 				if (mrec->hard_links)
670 					goto next;
671 
672 				if (!ni_std(ni))
673 					goto next;
674 
675 				if (ni_find_attr(ni, NULL, NULL, ATTR_NAME,
676 						 NULL, 0, NULL, NULL))
677 					goto next;
678 
679 				__clear_bit(ir - MFT_REC_RESERVED,
680 					    &sbi->mft.reserved_bitmap);
681 			}
682 		}
683 
684 		/* Scan 5 bits for zero. Bit 0 == MFT_REC_RESERVED */
685 		zbit = find_next_zero_bit(&sbi->mft.reserved_bitmap,
686 					  MFT_REC_FREE, MFT_REC_RESERVED);
687 		if (zbit >= MFT_REC_FREE) {
688 			sbi->mft.next_reserved = MFT_REC_FREE;
689 			goto out;
690 		}
691 
692 		zlen = 1;
693 		sbi->mft.next_reserved = zbit;
694 	} else {
695 reserve_mft:
696 		zlen = zbit == MFT_REC_FREE ? (MFT_REC_USER - MFT_REC_FREE) : 4;
697 		if (zbit + zlen > wnd->nbits)
698 			zlen = wnd->nbits - zbit;
699 
700 		while (zlen > 1 && !wnd_is_free(wnd, zbit, zlen))
701 			zlen -= 1;
702 
703 		/* [zbit, zbit + zlen) will be used for MFT itself. */
704 		from = sbi->mft.used;
705 		if (from < zbit)
706 			from = zbit;
707 		to = zbit + zlen;
708 		if (from < to) {
709 			ntfs_clear_mft_tail(sbi, from, to);
710 			sbi->mft.used = to;
711 		}
712 	}
713 
714 	if (mft) {
715 		*rno = zbit;
716 		zbit += 1;
717 		zlen -= 1;
718 	}
719 
720 	wnd_zone_set(wnd, zbit, zlen);
721 
722 found:
723 	if (!mft) {
724 		/* The request to get record for general purpose. */
725 		if (sbi->mft.next_free < MFT_REC_USER)
726 			sbi->mft.next_free = MFT_REC_USER;
727 
728 		for (;;) {
729 			if (sbi->mft.next_free >= sbi->mft.bitmap.nbits) {
730 			} else if (!wnd_find(wnd, 1, MFT_REC_USER, 0, &fr)) {
731 				sbi->mft.next_free = sbi->mft.bitmap.nbits;
732 			} else {
733 				*rno = fr;
734 				sbi->mft.next_free = *rno + 1;
735 				break;
736 			}
737 
738 			err = ntfs_extend_mft(sbi);
739 			if (err)
740 				goto out;
741 		}
742 	}
743 
744 	if (ni && !ni_add_subrecord(ni, *rno, mi)) {
745 		err = -ENOMEM;
746 		goto out;
747 	}
748 
749 	/* We have found a record that are not reserved for next MFT. */
750 	if (*rno >= MFT_REC_FREE)
751 		wnd_set_used(wnd, *rno, 1);
752 	else if (*rno >= MFT_REC_RESERVED && sbi->mft.reserved_bitmap_inited)
753 		__set_bit(*rno - MFT_REC_RESERVED, &sbi->mft.reserved_bitmap);
754 
755 out:
756 	if (!mft)
757 		up_write(&wnd->rw_lock);
758 
759 	return err;
760 }
761 
762 /*
763  * ntfs_mark_rec_free - Mark record as free.
764  * is_mft - true if we are changing MFT
765  */
ntfs_mark_rec_free(struct ntfs_sb_info * sbi,CLST rno,bool is_mft)766 void ntfs_mark_rec_free(struct ntfs_sb_info *sbi, CLST rno, bool is_mft)
767 {
768 	struct wnd_bitmap *wnd = &sbi->mft.bitmap;
769 
770 	if (!is_mft)
771 		down_write_nested(&wnd->rw_lock, BITMAP_MUTEX_MFT);
772 	if (rno >= wnd->nbits)
773 		goto out;
774 
775 	if (rno >= MFT_REC_FREE) {
776 		if (!wnd_is_used(wnd, rno, 1))
777 			ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
778 		else
779 			wnd_set_free(wnd, rno, 1);
780 	} else if (rno >= MFT_REC_RESERVED && sbi->mft.reserved_bitmap_inited) {
781 		__clear_bit(rno - MFT_REC_RESERVED, &sbi->mft.reserved_bitmap);
782 	}
783 
784 	if (rno < wnd_zone_bit(wnd))
785 		wnd_zone_set(wnd, rno, 1);
786 	else if (rno < sbi->mft.next_free && rno >= MFT_REC_USER)
787 		sbi->mft.next_free = rno;
788 
789 out:
790 	if (!is_mft)
791 		up_write(&wnd->rw_lock);
792 }
793 
794 /*
795  * ntfs_clear_mft_tail - Format empty records [from, to).
796  *
797  * sbi->mft.bitmap is locked for write.
798  */
ntfs_clear_mft_tail(struct ntfs_sb_info * sbi,size_t from,size_t to)799 int ntfs_clear_mft_tail(struct ntfs_sb_info *sbi, size_t from, size_t to)
800 {
801 	int err;
802 	u32 rs;
803 	u64 vbo;
804 	struct runs_tree *run;
805 	struct ntfs_inode *ni;
806 
807 	if (from >= to)
808 		return 0;
809 
810 	rs = sbi->record_size;
811 	ni = sbi->mft.ni;
812 	run = &ni->file.run;
813 
814 	down_read(&ni->file.run_lock);
815 	vbo = (u64)from * rs;
816 	for (; from < to; from++, vbo += rs) {
817 		struct ntfs_buffers nb;
818 
819 		err = ntfs_get_bh(sbi, run, vbo, rs, &nb);
820 		if (err)
821 			goto out;
822 
823 		err = ntfs_write_bh(sbi, &sbi->new_rec->rhdr, &nb, 0);
824 		nb_put(&nb);
825 		if (err)
826 			goto out;
827 	}
828 
829 out:
830 	sbi->mft.used = from;
831 	up_read(&ni->file.run_lock);
832 	return err;
833 }
834 
835 /*
836  * ntfs_refresh_zone - Refresh MFT zone.
837  *
838  * sbi->used.bitmap is locked for rw.
839  * sbi->mft.bitmap is locked for write.
840  * sbi->mft.ni->file.run_lock for write.
841  */
ntfs_refresh_zone(struct ntfs_sb_info * sbi)842 int ntfs_refresh_zone(struct ntfs_sb_info *sbi)
843 {
844 	CLST lcn, vcn, len;
845 	size_t lcn_s, zlen;
846 	struct wnd_bitmap *wnd = &sbi->used.bitmap;
847 	struct ntfs_inode *ni = sbi->mft.ni;
848 
849 	/* Do not change anything unless we have non empty MFT zone. */
850 	if (wnd_zone_len(wnd))
851 		return 0;
852 
853 	vcn = bytes_to_cluster(sbi,
854 			       (u64)sbi->mft.bitmap.nbits << sbi->record_bits);
855 
856 	if (!run_lookup_entry(&ni->file.run, vcn - 1, &lcn, &len, NULL))
857 		lcn = SPARSE_LCN;
858 
859 	/* We should always find Last Lcn for MFT. */
860 	if (lcn == SPARSE_LCN)
861 		return -EINVAL;
862 
863 	lcn_s = lcn + 1;
864 
865 	/* Try to allocate clusters after last MFT run. */
866 	zlen = wnd_find(wnd, sbi->zone_max, lcn_s, 0, &lcn_s);
867 	wnd_zone_set(wnd, lcn_s, zlen);
868 
869 	return 0;
870 }
871 
872 /*
873  * ntfs_update_mftmirr - Update $MFTMirr data.
874  */
ntfs_update_mftmirr(struct ntfs_sb_info * sbi)875 void ntfs_update_mftmirr(struct ntfs_sb_info *sbi)
876 {
877 	struct super_block *sb = sbi->sb;
878 	u32 blocksize, bytes;
879 	sector_t block1, block2;
880 
881 	/*
882 	 * sb can be NULL here. In this case sbi->flags should be 0 too.
883 	 */
884 	if (!sb || !(sbi->flags & NTFS_FLAGS_MFTMIRR) ||
885 	    unlikely(ntfs3_forced_shutdown(sb)))
886 		return;
887 
888 	blocksize = sb->s_blocksize;
889 	bytes = sbi->mft.recs_mirr << sbi->record_bits;
890 	block1 = sbi->mft.lbo >> sb->s_blocksize_bits;
891 	block2 = sbi->mft.lbo2 >> sb->s_blocksize_bits;
892 
893 	for (; bytes >= blocksize; bytes -= blocksize) {
894 		struct buffer_head *bh1, *bh2;
895 
896 		bh1 = sb_bread(sb, block1++);
897 		if (!bh1)
898 			return;
899 
900 		bh2 = sb_getblk(sb, block2++);
901 		if (!bh2) {
902 			put_bh(bh1);
903 			return;
904 		}
905 
906 		wait_on_buffer(bh2);
907 		lock_buffer(bh2);
908 		memcpy(bh2->b_data, bh1->b_data, blocksize);
909 		set_buffer_uptodate(bh2);
910 		mark_buffer_dirty(bh2);
911 		unlock_buffer(bh2);
912 
913 		put_bh(bh1);
914 		bh1 = NULL;
915 		put_bh(bh2);
916 	}
917 
918 	sbi->flags &= ~NTFS_FLAGS_MFTMIRR;
919 }
920 
921 /*
922  * ntfs_bad_inode
923  *
924  * Marks inode as bad and marks fs as 'dirty'
925  */
ntfs_bad_inode(struct inode * inode,const char * hint)926 void ntfs_bad_inode(struct inode *inode, const char *hint)
927 {
928 	struct ntfs_sb_info *sbi = inode->i_sb->s_fs_info;
929 	struct ntfs_inode *ni = ntfs_i(inode);
930 
931 	ntfs_inode_err(inode, "%s", hint);
932 
933 	/* Do not call make_bad_inode()! */
934 	ni->ni_bad = true;
935 
936 	/* Avoid recursion if bad inode is $Volume. */
937 	if (inode->i_ino != MFT_REC_VOL &&
938 	    !(sbi->flags & NTFS_FLAGS_LOG_REPLAYING)) {
939 		ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
940 	}
941 }
942 
943 /*
944  * ntfs_set_state
945  *
946  * Mount: ntfs_set_state(NTFS_DIRTY_DIRTY)
947  * Umount: ntfs_set_state(NTFS_DIRTY_CLEAR)
948  * NTFS error: ntfs_set_state(NTFS_DIRTY_ERROR)
949  */
ntfs_set_state(struct ntfs_sb_info * sbi,enum NTFS_DIRTY_FLAGS dirty)950 int ntfs_set_state(struct ntfs_sb_info *sbi, enum NTFS_DIRTY_FLAGS dirty)
951 {
952 	int err;
953 	struct ATTRIB *attr;
954 	struct VOLUME_INFO *info;
955 	struct mft_inode *mi;
956 	struct ntfs_inode *ni;
957 	__le16 info_flags;
958 
959 	/*
960 	 * Do not change state if fs was real_dirty.
961 	 * Do not change state if fs already dirty(clear).
962 	 * Do not change any thing if mounted read only.
963 	 */
964 	if (sbi->volume.real_dirty || sb_rdonly(sbi->sb))
965 		return 0;
966 
967 	/* Check cached value. */
968 	if ((dirty == NTFS_DIRTY_CLEAR ? 0 : VOLUME_FLAG_DIRTY) ==
969 	    (sbi->volume.flags & VOLUME_FLAG_DIRTY))
970 		return 0;
971 
972 	ni = sbi->volume.ni;
973 	if (!ni)
974 		return -EINVAL;
975 
976 	mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_DIRTY);
977 
978 	attr = ni_find_attr(ni, NULL, NULL, ATTR_VOL_INFO, NULL, 0, NULL, &mi);
979 	if (!attr) {
980 		err = -EINVAL;
981 		goto out;
982 	}
983 
984 	info = resident_data_ex(attr, SIZEOF_ATTRIBUTE_VOLUME_INFO);
985 	if (!info) {
986 		err = -EINVAL;
987 		goto out;
988 	}
989 
990 	info_flags = info->flags;
991 
992 	switch (dirty) {
993 	case NTFS_DIRTY_ERROR:
994 		ntfs_notice(sbi->sb, "Mark volume as dirty due to NTFS errors");
995 		sbi->volume.real_dirty = true;
996 		fallthrough;
997 	case NTFS_DIRTY_DIRTY:
998 		info->flags |= VOLUME_FLAG_DIRTY;
999 		break;
1000 	case NTFS_DIRTY_CLEAR:
1001 		info->flags &= ~VOLUME_FLAG_DIRTY;
1002 		break;
1003 	}
1004 	/* Cache current volume flags. */
1005 	if (info_flags != info->flags) {
1006 		sbi->volume.flags = info->flags;
1007 		mi->dirty = true;
1008 	}
1009 	err = 0;
1010 
1011 out:
1012 	ni_unlock(ni);
1013 	if (err)
1014 		return err;
1015 
1016 	mark_inode_dirty_sync(&ni->vfs_inode);
1017 	/* verify(!ntfs_update_mftmirr()); */
1018 
1019 	/* write mft record on disk. */
1020 	err = _ni_write_inode(&ni->vfs_inode, 1);
1021 
1022 	return err;
1023 }
1024 
1025 /*
1026  * security_hash - Calculates a hash of security descriptor.
1027  */
security_hash(const void * sd,size_t bytes)1028 static inline __le32 security_hash(const void *sd, size_t bytes)
1029 {
1030 	u32 hash = 0;
1031 	const __le32 *ptr = sd;
1032 
1033 	bytes >>= 2;
1034 	while (bytes--)
1035 		hash = ((hash >> 0x1D) | (hash << 3)) + le32_to_cpu(*ptr++);
1036 	return cpu_to_le32(hash);
1037 }
1038 
1039 /*
1040  * simple wrapper for sb_bread_unmovable.
1041  */
ntfs_bread(struct super_block * sb,sector_t block)1042 struct buffer_head *ntfs_bread(struct super_block *sb, sector_t block)
1043 {
1044 	struct ntfs_sb_info *sbi = sb->s_fs_info;
1045 	struct buffer_head *bh;
1046 
1047 	if (unlikely(block >= sbi->volume.blocks)) {
1048 		/* prevent generic message "attempt to access beyond end of device" */
1049 		ntfs_err(sb, "try to read out of volume at offset 0x%llx",
1050 			 (u64)block << sb->s_blocksize_bits);
1051 		return NULL;
1052 	}
1053 
1054 	bh = sb_bread_unmovable(sb, block);
1055 	if (bh)
1056 		return bh;
1057 
1058 	ntfs_err(sb, "failed to read volume at offset 0x%llx",
1059 		 (u64)block << sb->s_blocksize_bits);
1060 	return NULL;
1061 }
1062 
ntfs_sb_write(struct super_block * sb,u64 lbo,size_t bytes,const void * buf,int wait)1063 int ntfs_sb_write(struct super_block *sb, u64 lbo, size_t bytes,
1064 		  const void *buf, int wait)
1065 {
1066 	u32 blocksize = sb->s_blocksize;
1067 	struct block_device *bdev = sb->s_bdev;
1068 	sector_t block = lbo >> sb->s_blocksize_bits;
1069 	u32 off = lbo & (blocksize - 1);
1070 	u32 op = blocksize - off;
1071 	struct buffer_head *bh;
1072 
1073 	if (!wait && (sb->s_flags & SB_SYNCHRONOUS))
1074 		wait = 1;
1075 
1076 	for (; bytes; block += 1, off = 0, op = blocksize) {
1077 		if (op > bytes)
1078 			op = bytes;
1079 
1080 		if (op < blocksize) {
1081 			bh = __bread(bdev, block, blocksize);
1082 			if (!bh) {
1083 				ntfs_err(sb, "failed to read block %llx",
1084 					 (u64)block);
1085 				return -EIO;
1086 			}
1087 		} else {
1088 			bh = __getblk(bdev, block, blocksize);
1089 			if (!bh)
1090 				return -ENOMEM;
1091 		}
1092 
1093 		wait_on_buffer(bh);
1094 		lock_buffer(bh);
1095 		if (buf) {
1096 			memcpy(bh->b_data + off, buf, op);
1097 			buf = Add2Ptr(buf, op);
1098 		} else {
1099 			memset(bh->b_data + off, -1, op);
1100 		}
1101 
1102 		set_buffer_uptodate(bh);
1103 		mark_buffer_dirty(bh);
1104 		unlock_buffer(bh);
1105 
1106 		if (wait) {
1107 			int err = sync_dirty_buffer(bh);
1108 
1109 			if (err) {
1110 				ntfs_err(
1111 					sb,
1112 					"failed to sync buffer at block %llx, error %d",
1113 					(u64)block, err);
1114 				put_bh(bh);
1115 				return err;
1116 			}
1117 		}
1118 
1119 		put_bh(bh);
1120 
1121 		bytes -= op;
1122 	}
1123 	return 0;
1124 }
1125 
ntfs_sb_write_run(struct ntfs_sb_info * sbi,const struct runs_tree * run,u64 vbo,const void * buf,size_t bytes,int sync)1126 int ntfs_sb_write_run(struct ntfs_sb_info *sbi, const struct runs_tree *run,
1127 		      u64 vbo, const void *buf, size_t bytes, int sync)
1128 {
1129 	struct super_block *sb = sbi->sb;
1130 	u8 cluster_bits = sbi->cluster_bits;
1131 	u32 off = vbo & sbi->cluster_mask;
1132 	CLST lcn, clen, vcn = vbo >> cluster_bits, vcn_next;
1133 	u64 lbo, len;
1134 	size_t idx;
1135 
1136 	if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx))
1137 		return -ENOENT;
1138 
1139 	if (lcn == SPARSE_LCN)
1140 		return -EINVAL;
1141 
1142 	lbo = ((u64)lcn << cluster_bits) + off;
1143 	len = ((u64)clen << cluster_bits) - off;
1144 
1145 	for (;;) {
1146 		u32 op = min_t(u64, len, bytes);
1147 		int err = ntfs_sb_write(sb, lbo, op, buf, sync);
1148 
1149 		if (err)
1150 			return err;
1151 
1152 		bytes -= op;
1153 		if (!bytes)
1154 			break;
1155 
1156 		vcn_next = vcn + clen;
1157 		if (!run_get_entry(run, ++idx, &vcn, &lcn, &clen) ||
1158 		    vcn != vcn_next)
1159 			return -ENOENT;
1160 
1161 		if (lcn == SPARSE_LCN)
1162 			return -EINVAL;
1163 
1164 		if (buf)
1165 			buf = Add2Ptr(buf, op);
1166 
1167 		lbo = ((u64)lcn << cluster_bits);
1168 		len = ((u64)clen << cluster_bits);
1169 	}
1170 
1171 	return 0;
1172 }
1173 
ntfs_bread_run(struct ntfs_sb_info * sbi,const struct runs_tree * run,u64 vbo)1174 struct buffer_head *ntfs_bread_run(struct ntfs_sb_info *sbi,
1175 				   const struct runs_tree *run, u64 vbo)
1176 {
1177 	struct super_block *sb = sbi->sb;
1178 	u8 cluster_bits = sbi->cluster_bits;
1179 	CLST lcn;
1180 	u64 lbo;
1181 
1182 	if (!run_lookup_entry(run, vbo >> cluster_bits, &lcn, NULL, NULL))
1183 		return ERR_PTR(-ENOENT);
1184 
1185 	lbo = ((u64)lcn << cluster_bits) + (vbo & sbi->cluster_mask);
1186 
1187 	return ntfs_bread(sb, lbo >> sb->s_blocksize_bits);
1188 }
1189 
ntfs_read_run_nb_ra(struct ntfs_sb_info * sbi,const struct runs_tree * run,u64 vbo,void * buf,u32 bytes,struct ntfs_buffers * nb,struct file_ra_state * ra)1190 int ntfs_read_run_nb_ra(struct ntfs_sb_info *sbi, const struct runs_tree *run,
1191 			u64 vbo, void *buf, u32 bytes, struct ntfs_buffers *nb,
1192 			struct file_ra_state *ra)
1193 {
1194 	int err;
1195 	struct super_block *sb = sbi->sb;
1196 	struct address_space *mapping = sb->s_bdev->bd_mapping;
1197 	u32 blocksize = sb->s_blocksize;
1198 	u8 cluster_bits = sbi->cluster_bits;
1199 	u32 off = vbo & sbi->cluster_mask;
1200 	u32 nbh = 0;
1201 	CLST vcn_next, vcn = vbo >> cluster_bits;
1202 	CLST lcn, clen;
1203 	u64 lbo, len;
1204 	size_t idx;
1205 	struct buffer_head *bh;
1206 
1207 	if (!run) {
1208 		/* First reading of $Volume + $MFTMirr + $LogFile goes here. */
1209 		if (vbo > MFT_REC_VOL * sbi->record_size) {
1210 			err = -ENOENT;
1211 			goto out;
1212 		}
1213 
1214 		/* Use absolute boot's 'MFTCluster' to read record. */
1215 		lbo = vbo + sbi->mft.lbo;
1216 		len = sbi->record_size;
1217 	} else if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx)) {
1218 		err = -ENOENT;
1219 		goto out;
1220 	} else {
1221 		if (lcn == SPARSE_LCN) {
1222 			err = -EINVAL;
1223 			goto out;
1224 		}
1225 
1226 		lbo = ((u64)lcn << cluster_bits) + off;
1227 		len = ((u64)clen << cluster_bits) - off;
1228 	}
1229 
1230 	off = lbo & (blocksize - 1);
1231 	if (nb) {
1232 		nb->off = off;
1233 		nb->bytes = bytes;
1234 	}
1235 
1236 	if (ra && !ra->ra_pages)
1237 		file_ra_state_init(ra, mapping);
1238 
1239 	for (;;) {
1240 		u32 len32 = len >= bytes ? bytes : len;
1241 		sector_t block = lbo >> sb->s_blocksize_bits;
1242 
1243 		if (ra) {
1244 			pgoff_t index = lbo >> PAGE_SHIFT;
1245 			if (!ra_has_index(ra, index)) {
1246 				page_cache_sync_readahead(mapping, ra, NULL,
1247 							  index, 1);
1248 				ra->prev_pos = (loff_t)index << PAGE_SHIFT;
1249 			}
1250 		}
1251 
1252 		do {
1253 			u32 op = blocksize - off;
1254 
1255 			if (op > len32)
1256 				op = len32;
1257 
1258 			bh = ntfs_bread(sb, block);
1259 			if (!bh) {
1260 				err = -EIO;
1261 				goto out;
1262 			}
1263 
1264 			if (buf) {
1265 				memcpy(buf, bh->b_data + off, op);
1266 				buf = Add2Ptr(buf, op);
1267 			}
1268 
1269 			if (!nb) {
1270 				put_bh(bh);
1271 			} else if (nbh >= ARRAY_SIZE(nb->bh)) {
1272 				err = -EINVAL;
1273 				goto out;
1274 			} else {
1275 				nb->bh[nbh++] = bh;
1276 				nb->nbufs = nbh;
1277 			}
1278 
1279 			bytes -= op;
1280 			if (!bytes)
1281 				return 0;
1282 			len32 -= op;
1283 			block += 1;
1284 			off = 0;
1285 
1286 		} while (len32);
1287 
1288 		if (!run) {
1289 			err = -EINVAL;
1290 			goto out;
1291 		}
1292 
1293 		/* Get next fragment to read. */
1294 		vcn_next = vcn + clen;
1295 		if (!run_get_entry(run, ++idx, &vcn, &lcn, &clen) ||
1296 		    vcn != vcn_next) {
1297 			err = -ENOENT;
1298 			goto out;
1299 		}
1300 
1301 		if (lcn == SPARSE_LCN) {
1302 			err = -EINVAL;
1303 			goto out;
1304 		}
1305 
1306 		lbo = ((u64)lcn << cluster_bits);
1307 		len = ((u64)clen << cluster_bits);
1308 	}
1309 
1310 out:
1311 	if (!nbh)
1312 		return err;
1313 
1314 	while (nbh) {
1315 		put_bh(nb->bh[--nbh]);
1316 		nb->bh[nbh] = NULL;
1317 	}
1318 
1319 	nb->nbufs = 0;
1320 	return err;
1321 }
1322 
1323 /*
1324  * ntfs_read_bh
1325  *
1326  * Return: < 0 if error, 0 if ok, -E_NTFS_FIXUP if need to update fixups.
1327  */
ntfs_read_bh_ra(struct ntfs_sb_info * sbi,const struct runs_tree * run,u64 vbo,struct NTFS_RECORD_HEADER * rhdr,u32 bytes,struct ntfs_buffers * nb,struct file_ra_state * ra)1328 int ntfs_read_bh_ra(struct ntfs_sb_info *sbi, const struct runs_tree *run,
1329 		    u64 vbo, struct NTFS_RECORD_HEADER *rhdr, u32 bytes,
1330 		    struct ntfs_buffers *nb, struct file_ra_state *ra)
1331 {
1332 	int err = ntfs_read_run_nb_ra(sbi, run, vbo, rhdr, bytes, nb, ra);
1333 
1334 	if (err)
1335 		return err;
1336 	return ntfs_fix_post_read(rhdr, nb->bytes, true);
1337 }
1338 
ntfs_get_bh(struct ntfs_sb_info * sbi,const struct runs_tree * run,u64 vbo,u32 bytes,struct ntfs_buffers * nb)1339 int ntfs_get_bh(struct ntfs_sb_info *sbi, const struct runs_tree *run, u64 vbo,
1340 		u32 bytes, struct ntfs_buffers *nb)
1341 {
1342 	int err = 0;
1343 	struct super_block *sb = sbi->sb;
1344 	u32 blocksize = sb->s_blocksize;
1345 	u8 cluster_bits = sbi->cluster_bits;
1346 	CLST vcn_next, vcn = vbo >> cluster_bits;
1347 	u32 off;
1348 	u32 nbh = 0;
1349 	CLST lcn, clen;
1350 	u64 lbo, len;
1351 	size_t idx;
1352 
1353 	nb->bytes = bytes;
1354 
1355 	if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx)) {
1356 		err = -ENOENT;
1357 		goto out;
1358 	}
1359 
1360 	off = vbo & sbi->cluster_mask;
1361 	lbo = ((u64)lcn << cluster_bits) + off;
1362 	len = ((u64)clen << cluster_bits) - off;
1363 
1364 	nb->off = off = lbo & (blocksize - 1);
1365 
1366 	for (;;) {
1367 		u32 len32 = min_t(u64, len, bytes);
1368 		sector_t block = lbo >> sb->s_blocksize_bits;
1369 
1370 		do {
1371 			u32 op;
1372 			struct buffer_head *bh;
1373 
1374 			if (nbh >= ARRAY_SIZE(nb->bh)) {
1375 				err = -EINVAL;
1376 				goto out;
1377 			}
1378 
1379 			op = blocksize - off;
1380 			if (op > len32)
1381 				op = len32;
1382 
1383 			if (op == blocksize) {
1384 				bh = sb_getblk(sb, block);
1385 				if (!bh) {
1386 					err = -ENOMEM;
1387 					goto out;
1388 				}
1389 				wait_on_buffer(bh);
1390 				lock_buffer(bh);
1391 				if (!buffer_uptodate(bh)) {
1392 					memset(bh->b_data, 0, blocksize);
1393 					set_buffer_uptodate(bh);
1394 				}
1395 				unlock_buffer(bh);
1396 			} else {
1397 				bh = ntfs_bread(sb, block);
1398 				if (!bh) {
1399 					err = -EIO;
1400 					goto out;
1401 				}
1402 			}
1403 
1404 			nb->bh[nbh++] = bh;
1405 			bytes -= op;
1406 			if (!bytes) {
1407 				nb->nbufs = nbh;
1408 				return 0;
1409 			}
1410 
1411 			block += 1;
1412 			len32 -= op;
1413 			off = 0;
1414 		} while (len32);
1415 
1416 		vcn_next = vcn + clen;
1417 		if (!run_get_entry(run, ++idx, &vcn, &lcn, &clen) ||
1418 		    vcn != vcn_next) {
1419 			err = -ENOENT;
1420 			goto out;
1421 		}
1422 
1423 		lbo = ((u64)lcn << cluster_bits);
1424 		len = ((u64)clen << cluster_bits);
1425 	}
1426 
1427 out:
1428 	while (nbh) {
1429 		put_bh(nb->bh[--nbh]);
1430 		nb->bh[nbh] = NULL;
1431 	}
1432 
1433 	nb->nbufs = 0;
1434 
1435 	return err;
1436 }
1437 
ntfs_write_bh(struct ntfs_sb_info * sbi,struct NTFS_RECORD_HEADER * rhdr,struct ntfs_buffers * nb,int sync)1438 int ntfs_write_bh(struct ntfs_sb_info *sbi, struct NTFS_RECORD_HEADER *rhdr,
1439 		  struct ntfs_buffers *nb, int sync)
1440 {
1441 	int err = 0;
1442 	struct super_block *sb = sbi->sb;
1443 	u32 block_size = sb->s_blocksize;
1444 	u32 bytes = nb->bytes;
1445 	u32 off = nb->off;
1446 	u16 fo = le16_to_cpu(rhdr->fix_off);
1447 	u16 fn = le16_to_cpu(rhdr->fix_num);
1448 	u32 idx;
1449 	__le16 *fixup = NULL;
1450 	__le16 sample = cpu_to_le16(-1u);
1451 
1452 	if ((fo & 1) || fo + fn * sizeof(short) > SECTOR_SIZE || !fn-- ||
1453 	    fn * SECTOR_SIZE > bytes) {
1454 		return -EINVAL;
1455 	}
1456 
1457 	for (idx = 0; bytes && idx < nb->nbufs; idx += 1, off = 0) {
1458 		u32 op = block_size - off;
1459 		char *bh_data;
1460 		struct buffer_head *bh = nb->bh[idx];
1461 		__le16 *ptr, *end_data;
1462 
1463 		if (op > bytes)
1464 			op = bytes;
1465 
1466 		wait_on_buffer(bh);
1467 		lock_buffer(bh);
1468 
1469 		bh_data = bh->b_data + off;
1470 		end_data = Add2Ptr(bh_data, op);
1471 		memcpy(bh_data, rhdr, op);
1472 
1473 		if (!idx) {
1474 			u16 t16;
1475 
1476 			fixup = Add2Ptr(bh_data, fo);
1477 			sample = *fixup;
1478 			t16 = le16_to_cpu(sample);
1479 			if (t16 >= 0x7FFF) {
1480 				sample = *fixup = cpu_to_le16(1);
1481 			} else {
1482 				sample = cpu_to_le16(t16 + 1);
1483 				*fixup = sample;
1484 			}
1485 
1486 			*(__le16 *)Add2Ptr(rhdr, fo) = sample;
1487 		}
1488 
1489 		ptr = Add2Ptr(bh_data, SECTOR_SIZE - sizeof(short));
1490 
1491 		do {
1492 			*++fixup = *ptr;
1493 			*ptr = sample;
1494 			ptr += SECTOR_SIZE / sizeof(short);
1495 		} while (ptr < end_data);
1496 
1497 		set_buffer_uptodate(bh);
1498 		mark_buffer_dirty(bh);
1499 		unlock_buffer(bh);
1500 
1501 		if (sync) {
1502 			int err2 = sync_dirty_buffer(bh);
1503 
1504 			if (!err && err2)
1505 				err = err2;
1506 		}
1507 
1508 		bytes -= op;
1509 		rhdr = Add2Ptr(rhdr, op);
1510 	}
1511 
1512 	return err;
1513 }
1514 
1515 /*
1516  * ntfs_read_write_run - Read/Write disk's page cache.
1517  */
ntfs_read_write_run(struct ntfs_sb_info * sbi,const struct runs_tree * run,void * buf,u64 vbo,size_t bytes,int wr)1518 int ntfs_read_write_run(struct ntfs_sb_info *sbi, const struct runs_tree *run,
1519 			void *buf, u64 vbo, size_t bytes, int wr)
1520 {
1521 	struct super_block *sb = sbi->sb;
1522 	struct address_space *mapping = sb->s_bdev->bd_mapping;
1523 	u8 cluster_bits = sbi->cluster_bits;
1524 	CLST vcn_next, vcn = vbo >> cluster_bits;
1525 	CLST lcn, clen;
1526 	u64 lbo, len;
1527 	size_t idx;
1528 	u32 off, op;
1529 	struct folio *folio;
1530 	char *kaddr;
1531 
1532 	if (!bytes)
1533 		return 0;
1534 
1535 	if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx))
1536 		return -ENOENT;
1537 
1538 	if (lcn == SPARSE_LCN)
1539 		return -EINVAL;
1540 
1541 	off = vbo & sbi->cluster_mask;
1542 	lbo = ((u64)lcn << cluster_bits) + off;
1543 	len = ((u64)clen << cluster_bits) - off;
1544 
1545 	for (;;) {
1546 		/* Read range [lbo, lbo+len). */
1547 		folio = read_mapping_folio(mapping, lbo >> PAGE_SHIFT, NULL);
1548 
1549 		if (IS_ERR(folio))
1550 			return PTR_ERR(folio);
1551 
1552 		off = offset_in_page(lbo);
1553 		op = PAGE_SIZE - off;
1554 
1555 		if (op > len)
1556 			op = len;
1557 		if (op > bytes)
1558 			op = bytes;
1559 
1560 		kaddr = kmap_local_folio(folio, 0);
1561 		if (wr) {
1562 			memcpy(kaddr + off, buf, op);
1563 			folio_mark_dirty(folio);
1564 		} else {
1565 			memcpy(buf, kaddr + off, op);
1566 			flush_dcache_folio(folio);
1567 		}
1568 		kunmap_local(kaddr);
1569 		folio_put(folio);
1570 
1571 		bytes -= op;
1572 		if (!bytes)
1573 			return 0;
1574 
1575 		buf += op;
1576 		len -= op;
1577 		if (len) {
1578 			/* next volume's page. */
1579 			lbo += op;
1580 			continue;
1581 		}
1582 
1583 		/* get next range. */
1584 		vcn_next = vcn + clen;
1585 		if (!run_get_entry(run, ++idx, &vcn, &lcn, &clen) ||
1586 		    vcn != vcn_next) {
1587 			return -ENOENT;
1588 		}
1589 
1590 		if (lcn == SPARSE_LCN)
1591 			return -EINVAL;
1592 
1593 		lbo = ((u64)lcn << cluster_bits);
1594 		len = ((u64)clen << cluster_bits);
1595 	}
1596 }
1597 
1598 /*
1599  * ntfs_bio_fill_1 - Helper for ntfs_loadlog_and_replay().
1600  *
1601  * Fill on-disk logfile range by (-1)
1602  * this means empty logfile.
1603  */
ntfs_bio_fill_1(struct ntfs_sb_info * sbi,const struct runs_tree * run)1604 int ntfs_bio_fill_1(struct ntfs_sb_info *sbi, const struct runs_tree *run)
1605 {
1606 	int err = 0;
1607 	struct super_block *sb = sbi->sb;
1608 	struct block_device *bdev = sb->s_bdev;
1609 	u8 cluster_bits = sbi->cluster_bits;
1610 	struct bio *new, *bio = NULL;
1611 	CLST lcn, clen;
1612 	u64 lbo, len;
1613 	size_t run_idx;
1614 	struct page *fill;
1615 	void *kaddr;
1616 	struct blk_plug plug;
1617 
1618 	fill = alloc_page(GFP_KERNEL);
1619 	if (!fill)
1620 		return -ENOMEM;
1621 
1622 	kaddr = kmap_atomic(fill);
1623 	memset(kaddr, -1, PAGE_SIZE);
1624 	kunmap_atomic(kaddr);
1625 	flush_dcache_page(fill);
1626 	lock_page(fill);
1627 
1628 	if (!run_lookup_entry(run, 0, &lcn, &clen, &run_idx)) {
1629 		err = -ENOENT;
1630 		goto out;
1631 	}
1632 
1633 	/*
1634 	 * TODO: Try blkdev_issue_write_same.
1635 	 */
1636 	blk_start_plug(&plug);
1637 	do {
1638 		lbo = (u64)lcn << cluster_bits;
1639 		len = (u64)clen << cluster_bits;
1640 new_bio:
1641 		new = bio_alloc(bdev, BIO_MAX_VECS, REQ_OP_WRITE, GFP_NOFS);
1642 		if (bio) {
1643 			bio_chain(bio, new);
1644 			submit_bio(bio);
1645 		}
1646 		bio = new;
1647 		bio->bi_iter.bi_sector = lbo >> 9;
1648 
1649 		for (;;) {
1650 			u32 add = len > PAGE_SIZE ? PAGE_SIZE : len;
1651 
1652 			if (bio_add_page(bio, fill, add, 0) < add)
1653 				goto new_bio;
1654 
1655 			lbo += add;
1656 			if (len <= add)
1657 				break;
1658 			len -= add;
1659 		}
1660 	} while (run_get_entry(run, ++run_idx, NULL, &lcn, &clen));
1661 
1662 	if (!err)
1663 		err = submit_bio_wait(bio);
1664 	bio_put(bio);
1665 
1666 	blk_finish_plug(&plug);
1667 out:
1668 	unlock_page(fill);
1669 	put_page(fill);
1670 
1671 	return err;
1672 }
1673 
ntfs_vbo_to_lbo(struct ntfs_sb_info * sbi,const struct runs_tree * run,u64 vbo,u64 * lbo,u64 * bytes)1674 int ntfs_vbo_to_lbo(struct ntfs_sb_info *sbi, const struct runs_tree *run,
1675 		    u64 vbo, u64 *lbo, u64 *bytes)
1676 {
1677 	u32 off;
1678 	CLST lcn, len;
1679 	u8 cluster_bits = sbi->cluster_bits;
1680 
1681 	if (!run_lookup_entry(run, vbo >> cluster_bits, &lcn, &len, NULL))
1682 		return -ENOENT;
1683 
1684 	off = vbo & sbi->cluster_mask;
1685 	*lbo = lcn == SPARSE_LCN ? -1 : (((u64)lcn << cluster_bits) + off);
1686 	*bytes = ((u64)len << cluster_bits) - off;
1687 
1688 	return 0;
1689 }
1690 
ntfs_new_inode(struct ntfs_sb_info * sbi,CLST rno,enum RECORD_FLAG flag)1691 struct ntfs_inode *ntfs_new_inode(struct ntfs_sb_info *sbi, CLST rno,
1692 				  enum RECORD_FLAG flag)
1693 {
1694 	int err = 0;
1695 	struct super_block *sb = sbi->sb;
1696 	struct inode *inode = new_inode(sb);
1697 	struct ntfs_inode *ni;
1698 
1699 	if (!inode)
1700 		return ERR_PTR(-ENOMEM);
1701 
1702 	ni = ntfs_i(inode);
1703 
1704 	err = mi_format_new(&ni->mi, sbi, rno, flag, false);
1705 	if (err)
1706 		goto out;
1707 
1708 	inode->i_ino = rno;
1709 	if (insert_inode_locked(inode) < 0) {
1710 		err = -EIO;
1711 		goto out;
1712 	}
1713 
1714 	ni->base = ni;
1715 
1716 out:
1717 	if (err) {
1718 		make_bad_inode(inode);
1719 		iput(inode);
1720 		ni = ERR_PTR(err);
1721 	}
1722 	return ni;
1723 }
1724 
1725 /*
1726  * O:BAG:BAD:(A;OICI;FA;;;WD)
1727  * Owner S-1-5-32-544 (Administrators)
1728  * Group S-1-5-32-544 (Administrators)
1729  * ACE: allow S-1-1-0 (Everyone) with FILE_ALL_ACCESS
1730  */
1731 const u8 s_default_security[] __aligned(8) = {
1732 	0x01, 0x00, 0x04, 0x80, 0x30, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
1733 	0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x02, 0x00, 0x1C, 0x00,
1734 	0x01, 0x00, 0x00, 0x00, 0x00, 0x03, 0x14, 0x00, 0xFF, 0x01, 0x1F, 0x00,
1735 	0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
1736 	0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00,
1737 	0x20, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
1738 	0x20, 0x00, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00,
1739 };
1740 
1741 static_assert(sizeof(s_default_security) == 0x50);
1742 
sid_length(const struct SID * sid)1743 static inline u32 sid_length(const struct SID *sid)
1744 {
1745 	return struct_size(sid, SubAuthority, sid->SubAuthorityCount);
1746 }
1747 
1748 /*
1749  * is_acl_valid
1750  *
1751  * Thanks Mark Harmstone for idea.
1752  */
is_acl_valid(const struct ACL * acl,u32 len)1753 static bool is_acl_valid(const struct ACL *acl, u32 len)
1754 {
1755 	const struct ACE_HEADER *ace;
1756 	u32 i;
1757 	u16 ace_count, ace_size;
1758 
1759 	if (acl->AclRevision != ACL_REVISION &&
1760 	    acl->AclRevision != ACL_REVISION_DS) {
1761 		/*
1762 		 * This value should be ACL_REVISION, unless the ACL contains an
1763 		 * object-specific ACE, in which case this value must be ACL_REVISION_DS.
1764 		 * All ACEs in an ACL must be at the same revision level.
1765 		 */
1766 		return false;
1767 	}
1768 
1769 	if (acl->Sbz1)
1770 		return false;
1771 
1772 	if (le16_to_cpu(acl->AclSize) > len)
1773 		return false;
1774 
1775 	if (acl->Sbz2)
1776 		return false;
1777 
1778 	len -= sizeof(struct ACL);
1779 	ace = (struct ACE_HEADER *)&acl[1];
1780 	ace_count = le16_to_cpu(acl->AceCount);
1781 
1782 	for (i = 0; i < ace_count; i++) {
1783 		if (len < sizeof(struct ACE_HEADER))
1784 			return false;
1785 
1786 		ace_size = le16_to_cpu(ace->AceSize);
1787 		if (len < ace_size)
1788 			return false;
1789 
1790 		len -= ace_size;
1791 		ace = Add2Ptr(ace, ace_size);
1792 	}
1793 
1794 	return true;
1795 }
1796 
is_sd_valid(const struct SECURITY_DESCRIPTOR_RELATIVE * sd,u32 len)1797 bool is_sd_valid(const struct SECURITY_DESCRIPTOR_RELATIVE *sd, u32 len)
1798 {
1799 	u32 sd_owner, sd_group, sd_sacl, sd_dacl;
1800 
1801 	if (len < sizeof(struct SECURITY_DESCRIPTOR_RELATIVE))
1802 		return false;
1803 
1804 	if (sd->Revision != 1)
1805 		return false;
1806 
1807 	if (sd->Sbz1)
1808 		return false;
1809 
1810 	if (!(sd->Control & SE_SELF_RELATIVE))
1811 		return false;
1812 
1813 	sd_owner = le32_to_cpu(sd->Owner);
1814 	if (sd_owner) {
1815 		const struct SID *owner = Add2Ptr(sd, sd_owner);
1816 
1817 		if (sd_owner + offsetof(struct SID, SubAuthority) > len)
1818 			return false;
1819 
1820 		if (owner->Revision != 1)
1821 			return false;
1822 
1823 		if (sd_owner + sid_length(owner) > len)
1824 			return false;
1825 	}
1826 
1827 	sd_group = le32_to_cpu(sd->Group);
1828 	if (sd_group) {
1829 		const struct SID *group = Add2Ptr(sd, sd_group);
1830 
1831 		if (sd_group + offsetof(struct SID, SubAuthority) > len)
1832 			return false;
1833 
1834 		if (group->Revision != 1)
1835 			return false;
1836 
1837 		if (sd_group + sid_length(group) > len)
1838 			return false;
1839 	}
1840 
1841 	sd_sacl = le32_to_cpu(sd->Sacl);
1842 	if (sd_sacl) {
1843 		const struct ACL *sacl = Add2Ptr(sd, sd_sacl);
1844 
1845 		if (sd_sacl + sizeof(struct ACL) > len)
1846 			return false;
1847 
1848 		if (!is_acl_valid(sacl, len - sd_sacl))
1849 			return false;
1850 	}
1851 
1852 	sd_dacl = le32_to_cpu(sd->Dacl);
1853 	if (sd_dacl) {
1854 		const struct ACL *dacl = Add2Ptr(sd, sd_dacl);
1855 
1856 		if (sd_dacl + sizeof(struct ACL) > len)
1857 			return false;
1858 
1859 		if (!is_acl_valid(dacl, len - sd_dacl))
1860 			return false;
1861 	}
1862 
1863 	return true;
1864 }
1865 
1866 /*
1867  * ntfs_security_init - Load and parse $Secure.
1868  */
ntfs_security_init(struct ntfs_sb_info * sbi)1869 int ntfs_security_init(struct ntfs_sb_info *sbi)
1870 {
1871 	int err;
1872 	struct super_block *sb = sbi->sb;
1873 	struct inode *inode;
1874 	struct ntfs_inode *ni;
1875 	struct MFT_REF ref;
1876 	struct ATTRIB *attr;
1877 	struct ATTR_LIST_ENTRY *le;
1878 	u64 sds_size;
1879 	size_t off;
1880 	struct NTFS_DE *ne;
1881 	struct NTFS_DE_SII *sii_e;
1882 	struct ntfs_fnd *fnd_sii = NULL;
1883 	const struct INDEX_ROOT *root_sii;
1884 	const struct INDEX_ROOT *root_sdh;
1885 	struct ntfs_index *indx_sdh = &sbi->security.index_sdh;
1886 	struct ntfs_index *indx_sii = &sbi->security.index_sii;
1887 
1888 	ref.low = cpu_to_le32(MFT_REC_SECURE);
1889 	ref.high = 0;
1890 	ref.seq = cpu_to_le16(MFT_REC_SECURE);
1891 
1892 	inode = ntfs_iget5(sb, &ref, &NAME_SECURE);
1893 	if (IS_ERR(inode)) {
1894 		err = PTR_ERR(inode);
1895 		ntfs_err(sb, "Failed to load $Secure (%d).", err);
1896 		inode = NULL;
1897 		goto out;
1898 	}
1899 
1900 	ni = ntfs_i(inode);
1901 
1902 	le = NULL;
1903 
1904 	attr = ni_find_attr(ni, NULL, &le, ATTR_ROOT, SDH_NAME,
1905 			    ARRAY_SIZE(SDH_NAME), NULL, NULL);
1906 	if (!attr ||
1907 	    !(root_sdh = resident_data_ex(attr, sizeof(struct INDEX_ROOT))) ||
1908 	    root_sdh->type != ATTR_ZERO ||
1909 	    root_sdh->rule != NTFS_COLLATION_TYPE_SECURITY_HASH ||
1910 	    offsetof(struct INDEX_ROOT, ihdr) +
1911 			    le32_to_cpu(root_sdh->ihdr.used) >
1912 		    le32_to_cpu(attr->res.data_size)) {
1913 		ntfs_err(sb, "$Secure::$SDH is corrupted.");
1914 		err = -EINVAL;
1915 		goto out;
1916 	}
1917 
1918 	err = indx_init(indx_sdh, sbi, attr, INDEX_MUTEX_SDH);
1919 	if (err) {
1920 		ntfs_err(sb, "Failed to initialize $Secure::$SDH (%d).", err);
1921 		goto out;
1922 	}
1923 
1924 	attr = ni_find_attr(ni, attr, &le, ATTR_ROOT, SII_NAME,
1925 			    ARRAY_SIZE(SII_NAME), NULL, NULL);
1926 	if (!attr ||
1927 	    !(root_sii = resident_data_ex(attr, sizeof(struct INDEX_ROOT))) ||
1928 	    root_sii->type != ATTR_ZERO ||
1929 	    root_sii->rule != NTFS_COLLATION_TYPE_UINT ||
1930 	    offsetof(struct INDEX_ROOT, ihdr) +
1931 			    le32_to_cpu(root_sii->ihdr.used) >
1932 		    le32_to_cpu(attr->res.data_size)) {
1933 		ntfs_err(sb, "$Secure::$SII is corrupted.");
1934 		err = -EINVAL;
1935 		goto out;
1936 	}
1937 
1938 	err = indx_init(indx_sii, sbi, attr, INDEX_MUTEX_SII);
1939 	if (err) {
1940 		ntfs_err(sb, "Failed to initialize $Secure::$SII (%d).", err);
1941 		goto out;
1942 	}
1943 
1944 	fnd_sii = fnd_get();
1945 	if (!fnd_sii) {
1946 		err = -ENOMEM;
1947 		goto out;
1948 	}
1949 
1950 	sds_size = inode->i_size;
1951 
1952 	/* Find the last valid Id. */
1953 	sbi->security.next_id = SECURITY_ID_FIRST;
1954 	/* Always write new security at the end of bucket. */
1955 	sbi->security.next_off =
1956 		ALIGN(sds_size - SecurityDescriptorsBlockSize, 16);
1957 
1958 	off = 0;
1959 	ne = NULL;
1960 
1961 	for (;;) {
1962 		u32 next_id;
1963 
1964 		err = indx_find_raw(indx_sii, ni, root_sii, &ne, &off, fnd_sii);
1965 		if (err || !ne)
1966 			break;
1967 
1968 		sii_e = (struct NTFS_DE_SII *)ne;
1969 		if (le16_to_cpu(ne->view.data_size) < sizeof(sii_e->sec_hdr))
1970 			continue;
1971 
1972 		next_id = le32_to_cpu(sii_e->sec_id) + 1;
1973 		if (next_id >= sbi->security.next_id)
1974 			sbi->security.next_id = next_id;
1975 	}
1976 
1977 	sbi->security.ni = ni;
1978 	inode = NULL;
1979 out:
1980 	iput(inode);
1981 	fnd_put(fnd_sii);
1982 
1983 	return err;
1984 }
1985 
1986 /*
1987  * ntfs_get_security_by_id - Read security descriptor by id.
1988  */
ntfs_get_security_by_id(struct ntfs_sb_info * sbi,__le32 security_id,struct SECURITY_DESCRIPTOR_RELATIVE ** sd,size_t * size)1989 int ntfs_get_security_by_id(struct ntfs_sb_info *sbi, __le32 security_id,
1990 			    struct SECURITY_DESCRIPTOR_RELATIVE **sd,
1991 			    size_t *size)
1992 {
1993 	int err;
1994 	int diff;
1995 	struct ntfs_inode *ni = sbi->security.ni;
1996 	struct ntfs_index *indx = &sbi->security.index_sii;
1997 	void *p = NULL;
1998 	struct NTFS_DE_SII *sii_e;
1999 	struct ntfs_fnd *fnd_sii;
2000 	struct SECURITY_HDR d_security;
2001 	const struct INDEX_ROOT *root_sii;
2002 	u32 t32;
2003 
2004 	*sd = NULL;
2005 
2006 	mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_SECURITY);
2007 
2008 	fnd_sii = fnd_get();
2009 	if (!fnd_sii) {
2010 		err = -ENOMEM;
2011 		goto out;
2012 	}
2013 
2014 	root_sii = indx_get_root(indx, ni, NULL, NULL);
2015 	if (!root_sii) {
2016 		err = -EINVAL;
2017 		goto out;
2018 	}
2019 
2020 	/* Try to find this SECURITY descriptor in SII indexes. */
2021 	err = indx_find(indx, ni, root_sii, &security_id, sizeof(security_id),
2022 			NULL, &diff, (struct NTFS_DE **)&sii_e, fnd_sii);
2023 	if (err)
2024 		goto out;
2025 
2026 	if (diff)
2027 		goto out;
2028 
2029 	t32 = le32_to_cpu(sii_e->sec_hdr.size);
2030 	if (t32 < sizeof(struct SECURITY_HDR)) {
2031 		err = -EINVAL;
2032 		goto out;
2033 	}
2034 
2035 	if (t32 > sizeof(struct SECURITY_HDR) + 0x10000) {
2036 		/* Looks like too big security. 0x10000 - is arbitrary big number. */
2037 		err = -EFBIG;
2038 		goto out;
2039 	}
2040 
2041 	*size = t32 - sizeof(struct SECURITY_HDR);
2042 
2043 	p = kmalloc(*size, GFP_NOFS);
2044 	if (!p) {
2045 		err = -ENOMEM;
2046 		goto out;
2047 	}
2048 
2049 	err = ntfs_read_run_nb(sbi, &ni->file.run,
2050 			       le64_to_cpu(sii_e->sec_hdr.off), &d_security,
2051 			       sizeof(d_security), NULL);
2052 	if (err)
2053 		goto out;
2054 
2055 	if (memcmp(&d_security, &sii_e->sec_hdr, sizeof(d_security))) {
2056 		err = -EINVAL;
2057 		goto out;
2058 	}
2059 
2060 	err = ntfs_read_run_nb(sbi, &ni->file.run,
2061 			       le64_to_cpu(sii_e->sec_hdr.off) +
2062 				       sizeof(struct SECURITY_HDR),
2063 			       p, *size, NULL);
2064 	if (err)
2065 		goto out;
2066 
2067 	*sd = p;
2068 	p = NULL;
2069 
2070 out:
2071 	kfree(p);
2072 	fnd_put(fnd_sii);
2073 	ni_unlock(ni);
2074 
2075 	return err;
2076 }
2077 
2078 /*
2079  * ntfs_insert_security - Insert security descriptor into $Secure::SDS.
2080  *
2081  * SECURITY Descriptor Stream data is organized into chunks of 256K bytes
2082  * and it contains a mirror copy of each security descriptor.  When writing
2083  * to a security descriptor at location X, another copy will be written at
2084  * location (X+256K).
2085  * When writing a security descriptor that will cross the 256K boundary,
2086  * the pointer will be advanced by 256K to skip
2087  * over the mirror portion.
2088  */
ntfs_insert_security(struct ntfs_sb_info * sbi,const struct SECURITY_DESCRIPTOR_RELATIVE * sd,u32 size_sd,__le32 * security_id,bool * inserted)2089 int ntfs_insert_security(struct ntfs_sb_info *sbi,
2090 			 const struct SECURITY_DESCRIPTOR_RELATIVE *sd,
2091 			 u32 size_sd, __le32 *security_id, bool *inserted)
2092 {
2093 	int err, diff;
2094 	struct ntfs_inode *ni = sbi->security.ni;
2095 	struct ntfs_index *indx_sdh = &sbi->security.index_sdh;
2096 	struct ntfs_index *indx_sii = &sbi->security.index_sii;
2097 	struct NTFS_DE_SDH *e;
2098 	struct NTFS_DE_SDH sdh_e;
2099 	struct NTFS_DE_SII sii_e;
2100 	struct SECURITY_HDR *d_security;
2101 	u32 new_sec_size = size_sd + sizeof(struct SECURITY_HDR);
2102 	u32 aligned_sec_size = ALIGN(new_sec_size, 16);
2103 	struct SECURITY_KEY hash_key;
2104 	struct ntfs_fnd *fnd_sdh = NULL;
2105 	const struct INDEX_ROOT *root_sdh;
2106 	const struct INDEX_ROOT *root_sii;
2107 	u64 mirr_off, new_sds_size;
2108 	u32 next, left;
2109 
2110 	static_assert((1 << Log2OfSecurityDescriptorsBlockSize) ==
2111 		      SecurityDescriptorsBlockSize);
2112 
2113 	hash_key.hash = security_hash(sd, size_sd);
2114 	hash_key.sec_id = SECURITY_ID_INVALID;
2115 
2116 	if (inserted)
2117 		*inserted = false;
2118 	*security_id = SECURITY_ID_INVALID;
2119 
2120 	/* Allocate a temporal buffer. */
2121 	d_security = kzalloc(aligned_sec_size, GFP_NOFS);
2122 	if (!d_security)
2123 		return -ENOMEM;
2124 
2125 	mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_SECURITY);
2126 
2127 	fnd_sdh = fnd_get();
2128 	if (!fnd_sdh) {
2129 		err = -ENOMEM;
2130 		goto out;
2131 	}
2132 
2133 	root_sdh = indx_get_root(indx_sdh, ni, NULL, NULL);
2134 	if (!root_sdh) {
2135 		err = -EINVAL;
2136 		goto out;
2137 	}
2138 
2139 	root_sii = indx_get_root(indx_sii, ni, NULL, NULL);
2140 	if (!root_sii) {
2141 		err = -EINVAL;
2142 		goto out;
2143 	}
2144 
2145 	/*
2146 	 * Check if such security already exists.
2147 	 * Use "SDH" and hash -> to get the offset in "SDS".
2148 	 */
2149 	err = indx_find(indx_sdh, ni, root_sdh, &hash_key, sizeof(hash_key),
2150 			&d_security->key.sec_id, &diff, (struct NTFS_DE **)&e,
2151 			fnd_sdh);
2152 	if (err)
2153 		goto out;
2154 
2155 	while (e) {
2156 		if (le32_to_cpu(e->sec_hdr.size) == new_sec_size) {
2157 			err = ntfs_read_run_nb(sbi, &ni->file.run,
2158 					       le64_to_cpu(e->sec_hdr.off),
2159 					       d_security, new_sec_size, NULL);
2160 			if (err)
2161 				goto out;
2162 
2163 			if (le32_to_cpu(d_security->size) == new_sec_size &&
2164 			    d_security->key.hash == hash_key.hash &&
2165 			    !memcmp(d_security + 1, sd, size_sd)) {
2166 				/* Such security already exists. */
2167 				*security_id = d_security->key.sec_id;
2168 				err = 0;
2169 				goto out;
2170 			}
2171 		}
2172 
2173 		err = indx_find_sort(indx_sdh, ni, root_sdh,
2174 				     (struct NTFS_DE **)&e, fnd_sdh);
2175 		if (err)
2176 			goto out;
2177 
2178 		if (!e || e->key.hash != hash_key.hash)
2179 			break;
2180 	}
2181 
2182 	/* Zero unused space. */
2183 	next = sbi->security.next_off & (SecurityDescriptorsBlockSize - 1);
2184 	left = SecurityDescriptorsBlockSize - next;
2185 
2186 	/* Zero gap until SecurityDescriptorsBlockSize. */
2187 	if (left < new_sec_size) {
2188 		/* Zero "left" bytes from sbi->security.next_off. */
2189 		sbi->security.next_off += SecurityDescriptorsBlockSize + left;
2190 	}
2191 
2192 	/* Zero tail of previous security. */
2193 	//used = ni->vfs_inode.i_size & (SecurityDescriptorsBlockSize - 1);
2194 
2195 	/*
2196 	 * Example:
2197 	 * 0x40438 == ni->vfs_inode.i_size
2198 	 * 0x00440 == sbi->security.next_off
2199 	 * need to zero [0x438-0x440)
2200 	 * if (next > used) {
2201 	 *  u32 tozero = next - used;
2202 	 *  zero "tozero" bytes from sbi->security.next_off - tozero
2203 	 */
2204 
2205 	/* Format new security descriptor. */
2206 	d_security->key.hash = hash_key.hash;
2207 	d_security->key.sec_id = cpu_to_le32(sbi->security.next_id);
2208 	d_security->off = cpu_to_le64(sbi->security.next_off);
2209 	d_security->size = cpu_to_le32(new_sec_size);
2210 	memcpy(d_security + 1, sd, size_sd);
2211 
2212 	/* Write main SDS bucket. */
2213 	err = ntfs_sb_write_run(sbi, &ni->file.run, sbi->security.next_off,
2214 				d_security, aligned_sec_size, 0);
2215 
2216 	if (err)
2217 		goto out;
2218 
2219 	mirr_off = sbi->security.next_off + SecurityDescriptorsBlockSize;
2220 	new_sds_size = mirr_off + aligned_sec_size;
2221 
2222 	if (new_sds_size > ni->vfs_inode.i_size) {
2223 		err = attr_set_size(ni, ATTR_DATA, SDS_NAME,
2224 				    ARRAY_SIZE(SDS_NAME), &ni->file.run,
2225 				    new_sds_size, &new_sds_size, false);
2226 		if (err)
2227 			goto out;
2228 	}
2229 
2230 	/* Write copy SDS bucket. */
2231 	err = ntfs_sb_write_run(sbi, &ni->file.run, mirr_off, d_security,
2232 				aligned_sec_size, 0);
2233 	if (err)
2234 		goto out;
2235 
2236 	/* Fill SII entry. */
2237 	sii_e.de.view.data_off =
2238 		cpu_to_le16(offsetof(struct NTFS_DE_SII, sec_hdr));
2239 	sii_e.de.view.data_size = cpu_to_le16(sizeof(struct SECURITY_HDR));
2240 	sii_e.de.view.res = 0;
2241 	sii_e.de.size = cpu_to_le16(sizeof(struct NTFS_DE_SII));
2242 	sii_e.de.key_size = cpu_to_le16(sizeof(d_security->key.sec_id));
2243 	sii_e.de.flags = 0;
2244 	sii_e.de.res = 0;
2245 	sii_e.sec_id = d_security->key.sec_id;
2246 	memcpy(&sii_e.sec_hdr, d_security, sizeof(struct SECURITY_HDR));
2247 
2248 	err = indx_insert_entry(indx_sii, ni, &sii_e.de, NULL, NULL, 0);
2249 	if (err)
2250 		goto out;
2251 
2252 	/* Fill SDH entry. */
2253 	sdh_e.de.view.data_off =
2254 		cpu_to_le16(offsetof(struct NTFS_DE_SDH, sec_hdr));
2255 	sdh_e.de.view.data_size = cpu_to_le16(sizeof(struct SECURITY_HDR));
2256 	sdh_e.de.view.res = 0;
2257 	sdh_e.de.size = cpu_to_le16(SIZEOF_SDH_DIRENTRY);
2258 	sdh_e.de.key_size = cpu_to_le16(sizeof(sdh_e.key));
2259 	sdh_e.de.flags = 0;
2260 	sdh_e.de.res = 0;
2261 	sdh_e.key.hash = d_security->key.hash;
2262 	sdh_e.key.sec_id = d_security->key.sec_id;
2263 	memcpy(&sdh_e.sec_hdr, d_security, sizeof(struct SECURITY_HDR));
2264 	sdh_e.magic[0] = cpu_to_le16('I');
2265 	sdh_e.magic[1] = cpu_to_le16('I');
2266 
2267 	fnd_clear(fnd_sdh);
2268 	err = indx_insert_entry(indx_sdh, ni, &sdh_e.de, (void *)(size_t)1,
2269 				fnd_sdh, 0);
2270 	if (err)
2271 		goto out;
2272 
2273 	*security_id = d_security->key.sec_id;
2274 	if (inserted)
2275 		*inserted = true;
2276 
2277 	/* Update Id and offset for next descriptor. */
2278 	sbi->security.next_id += 1;
2279 	sbi->security.next_off += aligned_sec_size;
2280 
2281 out:
2282 	fnd_put(fnd_sdh);
2283 	mark_inode_dirty(&ni->vfs_inode);
2284 	ni_unlock(ni);
2285 	kfree(d_security);
2286 
2287 	return err;
2288 }
2289 
2290 /*
2291  * ntfs_reparse_init - Load and parse $Extend/$Reparse.
2292  */
ntfs_reparse_init(struct ntfs_sb_info * sbi)2293 int ntfs_reparse_init(struct ntfs_sb_info *sbi)
2294 {
2295 	int err;
2296 	struct ntfs_inode *ni = sbi->reparse.ni;
2297 	struct ntfs_index *indx = &sbi->reparse.index_r;
2298 	struct ATTRIB *attr;
2299 	struct ATTR_LIST_ENTRY *le;
2300 	const struct INDEX_ROOT *root_r;
2301 
2302 	if (!ni)
2303 		return 0;
2304 
2305 	le = NULL;
2306 	attr = ni_find_attr(ni, NULL, &le, ATTR_ROOT, SR_NAME,
2307 			    ARRAY_SIZE(SR_NAME), NULL, NULL);
2308 	if (!attr) {
2309 		err = -EINVAL;
2310 		goto out;
2311 	}
2312 
2313 	root_r = resident_data_ex(attr, sizeof(struct INDEX_ROOT));
2314 	if (!root_r || root_r->type != ATTR_ZERO ||
2315 	    root_r->rule != NTFS_COLLATION_TYPE_UINTS) {
2316 		err = -EINVAL;
2317 		goto out;
2318 	}
2319 
2320 	err = indx_init(indx, sbi, attr, INDEX_MUTEX_SR);
2321 	if (err)
2322 		goto out;
2323 
2324 out:
2325 	return err;
2326 }
2327 
2328 /*
2329  * ntfs_objid_init - Load and parse $Extend/$ObjId.
2330  */
ntfs_objid_init(struct ntfs_sb_info * sbi)2331 int ntfs_objid_init(struct ntfs_sb_info *sbi)
2332 {
2333 	int err;
2334 	struct ntfs_inode *ni = sbi->objid.ni;
2335 	struct ntfs_index *indx = &sbi->objid.index_o;
2336 	struct ATTRIB *attr;
2337 	struct ATTR_LIST_ENTRY *le;
2338 	const struct INDEX_ROOT *root;
2339 
2340 	if (!ni)
2341 		return 0;
2342 
2343 	le = NULL;
2344 	attr = ni_find_attr(ni, NULL, &le, ATTR_ROOT, SO_NAME,
2345 			    ARRAY_SIZE(SO_NAME), NULL, NULL);
2346 	if (!attr) {
2347 		err = -EINVAL;
2348 		goto out;
2349 	}
2350 
2351 	root = resident_data_ex(attr, sizeof(struct INDEX_ROOT));
2352 	if (!root || root->type != ATTR_ZERO ||
2353 	    root->rule != NTFS_COLLATION_TYPE_UINTS) {
2354 		err = -EINVAL;
2355 		goto out;
2356 	}
2357 
2358 	err = indx_init(indx, sbi, attr, INDEX_MUTEX_SO);
2359 	if (err)
2360 		goto out;
2361 
2362 out:
2363 	return err;
2364 }
2365 
ntfs_objid_remove(struct ntfs_sb_info * sbi,struct GUID * guid)2366 int ntfs_objid_remove(struct ntfs_sb_info *sbi, struct GUID *guid)
2367 {
2368 	int err;
2369 	struct ntfs_inode *ni = sbi->objid.ni;
2370 	struct ntfs_index *indx = &sbi->objid.index_o;
2371 
2372 	if (!ni)
2373 		return -EINVAL;
2374 
2375 	mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_OBJID);
2376 
2377 	err = indx_delete_entry(indx, ni, guid, sizeof(*guid), NULL);
2378 
2379 	mark_inode_dirty(&ni->vfs_inode);
2380 	ni_unlock(ni);
2381 
2382 	return err;
2383 }
2384 
ntfs_insert_reparse(struct ntfs_sb_info * sbi,__le32 rtag,const struct MFT_REF * ref)2385 int ntfs_insert_reparse(struct ntfs_sb_info *sbi, __le32 rtag,
2386 			const struct MFT_REF *ref)
2387 {
2388 	int err;
2389 	struct ntfs_inode *ni = sbi->reparse.ni;
2390 	struct ntfs_index *indx = &sbi->reparse.index_r;
2391 	struct NTFS_DE_R re;
2392 
2393 	if (!ni)
2394 		return -EINVAL;
2395 
2396 	memset(&re, 0, sizeof(re));
2397 
2398 	re.de.view.data_off = cpu_to_le16(offsetof(struct NTFS_DE_R, zero));
2399 	re.de.size = cpu_to_le16(sizeof(struct NTFS_DE_R));
2400 	re.de.key_size = cpu_to_le16(sizeof(re.key));
2401 
2402 	re.key.ReparseTag = rtag;
2403 	memcpy(&re.key.ref, ref, sizeof(*ref));
2404 
2405 	mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_REPARSE);
2406 
2407 	err = indx_insert_entry(indx, ni, &re.de, NULL, NULL, 0);
2408 
2409 	mark_inode_dirty(&ni->vfs_inode);
2410 	ni_unlock(ni);
2411 
2412 	return err;
2413 }
2414 
ntfs_remove_reparse(struct ntfs_sb_info * sbi,__le32 rtag,const struct MFT_REF * ref)2415 int ntfs_remove_reparse(struct ntfs_sb_info *sbi, __le32 rtag,
2416 			const struct MFT_REF *ref)
2417 {
2418 	int err, diff;
2419 	struct ntfs_inode *ni = sbi->reparse.ni;
2420 	struct ntfs_index *indx = &sbi->reparse.index_r;
2421 	struct ntfs_fnd *fnd = NULL;
2422 	struct REPARSE_KEY rkey;
2423 	struct NTFS_DE_R *re;
2424 	struct INDEX_ROOT *root_r;
2425 
2426 	if (!ni)
2427 		return -EINVAL;
2428 
2429 	rkey.ReparseTag = rtag;
2430 	rkey.ref = *ref;
2431 
2432 	mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_REPARSE);
2433 
2434 	if (rtag) {
2435 		err = indx_delete_entry(indx, ni, &rkey, sizeof(rkey), NULL);
2436 		goto out1;
2437 	}
2438 
2439 	fnd = fnd_get();
2440 	if (!fnd) {
2441 		err = -ENOMEM;
2442 		goto out1;
2443 	}
2444 
2445 	root_r = indx_get_root(indx, ni, NULL, NULL);
2446 	if (!root_r) {
2447 		err = -EINVAL;
2448 		goto out;
2449 	}
2450 
2451 	/* 1 - forces to ignore rkey.ReparseTag when comparing keys. */
2452 	err = indx_find(indx, ni, root_r, &rkey, sizeof(rkey), (void *)1, &diff,
2453 			(struct NTFS_DE **)&re, fnd);
2454 	if (err)
2455 		goto out;
2456 
2457 	if (memcmp(&re->key.ref, ref, sizeof(*ref))) {
2458 		/* Impossible. Looks like volume corrupt? */
2459 		goto out;
2460 	}
2461 
2462 	memcpy(&rkey, &re->key, sizeof(rkey));
2463 
2464 	fnd_put(fnd);
2465 	fnd = NULL;
2466 
2467 	err = indx_delete_entry(indx, ni, &rkey, sizeof(rkey), NULL);
2468 	if (err)
2469 		goto out;
2470 
2471 out:
2472 	fnd_put(fnd);
2473 
2474 out1:
2475 	mark_inode_dirty(&ni->vfs_inode);
2476 	ni_unlock(ni);
2477 
2478 	return err;
2479 }
2480 
ntfs_unmap_and_discard(struct ntfs_sb_info * sbi,CLST lcn,CLST len)2481 static inline void ntfs_unmap_and_discard(struct ntfs_sb_info *sbi, CLST lcn,
2482 					  CLST len)
2483 {
2484 	ntfs_unmap_meta(sbi->sb, lcn, len);
2485 	ntfs_discard(sbi, lcn, len);
2486 }
2487 
mark_as_free_ex(struct ntfs_sb_info * sbi,CLST lcn,CLST len,bool trim)2488 void mark_as_free_ex(struct ntfs_sb_info *sbi, CLST lcn, CLST len, bool trim)
2489 {
2490 	CLST end, i, zone_len, zlen;
2491 	struct wnd_bitmap *wnd = &sbi->used.bitmap;
2492 	bool dirty = false;
2493 
2494 	down_write_nested(&wnd->rw_lock, BITMAP_MUTEX_CLUSTERS);
2495 	if (!wnd_is_used(wnd, lcn, len)) {
2496 		/* mark volume as dirty out of wnd->rw_lock */
2497 		dirty = true;
2498 
2499 		end = lcn + len;
2500 		len = 0;
2501 		for (i = lcn; i < end; i++) {
2502 			if (wnd_is_used(wnd, i, 1)) {
2503 				if (!len)
2504 					lcn = i;
2505 				len += 1;
2506 				continue;
2507 			}
2508 
2509 			if (!len)
2510 				continue;
2511 
2512 			if (trim)
2513 				ntfs_unmap_and_discard(sbi, lcn, len);
2514 
2515 			wnd_set_free(wnd, lcn, len);
2516 			len = 0;
2517 		}
2518 
2519 		if (!len)
2520 			goto out;
2521 	}
2522 
2523 	if (trim)
2524 		ntfs_unmap_and_discard(sbi, lcn, len);
2525 	wnd_set_free(wnd, lcn, len);
2526 
2527 	/* append to MFT zone, if possible. */
2528 	zone_len = wnd_zone_len(wnd);
2529 	zlen = min(zone_len + len, sbi->zone_max);
2530 
2531 	if (zlen == zone_len) {
2532 		/* MFT zone already has maximum size. */
2533 	} else if (!zone_len) {
2534 		/* Create MFT zone only if 'zlen' is large enough. */
2535 		if (zlen == sbi->zone_max)
2536 			wnd_zone_set(wnd, lcn, zlen);
2537 	} else {
2538 		CLST zone_lcn = wnd_zone_bit(wnd);
2539 
2540 		if (lcn + len == zone_lcn) {
2541 			/* Append into head MFT zone. */
2542 			wnd_zone_set(wnd, lcn, zlen);
2543 		} else if (zone_lcn + zone_len == lcn) {
2544 			/* Append into tail MFT zone. */
2545 			wnd_zone_set(wnd, zone_lcn, zlen);
2546 		}
2547 	}
2548 
2549 out:
2550 	up_write(&wnd->rw_lock);
2551 	if (dirty)
2552 		ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
2553 }
2554 
2555 /*
2556  * run_deallocate - Deallocate clusters.
2557  */
run_deallocate(struct ntfs_sb_info * sbi,const struct runs_tree * run,bool trim)2558 int run_deallocate(struct ntfs_sb_info *sbi, const struct runs_tree *run,
2559 		   bool trim)
2560 {
2561 	CLST lcn, len;
2562 	size_t idx = 0;
2563 
2564 	while (run_get_entry(run, idx++, NULL, &lcn, &len)) {
2565 		if (lcn == SPARSE_LCN)
2566 			continue;
2567 
2568 		mark_as_free_ex(sbi, lcn, len, trim);
2569 	}
2570 
2571 	return 0;
2572 }
2573 
name_has_forbidden_chars(const struct le_str * fname)2574 static inline bool name_has_forbidden_chars(const struct le_str *fname)
2575 {
2576 	int i, ch;
2577 
2578 	/* check for forbidden chars */
2579 	for (i = 0; i < fname->len; ++i) {
2580 		ch = le16_to_cpu(fname->name[i]);
2581 
2582 		/* control chars */
2583 		if (ch < 0x20)
2584 			return true;
2585 
2586 		switch (ch) {
2587 		/* disallowed by Windows */
2588 		case '\\':
2589 		case '/':
2590 		case ':':
2591 		case '*':
2592 		case '?':
2593 		case '<':
2594 		case '>':
2595 		case '|':
2596 		case '\"':
2597 			return true;
2598 
2599 		default:
2600 			/* allowed char */
2601 			break;
2602 		}
2603 	}
2604 
2605 	/* file names cannot end with space or . */
2606 	if (fname->len > 0) {
2607 		ch = le16_to_cpu(fname->name[fname->len - 1]);
2608 		if (ch == ' ' || ch == '.')
2609 			return true;
2610 	}
2611 
2612 	return false;
2613 }
2614 
is_reserved_name(const struct ntfs_sb_info * sbi,const struct le_str * fname)2615 static inline bool is_reserved_name(const struct ntfs_sb_info *sbi,
2616 				    const struct le_str *fname)
2617 {
2618 	int port_digit;
2619 	const __le16 *name = fname->name;
2620 	int len = fname->len;
2621 	const u16 *upcase = sbi->upcase;
2622 
2623 	/* check for 3 chars reserved names (device names) */
2624 	/* name by itself or with any extension is forbidden */
2625 	if (len == 3 || (len > 3 && le16_to_cpu(name[3]) == '.'))
2626 		if (!ntfs_cmp_names(name, 3, CON_NAME, 3, upcase, false) ||
2627 		    !ntfs_cmp_names(name, 3, NUL_NAME, 3, upcase, false) ||
2628 		    !ntfs_cmp_names(name, 3, AUX_NAME, 3, upcase, false) ||
2629 		    !ntfs_cmp_names(name, 3, PRN_NAME, 3, upcase, false))
2630 			return true;
2631 
2632 	/* check for 4 chars reserved names (port name followed by 1..9) */
2633 	/* name by itself or with any extension is forbidden */
2634 	if (len == 4 || (len > 4 && le16_to_cpu(name[4]) == '.')) {
2635 		port_digit = le16_to_cpu(name[3]);
2636 		if (port_digit >= '1' && port_digit <= '9')
2637 			if (!ntfs_cmp_names(name, 3, COM_NAME, 3, upcase,
2638 					    false) ||
2639 			    !ntfs_cmp_names(name, 3, LPT_NAME, 3, upcase,
2640 					    false))
2641 				return true;
2642 	}
2643 
2644 	return false;
2645 }
2646 
2647 /*
2648  * valid_windows_name - Check if a file name is valid in Windows.
2649  */
valid_windows_name(struct ntfs_sb_info * sbi,const struct le_str * fname)2650 bool valid_windows_name(struct ntfs_sb_info *sbi, const struct le_str *fname)
2651 {
2652 	return !name_has_forbidden_chars(fname) &&
2653 	       !is_reserved_name(sbi, fname);
2654 }
2655 
2656 /*
2657  * ntfs_set_label - updates current ntfs label.
2658  */
ntfs_set_label(struct ntfs_sb_info * sbi,u8 * label,int len)2659 int ntfs_set_label(struct ntfs_sb_info *sbi, u8 *label, int len)
2660 {
2661 	int err;
2662 	struct ATTRIB *attr;
2663 	u32 uni_bytes;
2664 	struct ntfs_inode *ni = sbi->volume.ni;
2665 	struct cpu_str *uni = kmalloc(PATH_MAX, GFP_KERNEL);
2666 
2667 	if (!uni)
2668 		return -ENOMEM;
2669 
2670 	err = ntfs_nls_to_utf16(sbi, label, len, uni, (PATH_MAX - 2) / 2,
2671 				UTF16_LITTLE_ENDIAN);
2672 	if (err < 0)
2673 		goto out;
2674 
2675 	if (uni->ads_len) {
2676 		/* Undo delimiter parse */
2677 		uni->len += uni->ads_len + 1;
2678 		uni->ads_len = 0;
2679 	}
2680 
2681 	uni_bytes = uni->len * sizeof(u16);
2682 	if (uni_bytes > NTFS_LABEL_MAX_LENGTH * sizeof(u16)) {
2683 		ntfs_warn(sbi->sb, "new label is too long");
2684 		err = -EFBIG;
2685 		goto out;
2686 	}
2687 
2688 	ni_lock(ni);
2689 
2690 	/* Ignore any errors. */
2691 	ni_remove_attr(ni, ATTR_LABEL, NULL, 0, false, NULL);
2692 
2693 	err = ni_insert_resident(ni, uni_bytes, ATTR_LABEL, NULL, 0, &attr,
2694 				 NULL, NULL);
2695 	if (err < 0)
2696 		goto unlock_out;
2697 
2698 	/* write new label in on-disk struct. */
2699 	memcpy(resident_data(attr), uni->name, uni_bytes);
2700 
2701 	/* update cached value of current label. */
2702 	if (len >= ARRAY_SIZE(sbi->volume.label))
2703 		len = ARRAY_SIZE(sbi->volume.label) - 1;
2704 	memcpy(sbi->volume.label, label, len);
2705 	sbi->volume.label[len] = 0;
2706 	mark_inode_dirty_sync(&ni->vfs_inode);
2707 
2708 unlock_out:
2709 	ni_unlock(ni);
2710 
2711 	if (!err)
2712 		err = _ni_write_inode(&ni->vfs_inode, 0);
2713 
2714 out:
2715 	kfree(uni);
2716 	return err;
2717 }
2718