Skip to content

Commit ddee041

Browse files
benpeartGit for Windows Build Agent
authored andcommitted
fscache: teach fscache to use NtQueryDirectoryFile
Using FindFirstFileExW() requires the OS to allocate a 64K buffer for each directory and then free it when we call FindClose(). Update fscache to call the underlying kernel API NtQueryDirectoryFile so that we can do the buffer management ourselves. That allows us to allocate a single buffer for the lifetime of the cache and reuse it for each directory. This change improves performance of 'git status' by 18% in a repo with ~200K files and 30k folders. Documentation for NtQueryDirectoryFile can be found at: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ntifs/nf-ntifs-ntquerydirectoryfile https://docs.microsoft.com/en-us/windows/desktop/FileIO/file-attribute-constants https://docs.microsoft.com/en-us/windows/desktop/fileio/reparse-point-tags To determine if the specified directory is a symbolic link, inspect the FileAttributes member to see if the FILE_ATTRIBUTE_REPARSE_POINT flag is set. If so, EaSize will contain the reparse tag (this is a so far undocumented feature, but confirmed by the NTFS developers). To determine if the reparse point is a symbolic link (and not some other form of reparse point), test whether the tag value equals the value IO_REPARSE_TAG_SYMLINK. The NtQueryDirectoryFile() call works best (and on Windows 8.1 and earlier, it works *only*) with buffer sizes up to 64kB. Which is 32k wide characters, so let's use that as our buffer size. Signed-off-by: Johannes Schindelin <[email protected]>
1 parent 45b6678 commit ddee041

File tree

2 files changed

+219
-30
lines changed

2 files changed

+219
-30
lines changed

compat/win32/fscache.c

Lines changed: 88 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include "fscache.h"
55
#include "config.h"
66
#include "../../mem-pool.h"
7+
#include "ntifs.h"
78

89
static volatile long initialized;
910
static DWORD dwTlsIndex;
@@ -23,6 +24,13 @@ struct fscache {
2324
unsigned int opendir_requests;
2425
unsigned int fscache_requests;
2526
unsigned int fscache_misses;
27+
/*
28+
* 32k wide characters translates to 64kB, which is the maximum that
29+
* Windows 8.1 and earlier can handle. On network drives, not only
30+
* the client's Windows version matters, but also the server's,
31+
* therefore we need to keep this to 64kB.
32+
*/
33+
WCHAR buffer[32 * 1024];
2634
};
2735
static struct trace_key trace_fscache = TRACE_KEY_INIT(FSCACHE);
2836

@@ -145,25 +153,38 @@ static void fsentry_release(struct fsentry *fse)
145153
InterlockedDecrement(&(fse->u.refcnt));
146154
}
147155

156+
static int xwcstoutfn(char *utf, int utflen, const wchar_t *wcs, int wcslen)
157+
{
158+
if (!wcs || !utf || utflen < 1) {
159+
errno = EINVAL;
160+
return -1;
161+
}
162+
utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, wcslen, utf, utflen, NULL, NULL);
163+
if (utflen)
164+
return utflen;
165+
errno = ERANGE;
166+
return -1;
167+
}
168+
148169
/*
149-
* Allocate and initialize an fsentry from a WIN32_FIND_DATA structure.
170+
* Allocate and initialize an fsentry from a FILE_FULL_DIR_INFORMATION structure.
150171
*/
151172
static struct fsentry *fseentry_create_entry(struct fscache *cache, struct fsentry *list,
152-
const WIN32_FIND_DATAW *fdata)
173+
PFILE_FULL_DIR_INFORMATION fdata)
153174
{
154175
char buf[MAX_PATH * 3];
155176
int len;
156177
struct fsentry *fse;
157-
len = xwcstoutf(buf, fdata->cFileName, ARRAY_SIZE(buf));
178+
179+
len = xwcstoutfn(buf, ARRAY_SIZE(buf), fdata->FileName, fdata->FileNameLength / sizeof(wchar_t));
158180

159181
fse = fsentry_alloc(cache, list, buf, len);
160182

161-
fse->st_mode = file_attr_to_st_mode(fdata->dwFileAttributes);
162-
fse->u.s.st_size = (((off64_t) (fdata->nFileSizeHigh)) << 32)
163-
| fdata->nFileSizeLow;
164-
filetime_to_timespec(&(fdata->ftLastAccessTime), &(fse->u.s.st_atim));
165-
filetime_to_timespec(&(fdata->ftLastWriteTime), &(fse->u.s.st_mtim));
166-
filetime_to_timespec(&(fdata->ftCreationTime), &(fse->u.s.st_ctim));
183+
fse->st_mode = file_attr_to_st_mode(fdata->FileAttributes);
184+
fse->u.s.st_size = fdata->EndOfFile.LowPart | (((off_t)fdata->EndOfFile.HighPart) << 32);
185+
filetime_to_timespec((FILETIME *)&(fdata->LastAccessTime), &(fse->u.s.st_atim));
186+
filetime_to_timespec((FILETIME *)&(fdata->LastWriteTime), &(fse->u.s.st_mtim));
187+
filetime_to_timespec((FILETIME *)&(fdata->CreationTime), &(fse->u.s.st_ctim));
167188

168189
return fse;
169190
}
@@ -176,8 +197,10 @@ static struct fsentry *fseentry_create_entry(struct fscache *cache, struct fsent
176197
static struct fsentry *fsentry_create_list(struct fscache *cache, const struct fsentry *dir,
177198
int *dir_not_found)
178199
{
179-
wchar_t pattern[MAX_PATH + 2]; /* + 2 for '/' '*' */
180-
WIN32_FIND_DATAW fdata;
200+
wchar_t pattern[MAX_PATH];
201+
NTSTATUS status;
202+
IO_STATUS_BLOCK iosb;
203+
PFILE_FULL_DIR_INFORMATION di;
181204
HANDLE h;
182205
int wlen;
183206
struct fsentry *list, **phead;
@@ -192,15 +215,18 @@ static struct fsentry *fsentry_create_list(struct fscache *cache, const struct f
192215
return NULL;
193216
}
194217

195-
/* append optional '/' and wildcard '*' */
196-
if (wlen)
197-
pattern[wlen++] = '/';
198-
pattern[wlen++] = '*';
199-
pattern[wlen] = 0;
218+
/* handle CWD */
219+
if (!wlen) {
220+
wlen = GetCurrentDirectoryW(ARRAY_SIZE(pattern), pattern);
221+
if (!wlen || wlen >= ARRAY_SIZE(pattern)) {
222+
errno = wlen ? ENAMETOOLONG : err_win_to_posix(GetLastError());
223+
return NULL;
224+
}
225+
}
200226

201-
/* open find handle */
202-
h = FindFirstFileExW(pattern, FindExInfoBasic, &fdata, FindExSearchNameMatch,
203-
NULL, FIND_FIRST_EX_LARGE_FETCH);
227+
h = CreateFileW(pattern, FILE_LIST_DIRECTORY,
228+
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
229+
NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
204230
if (h == INVALID_HANDLE_VALUE) {
205231
err = GetLastError();
206232
*dir_not_found = 1; /* or empty directory */
@@ -216,22 +242,54 @@ static struct fsentry *fsentry_create_list(struct fscache *cache, const struct f
216242

217243
/* walk directory and build linked list of fsentry structures */
218244
phead = &list->next;
219-
do {
220-
*phead = fseentry_create_entry(cache, list, &fdata);
245+
status = NtQueryDirectoryFile(h, NULL, 0, 0, &iosb, cache->buffer,
246+
sizeof(cache->buffer), FileFullDirectoryInformation, FALSE, NULL, FALSE);
247+
if (!NT_SUCCESS(status)) {
248+
/*
249+
* NtQueryDirectoryFile returns STATUS_INVALID_PARAMETER when
250+
* asked to enumerate an invalid directory (ie it is a file
251+
* instead of a directory). Verify that is the actual cause
252+
* of the error.
253+
*/
254+
if (status == STATUS_INVALID_PARAMETER) {
255+
DWORD attributes = GetFileAttributesW(pattern);
256+
if (!(attributes & FILE_ATTRIBUTE_DIRECTORY))
257+
status = ERROR_DIRECTORY;
258+
}
259+
goto Error;
260+
}
261+
di = (PFILE_FULL_DIR_INFORMATION)(cache->buffer);
262+
for (;;) {
263+
264+
*phead = fseentry_create_entry(cache, list, di);
221265
phead = &(*phead)->next;
222-
} while (FindNextFileW(h, &fdata));
223266

224-
/* remember result of last FindNextFile, then close find handle */
225-
err = GetLastError();
226-
FindClose(h);
267+
/* If there is no offset in the entry, the buffer has been exhausted. */
268+
if (di->NextEntryOffset == 0) {
269+
status = NtQueryDirectoryFile(h, NULL, 0, 0, &iosb, cache->buffer,
270+
sizeof(cache->buffer), FileFullDirectoryInformation, FALSE, NULL, FALSE);
271+
if (!NT_SUCCESS(status)) {
272+
if (status == STATUS_NO_MORE_FILES)
273+
break;
274+
goto Error;
275+
}
276+
277+
di = (PFILE_FULL_DIR_INFORMATION)(cache->buffer);
278+
continue;
279+
}
280+
281+
/* Advance to the next entry. */
282+
di = (PFILE_FULL_DIR_INFORMATION)(((PUCHAR)di) + di->NextEntryOffset);
283+
}
227284

228-
/* return the list if we've got all the files */
229-
if (err == ERROR_NO_MORE_FILES)
230-
return list;
285+
CloseHandle(h);
286+
return list;
231287

232-
/* otherwise release the list and return error */
288+
Error:
289+
trace_printf_key(&trace_fscache, "fscache: status(%ld) unable to query directory contents '%.*s'\n",
290+
status, dir->len, dir->name);
291+
CloseHandle(h);
233292
fsentry_release(list);
234-
errno = err_win_to_posix(err);
235293
return NULL;
236294
}
237295

compat/win32/ntifs.h

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
#ifndef _NTIFS_
2+
#define _NTIFS_
3+
4+
/*
5+
* Copy necessary structures and definitions out of the Windows DDK
6+
* to enable calling NtQueryDirectoryFile()
7+
*/
8+
9+
typedef _Return_type_success_(return >= 0) LONG NTSTATUS;
10+
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
11+
12+
typedef struct _UNICODE_STRING {
13+
USHORT Length;
14+
USHORT MaximumLength;
15+
#ifdef MIDL_PASS
16+
[size_is(MaximumLength / 2), length_is((Length) / 2)] USHORT * Buffer;
17+
#else // MIDL_PASS
18+
_Field_size_bytes_part_(MaximumLength, Length) PWCH Buffer;
19+
#endif // MIDL_PASS
20+
} UNICODE_STRING;
21+
typedef UNICODE_STRING *PUNICODE_STRING;
22+
typedef const UNICODE_STRING *PCUNICODE_STRING;
23+
24+
typedef enum _FILE_INFORMATION_CLASS {
25+
FileDirectoryInformation = 1,
26+
FileFullDirectoryInformation,
27+
FileBothDirectoryInformation,
28+
FileBasicInformation,
29+
FileStandardInformation,
30+
FileInternalInformation,
31+
FileEaInformation,
32+
FileAccessInformation,
33+
FileNameInformation,
34+
FileRenameInformation,
35+
FileLinkInformation,
36+
FileNamesInformation,
37+
FileDispositionInformation,
38+
FilePositionInformation,
39+
FileFullEaInformation,
40+
FileModeInformation,
41+
FileAlignmentInformation,
42+
FileAllInformation,
43+
FileAllocationInformation,
44+
FileEndOfFileInformation,
45+
FileAlternateNameInformation,
46+
FileStreamInformation,
47+
FilePipeInformation,
48+
FilePipeLocalInformation,
49+
FilePipeRemoteInformation,
50+
FileMailslotQueryInformation,
51+
FileMailslotSetInformation,
52+
FileCompressionInformation,
53+
FileObjectIdInformation,
54+
FileCompletionInformation,
55+
FileMoveClusterInformation,
56+
FileQuotaInformation,
57+
FileReparsePointInformation,
58+
FileNetworkOpenInformation,
59+
FileAttributeTagInformation,
60+
FileTrackingInformation,
61+
FileIdBothDirectoryInformation,
62+
FileIdFullDirectoryInformation,
63+
FileValidDataLengthInformation,
64+
FileShortNameInformation,
65+
FileIoCompletionNotificationInformation,
66+
FileIoStatusBlockRangeInformation,
67+
FileIoPriorityHintInformation,
68+
FileSfioReserveInformation,
69+
FileSfioVolumeInformation,
70+
FileHardLinkInformation,
71+
FileProcessIdsUsingFileInformation,
72+
FileNormalizedNameInformation,
73+
FileNetworkPhysicalNameInformation,
74+
FileIdGlobalTxDirectoryInformation,
75+
FileIsRemoteDeviceInformation,
76+
FileAttributeCacheInformation,
77+
FileNumaNodeInformation,
78+
FileStandardLinkInformation,
79+
FileRemoteProtocolInformation,
80+
FileMaximumInformation
81+
} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS;
82+
83+
typedef struct _FILE_FULL_DIR_INFORMATION {
84+
ULONG NextEntryOffset;
85+
ULONG FileIndex;
86+
LARGE_INTEGER CreationTime;
87+
LARGE_INTEGER LastAccessTime;
88+
LARGE_INTEGER LastWriteTime;
89+
LARGE_INTEGER ChangeTime;
90+
LARGE_INTEGER EndOfFile;
91+
LARGE_INTEGER AllocationSize;
92+
ULONG FileAttributes;
93+
ULONG FileNameLength;
94+
ULONG EaSize;
95+
WCHAR FileName[1];
96+
} FILE_FULL_DIR_INFORMATION, *PFILE_FULL_DIR_INFORMATION;
97+
98+
typedef struct _IO_STATUS_BLOCK {
99+
union {
100+
NTSTATUS Status;
101+
PVOID Pointer;
102+
} u;
103+
ULONG_PTR Information;
104+
} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
105+
106+
typedef VOID
107+
(NTAPI *PIO_APC_ROUTINE)(
108+
IN PVOID ApcContext,
109+
IN PIO_STATUS_BLOCK IoStatusBlock,
110+
IN ULONG Reserved);
111+
112+
NTSYSCALLAPI
113+
NTSTATUS
114+
NTAPI
115+
NtQueryDirectoryFile(
116+
_In_ HANDLE FileHandle,
117+
_In_opt_ HANDLE Event,
118+
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
119+
_In_opt_ PVOID ApcContext,
120+
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
121+
_Out_writes_bytes_(Length) PVOID FileInformation,
122+
_In_ ULONG Length,
123+
_In_ FILE_INFORMATION_CLASS FileInformationClass,
124+
_In_ BOOLEAN ReturnSingleEntry,
125+
_In_opt_ PUNICODE_STRING FileName,
126+
_In_ BOOLEAN RestartScan
127+
);
128+
129+
#define STATUS_NO_MORE_FILES ((NTSTATUS)0x80000006L)
130+
131+
#endif

0 commit comments

Comments
 (0)