forked from winsiderss/systeminformer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkqueue.c
More file actions
501 lines (411 loc) · 14.2 KB
/
Copy pathworkqueue.c
File metadata and controls
501 lines (411 loc) · 14.2 KB
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/*
* Process Hacker -
* thread pool / work queue
*
* Copyright (C) 2009-2016 wj32
*
* This file is part of Process Hacker.
*
* Process Hacker is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Process Hacker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Process Hacker. If not, see <http://www.gnu.org/licenses/>.
*/
#include <phbase.h>
#include <workqueue.h>
#include <phintrnl.h>
#include <phnativeinl.h>
#include <workqueuep.h>
static PH_INITONCE PhWorkQueueInitOnce = PH_INITONCE_INIT;
static PH_FREE_LIST PhWorkQueueItemFreeList;
static PH_INITONCE PhGlobalWorkQueueInitOnce = PH_INITONCE_INIT;
static PH_WORK_QUEUE PhGlobalWorkQueue;
#ifdef DEBUG
PPH_LIST PhDbgWorkQueueList;
PH_QUEUED_LOCK PhDbgWorkQueueListLock = PH_QUEUED_LOCK_INIT;
#endif
/**
* Initializes a work queue.
*
* \param WorkQueue A work queue object.
* \param MinimumThreads The suggested minimum number of threads to keep alive, even when there is
* no work to be performed.
* \param MaximumThreads The suggested maximum number of threads to create.
* \param NoWorkTimeout The number of milliseconds after which threads without work will terminate.
*/
VOID PhInitializeWorkQueue(
_Out_ PPH_WORK_QUEUE WorkQueue,
_In_ ULONG MinimumThreads,
_In_ ULONG MaximumThreads,
_In_ ULONG NoWorkTimeout
)
{
if (PhBeginInitOnce(&PhWorkQueueInitOnce))
{
PhInitializeFreeList(&PhWorkQueueItemFreeList, sizeof(PH_WORK_QUEUE_ITEM), 32);
#ifdef DEBUG
PhDbgWorkQueueList = PhCreateList(4);
#endif
PhEndInitOnce(&PhWorkQueueInitOnce);
}
PhInitializeRundownProtection(&WorkQueue->RundownProtect);
WorkQueue->Terminating = FALSE;
InitializeListHead(&WorkQueue->QueueListHead);
PhInitializeQueuedLock(&WorkQueue->QueueLock);
PhInitializeCondition(&WorkQueue->QueueEmptyCondition);
WorkQueue->MinimumThreads = MinimumThreads;
WorkQueue->MaximumThreads = MaximumThreads;
WorkQueue->NoWorkTimeout = NoWorkTimeout;
PhInitializeQueuedLock(&WorkQueue->StateLock);
WorkQueue->SemaphoreHandle = NULL;
WorkQueue->CurrentThreads = 0;
WorkQueue->BusyCount = 0;
#ifdef DEBUG
PhAcquireQueuedLockExclusive(&PhDbgWorkQueueListLock);
PhAddItemList(PhDbgWorkQueueList, WorkQueue);
PhReleaseQueuedLockExclusive(&PhDbgWorkQueueListLock);
#endif
}
/**
* Frees resources used by a work queue.
*
* \param WorkQueue A work queue object.
*/
VOID PhDeleteWorkQueue(
_Inout_ PPH_WORK_QUEUE WorkQueue
)
{
PLIST_ENTRY listEntry;
PPH_WORK_QUEUE_ITEM workQueueItem;
#ifdef DEBUG
ULONG index;
#endif
#ifdef DEBUG
PhAcquireQueuedLockExclusive(&PhDbgWorkQueueListLock);
if ((index = PhFindItemList(PhDbgWorkQueueList, WorkQueue)) != -1)
PhRemoveItemList(PhDbgWorkQueueList, index);
PhReleaseQueuedLockExclusive(&PhDbgWorkQueueListLock);
#endif
// Wait for all worker threads to exit.
WorkQueue->Terminating = TRUE;
MemoryBarrier();
if (WorkQueue->SemaphoreHandle)
NtReleaseSemaphore(WorkQueue->SemaphoreHandle, WorkQueue->CurrentThreads, NULL);
PhWaitForRundownProtection(&WorkQueue->RundownProtect);
// Free all un-executed work items.
listEntry = WorkQueue->QueueListHead.Flink;
while (listEntry != &WorkQueue->QueueListHead)
{
workQueueItem = CONTAINING_RECORD(listEntry, PH_WORK_QUEUE_ITEM, ListEntry);
listEntry = listEntry->Flink;
PhpDestroyWorkQueueItem(workQueueItem);
}
if (WorkQueue->SemaphoreHandle)
NtClose(WorkQueue->SemaphoreHandle);
}
/**
* Waits for all queued work items to be executed.
*
* \param WorkQueue A work queue object.
*/
VOID PhWaitForWorkQueue(
_Inout_ PPH_WORK_QUEUE WorkQueue
)
{
PhAcquireQueuedLockExclusive(&WorkQueue->QueueLock);
while (!IsListEmpty(&WorkQueue->QueueListHead))
PhWaitForCondition(&WorkQueue->QueueEmptyCondition, &WorkQueue->QueueLock, NULL);
PhReleaseQueuedLockExclusive(&WorkQueue->QueueLock);
}
/**
* Queues a work item to a work queue.
*
* \param WorkQueue A work queue object.
* \param Function A function to execute.
* \param Context A user-defined value to pass to the function.
*/
VOID PhQueueItemWorkQueue(
_Inout_ PPH_WORK_QUEUE WorkQueue,
_In_ PUSER_THREAD_START_ROUTINE Function,
_In_opt_ PVOID Context
)
{
PhQueueItemWorkQueueEx(WorkQueue, Function, Context, NULL, NULL);
}
/**
* Queues a work item to a work queue.
*
* \param WorkQueue A work queue object.
* \param Function A function to execute.
* \param Context A user-defined value to pass to the function.
* \param DeleteFunction A callback function that is executed when the work queue item is about to
* be freed.
* \param Environment Execution environment parameters (e.g. priority).
*/
VOID PhQueueItemWorkQueueEx(
_Inout_ PPH_WORK_QUEUE WorkQueue,
_In_ PUSER_THREAD_START_ROUTINE Function,
_In_opt_ PVOID Context,
_In_opt_ PPH_WORK_QUEUE_ITEM_DELETE_FUNCTION DeleteFunction,
_In_opt_ PPH_WORK_QUEUE_ENVIRONMENT Environment
)
{
PPH_WORK_QUEUE_ITEM workQueueItem;
workQueueItem = PhpCreateWorkQueueItem(Function, Context, DeleteFunction, Environment);
// Enqueue the work item.
PhAcquireQueuedLockExclusive(&WorkQueue->QueueLock);
InsertTailList(&WorkQueue->QueueListHead, &workQueueItem->ListEntry);
_InterlockedIncrement(&WorkQueue->BusyCount);
PhReleaseQueuedLockExclusive(&WorkQueue->QueueLock);
// Signal the semaphore once to let a worker thread continue.
NtReleaseSemaphore(PhpGetSemaphoreWorkQueue(WorkQueue), 1, NULL);
PHLIB_INC_STATISTIC(WqWorkItemsQueued);
// Check if all worker threads are currently busy, and if we can create more threads.
if (WorkQueue->BusyCount >= WorkQueue->CurrentThreads &&
WorkQueue->CurrentThreads < WorkQueue->MaximumThreads)
{
// Lock and re-check.
PhAcquireQueuedLockExclusive(&WorkQueue->StateLock);
if (WorkQueue->CurrentThreads < WorkQueue->MaximumThreads)
PhpCreateWorkQueueThread(WorkQueue);
PhReleaseQueuedLockExclusive(&WorkQueue->StateLock);
}
}
VOID PhInitializeWorkQueueEnvironment(
_Out_ PPH_WORK_QUEUE_ENVIRONMENT Environment
)
{
PhpGetDefaultWorkQueueEnvironment(Environment);
}
/** Returns a pointer to the default shared work queue. */
PPH_WORK_QUEUE PhGetGlobalWorkQueue(
VOID
)
{
if (PhBeginInitOnce(&PhGlobalWorkQueueInitOnce))
{
PhInitializeWorkQueue(
&PhGlobalWorkQueue,
0,
3,
1000
);
PhEndInitOnce(&PhGlobalWorkQueueInitOnce);
}
return &PhGlobalWorkQueue;
}
VOID PhpGetDefaultWorkQueueEnvironment(
_Out_ PPH_WORK_QUEUE_ENVIRONMENT Environment
)
{
memset(Environment, 0, sizeof(PH_WORK_QUEUE_ENVIRONMENT));
Environment->BasePriority = 0;
Environment->IoPriority = IoPriorityNormal;
Environment->PagePriority = MEMORY_PRIORITY_NORMAL;
Environment->ForceUpdate = FALSE;
}
VOID PhpUpdateWorkQueueEnvironment(
_Inout_ PPH_WORK_QUEUE_ENVIRONMENT CurrentEnvironment,
_In_ PPH_WORK_QUEUE_ENVIRONMENT NewEnvironment
)
{
if (CurrentEnvironment->BasePriority != NewEnvironment->BasePriority || NewEnvironment->ForceUpdate)
{
LONG increment;
increment = NewEnvironment->BasePriority;
if (NT_SUCCESS(PhSetThreadBasePriority(NtCurrentThread(), increment)))
{
CurrentEnvironment->BasePriority = NewEnvironment->BasePriority;
}
}
if (CurrentEnvironment->IoPriority != NewEnvironment->IoPriority || NewEnvironment->ForceUpdate)
{
IO_PRIORITY_HINT ioPriority;
ioPriority = NewEnvironment->IoPriority;
if (NT_SUCCESS(PhSetThreadIoPriority(NtCurrentThread(), ioPriority)))
{
CurrentEnvironment->IoPriority = NewEnvironment->IoPriority;
}
}
if (CurrentEnvironment->PagePriority != NewEnvironment->PagePriority || NewEnvironment->ForceUpdate)
{
ULONG pagePriority;
pagePriority = NewEnvironment->PagePriority;
if (NT_SUCCESS(PhSetThreadPagePriority(NtCurrentThread(), pagePriority)))
{
CurrentEnvironment->PagePriority = NewEnvironment->PagePriority;
}
}
}
PPH_WORK_QUEUE_ITEM PhpCreateWorkQueueItem(
_In_ PUSER_THREAD_START_ROUTINE Function,
_In_opt_ PVOID Context,
_In_opt_ PPH_WORK_QUEUE_ITEM_DELETE_FUNCTION DeleteFunction,
_In_opt_ PPH_WORK_QUEUE_ENVIRONMENT Environment
)
{
PPH_WORK_QUEUE_ITEM workQueueItem;
workQueueItem = PhAllocateFromFreeList(&PhWorkQueueItemFreeList);
workQueueItem->Function = Function;
workQueueItem->Context = Context;
workQueueItem->DeleteFunction = DeleteFunction;
if (Environment)
workQueueItem->Environment = *Environment;
else
PhpGetDefaultWorkQueueEnvironment(&workQueueItem->Environment);
return workQueueItem;
}
VOID PhpDestroyWorkQueueItem(
_In_ PPH_WORK_QUEUE_ITEM WorkQueueItem
)
{
if (WorkQueueItem->DeleteFunction)
WorkQueueItem->DeleteFunction(WorkQueueItem->Function, WorkQueueItem->Context);
PhFreeToFreeList(&PhWorkQueueItemFreeList, WorkQueueItem);
}
VOID PhpExecuteWorkQueueItem(
_Inout_ PPH_WORK_QUEUE_ITEM WorkQueueItem
)
{
WorkQueueItem->Function(WorkQueueItem->Context);
}
HANDLE PhpGetSemaphoreWorkQueue(
_Inout_ PPH_WORK_QUEUE WorkQueue
)
{
HANDLE semaphoreHandle;
semaphoreHandle = WorkQueue->SemaphoreHandle;
if (!semaphoreHandle)
{
NtCreateSemaphore(&semaphoreHandle, SEMAPHORE_ALL_ACCESS, NULL, 0, MAXLONG);
assert(semaphoreHandle);
if (_InterlockedCompareExchangePointer(
&WorkQueue->SemaphoreHandle,
semaphoreHandle,
NULL
) != NULL)
{
// Someone else created the semaphore before we did.
NtClose(semaphoreHandle);
semaphoreHandle = WorkQueue->SemaphoreHandle;
}
}
return semaphoreHandle;
}
BOOLEAN PhpCreateWorkQueueThread(
_Inout_ PPH_WORK_QUEUE WorkQueue
)
{
HANDLE threadHandle;
// Make sure the structure doesn't get deleted while the thread is running.
if (!PhAcquireRundownProtection(&WorkQueue->RundownProtect))
return FALSE;
threadHandle = PhCreateThread(0, PhpWorkQueueThreadStart, WorkQueue);
if (threadHandle)
{
PHLIB_INC_STATISTIC(WqWorkQueueThreadsCreated);
WorkQueue->CurrentThreads++;
NtClose(threadHandle);
return TRUE;
}
else
{
PHLIB_INC_STATISTIC(WqWorkQueueThreadsCreateFailed);
PhReleaseRundownProtection(&WorkQueue->RundownProtect);
return FALSE;
}
}
NTSTATUS PhpWorkQueueThreadStart(
_In_ PVOID Parameter
)
{
PH_AUTO_POOL autoPool;
PPH_WORK_QUEUE workQueue = (PPH_WORK_QUEUE)Parameter;
PH_WORK_QUEUE_ENVIRONMENT currentEnvironment;
PhInitializeAutoPool(&autoPool);
PhpGetDefaultWorkQueueEnvironment(¤tEnvironment);
while (TRUE)
{
NTSTATUS status;
HANDLE semaphoreHandle;
LARGE_INTEGER timeout;
PPH_WORK_QUEUE_ITEM workQueueItem = NULL;
// Check if we have more threads than the limit.
if (workQueue->CurrentThreads > workQueue->MaximumThreads)
{
BOOLEAN terminate = FALSE;
// Lock and re-check.
PhAcquireQueuedLockExclusive(&workQueue->StateLock);
// Check the minimum as well.
if (workQueue->CurrentThreads > workQueue->MaximumThreads &&
workQueue->CurrentThreads > workQueue->MinimumThreads)
{
workQueue->CurrentThreads--;
terminate = TRUE;
}
PhReleaseQueuedLockExclusive(&workQueue->StateLock);
if (terminate)
break;
}
semaphoreHandle = PhpGetSemaphoreWorkQueue(workQueue);
if (!workQueue->Terminating)
{
// Wait for work.
status = NtWaitForSingleObject(
semaphoreHandle,
FALSE,
PhTimeoutFromMilliseconds(&timeout, workQueue->NoWorkTimeout)
);
}
else
{
status = STATUS_UNSUCCESSFUL;
}
if (status == STATUS_WAIT_0 && !workQueue->Terminating)
{
PLIST_ENTRY listEntry;
// Dequeue the work item.
PhAcquireQueuedLockExclusive(&workQueue->QueueLock);
listEntry = RemoveHeadList(&workQueue->QueueListHead);
if (IsListEmpty(&workQueue->QueueListHead))
PhPulseCondition(&workQueue->QueueEmptyCondition);
PhReleaseQueuedLockExclusive(&workQueue->QueueLock);
// Make sure we got work.
if (listEntry != &workQueue->QueueListHead)
{
workQueueItem = CONTAINING_RECORD(listEntry, PH_WORK_QUEUE_ITEM, ListEntry);
PhpUpdateWorkQueueEnvironment(¤tEnvironment, &workQueueItem->Environment);
PhpExecuteWorkQueueItem(workQueueItem);
_InterlockedDecrement(&workQueue->BusyCount);
PhpDestroyWorkQueueItem(workQueueItem);
}
}
else
{
BOOLEAN terminate = FALSE;
// No work arrived before the timeout passed, or we are terminating, or some error
// occurred. Terminate the thread.
PhAcquireQueuedLockExclusive(&workQueue->StateLock);
if (workQueue->Terminating || workQueue->CurrentThreads > workQueue->MinimumThreads)
{
workQueue->CurrentThreads--;
terminate = TRUE;
}
PhReleaseQueuedLockExclusive(&workQueue->StateLock);
if (terminate)
break;
}
PhDrainAutoPool(&autoPool);
}
PhReleaseRundownProtection(&workQueue->RundownProtect);
PhDeleteAutoPool(&autoPool);
return STATUS_SUCCESS;
}