• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *
4  * Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
5  *
6  */
7 
8 #include <linux/blkdev.h>
9 #include <linux/fs.h>
10 #include <linux/random.h>
11 #include <linux/slab.h>
12 
13 #include "debug.h"
14 #include "ntfs.h"
15 #include "ntfs_fs.h"
16 
17 /*
18  * LOG FILE structs
19  */
20 
21 // clang-format off
22 
23 #define MaxLogFileSize     0x100000000ull
24 #define DefaultLogPageSize 4096
25 #define MinLogRecordPages  0x30
26 
27 struct RESTART_HDR {
28 	struct NTFS_RECORD_HEADER rhdr; // 'RSTR'
29 	__le32 sys_page_size; // 0x10: Page size of the system which initialized the log.
30 	__le32 page_size;     // 0x14: Log page size used for this log file.
31 	__le16 ra_off;        // 0x18:
32 	__le16 minor_ver;     // 0x1A:
33 	__le16 major_ver;     // 0x1C:
34 	__le16 fixups[];
35 };
36 
37 #define LFS_NO_CLIENT 0xffff
38 #define LFS_NO_CLIENT_LE cpu_to_le16(0xffff)
39 
40 struct CLIENT_REC {
41 	__le64 oldest_lsn;
42 	__le64 restart_lsn; // 0x08:
43 	__le16 prev_client; // 0x10:
44 	__le16 next_client; // 0x12:
45 	__le16 seq_num;     // 0x14:
46 	u8 align[6];        // 0x16:
47 	__le32 name_bytes;  // 0x1C: In bytes.
48 	__le16 name[32];    // 0x20: Name of client.
49 };
50 
51 static_assert(sizeof(struct CLIENT_REC) == 0x60);
52 
53 /* Two copies of these will exist at the beginning of the log file */
54 struct RESTART_AREA {
55 	__le64 current_lsn;    // 0x00: Current logical end of log file.
56 	__le16 log_clients;    // 0x08: Maximum number of clients.
57 	__le16 client_idx[2];  // 0x0A: Free/use index into the client record arrays.
58 	__le16 flags;          // 0x0E: See RESTART_SINGLE_PAGE_IO.
59 	__le32 seq_num_bits;   // 0x10: The number of bits in sequence number.
60 	__le16 ra_len;         // 0x14:
61 	__le16 client_off;     // 0x16:
62 	__le64 l_size;         // 0x18: Usable log file size.
63 	__le32 last_lsn_data_len; // 0x20:
64 	__le16 rec_hdr_len;    // 0x24: Log page data offset.
65 	__le16 data_off;       // 0x26: Log page data length.
66 	__le32 open_log_count; // 0x28:
67 	__le32 align[5];       // 0x2C:
68 	struct CLIENT_REC clients[]; // 0x40:
69 };
70 
71 struct LOG_REC_HDR {
72 	__le16 redo_op;      // 0x00:  NTFS_LOG_OPERATION
73 	__le16 undo_op;      // 0x02:  NTFS_LOG_OPERATION
74 	__le16 redo_off;     // 0x04:  Offset to Redo record.
75 	__le16 redo_len;     // 0x06:  Redo length.
76 	__le16 undo_off;     // 0x08:  Offset to Undo record.
77 	__le16 undo_len;     // 0x0A:  Undo length.
78 	__le16 target_attr;  // 0x0C:
79 	__le16 lcns_follow;  // 0x0E:
80 	__le16 record_off;   // 0x10:
81 	__le16 attr_off;     // 0x12:
82 	__le16 cluster_off;  // 0x14:
83 	__le16 reserved;     // 0x16:
84 	__le64 target_vcn;   // 0x18:
85 	__le64 page_lcns[];  // 0x20:
86 };
87 
88 static_assert(sizeof(struct LOG_REC_HDR) == 0x20);
89 
90 #define RESTART_ENTRY_ALLOCATED    0xFFFFFFFF
91 #define RESTART_ENTRY_ALLOCATED_LE cpu_to_le32(0xFFFFFFFF)
92 
93 struct RESTART_TABLE {
94 	__le16 size;       // 0x00: In bytes
95 	__le16 used;       // 0x02: Entries
96 	__le16 total;      // 0x04: Entries
97 	__le16 res[3];     // 0x06:
98 	__le32 free_goal;  // 0x0C:
99 	__le32 first_free; // 0x10:
100 	__le32 last_free;  // 0x14:
101 
102 };
103 
104 static_assert(sizeof(struct RESTART_TABLE) == 0x18);
105 
106 struct ATTR_NAME_ENTRY {
107 	__le16 off; // Offset in the Open attribute Table.
108 	__le16 name_bytes;
109 	__le16 name[];
110 };
111 
112 struct OPEN_ATTR_ENRTY {
113 	__le32 next;            // 0x00: RESTART_ENTRY_ALLOCATED if allocated
114 	__le32 bytes_per_index; // 0x04:
115 	enum ATTR_TYPE type;    // 0x08:
116 	u8 is_dirty_pages;      // 0x0C:
117 	u8 is_attr_name;        // 0x0B: Faked field to manage 'ptr'
118 	u8 name_len;            // 0x0C: Faked field to manage 'ptr'
119 	u8 res;
120 	struct MFT_REF ref;     // 0x10: File Reference of file containing attribute
121 	__le64 open_record_lsn; // 0x18:
122 	void *ptr;              // 0x20:
123 };
124 
125 /* 32 bit version of 'struct OPEN_ATTR_ENRTY' */
126 struct OPEN_ATTR_ENRTY_32 {
127 	__le32 next;            // 0x00: RESTART_ENTRY_ALLOCATED if allocated
128 	__le32 ptr;             // 0x04:
129 	struct MFT_REF ref;     // 0x08:
130 	__le64 open_record_lsn; // 0x10:
131 	u8 is_dirty_pages;      // 0x18:
132 	u8 is_attr_name;        // 0x19:
133 	u8 res1[2];
134 	enum ATTR_TYPE type;    // 0x1C:
135 	u8 name_len;            // 0x20: In wchar
136 	u8 res2[3];
137 	__le32 AttributeName;   // 0x24:
138 	__le32 bytes_per_index; // 0x28:
139 };
140 
141 #define SIZEOF_OPENATTRIBUTEENTRY0 0x2c
142 // static_assert( 0x2C == sizeof(struct OPEN_ATTR_ENRTY_32) );
143 static_assert(sizeof(struct OPEN_ATTR_ENRTY) < SIZEOF_OPENATTRIBUTEENTRY0);
144 
145 /*
146  * One entry exists in the Dirty Pages Table for each page which is dirty at
147  * the time the Restart Area is written.
148  */
149 struct DIR_PAGE_ENTRY {
150 	__le32 next;         // 0x00: RESTART_ENTRY_ALLOCATED if allocated
151 	__le32 target_attr;  // 0x04: Index into the Open attribute Table
152 	__le32 transfer_len; // 0x08:
153 	__le32 lcns_follow;  // 0x0C:
154 	__le64 vcn;          // 0x10: Vcn of dirty page
155 	__le64 oldest_lsn;   // 0x18:
156 	__le64 page_lcns[];  // 0x20:
157 };
158 
159 static_assert(sizeof(struct DIR_PAGE_ENTRY) == 0x20);
160 
161 /* 32 bit version of 'struct DIR_PAGE_ENTRY' */
162 struct DIR_PAGE_ENTRY_32 {
163 	__le32 next;		// 0x00: RESTART_ENTRY_ALLOCATED if allocated
164 	__le32 target_attr;	// 0x04: Index into the Open attribute Table
165 	__le32 transfer_len;	// 0x08:
166 	__le32 lcns_follow;	// 0x0C:
167 	__le32 reserved;	// 0x10:
168 	__le32 vcn_low;		// 0x14: Vcn of dirty page
169 	__le32 vcn_hi;		// 0x18: Vcn of dirty page
170 	__le32 oldest_lsn_low;	// 0x1C:
171 	__le32 oldest_lsn_hi;	// 0x1C:
172 	__le32 page_lcns_low;	// 0x24:
173 	__le32 page_lcns_hi;	// 0x24:
174 };
175 
176 static_assert(offsetof(struct DIR_PAGE_ENTRY_32, vcn_low) == 0x14);
177 static_assert(sizeof(struct DIR_PAGE_ENTRY_32) == 0x2c);
178 
179 enum transact_state {
180 	TransactionUninitialized = 0,
181 	TransactionActive,
182 	TransactionPrepared,
183 	TransactionCommitted
184 };
185 
186 struct TRANSACTION_ENTRY {
187 	__le32 next;          // 0x00: RESTART_ENTRY_ALLOCATED if allocated
188 	u8 transact_state;    // 0x04:
189 	u8 reserved[3];       // 0x05:
190 	__le64 first_lsn;     // 0x08:
191 	__le64 prev_lsn;      // 0x10:
192 	__le64 undo_next_lsn; // 0x18:
193 	__le32 undo_records;  // 0x20: Number of undo log records pending abort
194 	__le32 undo_len;      // 0x24: Total undo size
195 };
196 
197 static_assert(sizeof(struct TRANSACTION_ENTRY) == 0x28);
198 
199 struct NTFS_RESTART {
200 	__le32 major_ver;             // 0x00:
201 	__le32 minor_ver;             // 0x04:
202 	__le64 check_point_start;     // 0x08:
203 	__le64 open_attr_table_lsn;   // 0x10:
204 	__le64 attr_names_lsn;        // 0x18:
205 	__le64 dirty_pages_table_lsn; // 0x20:
206 	__le64 transact_table_lsn;    // 0x28:
207 	__le32 open_attr_len;         // 0x30: In bytes
208 	__le32 attr_names_len;        // 0x34: In bytes
209 	__le32 dirty_pages_len;       // 0x38: In bytes
210 	__le32 transact_table_len;    // 0x3C: In bytes
211 };
212 
213 static_assert(sizeof(struct NTFS_RESTART) == 0x40);
214 
215 struct NEW_ATTRIBUTE_SIZES {
216 	__le64 alloc_size;
217 	__le64 valid_size;
218 	__le64 data_size;
219 	__le64 total_size;
220 };
221 
222 struct BITMAP_RANGE {
223 	__le32 bitmap_off;
224 	__le32 bits;
225 };
226 
227 struct LCN_RANGE {
228 	__le64 lcn;
229 	__le64 len;
230 };
231 
232 /* The following type defines the different log record types. */
233 #define LfsClientRecord  cpu_to_le32(1)
234 #define LfsClientRestart cpu_to_le32(2)
235 
236 /* This is used to uniquely identify a client for a particular log file. */
237 struct CLIENT_ID {
238 	__le16 seq_num;
239 	__le16 client_idx;
240 };
241 
242 /* This is the header that begins every Log Record in the log file. */
243 struct LFS_RECORD_HDR {
244 	__le64 this_lsn;		// 0x00:
245 	__le64 client_prev_lsn;		// 0x08:
246 	__le64 client_undo_next_lsn;	// 0x10:
247 	__le32 client_data_len;		// 0x18:
248 	struct CLIENT_ID client;	// 0x1C: Owner of this log record.
249 	__le32 record_type;		// 0x20: LfsClientRecord or LfsClientRestart.
250 	__le32 transact_id;		// 0x24:
251 	__le16 flags;			// 0x28: LOG_RECORD_MULTI_PAGE
252 	u8 align[6];			// 0x2A:
253 };
254 
255 #define LOG_RECORD_MULTI_PAGE cpu_to_le16(1)
256 
257 static_assert(sizeof(struct LFS_RECORD_HDR) == 0x30);
258 
259 struct LFS_RECORD {
260 	__le16 next_record_off;	// 0x00: Offset of the free space in the page,
261 	u8 align[6];		// 0x02:
262 	__le64 last_end_lsn;	// 0x08: lsn for the last log record which ends on the page,
263 };
264 
265 static_assert(sizeof(struct LFS_RECORD) == 0x10);
266 
267 struct RECORD_PAGE_HDR {
268 	struct NTFS_RECORD_HEADER rhdr;	// 'RCRD'
269 	__le32 rflags;			// 0x10: See LOG_PAGE_LOG_RECORD_END
270 	__le16 page_count;		// 0x14:
271 	__le16 page_pos;		// 0x16:
272 	struct LFS_RECORD record_hdr;	// 0x18:
273 	__le16 fixups[10];		// 0x28:
274 	__le32 file_off;		// 0x3c: Used when major version >= 2
275 };
276 
277 // clang-format on
278 
279 // Page contains the end of a log record.
280 #define LOG_PAGE_LOG_RECORD_END cpu_to_le32(0x00000001)
281 
is_log_record_end(const struct RECORD_PAGE_HDR * hdr)282 static inline bool is_log_record_end(const struct RECORD_PAGE_HDR *hdr)
283 {
284 	return hdr->rflags & LOG_PAGE_LOG_RECORD_END;
285 }
286 
287 static_assert(offsetof(struct RECORD_PAGE_HDR, file_off) == 0x3c);
288 
289 /*
290  * END of NTFS LOG structures
291  */
292 
293 /* Define some tuning parameters to keep the restart tables a reasonable size. */
294 #define INITIAL_NUMBER_TRANSACTIONS 5
295 
296 enum NTFS_LOG_OPERATION {
297 
298 	Noop = 0x00,
299 	CompensationLogRecord = 0x01,
300 	InitializeFileRecordSegment = 0x02,
301 	DeallocateFileRecordSegment = 0x03,
302 	WriteEndOfFileRecordSegment = 0x04,
303 	CreateAttribute = 0x05,
304 	DeleteAttribute = 0x06,
305 	UpdateResidentValue = 0x07,
306 	UpdateNonresidentValue = 0x08,
307 	UpdateMappingPairs = 0x09,
308 	DeleteDirtyClusters = 0x0A,
309 	SetNewAttributeSizes = 0x0B,
310 	AddIndexEntryRoot = 0x0C,
311 	DeleteIndexEntryRoot = 0x0D,
312 	AddIndexEntryAllocation = 0x0E,
313 	DeleteIndexEntryAllocation = 0x0F,
314 	WriteEndOfIndexBuffer = 0x10,
315 	SetIndexEntryVcnRoot = 0x11,
316 	SetIndexEntryVcnAllocation = 0x12,
317 	UpdateFileNameRoot = 0x13,
318 	UpdateFileNameAllocation = 0x14,
319 	SetBitsInNonresidentBitMap = 0x15,
320 	ClearBitsInNonresidentBitMap = 0x16,
321 	HotFix = 0x17,
322 	EndTopLevelAction = 0x18,
323 	PrepareTransaction = 0x19,
324 	CommitTransaction = 0x1A,
325 	ForgetTransaction = 0x1B,
326 	OpenNonresidentAttribute = 0x1C,
327 	OpenAttributeTableDump = 0x1D,
328 	AttributeNamesDump = 0x1E,
329 	DirtyPageTableDump = 0x1F,
330 	TransactionTableDump = 0x20,
331 	UpdateRecordDataRoot = 0x21,
332 	UpdateRecordDataAllocation = 0x22,
333 
334 	UpdateRelativeDataInIndex =
335 		0x23, // NtOfsRestartUpdateRelativeDataInIndex
336 	UpdateRelativeDataInIndex2 = 0x24,
337 	ZeroEndOfFileRecord = 0x25,
338 };
339 
340 /*
341  * Array for log records which require a target attribute.
342  * A true indicates that the corresponding restart operation
343  * requires a target attribute.
344  */
345 static const u8 AttributeRequired[] = {
346 	0xFC, 0xFB, 0xFF, 0x10, 0x06,
347 };
348 
is_target_required(u16 op)349 static inline bool is_target_required(u16 op)
350 {
351 	bool ret = op <= UpdateRecordDataAllocation &&
352 		   (AttributeRequired[op >> 3] >> (op & 7) & 1);
353 	return ret;
354 }
355 
can_skip_action(enum NTFS_LOG_OPERATION op)356 static inline bool can_skip_action(enum NTFS_LOG_OPERATION op)
357 {
358 	switch (op) {
359 	case Noop:
360 	case DeleteDirtyClusters:
361 	case HotFix:
362 	case EndTopLevelAction:
363 	case PrepareTransaction:
364 	case CommitTransaction:
365 	case ForgetTransaction:
366 	case CompensationLogRecord:
367 	case OpenNonresidentAttribute:
368 	case OpenAttributeTableDump:
369 	case AttributeNamesDump:
370 	case DirtyPageTableDump:
371 	case TransactionTableDump:
372 		return true;
373 	default:
374 		return false;
375 	}
376 }
377 
378 enum { lcb_ctx_undo_next, lcb_ctx_prev, lcb_ctx_next };
379 
380 /* Bytes per restart table. */
bytes_per_rt(const struct RESTART_TABLE * rt)381 static inline u32 bytes_per_rt(const struct RESTART_TABLE *rt)
382 {
383 	return le16_to_cpu(rt->used) * le16_to_cpu(rt->size) +
384 	       sizeof(struct RESTART_TABLE);
385 }
386 
387 /* Log record length. */
lrh_length(const struct LOG_REC_HDR * lr)388 static inline u32 lrh_length(const struct LOG_REC_HDR *lr)
389 {
390 	u16 t16 = le16_to_cpu(lr->lcns_follow);
391 
392 	return struct_size(lr, page_lcns, max_t(u16, 1, t16));
393 }
394 
395 struct lcb {
396 	struct LFS_RECORD_HDR *lrh; // Log record header of the current lsn.
397 	struct LOG_REC_HDR *log_rec;
398 	u32 ctx_mode; // lcb_ctx_undo_next/lcb_ctx_prev/lcb_ctx_next
399 	struct CLIENT_ID client;
400 	bool alloc; // If true the we should deallocate 'log_rec'.
401 };
402 
lcb_put(struct lcb * lcb)403 static void lcb_put(struct lcb *lcb)
404 {
405 	if (lcb->alloc)
406 		kfree(lcb->log_rec);
407 	kfree(lcb->lrh);
408 	kfree(lcb);
409 }
410 
411 /* Find the oldest lsn from active clients. */
oldest_client_lsn(const struct CLIENT_REC * ca,__le16 next_client,u64 * oldest_lsn)412 static inline void oldest_client_lsn(const struct CLIENT_REC *ca,
413 				     __le16 next_client, u64 *oldest_lsn)
414 {
415 	while (next_client != LFS_NO_CLIENT_LE) {
416 		const struct CLIENT_REC *cr = ca + le16_to_cpu(next_client);
417 		u64 lsn = le64_to_cpu(cr->oldest_lsn);
418 
419 		/* Ignore this block if it's oldest lsn is 0. */
420 		if (lsn && lsn < *oldest_lsn)
421 			*oldest_lsn = lsn;
422 
423 		next_client = cr->next_client;
424 	}
425 }
426 
is_rst_page_hdr_valid(u32 file_off,const struct RESTART_HDR * rhdr)427 static inline bool is_rst_page_hdr_valid(u32 file_off,
428 					 const struct RESTART_HDR *rhdr)
429 {
430 	u32 sys_page = le32_to_cpu(rhdr->sys_page_size);
431 	u32 page_size = le32_to_cpu(rhdr->page_size);
432 	u32 end_usa;
433 	u16 ro;
434 
435 	if (sys_page < SECTOR_SIZE || page_size < SECTOR_SIZE ||
436 	    sys_page & (sys_page - 1) || page_size & (page_size - 1)) {
437 		return false;
438 	}
439 
440 	/* Check that if the file offset isn't 0, it is the system page size. */
441 	if (file_off && file_off != sys_page)
442 		return false;
443 
444 	/* Check support version 1.1+. */
445 	if (le16_to_cpu(rhdr->major_ver) <= 1 && !rhdr->minor_ver)
446 		return false;
447 
448 	if (le16_to_cpu(rhdr->major_ver) > 2)
449 		return false;
450 
451 	ro = le16_to_cpu(rhdr->ra_off);
452 	if (!IS_ALIGNED(ro, 8) || ro > sys_page)
453 		return false;
454 
455 	end_usa = ((sys_page >> SECTOR_SHIFT) + 1) * sizeof(short);
456 	end_usa += le16_to_cpu(rhdr->rhdr.fix_off);
457 
458 	if (ro < end_usa)
459 		return false;
460 
461 	return true;
462 }
463 
is_rst_area_valid(const struct RESTART_HDR * rhdr)464 static inline bool is_rst_area_valid(const struct RESTART_HDR *rhdr)
465 {
466 	const struct RESTART_AREA *ra;
467 	u16 cl, fl, ul;
468 	u32 off, l_size, seq_bits;
469 	u16 ro = le16_to_cpu(rhdr->ra_off);
470 	u32 sys_page = le32_to_cpu(rhdr->sys_page_size);
471 
472 	if (ro + offsetof(struct RESTART_AREA, l_size) >
473 	    SECTOR_SIZE - sizeof(short))
474 		return false;
475 
476 	ra = Add2Ptr(rhdr, ro);
477 	cl = le16_to_cpu(ra->log_clients);
478 
479 	if (cl > 1)
480 		return false;
481 
482 	off = le16_to_cpu(ra->client_off);
483 
484 	if (!IS_ALIGNED(off, 8) || ro + off > SECTOR_SIZE - sizeof(short))
485 		return false;
486 
487 	off += cl * sizeof(struct CLIENT_REC);
488 
489 	if (off > sys_page)
490 		return false;
491 
492 	/*
493 	 * Check the restart length field and whether the entire
494 	 * restart area is contained that length.
495 	 */
496 	if (le16_to_cpu(rhdr->ra_off) + le16_to_cpu(ra->ra_len) > sys_page ||
497 	    off > le16_to_cpu(ra->ra_len)) {
498 		return false;
499 	}
500 
501 	/*
502 	 * As a final check make sure that the use list and the free list
503 	 * are either empty or point to a valid client.
504 	 */
505 	fl = le16_to_cpu(ra->client_idx[0]);
506 	ul = le16_to_cpu(ra->client_idx[1]);
507 	if ((fl != LFS_NO_CLIENT && fl >= cl) ||
508 	    (ul != LFS_NO_CLIENT && ul >= cl))
509 		return false;
510 
511 	/* Make sure the sequence number bits match the log file size. */
512 	l_size = le64_to_cpu(ra->l_size);
513 
514 	seq_bits = sizeof(u64) * 8 + 3;
515 	while (l_size) {
516 		l_size >>= 1;
517 		seq_bits -= 1;
518 	}
519 
520 	if (seq_bits != ra->seq_num_bits)
521 		return false;
522 
523 	/* The log page data offset and record header length must be quad-aligned. */
524 	if (!IS_ALIGNED(le16_to_cpu(ra->data_off), 8) ||
525 	    !IS_ALIGNED(le16_to_cpu(ra->rec_hdr_len), 8))
526 		return false;
527 
528 	return true;
529 }
530 
is_client_area_valid(const struct RESTART_HDR * rhdr,bool usa_error)531 static inline bool is_client_area_valid(const struct RESTART_HDR *rhdr,
532 					bool usa_error)
533 {
534 	u16 ro = le16_to_cpu(rhdr->ra_off);
535 	const struct RESTART_AREA *ra = Add2Ptr(rhdr, ro);
536 	u16 ra_len = le16_to_cpu(ra->ra_len);
537 	const struct CLIENT_REC *ca;
538 	u32 i;
539 
540 	if (usa_error && ra_len + ro > SECTOR_SIZE - sizeof(short))
541 		return false;
542 
543 	/* Find the start of the client array. */
544 	ca = Add2Ptr(ra, le16_to_cpu(ra->client_off));
545 
546 	/*
547 	 * Start with the free list.
548 	 * Check that all the clients are valid and that there isn't a cycle.
549 	 * Do the in-use list on the second pass.
550 	 */
551 	for (i = 0; i < 2; i++) {
552 		u16 client_idx = le16_to_cpu(ra->client_idx[i]);
553 		bool first_client = true;
554 		u16 clients = le16_to_cpu(ra->log_clients);
555 
556 		while (client_idx != LFS_NO_CLIENT) {
557 			const struct CLIENT_REC *cr;
558 
559 			if (!clients ||
560 			    client_idx >= le16_to_cpu(ra->log_clients))
561 				return false;
562 
563 			clients -= 1;
564 			cr = ca + client_idx;
565 
566 			client_idx = le16_to_cpu(cr->next_client);
567 
568 			if (first_client) {
569 				first_client = false;
570 				if (cr->prev_client != LFS_NO_CLIENT_LE)
571 					return false;
572 			}
573 		}
574 	}
575 
576 	return true;
577 }
578 
579 /*
580  * remove_client
581  *
582  * Remove a client record from a client record list an restart area.
583  */
remove_client(struct CLIENT_REC * ca,const struct CLIENT_REC * cr,__le16 * head)584 static inline void remove_client(struct CLIENT_REC *ca,
585 				 const struct CLIENT_REC *cr, __le16 *head)
586 {
587 	if (cr->prev_client == LFS_NO_CLIENT_LE)
588 		*head = cr->next_client;
589 	else
590 		ca[le16_to_cpu(cr->prev_client)].next_client = cr->next_client;
591 
592 	if (cr->next_client != LFS_NO_CLIENT_LE)
593 		ca[le16_to_cpu(cr->next_client)].prev_client = cr->prev_client;
594 }
595 
596 /*
597  * add_client - Add a client record to the start of a list.
598  */
add_client(struct CLIENT_REC * ca,u16 index,__le16 * head)599 static inline void add_client(struct CLIENT_REC *ca, u16 index, __le16 *head)
600 {
601 	struct CLIENT_REC *cr = ca + index;
602 
603 	cr->prev_client = LFS_NO_CLIENT_LE;
604 	cr->next_client = *head;
605 
606 	if (*head != LFS_NO_CLIENT_LE)
607 		ca[le16_to_cpu(*head)].prev_client = cpu_to_le16(index);
608 
609 	*head = cpu_to_le16(index);
610 }
611 
enum_rstbl(struct RESTART_TABLE * t,void * c)612 static inline void *enum_rstbl(struct RESTART_TABLE *t, void *c)
613 {
614 	__le32 *e;
615 	u32 bprt;
616 	u16 rsize = t ? le16_to_cpu(t->size) : 0;
617 
618 	if (!c) {
619 		if (!t || !t->total)
620 			return NULL;
621 		e = Add2Ptr(t, sizeof(struct RESTART_TABLE));
622 	} else {
623 		e = Add2Ptr(c, rsize);
624 	}
625 
626 	/* Loop until we hit the first one allocated, or the end of the list. */
627 	for (bprt = bytes_per_rt(t); PtrOffset(t, e) < bprt;
628 	     e = Add2Ptr(e, rsize)) {
629 		if (*e == RESTART_ENTRY_ALLOCATED_LE)
630 			return e;
631 	}
632 	return NULL;
633 }
634 
635 /*
636  * find_dp - Search for a @vcn in Dirty Page Table.
637  */
find_dp(struct RESTART_TABLE * dptbl,u32 target_attr,u64 vcn)638 static inline struct DIR_PAGE_ENTRY *find_dp(struct RESTART_TABLE *dptbl,
639 					     u32 target_attr, u64 vcn)
640 {
641 	__le32 ta = cpu_to_le32(target_attr);
642 	struct DIR_PAGE_ENTRY *dp = NULL;
643 
644 	while ((dp = enum_rstbl(dptbl, dp))) {
645 		u64 dp_vcn = le64_to_cpu(dp->vcn);
646 
647 		if (dp->target_attr == ta && vcn >= dp_vcn &&
648 		    vcn < dp_vcn + le32_to_cpu(dp->lcns_follow)) {
649 			return dp;
650 		}
651 	}
652 	return NULL;
653 }
654 
norm_file_page(u32 page_size,u32 * l_size,bool use_default)655 static inline u32 norm_file_page(u32 page_size, u32 *l_size, bool use_default)
656 {
657 	if (use_default)
658 		page_size = DefaultLogPageSize;
659 
660 	/* Round the file size down to a system page boundary. */
661 	*l_size &= ~(page_size - 1);
662 
663 	/* File should contain at least 2 restart pages and MinLogRecordPages pages. */
664 	if (*l_size < (MinLogRecordPages + 2) * page_size)
665 		return 0;
666 
667 	return page_size;
668 }
669 
check_log_rec(const struct LOG_REC_HDR * lr,u32 bytes,u32 tr,u32 bytes_per_attr_entry)670 static bool check_log_rec(const struct LOG_REC_HDR *lr, u32 bytes, u32 tr,
671 			  u32 bytes_per_attr_entry)
672 {
673 	u16 t16;
674 
675 	if (bytes < sizeof(struct LOG_REC_HDR))
676 		return false;
677 	if (!tr)
678 		return false;
679 
680 	if ((tr - sizeof(struct RESTART_TABLE)) %
681 	    sizeof(struct TRANSACTION_ENTRY))
682 		return false;
683 
684 	if (le16_to_cpu(lr->redo_off) & 7)
685 		return false;
686 
687 	if (le16_to_cpu(lr->undo_off) & 7)
688 		return false;
689 
690 	if (lr->target_attr)
691 		goto check_lcns;
692 
693 	if (is_target_required(le16_to_cpu(lr->redo_op)))
694 		return false;
695 
696 	if (is_target_required(le16_to_cpu(lr->undo_op)))
697 		return false;
698 
699 check_lcns:
700 	if (!lr->lcns_follow)
701 		goto check_length;
702 
703 	t16 = le16_to_cpu(lr->target_attr);
704 	if ((t16 - sizeof(struct RESTART_TABLE)) % bytes_per_attr_entry)
705 		return false;
706 
707 check_length:
708 	if (bytes < lrh_length(lr))
709 		return false;
710 
711 	return true;
712 }
713 
check_rstbl(const struct RESTART_TABLE * rt,size_t bytes)714 static bool check_rstbl(const struct RESTART_TABLE *rt, size_t bytes)
715 {
716 	u32 ts;
717 	u32 i, off;
718 	u16 rsize = le16_to_cpu(rt->size);
719 	u16 ne = le16_to_cpu(rt->used);
720 	u32 ff = le32_to_cpu(rt->first_free);
721 	u32 lf = le32_to_cpu(rt->last_free);
722 
723 	ts = rsize * ne + sizeof(struct RESTART_TABLE);
724 
725 	if (!rsize || rsize > bytes ||
726 	    rsize + sizeof(struct RESTART_TABLE) > bytes || bytes < ts ||
727 	    le16_to_cpu(rt->total) > ne || ff > ts || lf > ts ||
728 	    (ff && ff < sizeof(struct RESTART_TABLE)) ||
729 	    (lf && lf < sizeof(struct RESTART_TABLE))) {
730 		return false;
731 	}
732 
733 	/*
734 	 * Verify each entry is either allocated or points
735 	 * to a valid offset the table.
736 	 */
737 	for (i = 0; i < ne; i++) {
738 		off = le32_to_cpu(*(__le32 *)Add2Ptr(
739 			rt, i * rsize + sizeof(struct RESTART_TABLE)));
740 
741 		if (off != RESTART_ENTRY_ALLOCATED && off &&
742 		    (off < sizeof(struct RESTART_TABLE) ||
743 		     ((off - sizeof(struct RESTART_TABLE)) % rsize))) {
744 			return false;
745 		}
746 	}
747 
748 	/*
749 	 * Walk through the list headed by the first entry to make
750 	 * sure none of the entries are currently being used.
751 	 */
752 	for (off = ff; off;) {
753 		if (off == RESTART_ENTRY_ALLOCATED)
754 			return false;
755 
756 		off = le32_to_cpu(*(__le32 *)Add2Ptr(rt, off));
757 	}
758 
759 	return true;
760 }
761 
762 /*
763  * free_rsttbl_idx - Free a previously allocated index a Restart Table.
764  */
free_rsttbl_idx(struct RESTART_TABLE * rt,u32 off)765 static inline void free_rsttbl_idx(struct RESTART_TABLE *rt, u32 off)
766 {
767 	__le32 *e;
768 	u32 lf = le32_to_cpu(rt->last_free);
769 	__le32 off_le = cpu_to_le32(off);
770 
771 	e = Add2Ptr(rt, off);
772 
773 	if (off < le32_to_cpu(rt->free_goal)) {
774 		*e = rt->first_free;
775 		rt->first_free = off_le;
776 		if (!lf)
777 			rt->last_free = off_le;
778 	} else {
779 		if (lf)
780 			*(__le32 *)Add2Ptr(rt, lf) = off_le;
781 		else
782 			rt->first_free = off_le;
783 
784 		rt->last_free = off_le;
785 		*e = 0;
786 	}
787 
788 	le16_sub_cpu(&rt->total, 1);
789 }
790 
init_rsttbl(u16 esize,u16 used)791 static inline struct RESTART_TABLE *init_rsttbl(u16 esize, u16 used)
792 {
793 	__le32 *e, *last_free;
794 	u32 off;
795 	u32 bytes = esize * used + sizeof(struct RESTART_TABLE);
796 	u32 lf = sizeof(struct RESTART_TABLE) + (used - 1) * esize;
797 	struct RESTART_TABLE *t = kzalloc(bytes, GFP_NOFS);
798 
799 	if (!t)
800 		return NULL;
801 
802 	t->size = cpu_to_le16(esize);
803 	t->used = cpu_to_le16(used);
804 	t->free_goal = cpu_to_le32(~0u);
805 	t->first_free = cpu_to_le32(sizeof(struct RESTART_TABLE));
806 	t->last_free = cpu_to_le32(lf);
807 
808 	e = (__le32 *)(t + 1);
809 	last_free = Add2Ptr(t, lf);
810 
811 	for (off = sizeof(struct RESTART_TABLE) + esize; e < last_free;
812 	     e = Add2Ptr(e, esize), off += esize) {
813 		*e = cpu_to_le32(off);
814 	}
815 	return t;
816 }
817 
extend_rsttbl(struct RESTART_TABLE * tbl,u32 add,u32 free_goal)818 static inline struct RESTART_TABLE *extend_rsttbl(struct RESTART_TABLE *tbl,
819 						  u32 add, u32 free_goal)
820 {
821 	u16 esize = le16_to_cpu(tbl->size);
822 	__le32 osize = cpu_to_le32(bytes_per_rt(tbl));
823 	u32 used = le16_to_cpu(tbl->used);
824 	struct RESTART_TABLE *rt;
825 
826 	rt = init_rsttbl(esize, used + add);
827 	if (!rt)
828 		return NULL;
829 
830 	memcpy(rt + 1, tbl + 1, esize * used);
831 
832 	rt->free_goal = free_goal == ~0u
833 				? cpu_to_le32(~0u)
834 				: cpu_to_le32(sizeof(struct RESTART_TABLE) +
835 					      free_goal * esize);
836 
837 	if (tbl->first_free) {
838 		rt->first_free = tbl->first_free;
839 		*(__le32 *)Add2Ptr(rt, le32_to_cpu(tbl->last_free)) = osize;
840 	} else {
841 		rt->first_free = osize;
842 	}
843 
844 	rt->total = tbl->total;
845 
846 	kfree(tbl);
847 	return rt;
848 }
849 
850 /*
851  * alloc_rsttbl_idx
852  *
853  * Allocate an index from within a previously initialized Restart Table.
854  */
alloc_rsttbl_idx(struct RESTART_TABLE ** tbl)855 static inline void *alloc_rsttbl_idx(struct RESTART_TABLE **tbl)
856 {
857 	u32 off;
858 	__le32 *e;
859 	struct RESTART_TABLE *t = *tbl;
860 
861 	if (!t->first_free) {
862 		*tbl = t = extend_rsttbl(t, 16, ~0u);
863 		if (!t)
864 			return NULL;
865 	}
866 
867 	off = le32_to_cpu(t->first_free);
868 
869 	/* Dequeue this entry and zero it. */
870 	e = Add2Ptr(t, off);
871 
872 	t->first_free = *e;
873 
874 	memset(e, 0, le16_to_cpu(t->size));
875 
876 	*e = RESTART_ENTRY_ALLOCATED_LE;
877 
878 	/* If list is going empty, then we fix the last_free as well. */
879 	if (!t->first_free)
880 		t->last_free = 0;
881 
882 	le16_add_cpu(&t->total, 1);
883 
884 	return Add2Ptr(t, off);
885 }
886 
887 /*
888  * alloc_rsttbl_from_idx
889  *
890  * Allocate a specific index from within a previously initialized Restart Table.
891  */
alloc_rsttbl_from_idx(struct RESTART_TABLE ** tbl,u32 vbo)892 static inline void *alloc_rsttbl_from_idx(struct RESTART_TABLE **tbl, u32 vbo)
893 {
894 	u32 off;
895 	__le32 *e;
896 	struct RESTART_TABLE *rt = *tbl;
897 	u32 bytes = bytes_per_rt(rt);
898 	u16 esize = le16_to_cpu(rt->size);
899 
900 	/* If the entry is not the table, we will have to extend the table. */
901 	if (vbo >= bytes) {
902 		/*
903 		 * Extend the size by computing the number of entries between
904 		 * the existing size and the desired index and adding 1 to that.
905 		 */
906 		u32 bytes2idx = vbo - bytes;
907 
908 		/*
909 		 * There should always be an integral number of entries
910 		 * being added. Now extend the table.
911 		 */
912 		*tbl = rt = extend_rsttbl(rt, bytes2idx / esize + 1, bytes);
913 		if (!rt)
914 			return NULL;
915 	}
916 
917 	/* See if the entry is already allocated, and just return if it is. */
918 	e = Add2Ptr(rt, vbo);
919 
920 	if (*e == RESTART_ENTRY_ALLOCATED_LE)
921 		return e;
922 
923 	/*
924 	 * Walk through the table, looking for the entry we're
925 	 * interested and the previous entry.
926 	 */
927 	off = le32_to_cpu(rt->first_free);
928 	e = Add2Ptr(rt, off);
929 
930 	if (off == vbo) {
931 		/* this is a match */
932 		rt->first_free = *e;
933 		goto skip_looking;
934 	}
935 
936 	/*
937 	 * Need to walk through the list looking for the predecessor
938 	 * of our entry.
939 	 */
940 	for (;;) {
941 		/* Remember the entry just found */
942 		u32 last_off = off;
943 		__le32 *last_e = e;
944 
945 		/* Should never run of entries. */
946 
947 		/* Lookup up the next entry the list. */
948 		off = le32_to_cpu(*last_e);
949 		e = Add2Ptr(rt, off);
950 
951 		/* If this is our match we are done. */
952 		if (off == vbo) {
953 			*last_e = *e;
954 
955 			/*
956 			 * If this was the last entry, we update that
957 			 * table as well.
958 			 */
959 			if (le32_to_cpu(rt->last_free) == off)
960 				rt->last_free = cpu_to_le32(last_off);
961 			break;
962 		}
963 	}
964 
965 skip_looking:
966 	/* If the list is now empty, we fix the last_free as well. */
967 	if (!rt->first_free)
968 		rt->last_free = 0;
969 
970 	/* Zero this entry. */
971 	memset(e, 0, esize);
972 	*e = RESTART_ENTRY_ALLOCATED_LE;
973 
974 	le16_add_cpu(&rt->total, 1);
975 
976 	return e;
977 }
978 
979 #define RESTART_SINGLE_PAGE_IO cpu_to_le16(0x0001)
980 
981 #define NTFSLOG_WRAPPED 0x00000001
982 #define NTFSLOG_MULTIPLE_PAGE_IO 0x00000002
983 #define NTFSLOG_NO_LAST_LSN 0x00000004
984 #define NTFSLOG_REUSE_TAIL 0x00000010
985 #define NTFSLOG_NO_OLDEST_LSN 0x00000020
986 
987 /* Helper struct to work with NTFS $LogFile. */
988 struct ntfs_log {
989 	struct ntfs_inode *ni;
990 
991 	u32 l_size;
992 	u32 sys_page_size;
993 	u32 sys_page_mask;
994 	u32 page_size;
995 	u32 page_mask; // page_size - 1
996 	u8 page_bits;
997 	struct RECORD_PAGE_HDR *one_page_buf;
998 
999 	struct RESTART_TABLE *open_attr_tbl;
1000 	u32 transaction_id;
1001 	u32 clst_per_page;
1002 
1003 	u32 first_page;
1004 	u32 next_page;
1005 	u32 ra_off;
1006 	u32 data_off;
1007 	u32 restart_size;
1008 	u32 data_size;
1009 	u16 record_header_len;
1010 	u64 seq_num;
1011 	u32 seq_num_bits;
1012 	u32 file_data_bits;
1013 	u32 seq_num_mask; /* (1 << file_data_bits) - 1 */
1014 
1015 	struct RESTART_AREA *ra; /* In-memory image of the next restart area. */
1016 	u32 ra_size; /* The usable size of the restart area. */
1017 
1018 	/*
1019 	 * If true, then the in-memory restart area is to be written
1020 	 * to the first position on the disk.
1021 	 */
1022 	bool init_ra;
1023 	bool set_dirty; /* True if we need to set dirty flag. */
1024 
1025 	u64 oldest_lsn;
1026 
1027 	u32 oldest_lsn_off;
1028 	u64 last_lsn;
1029 
1030 	u32 total_avail;
1031 	u32 total_avail_pages;
1032 	u32 total_undo_commit;
1033 	u32 max_current_avail;
1034 	u32 current_avail;
1035 	u32 reserved;
1036 
1037 	short major_ver;
1038 	short minor_ver;
1039 
1040 	u32 l_flags; /* See NTFSLOG_XXX */
1041 	u32 current_openlog_count; /* On-disk value for open_log_count. */
1042 
1043 	struct CLIENT_ID client_id;
1044 	u32 client_undo_commit;
1045 };
1046 
lsn_to_vbo(struct ntfs_log * log,const u64 lsn)1047 static inline u32 lsn_to_vbo(struct ntfs_log *log, const u64 lsn)
1048 {
1049 	u32 vbo = (lsn << log->seq_num_bits) >> (log->seq_num_bits - 3);
1050 
1051 	return vbo;
1052 }
1053 
1054 /* Compute the offset in the log file of the next log page. */
next_page_off(struct ntfs_log * log,u32 off)1055 static inline u32 next_page_off(struct ntfs_log *log, u32 off)
1056 {
1057 	off = (off & ~log->sys_page_mask) + log->page_size;
1058 	return off >= log->l_size ? log->first_page : off;
1059 }
1060 
lsn_to_page_off(struct ntfs_log * log,u64 lsn)1061 static inline u32 lsn_to_page_off(struct ntfs_log *log, u64 lsn)
1062 {
1063 	return (((u32)lsn) << 3) & log->page_mask;
1064 }
1065 
vbo_to_lsn(struct ntfs_log * log,u32 off,u64 Seq)1066 static inline u64 vbo_to_lsn(struct ntfs_log *log, u32 off, u64 Seq)
1067 {
1068 	return (off >> 3) + (Seq << log->file_data_bits);
1069 }
1070 
is_lsn_in_file(struct ntfs_log * log,u64 lsn)1071 static inline bool is_lsn_in_file(struct ntfs_log *log, u64 lsn)
1072 {
1073 	return lsn >= log->oldest_lsn &&
1074 	       lsn <= le64_to_cpu(log->ra->current_lsn);
1075 }
1076 
hdr_file_off(struct ntfs_log * log,struct RECORD_PAGE_HDR * hdr)1077 static inline u32 hdr_file_off(struct ntfs_log *log,
1078 			       struct RECORD_PAGE_HDR *hdr)
1079 {
1080 	if (log->major_ver < 2)
1081 		return le64_to_cpu(hdr->rhdr.lsn);
1082 
1083 	return le32_to_cpu(hdr->file_off);
1084 }
1085 
base_lsn(struct ntfs_log * log,const struct RECORD_PAGE_HDR * hdr,u64 lsn)1086 static inline u64 base_lsn(struct ntfs_log *log,
1087 			   const struct RECORD_PAGE_HDR *hdr, u64 lsn)
1088 {
1089 	u64 h_lsn = le64_to_cpu(hdr->rhdr.lsn);
1090 	u64 ret = (((h_lsn >> log->file_data_bits) +
1091 		    (lsn < (lsn_to_vbo(log, h_lsn) & ~log->page_mask) ? 1 : 0))
1092 		   << log->file_data_bits) +
1093 		  ((((is_log_record_end(hdr) &&
1094 		      h_lsn <= le64_to_cpu(hdr->record_hdr.last_end_lsn))
1095 			     ? le16_to_cpu(hdr->record_hdr.next_record_off)
1096 			     : log->page_size) +
1097 		    lsn) >>
1098 		   3);
1099 
1100 	return ret;
1101 }
1102 
verify_client_lsn(struct ntfs_log * log,const struct CLIENT_REC * client,u64 lsn)1103 static inline bool verify_client_lsn(struct ntfs_log *log,
1104 				     const struct CLIENT_REC *client, u64 lsn)
1105 {
1106 	return lsn >= le64_to_cpu(client->oldest_lsn) &&
1107 	       lsn <= le64_to_cpu(log->ra->current_lsn) && lsn;
1108 }
1109 
1110 struct restart_info {
1111 	u64 last_lsn;
1112 	struct RESTART_HDR *r_page;
1113 	u32 vbo;
1114 	bool chkdsk_was_run;
1115 	bool valid_page;
1116 	bool initialized;
1117 	bool restart;
1118 };
1119 
read_log_page(struct ntfs_log * log,u32 vbo,struct RECORD_PAGE_HDR ** buffer,bool * usa_error)1120 static int read_log_page(struct ntfs_log *log, u32 vbo,
1121 			 struct RECORD_PAGE_HDR **buffer, bool *usa_error)
1122 {
1123 	int err = 0;
1124 	u32 page_idx = vbo >> log->page_bits;
1125 	u32 page_off = vbo & log->page_mask;
1126 	u32 bytes = log->page_size - page_off;
1127 	void *to_free = NULL;
1128 	u32 page_vbo = page_idx << log->page_bits;
1129 	struct RECORD_PAGE_HDR *page_buf;
1130 	struct ntfs_inode *ni = log->ni;
1131 	bool bBAAD;
1132 
1133 	if (vbo >= log->l_size)
1134 		return -EINVAL;
1135 
1136 	if (!*buffer) {
1137 		to_free = kmalloc(log->page_size, GFP_NOFS);
1138 		if (!to_free)
1139 			return -ENOMEM;
1140 		*buffer = to_free;
1141 	}
1142 
1143 	page_buf = page_off ? log->one_page_buf : *buffer;
1144 
1145 	err = ntfs_read_run_nb(ni->mi.sbi, &ni->file.run, page_vbo, page_buf,
1146 			       log->page_size, NULL);
1147 	if (err)
1148 		goto out;
1149 
1150 	if (page_buf->rhdr.sign != NTFS_FFFF_SIGNATURE)
1151 		ntfs_fix_post_read(&page_buf->rhdr, PAGE_SIZE, false);
1152 
1153 	if (page_buf != *buffer)
1154 		memcpy(*buffer, Add2Ptr(page_buf, page_off), bytes);
1155 
1156 	bBAAD = page_buf->rhdr.sign == NTFS_BAAD_SIGNATURE;
1157 
1158 	if (usa_error)
1159 		*usa_error = bBAAD;
1160 	/* Check that the update sequence array for this page is valid */
1161 	/* If we don't allow errors, raise an error status */
1162 	else if (bBAAD)
1163 		err = -EINVAL;
1164 
1165 out:
1166 	if (err && to_free) {
1167 		kfree(to_free);
1168 		*buffer = NULL;
1169 	}
1170 
1171 	return err;
1172 }
1173 
1174 /*
1175  * log_read_rst
1176  *
1177  * It walks through 512 blocks of the file looking for a valid
1178  * restart page header. It will stop the first time we find a
1179  * valid page header.
1180  */
log_read_rst(struct ntfs_log * log,u32 l_size,bool first,struct restart_info * info)1181 static int log_read_rst(struct ntfs_log *log, u32 l_size, bool first,
1182 			struct restart_info *info)
1183 {
1184 	u32 skip, vbo;
1185 	struct RESTART_HDR *r_page = NULL;
1186 
1187 	/* Determine which restart area we are looking for. */
1188 	if (first) {
1189 		vbo = 0;
1190 		skip = 512;
1191 	} else {
1192 		vbo = 512;
1193 		skip = 0;
1194 	}
1195 
1196 	/* Loop continuously until we succeed. */
1197 	for (; vbo < l_size; vbo = 2 * vbo + skip, skip = 0) {
1198 		bool usa_error;
1199 		bool brst, bchk;
1200 		struct RESTART_AREA *ra;
1201 
1202 		/* Read a page header at the current offset. */
1203 		if (read_log_page(log, vbo, (struct RECORD_PAGE_HDR **)&r_page,
1204 				  &usa_error)) {
1205 			/* Ignore any errors. */
1206 			continue;
1207 		}
1208 
1209 		/* Exit if the signature is a log record page. */
1210 		if (r_page->rhdr.sign == NTFS_RCRD_SIGNATURE) {
1211 			info->initialized = true;
1212 			break;
1213 		}
1214 
1215 		brst = r_page->rhdr.sign == NTFS_RSTR_SIGNATURE;
1216 		bchk = r_page->rhdr.sign == NTFS_CHKD_SIGNATURE;
1217 
1218 		if (!bchk && !brst) {
1219 			if (r_page->rhdr.sign != NTFS_FFFF_SIGNATURE) {
1220 				/*
1221 				 * Remember if the signature does not
1222 				 * indicate uninitialized file.
1223 				 */
1224 				info->initialized = true;
1225 			}
1226 			continue;
1227 		}
1228 
1229 		ra = NULL;
1230 		info->valid_page = false;
1231 		info->initialized = true;
1232 		info->vbo = vbo;
1233 
1234 		/* Let's check the restart area if this is a valid page. */
1235 		if (!is_rst_page_hdr_valid(vbo, r_page))
1236 			goto check_result;
1237 		ra = Add2Ptr(r_page, le16_to_cpu(r_page->ra_off));
1238 
1239 		if (!is_rst_area_valid(r_page))
1240 			goto check_result;
1241 
1242 		/*
1243 		 * We have a valid restart page header and restart area.
1244 		 * If chkdsk was run or we have no clients then we have
1245 		 * no more checking to do.
1246 		 */
1247 		if (bchk || ra->client_idx[1] == LFS_NO_CLIENT_LE) {
1248 			info->valid_page = true;
1249 			goto check_result;
1250 		}
1251 
1252 		if (is_client_area_valid(r_page, usa_error)) {
1253 			info->valid_page = true;
1254 			ra = Add2Ptr(r_page, le16_to_cpu(r_page->ra_off));
1255 		}
1256 
1257 check_result:
1258 		/*
1259 		 * If chkdsk was run then update the caller's
1260 		 * values and return.
1261 		 */
1262 		if (r_page->rhdr.sign == NTFS_CHKD_SIGNATURE) {
1263 			info->chkdsk_was_run = true;
1264 			info->last_lsn = le64_to_cpu(r_page->rhdr.lsn);
1265 			info->restart = true;
1266 			info->r_page = r_page;
1267 			return 0;
1268 		}
1269 
1270 		/*
1271 		 * If we have a valid page then copy the values
1272 		 * we need from it.
1273 		 */
1274 		if (info->valid_page) {
1275 			info->last_lsn = le64_to_cpu(ra->current_lsn);
1276 			info->restart = true;
1277 			info->r_page = r_page;
1278 			return 0;
1279 		}
1280 	}
1281 
1282 	kfree(r_page);
1283 
1284 	return 0;
1285 }
1286 
1287 /*
1288  * Ilog_init_pg_hdr - Init @log from restart page header.
1289  */
log_init_pg_hdr(struct ntfs_log * log,u32 sys_page_size,u32 page_size,u16 major_ver,u16 minor_ver)1290 static void log_init_pg_hdr(struct ntfs_log *log, u32 sys_page_size,
1291 			    u32 page_size, u16 major_ver, u16 minor_ver)
1292 {
1293 	log->sys_page_size = sys_page_size;
1294 	log->sys_page_mask = sys_page_size - 1;
1295 	log->page_size = page_size;
1296 	log->page_mask = page_size - 1;
1297 	log->page_bits = blksize_bits(page_size);
1298 
1299 	log->clst_per_page = log->page_size >> log->ni->mi.sbi->cluster_bits;
1300 	if (!log->clst_per_page)
1301 		log->clst_per_page = 1;
1302 
1303 	log->first_page = major_ver >= 2
1304 				  ? 0x22 * page_size
1305 				  : ((sys_page_size << 1) + (page_size << 1));
1306 	log->major_ver = major_ver;
1307 	log->minor_ver = minor_ver;
1308 }
1309 
1310 /*
1311  * log_create - Init @log in cases when we don't have a restart area to use.
1312  */
log_create(struct ntfs_log * log,u32 l_size,const u64 last_lsn,u32 open_log_count,bool wrapped,bool use_multi_page)1313 static void log_create(struct ntfs_log *log, u32 l_size, const u64 last_lsn,
1314 		       u32 open_log_count, bool wrapped, bool use_multi_page)
1315 {
1316 	log->l_size = l_size;
1317 	/* All file offsets must be quadword aligned. */
1318 	log->file_data_bits = blksize_bits(l_size) - 3;
1319 	log->seq_num_mask = (8 << log->file_data_bits) - 1;
1320 	log->seq_num_bits = sizeof(u64) * 8 - log->file_data_bits;
1321 	log->seq_num = (last_lsn >> log->file_data_bits) + 2;
1322 	log->next_page = log->first_page;
1323 	log->oldest_lsn = log->seq_num << log->file_data_bits;
1324 	log->oldest_lsn_off = 0;
1325 	log->last_lsn = log->oldest_lsn;
1326 
1327 	log->l_flags |= NTFSLOG_NO_LAST_LSN | NTFSLOG_NO_OLDEST_LSN;
1328 
1329 	/* Set the correct flags for the I/O and indicate if we have wrapped. */
1330 	if (wrapped)
1331 		log->l_flags |= NTFSLOG_WRAPPED;
1332 
1333 	if (use_multi_page)
1334 		log->l_flags |= NTFSLOG_MULTIPLE_PAGE_IO;
1335 
1336 	/* Compute the log page values. */
1337 	log->data_off = ALIGN(
1338 		offsetof(struct RECORD_PAGE_HDR, fixups) +
1339 			sizeof(short) * ((log->page_size >> SECTOR_SHIFT) + 1),
1340 		8);
1341 	log->data_size = log->page_size - log->data_off;
1342 	log->record_header_len = sizeof(struct LFS_RECORD_HDR);
1343 
1344 	/* Remember the different page sizes for reservation. */
1345 	log->reserved = log->data_size - log->record_header_len;
1346 
1347 	/* Compute the restart page values. */
1348 	log->ra_off = ALIGN(
1349 		offsetof(struct RESTART_HDR, fixups) +
1350 			sizeof(short) *
1351 				((log->sys_page_size >> SECTOR_SHIFT) + 1),
1352 		8);
1353 	log->restart_size = log->sys_page_size - log->ra_off;
1354 	log->ra_size = struct_size(log->ra, clients, 1);
1355 	log->current_openlog_count = open_log_count;
1356 
1357 	/*
1358 	 * The total available log file space is the number of
1359 	 * log file pages times the space available on each page.
1360 	 */
1361 	log->total_avail_pages = log->l_size - log->first_page;
1362 	log->total_avail = log->total_avail_pages >> log->page_bits;
1363 
1364 	/*
1365 	 * We assume that we can't use the end of the page less than
1366 	 * the file record size.
1367 	 * Then we won't need to reserve more than the caller asks for.
1368 	 */
1369 	log->max_current_avail = log->total_avail * log->reserved;
1370 	log->total_avail = log->total_avail * log->data_size;
1371 	log->current_avail = log->max_current_avail;
1372 }
1373 
1374 /*
1375  * log_create_ra - Fill a restart area from the values stored in @log.
1376  */
log_create_ra(struct ntfs_log * log)1377 static struct RESTART_AREA *log_create_ra(struct ntfs_log *log)
1378 {
1379 	struct CLIENT_REC *cr;
1380 	struct RESTART_AREA *ra = kzalloc(log->restart_size, GFP_NOFS);
1381 
1382 	if (!ra)
1383 		return NULL;
1384 
1385 	ra->current_lsn = cpu_to_le64(log->last_lsn);
1386 	ra->log_clients = cpu_to_le16(1);
1387 	ra->client_idx[1] = LFS_NO_CLIENT_LE;
1388 	if (log->l_flags & NTFSLOG_MULTIPLE_PAGE_IO)
1389 		ra->flags = RESTART_SINGLE_PAGE_IO;
1390 	ra->seq_num_bits = cpu_to_le32(log->seq_num_bits);
1391 	ra->ra_len = cpu_to_le16(log->ra_size);
1392 	ra->client_off = cpu_to_le16(offsetof(struct RESTART_AREA, clients));
1393 	ra->l_size = cpu_to_le64(log->l_size);
1394 	ra->rec_hdr_len = cpu_to_le16(log->record_header_len);
1395 	ra->data_off = cpu_to_le16(log->data_off);
1396 	ra->open_log_count = cpu_to_le32(log->current_openlog_count + 1);
1397 
1398 	cr = ra->clients;
1399 
1400 	cr->prev_client = LFS_NO_CLIENT_LE;
1401 	cr->next_client = LFS_NO_CLIENT_LE;
1402 
1403 	return ra;
1404 }
1405 
final_log_off(struct ntfs_log * log,u64 lsn,u32 data_len)1406 static u32 final_log_off(struct ntfs_log *log, u64 lsn, u32 data_len)
1407 {
1408 	u32 base_vbo = lsn << 3;
1409 	u32 final_log_off = (base_vbo & log->seq_num_mask) & ~log->page_mask;
1410 	u32 page_off = base_vbo & log->page_mask;
1411 	u32 tail = log->page_size - page_off;
1412 
1413 	page_off -= 1;
1414 
1415 	/* Add the length of the header. */
1416 	data_len += log->record_header_len;
1417 
1418 	/*
1419 	 * If this lsn is contained this log page we are done.
1420 	 * Otherwise we need to walk through several log pages.
1421 	 */
1422 	if (data_len > tail) {
1423 		data_len -= tail;
1424 		tail = log->data_size;
1425 		page_off = log->data_off - 1;
1426 
1427 		for (;;) {
1428 			final_log_off = next_page_off(log, final_log_off);
1429 
1430 			/*
1431 			 * We are done if the remaining bytes
1432 			 * fit on this page.
1433 			 */
1434 			if (data_len <= tail)
1435 				break;
1436 			data_len -= tail;
1437 		}
1438 	}
1439 
1440 	/*
1441 	 * We add the remaining bytes to our starting position on this page
1442 	 * and then add that value to the file offset of this log page.
1443 	 */
1444 	return final_log_off + data_len + page_off;
1445 }
1446 
next_log_lsn(struct ntfs_log * log,const struct LFS_RECORD_HDR * rh,u64 * lsn)1447 static int next_log_lsn(struct ntfs_log *log, const struct LFS_RECORD_HDR *rh,
1448 			u64 *lsn)
1449 {
1450 	int err;
1451 	u64 this_lsn = le64_to_cpu(rh->this_lsn);
1452 	u32 vbo = lsn_to_vbo(log, this_lsn);
1453 	u32 end =
1454 		final_log_off(log, this_lsn, le32_to_cpu(rh->client_data_len));
1455 	u32 hdr_off = end & ~log->sys_page_mask;
1456 	u64 seq = this_lsn >> log->file_data_bits;
1457 	struct RECORD_PAGE_HDR *page = NULL;
1458 
1459 	/* Remember if we wrapped. */
1460 	if (end <= vbo)
1461 		seq += 1;
1462 
1463 	/* Log page header for this page. */
1464 	err = read_log_page(log, hdr_off, &page, NULL);
1465 	if (err)
1466 		return err;
1467 
1468 	/*
1469 	 * If the lsn we were given was not the last lsn on this page,
1470 	 * then the starting offset for the next lsn is on a quad word
1471 	 * boundary following the last file offset for the current lsn.
1472 	 * Otherwise the file offset is the start of the data on the next page.
1473 	 */
1474 	if (this_lsn == le64_to_cpu(page->rhdr.lsn)) {
1475 		/* If we wrapped, we need to increment the sequence number. */
1476 		hdr_off = next_page_off(log, hdr_off);
1477 		if (hdr_off == log->first_page)
1478 			seq += 1;
1479 
1480 		vbo = hdr_off + log->data_off;
1481 	} else {
1482 		vbo = ALIGN(end, 8);
1483 	}
1484 
1485 	/* Compute the lsn based on the file offset and the sequence count. */
1486 	*lsn = vbo_to_lsn(log, vbo, seq);
1487 
1488 	/*
1489 	 * If this lsn is within the legal range for the file, we return true.
1490 	 * Otherwise false indicates that there are no more lsn's.
1491 	 */
1492 	if (!is_lsn_in_file(log, *lsn))
1493 		*lsn = 0;
1494 
1495 	kfree(page);
1496 
1497 	return 0;
1498 }
1499 
1500 /*
1501  * current_log_avail - Calculate the number of bytes available for log records.
1502  */
current_log_avail(struct ntfs_log * log)1503 static u32 current_log_avail(struct ntfs_log *log)
1504 {
1505 	u32 oldest_off, next_free_off, free_bytes;
1506 
1507 	if (log->l_flags & NTFSLOG_NO_LAST_LSN) {
1508 		/* The entire file is available. */
1509 		return log->max_current_avail;
1510 	}
1511 
1512 	/*
1513 	 * If there is a last lsn the restart area then we know that we will
1514 	 * have to compute the free range.
1515 	 * If there is no oldest lsn then start at the first page of the file.
1516 	 */
1517 	oldest_off = (log->l_flags & NTFSLOG_NO_OLDEST_LSN)
1518 			     ? log->first_page
1519 			     : (log->oldest_lsn_off & ~log->sys_page_mask);
1520 
1521 	/*
1522 	 * We will use the next log page offset to compute the next free page.
1523 	 * If we are going to reuse this page go to the next page.
1524 	 * If we are at the first page then use the end of the file.
1525 	 */
1526 	next_free_off = (log->l_flags & NTFSLOG_REUSE_TAIL)
1527 				? log->next_page + log->page_size
1528 				: log->next_page == log->first_page
1529 					  ? log->l_size
1530 					  : log->next_page;
1531 
1532 	/* If the two offsets are the same then there is no available space. */
1533 	if (oldest_off == next_free_off)
1534 		return 0;
1535 	/*
1536 	 * If the free offset follows the oldest offset then subtract
1537 	 * this range from the total available pages.
1538 	 */
1539 	free_bytes =
1540 		oldest_off < next_free_off
1541 			? log->total_avail_pages - (next_free_off - oldest_off)
1542 			: oldest_off - next_free_off;
1543 
1544 	free_bytes >>= log->page_bits;
1545 	return free_bytes * log->reserved;
1546 }
1547 
check_subseq_log_page(struct ntfs_log * log,const struct RECORD_PAGE_HDR * rp,u32 vbo,u64 seq)1548 static bool check_subseq_log_page(struct ntfs_log *log,
1549 				  const struct RECORD_PAGE_HDR *rp, u32 vbo,
1550 				  u64 seq)
1551 {
1552 	u64 lsn_seq;
1553 	const struct NTFS_RECORD_HEADER *rhdr = &rp->rhdr;
1554 	u64 lsn = le64_to_cpu(rhdr->lsn);
1555 
1556 	if (rhdr->sign == NTFS_FFFF_SIGNATURE || !rhdr->sign)
1557 		return false;
1558 
1559 	/*
1560 	 * If the last lsn on the page occurs was written after the page
1561 	 * that caused the original error then we have a fatal error.
1562 	 */
1563 	lsn_seq = lsn >> log->file_data_bits;
1564 
1565 	/*
1566 	 * If the sequence number for the lsn the page is equal or greater
1567 	 * than lsn we expect, then this is a subsequent write.
1568 	 */
1569 	return lsn_seq >= seq ||
1570 	       (lsn_seq == seq - 1 && log->first_page == vbo &&
1571 		vbo != (lsn_to_vbo(log, lsn) & ~log->page_mask));
1572 }
1573 
1574 /*
1575  * last_log_lsn
1576  *
1577  * Walks through the log pages for a file, searching for the
1578  * last log page written to the file.
1579  */
last_log_lsn(struct ntfs_log * log)1580 static int last_log_lsn(struct ntfs_log *log)
1581 {
1582 	int err;
1583 	bool usa_error = false;
1584 	bool replace_page = false;
1585 	bool reuse_page = log->l_flags & NTFSLOG_REUSE_TAIL;
1586 	bool wrapped_file, wrapped;
1587 
1588 	u32 page_cnt = 1, page_pos = 1;
1589 	u32 page_off = 0, page_off1 = 0, saved_off = 0;
1590 	u32 final_off, second_off, final_off_prev = 0, second_off_prev = 0;
1591 	u32 first_file_off = 0, second_file_off = 0;
1592 	u32 part_io_count = 0;
1593 	u32 tails = 0;
1594 	u32 this_off, curpage_off, nextpage_off, remain_pages;
1595 
1596 	u64 expected_seq, seq_base = 0, lsn_base = 0;
1597 	u64 best_lsn, best_lsn1, best_lsn2;
1598 	u64 lsn_cur, lsn1, lsn2;
1599 	u64 last_ok_lsn = reuse_page ? log->last_lsn : 0;
1600 
1601 	u16 cur_pos, best_page_pos;
1602 
1603 	struct RECORD_PAGE_HDR *page = NULL;
1604 	struct RECORD_PAGE_HDR *tst_page = NULL;
1605 	struct RECORD_PAGE_HDR *first_tail = NULL;
1606 	struct RECORD_PAGE_HDR *second_tail = NULL;
1607 	struct RECORD_PAGE_HDR *tail_page = NULL;
1608 	struct RECORD_PAGE_HDR *second_tail_prev = NULL;
1609 	struct RECORD_PAGE_HDR *first_tail_prev = NULL;
1610 	struct RECORD_PAGE_HDR *page_bufs = NULL;
1611 	struct RECORD_PAGE_HDR *best_page;
1612 
1613 	if (log->major_ver >= 2) {
1614 		final_off = 0x02 * log->page_size;
1615 		second_off = 0x12 * log->page_size;
1616 
1617 		// 0x10 == 0x12 - 0x2
1618 		page_bufs = kmalloc(log->page_size * 0x10, GFP_NOFS);
1619 		if (!page_bufs)
1620 			return -ENOMEM;
1621 	} else {
1622 		second_off = log->first_page - log->page_size;
1623 		final_off = second_off - log->page_size;
1624 	}
1625 
1626 next_tail:
1627 	/* Read second tail page (at pos 3/0x12000). */
1628 	if (read_log_page(log, second_off, &second_tail, &usa_error) ||
1629 	    usa_error || second_tail->rhdr.sign != NTFS_RCRD_SIGNATURE) {
1630 		kfree(second_tail);
1631 		second_tail = NULL;
1632 		second_file_off = 0;
1633 		lsn2 = 0;
1634 	} else {
1635 		second_file_off = hdr_file_off(log, second_tail);
1636 		lsn2 = le64_to_cpu(second_tail->record_hdr.last_end_lsn);
1637 	}
1638 
1639 	/* Read first tail page (at pos 2/0x2000). */
1640 	if (read_log_page(log, final_off, &first_tail, &usa_error) ||
1641 	    usa_error || first_tail->rhdr.sign != NTFS_RCRD_SIGNATURE) {
1642 		kfree(first_tail);
1643 		first_tail = NULL;
1644 		first_file_off = 0;
1645 		lsn1 = 0;
1646 	} else {
1647 		first_file_off = hdr_file_off(log, first_tail);
1648 		lsn1 = le64_to_cpu(first_tail->record_hdr.last_end_lsn);
1649 	}
1650 
1651 	if (log->major_ver < 2) {
1652 		int best_page;
1653 
1654 		first_tail_prev = first_tail;
1655 		final_off_prev = first_file_off;
1656 		second_tail_prev = second_tail;
1657 		second_off_prev = second_file_off;
1658 		tails = 1;
1659 
1660 		if (!first_tail && !second_tail)
1661 			goto tail_read;
1662 
1663 		if (first_tail && second_tail)
1664 			best_page = lsn1 < lsn2 ? 1 : 0;
1665 		else if (first_tail)
1666 			best_page = 0;
1667 		else
1668 			best_page = 1;
1669 
1670 		page_off = best_page ? second_file_off : first_file_off;
1671 		seq_base = (best_page ? lsn2 : lsn1) >> log->file_data_bits;
1672 		goto tail_read;
1673 	}
1674 
1675 	best_lsn1 = first_tail ? base_lsn(log, first_tail, first_file_off) : 0;
1676 	best_lsn2 =
1677 		second_tail ? base_lsn(log, second_tail, second_file_off) : 0;
1678 
1679 	if (first_tail && second_tail) {
1680 		if (best_lsn1 > best_lsn2) {
1681 			best_lsn = best_lsn1;
1682 			best_page = first_tail;
1683 			this_off = first_file_off;
1684 		} else {
1685 			best_lsn = best_lsn2;
1686 			best_page = second_tail;
1687 			this_off = second_file_off;
1688 		}
1689 	} else if (first_tail) {
1690 		best_lsn = best_lsn1;
1691 		best_page = first_tail;
1692 		this_off = first_file_off;
1693 	} else if (second_tail) {
1694 		best_lsn = best_lsn2;
1695 		best_page = second_tail;
1696 		this_off = second_file_off;
1697 	} else {
1698 		goto tail_read;
1699 	}
1700 
1701 	best_page_pos = le16_to_cpu(best_page->page_pos);
1702 
1703 	if (!tails) {
1704 		if (best_page_pos == page_pos) {
1705 			seq_base = best_lsn >> log->file_data_bits;
1706 			saved_off = page_off = le32_to_cpu(best_page->file_off);
1707 			lsn_base = best_lsn;
1708 
1709 			memmove(page_bufs, best_page, log->page_size);
1710 
1711 			page_cnt = le16_to_cpu(best_page->page_count);
1712 			if (page_cnt > 1)
1713 				page_pos += 1;
1714 
1715 			tails = 1;
1716 		}
1717 	} else if (seq_base == (best_lsn >> log->file_data_bits) &&
1718 		   saved_off + log->page_size == this_off &&
1719 		   lsn_base < best_lsn &&
1720 		   (page_pos != page_cnt || best_page_pos == page_pos ||
1721 		    best_page_pos == 1) &&
1722 		   (page_pos >= page_cnt || best_page_pos == page_pos)) {
1723 		u16 bppc = le16_to_cpu(best_page->page_count);
1724 
1725 		saved_off += log->page_size;
1726 		lsn_base = best_lsn;
1727 
1728 		memmove(Add2Ptr(page_bufs, tails * log->page_size), best_page,
1729 			log->page_size);
1730 
1731 		tails += 1;
1732 
1733 		if (best_page_pos != bppc) {
1734 			page_cnt = bppc;
1735 			page_pos = best_page_pos;
1736 
1737 			if (page_cnt > 1)
1738 				page_pos += 1;
1739 		} else {
1740 			page_pos = page_cnt = 1;
1741 		}
1742 	} else {
1743 		kfree(first_tail);
1744 		kfree(second_tail);
1745 		goto tail_read;
1746 	}
1747 
1748 	kfree(first_tail_prev);
1749 	first_tail_prev = first_tail;
1750 	final_off_prev = first_file_off;
1751 	first_tail = NULL;
1752 
1753 	kfree(second_tail_prev);
1754 	second_tail_prev = second_tail;
1755 	second_off_prev = second_file_off;
1756 	second_tail = NULL;
1757 
1758 	final_off += log->page_size;
1759 	second_off += log->page_size;
1760 
1761 	if (tails < 0x10)
1762 		goto next_tail;
1763 tail_read:
1764 	first_tail = first_tail_prev;
1765 	final_off = final_off_prev;
1766 
1767 	second_tail = second_tail_prev;
1768 	second_off = second_off_prev;
1769 
1770 	page_cnt = page_pos = 1;
1771 
1772 	curpage_off = seq_base == log->seq_num ? min(log->next_page, page_off)
1773 					       : log->next_page;
1774 
1775 	wrapped_file =
1776 		curpage_off == log->first_page &&
1777 		!(log->l_flags & (NTFSLOG_NO_LAST_LSN | NTFSLOG_REUSE_TAIL));
1778 
1779 	expected_seq = wrapped_file ? (log->seq_num + 1) : log->seq_num;
1780 
1781 	nextpage_off = curpage_off;
1782 
1783 next_page:
1784 	tail_page = NULL;
1785 	/* Read the next log page. */
1786 	err = read_log_page(log, curpage_off, &page, &usa_error);
1787 
1788 	/* Compute the next log page offset the file. */
1789 	nextpage_off = next_page_off(log, curpage_off);
1790 	wrapped = nextpage_off == log->first_page;
1791 
1792 	if (tails > 1) {
1793 		struct RECORD_PAGE_HDR *cur_page =
1794 			Add2Ptr(page_bufs, curpage_off - page_off);
1795 
1796 		if (curpage_off == saved_off) {
1797 			tail_page = cur_page;
1798 			goto use_tail_page;
1799 		}
1800 
1801 		if (page_off > curpage_off || curpage_off >= saved_off)
1802 			goto use_tail_page;
1803 
1804 		if (page_off1)
1805 			goto use_cur_page;
1806 
1807 		if (!err && !usa_error &&
1808 		    page->rhdr.sign == NTFS_RCRD_SIGNATURE &&
1809 		    cur_page->rhdr.lsn == page->rhdr.lsn &&
1810 		    cur_page->record_hdr.next_record_off ==
1811 			    page->record_hdr.next_record_off &&
1812 		    ((page_pos == page_cnt &&
1813 		      le16_to_cpu(page->page_pos) == 1) ||
1814 		     (page_pos != page_cnt &&
1815 		      le16_to_cpu(page->page_pos) == page_pos + 1 &&
1816 		      le16_to_cpu(page->page_count) == page_cnt))) {
1817 			cur_page = NULL;
1818 			goto use_tail_page;
1819 		}
1820 
1821 		page_off1 = page_off;
1822 
1823 use_cur_page:
1824 
1825 		lsn_cur = le64_to_cpu(cur_page->rhdr.lsn);
1826 
1827 		if (last_ok_lsn !=
1828 			    le64_to_cpu(cur_page->record_hdr.last_end_lsn) &&
1829 		    ((lsn_cur >> log->file_data_bits) +
1830 		     ((curpage_off <
1831 		       (lsn_to_vbo(log, lsn_cur) & ~log->page_mask))
1832 			      ? 1
1833 			      : 0)) != expected_seq) {
1834 			goto check_tail;
1835 		}
1836 
1837 		if (!is_log_record_end(cur_page)) {
1838 			tail_page = NULL;
1839 			last_ok_lsn = lsn_cur;
1840 			goto next_page_1;
1841 		}
1842 
1843 		log->seq_num = expected_seq;
1844 		log->l_flags &= ~NTFSLOG_NO_LAST_LSN;
1845 		log->last_lsn = le64_to_cpu(cur_page->record_hdr.last_end_lsn);
1846 		log->ra->current_lsn = cur_page->record_hdr.last_end_lsn;
1847 
1848 		if (log->record_header_len <=
1849 		    log->page_size -
1850 			    le16_to_cpu(cur_page->record_hdr.next_record_off)) {
1851 			log->l_flags |= NTFSLOG_REUSE_TAIL;
1852 			log->next_page = curpage_off;
1853 		} else {
1854 			log->l_flags &= ~NTFSLOG_REUSE_TAIL;
1855 			log->next_page = nextpage_off;
1856 		}
1857 
1858 		if (wrapped_file)
1859 			log->l_flags |= NTFSLOG_WRAPPED;
1860 
1861 		last_ok_lsn = le64_to_cpu(cur_page->record_hdr.last_end_lsn);
1862 		goto next_page_1;
1863 	}
1864 
1865 	/*
1866 	 * If we are at the expected first page of a transfer check to see
1867 	 * if either tail copy is at this offset.
1868 	 * If this page is the last page of a transfer, check if we wrote
1869 	 * a subsequent tail copy.
1870 	 */
1871 	if (page_cnt == page_pos || page_cnt == page_pos + 1) {
1872 		/*
1873 		 * Check if the offset matches either the first or second
1874 		 * tail copy. It is possible it will match both.
1875 		 */
1876 		if (curpage_off == final_off)
1877 			tail_page = first_tail;
1878 
1879 		/*
1880 		 * If we already matched on the first page then
1881 		 * check the ending lsn's.
1882 		 */
1883 		if (curpage_off == second_off) {
1884 			if (!tail_page ||
1885 			    (second_tail &&
1886 			     le64_to_cpu(second_tail->record_hdr.last_end_lsn) >
1887 				     le64_to_cpu(first_tail->record_hdr
1888 							 .last_end_lsn))) {
1889 				tail_page = second_tail;
1890 			}
1891 		}
1892 	}
1893 
1894 use_tail_page:
1895 	if (tail_page) {
1896 		/* We have a candidate for a tail copy. */
1897 		lsn_cur = le64_to_cpu(tail_page->record_hdr.last_end_lsn);
1898 
1899 		if (last_ok_lsn < lsn_cur) {
1900 			/*
1901 			 * If the sequence number is not expected,
1902 			 * then don't use the tail copy.
1903 			 */
1904 			if (expected_seq != (lsn_cur >> log->file_data_bits))
1905 				tail_page = NULL;
1906 		} else if (last_ok_lsn > lsn_cur) {
1907 			/*
1908 			 * If the last lsn is greater than the one on
1909 			 * this page then forget this tail.
1910 			 */
1911 			tail_page = NULL;
1912 		}
1913 	}
1914 
1915 	/*
1916 	 *If we have an error on the current page,
1917 	 * we will break of this loop.
1918 	 */
1919 	if (err || usa_error)
1920 		goto check_tail;
1921 
1922 	/*
1923 	 * Done if the last lsn on this page doesn't match the previous known
1924 	 * last lsn or the sequence number is not expected.
1925 	 */
1926 	lsn_cur = le64_to_cpu(page->rhdr.lsn);
1927 	if (last_ok_lsn != lsn_cur &&
1928 	    expected_seq != (lsn_cur >> log->file_data_bits)) {
1929 		goto check_tail;
1930 	}
1931 
1932 	/*
1933 	 * Check that the page position and page count values are correct.
1934 	 * If this is the first page of a transfer the position must be 1
1935 	 * and the count will be unknown.
1936 	 */
1937 	if (page_cnt == page_pos) {
1938 		if (page->page_pos != cpu_to_le16(1) &&
1939 		    (!reuse_page || page->page_pos != page->page_count)) {
1940 			/*
1941 			 * If the current page is the first page we are
1942 			 * looking at and we are reusing this page then
1943 			 * it can be either the first or last page of a
1944 			 * transfer. Otherwise it can only be the first.
1945 			 */
1946 			goto check_tail;
1947 		}
1948 	} else if (le16_to_cpu(page->page_count) != page_cnt ||
1949 		   le16_to_cpu(page->page_pos) != page_pos + 1) {
1950 		/*
1951 		 * The page position better be 1 more than the last page
1952 		 * position and the page count better match.
1953 		 */
1954 		goto check_tail;
1955 	}
1956 
1957 	/*
1958 	 * We have a valid page the file and may have a valid page
1959 	 * the tail copy area.
1960 	 * If the tail page was written after the page the file then
1961 	 * break of the loop.
1962 	 */
1963 	if (tail_page &&
1964 	    le64_to_cpu(tail_page->record_hdr.last_end_lsn) > lsn_cur) {
1965 		/* Remember if we will replace the page. */
1966 		replace_page = true;
1967 		goto check_tail;
1968 	}
1969 
1970 	tail_page = NULL;
1971 
1972 	if (is_log_record_end(page)) {
1973 		/*
1974 		 * Since we have read this page we know the sequence number
1975 		 * is the same as our expected value.
1976 		 */
1977 		log->seq_num = expected_seq;
1978 		log->last_lsn = le64_to_cpu(page->record_hdr.last_end_lsn);
1979 		log->ra->current_lsn = page->record_hdr.last_end_lsn;
1980 		log->l_flags &= ~NTFSLOG_NO_LAST_LSN;
1981 
1982 		/*
1983 		 * If there is room on this page for another header then
1984 		 * remember we want to reuse the page.
1985 		 */
1986 		if (log->record_header_len <=
1987 		    log->page_size -
1988 			    le16_to_cpu(page->record_hdr.next_record_off)) {
1989 			log->l_flags |= NTFSLOG_REUSE_TAIL;
1990 			log->next_page = curpage_off;
1991 		} else {
1992 			log->l_flags &= ~NTFSLOG_REUSE_TAIL;
1993 			log->next_page = nextpage_off;
1994 		}
1995 
1996 		/* Remember if we wrapped the log file. */
1997 		if (wrapped_file)
1998 			log->l_flags |= NTFSLOG_WRAPPED;
1999 	}
2000 
2001 	/*
2002 	 * Remember the last page count and position.
2003 	 * Also remember the last known lsn.
2004 	 */
2005 	page_cnt = le16_to_cpu(page->page_count);
2006 	page_pos = le16_to_cpu(page->page_pos);
2007 	last_ok_lsn = le64_to_cpu(page->rhdr.lsn);
2008 
2009 next_page_1:
2010 
2011 	if (wrapped) {
2012 		expected_seq += 1;
2013 		wrapped_file = 1;
2014 	}
2015 
2016 	curpage_off = nextpage_off;
2017 	kfree(page);
2018 	page = NULL;
2019 	reuse_page = 0;
2020 	goto next_page;
2021 
2022 check_tail:
2023 	if (tail_page) {
2024 		log->seq_num = expected_seq;
2025 		log->last_lsn = le64_to_cpu(tail_page->record_hdr.last_end_lsn);
2026 		log->ra->current_lsn = tail_page->record_hdr.last_end_lsn;
2027 		log->l_flags &= ~NTFSLOG_NO_LAST_LSN;
2028 
2029 		if (log->page_size -
2030 			    le16_to_cpu(
2031 				    tail_page->record_hdr.next_record_off) >=
2032 		    log->record_header_len) {
2033 			log->l_flags |= NTFSLOG_REUSE_TAIL;
2034 			log->next_page = curpage_off;
2035 		} else {
2036 			log->l_flags &= ~NTFSLOG_REUSE_TAIL;
2037 			log->next_page = nextpage_off;
2038 		}
2039 
2040 		if (wrapped)
2041 			log->l_flags |= NTFSLOG_WRAPPED;
2042 	}
2043 
2044 	/* Remember that the partial IO will start at the next page. */
2045 	second_off = nextpage_off;
2046 
2047 	/*
2048 	 * If the next page is the first page of the file then update
2049 	 * the sequence number for log records which begon the next page.
2050 	 */
2051 	if (wrapped)
2052 		expected_seq += 1;
2053 
2054 	/*
2055 	 * If we have a tail copy or are performing single page I/O we can
2056 	 * immediately look at the next page.
2057 	 */
2058 	if (replace_page || (log->ra->flags & RESTART_SINGLE_PAGE_IO)) {
2059 		page_cnt = 2;
2060 		page_pos = 1;
2061 		goto check_valid;
2062 	}
2063 
2064 	if (page_pos != page_cnt)
2065 		goto check_valid;
2066 	/*
2067 	 * If the next page causes us to wrap to the beginning of the log
2068 	 * file then we know which page to check next.
2069 	 */
2070 	if (wrapped) {
2071 		page_cnt = 2;
2072 		page_pos = 1;
2073 		goto check_valid;
2074 	}
2075 
2076 	cur_pos = 2;
2077 
2078 next_test_page:
2079 	kfree(tst_page);
2080 	tst_page = NULL;
2081 
2082 	/* Walk through the file, reading log pages. */
2083 	err = read_log_page(log, nextpage_off, &tst_page, &usa_error);
2084 
2085 	/*
2086 	 * If we get a USA error then assume that we correctly found
2087 	 * the end of the original transfer.
2088 	 */
2089 	if (usa_error)
2090 		goto file_is_valid;
2091 
2092 	/*
2093 	 * If we were able to read the page, we examine it to see if it
2094 	 * is the same or different Io block.
2095 	 */
2096 	if (err)
2097 		goto next_test_page_1;
2098 
2099 	if (le16_to_cpu(tst_page->page_pos) == cur_pos &&
2100 	    check_subseq_log_page(log, tst_page, nextpage_off, expected_seq)) {
2101 		page_cnt = le16_to_cpu(tst_page->page_count) + 1;
2102 		page_pos = le16_to_cpu(tst_page->page_pos);
2103 		goto check_valid;
2104 	} else {
2105 		goto file_is_valid;
2106 	}
2107 
2108 next_test_page_1:
2109 
2110 	nextpage_off = next_page_off(log, curpage_off);
2111 	wrapped = nextpage_off == log->first_page;
2112 
2113 	if (wrapped) {
2114 		expected_seq += 1;
2115 		page_cnt = 2;
2116 		page_pos = 1;
2117 	}
2118 
2119 	cur_pos += 1;
2120 	part_io_count += 1;
2121 	if (!wrapped)
2122 		goto next_test_page;
2123 
2124 check_valid:
2125 	/* Skip over the remaining pages this transfer. */
2126 	remain_pages = page_cnt - page_pos - 1;
2127 	part_io_count += remain_pages;
2128 
2129 	while (remain_pages--) {
2130 		nextpage_off = next_page_off(log, curpage_off);
2131 		wrapped = nextpage_off == log->first_page;
2132 
2133 		if (wrapped)
2134 			expected_seq += 1;
2135 	}
2136 
2137 	/* Call our routine to check this log page. */
2138 	kfree(tst_page);
2139 	tst_page = NULL;
2140 
2141 	err = read_log_page(log, nextpage_off, &tst_page, &usa_error);
2142 	if (!err && !usa_error &&
2143 	    check_subseq_log_page(log, tst_page, nextpage_off, expected_seq)) {
2144 		err = -EINVAL;
2145 		goto out;
2146 	}
2147 
2148 file_is_valid:
2149 
2150 	/* We have a valid file. */
2151 	if (page_off1 || tail_page) {
2152 		struct RECORD_PAGE_HDR *tmp_page;
2153 
2154 		if (sb_rdonly(log->ni->mi.sbi->sb)) {
2155 			err = -EROFS;
2156 			goto out;
2157 		}
2158 
2159 		if (page_off1) {
2160 			tmp_page = Add2Ptr(page_bufs, page_off1 - page_off);
2161 			tails -= (page_off1 - page_off) / log->page_size;
2162 			if (!tail_page)
2163 				tails -= 1;
2164 		} else {
2165 			tmp_page = tail_page;
2166 			tails = 1;
2167 		}
2168 
2169 		while (tails--) {
2170 			u64 off = hdr_file_off(log, tmp_page);
2171 
2172 			if (!page) {
2173 				page = kmalloc(log->page_size, GFP_NOFS);
2174 				if (!page) {
2175 					err = -ENOMEM;
2176 					goto out;
2177 				}
2178 			}
2179 
2180 			/*
2181 			 * Correct page and copy the data from this page
2182 			 * into it and flush it to disk.
2183 			 */
2184 			memcpy(page, tmp_page, log->page_size);
2185 
2186 			/* Fill last flushed lsn value flush the page. */
2187 			if (log->major_ver < 2)
2188 				page->rhdr.lsn = page->record_hdr.last_end_lsn;
2189 			else
2190 				page->file_off = 0;
2191 
2192 			page->page_pos = page->page_count = cpu_to_le16(1);
2193 
2194 			ntfs_fix_pre_write(&page->rhdr, log->page_size);
2195 
2196 			err = ntfs_sb_write_run(log->ni->mi.sbi,
2197 						&log->ni->file.run, off, page,
2198 						log->page_size, 0);
2199 
2200 			if (err)
2201 				goto out;
2202 
2203 			if (part_io_count && second_off == off) {
2204 				second_off += log->page_size;
2205 				part_io_count -= 1;
2206 			}
2207 
2208 			tmp_page = Add2Ptr(tmp_page, log->page_size);
2209 		}
2210 	}
2211 
2212 	if (part_io_count) {
2213 		if (sb_rdonly(log->ni->mi.sbi->sb)) {
2214 			err = -EROFS;
2215 			goto out;
2216 		}
2217 	}
2218 
2219 out:
2220 	kfree(second_tail);
2221 	kfree(first_tail);
2222 	kfree(page);
2223 	kfree(tst_page);
2224 	kfree(page_bufs);
2225 
2226 	return err;
2227 }
2228 
2229 /*
2230  * read_log_rec_buf - Copy a log record from the file to a buffer.
2231  *
2232  * The log record may span several log pages and may even wrap the file.
2233  */
read_log_rec_buf(struct ntfs_log * log,const struct LFS_RECORD_HDR * rh,void * buffer)2234 static int read_log_rec_buf(struct ntfs_log *log,
2235 			    const struct LFS_RECORD_HDR *rh, void *buffer)
2236 {
2237 	int err;
2238 	struct RECORD_PAGE_HDR *ph = NULL;
2239 	u64 lsn = le64_to_cpu(rh->this_lsn);
2240 	u32 vbo = lsn_to_vbo(log, lsn) & ~log->page_mask;
2241 	u32 off = lsn_to_page_off(log, lsn) + log->record_header_len;
2242 	u32 data_len = le32_to_cpu(rh->client_data_len);
2243 
2244 	/*
2245 	 * While there are more bytes to transfer,
2246 	 * we continue to attempt to perform the read.
2247 	 */
2248 	for (;;) {
2249 		bool usa_error;
2250 		u32 tail = log->page_size - off;
2251 
2252 		if (tail >= data_len)
2253 			tail = data_len;
2254 
2255 		data_len -= tail;
2256 
2257 		err = read_log_page(log, vbo, &ph, &usa_error);
2258 		if (err)
2259 			goto out;
2260 
2261 		/*
2262 		 * The last lsn on this page better be greater or equal
2263 		 * to the lsn we are copying.
2264 		 */
2265 		if (lsn > le64_to_cpu(ph->rhdr.lsn)) {
2266 			err = -EINVAL;
2267 			goto out;
2268 		}
2269 
2270 		memcpy(buffer, Add2Ptr(ph, off), tail);
2271 
2272 		/* If there are no more bytes to transfer, we exit the loop. */
2273 		if (!data_len) {
2274 			if (!is_log_record_end(ph) ||
2275 			    lsn > le64_to_cpu(ph->record_hdr.last_end_lsn)) {
2276 				err = -EINVAL;
2277 				goto out;
2278 			}
2279 			break;
2280 		}
2281 
2282 		if (ph->rhdr.lsn == ph->record_hdr.last_end_lsn ||
2283 		    lsn > le64_to_cpu(ph->rhdr.lsn)) {
2284 			err = -EINVAL;
2285 			goto out;
2286 		}
2287 
2288 		vbo = next_page_off(log, vbo);
2289 		off = log->data_off;
2290 
2291 		/*
2292 		 * Adjust our pointer the user's buffer to transfer
2293 		 * the next block to.
2294 		 */
2295 		buffer = Add2Ptr(buffer, tail);
2296 	}
2297 
2298 out:
2299 	kfree(ph);
2300 	return err;
2301 }
2302 
read_rst_area(struct ntfs_log * log,struct NTFS_RESTART ** rst_,u64 * lsn)2303 static int read_rst_area(struct ntfs_log *log, struct NTFS_RESTART **rst_,
2304 			 u64 *lsn)
2305 {
2306 	int err;
2307 	struct LFS_RECORD_HDR *rh = NULL;
2308 	const struct CLIENT_REC *cr =
2309 		Add2Ptr(log->ra, le16_to_cpu(log->ra->client_off));
2310 	u64 lsnr, lsnc = le64_to_cpu(cr->restart_lsn);
2311 	u32 len;
2312 	struct NTFS_RESTART *rst;
2313 
2314 	*lsn = 0;
2315 	*rst_ = NULL;
2316 
2317 	/* If the client doesn't have a restart area, go ahead and exit now. */
2318 	if (!lsnc)
2319 		return 0;
2320 
2321 	err = read_log_page(log, lsn_to_vbo(log, lsnc),
2322 			    (struct RECORD_PAGE_HDR **)&rh, NULL);
2323 	if (err)
2324 		return err;
2325 
2326 	rst = NULL;
2327 	lsnr = le64_to_cpu(rh->this_lsn);
2328 
2329 	if (lsnc != lsnr) {
2330 		/* If the lsn values don't match, then the disk is corrupt. */
2331 		err = -EINVAL;
2332 		goto out;
2333 	}
2334 
2335 	*lsn = lsnr;
2336 	len = le32_to_cpu(rh->client_data_len);
2337 
2338 	if (!len) {
2339 		err = 0;
2340 		goto out;
2341 	}
2342 
2343 	if (len < sizeof(struct NTFS_RESTART)) {
2344 		err = -EINVAL;
2345 		goto out;
2346 	}
2347 
2348 	rst = kmalloc(len, GFP_NOFS);
2349 	if (!rst) {
2350 		err = -ENOMEM;
2351 		goto out;
2352 	}
2353 
2354 	/* Copy the data into the 'rst' buffer. */
2355 	err = read_log_rec_buf(log, rh, rst);
2356 	if (err)
2357 		goto out;
2358 
2359 	*rst_ = rst;
2360 	rst = NULL;
2361 
2362 out:
2363 	kfree(rh);
2364 	kfree(rst);
2365 
2366 	return err;
2367 }
2368 
find_log_rec(struct ntfs_log * log,u64 lsn,struct lcb * lcb)2369 static int find_log_rec(struct ntfs_log *log, u64 lsn, struct lcb *lcb)
2370 {
2371 	int err;
2372 	struct LFS_RECORD_HDR *rh = lcb->lrh;
2373 	u32 rec_len, len;
2374 
2375 	/* Read the record header for this lsn. */
2376 	if (!rh) {
2377 		err = read_log_page(log, lsn_to_vbo(log, lsn),
2378 				    (struct RECORD_PAGE_HDR **)&rh, NULL);
2379 
2380 		lcb->lrh = rh;
2381 		if (err)
2382 			return err;
2383 	}
2384 
2385 	/*
2386 	 * If the lsn the log record doesn't match the desired
2387 	 * lsn then the disk is corrupt.
2388 	 */
2389 	if (lsn != le64_to_cpu(rh->this_lsn))
2390 		return -EINVAL;
2391 
2392 	len = le32_to_cpu(rh->client_data_len);
2393 
2394 	/*
2395 	 * Check that the length field isn't greater than the total
2396 	 * available space the log file.
2397 	 */
2398 	rec_len = len + log->record_header_len;
2399 	if (rec_len >= log->total_avail)
2400 		return -EINVAL;
2401 
2402 	/*
2403 	 * If the entire log record is on this log page,
2404 	 * put a pointer to the log record the context block.
2405 	 */
2406 	if (rh->flags & LOG_RECORD_MULTI_PAGE) {
2407 		void *lr = kmalloc(len, GFP_NOFS);
2408 
2409 		if (!lr)
2410 			return -ENOMEM;
2411 
2412 		lcb->log_rec = lr;
2413 		lcb->alloc = true;
2414 
2415 		/* Copy the data into the buffer returned. */
2416 		err = read_log_rec_buf(log, rh, lr);
2417 		if (err)
2418 			return err;
2419 	} else {
2420 		/* If beyond the end of the current page -> an error. */
2421 		u32 page_off = lsn_to_page_off(log, lsn);
2422 
2423 		if (page_off + len + log->record_header_len > log->page_size)
2424 			return -EINVAL;
2425 
2426 		lcb->log_rec = Add2Ptr(rh, sizeof(struct LFS_RECORD_HDR));
2427 		lcb->alloc = false;
2428 	}
2429 
2430 	return 0;
2431 }
2432 
2433 /*
2434  * read_log_rec_lcb - Init the query operation.
2435  */
read_log_rec_lcb(struct ntfs_log * log,u64 lsn,u32 ctx_mode,struct lcb ** lcb_)2436 static int read_log_rec_lcb(struct ntfs_log *log, u64 lsn, u32 ctx_mode,
2437 			    struct lcb **lcb_)
2438 {
2439 	int err;
2440 	const struct CLIENT_REC *cr;
2441 	struct lcb *lcb;
2442 
2443 	switch (ctx_mode) {
2444 	case lcb_ctx_undo_next:
2445 	case lcb_ctx_prev:
2446 	case lcb_ctx_next:
2447 		break;
2448 	default:
2449 		return -EINVAL;
2450 	}
2451 
2452 	/* Check that the given lsn is the legal range for this client. */
2453 	cr = Add2Ptr(log->ra, le16_to_cpu(log->ra->client_off));
2454 
2455 	if (!verify_client_lsn(log, cr, lsn))
2456 		return -EINVAL;
2457 
2458 	lcb = kzalloc(sizeof(struct lcb), GFP_NOFS);
2459 	if (!lcb)
2460 		return -ENOMEM;
2461 	lcb->client = log->client_id;
2462 	lcb->ctx_mode = ctx_mode;
2463 
2464 	/* Find the log record indicated by the given lsn. */
2465 	err = find_log_rec(log, lsn, lcb);
2466 	if (err)
2467 		goto out;
2468 
2469 	*lcb_ = lcb;
2470 	return 0;
2471 
2472 out:
2473 	lcb_put(lcb);
2474 	*lcb_ = NULL;
2475 	return err;
2476 }
2477 
2478 /*
2479  * find_client_next_lsn
2480  *
2481  * Attempt to find the next lsn to return to a client based on the context mode.
2482  */
find_client_next_lsn(struct ntfs_log * log,struct lcb * lcb,u64 * lsn)2483 static int find_client_next_lsn(struct ntfs_log *log, struct lcb *lcb, u64 *lsn)
2484 {
2485 	int err;
2486 	u64 next_lsn;
2487 	struct LFS_RECORD_HDR *hdr;
2488 
2489 	hdr = lcb->lrh;
2490 	*lsn = 0;
2491 
2492 	if (lcb_ctx_next != lcb->ctx_mode)
2493 		goto check_undo_next;
2494 
2495 	/* Loop as long as another lsn can be found. */
2496 	for (;;) {
2497 		u64 current_lsn;
2498 
2499 		err = next_log_lsn(log, hdr, &current_lsn);
2500 		if (err)
2501 			goto out;
2502 
2503 		if (!current_lsn)
2504 			break;
2505 
2506 		if (hdr != lcb->lrh)
2507 			kfree(hdr);
2508 
2509 		hdr = NULL;
2510 		err = read_log_page(log, lsn_to_vbo(log, current_lsn),
2511 				    (struct RECORD_PAGE_HDR **)&hdr, NULL);
2512 		if (err)
2513 			goto out;
2514 
2515 		if (memcmp(&hdr->client, &lcb->client,
2516 			   sizeof(struct CLIENT_ID))) {
2517 			/*err = -EINVAL; */
2518 		} else if (LfsClientRecord == hdr->record_type) {
2519 			kfree(lcb->lrh);
2520 			lcb->lrh = hdr;
2521 			*lsn = current_lsn;
2522 			return 0;
2523 		}
2524 	}
2525 
2526 out:
2527 	if (hdr != lcb->lrh)
2528 		kfree(hdr);
2529 	return err;
2530 
2531 check_undo_next:
2532 	if (lcb_ctx_undo_next == lcb->ctx_mode)
2533 		next_lsn = le64_to_cpu(hdr->client_undo_next_lsn);
2534 	else if (lcb_ctx_prev == lcb->ctx_mode)
2535 		next_lsn = le64_to_cpu(hdr->client_prev_lsn);
2536 	else
2537 		return 0;
2538 
2539 	if (!next_lsn)
2540 		return 0;
2541 
2542 	if (!verify_client_lsn(
2543 		    log, Add2Ptr(log->ra, le16_to_cpu(log->ra->client_off)),
2544 		    next_lsn))
2545 		return 0;
2546 
2547 	hdr = NULL;
2548 	err = read_log_page(log, lsn_to_vbo(log, next_lsn),
2549 			    (struct RECORD_PAGE_HDR **)&hdr, NULL);
2550 	if (err)
2551 		return err;
2552 	kfree(lcb->lrh);
2553 	lcb->lrh = hdr;
2554 
2555 	*lsn = next_lsn;
2556 
2557 	return 0;
2558 }
2559 
read_next_log_rec(struct ntfs_log * log,struct lcb * lcb,u64 * lsn)2560 static int read_next_log_rec(struct ntfs_log *log, struct lcb *lcb, u64 *lsn)
2561 {
2562 	int err;
2563 
2564 	err = find_client_next_lsn(log, lcb, lsn);
2565 	if (err)
2566 		return err;
2567 
2568 	if (!*lsn)
2569 		return 0;
2570 
2571 	if (lcb->alloc)
2572 		kfree(lcb->log_rec);
2573 
2574 	lcb->log_rec = NULL;
2575 	lcb->alloc = false;
2576 	kfree(lcb->lrh);
2577 	lcb->lrh = NULL;
2578 
2579 	return find_log_rec(log, *lsn, lcb);
2580 }
2581 
check_index_header(const struct INDEX_HDR * hdr,size_t bytes)2582 bool check_index_header(const struct INDEX_HDR *hdr, size_t bytes)
2583 {
2584 	__le16 mask;
2585 	u32 min_de, de_off, used, total;
2586 	const struct NTFS_DE *e;
2587 
2588 	if (hdr_has_subnode(hdr)) {
2589 		min_de = sizeof(struct NTFS_DE) + sizeof(u64);
2590 		mask = NTFS_IE_HAS_SUBNODES;
2591 	} else {
2592 		min_de = sizeof(struct NTFS_DE);
2593 		mask = 0;
2594 	}
2595 
2596 	de_off = le32_to_cpu(hdr->de_off);
2597 	used = le32_to_cpu(hdr->used);
2598 	total = le32_to_cpu(hdr->total);
2599 
2600 	if (de_off > bytes - min_de || used > bytes || total > bytes ||
2601 	    de_off + min_de > used || used > total) {
2602 		return false;
2603 	}
2604 
2605 	e = Add2Ptr(hdr, de_off);
2606 	for (;;) {
2607 		u16 esize = le16_to_cpu(e->size);
2608 		struct NTFS_DE *next = Add2Ptr(e, esize);
2609 
2610 		if (esize < min_de || PtrOffset(hdr, next) > used ||
2611 		    (e->flags & NTFS_IE_HAS_SUBNODES) != mask) {
2612 			return false;
2613 		}
2614 
2615 		if (de_is_last(e))
2616 			break;
2617 
2618 		e = next;
2619 	}
2620 
2621 	return true;
2622 }
2623 
check_index_buffer(const struct INDEX_BUFFER * ib,u32 bytes)2624 static inline bool check_index_buffer(const struct INDEX_BUFFER *ib, u32 bytes)
2625 {
2626 	u16 fo;
2627 	const struct NTFS_RECORD_HEADER *r = &ib->rhdr;
2628 
2629 	if (r->sign != NTFS_INDX_SIGNATURE)
2630 		return false;
2631 
2632 	fo = (SECTOR_SIZE - ((bytes >> SECTOR_SHIFT) + 1) * sizeof(short));
2633 
2634 	if (le16_to_cpu(r->fix_off) > fo)
2635 		return false;
2636 
2637 	if ((le16_to_cpu(r->fix_num) - 1) * SECTOR_SIZE != bytes)
2638 		return false;
2639 
2640 	return check_index_header(&ib->ihdr,
2641 				  bytes - offsetof(struct INDEX_BUFFER, ihdr));
2642 }
2643 
check_index_root(const struct ATTRIB * attr,struct ntfs_sb_info * sbi)2644 static inline bool check_index_root(const struct ATTRIB *attr,
2645 				    struct ntfs_sb_info *sbi)
2646 {
2647 	bool ret;
2648 	const struct INDEX_ROOT *root = resident_data(attr);
2649 	u8 index_bits = le32_to_cpu(root->index_block_size) >= sbi->cluster_size
2650 				? sbi->cluster_bits
2651 				: SECTOR_SHIFT;
2652 	u8 block_clst = root->index_block_clst;
2653 
2654 	if (le32_to_cpu(attr->res.data_size) < sizeof(struct INDEX_ROOT) ||
2655 	    (root->type != ATTR_NAME && root->type != ATTR_ZERO) ||
2656 	    (root->type == ATTR_NAME &&
2657 	     root->rule != NTFS_COLLATION_TYPE_FILENAME) ||
2658 	    (le32_to_cpu(root->index_block_size) !=
2659 	     (block_clst << index_bits)) ||
2660 	    (block_clst != 1 && block_clst != 2 && block_clst != 4 &&
2661 	     block_clst != 8 && block_clst != 0x10 && block_clst != 0x20 &&
2662 	     block_clst != 0x40 && block_clst != 0x80)) {
2663 		return false;
2664 	}
2665 
2666 	ret = check_index_header(&root->ihdr,
2667 				 le32_to_cpu(attr->res.data_size) -
2668 					 offsetof(struct INDEX_ROOT, ihdr));
2669 	return ret;
2670 }
2671 
check_attr(const struct MFT_REC * rec,const struct ATTRIB * attr,struct ntfs_sb_info * sbi)2672 static inline bool check_attr(const struct MFT_REC *rec,
2673 			      const struct ATTRIB *attr,
2674 			      struct ntfs_sb_info *sbi)
2675 {
2676 	u32 asize = le32_to_cpu(attr->size);
2677 	u32 rsize = 0;
2678 	u64 dsize, svcn, evcn;
2679 	u16 run_off;
2680 
2681 	/* Check the fixed part of the attribute record header. */
2682 	if (asize >= sbi->record_size ||
2683 	    asize + PtrOffset(rec, attr) >= sbi->record_size ||
2684 	    (attr->name_len &&
2685 	     le16_to_cpu(attr->name_off) + attr->name_len * sizeof(short) >
2686 		     asize)) {
2687 		return false;
2688 	}
2689 
2690 	/* Check the attribute fields. */
2691 	switch (attr->non_res) {
2692 	case 0:
2693 		rsize = le32_to_cpu(attr->res.data_size);
2694 		if (rsize >= asize ||
2695 		    le16_to_cpu(attr->res.data_off) + rsize > asize) {
2696 			return false;
2697 		}
2698 		break;
2699 
2700 	case 1:
2701 		dsize = le64_to_cpu(attr->nres.data_size);
2702 		svcn = le64_to_cpu(attr->nres.svcn);
2703 		evcn = le64_to_cpu(attr->nres.evcn);
2704 		run_off = le16_to_cpu(attr->nres.run_off);
2705 
2706 		if (svcn > evcn + 1 || run_off >= asize ||
2707 		    le64_to_cpu(attr->nres.valid_size) > dsize ||
2708 		    dsize > le64_to_cpu(attr->nres.alloc_size)) {
2709 			return false;
2710 		}
2711 
2712 		if (run_off > asize)
2713 			return false;
2714 
2715 		if (run_unpack(NULL, sbi, 0, svcn, evcn, svcn,
2716 			       Add2Ptr(attr, run_off), asize - run_off) < 0) {
2717 			return false;
2718 		}
2719 
2720 		return true;
2721 
2722 	default:
2723 		return false;
2724 	}
2725 
2726 	switch (attr->type) {
2727 	case ATTR_NAME:
2728 		if (fname_full_size(Add2Ptr(
2729 			    attr, le16_to_cpu(attr->res.data_off))) > asize) {
2730 			return false;
2731 		}
2732 		break;
2733 
2734 	case ATTR_ROOT:
2735 		return check_index_root(attr, sbi);
2736 
2737 	case ATTR_STD:
2738 		if (rsize < sizeof(struct ATTR_STD_INFO5) &&
2739 		    rsize != sizeof(struct ATTR_STD_INFO)) {
2740 			return false;
2741 		}
2742 		break;
2743 
2744 	case ATTR_LIST:
2745 	case ATTR_ID:
2746 	case ATTR_SECURE:
2747 	case ATTR_LABEL:
2748 	case ATTR_VOL_INFO:
2749 	case ATTR_DATA:
2750 	case ATTR_ALLOC:
2751 	case ATTR_BITMAP:
2752 	case ATTR_REPARSE:
2753 	case ATTR_EA_INFO:
2754 	case ATTR_EA:
2755 	case ATTR_PROPERTYSET:
2756 	case ATTR_LOGGED_UTILITY_STREAM:
2757 		break;
2758 
2759 	default:
2760 		return false;
2761 	}
2762 
2763 	return true;
2764 }
2765 
check_file_record(const struct MFT_REC * rec,const struct MFT_REC * rec2,struct ntfs_sb_info * sbi)2766 static inline bool check_file_record(const struct MFT_REC *rec,
2767 				     const struct MFT_REC *rec2,
2768 				     struct ntfs_sb_info *sbi)
2769 {
2770 	const struct ATTRIB *attr;
2771 	u16 fo = le16_to_cpu(rec->rhdr.fix_off);
2772 	u16 fn = le16_to_cpu(rec->rhdr.fix_num);
2773 	u16 ao = le16_to_cpu(rec->attr_off);
2774 	u32 rs = sbi->record_size;
2775 
2776 	/* Check the file record header for consistency. */
2777 	if (rec->rhdr.sign != NTFS_FILE_SIGNATURE ||
2778 	    fo > (SECTOR_SIZE - ((rs >> SECTOR_SHIFT) + 1) * sizeof(short)) ||
2779 	    (fn - 1) * SECTOR_SIZE != rs || ao < MFTRECORD_FIXUP_OFFSET_1 ||
2780 	    ao > sbi->record_size - SIZEOF_RESIDENT || !is_rec_inuse(rec) ||
2781 	    le32_to_cpu(rec->total) != rs) {
2782 		return false;
2783 	}
2784 
2785 	/* Loop to check all of the attributes. */
2786 	for (attr = Add2Ptr(rec, ao); attr->type != ATTR_END;
2787 	     attr = Add2Ptr(attr, le32_to_cpu(attr->size))) {
2788 		if (check_attr(rec, attr, sbi))
2789 			continue;
2790 		return false;
2791 	}
2792 
2793 	return true;
2794 }
2795 
check_lsn(const struct NTFS_RECORD_HEADER * hdr,const u64 * rlsn)2796 static inline int check_lsn(const struct NTFS_RECORD_HEADER *hdr,
2797 			    const u64 *rlsn)
2798 {
2799 	u64 lsn;
2800 
2801 	if (!rlsn)
2802 		return true;
2803 
2804 	lsn = le64_to_cpu(hdr->lsn);
2805 
2806 	if (hdr->sign == NTFS_HOLE_SIGNATURE)
2807 		return false;
2808 
2809 	if (*rlsn > lsn)
2810 		return true;
2811 
2812 	return false;
2813 }
2814 
check_if_attr(const struct MFT_REC * rec,const struct LOG_REC_HDR * lrh)2815 static inline bool check_if_attr(const struct MFT_REC *rec,
2816 				 const struct LOG_REC_HDR *lrh)
2817 {
2818 	u16 ro = le16_to_cpu(lrh->record_off);
2819 	u16 o = le16_to_cpu(rec->attr_off);
2820 	const struct ATTRIB *attr = Add2Ptr(rec, o);
2821 
2822 	while (o < ro) {
2823 		u32 asize;
2824 
2825 		if (attr->type == ATTR_END)
2826 			break;
2827 
2828 		asize = le32_to_cpu(attr->size);
2829 		if (!asize)
2830 			break;
2831 
2832 		o += asize;
2833 		attr = Add2Ptr(attr, asize);
2834 	}
2835 
2836 	return o == ro;
2837 }
2838 
check_if_index_root(const struct MFT_REC * rec,const struct LOG_REC_HDR * lrh)2839 static inline bool check_if_index_root(const struct MFT_REC *rec,
2840 				       const struct LOG_REC_HDR *lrh)
2841 {
2842 	u16 ro = le16_to_cpu(lrh->record_off);
2843 	u16 o = le16_to_cpu(rec->attr_off);
2844 	const struct ATTRIB *attr = Add2Ptr(rec, o);
2845 
2846 	while (o < ro) {
2847 		u32 asize;
2848 
2849 		if (attr->type == ATTR_END)
2850 			break;
2851 
2852 		asize = le32_to_cpu(attr->size);
2853 		if (!asize)
2854 			break;
2855 
2856 		o += asize;
2857 		attr = Add2Ptr(attr, asize);
2858 	}
2859 
2860 	return o == ro && attr->type == ATTR_ROOT;
2861 }
2862 
check_if_root_index(const struct ATTRIB * attr,const struct INDEX_HDR * hdr,const struct LOG_REC_HDR * lrh)2863 static inline bool check_if_root_index(const struct ATTRIB *attr,
2864 				       const struct INDEX_HDR *hdr,
2865 				       const struct LOG_REC_HDR *lrh)
2866 {
2867 	u16 ao = le16_to_cpu(lrh->attr_off);
2868 	u32 de_off = le32_to_cpu(hdr->de_off);
2869 	u32 o = PtrOffset(attr, hdr) + de_off;
2870 	const struct NTFS_DE *e = Add2Ptr(hdr, de_off);
2871 	u32 asize = le32_to_cpu(attr->size);
2872 
2873 	while (o < ao) {
2874 		u16 esize;
2875 
2876 		if (o >= asize)
2877 			break;
2878 
2879 		esize = le16_to_cpu(e->size);
2880 		if (!esize)
2881 			break;
2882 
2883 		o += esize;
2884 		e = Add2Ptr(e, esize);
2885 	}
2886 
2887 	return o == ao;
2888 }
2889 
check_if_alloc_index(const struct INDEX_HDR * hdr,u32 attr_off)2890 static inline bool check_if_alloc_index(const struct INDEX_HDR *hdr,
2891 					u32 attr_off)
2892 {
2893 	u32 de_off = le32_to_cpu(hdr->de_off);
2894 	u32 o = offsetof(struct INDEX_BUFFER, ihdr) + de_off;
2895 	const struct NTFS_DE *e = Add2Ptr(hdr, de_off);
2896 	u32 used = le32_to_cpu(hdr->used);
2897 
2898 	while (o < attr_off) {
2899 		u16 esize;
2900 
2901 		if (de_off >= used)
2902 			break;
2903 
2904 		esize = le16_to_cpu(e->size);
2905 		if (!esize)
2906 			break;
2907 
2908 		o += esize;
2909 		de_off += esize;
2910 		e = Add2Ptr(e, esize);
2911 	}
2912 
2913 	return o == attr_off;
2914 }
2915 
change_attr_size(struct MFT_REC * rec,struct ATTRIB * attr,u32 nsize)2916 static inline void change_attr_size(struct MFT_REC *rec, struct ATTRIB *attr,
2917 				    u32 nsize)
2918 {
2919 	u32 asize = le32_to_cpu(attr->size);
2920 	int dsize = nsize - asize;
2921 	u8 *next = Add2Ptr(attr, asize);
2922 	u32 used = le32_to_cpu(rec->used);
2923 
2924 	memmove(Add2Ptr(attr, nsize), next, used - PtrOffset(rec, next));
2925 
2926 	rec->used = cpu_to_le32(used + dsize);
2927 	attr->size = cpu_to_le32(nsize);
2928 }
2929 
2930 struct OpenAttr {
2931 	struct ATTRIB *attr;
2932 	struct runs_tree *run1;
2933 	struct runs_tree run0;
2934 	struct ntfs_inode *ni;
2935 	// CLST rno;
2936 };
2937 
2938 /*
2939  * cmp_type_and_name
2940  *
2941  * Return: 0 if 'attr' has the same type and name.
2942  */
cmp_type_and_name(const struct ATTRIB * a1,const struct ATTRIB * a2)2943 static inline int cmp_type_and_name(const struct ATTRIB *a1,
2944 				    const struct ATTRIB *a2)
2945 {
2946 	return a1->type != a2->type || a1->name_len != a2->name_len ||
2947 	       (a1->name_len && memcmp(attr_name(a1), attr_name(a2),
2948 				       a1->name_len * sizeof(short)));
2949 }
2950 
find_loaded_attr(struct ntfs_log * log,const struct ATTRIB * attr,CLST rno)2951 static struct OpenAttr *find_loaded_attr(struct ntfs_log *log,
2952 					 const struct ATTRIB *attr, CLST rno)
2953 {
2954 	struct OPEN_ATTR_ENRTY *oe = NULL;
2955 
2956 	while ((oe = enum_rstbl(log->open_attr_tbl, oe))) {
2957 		struct OpenAttr *op_attr;
2958 
2959 		if (ino_get(&oe->ref) != rno)
2960 			continue;
2961 
2962 		op_attr = (struct OpenAttr *)oe->ptr;
2963 		if (!cmp_type_and_name(op_attr->attr, attr))
2964 			return op_attr;
2965 	}
2966 	return NULL;
2967 }
2968 
attr_create_nonres_log(struct ntfs_sb_info * sbi,enum ATTR_TYPE type,u64 size,const u16 * name,size_t name_len,__le16 flags)2969 static struct ATTRIB *attr_create_nonres_log(struct ntfs_sb_info *sbi,
2970 					     enum ATTR_TYPE type, u64 size,
2971 					     const u16 *name, size_t name_len,
2972 					     __le16 flags)
2973 {
2974 	struct ATTRIB *attr;
2975 	u32 name_size = ALIGN(name_len * sizeof(short), 8);
2976 	bool is_ext = flags & (ATTR_FLAG_COMPRESSED | ATTR_FLAG_SPARSED);
2977 	u32 asize = name_size +
2978 		    (is_ext ? SIZEOF_NONRESIDENT_EX : SIZEOF_NONRESIDENT);
2979 
2980 	attr = kzalloc(asize, GFP_NOFS);
2981 	if (!attr)
2982 		return NULL;
2983 
2984 	attr->type = type;
2985 	attr->size = cpu_to_le32(asize);
2986 	attr->flags = flags;
2987 	attr->non_res = 1;
2988 	attr->name_len = name_len;
2989 
2990 	attr->nres.evcn = cpu_to_le64((u64)bytes_to_cluster(sbi, size) - 1);
2991 	attr->nres.alloc_size = cpu_to_le64(ntfs_up_cluster(sbi, size));
2992 	attr->nres.data_size = cpu_to_le64(size);
2993 	attr->nres.valid_size = attr->nres.data_size;
2994 	if (is_ext) {
2995 		attr->name_off = SIZEOF_NONRESIDENT_EX_LE;
2996 		if (is_attr_compressed(attr))
2997 			attr->nres.c_unit = COMPRESSION_UNIT;
2998 
2999 		attr->nres.run_off =
3000 			cpu_to_le16(SIZEOF_NONRESIDENT_EX + name_size);
3001 		memcpy(Add2Ptr(attr, SIZEOF_NONRESIDENT_EX), name,
3002 		       name_len * sizeof(short));
3003 	} else {
3004 		attr->name_off = SIZEOF_NONRESIDENT_LE;
3005 		attr->nres.run_off =
3006 			cpu_to_le16(SIZEOF_NONRESIDENT + name_size);
3007 		memcpy(Add2Ptr(attr, SIZEOF_NONRESIDENT), name,
3008 		       name_len * sizeof(short));
3009 	}
3010 
3011 	return attr;
3012 }
3013 
3014 /*
3015  * do_action - Common routine for the Redo and Undo Passes.
3016  * @rlsn: If it is NULL then undo.
3017  */
do_action(struct ntfs_log * log,struct OPEN_ATTR_ENRTY * oe,const struct LOG_REC_HDR * lrh,u32 op,void * data,u32 dlen,u32 rec_len,const u64 * rlsn)3018 static int do_action(struct ntfs_log *log, struct OPEN_ATTR_ENRTY *oe,
3019 		     const struct LOG_REC_HDR *lrh, u32 op, void *data,
3020 		     u32 dlen, u32 rec_len, const u64 *rlsn)
3021 {
3022 	int err = 0;
3023 	struct ntfs_sb_info *sbi = log->ni->mi.sbi;
3024 	struct inode *inode = NULL, *inode_parent;
3025 	struct mft_inode *mi = NULL, *mi2_child = NULL;
3026 	CLST rno = 0, rno_base = 0;
3027 	struct INDEX_BUFFER *ib = NULL;
3028 	struct MFT_REC *rec = NULL;
3029 	struct ATTRIB *attr = NULL, *attr2;
3030 	struct INDEX_HDR *hdr;
3031 	struct INDEX_ROOT *root;
3032 	struct NTFS_DE *e, *e1, *e2;
3033 	struct NEW_ATTRIBUTE_SIZES *new_sz;
3034 	struct ATTR_FILE_NAME *fname;
3035 	struct OpenAttr *oa, *oa2;
3036 	u32 nsize, t32, asize, used, esize, bmp_off, bmp_bits;
3037 	u16 id, id2;
3038 	u32 record_size = sbi->record_size;
3039 	u64 t64;
3040 	u16 roff = le16_to_cpu(lrh->record_off);
3041 	u16 aoff = le16_to_cpu(lrh->attr_off);
3042 	u64 lco = 0;
3043 	u64 cbo = (u64)le16_to_cpu(lrh->cluster_off) << SECTOR_SHIFT;
3044 	u64 tvo = le64_to_cpu(lrh->target_vcn) << sbi->cluster_bits;
3045 	u64 vbo = cbo + tvo;
3046 	void *buffer_le = NULL;
3047 	u32 bytes = 0;
3048 	bool a_dirty = false;
3049 	u16 data_off;
3050 
3051 	oa = oe->ptr;
3052 
3053 	/* Big switch to prepare. */
3054 	switch (op) {
3055 	/* ============================================================
3056 	 * Process MFT records, as described by the current log record.
3057 	 * ============================================================
3058 	 */
3059 	case InitializeFileRecordSegment:
3060 	case DeallocateFileRecordSegment:
3061 	case WriteEndOfFileRecordSegment:
3062 	case CreateAttribute:
3063 	case DeleteAttribute:
3064 	case UpdateResidentValue:
3065 	case UpdateMappingPairs:
3066 	case SetNewAttributeSizes:
3067 	case AddIndexEntryRoot:
3068 	case DeleteIndexEntryRoot:
3069 	case SetIndexEntryVcnRoot:
3070 	case UpdateFileNameRoot:
3071 	case UpdateRecordDataRoot:
3072 	case ZeroEndOfFileRecord:
3073 		rno = vbo >> sbi->record_bits;
3074 		inode = ilookup(sbi->sb, rno);
3075 		if (inode) {
3076 			mi = &ntfs_i(inode)->mi;
3077 		} else if (op == InitializeFileRecordSegment) {
3078 			mi = kzalloc(sizeof(struct mft_inode), GFP_NOFS);
3079 			if (!mi)
3080 				return -ENOMEM;
3081 			err = mi_format_new(mi, sbi, rno, 0, false);
3082 			if (err)
3083 				goto out;
3084 		} else {
3085 			/* Read from disk. */
3086 			err = mi_get(sbi, rno, &mi);
3087 			if (err)
3088 				return err;
3089 		}
3090 		rec = mi->mrec;
3091 
3092 		if (op == DeallocateFileRecordSegment)
3093 			goto skip_load_parent;
3094 
3095 		if (InitializeFileRecordSegment != op) {
3096 			if (rec->rhdr.sign == NTFS_BAAD_SIGNATURE)
3097 				goto dirty_vol;
3098 			if (!check_lsn(&rec->rhdr, rlsn))
3099 				goto out;
3100 			if (!check_file_record(rec, NULL, sbi))
3101 				goto dirty_vol;
3102 			attr = Add2Ptr(rec, roff);
3103 		}
3104 
3105 		if (is_rec_base(rec) || InitializeFileRecordSegment == op) {
3106 			rno_base = rno;
3107 			goto skip_load_parent;
3108 		}
3109 
3110 		rno_base = ino_get(&rec->parent_ref);
3111 		inode_parent = ntfs_iget5(sbi->sb, &rec->parent_ref, NULL);
3112 		if (IS_ERR(inode_parent))
3113 			goto skip_load_parent;
3114 
3115 		if (is_bad_inode(inode_parent)) {
3116 			iput(inode_parent);
3117 			goto skip_load_parent;
3118 		}
3119 
3120 		if (ni_load_mi_ex(ntfs_i(inode_parent), rno, &mi2_child)) {
3121 			iput(inode_parent);
3122 		} else {
3123 			if (mi2_child->mrec != mi->mrec)
3124 				memcpy(mi2_child->mrec, mi->mrec,
3125 				       sbi->record_size);
3126 
3127 			if (inode)
3128 				iput(inode);
3129 			else if (mi)
3130 				mi_put(mi);
3131 
3132 			inode = inode_parent;
3133 			mi = mi2_child;
3134 			rec = mi2_child->mrec;
3135 			attr = Add2Ptr(rec, roff);
3136 		}
3137 
3138 skip_load_parent:
3139 		inode_parent = NULL;
3140 		break;
3141 
3142 	/*
3143 	 * Process attributes, as described by the current log record.
3144 	 */
3145 	case UpdateNonresidentValue:
3146 	case AddIndexEntryAllocation:
3147 	case DeleteIndexEntryAllocation:
3148 	case WriteEndOfIndexBuffer:
3149 	case SetIndexEntryVcnAllocation:
3150 	case UpdateFileNameAllocation:
3151 	case SetBitsInNonresidentBitMap:
3152 	case ClearBitsInNonresidentBitMap:
3153 	case UpdateRecordDataAllocation:
3154 		attr = oa->attr;
3155 		bytes = UpdateNonresidentValue == op ? dlen : 0;
3156 		lco = (u64)le16_to_cpu(lrh->lcns_follow) << sbi->cluster_bits;
3157 
3158 		if (attr->type == ATTR_ALLOC) {
3159 			t32 = le32_to_cpu(oe->bytes_per_index);
3160 			if (bytes < t32)
3161 				bytes = t32;
3162 		}
3163 
3164 		if (!bytes)
3165 			bytes = lco - cbo;
3166 
3167 		bytes += roff;
3168 		if (attr->type == ATTR_ALLOC)
3169 			bytes = (bytes + 511) & ~511; // align
3170 
3171 		buffer_le = kmalloc(bytes, GFP_NOFS);
3172 		if (!buffer_le)
3173 			return -ENOMEM;
3174 
3175 		err = ntfs_read_run_nb(sbi, oa->run1, vbo, buffer_le, bytes,
3176 				       NULL);
3177 		if (err)
3178 			goto out;
3179 
3180 		if (attr->type == ATTR_ALLOC && *(int *)buffer_le)
3181 			ntfs_fix_post_read(buffer_le, bytes, false);
3182 		break;
3183 
3184 	default:
3185 		WARN_ON(1);
3186 	}
3187 
3188 	/* Big switch to do operation. */
3189 	switch (op) {
3190 	case InitializeFileRecordSegment:
3191 		if (roff + dlen > record_size)
3192 			goto dirty_vol;
3193 
3194 		memcpy(Add2Ptr(rec, roff), data, dlen);
3195 		mi->dirty = true;
3196 		break;
3197 
3198 	case DeallocateFileRecordSegment:
3199 		clear_rec_inuse(rec);
3200 		le16_add_cpu(&rec->seq, 1);
3201 		mi->dirty = true;
3202 		break;
3203 
3204 	case WriteEndOfFileRecordSegment:
3205 		attr2 = (struct ATTRIB *)data;
3206 		if (!check_if_attr(rec, lrh) || roff + dlen > record_size)
3207 			goto dirty_vol;
3208 
3209 		memmove(attr, attr2, dlen);
3210 		rec->used = cpu_to_le32(ALIGN(roff + dlen, 8));
3211 
3212 		mi->dirty = true;
3213 		break;
3214 
3215 	case CreateAttribute:
3216 		attr2 = (struct ATTRIB *)data;
3217 		asize = le32_to_cpu(attr2->size);
3218 		used = le32_to_cpu(rec->used);
3219 
3220 		if (!check_if_attr(rec, lrh) || dlen < SIZEOF_RESIDENT ||
3221 		    !IS_ALIGNED(asize, 8) ||
3222 		    Add2Ptr(attr2, asize) > Add2Ptr(lrh, rec_len) ||
3223 		    dlen > record_size - used) {
3224 			goto dirty_vol;
3225 		}
3226 
3227 		memmove(Add2Ptr(attr, asize), attr, used - roff);
3228 		memcpy(attr, attr2, asize);
3229 
3230 		rec->used = cpu_to_le32(used + asize);
3231 		id = le16_to_cpu(rec->next_attr_id);
3232 		id2 = le16_to_cpu(attr2->id);
3233 		if (id <= id2)
3234 			rec->next_attr_id = cpu_to_le16(id2 + 1);
3235 		if (is_attr_indexed(attr))
3236 			le16_add_cpu(&rec->hard_links, 1);
3237 
3238 		oa2 = find_loaded_attr(log, attr, rno_base);
3239 		if (oa2) {
3240 			void *p2 = kmemdup(attr, le32_to_cpu(attr->size),
3241 					   GFP_NOFS);
3242 			if (p2) {
3243 				// run_close(oa2->run1);
3244 				kfree(oa2->attr);
3245 				oa2->attr = p2;
3246 			}
3247 		}
3248 
3249 		mi->dirty = true;
3250 		break;
3251 
3252 	case DeleteAttribute:
3253 		asize = le32_to_cpu(attr->size);
3254 		used = le32_to_cpu(rec->used);
3255 
3256 		if (!check_if_attr(rec, lrh))
3257 			goto dirty_vol;
3258 
3259 		rec->used = cpu_to_le32(used - asize);
3260 		if (is_attr_indexed(attr))
3261 			le16_add_cpu(&rec->hard_links, -1);
3262 
3263 		memmove(attr, Add2Ptr(attr, asize), used - asize - roff);
3264 
3265 		mi->dirty = true;
3266 		break;
3267 
3268 	case UpdateResidentValue:
3269 		nsize = aoff + dlen;
3270 
3271 		if (!check_if_attr(rec, lrh))
3272 			goto dirty_vol;
3273 
3274 		asize = le32_to_cpu(attr->size);
3275 		used = le32_to_cpu(rec->used);
3276 
3277 		if (lrh->redo_len == lrh->undo_len) {
3278 			if (nsize > asize)
3279 				goto dirty_vol;
3280 			goto move_data;
3281 		}
3282 
3283 		if (nsize > asize && nsize - asize > record_size - used)
3284 			goto dirty_vol;
3285 
3286 		nsize = ALIGN(nsize, 8);
3287 		data_off = le16_to_cpu(attr->res.data_off);
3288 
3289 		if (nsize < asize) {
3290 			memmove(Add2Ptr(attr, aoff), data, dlen);
3291 			data = NULL; // To skip below memmove().
3292 		}
3293 
3294 		memmove(Add2Ptr(attr, nsize), Add2Ptr(attr, asize),
3295 			used - le16_to_cpu(lrh->record_off) - asize);
3296 
3297 		rec->used = cpu_to_le32(used + nsize - asize);
3298 		attr->size = cpu_to_le32(nsize);
3299 		attr->res.data_size = cpu_to_le32(aoff + dlen - data_off);
3300 
3301 move_data:
3302 		if (data)
3303 			memmove(Add2Ptr(attr, aoff), data, dlen);
3304 
3305 		oa2 = find_loaded_attr(log, attr, rno_base);
3306 		if (oa2) {
3307 			void *p2 = kmemdup(attr, le32_to_cpu(attr->size),
3308 					   GFP_NOFS);
3309 			if (p2) {
3310 				// run_close(&oa2->run0);
3311 				oa2->run1 = &oa2->run0;
3312 				kfree(oa2->attr);
3313 				oa2->attr = p2;
3314 			}
3315 		}
3316 
3317 		mi->dirty = true;
3318 		break;
3319 
3320 	case UpdateMappingPairs:
3321 		nsize = aoff + dlen;
3322 		asize = le32_to_cpu(attr->size);
3323 		used = le32_to_cpu(rec->used);
3324 
3325 		if (!check_if_attr(rec, lrh) || !attr->non_res ||
3326 		    aoff < le16_to_cpu(attr->nres.run_off) || aoff > asize ||
3327 		    (nsize > asize && nsize - asize > record_size - used)) {
3328 			goto dirty_vol;
3329 		}
3330 
3331 		nsize = ALIGN(nsize, 8);
3332 
3333 		memmove(Add2Ptr(attr, nsize), Add2Ptr(attr, asize),
3334 			used - le16_to_cpu(lrh->record_off) - asize);
3335 		rec->used = cpu_to_le32(used + nsize - asize);
3336 		attr->size = cpu_to_le32(nsize);
3337 		memmove(Add2Ptr(attr, aoff), data, dlen);
3338 
3339 		if (run_get_highest_vcn(le64_to_cpu(attr->nres.svcn),
3340 					attr_run(attr), &t64)) {
3341 			goto dirty_vol;
3342 		}
3343 
3344 		attr->nres.evcn = cpu_to_le64(t64);
3345 		oa2 = find_loaded_attr(log, attr, rno_base);
3346 		if (oa2 && oa2->attr->non_res)
3347 			oa2->attr->nres.evcn = attr->nres.evcn;
3348 
3349 		mi->dirty = true;
3350 		break;
3351 
3352 	case SetNewAttributeSizes:
3353 		new_sz = data;
3354 		if (!check_if_attr(rec, lrh) || !attr->non_res)
3355 			goto dirty_vol;
3356 
3357 		attr->nres.alloc_size = new_sz->alloc_size;
3358 		attr->nres.data_size = new_sz->data_size;
3359 		attr->nres.valid_size = new_sz->valid_size;
3360 
3361 		if (dlen >= sizeof(struct NEW_ATTRIBUTE_SIZES))
3362 			attr->nres.total_size = new_sz->total_size;
3363 
3364 		oa2 = find_loaded_attr(log, attr, rno_base);
3365 		if (oa2) {
3366 			void *p2 = kmemdup(attr, le32_to_cpu(attr->size),
3367 					   GFP_NOFS);
3368 			if (p2) {
3369 				kfree(oa2->attr);
3370 				oa2->attr = p2;
3371 			}
3372 		}
3373 		mi->dirty = true;
3374 		break;
3375 
3376 	case AddIndexEntryRoot:
3377 		e = (struct NTFS_DE *)data;
3378 		esize = le16_to_cpu(e->size);
3379 		root = resident_data(attr);
3380 		hdr = &root->ihdr;
3381 		used = le32_to_cpu(hdr->used);
3382 
3383 		if (!check_if_index_root(rec, lrh) ||
3384 		    !check_if_root_index(attr, hdr, lrh) ||
3385 		    Add2Ptr(data, esize) > Add2Ptr(lrh, rec_len) ||
3386 		    esize > le32_to_cpu(rec->total) - le32_to_cpu(rec->used)) {
3387 			goto dirty_vol;
3388 		}
3389 
3390 		e1 = Add2Ptr(attr, le16_to_cpu(lrh->attr_off));
3391 
3392 		change_attr_size(rec, attr, le32_to_cpu(attr->size) + esize);
3393 
3394 		memmove(Add2Ptr(e1, esize), e1,
3395 			PtrOffset(e1, Add2Ptr(hdr, used)));
3396 		memmove(e1, e, esize);
3397 
3398 		le32_add_cpu(&attr->res.data_size, esize);
3399 		hdr->used = cpu_to_le32(used + esize);
3400 		le32_add_cpu(&hdr->total, esize);
3401 
3402 		mi->dirty = true;
3403 		break;
3404 
3405 	case DeleteIndexEntryRoot:
3406 		root = resident_data(attr);
3407 		hdr = &root->ihdr;
3408 		used = le32_to_cpu(hdr->used);
3409 
3410 		if (!check_if_index_root(rec, lrh) ||
3411 		    !check_if_root_index(attr, hdr, lrh)) {
3412 			goto dirty_vol;
3413 		}
3414 
3415 		e1 = Add2Ptr(attr, le16_to_cpu(lrh->attr_off));
3416 		esize = le16_to_cpu(e1->size);
3417 		e2 = Add2Ptr(e1, esize);
3418 
3419 		memmove(e1, e2, PtrOffset(e2, Add2Ptr(hdr, used)));
3420 
3421 		le32_sub_cpu(&attr->res.data_size, esize);
3422 		hdr->used = cpu_to_le32(used - esize);
3423 		le32_sub_cpu(&hdr->total, esize);
3424 
3425 		change_attr_size(rec, attr, le32_to_cpu(attr->size) - esize);
3426 
3427 		mi->dirty = true;
3428 		break;
3429 
3430 	case SetIndexEntryVcnRoot:
3431 		root = resident_data(attr);
3432 		hdr = &root->ihdr;
3433 
3434 		if (!check_if_index_root(rec, lrh) ||
3435 		    !check_if_root_index(attr, hdr, lrh)) {
3436 			goto dirty_vol;
3437 		}
3438 
3439 		e = Add2Ptr(attr, le16_to_cpu(lrh->attr_off));
3440 
3441 		de_set_vbn_le(e, *(__le64 *)data);
3442 		mi->dirty = true;
3443 		break;
3444 
3445 	case UpdateFileNameRoot:
3446 		root = resident_data(attr);
3447 		hdr = &root->ihdr;
3448 
3449 		if (!check_if_index_root(rec, lrh) ||
3450 		    !check_if_root_index(attr, hdr, lrh)) {
3451 			goto dirty_vol;
3452 		}
3453 
3454 		e = Add2Ptr(attr, le16_to_cpu(lrh->attr_off));
3455 		fname = (struct ATTR_FILE_NAME *)(e + 1);
3456 		memmove(&fname->dup, data, sizeof(fname->dup)); //
3457 		mi->dirty = true;
3458 		break;
3459 
3460 	case UpdateRecordDataRoot:
3461 		root = resident_data(attr);
3462 		hdr = &root->ihdr;
3463 
3464 		if (!check_if_index_root(rec, lrh) ||
3465 		    !check_if_root_index(attr, hdr, lrh)) {
3466 			goto dirty_vol;
3467 		}
3468 
3469 		e = Add2Ptr(attr, le16_to_cpu(lrh->attr_off));
3470 
3471 		memmove(Add2Ptr(e, le16_to_cpu(e->view.data_off)), data, dlen);
3472 
3473 		mi->dirty = true;
3474 		break;
3475 
3476 	case ZeroEndOfFileRecord:
3477 		if (roff + dlen > record_size)
3478 			goto dirty_vol;
3479 
3480 		memset(attr, 0, dlen);
3481 		mi->dirty = true;
3482 		break;
3483 
3484 	case UpdateNonresidentValue:
3485 		if (lco < cbo + roff + dlen)
3486 			goto dirty_vol;
3487 
3488 		memcpy(Add2Ptr(buffer_le, roff), data, dlen);
3489 
3490 		a_dirty = true;
3491 		if (attr->type == ATTR_ALLOC)
3492 			ntfs_fix_pre_write(buffer_le, bytes);
3493 		break;
3494 
3495 	case AddIndexEntryAllocation:
3496 		ib = Add2Ptr(buffer_le, roff);
3497 		hdr = &ib->ihdr;
3498 		e = data;
3499 		esize = le16_to_cpu(e->size);
3500 		e1 = Add2Ptr(ib, aoff);
3501 
3502 		if (is_baad(&ib->rhdr))
3503 			goto dirty_vol;
3504 		if (!check_lsn(&ib->rhdr, rlsn))
3505 			goto out;
3506 
3507 		used = le32_to_cpu(hdr->used);
3508 
3509 		if (!check_index_buffer(ib, bytes) ||
3510 		    !check_if_alloc_index(hdr, aoff) ||
3511 		    Add2Ptr(e, esize) > Add2Ptr(lrh, rec_len) ||
3512 		    used + esize > le32_to_cpu(hdr->total)) {
3513 			goto dirty_vol;
3514 		}
3515 
3516 		memmove(Add2Ptr(e1, esize), e1,
3517 			PtrOffset(e1, Add2Ptr(hdr, used)));
3518 		memcpy(e1, e, esize);
3519 
3520 		hdr->used = cpu_to_le32(used + esize);
3521 
3522 		a_dirty = true;
3523 
3524 		ntfs_fix_pre_write(&ib->rhdr, bytes);
3525 		break;
3526 
3527 	case DeleteIndexEntryAllocation:
3528 		ib = Add2Ptr(buffer_le, roff);
3529 		hdr = &ib->ihdr;
3530 		e = Add2Ptr(ib, aoff);
3531 		esize = le16_to_cpu(e->size);
3532 
3533 		if (is_baad(&ib->rhdr))
3534 			goto dirty_vol;
3535 		if (!check_lsn(&ib->rhdr, rlsn))
3536 			goto out;
3537 
3538 		if (!check_index_buffer(ib, bytes) ||
3539 		    !check_if_alloc_index(hdr, aoff)) {
3540 			goto dirty_vol;
3541 		}
3542 
3543 		e1 = Add2Ptr(e, esize);
3544 		nsize = esize;
3545 		used = le32_to_cpu(hdr->used);
3546 
3547 		memmove(e, e1, PtrOffset(e1, Add2Ptr(hdr, used)));
3548 
3549 		hdr->used = cpu_to_le32(used - nsize);
3550 
3551 		a_dirty = true;
3552 
3553 		ntfs_fix_pre_write(&ib->rhdr, bytes);
3554 		break;
3555 
3556 	case WriteEndOfIndexBuffer:
3557 		ib = Add2Ptr(buffer_le, roff);
3558 		hdr = &ib->ihdr;
3559 		e = Add2Ptr(ib, aoff);
3560 
3561 		if (is_baad(&ib->rhdr))
3562 			goto dirty_vol;
3563 		if (!check_lsn(&ib->rhdr, rlsn))
3564 			goto out;
3565 		if (!check_index_buffer(ib, bytes) ||
3566 		    !check_if_alloc_index(hdr, aoff) ||
3567 		    aoff + dlen > offsetof(struct INDEX_BUFFER, ihdr) +
3568 					  le32_to_cpu(hdr->total)) {
3569 			goto dirty_vol;
3570 		}
3571 
3572 		hdr->used = cpu_to_le32(dlen + PtrOffset(hdr, e));
3573 		memmove(e, data, dlen);
3574 
3575 		a_dirty = true;
3576 		ntfs_fix_pre_write(&ib->rhdr, bytes);
3577 		break;
3578 
3579 	case SetIndexEntryVcnAllocation:
3580 		ib = Add2Ptr(buffer_le, roff);
3581 		hdr = &ib->ihdr;
3582 		e = Add2Ptr(ib, aoff);
3583 
3584 		if (is_baad(&ib->rhdr))
3585 			goto dirty_vol;
3586 
3587 		if (!check_lsn(&ib->rhdr, rlsn))
3588 			goto out;
3589 		if (!check_index_buffer(ib, bytes) ||
3590 		    !check_if_alloc_index(hdr, aoff)) {
3591 			goto dirty_vol;
3592 		}
3593 
3594 		de_set_vbn_le(e, *(__le64 *)data);
3595 
3596 		a_dirty = true;
3597 		ntfs_fix_pre_write(&ib->rhdr, bytes);
3598 		break;
3599 
3600 	case UpdateFileNameAllocation:
3601 		ib = Add2Ptr(buffer_le, roff);
3602 		hdr = &ib->ihdr;
3603 		e = Add2Ptr(ib, aoff);
3604 
3605 		if (is_baad(&ib->rhdr))
3606 			goto dirty_vol;
3607 
3608 		if (!check_lsn(&ib->rhdr, rlsn))
3609 			goto out;
3610 		if (!check_index_buffer(ib, bytes) ||
3611 		    !check_if_alloc_index(hdr, aoff)) {
3612 			goto dirty_vol;
3613 		}
3614 
3615 		fname = (struct ATTR_FILE_NAME *)(e + 1);
3616 		memmove(&fname->dup, data, sizeof(fname->dup));
3617 
3618 		a_dirty = true;
3619 		ntfs_fix_pre_write(&ib->rhdr, bytes);
3620 		break;
3621 
3622 	case SetBitsInNonresidentBitMap:
3623 		bmp_off =
3624 			le32_to_cpu(((struct BITMAP_RANGE *)data)->bitmap_off);
3625 		bmp_bits = le32_to_cpu(((struct BITMAP_RANGE *)data)->bits);
3626 
3627 		if (cbo + (bmp_off + 7) / 8 > lco ||
3628 		    cbo + ((bmp_off + bmp_bits + 7) / 8) > lco) {
3629 			goto dirty_vol;
3630 		}
3631 
3632 		__bitmap_set(Add2Ptr(buffer_le, roff), bmp_off, bmp_bits);
3633 		a_dirty = true;
3634 		break;
3635 
3636 	case ClearBitsInNonresidentBitMap:
3637 		bmp_off =
3638 			le32_to_cpu(((struct BITMAP_RANGE *)data)->bitmap_off);
3639 		bmp_bits = le32_to_cpu(((struct BITMAP_RANGE *)data)->bits);
3640 
3641 		if (cbo + (bmp_off + 7) / 8 > lco ||
3642 		    cbo + ((bmp_off + bmp_bits + 7) / 8) > lco) {
3643 			goto dirty_vol;
3644 		}
3645 
3646 		__bitmap_clear(Add2Ptr(buffer_le, roff), bmp_off, bmp_bits);
3647 		a_dirty = true;
3648 		break;
3649 
3650 	case UpdateRecordDataAllocation:
3651 		ib = Add2Ptr(buffer_le, roff);
3652 		hdr = &ib->ihdr;
3653 		e = Add2Ptr(ib, aoff);
3654 
3655 		if (is_baad(&ib->rhdr))
3656 			goto dirty_vol;
3657 
3658 		if (!check_lsn(&ib->rhdr, rlsn))
3659 			goto out;
3660 		if (!check_index_buffer(ib, bytes) ||
3661 		    !check_if_alloc_index(hdr, aoff)) {
3662 			goto dirty_vol;
3663 		}
3664 
3665 		memmove(Add2Ptr(e, le16_to_cpu(e->view.data_off)), data, dlen);
3666 
3667 		a_dirty = true;
3668 		ntfs_fix_pre_write(&ib->rhdr, bytes);
3669 		break;
3670 
3671 	default:
3672 		WARN_ON(1);
3673 	}
3674 
3675 	if (rlsn) {
3676 		__le64 t64 = cpu_to_le64(*rlsn);
3677 
3678 		if (rec)
3679 			rec->rhdr.lsn = t64;
3680 		if (ib)
3681 			ib->rhdr.lsn = t64;
3682 	}
3683 
3684 	if (mi && mi->dirty) {
3685 		err = mi_write(mi, 0);
3686 		if (err)
3687 			goto out;
3688 	}
3689 
3690 	if (a_dirty) {
3691 		attr = oa->attr;
3692 		err = ntfs_sb_write_run(sbi, oa->run1, vbo, buffer_le, bytes, 0);
3693 		if (err)
3694 			goto out;
3695 	}
3696 
3697 out:
3698 
3699 	if (inode)
3700 		iput(inode);
3701 	else if (mi != mi2_child)
3702 		mi_put(mi);
3703 
3704 	kfree(buffer_le);
3705 
3706 	return err;
3707 
3708 dirty_vol:
3709 	log->set_dirty = true;
3710 	goto out;
3711 }
3712 
3713 /*
3714  * log_replay - Replays log and empties it.
3715  *
3716  * This function is called during mount operation.
3717  * It replays log and empties it.
3718  * Initialized is set false if logfile contains '-1'.
3719  */
log_replay(struct ntfs_inode * ni,bool * initialized)3720 int log_replay(struct ntfs_inode *ni, bool *initialized)
3721 {
3722 	int err;
3723 	struct ntfs_sb_info *sbi = ni->mi.sbi;
3724 	struct ntfs_log *log;
3725 
3726 	struct restart_info rst_info, rst_info2;
3727 	u64 rec_lsn, ra_lsn, checkpt_lsn = 0, rlsn = 0;
3728 	struct ATTR_NAME_ENTRY *attr_names = NULL;
3729 	struct ATTR_NAME_ENTRY *ane;
3730 	struct RESTART_TABLE *dptbl = NULL;
3731 	struct RESTART_TABLE *trtbl = NULL;
3732 	const struct RESTART_TABLE *rt;
3733 	struct RESTART_TABLE *oatbl = NULL;
3734 	struct inode *inode;
3735 	struct OpenAttr *oa;
3736 	struct ntfs_inode *ni_oe;
3737 	struct ATTRIB *attr = NULL;
3738 	u64 size, vcn, undo_next_lsn;
3739 	CLST rno, lcn, lcn0, len0, clen;
3740 	void *data;
3741 	struct NTFS_RESTART *rst = NULL;
3742 	struct lcb *lcb = NULL;
3743 	struct OPEN_ATTR_ENRTY *oe;
3744 	struct TRANSACTION_ENTRY *tr;
3745 	struct DIR_PAGE_ENTRY *dp;
3746 	u32 i, bytes_per_attr_entry;
3747 	u32 l_size = ni->vfs_inode.i_size;
3748 	u32 orig_file_size = l_size;
3749 	u32 page_size, vbo, tail, off, dlen;
3750 	u32 saved_len, rec_len, transact_id;
3751 	bool use_second_page;
3752 	struct RESTART_AREA *ra2, *ra = NULL;
3753 	struct CLIENT_REC *ca, *cr;
3754 	__le16 client;
3755 	struct RESTART_HDR *rh;
3756 	const struct LFS_RECORD_HDR *frh;
3757 	const struct LOG_REC_HDR *lrh;
3758 	bool is_mapped;
3759 	bool is_ro = sb_rdonly(sbi->sb);
3760 	u64 t64;
3761 	u16 t16;
3762 	u32 t32;
3763 
3764 	/* Get the size of page. NOTE: To replay we can use default page. */
3765 #if PAGE_SIZE >= DefaultLogPageSize && PAGE_SIZE <= DefaultLogPageSize * 2
3766 	page_size = norm_file_page(PAGE_SIZE, &l_size, true);
3767 #else
3768 	page_size = norm_file_page(PAGE_SIZE, &l_size, false);
3769 #endif
3770 	if (!page_size)
3771 		return -EINVAL;
3772 
3773 	log = kzalloc(sizeof(struct ntfs_log), GFP_NOFS);
3774 	if (!log)
3775 		return -ENOMEM;
3776 
3777 	memset(&rst_info, 0, sizeof(struct restart_info));
3778 
3779 	log->ni = ni;
3780 	log->l_size = l_size;
3781 	log->one_page_buf = kmalloc(page_size, GFP_NOFS);
3782 	if (!log->one_page_buf) {
3783 		err = -ENOMEM;
3784 		goto out;
3785 	}
3786 
3787 	log->page_size = page_size;
3788 	log->page_mask = page_size - 1;
3789 	log->page_bits = blksize_bits(page_size);
3790 
3791 	/* Look for a restart area on the disk. */
3792 	err = log_read_rst(log, l_size, true, &rst_info);
3793 	if (err)
3794 		goto out;
3795 
3796 	/* remember 'initialized' */
3797 	*initialized = rst_info.initialized;
3798 
3799 	if (!rst_info.restart) {
3800 		if (rst_info.initialized) {
3801 			/* No restart area but the file is not initialized. */
3802 			err = -EINVAL;
3803 			goto out;
3804 		}
3805 
3806 		log_init_pg_hdr(log, page_size, page_size, 1, 1);
3807 		log_create(log, l_size, 0, get_random_int(), false, false);
3808 
3809 		log->ra = ra;
3810 
3811 		ra = log_create_ra(log);
3812 		if (!ra) {
3813 			err = -ENOMEM;
3814 			goto out;
3815 		}
3816 		log->ra = ra;
3817 		log->init_ra = true;
3818 
3819 		goto process_log;
3820 	}
3821 
3822 	/*
3823 	 * If the restart offset above wasn't zero then we won't
3824 	 * look for a second restart.
3825 	 */
3826 	if (rst_info.vbo)
3827 		goto check_restart_area;
3828 
3829 	memset(&rst_info2, 0, sizeof(struct restart_info));
3830 	err = log_read_rst(log, l_size, false, &rst_info2);
3831 
3832 	/* Determine which restart area to use. */
3833 	if (!rst_info2.restart || rst_info2.last_lsn <= rst_info.last_lsn)
3834 		goto use_first_page;
3835 
3836 	use_second_page = true;
3837 
3838 	if (rst_info.chkdsk_was_run && page_size != rst_info.vbo) {
3839 		struct RECORD_PAGE_HDR *sp = NULL;
3840 		bool usa_error;
3841 
3842 		if (!read_log_page(log, page_size, &sp, &usa_error) &&
3843 		    sp->rhdr.sign == NTFS_CHKD_SIGNATURE) {
3844 			use_second_page = false;
3845 		}
3846 		kfree(sp);
3847 	}
3848 
3849 	if (use_second_page) {
3850 		kfree(rst_info.r_page);
3851 		memcpy(&rst_info, &rst_info2, sizeof(struct restart_info));
3852 		rst_info2.r_page = NULL;
3853 	}
3854 
3855 use_first_page:
3856 	kfree(rst_info2.r_page);
3857 
3858 check_restart_area:
3859 	/*
3860 	 * If the restart area is at offset 0, we want
3861 	 * to write the second restart area first.
3862 	 */
3863 	log->init_ra = !!rst_info.vbo;
3864 
3865 	/* If we have a valid page then grab a pointer to the restart area. */
3866 	ra2 = rst_info.valid_page
3867 		      ? Add2Ptr(rst_info.r_page,
3868 				le16_to_cpu(rst_info.r_page->ra_off))
3869 		      : NULL;
3870 
3871 	if (rst_info.chkdsk_was_run ||
3872 	    (ra2 && ra2->client_idx[1] == LFS_NO_CLIENT_LE)) {
3873 		bool wrapped = false;
3874 		bool use_multi_page = false;
3875 		u32 open_log_count;
3876 
3877 		/* Do some checks based on whether we have a valid log page. */
3878 		if (!rst_info.valid_page) {
3879 			open_log_count = get_random_int();
3880 			goto init_log_instance;
3881 		}
3882 		open_log_count = le32_to_cpu(ra2->open_log_count);
3883 
3884 		/*
3885 		 * If the restart page size isn't changing then we want to
3886 		 * check how much work we need to do.
3887 		 */
3888 		if (page_size != le32_to_cpu(rst_info.r_page->sys_page_size))
3889 			goto init_log_instance;
3890 
3891 init_log_instance:
3892 		log_init_pg_hdr(log, page_size, page_size, 1, 1);
3893 
3894 		log_create(log, l_size, rst_info.last_lsn, open_log_count,
3895 			   wrapped, use_multi_page);
3896 
3897 		ra = log_create_ra(log);
3898 		if (!ra) {
3899 			err = -ENOMEM;
3900 			goto out;
3901 		}
3902 		log->ra = ra;
3903 
3904 		/* Put the restart areas and initialize
3905 		 * the log file as required.
3906 		 */
3907 		goto process_log;
3908 	}
3909 
3910 	if (!ra2) {
3911 		err = -EINVAL;
3912 		goto out;
3913 	}
3914 
3915 	/*
3916 	 * If the log page or the system page sizes have changed, we can't
3917 	 * use the log file. We must use the system page size instead of the
3918 	 * default size if there is not a clean shutdown.
3919 	 */
3920 	t32 = le32_to_cpu(rst_info.r_page->sys_page_size);
3921 	if (page_size != t32) {
3922 		l_size = orig_file_size;
3923 		page_size =
3924 			norm_file_page(t32, &l_size, t32 == DefaultLogPageSize);
3925 	}
3926 
3927 	if (page_size != t32 ||
3928 	    page_size != le32_to_cpu(rst_info.r_page->page_size)) {
3929 		err = -EINVAL;
3930 		goto out;
3931 	}
3932 
3933 	/* If the file size has shrunk then we won't mount it. */
3934 	if (l_size < le64_to_cpu(ra2->l_size)) {
3935 		err = -EINVAL;
3936 		goto out;
3937 	}
3938 
3939 	log_init_pg_hdr(log, page_size, page_size,
3940 			le16_to_cpu(rst_info.r_page->major_ver),
3941 			le16_to_cpu(rst_info.r_page->minor_ver));
3942 
3943 	log->l_size = le64_to_cpu(ra2->l_size);
3944 	log->seq_num_bits = le32_to_cpu(ra2->seq_num_bits);
3945 	log->file_data_bits = sizeof(u64) * 8 - log->seq_num_bits;
3946 	log->seq_num_mask = (8 << log->file_data_bits) - 1;
3947 	log->last_lsn = le64_to_cpu(ra2->current_lsn);
3948 	log->seq_num = log->last_lsn >> log->file_data_bits;
3949 	log->ra_off = le16_to_cpu(rst_info.r_page->ra_off);
3950 	log->restart_size = log->sys_page_size - log->ra_off;
3951 	log->record_header_len = le16_to_cpu(ra2->rec_hdr_len);
3952 	log->ra_size = le16_to_cpu(ra2->ra_len);
3953 	log->data_off = le16_to_cpu(ra2->data_off);
3954 	log->data_size = log->page_size - log->data_off;
3955 	log->reserved = log->data_size - log->record_header_len;
3956 
3957 	vbo = lsn_to_vbo(log, log->last_lsn);
3958 
3959 	if (vbo < log->first_page) {
3960 		/* This is a pseudo lsn. */
3961 		log->l_flags |= NTFSLOG_NO_LAST_LSN;
3962 		log->next_page = log->first_page;
3963 		goto find_oldest;
3964 	}
3965 
3966 	/* Find the end of this log record. */
3967 	off = final_log_off(log, log->last_lsn,
3968 			    le32_to_cpu(ra2->last_lsn_data_len));
3969 
3970 	/* If we wrapped the file then increment the sequence number. */
3971 	if (off <= vbo) {
3972 		log->seq_num += 1;
3973 		log->l_flags |= NTFSLOG_WRAPPED;
3974 	}
3975 
3976 	/* Now compute the next log page to use. */
3977 	vbo &= ~log->sys_page_mask;
3978 	tail = log->page_size - (off & log->page_mask) - 1;
3979 
3980 	/*
3981 	 *If we can fit another log record on the page,
3982 	 * move back a page the log file.
3983 	 */
3984 	if (tail >= log->record_header_len) {
3985 		log->l_flags |= NTFSLOG_REUSE_TAIL;
3986 		log->next_page = vbo;
3987 	} else {
3988 		log->next_page = next_page_off(log, vbo);
3989 	}
3990 
3991 find_oldest:
3992 	/*
3993 	 * Find the oldest client lsn. Use the last
3994 	 * flushed lsn as a starting point.
3995 	 */
3996 	log->oldest_lsn = log->last_lsn;
3997 	oldest_client_lsn(Add2Ptr(ra2, le16_to_cpu(ra2->client_off)),
3998 			  ra2->client_idx[1], &log->oldest_lsn);
3999 	log->oldest_lsn_off = lsn_to_vbo(log, log->oldest_lsn);
4000 
4001 	if (log->oldest_lsn_off < log->first_page)
4002 		log->l_flags |= NTFSLOG_NO_OLDEST_LSN;
4003 
4004 	if (!(ra2->flags & RESTART_SINGLE_PAGE_IO))
4005 		log->l_flags |= NTFSLOG_WRAPPED | NTFSLOG_MULTIPLE_PAGE_IO;
4006 
4007 	log->current_openlog_count = le32_to_cpu(ra2->open_log_count);
4008 	log->total_avail_pages = log->l_size - log->first_page;
4009 	log->total_avail = log->total_avail_pages >> log->page_bits;
4010 	log->max_current_avail = log->total_avail * log->reserved;
4011 	log->total_avail = log->total_avail * log->data_size;
4012 
4013 	log->current_avail = current_log_avail(log);
4014 
4015 	ra = kzalloc(log->restart_size, GFP_NOFS);
4016 	if (!ra) {
4017 		err = -ENOMEM;
4018 		goto out;
4019 	}
4020 	log->ra = ra;
4021 
4022 	t16 = le16_to_cpu(ra2->client_off);
4023 	if (t16 == offsetof(struct RESTART_AREA, clients)) {
4024 		memcpy(ra, ra2, log->ra_size);
4025 	} else {
4026 		memcpy(ra, ra2, offsetof(struct RESTART_AREA, clients));
4027 		memcpy(ra->clients, Add2Ptr(ra2, t16),
4028 		       le16_to_cpu(ra2->ra_len) - t16);
4029 
4030 		log->current_openlog_count = get_random_int();
4031 		ra->open_log_count = cpu_to_le32(log->current_openlog_count);
4032 		log->ra_size = offsetof(struct RESTART_AREA, clients) +
4033 			       sizeof(struct CLIENT_REC);
4034 		ra->client_off =
4035 			cpu_to_le16(offsetof(struct RESTART_AREA, clients));
4036 		ra->ra_len = cpu_to_le16(log->ra_size);
4037 	}
4038 
4039 	le32_add_cpu(&ra->open_log_count, 1);
4040 
4041 	/* Now we need to walk through looking for the last lsn. */
4042 	err = last_log_lsn(log);
4043 	if (err)
4044 		goto out;
4045 
4046 	log->current_avail = current_log_avail(log);
4047 
4048 	/* Remember which restart area to write first. */
4049 	log->init_ra = rst_info.vbo;
4050 
4051 process_log:
4052 	/* 1.0, 1.1, 2.0 log->major_ver/minor_ver - short values. */
4053 	switch ((log->major_ver << 16) + log->minor_ver) {
4054 	case 0x10000:
4055 	case 0x10001:
4056 	case 0x20000:
4057 		break;
4058 	default:
4059 		ntfs_warn(sbi->sb, "\x24LogFile version %d.%d is not supported",
4060 			  log->major_ver, log->minor_ver);
4061 		err = -EOPNOTSUPP;
4062 		log->set_dirty = true;
4063 		goto out;
4064 	}
4065 
4066 	/* One client "NTFS" per logfile. */
4067 	ca = Add2Ptr(ra, le16_to_cpu(ra->client_off));
4068 
4069 	for (client = ra->client_idx[1];; client = cr->next_client) {
4070 		if (client == LFS_NO_CLIENT_LE) {
4071 			/* Insert "NTFS" client LogFile. */
4072 			client = ra->client_idx[0];
4073 			if (client == LFS_NO_CLIENT_LE) {
4074 				err = -EINVAL;
4075 				goto out;
4076 			}
4077 
4078 			t16 = le16_to_cpu(client);
4079 			cr = ca + t16;
4080 
4081 			remove_client(ca, cr, &ra->client_idx[0]);
4082 
4083 			cr->restart_lsn = 0;
4084 			cr->oldest_lsn = cpu_to_le64(log->oldest_lsn);
4085 			cr->name_bytes = cpu_to_le32(8);
4086 			cr->name[0] = cpu_to_le16('N');
4087 			cr->name[1] = cpu_to_le16('T');
4088 			cr->name[2] = cpu_to_le16('F');
4089 			cr->name[3] = cpu_to_le16('S');
4090 
4091 			add_client(ca, t16, &ra->client_idx[1]);
4092 			break;
4093 		}
4094 
4095 		cr = ca + le16_to_cpu(client);
4096 
4097 		if (cpu_to_le32(8) == cr->name_bytes &&
4098 		    cpu_to_le16('N') == cr->name[0] &&
4099 		    cpu_to_le16('T') == cr->name[1] &&
4100 		    cpu_to_le16('F') == cr->name[2] &&
4101 		    cpu_to_le16('S') == cr->name[3])
4102 			break;
4103 	}
4104 
4105 	/* Update the client handle with the client block information. */
4106 	log->client_id.seq_num = cr->seq_num;
4107 	log->client_id.client_idx = client;
4108 
4109 	err = read_rst_area(log, &rst, &ra_lsn);
4110 	if (err)
4111 		goto out;
4112 
4113 	if (!rst)
4114 		goto out;
4115 
4116 	bytes_per_attr_entry = !rst->major_ver ? 0x2C : 0x28;
4117 
4118 	checkpt_lsn = le64_to_cpu(rst->check_point_start);
4119 	if (!checkpt_lsn)
4120 		checkpt_lsn = ra_lsn;
4121 
4122 	/* Allocate and Read the Transaction Table. */
4123 	if (!rst->transact_table_len)
4124 		goto check_dirty_page_table;
4125 
4126 	t64 = le64_to_cpu(rst->transact_table_lsn);
4127 	err = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);
4128 	if (err)
4129 		goto out;
4130 
4131 	lrh = lcb->log_rec;
4132 	frh = lcb->lrh;
4133 	rec_len = le32_to_cpu(frh->client_data_len);
4134 
4135 	if (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),
4136 			   bytes_per_attr_entry)) {
4137 		err = -EINVAL;
4138 		goto out;
4139 	}
4140 
4141 	t16 = le16_to_cpu(lrh->redo_off);
4142 
4143 	rt = Add2Ptr(lrh, t16);
4144 	t32 = rec_len - t16;
4145 
4146 	/* Now check that this is a valid restart table. */
4147 	if (!check_rstbl(rt, t32)) {
4148 		err = -EINVAL;
4149 		goto out;
4150 	}
4151 
4152 	trtbl = kmemdup(rt, t32, GFP_NOFS);
4153 	if (!trtbl) {
4154 		err = -ENOMEM;
4155 		goto out;
4156 	}
4157 
4158 	lcb_put(lcb);
4159 	lcb = NULL;
4160 
4161 check_dirty_page_table:
4162 	/* The next record back should be the Dirty Pages Table. */
4163 	if (!rst->dirty_pages_len)
4164 		goto check_attribute_names;
4165 
4166 	t64 = le64_to_cpu(rst->dirty_pages_table_lsn);
4167 	err = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);
4168 	if (err)
4169 		goto out;
4170 
4171 	lrh = lcb->log_rec;
4172 	frh = lcb->lrh;
4173 	rec_len = le32_to_cpu(frh->client_data_len);
4174 
4175 	if (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),
4176 			   bytes_per_attr_entry)) {
4177 		err = -EINVAL;
4178 		goto out;
4179 	}
4180 
4181 	t16 = le16_to_cpu(lrh->redo_off);
4182 
4183 	rt = Add2Ptr(lrh, t16);
4184 	t32 = rec_len - t16;
4185 
4186 	/* Now check that this is a valid restart table. */
4187 	if (!check_rstbl(rt, t32)) {
4188 		err = -EINVAL;
4189 		goto out;
4190 	}
4191 
4192 	dptbl = kmemdup(rt, t32, GFP_NOFS);
4193 	if (!dptbl) {
4194 		err = -ENOMEM;
4195 		goto out;
4196 	}
4197 
4198 	/* Convert Ra version '0' into version '1'. */
4199 	if (rst->major_ver)
4200 		goto end_conv_1;
4201 
4202 	dp = NULL;
4203 	while ((dp = enum_rstbl(dptbl, dp))) {
4204 		struct DIR_PAGE_ENTRY_32 *dp0 = (struct DIR_PAGE_ENTRY_32 *)dp;
4205 		// NOTE: Danger. Check for of boundary.
4206 		memmove(&dp->vcn, &dp0->vcn_low,
4207 			2 * sizeof(u64) +
4208 				le32_to_cpu(dp->lcns_follow) * sizeof(u64));
4209 	}
4210 
4211 end_conv_1:
4212 	lcb_put(lcb);
4213 	lcb = NULL;
4214 
4215 	/*
4216 	 * Go through the table and remove the duplicates,
4217 	 * remembering the oldest lsn values.
4218 	 */
4219 	if (sbi->cluster_size <= log->page_size)
4220 		goto trace_dp_table;
4221 
4222 	dp = NULL;
4223 	while ((dp = enum_rstbl(dptbl, dp))) {
4224 		struct DIR_PAGE_ENTRY *next = dp;
4225 
4226 		while ((next = enum_rstbl(dptbl, next))) {
4227 			if (next->target_attr == dp->target_attr &&
4228 			    next->vcn == dp->vcn) {
4229 				if (le64_to_cpu(next->oldest_lsn) <
4230 				    le64_to_cpu(dp->oldest_lsn)) {
4231 					dp->oldest_lsn = next->oldest_lsn;
4232 				}
4233 
4234 				free_rsttbl_idx(dptbl, PtrOffset(dptbl, next));
4235 			}
4236 		}
4237 	}
4238 trace_dp_table:
4239 check_attribute_names:
4240 	/* The next record should be the Attribute Names. */
4241 	if (!rst->attr_names_len)
4242 		goto check_attr_table;
4243 
4244 	t64 = le64_to_cpu(rst->attr_names_lsn);
4245 	err = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);
4246 	if (err)
4247 		goto out;
4248 
4249 	lrh = lcb->log_rec;
4250 	frh = lcb->lrh;
4251 	rec_len = le32_to_cpu(frh->client_data_len);
4252 
4253 	if (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),
4254 			   bytes_per_attr_entry)) {
4255 		err = -EINVAL;
4256 		goto out;
4257 	}
4258 
4259 	t32 = lrh_length(lrh);
4260 	rec_len -= t32;
4261 
4262 	attr_names = kmemdup(Add2Ptr(lrh, t32), rec_len, GFP_NOFS);
4263 	if (!attr_names) {
4264 		err = -ENOMEM;
4265 		goto out;
4266 	}
4267 
4268 	lcb_put(lcb);
4269 	lcb = NULL;
4270 
4271 check_attr_table:
4272 	/* The next record should be the attribute Table. */
4273 	if (!rst->open_attr_len)
4274 		goto check_attribute_names2;
4275 
4276 	t64 = le64_to_cpu(rst->open_attr_table_lsn);
4277 	err = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);
4278 	if (err)
4279 		goto out;
4280 
4281 	lrh = lcb->log_rec;
4282 	frh = lcb->lrh;
4283 	rec_len = le32_to_cpu(frh->client_data_len);
4284 
4285 	if (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),
4286 			   bytes_per_attr_entry)) {
4287 		err = -EINVAL;
4288 		goto out;
4289 	}
4290 
4291 	t16 = le16_to_cpu(lrh->redo_off);
4292 
4293 	rt = Add2Ptr(lrh, t16);
4294 	t32 = rec_len - t16;
4295 
4296 	if (!check_rstbl(rt, t32)) {
4297 		err = -EINVAL;
4298 		goto out;
4299 	}
4300 
4301 	oatbl = kmemdup(rt, t32, GFP_NOFS);
4302 	if (!oatbl) {
4303 		err = -ENOMEM;
4304 		goto out;
4305 	}
4306 
4307 	log->open_attr_tbl = oatbl;
4308 
4309 	/* Clear all of the Attr pointers. */
4310 	oe = NULL;
4311 	while ((oe = enum_rstbl(oatbl, oe))) {
4312 		if (!rst->major_ver) {
4313 			struct OPEN_ATTR_ENRTY_32 oe0;
4314 
4315 			/* Really 'oe' points to OPEN_ATTR_ENRTY_32. */
4316 			memcpy(&oe0, oe, SIZEOF_OPENATTRIBUTEENTRY0);
4317 
4318 			oe->bytes_per_index = oe0.bytes_per_index;
4319 			oe->type = oe0.type;
4320 			oe->is_dirty_pages = oe0.is_dirty_pages;
4321 			oe->name_len = 0;
4322 			oe->ref = oe0.ref;
4323 			oe->open_record_lsn = oe0.open_record_lsn;
4324 		}
4325 
4326 		oe->is_attr_name = 0;
4327 		oe->ptr = NULL;
4328 	}
4329 
4330 	lcb_put(lcb);
4331 	lcb = NULL;
4332 
4333 check_attribute_names2:
4334 	if (!rst->attr_names_len)
4335 		goto trace_attribute_table;
4336 
4337 	ane = attr_names;
4338 	if (!oatbl)
4339 		goto trace_attribute_table;
4340 	while (ane->off) {
4341 		/* TODO: Clear table on exit! */
4342 		oe = Add2Ptr(oatbl, le16_to_cpu(ane->off));
4343 		t16 = le16_to_cpu(ane->name_bytes);
4344 		oe->name_len = t16 / sizeof(short);
4345 		oe->ptr = ane->name;
4346 		oe->is_attr_name = 2;
4347 		ane = Add2Ptr(ane, sizeof(struct ATTR_NAME_ENTRY) + t16);
4348 	}
4349 
4350 trace_attribute_table:
4351 	/*
4352 	 * If the checkpt_lsn is zero, then this is a freshly
4353 	 * formatted disk and we have no work to do.
4354 	 */
4355 	if (!checkpt_lsn) {
4356 		err = 0;
4357 		goto out;
4358 	}
4359 
4360 	if (!oatbl) {
4361 		oatbl = init_rsttbl(bytes_per_attr_entry, 8);
4362 		if (!oatbl) {
4363 			err = -ENOMEM;
4364 			goto out;
4365 		}
4366 	}
4367 
4368 	log->open_attr_tbl = oatbl;
4369 
4370 	/* Start the analysis pass from the Checkpoint lsn. */
4371 	rec_lsn = checkpt_lsn;
4372 
4373 	/* Read the first lsn. */
4374 	err = read_log_rec_lcb(log, checkpt_lsn, lcb_ctx_next, &lcb);
4375 	if (err)
4376 		goto out;
4377 
4378 	/* Loop to read all subsequent records to the end of the log file. */
4379 next_log_record_analyze:
4380 	err = read_next_log_rec(log, lcb, &rec_lsn);
4381 	if (err)
4382 		goto out;
4383 
4384 	if (!rec_lsn)
4385 		goto end_log_records_enumerate;
4386 
4387 	frh = lcb->lrh;
4388 	transact_id = le32_to_cpu(frh->transact_id);
4389 	rec_len = le32_to_cpu(frh->client_data_len);
4390 	lrh = lcb->log_rec;
4391 
4392 	if (!check_log_rec(lrh, rec_len, transact_id, bytes_per_attr_entry)) {
4393 		err = -EINVAL;
4394 		goto out;
4395 	}
4396 
4397 	/*
4398 	 * The first lsn after the previous lsn remembered
4399 	 * the checkpoint is the first candidate for the rlsn.
4400 	 */
4401 	if (!rlsn)
4402 		rlsn = rec_lsn;
4403 
4404 	if (LfsClientRecord != frh->record_type)
4405 		goto next_log_record_analyze;
4406 
4407 	/*
4408 	 * Now update the Transaction Table for this transaction. If there
4409 	 * is no entry present or it is unallocated we allocate the entry.
4410 	 */
4411 	if (!trtbl) {
4412 		trtbl = init_rsttbl(sizeof(struct TRANSACTION_ENTRY),
4413 				    INITIAL_NUMBER_TRANSACTIONS);
4414 		if (!trtbl) {
4415 			err = -ENOMEM;
4416 			goto out;
4417 		}
4418 	}
4419 
4420 	tr = Add2Ptr(trtbl, transact_id);
4421 
4422 	if (transact_id >= bytes_per_rt(trtbl) ||
4423 	    tr->next != RESTART_ENTRY_ALLOCATED_LE) {
4424 		tr = alloc_rsttbl_from_idx(&trtbl, transact_id);
4425 		if (!tr) {
4426 			err = -ENOMEM;
4427 			goto out;
4428 		}
4429 		tr->transact_state = TransactionActive;
4430 		tr->first_lsn = cpu_to_le64(rec_lsn);
4431 	}
4432 
4433 	tr->prev_lsn = tr->undo_next_lsn = cpu_to_le64(rec_lsn);
4434 
4435 	/*
4436 	 * If this is a compensation log record, then change
4437 	 * the undo_next_lsn to be the undo_next_lsn of this record.
4438 	 */
4439 	if (lrh->undo_op == cpu_to_le16(CompensationLogRecord))
4440 		tr->undo_next_lsn = frh->client_undo_next_lsn;
4441 
4442 	/* Dispatch to handle log record depending on type. */
4443 	switch (le16_to_cpu(lrh->redo_op)) {
4444 	case InitializeFileRecordSegment:
4445 	case DeallocateFileRecordSegment:
4446 	case WriteEndOfFileRecordSegment:
4447 	case CreateAttribute:
4448 	case DeleteAttribute:
4449 	case UpdateResidentValue:
4450 	case UpdateNonresidentValue:
4451 	case UpdateMappingPairs:
4452 	case SetNewAttributeSizes:
4453 	case AddIndexEntryRoot:
4454 	case DeleteIndexEntryRoot:
4455 	case AddIndexEntryAllocation:
4456 	case DeleteIndexEntryAllocation:
4457 	case WriteEndOfIndexBuffer:
4458 	case SetIndexEntryVcnRoot:
4459 	case SetIndexEntryVcnAllocation:
4460 	case UpdateFileNameRoot:
4461 	case UpdateFileNameAllocation:
4462 	case SetBitsInNonresidentBitMap:
4463 	case ClearBitsInNonresidentBitMap:
4464 	case UpdateRecordDataRoot:
4465 	case UpdateRecordDataAllocation:
4466 	case ZeroEndOfFileRecord:
4467 		t16 = le16_to_cpu(lrh->target_attr);
4468 		t64 = le64_to_cpu(lrh->target_vcn);
4469 		dp = find_dp(dptbl, t16, t64);
4470 
4471 		if (dp)
4472 			goto copy_lcns;
4473 
4474 		/*
4475 		 * Calculate the number of clusters per page the system
4476 		 * which wrote the checkpoint, possibly creating the table.
4477 		 */
4478 		if (dptbl) {
4479 			t32 = (le16_to_cpu(dptbl->size) -
4480 			       sizeof(struct DIR_PAGE_ENTRY)) /
4481 			      sizeof(u64);
4482 		} else {
4483 			t32 = log->clst_per_page;
4484 			kfree(dptbl);
4485 			dptbl = init_rsttbl(struct_size(dp, page_lcns, t32),
4486 					    32);
4487 			if (!dptbl) {
4488 				err = -ENOMEM;
4489 				goto out;
4490 			}
4491 		}
4492 
4493 		dp = alloc_rsttbl_idx(&dptbl);
4494 		if (!dp) {
4495 			err = -ENOMEM;
4496 			goto out;
4497 		}
4498 		dp->target_attr = cpu_to_le32(t16);
4499 		dp->transfer_len = cpu_to_le32(t32 << sbi->cluster_bits);
4500 		dp->lcns_follow = cpu_to_le32(t32);
4501 		dp->vcn = cpu_to_le64(t64 & ~((u64)t32 - 1));
4502 		dp->oldest_lsn = cpu_to_le64(rec_lsn);
4503 
4504 copy_lcns:
4505 		/*
4506 		 * Copy the Lcns from the log record into the Dirty Page Entry.
4507 		 * TODO: For different page size support, must somehow make
4508 		 * whole routine a loop, case Lcns do not fit below.
4509 		 */
4510 		t16 = le16_to_cpu(lrh->lcns_follow);
4511 		for (i = 0; i < t16; i++) {
4512 			size_t j = (size_t)(le64_to_cpu(lrh->target_vcn) -
4513 					    le64_to_cpu(dp->vcn));
4514 			dp->page_lcns[j + i] = lrh->page_lcns[i];
4515 		}
4516 
4517 		goto next_log_record_analyze;
4518 
4519 	case DeleteDirtyClusters: {
4520 		u32 range_count =
4521 			le16_to_cpu(lrh->redo_len) / sizeof(struct LCN_RANGE);
4522 		const struct LCN_RANGE *r =
4523 			Add2Ptr(lrh, le16_to_cpu(lrh->redo_off));
4524 
4525 		/* Loop through all of the Lcn ranges this log record. */
4526 		for (i = 0; i < range_count; i++, r++) {
4527 			u64 lcn0 = le64_to_cpu(r->lcn);
4528 			u64 lcn_e = lcn0 + le64_to_cpu(r->len) - 1;
4529 
4530 			dp = NULL;
4531 			while ((dp = enum_rstbl(dptbl, dp))) {
4532 				u32 j;
4533 
4534 				t32 = le32_to_cpu(dp->lcns_follow);
4535 				for (j = 0; j < t32; j++) {
4536 					t64 = le64_to_cpu(dp->page_lcns[j]);
4537 					if (t64 >= lcn0 && t64 <= lcn_e)
4538 						dp->page_lcns[j] = 0;
4539 				}
4540 			}
4541 		}
4542 		goto next_log_record_analyze;
4543 		;
4544 	}
4545 
4546 	case OpenNonresidentAttribute:
4547 		t16 = le16_to_cpu(lrh->target_attr);
4548 		if (t16 >= bytes_per_rt(oatbl)) {
4549 			/*
4550 			 * Compute how big the table needs to be.
4551 			 * Add 10 extra entries for some cushion.
4552 			 */
4553 			u32 new_e = t16 / le16_to_cpu(oatbl->size);
4554 
4555 			new_e += 10 - le16_to_cpu(oatbl->used);
4556 
4557 			oatbl = extend_rsttbl(oatbl, new_e, ~0u);
4558 			log->open_attr_tbl = oatbl;
4559 			if (!oatbl) {
4560 				err = -ENOMEM;
4561 				goto out;
4562 			}
4563 		}
4564 
4565 		/* Point to the entry being opened. */
4566 		oe = alloc_rsttbl_from_idx(&oatbl, t16);
4567 		log->open_attr_tbl = oatbl;
4568 		if (!oe) {
4569 			err = -ENOMEM;
4570 			goto out;
4571 		}
4572 
4573 		/* Initialize this entry from the log record. */
4574 		t16 = le16_to_cpu(lrh->redo_off);
4575 		if (!rst->major_ver) {
4576 			/* Convert version '0' into version '1'. */
4577 			struct OPEN_ATTR_ENRTY_32 *oe0 = Add2Ptr(lrh, t16);
4578 
4579 			oe->bytes_per_index = oe0->bytes_per_index;
4580 			oe->type = oe0->type;
4581 			oe->is_dirty_pages = oe0->is_dirty_pages;
4582 			oe->name_len = 0; //oe0.name_len;
4583 			oe->ref = oe0->ref;
4584 			oe->open_record_lsn = oe0->open_record_lsn;
4585 		} else {
4586 			memcpy(oe, Add2Ptr(lrh, t16), bytes_per_attr_entry);
4587 		}
4588 
4589 		t16 = le16_to_cpu(lrh->undo_len);
4590 		if (t16) {
4591 			oe->ptr = kmalloc(t16, GFP_NOFS);
4592 			if (!oe->ptr) {
4593 				err = -ENOMEM;
4594 				goto out;
4595 			}
4596 			oe->name_len = t16 / sizeof(short);
4597 			memcpy(oe->ptr,
4598 			       Add2Ptr(lrh, le16_to_cpu(lrh->undo_off)), t16);
4599 			oe->is_attr_name = 1;
4600 		} else {
4601 			oe->ptr = NULL;
4602 			oe->is_attr_name = 0;
4603 		}
4604 
4605 		goto next_log_record_analyze;
4606 
4607 	case HotFix:
4608 		t16 = le16_to_cpu(lrh->target_attr);
4609 		t64 = le64_to_cpu(lrh->target_vcn);
4610 		dp = find_dp(dptbl, t16, t64);
4611 		if (dp) {
4612 			size_t j = le64_to_cpu(lrh->target_vcn) -
4613 				   le64_to_cpu(dp->vcn);
4614 			if (dp->page_lcns[j])
4615 				dp->page_lcns[j] = lrh->page_lcns[0];
4616 		}
4617 		goto next_log_record_analyze;
4618 
4619 	case EndTopLevelAction:
4620 		tr = Add2Ptr(trtbl, transact_id);
4621 		tr->prev_lsn = cpu_to_le64(rec_lsn);
4622 		tr->undo_next_lsn = frh->client_undo_next_lsn;
4623 		goto next_log_record_analyze;
4624 
4625 	case PrepareTransaction:
4626 		tr = Add2Ptr(trtbl, transact_id);
4627 		tr->transact_state = TransactionPrepared;
4628 		goto next_log_record_analyze;
4629 
4630 	case CommitTransaction:
4631 		tr = Add2Ptr(trtbl, transact_id);
4632 		tr->transact_state = TransactionCommitted;
4633 		goto next_log_record_analyze;
4634 
4635 	case ForgetTransaction:
4636 		free_rsttbl_idx(trtbl, transact_id);
4637 		goto next_log_record_analyze;
4638 
4639 	case Noop:
4640 	case OpenAttributeTableDump:
4641 	case AttributeNamesDump:
4642 	case DirtyPageTableDump:
4643 	case TransactionTableDump:
4644 		/* The following cases require no action the Analysis Pass. */
4645 		goto next_log_record_analyze;
4646 
4647 	default:
4648 		/*
4649 		 * All codes will be explicitly handled.
4650 		 * If we see a code we do not expect, then we are trouble.
4651 		 */
4652 		goto next_log_record_analyze;
4653 	}
4654 
4655 end_log_records_enumerate:
4656 	lcb_put(lcb);
4657 	lcb = NULL;
4658 
4659 	/*
4660 	 * Scan the Dirty Page Table and Transaction Table for
4661 	 * the lowest lsn, and return it as the Redo lsn.
4662 	 */
4663 	dp = NULL;
4664 	while ((dp = enum_rstbl(dptbl, dp))) {
4665 		t64 = le64_to_cpu(dp->oldest_lsn);
4666 		if (t64 && t64 < rlsn)
4667 			rlsn = t64;
4668 	}
4669 
4670 	tr = NULL;
4671 	while ((tr = enum_rstbl(trtbl, tr))) {
4672 		t64 = le64_to_cpu(tr->first_lsn);
4673 		if (t64 && t64 < rlsn)
4674 			rlsn = t64;
4675 	}
4676 
4677 	/*
4678 	 * Only proceed if the Dirty Page Table or Transaction
4679 	 * table are not empty.
4680 	 */
4681 	if ((!dptbl || !dptbl->total) && (!trtbl || !trtbl->total))
4682 		goto end_reply;
4683 
4684 	sbi->flags |= NTFS_FLAGS_NEED_REPLAY;
4685 	if (is_ro)
4686 		goto out;
4687 
4688 	/* Reopen all of the attributes with dirty pages. */
4689 	oe = NULL;
4690 next_open_attribute:
4691 
4692 	oe = enum_rstbl(oatbl, oe);
4693 	if (!oe) {
4694 		err = 0;
4695 		dp = NULL;
4696 		goto next_dirty_page;
4697 	}
4698 
4699 	oa = kzalloc(sizeof(struct OpenAttr), GFP_NOFS);
4700 	if (!oa) {
4701 		err = -ENOMEM;
4702 		goto out;
4703 	}
4704 
4705 	inode = ntfs_iget5(sbi->sb, &oe->ref, NULL);
4706 	if (IS_ERR(inode))
4707 		goto fake_attr;
4708 
4709 	if (is_bad_inode(inode)) {
4710 		iput(inode);
4711 fake_attr:
4712 		if (oa->ni) {
4713 			iput(&oa->ni->vfs_inode);
4714 			oa->ni = NULL;
4715 		}
4716 
4717 		attr = attr_create_nonres_log(sbi, oe->type, 0, oe->ptr,
4718 					      oe->name_len, 0);
4719 		if (!attr) {
4720 			kfree(oa);
4721 			err = -ENOMEM;
4722 			goto out;
4723 		}
4724 		oa->attr = attr;
4725 		oa->run1 = &oa->run0;
4726 		goto final_oe;
4727 	}
4728 
4729 	ni_oe = ntfs_i(inode);
4730 	oa->ni = ni_oe;
4731 
4732 	attr = ni_find_attr(ni_oe, NULL, NULL, oe->type, oe->ptr, oe->name_len,
4733 			    NULL, NULL);
4734 
4735 	if (!attr)
4736 		goto fake_attr;
4737 
4738 	t32 = le32_to_cpu(attr->size);
4739 	oa->attr = kmemdup(attr, t32, GFP_NOFS);
4740 	if (!oa->attr)
4741 		goto fake_attr;
4742 
4743 	if (!S_ISDIR(inode->i_mode)) {
4744 		if (attr->type == ATTR_DATA && !attr->name_len) {
4745 			oa->run1 = &ni_oe->file.run;
4746 			goto final_oe;
4747 		}
4748 	} else {
4749 		if (attr->type == ATTR_ALLOC &&
4750 		    attr->name_len == ARRAY_SIZE(I30_NAME) &&
4751 		    !memcmp(attr_name(attr), I30_NAME, sizeof(I30_NAME))) {
4752 			oa->run1 = &ni_oe->dir.alloc_run;
4753 			goto final_oe;
4754 		}
4755 	}
4756 
4757 	if (attr->non_res) {
4758 		u16 roff = le16_to_cpu(attr->nres.run_off);
4759 		CLST svcn = le64_to_cpu(attr->nres.svcn);
4760 
4761 		if (roff > t32) {
4762 			kfree(oa->attr);
4763 			oa->attr = NULL;
4764 			goto fake_attr;
4765 		}
4766 
4767 		err = run_unpack(&oa->run0, sbi, inode->i_ino, svcn,
4768 				 le64_to_cpu(attr->nres.evcn), svcn,
4769 				 Add2Ptr(attr, roff), t32 - roff);
4770 		if (err < 0) {
4771 			kfree(oa->attr);
4772 			oa->attr = NULL;
4773 			goto fake_attr;
4774 		}
4775 		err = 0;
4776 	}
4777 	oa->run1 = &oa->run0;
4778 	attr = oa->attr;
4779 
4780 final_oe:
4781 	if (oe->is_attr_name == 1)
4782 		kfree(oe->ptr);
4783 	oe->is_attr_name = 0;
4784 	oe->ptr = oa;
4785 	oe->name_len = attr->name_len;
4786 
4787 	goto next_open_attribute;
4788 
4789 	/*
4790 	 * Now loop through the dirty page table to extract all of the Vcn/Lcn.
4791 	 * Mapping that we have, and insert it into the appropriate run.
4792 	 */
4793 next_dirty_page:
4794 	dp = enum_rstbl(dptbl, dp);
4795 	if (!dp)
4796 		goto do_redo_1;
4797 
4798 	oe = Add2Ptr(oatbl, le32_to_cpu(dp->target_attr));
4799 
4800 	if (oe->next != RESTART_ENTRY_ALLOCATED_LE)
4801 		goto next_dirty_page;
4802 
4803 	oa = oe->ptr;
4804 	if (!oa)
4805 		goto next_dirty_page;
4806 
4807 	i = -1;
4808 next_dirty_page_vcn:
4809 	i += 1;
4810 	if (i >= le32_to_cpu(dp->lcns_follow))
4811 		goto next_dirty_page;
4812 
4813 	vcn = le64_to_cpu(dp->vcn) + i;
4814 	size = (vcn + 1) << sbi->cluster_bits;
4815 
4816 	if (!dp->page_lcns[i])
4817 		goto next_dirty_page_vcn;
4818 
4819 	rno = ino_get(&oe->ref);
4820 	if (rno <= MFT_REC_MIRR &&
4821 	    size < (MFT_REC_VOL + 1) * sbi->record_size &&
4822 	    oe->type == ATTR_DATA) {
4823 		goto next_dirty_page_vcn;
4824 	}
4825 
4826 	lcn = le64_to_cpu(dp->page_lcns[i]);
4827 
4828 	if ((!run_lookup_entry(oa->run1, vcn, &lcn0, &len0, NULL) ||
4829 	     lcn0 != lcn) &&
4830 	    !run_add_entry(oa->run1, vcn, lcn, 1, false)) {
4831 		err = -ENOMEM;
4832 		goto out;
4833 	}
4834 	attr = oa->attr;
4835 	t64 = le64_to_cpu(attr->nres.alloc_size);
4836 	if (size > t64) {
4837 		attr->nres.valid_size = attr->nres.data_size =
4838 			attr->nres.alloc_size = cpu_to_le64(size);
4839 	}
4840 	goto next_dirty_page_vcn;
4841 
4842 do_redo_1:
4843 	/*
4844 	 * Perform the Redo Pass, to restore all of the dirty pages to the same
4845 	 * contents that they had immediately before the crash. If the dirty
4846 	 * page table is empty, then we can skip the entire Redo Pass.
4847 	 */
4848 	if (!dptbl || !dptbl->total)
4849 		goto do_undo_action;
4850 
4851 	rec_lsn = rlsn;
4852 
4853 	/*
4854 	 * Read the record at the Redo lsn, before falling
4855 	 * into common code to handle each record.
4856 	 */
4857 	err = read_log_rec_lcb(log, rlsn, lcb_ctx_next, &lcb);
4858 	if (err)
4859 		goto out;
4860 
4861 	/*
4862 	 * Now loop to read all of our log records forwards, until
4863 	 * we hit the end of the file, cleaning up at the end.
4864 	 */
4865 do_action_next:
4866 	frh = lcb->lrh;
4867 
4868 	if (LfsClientRecord != frh->record_type)
4869 		goto read_next_log_do_action;
4870 
4871 	transact_id = le32_to_cpu(frh->transact_id);
4872 	rec_len = le32_to_cpu(frh->client_data_len);
4873 	lrh = lcb->log_rec;
4874 
4875 	if (!check_log_rec(lrh, rec_len, transact_id, bytes_per_attr_entry)) {
4876 		err = -EINVAL;
4877 		goto out;
4878 	}
4879 
4880 	/* Ignore log records that do not update pages. */
4881 	if (lrh->lcns_follow)
4882 		goto find_dirty_page;
4883 
4884 	goto read_next_log_do_action;
4885 
4886 find_dirty_page:
4887 	t16 = le16_to_cpu(lrh->target_attr);
4888 	t64 = le64_to_cpu(lrh->target_vcn);
4889 	dp = find_dp(dptbl, t16, t64);
4890 
4891 	if (!dp)
4892 		goto read_next_log_do_action;
4893 
4894 	if (rec_lsn < le64_to_cpu(dp->oldest_lsn))
4895 		goto read_next_log_do_action;
4896 
4897 	t16 = le16_to_cpu(lrh->target_attr);
4898 	if (t16 >= bytes_per_rt(oatbl)) {
4899 		err = -EINVAL;
4900 		goto out;
4901 	}
4902 
4903 	oe = Add2Ptr(oatbl, t16);
4904 
4905 	if (oe->next != RESTART_ENTRY_ALLOCATED_LE) {
4906 		err = -EINVAL;
4907 		goto out;
4908 	}
4909 
4910 	oa = oe->ptr;
4911 
4912 	if (!oa) {
4913 		err = -EINVAL;
4914 		goto out;
4915 	}
4916 	attr = oa->attr;
4917 
4918 	vcn = le64_to_cpu(lrh->target_vcn);
4919 
4920 	if (!run_lookup_entry(oa->run1, vcn, &lcn, NULL, NULL) ||
4921 	    lcn == SPARSE_LCN) {
4922 		goto read_next_log_do_action;
4923 	}
4924 
4925 	/* Point to the Redo data and get its length. */
4926 	data = Add2Ptr(lrh, le16_to_cpu(lrh->redo_off));
4927 	dlen = le16_to_cpu(lrh->redo_len);
4928 
4929 	/* Shorten length by any Lcns which were deleted. */
4930 	saved_len = dlen;
4931 
4932 	for (i = le16_to_cpu(lrh->lcns_follow); i; i--) {
4933 		size_t j;
4934 		u32 alen, voff;
4935 
4936 		voff = le16_to_cpu(lrh->record_off) +
4937 		       le16_to_cpu(lrh->attr_off);
4938 		voff += le16_to_cpu(lrh->cluster_off) << SECTOR_SHIFT;
4939 
4940 		/* If the Vcn question is allocated, we can just get out. */
4941 		j = le64_to_cpu(lrh->target_vcn) - le64_to_cpu(dp->vcn);
4942 		if (dp->page_lcns[j + i - 1])
4943 			break;
4944 
4945 		if (!saved_len)
4946 			saved_len = 1;
4947 
4948 		/*
4949 		 * Calculate the allocated space left relative to the
4950 		 * log record Vcn, after removing this unallocated Vcn.
4951 		 */
4952 		alen = (i - 1) << sbi->cluster_bits;
4953 
4954 		/*
4955 		 * If the update described this log record goes beyond
4956 		 * the allocated space, then we will have to reduce the length.
4957 		 */
4958 		if (voff >= alen)
4959 			dlen = 0;
4960 		else if (voff + dlen > alen)
4961 			dlen = alen - voff;
4962 	}
4963 
4964 	/*
4965 	 * If the resulting dlen from above is now zero,
4966 	 * we can skip this log record.
4967 	 */
4968 	if (!dlen && saved_len)
4969 		goto read_next_log_do_action;
4970 
4971 	t16 = le16_to_cpu(lrh->redo_op);
4972 	if (can_skip_action(t16))
4973 		goto read_next_log_do_action;
4974 
4975 	/* Apply the Redo operation a common routine. */
4976 	err = do_action(log, oe, lrh, t16, data, dlen, rec_len, &rec_lsn);
4977 	if (err)
4978 		goto out;
4979 
4980 	/* Keep reading and looping back until end of file. */
4981 read_next_log_do_action:
4982 	err = read_next_log_rec(log, lcb, &rec_lsn);
4983 	if (!err && rec_lsn)
4984 		goto do_action_next;
4985 
4986 	lcb_put(lcb);
4987 	lcb = NULL;
4988 
4989 do_undo_action:
4990 	/* Scan Transaction Table. */
4991 	tr = NULL;
4992 transaction_table_next:
4993 	tr = enum_rstbl(trtbl, tr);
4994 	if (!tr)
4995 		goto undo_action_done;
4996 
4997 	if (TransactionActive != tr->transact_state || !tr->undo_next_lsn) {
4998 		free_rsttbl_idx(trtbl, PtrOffset(trtbl, tr));
4999 		goto transaction_table_next;
5000 	}
5001 
5002 	log->transaction_id = PtrOffset(trtbl, tr);
5003 	undo_next_lsn = le64_to_cpu(tr->undo_next_lsn);
5004 
5005 	/*
5006 	 * We only have to do anything if the transaction has
5007 	 * something its undo_next_lsn field.
5008 	 */
5009 	if (!undo_next_lsn)
5010 		goto commit_undo;
5011 
5012 	/* Read the first record to be undone by this transaction. */
5013 	err = read_log_rec_lcb(log, undo_next_lsn, lcb_ctx_undo_next, &lcb);
5014 	if (err)
5015 		goto out;
5016 
5017 	/*
5018 	 * Now loop to read all of our log records forwards,
5019 	 * until we hit the end of the file, cleaning up at the end.
5020 	 */
5021 undo_action_next:
5022 
5023 	lrh = lcb->log_rec;
5024 	frh = lcb->lrh;
5025 	transact_id = le32_to_cpu(frh->transact_id);
5026 	rec_len = le32_to_cpu(frh->client_data_len);
5027 
5028 	if (!check_log_rec(lrh, rec_len, transact_id, bytes_per_attr_entry)) {
5029 		err = -EINVAL;
5030 		goto out;
5031 	}
5032 
5033 	if (lrh->undo_op == cpu_to_le16(Noop))
5034 		goto read_next_log_undo_action;
5035 
5036 	oe = Add2Ptr(oatbl, le16_to_cpu(lrh->target_attr));
5037 	oa = oe->ptr;
5038 
5039 	t16 = le16_to_cpu(lrh->lcns_follow);
5040 	if (!t16)
5041 		goto add_allocated_vcns;
5042 
5043 	is_mapped = run_lookup_entry(oa->run1, le64_to_cpu(lrh->target_vcn),
5044 				     &lcn, &clen, NULL);
5045 
5046 	/*
5047 	 * If the mapping isn't already the table or the  mapping
5048 	 * corresponds to a hole the mapping, we need to make sure
5049 	 * there is no partial page already memory.
5050 	 */
5051 	if (is_mapped && lcn != SPARSE_LCN && clen >= t16)
5052 		goto add_allocated_vcns;
5053 
5054 	vcn = le64_to_cpu(lrh->target_vcn);
5055 	vcn &= ~(u64)(log->clst_per_page - 1);
5056 
5057 add_allocated_vcns:
5058 	for (i = 0, vcn = le64_to_cpu(lrh->target_vcn),
5059 	    size = (vcn + 1) << sbi->cluster_bits;
5060 	     i < t16; i++, vcn += 1, size += sbi->cluster_size) {
5061 		attr = oa->attr;
5062 		if (!attr->non_res) {
5063 			if (size > le32_to_cpu(attr->res.data_size))
5064 				attr->res.data_size = cpu_to_le32(size);
5065 		} else {
5066 			if (size > le64_to_cpu(attr->nres.data_size))
5067 				attr->nres.valid_size = attr->nres.data_size =
5068 					attr->nres.alloc_size =
5069 						cpu_to_le64(size);
5070 		}
5071 	}
5072 
5073 	t16 = le16_to_cpu(lrh->undo_op);
5074 	if (can_skip_action(t16))
5075 		goto read_next_log_undo_action;
5076 
5077 	/* Point to the Redo data and get its length. */
5078 	data = Add2Ptr(lrh, le16_to_cpu(lrh->undo_off));
5079 	dlen = le16_to_cpu(lrh->undo_len);
5080 
5081 	/* It is time to apply the undo action. */
5082 	err = do_action(log, oe, lrh, t16, data, dlen, rec_len, NULL);
5083 
5084 read_next_log_undo_action:
5085 	/*
5086 	 * Keep reading and looping back until we have read the
5087 	 * last record for this transaction.
5088 	 */
5089 	err = read_next_log_rec(log, lcb, &rec_lsn);
5090 	if (err)
5091 		goto out;
5092 
5093 	if (rec_lsn)
5094 		goto undo_action_next;
5095 
5096 	lcb_put(lcb);
5097 	lcb = NULL;
5098 
5099 commit_undo:
5100 	free_rsttbl_idx(trtbl, log->transaction_id);
5101 
5102 	log->transaction_id = 0;
5103 
5104 	goto transaction_table_next;
5105 
5106 undo_action_done:
5107 
5108 	ntfs_update_mftmirr(sbi, 0);
5109 
5110 	sbi->flags &= ~NTFS_FLAGS_NEED_REPLAY;
5111 
5112 end_reply:
5113 
5114 	err = 0;
5115 	if (is_ro)
5116 		goto out;
5117 
5118 	rh = kzalloc(log->page_size, GFP_NOFS);
5119 	if (!rh) {
5120 		err = -ENOMEM;
5121 		goto out;
5122 	}
5123 
5124 	rh->rhdr.sign = NTFS_RSTR_SIGNATURE;
5125 	rh->rhdr.fix_off = cpu_to_le16(offsetof(struct RESTART_HDR, fixups));
5126 	t16 = (log->page_size >> SECTOR_SHIFT) + 1;
5127 	rh->rhdr.fix_num = cpu_to_le16(t16);
5128 	rh->sys_page_size = cpu_to_le32(log->page_size);
5129 	rh->page_size = cpu_to_le32(log->page_size);
5130 
5131 	t16 = ALIGN(offsetof(struct RESTART_HDR, fixups) + sizeof(short) * t16,
5132 		    8);
5133 	rh->ra_off = cpu_to_le16(t16);
5134 	rh->minor_ver = cpu_to_le16(1); // 0x1A:
5135 	rh->major_ver = cpu_to_le16(1); // 0x1C:
5136 
5137 	ra2 = Add2Ptr(rh, t16);
5138 	memcpy(ra2, ra, sizeof(struct RESTART_AREA));
5139 
5140 	ra2->client_idx[0] = 0;
5141 	ra2->client_idx[1] = LFS_NO_CLIENT_LE;
5142 	ra2->flags = cpu_to_le16(2);
5143 
5144 	le32_add_cpu(&ra2->open_log_count, 1);
5145 
5146 	ntfs_fix_pre_write(&rh->rhdr, log->page_size);
5147 
5148 	err = ntfs_sb_write_run(sbi, &ni->file.run, 0, rh, log->page_size, 0);
5149 	if (!err)
5150 		err = ntfs_sb_write_run(sbi, &log->ni->file.run, log->page_size,
5151 					rh, log->page_size, 0);
5152 
5153 	kfree(rh);
5154 	if (err)
5155 		goto out;
5156 
5157 out:
5158 	kfree(rst);
5159 	if (lcb)
5160 		lcb_put(lcb);
5161 
5162 	/*
5163 	 * Scan the Open Attribute Table to close all of
5164 	 * the open attributes.
5165 	 */
5166 	oe = NULL;
5167 	while ((oe = enum_rstbl(oatbl, oe))) {
5168 		rno = ino_get(&oe->ref);
5169 
5170 		if (oe->is_attr_name == 1) {
5171 			kfree(oe->ptr);
5172 			oe->ptr = NULL;
5173 			continue;
5174 		}
5175 
5176 		if (oe->is_attr_name)
5177 			continue;
5178 
5179 		oa = oe->ptr;
5180 		if (!oa)
5181 			continue;
5182 
5183 		run_close(&oa->run0);
5184 		kfree(oa->attr);
5185 		if (oa->ni)
5186 			iput(&oa->ni->vfs_inode);
5187 		kfree(oa);
5188 	}
5189 
5190 	kfree(trtbl);
5191 	kfree(oatbl);
5192 	kfree(dptbl);
5193 	kfree(attr_names);
5194 	kfree(rst_info.r_page);
5195 
5196 	kfree(ra);
5197 	kfree(log->one_page_buf);
5198 
5199 	if (err)
5200 		sbi->flags |= NTFS_FLAGS_NEED_REPLAY;
5201 
5202 	if (err == -EROFS)
5203 		err = 0;
5204 	else if (log->set_dirty)
5205 		ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
5206 
5207 	kfree(log);
5208 
5209 	return err;
5210 }
5211