wined3d: Keep track of what fixed function texture stages are in use.
[wine] / dlls / ntdll / sync.c
1 /*
2  *      Process synchronisation
3  *
4  * Copyright 1996, 1997, 1998 Marcus Meissner
5  * Copyright 1997, 1999 Alexandre Julliard
6  * Copyright 1999, 2000 Juergen Schmied
7  * Copyright 2003 Eric Pouech
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include "config.h"
25
26 #include <assert.h>
27 #include <errno.h>
28 #include <signal.h>
29 #ifdef HAVE_SYS_TIME_H
30 # include <sys/time.h>
31 #endif
32 #ifdef HAVE_POLL_H
33 #include <poll.h>
34 #endif
35 #ifdef HAVE_SYS_POLL_H
36 # include <sys/poll.h>
37 #endif
38 #ifdef HAVE_UNISTD_H
39 # include <unistd.h>
40 #endif
41 #ifdef HAVE_SCHED_H
42 # include <sched.h>
43 #endif
44 #include <string.h>
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <time.h>
49
50 #define NONAMELESSUNION
51 #define NONAMELESSSTRUCT
52
53 #include "ntstatus.h"
54 #define WIN32_NO_STATUS
55 #include "windef.h"
56 #include "thread.h"
57 #include "wine/server.h"
58 #include "wine/debug.h"
59 #include "ntdll_misc.h"
60
61 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
62
63
64 /*
65  *      Semaphores
66  */
67
68 /******************************************************************************
69  *  NtCreateSemaphore (NTDLL.@)
70  */
71 NTSTATUS WINAPI NtCreateSemaphore( OUT PHANDLE SemaphoreHandle,
72                                    IN ACCESS_MASK access,
73                                    IN const OBJECT_ATTRIBUTES *attr OPTIONAL,
74                                    IN LONG InitialCount,
75                                    IN LONG MaximumCount )
76 {
77     DWORD len = attr && attr->ObjectName ? attr->ObjectName->Length : 0;
78     NTSTATUS ret;
79
80     if (MaximumCount <= 0 || InitialCount < 0 || InitialCount > MaximumCount)
81         return STATUS_INVALID_PARAMETER;
82     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
83
84     SERVER_START_REQ( create_semaphore )
85     {
86         req->access  = access;
87         req->attributes = (attr) ? attr->Attributes : 0;
88         req->rootdir = attr ? attr->RootDirectory : 0;
89         req->initial = InitialCount;
90         req->max     = MaximumCount;
91         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
92         ret = wine_server_call( req );
93         *SemaphoreHandle = reply->handle;
94     }
95     SERVER_END_REQ;
96     return ret;
97 }
98
99 /******************************************************************************
100  *  NtOpenSemaphore (NTDLL.@)
101  */
102 NTSTATUS WINAPI NtOpenSemaphore( OUT PHANDLE SemaphoreHandle,
103                                  IN ACCESS_MASK access,
104                                  IN const OBJECT_ATTRIBUTES *attr )
105 {
106     DWORD len = attr && attr->ObjectName ? attr->ObjectName->Length : 0;
107     NTSTATUS ret;
108
109     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
110
111     SERVER_START_REQ( open_semaphore )
112     {
113         req->access  = access;
114         req->attributes = (attr) ? attr->Attributes : 0;
115         req->rootdir = attr ? attr->RootDirectory : 0;
116         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
117         ret = wine_server_call( req );
118         *SemaphoreHandle = reply->handle;
119     }
120     SERVER_END_REQ;
121     return ret;
122 }
123
124 /******************************************************************************
125  *  NtQuerySemaphore (NTDLL.@)
126  */
127 NTSTATUS WINAPI NtQuerySemaphore(
128         HANDLE SemaphoreHandle,
129         SEMAPHORE_INFORMATION_CLASS SemaphoreInformationClass,
130         PVOID SemaphoreInformation,
131         ULONG Length,
132         PULONG ReturnLength)
133 {
134         FIXME("(%p,%d,%p,0x%08x,%p) stub!\n",
135         SemaphoreHandle, SemaphoreInformationClass, SemaphoreInformation, Length, ReturnLength);
136         return STATUS_SUCCESS;
137 }
138
139 /******************************************************************************
140  *  NtReleaseSemaphore (NTDLL.@)
141  */
142 NTSTATUS WINAPI NtReleaseSemaphore( HANDLE handle, ULONG count, PULONG previous )
143 {
144     NTSTATUS ret;
145     SERVER_START_REQ( release_semaphore )
146     {
147         req->handle = handle;
148         req->count  = count;
149         if (!(ret = wine_server_call( req )))
150         {
151             if (previous) *previous = reply->prev_count;
152         }
153     }
154     SERVER_END_REQ;
155     return ret;
156 }
157
158 /*
159  *      Events
160  */
161
162 /**************************************************************************
163  * NtCreateEvent (NTDLL.@)
164  * ZwCreateEvent (NTDLL.@)
165  */
166 NTSTATUS WINAPI NtCreateEvent(
167         OUT PHANDLE EventHandle,
168         IN ACCESS_MASK DesiredAccess,
169         IN const OBJECT_ATTRIBUTES *attr,
170         IN BOOLEAN ManualReset,
171         IN BOOLEAN InitialState)
172 {
173     DWORD len = attr && attr->ObjectName ? attr->ObjectName->Length : 0;
174     NTSTATUS ret;
175
176     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
177
178     SERVER_START_REQ( create_event )
179     {
180         req->access = DesiredAccess;
181         req->attributes = (attr) ? attr->Attributes : 0;
182         req->rootdir = attr ? attr->RootDirectory : 0;
183         req->manual_reset = ManualReset;
184         req->initial_state = InitialState;
185         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
186         ret = wine_server_call( req );
187         *EventHandle = reply->handle;
188     }
189     SERVER_END_REQ;
190     return ret;
191 }
192
193 /******************************************************************************
194  *  NtOpenEvent (NTDLL.@)
195  *  ZwOpenEvent (NTDLL.@)
196  */
197 NTSTATUS WINAPI NtOpenEvent(
198         OUT PHANDLE EventHandle,
199         IN ACCESS_MASK DesiredAccess,
200         IN const OBJECT_ATTRIBUTES *attr )
201 {
202     DWORD len = attr && attr->ObjectName ? attr->ObjectName->Length : 0;
203     NTSTATUS ret;
204
205     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
206
207     SERVER_START_REQ( open_event )
208     {
209         req->access  = DesiredAccess;
210         req->attributes = (attr) ? attr->Attributes : 0;
211         req->rootdir = attr ? attr->RootDirectory : 0;
212         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
213         ret = wine_server_call( req );
214         *EventHandle = reply->handle;
215     }
216     SERVER_END_REQ;
217     return ret;
218 }
219
220
221 /******************************************************************************
222  *  NtSetEvent (NTDLL.@)
223  *  ZwSetEvent (NTDLL.@)
224  */
225 NTSTATUS WINAPI NtSetEvent( HANDLE handle, PULONG NumberOfThreadsReleased )
226 {
227     NTSTATUS ret;
228
229     /* FIXME: set NumberOfThreadsReleased */
230
231     SERVER_START_REQ( event_op )
232     {
233         req->handle = handle;
234         req->op     = SET_EVENT;
235         ret = wine_server_call( req );
236     }
237     SERVER_END_REQ;
238     return ret;
239 }
240
241 /******************************************************************************
242  *  NtResetEvent (NTDLL.@)
243  */
244 NTSTATUS WINAPI NtResetEvent( HANDLE handle, PULONG NumberOfThreadsReleased )
245 {
246     NTSTATUS ret;
247
248     /* resetting an event can't release any thread... */
249     if (NumberOfThreadsReleased) *NumberOfThreadsReleased = 0;
250
251     SERVER_START_REQ( event_op )
252     {
253         req->handle = handle;
254         req->op     = RESET_EVENT;
255         ret = wine_server_call( req );
256     }
257     SERVER_END_REQ;
258     return ret;
259 }
260
261 /******************************************************************************
262  *  NtClearEvent (NTDLL.@)
263  *
264  * FIXME
265  *   same as NtResetEvent ???
266  */
267 NTSTATUS WINAPI NtClearEvent ( HANDLE handle )
268 {
269     return NtResetEvent( handle, NULL );
270 }
271
272 /******************************************************************************
273  *  NtPulseEvent (NTDLL.@)
274  *
275  * FIXME
276  *   PulseCount
277  */
278 NTSTATUS WINAPI NtPulseEvent( HANDLE handle, PULONG PulseCount )
279 {
280     NTSTATUS ret;
281
282     if (PulseCount)
283       FIXME("(%p,%d)\n", handle, *PulseCount);
284
285     SERVER_START_REQ( event_op )
286     {
287         req->handle = handle;
288         req->op     = PULSE_EVENT;
289         ret = wine_server_call( req );
290     }
291     SERVER_END_REQ;
292     return ret;
293 }
294
295 /******************************************************************************
296  *  NtQueryEvent (NTDLL.@)
297  */
298 NTSTATUS WINAPI NtQueryEvent (
299         IN  HANDLE EventHandle,
300         IN  UINT EventInformationClass,
301         OUT PVOID EventInformation,
302         IN  ULONG EventInformationLength,
303         OUT PULONG  ReturnLength)
304 {
305         FIXME("(%p)\n", EventHandle);
306         return STATUS_SUCCESS;
307 }
308
309 /*
310  *      Mutants (known as Mutexes in Kernel32)
311  */
312
313 /******************************************************************************
314  *              NtCreateMutant                          [NTDLL.@]
315  *              ZwCreateMutant                          [NTDLL.@]
316  */
317 NTSTATUS WINAPI NtCreateMutant(OUT HANDLE* MutantHandle,
318                                IN ACCESS_MASK access,
319                                IN const OBJECT_ATTRIBUTES* attr OPTIONAL,
320                                IN BOOLEAN InitialOwner)
321 {
322     NTSTATUS    status;
323     DWORD       len = attr && attr->ObjectName ? attr->ObjectName->Length : 0;
324
325     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
326
327     SERVER_START_REQ( create_mutex )
328     {
329         req->access  = access;
330         req->attributes = (attr) ? attr->Attributes : 0;
331         req->rootdir = attr ? attr->RootDirectory : 0;
332         req->owned   = InitialOwner;
333         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
334         status = wine_server_call( req );
335         *MutantHandle = reply->handle;
336     }
337     SERVER_END_REQ;
338     return status;
339 }
340
341 /**************************************************************************
342  *              NtOpenMutant                            [NTDLL.@]
343  *              ZwOpenMutant                            [NTDLL.@]
344  */
345 NTSTATUS WINAPI NtOpenMutant(OUT HANDLE* MutantHandle, 
346                              IN ACCESS_MASK access, 
347                              IN const OBJECT_ATTRIBUTES* attr )
348 {
349     NTSTATUS    status;
350     DWORD       len = attr && attr->ObjectName ? attr->ObjectName->Length : 0;
351
352     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
353
354     SERVER_START_REQ( open_mutex )
355     {
356         req->access  = access;
357         req->attributes = (attr) ? attr->Attributes : 0;
358         req->rootdir = attr ? attr->RootDirectory : 0;
359         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
360         status = wine_server_call( req );
361         *MutantHandle = reply->handle;
362     }
363     SERVER_END_REQ;
364     return status;
365 }
366
367 /**************************************************************************
368  *              NtReleaseMutant                         [NTDLL.@]
369  *              ZwReleaseMutant                         [NTDLL.@]
370  */
371 NTSTATUS WINAPI NtReleaseMutant( IN HANDLE handle, OUT PLONG prev_count OPTIONAL)
372 {
373     NTSTATUS    status;
374
375     SERVER_START_REQ( release_mutex )
376     {
377         req->handle = handle;
378         status = wine_server_call( req );
379         if (prev_count) *prev_count = reply->prev_count;
380     }
381     SERVER_END_REQ;
382     return status;
383 }
384
385 /******************************************************************
386  *              NtQueryMutant                   [NTDLL.@]
387  *              ZwQueryMutant                   [NTDLL.@]
388  */
389 NTSTATUS WINAPI NtQueryMutant(IN HANDLE handle, 
390                               IN MUTANT_INFORMATION_CLASS MutantInformationClass, 
391                               OUT PVOID MutantInformation, 
392                               IN ULONG MutantInformationLength, 
393                               OUT PULONG ResultLength OPTIONAL )
394 {
395     FIXME("(%p %u %p %u %p): stub!\n", 
396           handle, MutantInformationClass, MutantInformation, MutantInformationLength, ResultLength);
397     return STATUS_NOT_IMPLEMENTED;
398 }
399
400 /*
401  *      Timers
402  */
403
404 /**************************************************************************
405  *              NtCreateTimer                           [NTDLL.@]
406  *              ZwCreateTimer                           [NTDLL.@]
407  */
408 NTSTATUS WINAPI NtCreateTimer(OUT HANDLE *handle,
409                               IN ACCESS_MASK access,
410                               IN const OBJECT_ATTRIBUTES *attr OPTIONAL,
411                               IN TIMER_TYPE timer_type)
412 {
413     DWORD       len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
414     NTSTATUS    status;
415
416     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
417
418     if (timer_type != NotificationTimer && timer_type != SynchronizationTimer)
419         return STATUS_INVALID_PARAMETER;
420
421     SERVER_START_REQ( create_timer )
422     {
423         req->access  = access;
424         req->attributes = (attr) ? attr->Attributes : 0;
425         req->rootdir = attr ? attr->RootDirectory : 0;
426         req->manual  = (timer_type == NotificationTimer) ? TRUE : FALSE;
427         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
428         status = wine_server_call( req );
429         *handle = reply->handle;
430     }
431     SERVER_END_REQ;
432     return status;
433
434 }
435
436 /**************************************************************************
437  *              NtOpenTimer                             [NTDLL.@]
438  *              ZwOpenTimer                             [NTDLL.@]
439  */
440 NTSTATUS WINAPI NtOpenTimer(OUT PHANDLE handle,
441                             IN ACCESS_MASK access,
442                             IN const OBJECT_ATTRIBUTES* attr )
443 {
444     DWORD       len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
445     NTSTATUS    status;
446
447     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
448
449     SERVER_START_REQ( open_timer )
450     {
451         req->access  = access;
452         req->attributes = (attr) ? attr->Attributes : 0;
453         req->rootdir = attr ? attr->RootDirectory : 0;
454         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
455         status = wine_server_call( req );
456         *handle = reply->handle;
457     }
458     SERVER_END_REQ;
459     return status;
460 }
461
462 /**************************************************************************
463  *              NtSetTimer                              [NTDLL.@]
464  *              ZwSetTimer                              [NTDLL.@]
465  */
466 NTSTATUS WINAPI NtSetTimer(IN HANDLE handle,
467                            IN const LARGE_INTEGER* when,
468                            IN PTIMER_APC_ROUTINE callback,
469                            IN PVOID callback_arg,
470                            IN BOOLEAN resume,
471                            IN ULONG period OPTIONAL,
472                            OUT PBOOLEAN state OPTIONAL)
473 {
474     NTSTATUS    status = STATUS_SUCCESS;
475
476     TRACE("(%p,%p,%p,%p,%08x,0x%08x,%p) stub\n",
477           handle, when, callback, callback_arg, resume, period, state);
478
479     SERVER_START_REQ( set_timer )
480     {
481         req->handle   = handle;
482         req->period   = period;
483         req->expire   = when->QuadPart;
484         req->callback = callback;
485         req->arg      = callback_arg;
486         status = wine_server_call( req );
487         if (state) *state = reply->signaled;
488     }
489     SERVER_END_REQ;
490
491     /* set error but can still succeed */
492     if (resume && status == STATUS_SUCCESS) return STATUS_TIMER_RESUME_IGNORED;
493     return status;
494 }
495
496 /**************************************************************************
497  *              NtCancelTimer                           [NTDLL.@]
498  *              ZwCancelTimer                           [NTDLL.@]
499  */
500 NTSTATUS WINAPI NtCancelTimer(IN HANDLE handle, OUT BOOLEAN* state)
501 {
502     NTSTATUS    status;
503
504     SERVER_START_REQ( cancel_timer )
505     {
506         req->handle = handle;
507         status = wine_server_call( req );
508         if (state) *state = reply->signaled;
509     }
510     SERVER_END_REQ;
511     return status;
512 }
513
514 /******************************************************************************
515  *  NtQueryTimer (NTDLL.@)
516  *
517  * Retrieves information about a timer.
518  *
519  * PARAMS
520  *  TimerHandle           [I] The timer to retrieve information about.
521  *  TimerInformationClass [I] The type of information to retrieve.
522  *  TimerInformation      [O] Pointer to buffer to store information in.
523  *  Length                [I] The length of the buffer pointed to by TimerInformation.
524  *  ReturnLength          [O] Optional. The size of buffer actually used.
525  *
526  * RETURNS
527  *  Success: STATUS_SUCCESS
528  *  Failure: STATUS_INFO_LENGTH_MISMATCH, if Length doesn't match the required data
529  *           size for the class specified.
530  *           STATUS_INVALID_INFO_CLASS, if an invalid TimerInformationClass was specified.
531  *           STATUS_ACCESS_DENIED, if TimerHandle does not have TIMER_QUERY_STATE access
532  *           to the timer.
533  */
534 NTSTATUS WINAPI NtQueryTimer(
535     HANDLE TimerHandle,
536     TIMER_INFORMATION_CLASS TimerInformationClass,
537     PVOID TimerInformation,
538     ULONG Length,
539     PULONG ReturnLength)
540 {
541     TIMER_BASIC_INFORMATION * basic_info = (TIMER_BASIC_INFORMATION *)TimerInformation;
542     NTSTATUS status;
543     LARGE_INTEGER now;
544
545     TRACE("(%p,%d,%p,0x%08x,%p)\n", TimerHandle, TimerInformationClass,
546        TimerInformation, Length, ReturnLength);
547
548     switch (TimerInformationClass)
549     {
550     case TimerBasicInformation:
551         if (Length < sizeof(TIMER_BASIC_INFORMATION))
552             return STATUS_INFO_LENGTH_MISMATCH;
553
554         SERVER_START_REQ(get_timer_info)
555         {
556             req->handle = TimerHandle;
557             status = wine_server_call(req);
558
559             /* convert server time to absolute NTDLL time */
560             basic_info->RemainingTime.QuadPart = reply->when;
561             basic_info->TimerState = reply->signaled;
562         }
563         SERVER_END_REQ;
564
565         /* convert from absolute into relative time */
566         NtQuerySystemTime(&now);
567         if (now.QuadPart > basic_info->RemainingTime.QuadPart)
568             basic_info->RemainingTime.QuadPart = 0;
569         else
570             basic_info->RemainingTime.QuadPart -= now.QuadPart;
571
572         if (ReturnLength) *ReturnLength = sizeof(TIMER_BASIC_INFORMATION);
573
574         return status;
575     }
576
577     FIXME("Unhandled class %d\n", TimerInformationClass);
578     return STATUS_INVALID_INFO_CLASS;
579 }
580
581
582 /******************************************************************************
583  * NtQueryTimerResolution [NTDLL.@]
584  */
585 NTSTATUS WINAPI NtQueryTimerResolution(OUT ULONG* min_resolution,
586                                        OUT ULONG* max_resolution,
587                                        OUT ULONG* current_resolution)
588 {
589     FIXME("(%p,%p,%p), stub!\n",
590           min_resolution, max_resolution, current_resolution);
591
592     return STATUS_NOT_IMPLEMENTED;
593 }
594
595 /******************************************************************************
596  * NtSetTimerResolution [NTDLL.@]
597  */
598 NTSTATUS WINAPI NtSetTimerResolution(IN ULONG resolution,
599                                      IN BOOLEAN set_resolution,
600                                      OUT ULONG* current_resolution )
601 {
602     FIXME("(%u,%u,%p), stub!\n",
603           resolution, set_resolution, current_resolution);
604
605     return STATUS_NOT_IMPLEMENTED;
606 }
607
608
609 /***********************************************************************
610  *              wait_reply
611  *
612  * Wait for a reply on the waiting pipe of the current thread.
613  */
614 static int wait_reply( void *cookie )
615 {
616     int signaled;
617     struct wake_up_reply reply;
618     for (;;)
619     {
620         int ret;
621         ret = read( ntdll_get_thread_data()->wait_fd[0], &reply, sizeof(reply) );
622         if (ret == sizeof(reply))
623         {
624             if (!reply.cookie) break;  /* thread got killed */
625             if (reply.cookie == cookie) return reply.signaled;
626             /* we stole another reply, wait for the real one */
627             signaled = wait_reply( cookie );
628             /* and now put the wrong one back in the pipe */
629             for (;;)
630             {
631                 ret = write( ntdll_get_thread_data()->wait_fd[1], &reply, sizeof(reply) );
632                 if (ret == sizeof(reply)) break;
633                 if (ret >= 0) server_protocol_error( "partial wakeup write %d\n", ret );
634                 if (errno == EINTR) continue;
635                 server_protocol_perror("wakeup write");
636             }
637             return signaled;
638         }
639         if (ret >= 0) server_protocol_error( "partial wakeup read %d\n", ret );
640         if (errno == EINTR) continue;
641         server_protocol_perror("wakeup read");
642     }
643     /* the server closed the connection; time to die... */
644     server_abort_thread(0);
645 }
646
647
648 /***********************************************************************
649  *              invoke_apc
650  *
651  * Invoke a single APC. Return TRUE if a user APC has been run.
652  */
653 static BOOL invoke_apc( const apc_call_t *call, apc_result_t *result )
654 {
655     BOOL user_apc = FALSE;
656
657     memset( result, 0, sizeof(*result) );
658
659     switch (call->type)
660     {
661     case APC_USER:
662         call->user.func( call->user.args[0], call->user.args[1], call->user.args[2] );
663         user_apc = TRUE;
664         break;
665     case APC_TIMER:
666         call->timer.func( call->timer.arg, (DWORD)call->timer.time, (DWORD)(call->timer.time >> 32) );
667         user_apc = TRUE;
668         break;
669     case APC_ASYNC_IO:
670         result->type = call->type;
671         result->async_io.status = call->async_io.func( call->async_io.user,
672                                                        call->async_io.sb,
673                                                        call->async_io.status );
674         break;
675     case APC_VIRTUAL_ALLOC:
676         result->type = call->type;
677         result->virtual_alloc.addr = call->virtual_alloc.addr;
678         result->virtual_alloc.size = call->virtual_alloc.size;
679         result->virtual_alloc.status = NtAllocateVirtualMemory( NtCurrentProcess(),
680                                                                 &result->virtual_alloc.addr,
681                                                                 call->virtual_alloc.zero_bits,
682                                                                 &result->virtual_alloc.size,
683                                                                 call->virtual_alloc.op_type,
684                                                                 call->virtual_alloc.prot );
685         break;
686     case APC_VIRTUAL_FREE:
687         result->type = call->type;
688         result->virtual_free.addr = call->virtual_free.addr;
689         result->virtual_free.size = call->virtual_free.size;
690         result->virtual_free.status = NtFreeVirtualMemory( NtCurrentProcess(),
691                                                            &result->virtual_free.addr,
692                                                            &result->virtual_free.size,
693                                                            call->virtual_free.op_type );
694         break;
695     case APC_VIRTUAL_QUERY:
696     {
697         MEMORY_BASIC_INFORMATION info;
698         result->type = call->type;
699         result->virtual_query.status = NtQueryVirtualMemory( NtCurrentProcess(),
700                                                              call->virtual_query.addr,
701                                                              MemoryBasicInformation, &info,
702                                                              sizeof(info), NULL );
703         if (result->virtual_query.status == STATUS_SUCCESS)
704         {
705             result->virtual_query.base       = info.BaseAddress;
706             result->virtual_query.alloc_base = info.AllocationBase;
707             result->virtual_query.size       = info.RegionSize;
708             result->virtual_query.state      = info.State;
709             result->virtual_query.prot       = info.Protect;
710             result->virtual_query.alloc_prot = info.AllocationProtect;
711             result->virtual_query.alloc_type = info.Type;
712         }
713         break;
714     }
715     case APC_VIRTUAL_PROTECT:
716         result->type = call->type;
717         result->virtual_protect.addr = call->virtual_protect.addr;
718         result->virtual_protect.size = call->virtual_protect.size;
719         result->virtual_protect.status = NtProtectVirtualMemory( NtCurrentProcess(),
720                                                                  &result->virtual_protect.addr,
721                                                                  &result->virtual_protect.size,
722                                                                  call->virtual_protect.prot,
723                                                                  &result->virtual_protect.prot );
724         break;
725     case APC_VIRTUAL_FLUSH:
726         result->type = call->type;
727         result->virtual_flush.addr = call->virtual_flush.addr;
728         result->virtual_flush.size = call->virtual_flush.size;
729         result->virtual_flush.status = NtFlushVirtualMemory( NtCurrentProcess(),
730                                                              &result->virtual_flush.addr,
731                                                              &result->virtual_flush.size, 0 );
732         break;
733     case APC_VIRTUAL_LOCK:
734         result->type = call->type;
735         result->virtual_lock.addr = call->virtual_lock.addr;
736         result->virtual_lock.size = call->virtual_lock.size;
737         result->virtual_lock.status = NtLockVirtualMemory( NtCurrentProcess(),
738                                                            &result->virtual_lock.addr,
739                                                            &result->virtual_lock.size, 0 );
740         break;
741     case APC_VIRTUAL_UNLOCK:
742         result->type = call->type;
743         result->virtual_unlock.addr = call->virtual_unlock.addr;
744         result->virtual_unlock.size = call->virtual_unlock.size;
745         result->virtual_unlock.status = NtUnlockVirtualMemory( NtCurrentProcess(),
746                                                                &result->virtual_unlock.addr,
747                                                                &result->virtual_unlock.size, 0 );
748         break;
749     case APC_MAP_VIEW:
750     {
751         LARGE_INTEGER offset;
752         result->type = call->type;
753         result->map_view.addr   = call->map_view.addr;
754         result->map_view.size   = call->map_view.size;
755         offset.u.LowPart        = call->map_view.offset_low;
756         offset.u.HighPart       = call->map_view.offset_high;
757         result->map_view.status = NtMapViewOfSection( call->map_view.handle, NtCurrentProcess(),
758                                                       &result->map_view.addr, call->map_view.zero_bits,
759                                                       0, &offset, &result->map_view.size, ViewShare,
760                                                       call->map_view.alloc_type, call->map_view.prot );
761         NtClose( call->map_view.handle );
762         break;
763     }
764     case APC_UNMAP_VIEW:
765         result->type = call->type;
766         result->unmap_view.status = NtUnmapViewOfSection( NtCurrentProcess(), call->unmap_view.addr );
767         break;
768     case APC_CREATE_THREAD:
769     {
770         CLIENT_ID id;
771         result->type = call->type;
772         result->create_thread.status = RtlCreateUserThread( NtCurrentProcess(), NULL,
773                                                             call->create_thread.suspend, NULL,
774                                                             call->create_thread.reserve,
775                                                             call->create_thread.commit,
776                                                             call->create_thread.func,
777                                                             call->create_thread.arg,
778                                                             &result->create_thread.handle, &id );
779         result->create_thread.tid = HandleToULong(id.UniqueThread);
780         break;
781     }
782     default:
783         server_protocol_error( "get_apc_request: bad type %d\n", call->type );
784         break;
785     }
786     return user_apc;
787 }
788
789 /***********************************************************************
790  *              call_apcs
791  *
792  * Call outstanding APCs. Return TRUE if a user APC has been run.
793  */
794 static BOOL call_apcs( BOOL alertable )
795 {
796     BOOL user_apc = FALSE;
797     NTSTATUS ret;
798     apc_call_t call;
799     apc_result_t result;
800     HANDLE handle = 0;
801
802     memset( &result, 0, sizeof(result) );
803
804     for (;;)
805     {
806         SERVER_START_REQ( get_apc )
807         {
808             req->alertable = alertable;
809             req->prev      = handle;
810             req->result    = result;
811             if (!(ret = wine_server_call( req )))
812             {
813                 handle = reply->handle;
814                 call   = reply->call;
815             }
816         }
817         SERVER_END_REQ;
818
819         if (ret) return user_apc;  /* no more APCs */
820
821         user_apc = invoke_apc( &call, &result );
822     }
823 }
824
825
826 /***********************************************************************
827  *           NTDLL_queue_process_apc
828  */
829 NTSTATUS NTDLL_queue_process_apc( HANDLE process, const apc_call_t *call, apc_result_t *result )
830 {
831     for (;;)
832     {
833         NTSTATUS ret;
834         HANDLE handle = 0;
835         BOOL self = FALSE;
836
837         SERVER_START_REQ( queue_apc )
838         {
839             req->process = process;
840             req->call = *call;
841             if (!(ret = wine_server_call( req )))
842             {
843                 handle = reply->handle;
844                 self = reply->self;
845             }
846         }
847         SERVER_END_REQ;
848         if (ret != STATUS_SUCCESS) return ret;
849
850         if (self)
851         {
852             invoke_apc( call, result );
853         }
854         else
855         {
856             NtWaitForSingleObject( handle, FALSE, NULL );
857
858             SERVER_START_REQ( get_apc_result )
859             {
860                 req->handle = handle;
861                 if (!(ret = wine_server_call( req ))) *result = reply->result;
862             }
863             SERVER_END_REQ;
864
865             if (!ret && result->type == APC_NONE) continue;  /* APC didn't run, try again */
866             if (ret) NtClose( handle );
867         }
868         return ret;
869     }
870 }
871
872
873 /***********************************************************************
874  *              NTDLL_wait_for_multiple_objects
875  *
876  * Implementation of NtWaitForMultipleObjects
877  */
878 NTSTATUS NTDLL_wait_for_multiple_objects( UINT count, const HANDLE *handles, UINT flags,
879                                           const LARGE_INTEGER *timeout, HANDLE signal_object )
880 {
881     NTSTATUS ret;
882     int cookie;
883     timeout_t abs_timeout = timeout ? timeout->QuadPart : TIMEOUT_INFINITE;
884
885     for (;;)
886     {
887         SERVER_START_REQ( select )
888         {
889             req->flags   = flags;
890             req->cookie  = &cookie;
891             req->signal  = signal_object;
892             req->timeout = abs_timeout;
893             wine_server_add_data( req, handles, count * sizeof(HANDLE) );
894             ret = wine_server_call( req );
895             abs_timeout = reply->timeout;
896         }
897         SERVER_END_REQ;
898         if (ret == STATUS_PENDING) ret = wait_reply( &cookie );
899         if (ret != STATUS_USER_APC) break;
900         if (call_apcs( (flags & SELECT_ALERTABLE) != 0 )) break;
901         signal_object = 0;  /* don't signal it multiple times */
902     }
903
904     /* A test on Windows 2000 shows that Windows always yields during
905        a wait, but a wait that is hit by an event gets a priority
906        boost as well.  This seems to model that behavior the closest.  */
907     if (ret == WAIT_TIMEOUT) NtYieldExecution();
908
909     return ret;
910 }
911
912
913 /* wait operations */
914
915 /******************************************************************
916  *              NtWaitForMultipleObjects (NTDLL.@)
917  */
918 NTSTATUS WINAPI NtWaitForMultipleObjects( DWORD count, const HANDLE *handles,
919                                           BOOLEAN wait_all, BOOLEAN alertable,
920                                           const LARGE_INTEGER *timeout )
921 {
922     UINT flags = SELECT_INTERRUPTIBLE;
923
924     if (!count || count > MAXIMUM_WAIT_OBJECTS) return STATUS_INVALID_PARAMETER_1;
925
926     if (wait_all) flags |= SELECT_ALL;
927     if (alertable) flags |= SELECT_ALERTABLE;
928     return NTDLL_wait_for_multiple_objects( count, handles, flags, timeout, 0 );
929 }
930
931
932 /******************************************************************
933  *              NtWaitForSingleObject (NTDLL.@)
934  */
935 NTSTATUS WINAPI NtWaitForSingleObject(HANDLE handle, BOOLEAN alertable, const LARGE_INTEGER *timeout )
936 {
937     return NtWaitForMultipleObjects( 1, &handle, FALSE, alertable, timeout );
938 }
939
940
941 /******************************************************************
942  *              NtSignalAndWaitForSingleObject (NTDLL.@)
943  */
944 NTSTATUS WINAPI NtSignalAndWaitForSingleObject( HANDLE hSignalObject, HANDLE hWaitObject,
945                                                 BOOLEAN alertable, const LARGE_INTEGER *timeout )
946 {
947     UINT flags = SELECT_INTERRUPTIBLE;
948
949     if (!hSignalObject) return STATUS_INVALID_HANDLE;
950     if (alertable) flags |= SELECT_ALERTABLE;
951     return NTDLL_wait_for_multiple_objects( 1, &hWaitObject, flags, timeout, hSignalObject );
952 }
953
954
955 /******************************************************************
956  *              NtYieldExecution (NTDLL.@)
957  */
958 NTSTATUS WINAPI NtYieldExecution(void)
959 {
960 #ifdef HAVE_SCHED_YIELD
961     sched_yield();
962     return STATUS_SUCCESS;
963 #else
964     return STATUS_NO_YIELD_PERFORMED;
965 #endif
966 }
967
968
969 /******************************************************************
970  *              NtDelayExecution (NTDLL.@)
971  */
972 NTSTATUS WINAPI NtDelayExecution( BOOLEAN alertable, const LARGE_INTEGER *timeout )
973 {
974     /* if alertable, we need to query the server */
975     if (alertable)
976         return NTDLL_wait_for_multiple_objects( 0, NULL, SELECT_INTERRUPTIBLE | SELECT_ALERTABLE,
977                                                 timeout, 0 );
978
979     if (!timeout || timeout->QuadPart == TIMEOUT_INFINITE)  /* sleep forever */
980     {
981         for (;;) select( 0, NULL, NULL, NULL, NULL );
982     }
983     else
984     {
985         LARGE_INTEGER now;
986         timeout_t when, diff;
987
988         if ((when = timeout->QuadPart) < 0)
989         {
990             NtQuerySystemTime( &now );
991             when = now.QuadPart - when;
992         }
993
994         /* Note that we yield after establishing the desired timeout */
995         NtYieldExecution();
996         if (!when) return STATUS_SUCCESS;
997
998         for (;;)
999         {
1000             struct timeval tv;
1001             NtQuerySystemTime( &now );
1002             diff = (when - now.QuadPart + 9) / 10;
1003             if (diff <= 0) break;
1004             tv.tv_sec  = diff / 1000000;
1005             tv.tv_usec = diff % 1000000;
1006             if (select( 0, NULL, NULL, NULL, &tv ) != -1) break;
1007         }
1008     }
1009     return STATUS_SUCCESS;
1010 }
1011
1012 /******************************************************************
1013  *              NtCreateIoCompletion (NTDLL.@)
1014  *              ZwCreateIoCompletion (NTDLL.@)
1015  *
1016  * Creates I/O completion object.
1017  *
1018  * PARAMS
1019  *      CompletionPort            [O] created completion object handle will be placed there
1020  *      DesiredAccess             [I] desired access to a handle (combination of IO_COMPLETION_*)
1021  *      ObjectAttributes          [I] completion object attributes
1022  *      NumberOfConcurrentThreads [I] desired number of concurrent active worker threads
1023  *
1024  */
1025 NTSTATUS WINAPI NtCreateIoCompletion( PHANDLE CompletionPort, ACCESS_MASK DesiredAccess,
1026                                       POBJECT_ATTRIBUTES ObjectAttributes, ULONG NumberOfConcurrentThreads )
1027 {
1028     FIXME("(%p, %x, %p, %d)\n", CompletionPort, DesiredAccess,
1029           ObjectAttributes, NumberOfConcurrentThreads);
1030     return STATUS_NOT_IMPLEMENTED;
1031 }
1032
1033 /******************************************************************
1034  *              NtSetIoCompletion (NTDLL.@)
1035  *              ZwSetIoCompletion (NTDLL.@)
1036  *
1037  * Inserts completion message into queue
1038  *
1039  * PARAMS
1040  *      CompletionPort           [I] HANDLE to completion object
1041  *      CompletionKey            [I] completion key
1042  *      CompletionValue          [I] completion value (usually pointer to OVERLAPPED)
1043  *      Status                   [I] operation status
1044  *      NumberOfBytesTransferred [I] number of bytes transferred
1045  */
1046 NTSTATUS WINAPI NtSetIoCompletion( HANDLE CompletionPort, ULONG_PTR CompletionKey,
1047                                    ULONG_PTR CompletionValue, NTSTATUS Status,
1048                                    ULONG NumberOfBytesToTransfer )
1049 {
1050     FIXME("(%p, %lx, %lx, %x, %d)\n", CompletionPort, CompletionKey,
1051           CompletionValue, Status, NumberOfBytesToTransfer);
1052     return STATUS_NOT_IMPLEMENTED;
1053 }
1054
1055 /******************************************************************
1056  *              NtRemoveIoCompletion (NTDLL.@)
1057  *              ZwRemoveIoCompletion (NTDLL.@)
1058  *
1059  * (Wait for and) retrieve first completion message from completion object's queue
1060  *
1061  * PARAMS
1062  *      CompletionPort  [I] HANDLE to I/O completion object
1063  *      CompletionKey   [O] completion key
1064  *      CompletionValue [O] Completion value given in NtSetIoCompletion or in async operation
1065  *      iosb            [O] IO_STATUS_BLOCK of completed asynchronous operation
1066  *      WaitTime        [I] optional wait time in NTDLL format
1067  *
1068  */
1069 NTSTATUS WINAPI NtRemoveIoCompletion( HANDLE CompletionPort, PULONG_PTR CompletionKey,
1070                                       PULONG_PTR CompletionValue, PIO_STATUS_BLOCK iosb,
1071                                       PLARGE_INTEGER WaitTime )
1072 {
1073     FIXME("(%p, %p, %p, %p, %p)\n", CompletionPort, CompletionKey,
1074           CompletionValue, iosb, WaitTime);
1075     return STATUS_NOT_IMPLEMENTED;
1076 }
1077
1078 /******************************************************************
1079  *              NtOpenIoCompletion (NTDLL.@)
1080  *              ZwOpenIoCompletion (NTDLL.@)
1081  *
1082  * Opens I/O completion object
1083  *
1084  * PARAMS
1085  *      CompletionPort     [O] completion object handle will be placed there
1086  *      DesiredAccess      [I] desired access to a handle (combination of IO_COMPLETION_*)
1087  *      ObjectAttributes   [I] completion object name
1088  *
1089  */
1090 NTSTATUS WINAPI NtOpenIoCompletion( PHANDLE CompletionPort, ACCESS_MASK DesiredAccess,
1091                                     POBJECT_ATTRIBUTES ObjectAttributes )
1092 {
1093     FIXME("(%p, 0x%x, %p)\n", CompletionPort, DesiredAccess, ObjectAttributes);
1094     return STATUS_NOT_IMPLEMENTED;
1095 }
1096
1097 /******************************************************************
1098  *              NtQueryIoCompletion (NTDLL.@)
1099  *              ZwQueryIoCompletion (NTDLL.@)
1100  *
1101  * Requests information about given I/O completion object
1102  *
1103  * PARAMS
1104  *      CompletionPort        [I] HANDLE to completion port to request
1105  *      InformationClass      [I] information class
1106  *      CompletionInformation [O] user-provided buffer for data
1107  *      BufferLength          [I] buffer length
1108  *      RequiredLength        [O] required buffer length
1109  *
1110  */
1111 NTSTATUS WINAPI NtQueryIoCompletion( HANDLE CompletionPort, IO_COMPLETION_INFORMATION_CLASS InformationClass,
1112                                      PVOID CompletionInformation, ULONG BufferLength, PULONG RequiredLength )
1113 {
1114     FIXME("(%p, %d, %p, 0x%x, %p)\n", CompletionPort, InformationClass, CompletionInformation,
1115             BufferLength, RequiredLength);
1116     return STATUS_NOT_IMPLEMENTED;
1117 }