threadpool.c 91.8 KB
Newer Older
1 2 3 4
/*
 * Thread pooling
 *
 * Copyright (c) 2006 Robert Shearman
5
 * Copyright (c) 2014-2016 Sebastian Lackner
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 21
 */

22 23 24
#include "config.h"
#include "wine/port.h"

25
#include <assert.h>
26
#include <stdarg.h>
27
#include <limits.h>
28 29 30 31 32 33 34

#define NONAMELESSUNION
#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "winternl.h"

#include "wine/debug.h"
35 36
#include "wine/list.h"

37 38 39 40
#include "ntdll_misc.h"

WINE_DEFAULT_DEBUG_CHANNEL(threadpool);

41 42 43 44
/*
 * Old thread pooling API
 */

45 46 47 48 49 50
struct rtl_work_item
{
    PRTL_WORK_ITEM_ROUTINE function;
    PVOID context;
};

51 52
#define EXPIRE_NEVER       (~(ULONGLONG)0)
#define TIMER_QUEUE_MAGIC  0x516d6954   /* TimQ */
53

54
static RTL_CRITICAL_SECTION_DEBUG critsect_compl_debug;
55

56 57 58 59 60 61 62 63 64 65
static struct
{
    HANDLE                  compl_port;
    RTL_CRITICAL_SECTION    threadpool_compl_cs;
}
old_threadpool =
{
    NULL,                                       /* compl_port */
    { &critsect_compl_debug, -1, 0, 0, 0, 0 },  /* threadpool_compl_cs */
};
66

67 68
static RTL_CRITICAL_SECTION_DEBUG critsect_compl_debug =
{
69
    0, 0, &old_threadpool.threadpool_compl_cs,
70
    { &critsect_compl_debug.ProcessLocksList, &critsect_compl_debug.ProcessLocksList },
71
      0, 0, { (DWORD_PTR)(__FILE__ ": threadpool_compl_cs") }
72 73
};

74 75 76 77 78 79 80 81 82 83
struct wait_work_item
{
    HANDLE Object;
    HANDLE CancelEvent;
    WAITORTIMERCALLBACK Callback;
    PVOID Context;
    ULONG Milliseconds;
    ULONG Flags;
    HANDLE CompletionEvent;
    LONG DeleteCount;
84
    int CallbackInProgress;
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
};

struct timer_queue;
struct queue_timer
{
    struct timer_queue *q;
    struct list entry;
    ULONG runcount;             /* number of callbacks pending execution */
    RTL_WAITORTIMERCALLBACKFUNC callback;
    PVOID param;
    DWORD period;
    ULONG flags;
    ULONGLONG expire;
    BOOL destroy;               /* timer should be deleted; once set, never unset */
    HANDLE event;               /* removal event */
};

struct timer_queue
{
    DWORD magic;
    RTL_CRITICAL_SECTION cs;
    struct list timers;         /* sorted by expiration time */
    BOOL quit;                  /* queue should be deleted; once set, never unset */
    HANDLE event;
    HANDLE thread;
};

112 113 114 115 116
/*
 * Object-oriented thread pooling API
 */

#define THREADPOOL_WORKER_TIMEOUT 5000
117
#define MAXIMUM_WAITQUEUE_OBJECTS (MAXIMUM_WAIT_OBJECTS - 1)
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

/* internal threadpool representation */
struct threadpool
{
    LONG                    refcount;
    LONG                    objcount;
    BOOL                    shutdown;
    CRITICAL_SECTION        cs;
    /* pool of work items, locked via .cs */
    struct list             pool;
    RTL_CONDITION_VARIABLE  update_event;
    /* information about worker threads, locked via .cs */
    int                     max_workers;
    int                     min_workers;
    int                     num_workers;
    int                     num_busy_workers;
};

enum threadpool_objtype
{
138
    TP_OBJECT_TYPE_SIMPLE,
139
    TP_OBJECT_TYPE_WORK,
140 141
    TP_OBJECT_TYPE_TIMER,
    TP_OBJECT_TYPE_WAIT
142 143 144 145 146 147 148 149 150 151
};

/* internal threadpool object representation */
struct threadpool_object
{
    LONG                    refcount;
    BOOL                    shutdown;
    /* read-only information */
    enum threadpool_objtype type;
    struct threadpool       *pool;
152
    struct threadpool_group *group;
153
    PVOID                   userdata;
154
    PTP_CLEANUP_GROUP_CANCEL_CALLBACK group_cancel_callback;
155
    PTP_SIMPLE_CALLBACK     finalization_callback;
156
    BOOL                    may_run_long;
157
    HMODULE                 race_dll;
158 159 160
    /* information about the group, locked via .group->cs */
    struct list             group_entry;
    BOOL                    is_group_member;
161 162
    /* information about the pool, locked via .pool->cs */
    struct list             pool_entry;
163
    RTL_CONDITION_VARIABLE  finished_event;
164
    RTL_CONDITION_VARIABLE  group_finished_event;
165 166
    LONG                    num_pending_callbacks;
    LONG                    num_running_callbacks;
167
    LONG                    num_associated_callbacks;
168 169 170 171 172 173 174
    /* arguments for callback */
    union
    {
        struct
        {
            PTP_SIMPLE_CALLBACK callback;
        } simple;
175 176 177 178
        struct
        {
            PTP_WORK_CALLBACK callback;
        } work;
179 180 181
        struct
        {
            PTP_TIMER_CALLBACK callback;
182 183 184 185 186 187 188 189
            /* information about the timer, locked via timerqueue.cs */
            BOOL            timer_initialized;
            BOOL            timer_pending;
            struct list     timer_entry;
            BOOL            timer_set;
            ULONGLONG       timeout;
            LONG            period;
            LONG            window_length;
190
        } timer;
191 192 193
        struct
        {
            PTP_WAIT_CALLBACK callback;
194 195 196 197 198 199 200
            LONG            signaled;
            /* information about the wait object, locked via waitqueue.cs */
            struct waitqueue_bucket *bucket;
            BOOL            wait_pending;
            struct list     wait_entry;
            ULONGLONG       timeout;
            HANDLE          handle;
201
        } wait;
202 203 204
    } u;
};

205 206 207 208 209
/* internal threadpool instance representation */
struct threadpool_instance
{
    struct threadpool_object *object;
    DWORD                   threadid;
210
    BOOL                    associated;
211
    BOOL                    may_run_long;
212 213 214
    struct
    {
        CRITICAL_SECTION    *critical_section;
215
        HANDLE              mutex;
216 217
        HANDLE              semaphore;
        LONG                semaphore_count;
218
        HANDLE              event;
219
        HMODULE             library;
220
    } cleanup;
221 222
};

223 224 225 226 227 228 229 230 231 232
/* internal threadpool group representation */
struct threadpool_group
{
    LONG                    refcount;
    BOOL                    shutdown;
    CRITICAL_SECTION        cs;
    /* list of group members, locked via .cs */
    struct list             members;
};

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
/* global timerqueue object */
static RTL_CRITICAL_SECTION_DEBUG timerqueue_debug;

static struct
{
    CRITICAL_SECTION        cs;
    LONG                    objcount;
    BOOL                    thread_running;
    struct list             pending_timers;
    RTL_CONDITION_VARIABLE  update_event;
}
timerqueue =
{
    { &timerqueue_debug, -1, 0, 0, 0, 0 },      /* cs */
    0,                                          /* objcount */
    FALSE,                                      /* thread_running */
    LIST_INIT( timerqueue.pending_timers ),     /* pending_timers */
    RTL_CONDITION_VARIABLE_INIT                 /* update_event */
};

static RTL_CRITICAL_SECTION_DEBUG timerqueue_debug =
{
    0, 0, &timerqueue.cs,
    { &timerqueue_debug.ProcessLocksList, &timerqueue_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": timerqueue.cs") }
};

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
/* global waitqueue object */
static RTL_CRITICAL_SECTION_DEBUG waitqueue_debug;

static struct
{
    CRITICAL_SECTION        cs;
    LONG                    num_buckets;
    struct list             buckets;
}
waitqueue =
{
    { &waitqueue_debug, -1, 0, 0, 0, 0 },       /* cs */
    0,                                          /* num_buckets */
    LIST_INIT( waitqueue.buckets )              /* buckets */
};

static RTL_CRITICAL_SECTION_DEBUG waitqueue_debug =
{
    0, 0, &waitqueue.cs,
    { &waitqueue_debug.ProcessLocksList, &waitqueue_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": waitqueue.cs") }
};

struct waitqueue_bucket
{
    struct list             bucket_entry;
    LONG                    objcount;
    struct list             reserved;
    struct list             waiting;
    HANDLE                  update_event;
};

292 293 294 295 296
static inline struct threadpool *impl_from_TP_POOL( TP_POOL *pool )
{
    return (struct threadpool *)pool;
}

297 298 299 300 301 302 303
static inline struct threadpool_object *impl_from_TP_WORK( TP_WORK *work )
{
    struct threadpool_object *object = (struct threadpool_object *)work;
    assert( object->type == TP_OBJECT_TYPE_WORK );
    return object;
}

304 305 306 307 308 309 310
static inline struct threadpool_object *impl_from_TP_TIMER( TP_TIMER *timer )
{
    struct threadpool_object *object = (struct threadpool_object *)timer;
    assert( object->type == TP_OBJECT_TYPE_TIMER );
    return object;
}

311 312 313 314 315 316 317
static inline struct threadpool_object *impl_from_TP_WAIT( TP_WAIT *wait )
{
    struct threadpool_object *object = (struct threadpool_object *)wait;
    assert( object->type == TP_OBJECT_TYPE_WAIT );
    return object;
}

318 319 320 321 322
static inline struct threadpool_group *impl_from_TP_CLEANUP_GROUP( TP_CLEANUP_GROUP *group )
{
    return (struct threadpool_group *)group;
}

323 324 325 326 327
static inline struct threadpool_instance *impl_from_TP_CALLBACK_INSTANCE( TP_CALLBACK_INSTANCE *instance )
{
    return (struct threadpool_instance *)instance;
}

328
static void CALLBACK threadpool_worker_proc( void *param );
329
static void tp_object_submit( struct threadpool_object *object, BOOL signaled );
330
static void tp_object_prepare_shutdown( struct threadpool_object *object );
331
static BOOL tp_object_release( struct threadpool_object *object );
332 333
static struct threadpool *default_threadpool = NULL;

334
static inline LONG interlocked_inc( PLONG dest )
335
{
336
    return interlocked_xchg_add( dest, 1 ) + 1;
337 338
}

339
static inline LONG interlocked_dec( PLONG dest )
340
{
341
    return interlocked_xchg_add( dest, -1 ) - 1;
342 343
}

344
static void CALLBACK process_rtl_work_item( TP_CALLBACK_INSTANCE *instance, void *userdata )
345
{
346
    struct rtl_work_item *item = userdata;
347

348 349
    TRACE("executing %p(%p)\n", item->function, item->context);
    item->function( item->context );
350

351
    RtlFreeHeap( GetProcessHeap(), 0, item );
352 353 354 355 356 357 358 359
}

/***********************************************************************
 *              RtlQueueWorkItem   (NTDLL.@)
 *
 * Queues a work item into a thread in the thread pool.
 *
 * PARAMS
360 361 362
 *  function [I] Work function to execute.
 *  context  [I] Context to pass to the work function when it is executed.
 *  flags    [I] Flags. See notes.
363 364 365 366 367 368 369 370 371 372 373 374 375
 *
 * RETURNS
 *  Success: STATUS_SUCCESS.
 *  Failure: Any NTSTATUS code.
 *
 * NOTES
 *  Flags can be one or more of the following:
 *|WT_EXECUTEDEFAULT - Executes the work item in a non-I/O worker thread.
 *|WT_EXECUTEINIOTHREAD - Executes the work item in an I/O worker thread.
 *|WT_EXECUTEINPERSISTENTTHREAD - Executes the work item in a thread that is persistent.
 *|WT_EXECUTELONGFUNCTION - Hints that the execution can take a long time.
 *|WT_TRANSFER_IMPERSONATION - Executes the function with the current access token.
 */
376
NTSTATUS WINAPI RtlQueueWorkItem( PRTL_WORK_ITEM_ROUTINE function, PVOID context, ULONG flags )
377
{
378 379
    TP_CALLBACK_ENVIRON environment;
    struct rtl_work_item *item;
380 381
    NTSTATUS status;

382 383
    TRACE( "%p %p %u\n", function, context, flags );

384 385
    item = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*item) );
    if (!item)
386 387
        return STATUS_NO_MEMORY;

388 389 390 391
    memset( &environment, 0, sizeof(environment) );
    environment.Version = 1;
    environment.u.s.LongFunction = (flags & WT_EXECUTELONGFUNCTION) != 0;
    environment.u.s.Persistent   = (flags & WT_EXECUTEINPERSISTENTTHREAD) != 0;
392

393 394
    item->function = function;
    item->context  = context;
395

396 397
    status = TpSimpleTryPost( process_rtl_work_item, item, &environment );
    if (status) RtlFreeHeap( GetProcessHeap(), 0, item );
398
    return status;
399
}
400 401 402 403 404 405

/***********************************************************************
 * iocp_poller - get completion events and run callbacks
 */
static DWORD CALLBACK iocp_poller(LPVOID Arg)
{
406 407
    HANDLE cport = Arg;

408 409 410 411 412
    while( TRUE )
    {
        PRTL_OVERLAPPED_COMPLETION_ROUTINE callback;
        LPVOID overlapped;
        IO_STATUS_BLOCK iosb;
413
        NTSTATUS res = NtRemoveIoCompletion( cport, (PULONG_PTR)&callback, (PULONG_PTR)&overlapped, &iosb, NULL );
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        if (res)
        {
            ERR("NtRemoveIoCompletion failed: 0x%x\n", res);
        }
        else
        {
            DWORD transferred = 0;
            DWORD err = 0;

            if (iosb.u.Status == STATUS_SUCCESS)
                transferred = iosb.Information;
            else
                err = RtlNtStatusToDosError(iosb.u.Status);

            callback( err, transferred, overlapped );
        }
    }
431
    return 0;
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
}

/***********************************************************************
 *              RtlSetIoCompletionCallback  (NTDLL.@)
 *
 * Binds a handle to a thread pool's completion port, and possibly
 * starts a non-I/O thread to monitor this port and call functions back.
 *
 * PARAMS
 *  FileHandle [I] Handle to bind to a completion port.
 *  Function   [I] Callback function to call on I/O completions.
 *  Flags      [I] Not used.
 *
 * RETURNS
 *  Success: STATUS_SUCCESS.
 *  Failure: Any NTSTATUS code.
 *
 */
NTSTATUS WINAPI RtlSetIoCompletionCallback(HANDLE FileHandle, PRTL_OVERLAPPED_COMPLETION_ROUTINE Function, ULONG Flags)
{
    IO_STATUS_BLOCK iosb;
    FILE_COMPLETION_INFORMATION info;

    if (Flags) FIXME("Unknown value Flags=0x%x\n", Flags);

457
    if (!old_threadpool.compl_port)
458 459 460
    {
        NTSTATUS res = STATUS_SUCCESS;

461 462
        RtlEnterCriticalSection(&old_threadpool.threadpool_compl_cs);
        if (!old_threadpool.compl_port)
463 464 465 466 467 468 469
        {
            HANDLE cport;

            res = NtCreateIoCompletion( &cport, IO_COMPLETION_ALL_ACCESS, NULL, 0 );
            if (!res)
            {
                /* FIXME native can start additional threads in case of e.g. hung callback function. */
470
                res = RtlQueueWorkItem( iocp_poller, cport, WT_EXECUTEDEFAULT );
471
                if (!res)
472
                    old_threadpool.compl_port = cport;
473 474 475 476
                else
                    NtClose( cport );
            }
        }
477
        RtlLeaveCriticalSection(&old_threadpool.threadpool_compl_cs);
478 479 480
        if (res) return res;
    }

481
    info.CompletionPort = old_threadpool.compl_port;
482 483 484 485
    info.CompletionKey = (ULONG_PTR)Function;

    return NtSetInformationFile( FileHandle, &iosb, &info, sizeof(info), FileCompletionInformation );
}
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503

static inline PLARGE_INTEGER get_nt_timeout( PLARGE_INTEGER pTime, ULONG timeout )
{
    if (timeout == INFINITE) return NULL;
    pTime->QuadPart = (ULONGLONG)timeout * -10000;
    return pTime;
}

static void delete_wait_work_item(struct wait_work_item *wait_work_item)
{
    NtClose( wait_work_item->CancelEvent );
    RtlFreeHeap( GetProcessHeap(), 0, wait_work_item );
}

static DWORD CALLBACK wait_thread_proc(LPVOID Arg)
{
    struct wait_work_item *wait_work_item = Arg;
    NTSTATUS status;
504
    BOOLEAN alertable = (wait_work_item->Flags & WT_EXECUTEINIOTHREAD) != 0;
505 506 507 508 509 510 511 512
    HANDLE handles[2] = { wait_work_item->Object, wait_work_item->CancelEvent };
    LARGE_INTEGER timeout;
    HANDLE completion_event;

    TRACE("\n");

    while (TRUE)
    {
513
        status = NtWaitForMultipleObjects( 2, handles, TRUE, alertable,
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
                                           get_nt_timeout( &timeout, wait_work_item->Milliseconds ) );
        if (status == STATUS_WAIT_0 || status == STATUS_TIMEOUT)
        {
            BOOLEAN TimerOrWaitFired;

            if (status == STATUS_WAIT_0)
            {
                TRACE( "object %p signaled, calling callback %p with context %p\n",
                    wait_work_item->Object, wait_work_item->Callback,
                    wait_work_item->Context );
                TimerOrWaitFired = FALSE;
            }
            else
            {
                TRACE( "wait for object %p timed out, calling callback %p with context %p\n",
                    wait_work_item->Object, wait_work_item->Callback,
                    wait_work_item->Context );
                TimerOrWaitFired = TRUE;
            }
533 534 535 536 537 538
            interlocked_xchg( &wait_work_item->CallbackInProgress, TRUE );
            if (wait_work_item->CompletionEvent)
            {
                TRACE( "Work has been canceled.\n" );
                break;
            }
539
            wait_work_item->Callback( wait_work_item->Context, TimerOrWaitFired );
540
            interlocked_xchg( &wait_work_item->CallbackInProgress, FALSE );
541 542 543 544

            if (wait_work_item->Flags & WT_EXECUTEONLYONCE)
                break;
        }
545
        else if (status != STATUS_USER_APC)
546 547 548 549 550
            break;
    }


    if (interlocked_inc( &wait_work_item->DeleteCount ) == 2 )
551 552
    {
        completion_event = wait_work_item->CompletionEvent;
553
        delete_wait_work_item( wait_work_item );
554 555
        if (completion_event && completion_event != INVALID_HANDLE_VALUE)
            NtSetEvent( completion_event, NULL );
556
    }
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607

    return 0;
}

/***********************************************************************
 *              RtlRegisterWait   (NTDLL.@)
 *
 * Registers a wait for a handle to become signaled.
 *
 * PARAMS
 *  NewWaitObject [I] Handle to the new wait object. Use RtlDeregisterWait() to free it.
 *  Object   [I] Object to wait to become signaled.
 *  Callback [I] Callback function to execute when the wait times out or the handle is signaled.
 *  Context  [I] Context to pass to the callback function when it is executed.
 *  Milliseconds [I] Number of milliseconds to wait before timing out.
 *  Flags    [I] Flags. See notes.
 *
 * RETURNS
 *  Success: STATUS_SUCCESS.
 *  Failure: Any NTSTATUS code.
 *
 * NOTES
 *  Flags can be one or more of the following:
 *|WT_EXECUTEDEFAULT - Executes the work item in a non-I/O worker thread.
 *|WT_EXECUTEINIOTHREAD - Executes the work item in an I/O worker thread.
 *|WT_EXECUTEINPERSISTENTTHREAD - Executes the work item in a thread that is persistent.
 *|WT_EXECUTELONGFUNCTION - Hints that the execution can take a long time.
 *|WT_TRANSFER_IMPERSONATION - Executes the function with the current access token.
 */
NTSTATUS WINAPI RtlRegisterWait(PHANDLE NewWaitObject, HANDLE Object,
                                RTL_WAITORTIMERCALLBACKFUNC Callback,
                                PVOID Context, ULONG Milliseconds, ULONG Flags)
{
    struct wait_work_item *wait_work_item;
    NTSTATUS status;

    TRACE( "(%p, %p, %p, %p, %d, 0x%x)\n", NewWaitObject, Object, Callback, Context, Milliseconds, Flags );

    wait_work_item = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wait_work_item) );
    if (!wait_work_item)
        return STATUS_NO_MEMORY;

    wait_work_item->Object = Object;
    wait_work_item->Callback = Callback;
    wait_work_item->Context = Context;
    wait_work_item->Milliseconds = Milliseconds;
    wait_work_item->Flags = Flags;
    wait_work_item->CallbackInProgress = FALSE;
    wait_work_item->DeleteCount = 0;
    wait_work_item->CompletionEvent = NULL;

608
    status = NtCreateEvent( &wait_work_item->CancelEvent, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE );
609 610 611 612 613 614
    if (status != STATUS_SUCCESS)
    {
        RtlFreeHeap( GetProcessHeap(), 0, wait_work_item );
        return status;
    }

615 616 617
    Flags = Flags & (WT_EXECUTEINIOTHREAD | WT_EXECUTEINPERSISTENTTHREAD |
                     WT_EXECUTELONGFUNCTION | WT_TRANSFER_IMPERSONATION);
    status = RtlQueueWorkItem( wait_thread_proc, wait_work_item, Flags );
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    if (status != STATUS_SUCCESS)
    {
        delete_wait_work_item( wait_work_item );
        return status;
    }

    *NewWaitObject = wait_work_item;
    return status;
}

/***********************************************************************
 *              RtlDeregisterWaitEx   (NTDLL.@)
 *
 * Cancels a wait operation and frees the resources associated with calling
 * RtlRegisterWait().
 *
 * PARAMS
 *  WaitObject [I] Handle to the wait object to free.
 *
 * RETURNS
 *  Success: STATUS_SUCCESS.
 *  Failure: Any NTSTATUS code.
 */
NTSTATUS WINAPI RtlDeregisterWaitEx(HANDLE WaitHandle, HANDLE CompletionEvent)
{
    struct wait_work_item *wait_work_item = WaitHandle;
644 645
    NTSTATUS status;
    HANDLE LocalEvent = NULL;
646
    int CallbackInProgress;
647

648
    TRACE( "(%p %p)\n", WaitHandle, CompletionEvent );
649

650 651 652
    if (WaitHandle == NULL)
        return STATUS_INVALID_HANDLE;

653
    interlocked_xchg_ptr( &wait_work_item->CompletionEvent, INVALID_HANDLE_VALUE );
654
    CallbackInProgress = wait_work_item->CallbackInProgress;
655
    TRACE( "callback in progress %u\n", CallbackInProgress );
656
    if (CompletionEvent == INVALID_HANDLE_VALUE || !CallbackInProgress)
657
    {
658 659 660 661 662 663 664 665
        status = NtCreateEvent( &LocalEvent, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE );
        if (status != STATUS_SUCCESS)
            return status;
        interlocked_xchg_ptr( &wait_work_item->CompletionEvent, LocalEvent );
    }
    else if (CompletionEvent != NULL)
    {
        interlocked_xchg_ptr( &wait_work_item->CompletionEvent, CompletionEvent );
666 667
    }

668 669
    NtSetEvent( wait_work_item->CancelEvent, NULL );

670 671 672 673 674
    if (interlocked_inc( &wait_work_item->DeleteCount ) == 2 )
    {
        status = STATUS_SUCCESS;
        delete_wait_work_item( wait_work_item );
    }
675 676
    else if (LocalEvent)
    {
677
        TRACE( "Waiting for completion event\n" );
678 679 680 681 682 683 684 685 686 687
        NtWaitForSingleObject( LocalEvent, FALSE, NULL );
        status = STATUS_SUCCESS;
    }
    else
    {
        status = STATUS_PENDING;
    }

    if (LocalEvent)
        NtClose( LocalEvent );
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708

    return status;
}

/***********************************************************************
 *              RtlDeregisterWait   (NTDLL.@)
 *
 * Cancels a wait operation and frees the resources associated with calling
 * RtlRegisterWait().
 *
 * PARAMS
 *  WaitObject [I] Handle to the wait object to free.
 *
 * RETURNS
 *  Success: STATUS_SUCCESS.
 *  Failure: Any NTSTATUS code.
 */
NTSTATUS WINAPI RtlDeregisterWait(HANDLE WaitHandle)
{
    return RtlDeregisterWaitEx(WaitHandle, NULL);
}
709 710 711 712


/************************** Timer Queue Impl **************************/

713 714
static void queue_remove_timer(struct queue_timer *t)
{
715 716 717 718 719 720 721 722
    /* We MUST hold the queue cs while calling this function.  This ensures
       that we cannot queue another callback for this timer.  The runcount
       being zero makes sure we don't have any already queued.  */
    struct timer_queue *q = t->q;

    assert(t->runcount == 0);
    assert(t->destroy);

723
    list_remove(&t->entry);
724 725
    if (t->event)
        NtSetEvent(t->event, NULL);
726
    RtlFreeHeap(GetProcessHeap(), 0, t);
727

728
    if (q->quit && list_empty(&q->timers))
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
        NtSetEvent(q->event, NULL);
}

static void timer_cleanup_callback(struct queue_timer *t)
{
    struct timer_queue *q = t->q;
    RtlEnterCriticalSection(&q->cs);

    assert(0 < t->runcount);
    --t->runcount;

    if (t->destroy && t->runcount == 0)
        queue_remove_timer(t);

    RtlLeaveCriticalSection(&q->cs);
}

static DWORD WINAPI timer_callback_wrapper(LPVOID p)
{
    struct queue_timer *t = p;
    t->callback(t->param, TRUE);
    timer_cleanup_callback(t);
    return 0;
}

static inline ULONGLONG queue_current_time(void)
{
756 757 758
    LARGE_INTEGER now, freq;
    NtQueryPerformanceCounter(&now, &freq);
    return now.QuadPart * 1000 / freq.QuadPart;
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
}

static void queue_add_timer(struct queue_timer *t, ULONGLONG time,
                            BOOL set_event)
{
    /* We MUST hold the queue cs while calling this function.  */
    struct timer_queue *q = t->q;
    struct list *ptr = &q->timers;

    assert(!q->quit || (t->destroy && time == EXPIRE_NEVER));

    if (time != EXPIRE_NEVER)
        LIST_FOR_EACH(ptr, &q->timers)
        {
            struct queue_timer *cur = LIST_ENTRY(ptr, struct queue_timer, entry);
            if (time < cur->expire)
                break;
        }
    list_add_before(ptr, &t->entry);

    t->expire = time;

    /* If we insert at the head of the list, we need to expire sooner
       than expected.  */
    if (set_event && &t->entry == list_head(&q->timers))
        NtSetEvent(q->event, NULL);
}

static inline void queue_move_timer(struct queue_timer *t, ULONGLONG time,
                                    BOOL set_event)
{
    /* We MUST hold the queue cs while calling this function.  */
    list_remove(&t->entry);
    queue_add_timer(t, time, set_event);
}

static void queue_timer_expire(struct timer_queue *q)
{
797
    struct queue_timer *t = NULL;
798 799 800 801

    RtlEnterCriticalSection(&q->cs);
    if (list_head(&q->timers))
    {
802
        ULONGLONG now, next;
803
        t = LIST_ENTRY(list_head(&q->timers), struct queue_timer, entry);
804
        if (!t->destroy && t->expire <= ((now = queue_current_time())))
805 806
        {
            ++t->runcount;
807 808 809 810 811 812 813 814 815 816
            if (t->period)
            {
                next = t->expire + t->period;
                /* avoid trigger cascade if overloaded / hibernated */
                if (next < now)
                    next = now + t->period;
            }
            else
                next = EXPIRE_NEVER;
            queue_move_timer(t, next, FALSE);
817
        }
818 819
        else
            t = NULL;
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
    }
    RtlLeaveCriticalSection(&q->cs);

    if (t)
    {
        if (t->flags & WT_EXECUTEINTIMERTHREAD)
            timer_callback_wrapper(t);
        else
        {
            ULONG flags
                = (t->flags
                   & (WT_EXECUTEINIOTHREAD | WT_EXECUTEINPERSISTENTTHREAD
                      | WT_EXECUTELONGFUNCTION | WT_TRANSFER_IMPERSONATION));
            NTSTATUS status = RtlQueueWorkItem(timer_callback_wrapper, t, flags);
            if (status != STATUS_SUCCESS)
                timer_cleanup_callback(t);
        }
    }
}

static ULONG queue_get_timeout(struct timer_queue *q)
{
    struct queue_timer *t;
    ULONG timeout = INFINITE;

    RtlEnterCriticalSection(&q->cs);
    if (list_head(&q->timers))
    {
        t = LIST_ENTRY(list_head(&q->timers), struct queue_timer, entry);
        assert(!t->destroy || t->expire == EXPIRE_NEVER);

        if (t->expire != EXPIRE_NEVER)
        {
            ULONGLONG time = queue_current_time();
            timeout = t->expire < time ? 0 : t->expire - time;
        }
    }
    RtlLeaveCriticalSection(&q->cs);

    return timeout;
}

static void WINAPI timer_queue_thread_proc(LPVOID p)
{
    struct timer_queue *q = p;
    ULONG timeout_ms;

    timeout_ms = INFINITE;
    for (;;)
    {
        LARGE_INTEGER timeout;
        NTSTATUS status;
        BOOL done = FALSE;

        status = NtWaitForSingleObject(
            q->event, FALSE, get_nt_timeout(&timeout, timeout_ms));

        if (status == STATUS_WAIT_0)
        {
            /* There are two possible ways to trigger the event.  Either
               we are quitting and the last timer got removed, or a new
               timer got put at the head of the list so we need to adjust
               our timeout.  */
            RtlEnterCriticalSection(&q->cs);
884
            if (q->quit && list_empty(&q->timers))
885 886 887 888 889 890 891 892 893 894 895 896 897 898
                done = TRUE;
            RtlLeaveCriticalSection(&q->cs);
        }
        else if (status == STATUS_TIMEOUT)
            queue_timer_expire(q);

        if (done)
            break;

        timeout_ms = queue_get_timeout(q);
    }

    NtClose(q->event);
    RtlDeleteCriticalSection(&q->cs);
899
    q->magic = 0;
900
    RtlFreeHeap(GetProcessHeap(), 0, q);
901
    RtlExitUserThread( 0 );
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
}

static void queue_destroy_timer(struct queue_timer *t)
{
    /* We MUST hold the queue cs while calling this function.  */
    t->destroy = TRUE;
    if (t->runcount == 0)
        /* Ensure a timer is promptly removed.  If callbacks are pending,
           it will be removed after the last one finishes by the callback
           cleanup wrapper.  */
        queue_remove_timer(t);
    else
        /* Make sure no destroyed timer masks an active timer at the head
           of the sorted list.  */
        queue_move_timer(t, EXPIRE_NEVER, FALSE);
917 918
}

919 920 921 922 923 924 925 926 927 928 929 930 931 932
/***********************************************************************
 *              RtlCreateTimerQueue   (NTDLL.@)
 *
 * Creates a timer queue object and returns a handle to it.
 *
 * PARAMS
 *  NewTimerQueue [O] The newly created queue.
 *
 * RETURNS
 *  Success: STATUS_SUCCESS.
 *  Failure: Any NTSTATUS code.
 */
NTSTATUS WINAPI RtlCreateTimerQueue(PHANDLE NewTimerQueue)
{
933
    NTSTATUS status;
934 935 936 937 938 939
    struct timer_queue *q = RtlAllocateHeap(GetProcessHeap(), 0, sizeof *q);
    if (!q)
        return STATUS_NO_MEMORY;

    RtlInitializeCriticalSection(&q->cs);
    list_init(&q->timers);
940
    q->quit = FALSE;
941
    q->magic = TIMER_QUEUE_MAGIC;
942
    status = NtCreateEvent(&q->event, EVENT_ALL_ACCESS, NULL, SynchronizationEvent, FALSE);
943 944 945 946 947 948 949 950 951 952 953 954 955
    if (status != STATUS_SUCCESS)
    {
        RtlFreeHeap(GetProcessHeap(), 0, q);
        return status;
    }
    status = RtlCreateUserThread(GetCurrentProcess(), NULL, FALSE, NULL, 0, 0,
                                 timer_queue_thread_proc, q, &q->thread, NULL);
    if (status != STATUS_SUCCESS)
    {
        NtClose(q->event);
        RtlFreeHeap(GetProcessHeap(), 0, q);
        return status;
    }
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979

    *NewTimerQueue = q;
    return STATUS_SUCCESS;
}

/***********************************************************************
 *              RtlDeleteTimerQueueEx   (NTDLL.@)
 *
 * Deletes a timer queue object.
 *
 * PARAMS
 *  TimerQueue      [I] The timer queue to destroy.
 *  CompletionEvent [I] If NULL, return immediately.  If INVALID_HANDLE_VALUE,
 *                      wait until all timers are finished firing before
 *                      returning.  Otherwise, return immediately and set the
 *                      event when all timers are done.
 *
 * RETURNS
 *  Success: STATUS_SUCCESS if synchronous, STATUS_PENDING if not.
 *  Failure: Any NTSTATUS code.
 */
NTSTATUS WINAPI RtlDeleteTimerQueueEx(HANDLE TimerQueue, HANDLE CompletionEvent)
{
    struct timer_queue *q = TimerQueue;
980
    struct queue_timer *t, *temp;
981
    HANDLE thread;
982
    NTSTATUS status;
983

984
    if (!q || q->magic != TIMER_QUEUE_MAGIC)
985 986 987 988
        return STATUS_INVALID_HANDLE;

    thread = q->thread;

989
    RtlEnterCriticalSection(&q->cs);
990 991 992 993 994 995 996 997 998
    q->quit = TRUE;
    if (list_head(&q->timers))
        /* When the last timer is removed, it will signal the timer thread to
           exit...  */
        LIST_FOR_EACH_ENTRY_SAFE(t, temp, &q->timers, struct queue_timer, entry)
            queue_destroy_timer(t);
    else
        /* However if we have none, we must do it ourselves.  */
        NtSetEvent(q->event, NULL);
999
    RtlLeaveCriticalSection(&q->cs);
1000 1001

    if (CompletionEvent == INVALID_HANDLE_VALUE)
1002 1003 1004 1005
    {
        NtWaitForSingleObject(thread, FALSE, NULL);
        status = STATUS_SUCCESS;
    }
1006 1007 1008
    else
    {
        if (CompletionEvent)
1009 1010 1011
        {
            FIXME("asynchronous return on completion event unimplemented\n");
            NtWaitForSingleObject(thread, FALSE, NULL);
1012
            NtSetEvent(CompletionEvent, NULL);
1013 1014
        }
        status = STATUS_PENDING;
1015
    }
1016 1017 1018

    NtClose(thread);
    return status;
1019
}
1020

1021 1022
static struct timer_queue *get_timer_queue(HANDLE TimerQueue)
{
1023 1024
    static struct timer_queue *default_timer_queue;

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    if (TimerQueue)
        return TimerQueue;
    else
    {
        if (!default_timer_queue)
        {
            HANDLE q;
            NTSTATUS status = RtlCreateTimerQueue(&q);
            if (status == STATUS_SUCCESS)
            {
                PVOID p = interlocked_cmpxchg_ptr(
                    (void **) &default_timer_queue, q, NULL);
                if (p)
                    /* Got beat to the punch.  */
1039
                    RtlDeleteTimerQueueEx(q, NULL);
1040 1041 1042 1043 1044 1045
            }
        }
        return default_timer_queue;
    }
}

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
/***********************************************************************
 *              RtlCreateTimer   (NTDLL.@)
 *
 * Creates a new timer associated with the given queue.
 *
 * PARAMS
 *  NewTimer   [O] The newly created timer.
 *  TimerQueue [I] The queue to hold the timer.
 *  Callback   [I] The callback to fire.
 *  Parameter  [I] The argument for the callback.
 *  DueTime    [I] The delay, in milliseconds, before first firing the
 *                 timer.
 *  Period     [I] The period, in milliseconds, at which to fire the timer
 *                 after the first callback.  If zero, the timer will only
 *                 fire once.  It still needs to be deleted with
 *                 RtlDeleteTimer.
1062
 * Flags       [I] Flags controlling the execution of the callback.  In
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
 *                 addition to the WT_* thread pool flags (see
 *                 RtlQueueWorkItem), WT_EXECUTEINTIMERTHREAD and
 *                 WT_EXECUTEONLYONCE are supported.
 *
 * RETURNS
 *  Success: STATUS_SUCCESS.
 *  Failure: Any NTSTATUS code.
 */
NTSTATUS WINAPI RtlCreateTimer(PHANDLE NewTimer, HANDLE TimerQueue,
                               RTL_WAITORTIMERCALLBACKFUNC Callback,
                               PVOID Parameter, DWORD DueTime, DWORD Period,
                               ULONG Flags)
{
1076
    NTSTATUS status;
1077 1078
    struct queue_timer *t;
    struct timer_queue *q = get_timer_queue(TimerQueue);
1079 1080 1081

    if (!q) return STATUS_NO_MEMORY;
    if (q->magic != TIMER_QUEUE_MAGIC) return STATUS_INVALID_HANDLE;
1082 1083

    t = RtlAllocateHeap(GetProcessHeap(), 0, sizeof *t);
1084 1085 1086
    if (!t)
        return STATUS_NO_MEMORY;

1087 1088 1089 1090 1091 1092 1093
    t->q = q;
    t->runcount = 0;
    t->callback = Callback;
    t->param = Parameter;
    t->period = Period;
    t->flags = Flags;
    t->destroy = FALSE;
1094
    t->event = NULL;
1095

1096
    status = STATUS_SUCCESS;
1097
    RtlEnterCriticalSection(&q->cs);
1098 1099 1100 1101
    if (q->quit)
        status = STATUS_INVALID_HANDLE;
    else
        queue_add_timer(t, queue_current_time() + DueTime, TRUE);
1102 1103
    RtlLeaveCriticalSection(&q->cs);

1104 1105 1106 1107 1108 1109
    if (status == STATUS_SUCCESS)
        *NewTimer = t;
    else
        RtlFreeHeap(GetProcessHeap(), 0, t);

    return status;
1110
}
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

/***********************************************************************
 *              RtlUpdateTimer   (NTDLL.@)
 *
 * Changes the time at which a timer expires.
 *
 * PARAMS
 *  TimerQueue [I] The queue that holds the timer.
 *  Timer      [I] The timer to update.
 *  DueTime    [I] The delay, in milliseconds, before next firing the timer.
 *  Period     [I] The period, in milliseconds, at which to fire the timer
 *                 after the first callback.  If zero, the timer will not
 *                 refire once.  It still needs to be deleted with
 *                 RtlDeleteTimer.
 *
 * RETURNS
 *  Success: STATUS_SUCCESS.
 *  Failure: Any NTSTATUS code.
 */
NTSTATUS WINAPI RtlUpdateTimer(HANDLE TimerQueue, HANDLE Timer,
                               DWORD DueTime, DWORD Period)
{
    struct queue_timer *t = Timer;
1134
    struct timer_queue *q = t->q;
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

    RtlEnterCriticalSection(&q->cs);
    /* Can't change a timer if it was once-only or destroyed.  */
    if (t->expire != EXPIRE_NEVER)
    {
        t->period = Period;
        queue_move_timer(t, queue_current_time() + DueTime, TRUE);
    }
    RtlLeaveCriticalSection(&q->cs);

    return STATUS_SUCCESS;
}
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169

/***********************************************************************
 *              RtlDeleteTimer   (NTDLL.@)
 *
 * Cancels a timer-queue timer.
 *
 * PARAMS
 *  TimerQueue      [I] The queue that holds the timer.
 *  Timer           [I] The timer to update.
 *  CompletionEvent [I] If NULL, return immediately.  If INVALID_HANDLE_VALUE,
 *                      wait until the timer is finished firing all pending
 *                      callbacks before returning.  Otherwise, return
 *                      immediately and set the timer is done.
 *
 * RETURNS
 *  Success: STATUS_SUCCESS if the timer is done, STATUS_PENDING if not,
             or if the completion event is NULL.
 *  Failure: Any NTSTATUS code.
 */
NTSTATUS WINAPI RtlDeleteTimer(HANDLE TimerQueue, HANDLE Timer,
                               HANDLE CompletionEvent)
{
    struct queue_timer *t = Timer;
1170
    struct timer_queue *q;
1171 1172 1173
    NTSTATUS status = STATUS_PENDING;
    HANDLE event = NULL;

1174 1175 1176
    if (!Timer)
        return STATUS_INVALID_PARAMETER_1;
    q = t->q;
1177
    if (CompletionEvent == INVALID_HANDLE_VALUE)
1178
    {
1179
        status = NtCreateEvent(&event, EVENT_ALL_ACCESS, NULL, SynchronizationEvent, FALSE);
1180 1181 1182
        if (status == STATUS_SUCCESS)
            status = STATUS_PENDING;
    }
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
    else if (CompletionEvent)
        event = CompletionEvent;

    RtlEnterCriticalSection(&q->cs);
    t->event = event;
    if (t->runcount == 0 && event)
        status = STATUS_SUCCESS;
    queue_destroy_timer(t);
    RtlLeaveCriticalSection(&q->cs);

    if (CompletionEvent == INVALID_HANDLE_VALUE && event)
    {
        if (status == STATUS_PENDING)
1196
        {
1197
            NtWaitForSingleObject(event, FALSE, NULL);
1198 1199
            status = STATUS_SUCCESS;
        }
1200 1201 1202 1203 1204
        NtClose(event);
    }

    return status;
}
1205

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
/***********************************************************************
 *           timerqueue_thread_proc    (internal)
 */
static void CALLBACK timerqueue_thread_proc( void *param )
{
    ULONGLONG timeout_lower, timeout_upper, new_timeout;
    struct threadpool_object *other_timer;
    LARGE_INTEGER now, timeout;
    struct list *ptr;

    TRACE( "starting timer queue thread\n" );

    RtlEnterCriticalSection( &timerqueue.cs );
    for (;;)
    {
        NtQuerySystemTime( &now );

        /* Check for expired timers. */
        while ((ptr = list_head( &timerqueue.pending_timers )))
        {
            struct threadpool_object *timer = LIST_ENTRY( ptr, struct threadpool_object, u.timer.timer_entry );
            assert( timer->type == TP_OBJECT_TYPE_TIMER );
            assert( timer->u.timer.timer_pending );
            if (timer->u.timer.timeout > now.QuadPart)
                break;

            /* Queue a new callback in one of the worker threads. */
            list_remove( &timer->u.timer.timer_entry );
            timer->u.timer.timer_pending = FALSE;
1235
            tp_object_submit( timer, FALSE );
1236

1237
            /* Insert the timer back into the queue, except it's marked for shutdown. */
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
            if (timer->u.timer.period && !timer->shutdown)
            {
                timer->u.timer.timeout += (ULONGLONG)timer->u.timer.period * 10000;
                if (timer->u.timer.timeout <= now.QuadPart)
                    timer->u.timer.timeout = now.QuadPart + 1;

                LIST_FOR_EACH_ENTRY( other_timer, &timerqueue.pending_timers,
                                     struct threadpool_object, u.timer.timer_entry )
                {
                    assert( other_timer->type == TP_OBJECT_TYPE_TIMER );
                    if (timer->u.timer.timeout < other_timer->u.timer.timeout)
                        break;
                }
                list_add_before( &other_timer->u.timer.timer_entry, &timer->u.timer.timer_entry );
                timer->u.timer.timer_pending = TRUE;
            }
        }

        timeout_lower = TIMEOUT_INFINITE;
        timeout_upper = TIMEOUT_INFINITE;

        /* Determine next timeout and use the window length to optimize wakeup times. */
        LIST_FOR_EACH_ENTRY( other_timer, &timerqueue.pending_timers,
                             struct threadpool_object, u.timer.timer_entry )
        {
            assert( other_timer->type == TP_OBJECT_TYPE_TIMER );
            if (other_timer->u.timer.timeout >= timeout_upper)
                break;

            timeout_lower = other_timer->u.timer.timeout;
            new_timeout   = timeout_lower + (ULONGLONG)other_timer->u.timer.window_length * 10000;
            if (new_timeout < timeout_upper)
                timeout_upper = new_timeout;
        }

        /* Wait for timer update events or until the next timer expires. */
        if (timerqueue.objcount)
        {
            timeout.QuadPart = timeout_lower;
            RtlSleepConditionVariableCS( &timerqueue.update_event, &timerqueue.cs, &timeout );
            continue;
        }

        /* All timers have been destroyed, if no new timers are created
         * within some amount of time, then we can shutdown this thread. */
        timeout.QuadPart = (ULONGLONG)THREADPOOL_WORKER_TIMEOUT * -10000;
        if (RtlSleepConditionVariableCS( &timerqueue.update_event, &timerqueue.cs,
            &timeout ) == STATUS_TIMEOUT && !timerqueue.objcount)
        {
            break;
        }
    }

    timerqueue.thread_running = FALSE;
    RtlLeaveCriticalSection( &timerqueue.cs );

    TRACE( "terminating timer queue thread\n" );
1295
    RtlExitUserThread( 0 );
1296 1297
}

1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
/***********************************************************************
 *           tp_new_worker_thread    (internal)
 *
 * Create and account a new worker thread for the desired pool.
 */
static NTSTATUS tp_new_worker_thread( struct threadpool *pool )
{
    HANDLE thread;
    NTSTATUS status;

    status = RtlCreateUserThread( GetCurrentProcess(), NULL, FALSE, NULL, 0, 0,
                                  threadpool_worker_proc, pool, &thread, NULL );
    if (status == STATUS_SUCCESS)
    {
        interlocked_inc( &pool->refcount );
        pool->num_workers++;
        pool->num_busy_workers++;
        NtClose( thread );
    }
    return status;
}

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
/***********************************************************************
 *           tp_timerqueue_lock    (internal)
 *
 * Acquires a lock on the global timerqueue. When the lock is acquired
 * successfully, it is guaranteed that the timer thread is running.
 */
static NTSTATUS tp_timerqueue_lock( struct threadpool_object *timer )
{
    NTSTATUS status = STATUS_SUCCESS;
    assert( timer->type == TP_OBJECT_TYPE_TIMER );

    timer->u.timer.timer_initialized    = FALSE;
    timer->u.timer.timer_pending        = FALSE;
    timer->u.timer.timer_set            = FALSE;
    timer->u.timer.timeout              = 0;
    timer->u.timer.period               = 0;
    timer->u.timer.window_length        = 0;

    RtlEnterCriticalSection( &timerqueue.cs );

    /* Make sure that the timerqueue thread is running. */
    if (!timerqueue.thread_running)
    {
        HANDLE thread;
        status = RtlCreateUserThread( GetCurrentProcess(), NULL, FALSE, NULL, 0, 0,
                                      timerqueue_thread_proc, NULL, &thread, NULL );
        if (status == STATUS_SUCCESS)
        {
            timerqueue.thread_running = TRUE;
            NtClose( thread );
        }
    }

    if (status == STATUS_SUCCESS)
    {
        timer->u.timer.timer_initialized = TRUE;
        timerqueue.objcount++;
    }

    RtlLeaveCriticalSection( &timerqueue.cs );
    return status;
}

/***********************************************************************
 *           tp_timerqueue_unlock    (internal)
 *
 * Releases a lock on the global timerqueue.
 */
static void tp_timerqueue_unlock( struct threadpool_object *timer )
{
    assert( timer->type == TP_OBJECT_TYPE_TIMER );

    RtlEnterCriticalSection( &timerqueue.cs );
    if (timer->u.timer.timer_initialized)
    {
        /* If timer was pending, remove it. */
        if (timer->u.timer.timer_pending)
        {
            list_remove( &timer->u.timer.timer_entry );
            timer->u.timer.timer_pending = FALSE;
        }

        /* If the last timer object was destroyed, then wake up the thread. */
        if (!--timerqueue.objcount)
        {
            assert( list_empty( &timerqueue.pending_timers ) );
            RtlWakeAllConditionVariable( &timerqueue.update_event );
        }

        timer->u.timer.timer_initialized = FALSE;
    }
    RtlLeaveCriticalSection( &timerqueue.cs );
}

1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
/***********************************************************************
 *           waitqueue_thread_proc    (internal)
 */
static void CALLBACK waitqueue_thread_proc( void *param )
{
    struct threadpool_object *objects[MAXIMUM_WAITQUEUE_OBJECTS];
    HANDLE handles[MAXIMUM_WAITQUEUE_OBJECTS + 1];
    struct waitqueue_bucket *bucket = param;
    struct threadpool_object *wait, *next;
    LARGE_INTEGER now, timeout;
    DWORD num_handles;
    NTSTATUS status;

    TRACE( "starting wait queue thread\n" );

    RtlEnterCriticalSection( &waitqueue.cs );

    for (;;)
    {
        NtQuerySystemTime( &now );
        timeout.QuadPart = TIMEOUT_INFINITE;
        num_handles = 0;

        LIST_FOR_EACH_ENTRY_SAFE( wait, next, &bucket->waiting, struct threadpool_object,
                                  u.wait.wait_entry )
        {
            assert( wait->type == TP_OBJECT_TYPE_WAIT );
            if (wait->u.wait.timeout <= now.QuadPart)
            {
                /* Wait object timed out. */
                list_remove( &wait->u.wait.wait_entry );
                list_add_tail( &bucket->reserved, &wait->u.wait.wait_entry );
                tp_object_submit( wait, FALSE );
            }
            else
            {
                if (wait->u.wait.timeout < timeout.QuadPart)
                    timeout.QuadPart = wait->u.wait.timeout;

                assert( num_handles < MAXIMUM_WAITQUEUE_OBJECTS );
                interlocked_inc( &wait->refcount );
                objects[num_handles] = wait;
                handles[num_handles] = wait->u.wait.handle;
                num_handles++;
            }
        }

        if (!bucket->objcount)
        {
            /* All wait objects have been destroyed, if no new wait objects are created
             * within some amount of time, then we can shutdown this thread. */
            assert( num_handles == 0 );
            RtlLeaveCriticalSection( &waitqueue.cs );
            timeout.QuadPart = (ULONGLONG)THREADPOOL_WORKER_TIMEOUT * -10000;
            status = NtWaitForMultipleObjects( 1, &bucket->update_event, TRUE, FALSE, &timeout );
            RtlEnterCriticalSection( &waitqueue.cs );

            if (status == STATUS_TIMEOUT && !bucket->objcount)
                break;
        }
        else
        {
            handles[num_handles] = bucket->update_event;
            RtlLeaveCriticalSection( &waitqueue.cs );
            status = NtWaitForMultipleObjects( num_handles + 1, handles, TRUE, FALSE, &timeout );
            RtlEnterCriticalSection( &waitqueue.cs );

            if (status >= STATUS_WAIT_0 && status < STATUS_WAIT_0 + num_handles)
            {
                wait = objects[status - STATUS_WAIT_0];
                assert( wait->type == TP_OBJECT_TYPE_WAIT );
                if (wait->u.wait.bucket)
                {
                    /* Wait object signaled. */
                    assert( wait->u.wait.bucket == bucket );
                    list_remove( &wait->u.wait.wait_entry );
                    list_add_tail( &bucket->reserved, &wait->u.wait.wait_entry );
                    tp_object_submit( wait, TRUE );
                }
                else
1474
                    WARN("wait object %p triggered while object was destroyed\n", wait);
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
            }

            /* Release temporary references to wait objects. */
            while (num_handles)
            {
                wait = objects[--num_handles];
                assert( wait->type == TP_OBJECT_TYPE_WAIT );
                tp_object_release( wait );
            }
        }
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524

        /* Try to merge bucket with other threads. */
        if (waitqueue.num_buckets > 1 && bucket->objcount &&
            bucket->objcount <= MAXIMUM_WAITQUEUE_OBJECTS * 1 / 3)
        {
            struct waitqueue_bucket *other_bucket;
            LIST_FOR_EACH_ENTRY( other_bucket, &waitqueue.buckets, struct waitqueue_bucket, bucket_entry )
            {
                if (other_bucket != bucket && other_bucket->objcount &&
                    other_bucket->objcount + bucket->objcount <= MAXIMUM_WAITQUEUE_OBJECTS * 2 / 3)
                {
                    other_bucket->objcount += bucket->objcount;
                    bucket->objcount = 0;

                    /* Update reserved list. */
                    LIST_FOR_EACH_ENTRY( wait, &bucket->reserved, struct threadpool_object, u.wait.wait_entry )
                    {
                        assert( wait->type == TP_OBJECT_TYPE_WAIT );
                        wait->u.wait.bucket = other_bucket;
                    }
                    list_move_tail( &other_bucket->reserved, &bucket->reserved );

                    /* Update waiting list. */
                    LIST_FOR_EACH_ENTRY( wait, &bucket->waiting, struct threadpool_object, u.wait.wait_entry )
                    {
                        assert( wait->type == TP_OBJECT_TYPE_WAIT );
                        wait->u.wait.bucket = other_bucket;
                    }
                    list_move_tail( &other_bucket->waiting, &bucket->waiting );

                    /* Move bucket to the end, to keep the probability of
                     * newly added wait objects as small as possible. */
                    list_remove( &bucket->bucket_entry );
                    list_add_tail( &waitqueue.buckets, &bucket->bucket_entry );

                    NtSetEvent( other_bucket->update_event, NULL );
                    break;
                }
            }
        }
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
    }

    /* Remove this bucket from the list. */
    list_remove( &bucket->bucket_entry );
    if (!--waitqueue.num_buckets)
        assert( list_empty( &waitqueue.buckets ) );

    RtlLeaveCriticalSection( &waitqueue.cs );

    TRACE( "terminating wait queue thread\n" );

    assert( bucket->objcount == 0 );
    assert( list_empty( &bucket->reserved ) );
    assert( list_empty( &bucket->waiting ) );
    NtClose( bucket->update_event );

    RtlFreeHeap( GetProcessHeap(), 0, bucket );
1542
    RtlExitUserThread( 0 );
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
}

/***********************************************************************
 *           tp_waitqueue_lock    (internal)
 */
static NTSTATUS tp_waitqueue_lock( struct threadpool_object *wait )
{
    struct waitqueue_bucket *bucket;
    NTSTATUS status;
    HANDLE thread;
1553
    assert( wait->type == TP_OBJECT_TYPE_WAIT );
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642

    wait->u.wait.signaled       = 0;
    wait->u.wait.bucket         = NULL;
    wait->u.wait.wait_pending   = FALSE;
    wait->u.wait.timeout        = 0;
    wait->u.wait.handle         = INVALID_HANDLE_VALUE;

    RtlEnterCriticalSection( &waitqueue.cs );

    /* Try to assign to existing bucket if possible. */
    LIST_FOR_EACH_ENTRY( bucket, &waitqueue.buckets, struct waitqueue_bucket, bucket_entry )
    {
        if (bucket->objcount < MAXIMUM_WAITQUEUE_OBJECTS)
        {
            list_add_tail( &bucket->reserved, &wait->u.wait.wait_entry );
            wait->u.wait.bucket = bucket;
            bucket->objcount++;

            status = STATUS_SUCCESS;
            goto out;
        }
    }

    /* Create a new bucket and corresponding worker thread. */
    bucket = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*bucket) );
    if (!bucket)
    {
        status = STATUS_NO_MEMORY;
        goto out;
    }

    bucket->objcount = 0;
    list_init( &bucket->reserved );
    list_init( &bucket->waiting );

    status = NtCreateEvent( &bucket->update_event, EVENT_ALL_ACCESS,
                            NULL, SynchronizationEvent, FALSE );
    if (status)
    {
        RtlFreeHeap( GetProcessHeap(), 0, bucket );
        goto out;
    }

    status = RtlCreateUserThread( GetCurrentProcess(), NULL, FALSE, NULL, 0, 0,
                                  waitqueue_thread_proc, bucket, &thread, NULL );
    if (status == STATUS_SUCCESS)
    {
        list_add_tail( &waitqueue.buckets, &bucket->bucket_entry );
        waitqueue.num_buckets++;

        list_add_tail( &bucket->reserved, &wait->u.wait.wait_entry );
        wait->u.wait.bucket = bucket;
        bucket->objcount++;

        NtClose( thread );
    }
    else
    {
        NtClose( bucket->update_event );
        RtlFreeHeap( GetProcessHeap(), 0, bucket );
    }

out:
    RtlLeaveCriticalSection( &waitqueue.cs );
    return status;
}

/***********************************************************************
 *           tp_waitqueue_unlock    (internal)
 */
static void tp_waitqueue_unlock( struct threadpool_object *wait )
{
    assert( wait->type == TP_OBJECT_TYPE_WAIT );

    RtlEnterCriticalSection( &waitqueue.cs );
    if (wait->u.wait.bucket)
    {
        struct waitqueue_bucket *bucket = wait->u.wait.bucket;
        assert( bucket->objcount > 0 );

        list_remove( &wait->u.wait.wait_entry );
        wait->u.wait.bucket = NULL;
        bucket->objcount--;

        NtSetEvent( bucket->update_event, NULL );
    }
    RtlLeaveCriticalSection( &waitqueue.cs );
}

1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
/***********************************************************************
 *           tp_threadpool_alloc    (internal)
 *
 * Allocates a new threadpool object.
 */
static NTSTATUS tp_threadpool_alloc( struct threadpool **out )
{
    struct threadpool *pool;

    pool = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*pool) );
    if (!pool)
        return STATUS_NO_MEMORY;

    pool->refcount              = 1;
    pool->objcount              = 0;
    pool->shutdown              = FALSE;

    RtlInitializeCriticalSection( &pool->cs );
    pool->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": threadpool.cs");

    list_init( &pool->pool );
    RtlInitializeConditionVariable( &pool->update_event );

    pool->max_workers           = 500;
    pool->min_workers           = 0;
    pool->num_workers           = 0;
    pool->num_busy_workers      = 0;

    TRACE( "allocated threadpool %p\n", pool );

    *out = pool;
    return STATUS_SUCCESS;
}

/***********************************************************************
 *           tp_threadpool_shutdown    (internal)
 *
 * Prepares the shutdown of a threadpool object and notifies all worker
 * threads to terminate (after all remaining work items have been
 * processed).
 */
static void tp_threadpool_shutdown( struct threadpool *pool )
{
    assert( pool != default_threadpool );

    pool->shutdown = TRUE;
    RtlWakeAllConditionVariable( &pool->update_event );
}

/***********************************************************************
 *           tp_threadpool_release    (internal)
 *
 * Releases a reference to a threadpool object.
 */
static BOOL tp_threadpool_release( struct threadpool *pool )
{
    if (interlocked_dec( &pool->refcount ))
        return FALSE;

    TRACE( "destroying threadpool %p\n", pool );

    assert( pool->shutdown );
    assert( !pool->objcount );
    assert( list_empty( &pool->pool ) );

    pool->cs.DebugInfo->Spare[0] = 0;
    RtlDeleteCriticalSection( &pool->cs );

    RtlFreeHeap( GetProcessHeap(), 0, pool );
    return TRUE;
}

/***********************************************************************
 *           tp_threadpool_lock    (internal)
 *
 * Acquires a lock on a threadpool, specified with an TP_CALLBACK_ENVIRON
 * block. When the lock is acquired successfully, it is guaranteed that
 * there is at least one worker thread to process tasks.
 */
static NTSTATUS tp_threadpool_lock( struct threadpool **out, TP_CALLBACK_ENVIRON *environment )
{
    struct threadpool *pool = NULL;
    NTSTATUS status = STATUS_SUCCESS;

    if (environment)
        pool = (struct threadpool *)environment->Pool;

    if (!pool)
    {
        if (!default_threadpool)
        {
            status = tp_threadpool_alloc( &pool );
            if (status != STATUS_SUCCESS)
                return status;

            if (interlocked_cmpxchg_ptr( (void *)&default_threadpool, pool, NULL ) != NULL)
            {
                tp_threadpool_shutdown( pool );
                tp_threadpool_release( pool );
            }
        }

        pool = default_threadpool;
    }

    RtlEnterCriticalSection( &pool->cs );

    /* Make sure that the threadpool has at least one thread. */
    if (!pool->num_workers)
1752
        status = tp_new_worker_thread( pool );
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783

    /* Keep a reference, and increment objcount to ensure that the
     * last thread doesn't terminate. */
    if (status == STATUS_SUCCESS)
    {
        interlocked_inc( &pool->refcount );
        pool->objcount++;
    }

    RtlLeaveCriticalSection( &pool->cs );

    if (status != STATUS_SUCCESS)
        return status;

    *out = pool;
    return STATUS_SUCCESS;
}

/***********************************************************************
 *           tp_threadpool_unlock    (internal)
 *
 * Releases a lock on a threadpool.
 */
static void tp_threadpool_unlock( struct threadpool *pool )
{
    RtlEnterCriticalSection( &pool->cs );
    pool->objcount--;
    RtlLeaveCriticalSection( &pool->cs );
    tp_threadpool_release( pool );
}

1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
/***********************************************************************
 *           tp_group_alloc    (internal)
 *
 * Allocates a new threadpool group object.
 */
static NTSTATUS tp_group_alloc( struct threadpool_group **out )
{
    struct threadpool_group *group;

    group = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*group) );
    if (!group)
        return STATUS_NO_MEMORY;

    group->refcount     = 1;
    group->shutdown     = FALSE;

    RtlInitializeCriticalSection( &group->cs );
    group->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": threadpool_group.cs");

    list_init( &group->members );

    TRACE( "allocated group %p\n", group );

    *out = group;
    return STATUS_SUCCESS;
}

/***********************************************************************
 *           tp_group_shutdown    (internal)
 *
 * Marks the group object for shutdown.
 */
static void tp_group_shutdown( struct threadpool_group *group )
{
    group->shutdown = TRUE;
}

/***********************************************************************
 *           tp_group_release    (internal)
 *
 * Releases a reference to a group object.
 */
static BOOL tp_group_release( struct threadpool_group *group )
{
    if (interlocked_dec( &group->refcount ))
        return FALSE;

    TRACE( "destroying group %p\n", group );

    assert( group->shutdown );
    assert( list_empty( &group->members ) );

    group->cs.DebugInfo->Spare[0] = 0;
    RtlDeleteCriticalSection( &group->cs );

    RtlFreeHeap( GetProcessHeap(), 0, group );
    return TRUE;
}

1843 1844 1845 1846 1847 1848 1849 1850
/***********************************************************************
 *           tp_object_initialize    (internal)
 *
 * Initializes members of a threadpool object.
 */
static void tp_object_initialize( struct threadpool_object *object, struct threadpool *pool,
                                  PVOID userdata, TP_CALLBACK_ENVIRON *environment )
{
1851 1852
    BOOL is_simple_callback = (object->type == TP_OBJECT_TYPE_SIMPLE);

1853 1854 1855 1856
    object->refcount                = 1;
    object->shutdown                = FALSE;

    object->pool                    = pool;
1857
    object->group                   = NULL;
1858
    object->userdata                = userdata;
1859
    object->group_cancel_callback   = NULL;
1860
    object->finalization_callback   = NULL;
1861
    object->may_run_long            = 0;
1862
    object->race_dll                = NULL;
1863

1864 1865 1866
    memset( &object->group_entry, 0, sizeof(object->group_entry) );
    object->is_group_member         = FALSE;

1867
    memset( &object->pool_entry, 0, sizeof(object->pool_entry) );
1868
    RtlInitializeConditionVariable( &object->finished_event );
1869
    RtlInitializeConditionVariable( &object->group_finished_event );
1870 1871
    object->num_pending_callbacks   = 0;
    object->num_running_callbacks   = 0;
1872
    object->num_associated_callbacks = 0;
1873 1874

    if (environment)
1875
    {
1876
        if (environment->Version != 1 && environment->Version != 3)
1877 1878 1879
            FIXME( "unsupported environment version %u\n", environment->Version );

        object->group = impl_from_TP_CLEANUP_GROUP( environment->CleanupGroup );
1880
        object->group_cancel_callback   = environment->CleanupGroupCancelCallback;
1881
        object->finalization_callback   = environment->FinalizationCallback;
1882
        object->may_run_long            = environment->u.s.LongFunction != 0;
1883
        object->race_dll                = environment->RaceDll;
1884

1885 1886 1887 1888 1889
        if (environment->ActivationContext)
            FIXME( "activation context not supported yet\n" );

        if (environment->u.s.Persistent)
            FIXME( "persistent threads not supported yet\n" );
1890
    }
1891

1892 1893 1894
    if (object->race_dll)
        LdrAddRefDll( 0, object->race_dll );

1895
    TRACE( "allocated object %p of type %u\n", object, object->type );
1896 1897 1898 1899 1900 1901

    /* For simple callbacks we have to run tp_object_submit before adding this object
     * to the cleanup group. As soon as the cleanup group members are released ->shutdown
     * will be set, and tp_object_submit would fail with an assertion. */

    if (is_simple_callback)
1902
        tp_object_submit( object, FALSE );
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916

    if (object->group)
    {
        struct threadpool_group *group = object->group;
        interlocked_inc( &group->refcount );

        RtlEnterCriticalSection( &group->cs );
        list_add_tail( &group->members, &object->group_entry );
        object->is_group_member = TRUE;
        RtlLeaveCriticalSection( &group->cs );
    }

    if (is_simple_callback)
        tp_object_release( object );
1917 1918 1919 1920 1921
}

/***********************************************************************
 *           tp_object_submit    (internal)
 *
1922
 * Submits a threadpool object to the associated threadpool. This
1923 1924
 * function has to be VOID because TpPostWork can never fail on Windows.
 */
1925
static void tp_object_submit( struct threadpool_object *object, BOOL signaled )
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
{
    struct threadpool *pool = object->pool;
    NTSTATUS status = STATUS_UNSUCCESSFUL;

    assert( !object->shutdown );
    assert( !pool->shutdown );

    RtlEnterCriticalSection( &pool->cs );

    /* Start new worker threads if required. */
    if (pool->num_busy_workers >= pool->num_workers &&
        pool->num_workers < pool->max_workers)
1938
        status = tp_new_worker_thread( pool );
1939 1940 1941 1942 1943 1944

    /* Queue work item and increment refcount. */
    interlocked_inc( &object->refcount );
    if (!object->num_pending_callbacks++)
        list_add_tail( &pool->pool, &object->pool_entry );

1945 1946 1947 1948
    /* Count how often the object was signaled. */
    if (object->type == TP_OBJECT_TYPE_WAIT && signaled)
        object->u.wait.signaled++;

1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
    /* No new thread started - wake up one existing thread. */
    if (status != STATUS_SUCCESS)
    {
        assert( pool->num_workers > 0 );
        RtlWakeConditionVariable( &pool->update_event );
    }

    RtlLeaveCriticalSection( &pool->cs );
}

1959 1960 1961 1962 1963
/***********************************************************************
 *           tp_object_cancel    (internal)
 *
 * Cancels all currently pending callbacks for a specific object.
 */
1964
static void tp_object_cancel( struct threadpool_object *object )
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
{
    struct threadpool *pool = object->pool;
    LONG pending_callbacks = 0;

    RtlEnterCriticalSection( &pool->cs );
    if (object->num_pending_callbacks)
    {
        pending_callbacks = object->num_pending_callbacks;
        object->num_pending_callbacks = 0;
        list_remove( &object->pool_entry );
1975 1976 1977

        if (object->type == TP_OBJECT_TYPE_WAIT)
            object->u.wait.signaled = 0;
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
    }
    RtlLeaveCriticalSection( &pool->cs );

    while (pending_callbacks--)
        tp_object_release( object );
}

/***********************************************************************
 *           tp_object_wait    (internal)
 *
 * Waits until all pending and running callbacks of a specific object
 * have been processed.
 */
1991
static void tp_object_wait( struct threadpool_object *object, BOOL group_wait )
1992 1993 1994 1995
{
    struct threadpool *pool = object->pool;

    RtlEnterCriticalSection( &pool->cs );
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
    if (group_wait)
    {
        while (object->num_pending_callbacks || object->num_running_callbacks)
            RtlSleepConditionVariableCS( &object->group_finished_event, &pool->cs, NULL );
    }
    else
    {
        while (object->num_pending_callbacks || object->num_associated_callbacks)
            RtlSleepConditionVariableCS( &object->finished_event, &pool->cs, NULL );
    }
2006 2007 2008
    RtlLeaveCriticalSection( &pool->cs );
}

2009
/***********************************************************************
2010
 *           tp_object_prepare_shutdown    (internal)
2011
 *
2012
 * Prepares a threadpool object for shutdown.
2013
 */
2014
static void tp_object_prepare_shutdown( struct threadpool_object *object )
2015
{
2016 2017
    if (object->type == TP_OBJECT_TYPE_TIMER)
        tp_timerqueue_unlock( object );
2018 2019
    else if (object->type == TP_OBJECT_TYPE_WAIT)
        tp_waitqueue_unlock( object );
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
}

/***********************************************************************
 *           tp_object_release    (internal)
 *
 * Releases a reference to a threadpool object.
 */
static BOOL tp_object_release( struct threadpool_object *object )
{
    if (interlocked_dec( &object->refcount ))
        return FALSE;

    TRACE( "destroying object %p of type %u\n", object, object->type );

    assert( object->shutdown );
    assert( !object->num_pending_callbacks );
    assert( !object->num_running_callbacks );
2037
    assert( !object->num_associated_callbacks );
2038

2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
    /* release reference to the group */
    if (object->group)
    {
        struct threadpool_group *group = object->group;

        RtlEnterCriticalSection( &group->cs );
        if (object->is_group_member)
        {
            list_remove( &object->group_entry );
            object->is_group_member = FALSE;
        }
        RtlLeaveCriticalSection( &group->cs );

        tp_group_release( group );
    }

2055 2056
    tp_threadpool_unlock( object->pool );

2057 2058 2059
    if (object->race_dll)
        LdrUnloadDll( object->race_dll );

2060 2061 2062 2063 2064 2065 2066 2067 2068
    RtlFreeHeap( GetProcessHeap(), 0, object );
    return TRUE;
}

/***********************************************************************
 *           threadpool_worker_proc    (internal)
 */
static void CALLBACK threadpool_worker_proc( void *param )
{
2069 2070
    TP_CALLBACK_INSTANCE *callback_instance;
    struct threadpool_instance instance;
2071
    struct threadpool *pool = param;
2072
    TP_WAIT_RESULT wait_result = 0;
2073 2074
    LARGE_INTEGER timeout;
    struct list *ptr;
2075
    NTSTATUS status;
2076 2077 2078 2079

    TRACE( "starting worker thread for pool %p\n", pool );

    RtlEnterCriticalSection( &pool->cs );
2080
    pool->num_busy_workers--;
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
    for (;;)
    {
        while ((ptr = list_head( &pool->pool )))
        {
            struct threadpool_object *object = LIST_ENTRY( ptr, struct threadpool_object, pool_entry );
            assert( object->num_pending_callbacks > 0 );

            /* If further pending callbacks are queued, move the work item to
             * the end of the pool list. Otherwise remove it from the pool. */
            list_remove( &object->pool_entry );
            if (--object->num_pending_callbacks)
                list_add_tail( &pool->pool, &object->pool_entry );

2094 2095 2096 2097 2098 2099 2100
            /* For wait objects check if they were signaled or have timed out. */
            if (object->type == TP_OBJECT_TYPE_WAIT)
            {
                wait_result = object->u.wait.signaled ? WAIT_OBJECT_0 : WAIT_TIMEOUT;
                if (wait_result == WAIT_OBJECT_0) object->u.wait.signaled--;
            }

2101
            /* Leave critical section and do the actual callback. */
2102
            object->num_associated_callbacks++;
2103 2104 2105 2106
            object->num_running_callbacks++;
            pool->num_busy_workers++;
            RtlLeaveCriticalSection( &pool->cs );

2107 2108 2109 2110
            /* Initialize threadpool instance struct. */
            callback_instance = (TP_CALLBACK_INSTANCE *)&instance;
            instance.object                     = object;
            instance.threadid                   = GetCurrentThreadId();
2111
            instance.associated                 = TRUE;
2112
            instance.may_run_long               = object->may_run_long;
2113
            instance.cleanup.critical_section   = NULL;
2114
            instance.cleanup.mutex              = NULL;
2115 2116
            instance.cleanup.semaphore          = NULL;
            instance.cleanup.semaphore_count    = 0;
2117
            instance.cleanup.event              = NULL;
2118
            instance.cleanup.library            = NULL;
2119

2120 2121 2122 2123
            switch (object->type)
            {
                case TP_OBJECT_TYPE_SIMPLE:
                {
2124 2125 2126
                    TRACE( "executing simple callback %p(%p, %p)\n",
                           object->u.simple.callback, callback_instance, object->userdata );
                    object->u.simple.callback( callback_instance, object->userdata );
2127 2128 2129 2130
                    TRACE( "callback %p returned\n", object->u.simple.callback );
                    break;
                }

2131 2132
                case TP_OBJECT_TYPE_WORK:
                {
2133 2134 2135
                    TRACE( "executing work callback %p(%p, %p, %p)\n",
                           object->u.work.callback, callback_instance, object->userdata, object );
                    object->u.work.callback( callback_instance, object->userdata, (TP_WORK *)object );
2136 2137 2138 2139
                    TRACE( "callback %p returned\n", object->u.work.callback );
                    break;
                }

2140 2141 2142 2143 2144 2145 2146 2147 2148
                case TP_OBJECT_TYPE_TIMER:
                {
                    TRACE( "executing timer callback %p(%p, %p, %p)\n",
                           object->u.timer.callback, callback_instance, object->userdata, object );
                    object->u.timer.callback( callback_instance, object->userdata, (TP_TIMER *)object );
                    TRACE( "callback %p returned\n", object->u.timer.callback );
                    break;
                }

2149 2150 2151
                case TP_OBJECT_TYPE_WAIT:
                {
                    TRACE( "executing wait callback %p(%p, %p, %p, %u)\n",
2152 2153
                           object->u.wait.callback, callback_instance, object->userdata, object, wait_result );
                    object->u.wait.callback( callback_instance, object->userdata, (TP_WAIT *)object, wait_result );
2154 2155 2156 2157
                    TRACE( "callback %p returned\n", object->u.wait.callback );
                    break;
                }

2158 2159 2160 2161 2162
                default:
                    assert(0);
                    break;
            }

2163 2164 2165
            /* Execute finalization callback. */
            if (object->finalization_callback)
            {
2166 2167 2168
                TRACE( "executing finalization callback %p(%p, %p)\n",
                       object->finalization_callback, callback_instance, object->userdata );
                object->finalization_callback( callback_instance, object->userdata );
2169 2170 2171
                TRACE( "callback %p returned\n", object->finalization_callback );
            }

2172 2173 2174 2175 2176
            /* Execute cleanup tasks. */
            if (instance.cleanup.critical_section)
            {
                RtlLeaveCriticalSection( instance.cleanup.critical_section );
            }
2177 2178
            if (instance.cleanup.mutex)
            {
2179 2180 2181 2182 2183
                status = NtReleaseMutant( instance.cleanup.mutex, NULL );
                if (status != STATUS_SUCCESS) goto skip_cleanup;
            }
            if (instance.cleanup.semaphore)
            {
2184 2185 2186 2187 2188
                status = NtReleaseSemaphore( instance.cleanup.semaphore, instance.cleanup.semaphore_count, NULL );
                if (status != STATUS_SUCCESS) goto skip_cleanup;
            }
            if (instance.cleanup.event)
            {
2189 2190 2191 2192 2193 2194
                status = NtSetEvent( instance.cleanup.event, NULL );
                if (status != STATUS_SUCCESS) goto skip_cleanup;
            }
            if (instance.cleanup.library)
            {
                LdrUnloadDll( instance.cleanup.library );
2195
            }
2196

2197
        skip_cleanup:
2198 2199
            RtlEnterCriticalSection( &pool->cs );
            pool->num_busy_workers--;
2200

2201 2202 2203 2204 2205 2206 2207
            /* Simple callbacks are automatically shutdown after execution. */
            if (object->type == TP_OBJECT_TYPE_SIMPLE)
            {
                tp_object_prepare_shutdown( object );
                object->shutdown = TRUE;
            }

2208
            object->num_running_callbacks--;
2209
            if (!object->num_pending_callbacks && !object->num_running_callbacks)
2210 2211 2212 2213 2214 2215 2216 2217 2218
                RtlWakeAllConditionVariable( &object->group_finished_event );

            if (instance.associated)
            {
                object->num_associated_callbacks--;
                if (!object->num_pending_callbacks && !object->num_associated_callbacks)
                    RtlWakeAllConditionVariable( &object->finished_event );
            }

2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
            tp_object_release( object );
        }

        /* Shutdown worker thread if requested. */
        if (pool->shutdown)
            break;

        /* Wait for new tasks or until the timeout expires. A thread only terminates
         * when no new tasks are available, and the number of threads can be
         * decreased without violating the min_workers limit. An exception is when
         * min_workers == 0, then objcount is used to detect if the last thread
         * can be terminated. */
        timeout.QuadPart = (ULONGLONG)THREADPOOL_WORKER_TIMEOUT * -10000;
        if (RtlSleepConditionVariableCS( &pool->update_event, &pool->cs, &timeout ) == STATUS_TIMEOUT &&
            !list_head( &pool->pool ) && (pool->num_workers > max( pool->min_workers, 1 ) ||
            (!pool->min_workers && !pool->objcount)))
        {
            break;
        }
    }
    pool->num_workers--;
    RtlLeaveCriticalSection( &pool->cs );

    TRACE( "terminating worker thread for pool %p\n", pool );
    tp_threadpool_release( pool );
2244
    RtlExitUserThread( 0 );
2245 2246
}

2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
/***********************************************************************
 *           TpAllocCleanupGroup    (NTDLL.@)
 */
NTSTATUS WINAPI TpAllocCleanupGroup( TP_CLEANUP_GROUP **out )
{
    TRACE( "%p\n", out );

    return tp_group_alloc( (struct threadpool_group **)out );
}

2257 2258 2259 2260 2261 2262 2263 2264
/***********************************************************************
 *           TpAllocPool    (NTDLL.@)
 */
NTSTATUS WINAPI TpAllocPool( TP_POOL **out, PVOID reserved )
{
    TRACE( "%p %p\n", out, reserved );

    if (reserved)
2265
        FIXME( "reserved argument is nonzero (%p)\n", reserved );
2266 2267 2268 2269

    return tp_threadpool_alloc( (struct threadpool **)out );
}

2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294
/***********************************************************************
 *           TpAllocTimer    (NTDLL.@)
 */
NTSTATUS WINAPI TpAllocTimer( TP_TIMER **out, PTP_TIMER_CALLBACK callback, PVOID userdata,
                              TP_CALLBACK_ENVIRON *environment )
{
    struct threadpool_object *object;
    struct threadpool *pool;
    NTSTATUS status;

    TRACE( "%p %p %p %p\n", out, callback, userdata, environment );

    object = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*object) );
    if (!object)
        return STATUS_NO_MEMORY;

    status = tp_threadpool_lock( &pool, environment );
    if (status)
    {
        RtlFreeHeap( GetProcessHeap(), 0, object );
        return status;
    }

    object->type = TP_OBJECT_TYPE_TIMER;
    object->u.timer.callback = callback;
2295 2296 2297 2298 2299 2300 2301 2302 2303

    status = tp_timerqueue_lock( object );
    if (status)
    {
        tp_threadpool_unlock( pool );
        RtlFreeHeap( GetProcessHeap(), 0, object );
        return status;
    }

2304 2305 2306 2307 2308 2309
    tp_object_initialize( object, pool, userdata, environment );

    *out = (TP_TIMER *)object;
    return STATUS_SUCCESS;
}

2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
/***********************************************************************
 *           TpAllocWait     (NTDLL.@)
 */
NTSTATUS WINAPI TpAllocWait( TP_WAIT **out, PTP_WAIT_CALLBACK callback, PVOID userdata,
                             TP_CALLBACK_ENVIRON *environment )
{
    struct threadpool_object *object;
    struct threadpool *pool;
    NTSTATUS status;

    TRACE( "%p %p %p %p\n", out, callback, userdata, environment );

    object = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*object) );
    if (!object)
        return STATUS_NO_MEMORY;

    status = tp_threadpool_lock( &pool, environment );
    if (status)
    {
        RtlFreeHeap( GetProcessHeap(), 0, object );
        return status;
    }

    object->type = TP_OBJECT_TYPE_WAIT;
    object->u.wait.callback = callback;
2335 2336 2337 2338 2339 2340 2341 2342 2343

    status = tp_waitqueue_lock( object );
    if (status)
    {
        tp_threadpool_unlock( pool );
        RtlFreeHeap( GetProcessHeap(), 0, object );
        return status;
    }

2344 2345 2346 2347 2348 2349
    tp_object_initialize( object, pool, userdata, environment );

    *out = (TP_WAIT *)object;
    return STATUS_SUCCESS;
}

2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
/***********************************************************************
 *           TpAllocWork    (NTDLL.@)
 */
NTSTATUS WINAPI TpAllocWork( TP_WORK **out, PTP_WORK_CALLBACK callback, PVOID userdata,
                             TP_CALLBACK_ENVIRON *environment )
{
    struct threadpool_object *object;
    struct threadpool *pool;
    NTSTATUS status;

    TRACE( "%p %p %p %p\n", out, callback, userdata, environment );

    object = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*object) );
    if (!object)
        return STATUS_NO_MEMORY;

    status = tp_threadpool_lock( &pool, environment );
    if (status)
    {
        RtlFreeHeap( GetProcessHeap(), 0, object );
        return status;
    }

    object->type = TP_OBJECT_TYPE_WORK;
    object->u.work.callback = callback;
    tp_object_initialize( object, pool, userdata, environment );

    *out = (TP_WORK *)object;
    return STATUS_SUCCESS;
}

2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
/***********************************************************************
 *           TpCallbackLeaveCriticalSectionOnCompletion    (NTDLL.@)
 */
VOID WINAPI TpCallbackLeaveCriticalSectionOnCompletion( TP_CALLBACK_INSTANCE *instance, CRITICAL_SECTION *crit )
{
    struct threadpool_instance *this = impl_from_TP_CALLBACK_INSTANCE( instance );

    TRACE( "%p %p\n", instance, crit );

    if (!this->cleanup.critical_section)
        this->cleanup.critical_section = crit;
}

2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
/***********************************************************************
 *           TpCallbackMayRunLong    (NTDLL.@)
 */
NTSTATUS WINAPI TpCallbackMayRunLong( TP_CALLBACK_INSTANCE *instance )
{
    struct threadpool_instance *this = impl_from_TP_CALLBACK_INSTANCE( instance );
    struct threadpool_object *object = this->object;
    struct threadpool *pool;
    NTSTATUS status = STATUS_SUCCESS;

    TRACE( "%p\n", instance );

    if (this->threadid != GetCurrentThreadId())
    {
        ERR("called from wrong thread, ignoring\n");
        return STATUS_UNSUCCESSFUL; /* FIXME */
    }

    if (this->may_run_long)
        return STATUS_SUCCESS;

    pool = object->pool;
    RtlEnterCriticalSection( &pool->cs );

    /* Start new worker threads if required. */
    if (pool->num_busy_workers >= pool->num_workers)
    {
        if (pool->num_workers < pool->max_workers)
        {
2423
            status = tp_new_worker_thread( pool );
2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
        }
        else
        {
            status = STATUS_TOO_MANY_THREADS;
        }
    }

    RtlLeaveCriticalSection( &pool->cs );
    this->may_run_long = TRUE;
    return status;
}

2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448
/***********************************************************************
 *           TpCallbackReleaseMutexOnCompletion    (NTDLL.@)
 */
VOID WINAPI TpCallbackReleaseMutexOnCompletion( TP_CALLBACK_INSTANCE *instance, HANDLE mutex )
{
    struct threadpool_instance *this = impl_from_TP_CALLBACK_INSTANCE( instance );

    TRACE( "%p %p\n", instance, mutex );

    if (!this->cleanup.mutex)
        this->cleanup.mutex = mutex;
}

2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464
/***********************************************************************
 *           TpCallbackReleaseSemaphoreOnCompletion    (NTDLL.@)
 */
VOID WINAPI TpCallbackReleaseSemaphoreOnCompletion( TP_CALLBACK_INSTANCE *instance, HANDLE semaphore, DWORD count )
{
    struct threadpool_instance *this = impl_from_TP_CALLBACK_INSTANCE( instance );

    TRACE( "%p %p %u\n", instance, semaphore, count );

    if (!this->cleanup.semaphore)
    {
        this->cleanup.semaphore = semaphore;
        this->cleanup.semaphore_count = count;
    }
}

2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
/***********************************************************************
 *           TpCallbackSetEventOnCompletion    (NTDLL.@)
 */
VOID WINAPI TpCallbackSetEventOnCompletion( TP_CALLBACK_INSTANCE *instance, HANDLE event )
{
    struct threadpool_instance *this = impl_from_TP_CALLBACK_INSTANCE( instance );

    TRACE( "%p %p\n", instance, event );

    if (!this->cleanup.event)
        this->cleanup.event = event;
}

2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
/***********************************************************************
 *           TpCallbackUnloadDllOnCompletion    (NTDLL.@)
 */
VOID WINAPI TpCallbackUnloadDllOnCompletion( TP_CALLBACK_INSTANCE *instance, HMODULE module )
{
    struct threadpool_instance *this = impl_from_TP_CALLBACK_INSTANCE( instance );

    TRACE( "%p %p\n", instance, module );

    if (!this->cleanup.library)
        this->cleanup.library = module;
}

2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
/***********************************************************************
 *           TpDisassociateCallback    (NTDLL.@)
 */
VOID WINAPI TpDisassociateCallback( TP_CALLBACK_INSTANCE *instance )
{
    struct threadpool_instance *this = impl_from_TP_CALLBACK_INSTANCE( instance );
    struct threadpool_object *object = this->object;
    struct threadpool *pool;

    TRACE( "%p\n", instance );

    if (this->threadid != GetCurrentThreadId())
    {
        ERR("called from wrong thread, ignoring\n");
        return;
    }

    if (!this->associated)
        return;

    pool = object->pool;
    RtlEnterCriticalSection( &pool->cs );

    object->num_associated_callbacks--;
    if (!object->num_pending_callbacks && !object->num_associated_callbacks)
        RtlWakeAllConditionVariable( &object->finished_event );

    RtlLeaveCriticalSection( &pool->cs );
    this->associated = FALSE;
}

2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
/***********************************************************************
 *           TpIsTimerSet    (NTDLL.@)
 */
BOOL WINAPI TpIsTimerSet( TP_TIMER *timer )
{
    struct threadpool_object *this = impl_from_TP_TIMER( timer );

    TRACE( "%p\n", timer );

    return this->u.timer.timer_set;
}

2534 2535 2536 2537 2538 2539 2540 2541 2542
/***********************************************************************
 *           TpPostWork    (NTDLL.@)
 */
VOID WINAPI TpPostWork( TP_WORK *work )
{
    struct threadpool_object *this = impl_from_TP_WORK( work );

    TRACE( "%p\n", work );

2543
    tp_object_submit( this, FALSE );
2544 2545
}

2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
/***********************************************************************
 *           TpReleaseCleanupGroup    (NTDLL.@)
 */
VOID WINAPI TpReleaseCleanupGroup( TP_CLEANUP_GROUP *group )
{
    struct threadpool_group *this = impl_from_TP_CLEANUP_GROUP( group );

    TRACE( "%p\n", group );

    tp_group_shutdown( this );
    tp_group_release( this );
}

/***********************************************************************
 *           TpReleaseCleanupGroupMembers    (NTDLL.@)
 */
VOID WINAPI TpReleaseCleanupGroupMembers( TP_CLEANUP_GROUP *group, BOOL cancel_pending, PVOID userdata )
{
    struct threadpool_group *this = impl_from_TP_CLEANUP_GROUP( group );
    struct threadpool_object *object, *next;
    struct list members;

    TRACE( "%p %u %p\n", group, cancel_pending, userdata );

    RtlEnterCriticalSection( &this->cs );

    /* Unset group, increase references, and mark objects for shutdown */
    LIST_FOR_EACH_ENTRY_SAFE( object, next, &this->members, struct threadpool_object, group_entry )
    {
        assert( object->group == this );
        assert( object->is_group_member );

2578
        if (interlocked_inc( &object->refcount ) == 1)
2579
        {
2580 2581 2582 2583 2584 2585
            /* Object is basically already destroyed, but group reference
             * was not deleted yet. We can safely ignore this object. */
            interlocked_dec( &object->refcount );
            list_remove( &object->group_entry );
            object->is_group_member = FALSE;
            continue;
2586 2587 2588
        }

        object->is_group_member = FALSE;
2589
        tp_object_prepare_shutdown( object );
2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
    }

    /* Move members to a new temporary list */
    list_init( &members );
    list_move_tail( &members, &this->members );

    RtlLeaveCriticalSection( &this->cs );

    /* Cancel pending callbacks if requested */
    if (cancel_pending)
    {
        LIST_FOR_EACH_ENTRY( object, &members, struct threadpool_object, group_entry )
        {
2603
            tp_object_cancel( object );
2604 2605 2606 2607 2608 2609
        }
    }

    /* Wait for remaining callbacks to finish */
    LIST_FOR_EACH_ENTRY_SAFE( object, next, &members, struct threadpool_object, group_entry )
    {
2610
        tp_object_wait( object, TRUE );
2611

2612
        if (!object->shutdown)
2613
        {
2614 2615 2616 2617 2618 2619 2620 2621
            /* Execute group cancellation callback if defined, and if this was actually a group cancel. */
            if (cancel_pending && object->group_cancel_callback)
            {
                TRACE( "executing group cancel callback %p(%p, %p)\n",
                       object->group_cancel_callback, object->userdata, userdata );
                object->group_cancel_callback( object->userdata, userdata );
                TRACE( "callback %p returned\n", object->group_cancel_callback );
            }
2622

2623 2624 2625
            if (object->type != TP_OBJECT_TYPE_SIMPLE)
                tp_object_release( object );
        }
2626 2627

        object->shutdown = TRUE;
2628 2629 2630 2631
        tp_object_release( object );
    }
}

2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
/***********************************************************************
 *           TpReleasePool    (NTDLL.@)
 */
VOID WINAPI TpReleasePool( TP_POOL *pool )
{
    struct threadpool *this = impl_from_TP_POOL( pool );

    TRACE( "%p\n", pool );

    tp_threadpool_shutdown( this );
    tp_threadpool_release( this );
}

2645 2646 2647 2648 2649 2650 2651 2652 2653
/***********************************************************************
 *           TpReleaseTimer     (NTDLL.@)
 */
VOID WINAPI TpReleaseTimer( TP_TIMER *timer )
{
    struct threadpool_object *this = impl_from_TP_TIMER( timer );

    TRACE( "%p\n", timer );

2654 2655
    tp_object_prepare_shutdown( this );
    this->shutdown = TRUE;
2656 2657 2658
    tp_object_release( this );
}

2659 2660 2661 2662 2663 2664 2665 2666 2667
/***********************************************************************
 *           TpReleaseWait    (NTDLL.@)
 */
VOID WINAPI TpReleaseWait( TP_WAIT *wait )
{
    struct threadpool_object *this = impl_from_TP_WAIT( wait );

    TRACE( "%p\n", wait );

2668 2669
    tp_object_prepare_shutdown( this );
    this->shutdown = TRUE;
2670 2671 2672
    tp_object_release( this );
}

2673 2674 2675 2676 2677 2678 2679 2680 2681
/***********************************************************************
 *           TpReleaseWork    (NTDLL.@)
 */
VOID WINAPI TpReleaseWork( TP_WORK *work )
{
    struct threadpool_object *this = impl_from_TP_WORK( work );

    TRACE( "%p\n", work );

2682 2683
    tp_object_prepare_shutdown( this );
    this->shutdown = TRUE;
2684 2685 2686
    tp_object_release( this );
}

2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
/***********************************************************************
 *           TpSetPoolMaxThreads    (NTDLL.@)
 */
VOID WINAPI TpSetPoolMaxThreads( TP_POOL *pool, DWORD maximum )
{
    struct threadpool *this = impl_from_TP_POOL( pool );

    TRACE( "%p %u\n", pool, maximum );

    RtlEnterCriticalSection( &this->cs );
    this->max_workers = max( maximum, 1 );
    this->min_workers = min( this->min_workers, this->max_workers );
    RtlLeaveCriticalSection( &this->cs );
}

2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
/***********************************************************************
 *           TpSetPoolMinThreads    (NTDLL.@)
 */
BOOL WINAPI TpSetPoolMinThreads( TP_POOL *pool, DWORD minimum )
{
    struct threadpool *this = impl_from_TP_POOL( pool );
    NTSTATUS status = STATUS_SUCCESS;

    TRACE( "%p %u\n", pool, minimum );

    RtlEnterCriticalSection( &this->cs );

    while (this->num_workers < minimum)
    {
2716
        status = tp_new_worker_thread( this );
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
        if (status != STATUS_SUCCESS)
            break;
    }

    if (status == STATUS_SUCCESS)
    {
        this->min_workers = minimum;
        this->max_workers = max( this->min_workers, this->max_workers );
    }

    RtlLeaveCriticalSection( &this->cs );
    return !status;
}

2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
/***********************************************************************
 *           TpSetTimer    (NTDLL.@)
 */
VOID WINAPI TpSetTimer( TP_TIMER *timer, LARGE_INTEGER *timeout, LONG period, LONG window_length )
{
    struct threadpool_object *this = impl_from_TP_TIMER( timer );
    struct threadpool_object *other_timer;
    BOOL submit_timer = FALSE;
    ULONGLONG timestamp;

    TRACE( "%p %p %u %u\n", timer, timeout, period, window_length );

    RtlEnterCriticalSection( &timerqueue.cs );

    assert( this->u.timer.timer_initialized );
    this->u.timer.timer_set = timeout != NULL;

    /* Convert relative timeout to absolute timestamp and handle a timeout
     * of zero, which means that the timer is submitted immediately. */
    if (timeout)
    {
        timestamp = timeout->QuadPart;
        if ((LONGLONG)timestamp < 0)
        {
            LARGE_INTEGER now;
            NtQuerySystemTime( &now );
            timestamp = now.QuadPart - timestamp;
        }
        else if (!timestamp)
        {
            if (!period)
                timeout = NULL;
            else
            {
                LARGE_INTEGER now;
                NtQuerySystemTime( &now );
                timestamp = now.QuadPart + (ULONGLONG)period * 10000;
            }
            submit_timer = TRUE;
        }
    }

    /* First remove existing timeout. */
    if (this->u.timer.timer_pending)
    {
        list_remove( &this->u.timer.timer_entry );
        this->u.timer.timer_pending = FALSE;
    }

    /* If the timer was enabled, then add it back to the queue. */
    if (timeout)
    {
        this->u.timer.timeout       = timestamp;
        this->u.timer.period        = period;
        this->u.timer.window_length = window_length;

        LIST_FOR_EACH_ENTRY( other_timer, &timerqueue.pending_timers,
                             struct threadpool_object, u.timer.timer_entry )
        {
            assert( other_timer->type == TP_OBJECT_TYPE_TIMER );
            if (this->u.timer.timeout < other_timer->u.timer.timeout)
                break;
        }
        list_add_before( &other_timer->u.timer.timer_entry, &this->u.timer.timer_entry );

        /* Wake up the timer thread when the timeout has to be updated. */
        if (list_head( &timerqueue.pending_timers ) == &this->u.timer.timer_entry )
            RtlWakeAllConditionVariable( &timerqueue.update_event );

        this->u.timer.timer_pending = TRUE;
    }

    RtlLeaveCriticalSection( &timerqueue.cs );

    if (submit_timer)
2806
       tp_object_submit( this, FALSE );
2807 2808
}

2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
/***********************************************************************
 *           TpSetWait    (NTDLL.@)
 */
VOID WINAPI TpSetWait( TP_WAIT *wait, HANDLE handle, LARGE_INTEGER *timeout )
{
    struct threadpool_object *this = impl_from_TP_WAIT( wait );
    ULONGLONG timestamp = TIMEOUT_INFINITE;
    BOOL submit_wait = FALSE;

    TRACE( "%p %p %p\n", wait, handle, timeout );

    RtlEnterCriticalSection( &waitqueue.cs );

    assert( this->u.wait.bucket );
    this->u.wait.handle = handle;

    if (handle || this->u.wait.wait_pending)
    {
        struct waitqueue_bucket *bucket = this->u.wait.bucket;
        list_remove( &this->u.wait.wait_entry );

        /* Convert relative timeout to absolute timestamp. */
        if (handle && timeout)
        {
            timestamp = timeout->QuadPart;
            if ((LONGLONG)timestamp < 0)
            {
                LARGE_INTEGER now;
                NtQuerySystemTime( &now );
                timestamp = now.QuadPart - timestamp;
            }
            else if (!timestamp)
            {
                submit_wait = TRUE;
                handle = NULL;
            }
        }

        /* Add wait object back into one of the queues. */
        if (handle)
        {
            list_add_tail( &bucket->waiting, &this->u.wait.wait_entry );
            this->u.wait.wait_pending = TRUE;
            this->u.wait.timeout = timestamp;
        }
        else
        {
            list_add_tail( &bucket->reserved, &this->u.wait.wait_entry );
            this->u.wait.wait_pending = FALSE;
        }

        /* Wake up the wait queue thread. */
        NtSetEvent( bucket->update_event, NULL );
    }

    RtlLeaveCriticalSection( &waitqueue.cs );

    if (submit_wait)
        tp_object_submit( this, FALSE );
}

2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
/***********************************************************************
 *           TpSimpleTryPost    (NTDLL.@)
 */
NTSTATUS WINAPI TpSimpleTryPost( PTP_SIMPLE_CALLBACK callback, PVOID userdata,
                                 TP_CALLBACK_ENVIRON *environment )
{
    struct threadpool_object *object;
    struct threadpool *pool;
    NTSTATUS status;

    TRACE( "%p %p %p\n", callback, userdata, environment );

    object = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*object) );
    if (!object)
        return STATUS_NO_MEMORY;

    status = tp_threadpool_lock( &pool, environment );
    if (status)
    {
        RtlFreeHeap( GetProcessHeap(), 0, object );
        return status;
    }

    object->type = TP_OBJECT_TYPE_SIMPLE;
    object->u.simple.callback = callback;
    tp_object_initialize( object, pool, userdata, environment );

    return STATUS_SUCCESS;
}
2899

2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
/***********************************************************************
 *           TpWaitForTimer    (NTDLL.@)
 */
VOID WINAPI TpWaitForTimer( TP_TIMER *timer, BOOL cancel_pending )
{
    struct threadpool_object *this = impl_from_TP_TIMER( timer );

    TRACE( "%p %d\n", timer, cancel_pending );

    if (cancel_pending)
2910
        tp_object_cancel( this );
2911 2912 2913
    tp_object_wait( this, FALSE );
}

2914 2915 2916 2917 2918 2919 2920 2921 2922 2923
/***********************************************************************
 *           TpWaitForWait    (NTDLL.@)
 */
VOID WINAPI TpWaitForWait( TP_WAIT *wait, BOOL cancel_pending )
{
    struct threadpool_object *this = impl_from_TP_WAIT( wait );

    TRACE( "%p %d\n", wait, cancel_pending );

    if (cancel_pending)
2924
        tp_object_cancel( this );
2925 2926 2927
    tp_object_wait( this, FALSE );
}

2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
/***********************************************************************
 *           TpWaitForWork    (NTDLL.@)
 */
VOID WINAPI TpWaitForWork( TP_WORK *work, BOOL cancel_pending )
{
    struct threadpool_object *this = impl_from_TP_WORK( work );

    TRACE( "%p %u\n", work, cancel_pending );

    if (cancel_pending)
2938
        tp_object_cancel( this );
2939
    tp_object_wait( this, FALSE );
2940
}