aboutsummaryrefslogtreecommitdiff
path: root/zenserver/experimental/usnjournal.cpp
blob: 580d71e45e6eb722cc0e396342c9221bf9e4e122 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zencore/zencore.h>

#if ZEN_PLATFORM_WINDOWS

#	include "usnjournal.h"

#	include <zencore/except.h>
#	include <zencore/logging.h>
#	include <zencore/timer.h>

ZEN_THIRD_PARTY_INCLUDES_START
#	include <atlfile.h>
ZEN_THIRD_PARTY_INCLUDES_END

#	include <filesystem>

namespace zen {

UsnJournalReader::UsnJournalReader()
{
}

UsnJournalReader::~UsnJournalReader()
{
	delete[] m_JournalReadBuffer;
}

bool
UsnJournalReader::Initialize(std::filesystem::path VolumePath)
{
	TCHAR VolumeName[MAX_PATH];
	TCHAR VolumePathName[MAX_PATH];

	{
		auto NativePath = VolumePath.native();
		BOOL Success	= GetVolumePathName(NativePath.c_str(), VolumePathName, ZEN_ARRAY_COUNT(VolumePathName));

		if (!Success)
		{
			zen::ThrowLastError("GetVolumePathName failed");
		}

		Success = GetVolumeNameForVolumeMountPoint(VolumePathName, VolumeName, ZEN_ARRAY_COUNT(VolumeName));

		if (!Success)
		{
			zen::ThrowLastError("GetVolumeNameForVolumeMountPoint failed");
		}

		// Chop off trailing slash since we want to open a volume handle, not a handle to the volume root directory

		const size_t VolumeNameLength = wcslen(VolumeName);

		if (VolumeNameLength)
		{
			VolumeName[VolumeNameLength - 1] = '\0';
		}
	}

	m_VolumeHandle = CreateFile(VolumeName,
								GENERIC_READ | GENERIC_WRITE,
								FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
								nullptr, /* no custom security */
								OPEN_EXISTING,
								FILE_FLAG_BACKUP_SEMANTICS,
								nullptr); /* template */

	if (m_VolumeHandle == INVALID_HANDLE_VALUE)
	{
		ThrowLastError("Volume handle open failed");
	}

	// Figure out which file system is in use for volume

	{
		WCHAR InfoVolumeName[MAX_PATH + 1]{};
		WCHAR FileSystemName[MAX_PATH + 1]{};
		DWORD MaximumComponentLength = 0;
		DWORD FileSystemFlags		 = 0;

		BOOL Success = GetVolumeInformationByHandleW(m_VolumeHandle,
													 InfoVolumeName,
													 MAX_PATH + 1,
													 NULL,
													 &MaximumComponentLength,
													 &FileSystemFlags,
													 FileSystemName,
													 ZEN_ARRAY_COUNT(FileSystemName));

		if (!Success)
		{
			ThrowLastError("Failed to get volume information");
		}

		ZEN_DEBUG("File system type is {}", WideToUtf8(FileSystemName));

		if (wcscmp(L"ReFS", FileSystemName) == 0)
		{
			m_FileSystemType = FileSystemType::ReFS;
		}
		else if (wcscmp(L"NTFS", FileSystemName) == 0)
		{
			m_FileSystemType = FileSystemType::NTFS;
		}
		else
		{
			// Unknown file system type!
		}
	}

	// Determine if volume is on fast storage, where seeks aren't so expensive

	{
		STORAGE_PROPERTY_QUERY StorageQuery{};
		StorageQuery.PropertyId = StorageDeviceSeekPenaltyProperty;
		StorageQuery.QueryType	= PropertyStandardQuery;
		DWORD						   BytesWritten;
		DEVICE_SEEK_PENALTY_DESCRIPTOR Result{};

		if (DeviceIoControl(m_VolumeHandle,
							IOCTL_STORAGE_QUERY_PROPERTY,
							&StorageQuery,
							sizeof(StorageQuery),
							&Result,
							sizeof(Result),
							&BytesWritten,
							nullptr))
		{
			m_IncursSeekPenalty = !!Result.IncursSeekPenalty;
		}
	}

	// Query Journal

	USN_JOURNAL_DATA_V2 UsnData{};

	{
		DWORD BytesWritten = 0;

		const BOOL Success =
			DeviceIoControl(m_VolumeHandle, FSCTL_QUERY_USN_JOURNAL, nullptr, 0, &UsnData, sizeof UsnData, &BytesWritten, nullptr);

		if (!Success)
		{
			switch (DWORD Error = GetLastError())
			{
				case ERROR_JOURNAL_NOT_ACTIVE:
					ZEN_INFO("No USN journal active on drive");

					// TODO: optionally activate USN journal on drive?

					ThrowSystemException(HRESULT_FROM_WIN32(Error), "No USN journal active on drive");
					break;

				default:
					ThrowSystemException(HRESULT_FROM_WIN32(Error), "FSCTL_QUERY_USN_JOURNAL failed");
			}
		}
	}

	m_JournalReadBuffer = new uint8_t[m_ReadBufferSize];

	// Catch up to USN start

	CAtlFile VolumeRootDir;
	HRESULT	 hRes =
		VolumeRootDir.Create(VolumePathName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS);

	if (FAILED(hRes))
	{
		ThrowSystemException(hRes, "Failed to open handle to volume root");
	}

	FILE_ID_INFO FileInformation{};
	BOOL		 Success = GetFileInformationByHandleEx(VolumeRootDir, FileIdInfo, &FileInformation, sizeof FileInformation);

	if (!Success)
	{
		ThrowLastError("GetFileInformationByHandleEx failed");
	}

	const Frn VolumeRootFrn = FileInformation.FileId;

	// Enumerate MFT (but not for ReFS)

	if (m_FileSystemType == FileSystemType::NTFS)
	{
		ZEN_INFO("Enumerating MFT for {}", WideToUtf8(VolumePathName));

		zen::Stopwatch Timer;
		uint64_t	   MftBytesProcessed = 0;

		MFT_ENUM_DATA_V1 MftEnumData{.StartFileReferenceNumber = 0, .LowUsn = 0, .HighUsn = 0, .MinMajorVersion = 2, .MaxMajorVersion = 3};

		BYTE  MftBuffer[64 * 1024 + sizeof(DWORDLONG)];
		DWORD BytesWritten = 0;

		for (;;)
		{
			Success = DeviceIoControl(m_VolumeHandle,
									  FSCTL_ENUM_USN_DATA,
									  &MftEnumData,
									  sizeof MftEnumData,
									  MftBuffer,
									  sizeof MftBuffer,
									  &BytesWritten,
									  nullptr);

			if (!Success)
			{
				DWORD Error = GetLastError();

				if (Error == ERROR_HANDLE_EOF)
				{
					break;
				}

				ThrowSystemException(HRESULT_FROM_WIN32(Error), "FSCTL_ENUM_USN_DATA failed");
			}

			void* BufferEnd = (void*)&MftBuffer[BytesWritten];

			// The enumeration call returns the next FRN ahead of the other data in the buffer
			MftEnumData.StartFileReferenceNumber = ((DWORDLONG*)MftBuffer)[0];

			PUSN_RECORD_UNION CommonRecord = PUSN_RECORD_UNION(&((DWORDLONG*)MftBuffer)[1]);

			while (CommonRecord < BufferEnd)
			{
				switch (CommonRecord->Header.MajorVersion)
				{
					case 2:
						{
							USN_RECORD_V2& Record = CommonRecord->V2;

							const Frn		  FileReference	  = Record.FileReferenceNumber;
							const Frn		  ParentReference = Record.ParentFileReferenceNumber;
							std::wstring_view FileName{Record.FileName, Record.FileNameLength};
						}
						break;
					case 3:
						{
							USN_RECORD_V3& Record = CommonRecord->V3;

							const Frn		  FileReference	  = Record.FileReferenceNumber;
							const Frn		  ParentReference = Record.ParentFileReferenceNumber;
							std::wstring_view FileName{Record.FileName, Record.FileNameLength};
						}
						break;
					case 4:
						{
							// This captures file modification ranges. We do not yet support this however
							USN_RECORD_V4& Record = CommonRecord->V4;
							ZEN_UNUSED(Record);
						}
						break;
				}

				const DWORD RecordLength = CommonRecord->Header.RecordLength;
				CommonRecord			 = PUSN_RECORD_UNION(((uint8_t*)CommonRecord) + RecordLength);
				MftBytesProcessed += RecordLength;
			}
		}

		const auto ElapsedMs = Timer.GetElapsedTimeMs();

		ZEN_INFO("MFT enumeration of {} completed after {} ({})",
				 zen::NiceBytes(MftBytesProcessed),
				 zen::NiceTimeSpanMs(ElapsedMs),
				 zen::NiceByteRate(MftBytesProcessed, ElapsedMs));
	}

	// Populate by traversal
	if (m_FileSystemType == FileSystemType::ReFS)
	{
		uint64_t FileInfoBuffer[8 * 1024];

		FILE_INFO_BY_HANDLE_CLASS FibClass = FileIdBothDirectoryRestartInfo;
		bool					  Continue = true;

		while (Continue)
		{
			Success	 = GetFileInformationByHandleEx(VolumeRootDir, FibClass, FileInfoBuffer, sizeof FileInfoBuffer);
			FibClass = FileIdBothDirectoryInfo;	 // Set up for next iteration

			uint64_t EntryOffset = 0;

			if (!Success)
			{
				// Report failure?

				break;
			}

			do
			{
				const FILE_ID_BOTH_DIR_INFO* DirInfo =
					reinterpret_cast<const FILE_ID_BOTH_DIR_INFO*>(reinterpret_cast<const uint8_t*>(FileInfoBuffer) + EntryOffset);

				const uint64_t NextOffset = DirInfo->NextEntryOffset;

				if (NextOffset == 0)
				{
					if (EntryOffset == 0)
					{
						// First and last - end of iteration
						Continue = false;
					}
					break;
				}

				if (DirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
				{
					// TODO Directory
				}
				else if (DirInfo->FileAttributes & FILE_ATTRIBUTE_DEVICE)
				{
					// TODO Device
				}
				else
				{
					// TODO File
				}

				EntryOffset += DirInfo->NextEntryOffset;
			} while (EntryOffset);
		}
	}

	// Initialize journal reading

	m_ReadUsnJournalData = {.StartUsn	= UsnData.FirstUsn,
							.ReasonMask = USN_REASON_BASIC_INFO_CHANGE | USN_REASON_CLOSE | USN_REASON_DATA_EXTEND |
										  USN_REASON_DATA_OVERWRITE | USN_REASON_DATA_TRUNCATION | USN_REASON_FILE_CREATE |
										  USN_REASON_FILE_DELETE | USN_REASON_HARD_LINK_CHANGE | USN_REASON_RENAME_NEW_NAME |
										  USN_REASON_RENAME_OLD_NAME | USN_REASON_REPARSE_POINT_CHANGE,
							.ReturnOnlyOnClose = true,
							.Timeout		   = 0,
							.BytesToWaitFor	   = 0,
							.UsnJournalID	   = UsnData.UsnJournalID,
							.MinMajorVersion   = 0,
							.MaxMajorVersion   = 0};

	return false;
}

}  // namespace zen

#endif	// ZEN_PLATFORM_WINDOWS