wined3d: Fix the nvrc implementation of WINED3DTOP_MULTIPLYADD and WINED3DTOP_LERP.
[wine] / dlls / ntdll / file.c
1 /*
2  * Copyright 1999, 2000 Juergen Schmied
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 #include "config.h"
20 #include "wine/port.h"
21
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <assert.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #ifdef HAVE_SYS_ERRNO_H
31 #include <sys/errno.h>
32 #endif
33 #ifdef HAVE_LINUX_MAJOR_H
34 # include <linux/major.h>
35 #endif
36 #ifdef HAVE_SYS_STATVFS_H
37 # include <sys/statvfs.h>
38 #endif
39 #ifdef HAVE_SYS_PARAM_H
40 # include <sys/param.h>
41 #endif
42 #ifdef HAVE_SYS_TIME_H
43 # include <sys/time.h>
44 #endif
45 #ifdef HAVE_SYS_IOCTL_H
46 #include <sys/ioctl.h>
47 #endif
48 #ifdef HAVE_POLL_H
49 #include <poll.h>
50 #endif
51 #ifdef HAVE_SYS_POLL_H
52 #include <sys/poll.h>
53 #endif
54 #ifdef HAVE_SYS_SOCKET_H
55 #include <sys/socket.h>
56 #endif
57 #ifdef HAVE_UTIME_H
58 # include <utime.h>
59 #endif
60 #ifdef HAVE_SYS_VFS_H
61 # include <sys/vfs.h>
62 #endif
63 #ifdef HAVE_SYS_MOUNT_H
64 # include <sys/mount.h>
65 #endif
66 #ifdef HAVE_SYS_STATFS_H
67 # include <sys/statfs.h>
68 #endif
69
70 #define NONAMELESSUNION
71 #define NONAMELESSSTRUCT
72 #include "ntstatus.h"
73 #define WIN32_NO_STATUS
74 #include "wine/unicode.h"
75 #include "wine/debug.h"
76 #include "wine/server.h"
77 #include "ntdll_misc.h"
78
79 #include "winternl.h"
80 #include "winioctl.h"
81 #include "ddk/ntddser.h"
82
83 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
84
85 mode_t FILE_umask = 0;
86
87 #define SECSPERDAY         86400
88 #define SECS_1601_TO_1970  ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
89
90 /**************************************************************************
91  *                 NtOpenFile                           [NTDLL.@]
92  *                 ZwOpenFile                           [NTDLL.@]
93  *
94  * Open a file.
95  *
96  * PARAMS
97  *  handle    [O] Variable that receives the file handle on return
98  *  access    [I] Access desired by the caller to the file
99  *  attr      [I] Structure describing the file to be opened
100  *  io        [O] Receives details about the result of the operation
101  *  sharing   [I] Type of shared access the caller requires
102  *  options   [I] Options for the file open
103  *
104  * RETURNS
105  *  Success: 0. FileHandle and IoStatusBlock are updated.
106  *  Failure: An NTSTATUS error code describing the error.
107  */
108 NTSTATUS WINAPI NtOpenFile( PHANDLE handle, ACCESS_MASK access,
109                             POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK io,
110                             ULONG sharing, ULONG options )
111 {
112     return NtCreateFile( handle, access, attr, io, NULL, 0,
113                          sharing, FILE_OPEN, options, NULL, 0 );
114 }
115
116 /**************************************************************************
117  *              NtCreateFile                            [NTDLL.@]
118  *              ZwCreateFile                            [NTDLL.@]
119  *
120  * Either create a new file or directory, or open an existing file, device,
121  * directory or volume.
122  *
123  * PARAMS
124  *      handle       [O] Points to a variable which receives the file handle on return
125  *      access       [I] Desired access to the file
126  *      attr         [I] Structure describing the file
127  *      io           [O] Receives information about the operation on return
128  *      alloc_size   [I] Initial size of the file in bytes
129  *      attributes   [I] Attributes to create the file with
130  *      sharing      [I] Type of shared access the caller would like to the file
131  *      disposition  [I] Specifies what to do, depending on whether the file already exists
132  *      options      [I] Options for creating a new file
133  *      ea_buffer    [I] Pointer to an extended attributes buffer
134  *      ea_length    [I] Length of ea_buffer
135  *
136  * RETURNS
137  *  Success: 0. handle and io are updated.
138  *  Failure: An NTSTATUS error code describing the error.
139  */
140 NTSTATUS WINAPI NtCreateFile( PHANDLE handle, ACCESS_MASK access, POBJECT_ATTRIBUTES attr,
141                               PIO_STATUS_BLOCK io, PLARGE_INTEGER alloc_size,
142                               ULONG attributes, ULONG sharing, ULONG disposition,
143                               ULONG options, PVOID ea_buffer, ULONG ea_length )
144 {
145     ANSI_STRING unix_name;
146     int created = FALSE;
147
148     TRACE("handle=%p access=%08x name=%s objattr=%08x root=%p sec=%p io=%p alloc_size=%p\n"
149           "attr=%08x sharing=%08x disp=%d options=%08x ea=%p.0x%08x\n",
150           handle, access, debugstr_us(attr->ObjectName), attr->Attributes,
151           attr->RootDirectory, attr->SecurityDescriptor, io, alloc_size,
152           attributes, sharing, disposition, options, ea_buffer, ea_length );
153
154     if (!attr || !attr->ObjectName) return STATUS_INVALID_PARAMETER;
155
156     if (alloc_size) FIXME( "alloc_size not supported\n" );
157
158     if (attr->RootDirectory)
159     {
160         FIXME( "RootDirectory %p not supported\n", attr->RootDirectory );
161         return STATUS_OBJECT_NAME_NOT_FOUND;
162     }
163
164     io->u.Status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, disposition,
165                                               !(attr->Attributes & OBJ_CASE_INSENSITIVE) );
166
167     if (io->u.Status == STATUS_BAD_DEVICE_TYPE)
168     {
169         SERVER_START_REQ( open_file_object )
170         {
171             req->access     = access;
172             req->attributes = attr->Attributes;
173             req->rootdir    = attr->RootDirectory;
174             req->sharing    = sharing;
175             req->options    = options;
176             wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
177             io->u.Status = wine_server_call( req );
178             *handle = reply->handle;
179         }
180         SERVER_END_REQ;
181         if (io->u.Status == STATUS_SUCCESS) io->Information = FILE_OPENED;
182         return io->u.Status;
183     }
184
185     if (io->u.Status == STATUS_NO_SUCH_FILE &&
186         disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
187     {
188         created = TRUE;
189         io->u.Status = STATUS_SUCCESS;
190     }
191
192     if (io->u.Status == STATUS_SUCCESS)
193     {
194         struct security_descriptor *sd = NULL;
195         struct object_attributes objattr;
196
197         objattr.rootdir = 0;
198         objattr.sd_len = 0;
199         objattr.name_len = 0;
200         if (attr)
201         {
202             io->u.Status = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
203             if (io->u.Status != STATUS_SUCCESS)
204             {
205                 RtlFreeAnsiString( &unix_name );
206                 return io->u.Status;
207             }
208         }
209
210         SERVER_START_REQ( create_file )
211         {
212             req->access     = access;
213             req->attributes = attr->Attributes;
214             req->sharing    = sharing;
215             req->create     = disposition;
216             req->options    = options;
217             req->attrs      = attributes;
218             wine_server_add_data( req, &objattr, sizeof(objattr) );
219             if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
220             wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
221             io->u.Status = wine_server_call( req );
222             *handle = reply->handle;
223         }
224         SERVER_END_REQ;
225         NTDLL_free_struct_sd( sd );
226         RtlFreeAnsiString( &unix_name );
227     }
228     else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), io->u.Status );
229
230     if (io->u.Status == STATUS_SUCCESS)
231     {
232         if (created) io->Information = FILE_CREATED;
233         else switch(disposition)
234         {
235         case FILE_SUPERSEDE:
236             io->Information = FILE_SUPERSEDED;
237             break;
238         case FILE_CREATE:
239             io->Information = FILE_CREATED;
240             break;
241         case FILE_OPEN:
242         case FILE_OPEN_IF:
243             io->Information = FILE_OPENED;
244             break;
245         case FILE_OVERWRITE:
246         case FILE_OVERWRITE_IF:
247             io->Information = FILE_OVERWRITTEN;
248             break;
249         }
250     }
251
252     return io->u.Status;
253 }
254
255 /***********************************************************************
256  *                  Asynchronous file I/O                              *
257  */
258
259 struct async_fileio
260 {
261     HANDLE              handle;
262     PIO_APC_ROUTINE     apc;
263     void               *apc_arg;
264 };
265
266 typedef struct
267 {
268     struct async_fileio io;
269     char*               buffer;
270     unsigned int        already;
271     unsigned int        count;
272     BOOL                avail_mode;
273 } async_fileio_read;
274
275 typedef struct
276 {
277     struct async_fileio io;
278     const char         *buffer;
279     unsigned int        already;
280     unsigned int        count;
281 } async_fileio_write;
282
283
284 /* callback for file I/O user APC */
285 static void WINAPI fileio_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
286 {
287     struct async_fileio *async = arg;
288     if (async->apc) async->apc( async->apc_arg, io, reserved );
289     RtlFreeHeap( GetProcessHeap(), 0, async );
290 }
291
292 /***********************************************************************
293  *           FILE_GetNtStatus(void)
294  *
295  * Retrieve the Nt Status code from errno.
296  * Try to be consistent with FILE_SetDosError().
297  */
298 NTSTATUS FILE_GetNtStatus(void)
299 {
300     int err = errno;
301
302     TRACE( "errno = %d\n", errno );
303     switch (err)
304     {
305     case EAGAIN:    return STATUS_SHARING_VIOLATION;
306     case EBADF:     return STATUS_INVALID_HANDLE;
307     case EBUSY:     return STATUS_DEVICE_BUSY;
308     case ENOSPC:    return STATUS_DISK_FULL;
309     case EPERM:
310     case EROFS:
311     case EACCES:    return STATUS_ACCESS_DENIED;
312     case ENOTDIR:   return STATUS_OBJECT_PATH_NOT_FOUND;
313     case ENOENT:    return STATUS_OBJECT_NAME_NOT_FOUND;
314     case EISDIR:    return STATUS_FILE_IS_A_DIRECTORY;
315     case EMFILE:
316     case ENFILE:    return STATUS_TOO_MANY_OPENED_FILES;
317     case EINVAL:    return STATUS_INVALID_PARAMETER;
318     case ENOTEMPTY: return STATUS_DIRECTORY_NOT_EMPTY;
319     case EPIPE:     return STATUS_PIPE_DISCONNECTED;
320     case EIO:       return STATUS_DEVICE_NOT_READY;
321 #ifdef ENOMEDIUM
322     case ENOMEDIUM: return STATUS_NO_MEDIA_IN_DEVICE;
323 #endif
324     case ENXIO:     return STATUS_NO_SUCH_DEVICE;
325     case ENOTTY:
326     case EOPNOTSUPP:return STATUS_NOT_SUPPORTED;
327     case ECONNRESET:return STATUS_PIPE_DISCONNECTED;
328     case EFAULT:    return STATUS_ACCESS_VIOLATION;
329     case ESPIPE:    return STATUS_ILLEGAL_FUNCTION;
330     case ENOEXEC:   /* ?? */
331     case EEXIST:    /* ?? */
332     default:
333         FIXME( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
334         return STATUS_UNSUCCESSFUL;
335     }
336 }
337
338 /***********************************************************************
339  *             FILE_AsyncReadService      (INTERNAL)
340  */
341 static NTSTATUS FILE_AsyncReadService(void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, ULONG_PTR *total)
342 {
343     async_fileio_read *fileio = user;
344     int fd, needs_close, result;
345
346     switch (status)
347     {
348     case STATUS_ALERTED: /* got some new data */
349         /* check to see if the data is ready (non-blocking) */
350         if ((status = server_get_unix_fd( fileio->io.handle, FILE_READ_DATA, &fd,
351                                           &needs_close, NULL, NULL )))
352             break;
353
354         result = read(fd, &fileio->buffer[fileio->already], fileio->count - fileio->already);
355         if (needs_close) close( fd );
356
357         if (result < 0)
358         {
359             if (errno == EAGAIN || errno == EINTR)
360                 status = STATUS_PENDING;
361             else /* check to see if the transfer is complete */
362                 status = FILE_GetNtStatus();
363         }
364         else if (result == 0)
365         {
366             status = fileio->already ? STATUS_SUCCESS : STATUS_PIPE_BROKEN;
367         }
368         else
369         {
370             fileio->already += result;
371             if (fileio->already >= fileio->count || fileio->avail_mode)
372                 status = STATUS_SUCCESS;
373             else
374             {
375                 /* if we only have to read the available data, and none is available,
376                  * simply cancel the request. If data was available, it has been read
377                  * while in by previous call (NtDelayExecution)
378                  */
379                 status = (fileio->avail_mode) ? STATUS_SUCCESS : STATUS_PENDING;
380             }
381         }
382         break;
383
384     case STATUS_TIMEOUT:
385     case STATUS_IO_TIMEOUT:
386         if (fileio->already) status = STATUS_SUCCESS;
387         break;
388     }
389     if (status != STATUS_PENDING)
390     {
391         iosb->u.Status = status;
392         iosb->Information = *total = fileio->already;
393     }
394     return status;
395 }
396
397 struct io_timeouts
398 {
399     int interval;   /* max interval between two bytes */
400     int total;      /* total timeout for the whole operation */
401     int end_time;   /* absolute time of end of operation */
402 };
403
404 /* retrieve the I/O timeouts to use for a given handle */
405 static NTSTATUS get_io_timeouts( HANDLE handle, enum server_fd_type type, ULONG count, BOOL is_read,
406                                  struct io_timeouts *timeouts )
407 {
408     NTSTATUS status = STATUS_SUCCESS;
409
410     timeouts->interval = timeouts->total = -1;
411
412     switch(type)
413     {
414     case FD_TYPE_SERIAL:
415         {
416             /* GetCommTimeouts */
417             SERIAL_TIMEOUTS st;
418             IO_STATUS_BLOCK io;
419
420             status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
421                                             IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
422             if (status) break;
423
424             if (is_read)
425             {
426                 if (st.ReadIntervalTimeout)
427                     timeouts->interval = st.ReadIntervalTimeout;
428
429                 if (st.ReadTotalTimeoutMultiplier || st.ReadTotalTimeoutConstant)
430                 {
431                     timeouts->total = st.ReadTotalTimeoutConstant;
432                     if (st.ReadTotalTimeoutMultiplier != MAXDWORD)
433                         timeouts->total += count * st.ReadTotalTimeoutMultiplier;
434                 }
435                 else if (st.ReadIntervalTimeout == MAXDWORD)
436                     timeouts->interval = timeouts->total = 0;
437             }
438             else  /* write */
439             {
440                 if (st.WriteTotalTimeoutMultiplier || st.WriteTotalTimeoutConstant)
441                 {
442                     timeouts->total = st.WriteTotalTimeoutConstant;
443                     if (st.WriteTotalTimeoutMultiplier != MAXDWORD)
444                         timeouts->total += count * st.WriteTotalTimeoutMultiplier;
445                 }
446             }
447         }
448         break;
449     case FD_TYPE_MAILSLOT:
450         if (is_read)
451         {
452             timeouts->interval = 0;  /* return as soon as we got something */
453             SERVER_START_REQ( set_mailslot_info )
454             {
455                 req->handle = handle;
456                 req->flags = 0;
457                 if (!(status = wine_server_call( req )) &&
458                     reply->read_timeout != TIMEOUT_INFINITE)
459                     timeouts->total = reply->read_timeout / -10000;
460             }
461             SERVER_END_REQ;
462         }
463         break;
464     case FD_TYPE_SOCKET:
465     case FD_TYPE_PIPE:
466     case FD_TYPE_CHAR:
467         if (is_read) timeouts->interval = 0;  /* return as soon as we got something */
468         break;
469     default:
470         break;
471     }
472     if (timeouts->total != -1) timeouts->end_time = NtGetTickCount() + timeouts->total;
473     return STATUS_SUCCESS;
474 }
475
476
477 /* retrieve the timeout for the next wait, in milliseconds */
478 static inline int get_next_io_timeout( const struct io_timeouts *timeouts, ULONG already )
479 {
480     int ret = -1;
481
482     if (timeouts->total != -1)
483     {
484         ret = timeouts->end_time - NtGetTickCount();
485         if (ret < 0) ret = 0;
486     }
487     if (already && timeouts->interval != -1)
488     {
489         if (ret == -1 || ret > timeouts->interval) ret = timeouts->interval;
490     }
491     return ret;
492 }
493
494
495 /* retrieve the avail_mode flag for async reads */
496 static NTSTATUS get_io_avail_mode( HANDLE handle, enum server_fd_type type, BOOL *avail_mode )
497 {
498     NTSTATUS status = STATUS_SUCCESS;
499
500     switch(type)
501     {
502     case FD_TYPE_SERIAL:
503         {
504             /* GetCommTimeouts */
505             SERIAL_TIMEOUTS st;
506             IO_STATUS_BLOCK io;
507
508             status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
509                                             IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
510             if (status) break;
511             *avail_mode = (!st.ReadTotalTimeoutMultiplier &&
512                            !st.ReadTotalTimeoutConstant &&
513                            st.ReadIntervalTimeout == MAXDWORD);
514         }
515         break;
516     case FD_TYPE_MAILSLOT:
517     case FD_TYPE_SOCKET:
518     case FD_TYPE_PIPE:
519     case FD_TYPE_CHAR:
520         *avail_mode = TRUE;
521         break;
522     default:
523         *avail_mode = FALSE;
524         break;
525     }
526     return status;
527 }
528
529
530 /******************************************************************************
531  *  NtReadFile                                  [NTDLL.@]
532  *  ZwReadFile                                  [NTDLL.@]
533  *
534  * Read from an open file handle.
535  *
536  * PARAMS
537  *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
538  *  Event         [I] Event to signal upon completion (or NULL)
539  *  ApcRoutine    [I] Callback to call upon completion (or NULL)
540  *  ApcContext    [I] Context for ApcRoutine (or NULL)
541  *  IoStatusBlock [O] Receives information about the operation on return
542  *  Buffer        [O] Destination for the data read
543  *  Length        [I] Size of Buffer
544  *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
545  *  Key           [O] Function unknown (may be NULL)
546  *
547  * RETURNS
548  *  Success: 0. IoStatusBlock is updated, and the Information member contains
549  *           The number of bytes read.
550  *  Failure: An NTSTATUS error code describing the error.
551  */
552 NTSTATUS WINAPI NtReadFile(HANDLE hFile, HANDLE hEvent,
553                            PIO_APC_ROUTINE apc, void* apc_user,
554                            PIO_STATUS_BLOCK io_status, void* buffer, ULONG length,
555                            PLARGE_INTEGER offset, PULONG key)
556 {
557     int result, unix_handle, needs_close, timeout_init_done = 0;
558     unsigned int options;
559     struct io_timeouts timeouts;
560     NTSTATUS status;
561     ULONG total = 0;
562     enum server_fd_type type;
563     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
564
565     TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
566           hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
567
568     if (!io_status) return STATUS_ACCESS_VIOLATION;
569
570     status = server_get_unix_fd( hFile, FILE_READ_DATA, &unix_handle,
571                                  &needs_close, &type, &options );
572     if (status) return status;
573
574     if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
575     {
576         /* async I/O doesn't make sense on regular files */
577         while ((result = pread( unix_handle, buffer, length, offset->QuadPart )) == -1)
578         {
579             if (errno != EINTR)
580             {
581                 status = FILE_GetNtStatus();
582                 goto done;
583             }
584         }
585         if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
586             /* update file pointer position */
587             lseek( unix_handle, offset->QuadPart + result, SEEK_SET );
588
589         total = result;
590         status = total ? STATUS_SUCCESS : STATUS_END_OF_FILE;
591         goto done;
592     }
593
594     for (;;)
595     {
596         if ((result = read( unix_handle, (char *)buffer + total, length - total )) >= 0)
597         {
598             total += result;
599             if (!result || total == length)
600             {
601                 if (total)
602                 {
603                     status = STATUS_SUCCESS;
604                     goto done;
605                 }
606                 switch (type)
607                 {
608                 case FD_TYPE_FILE:
609                 case FD_TYPE_CHAR:
610                     status = STATUS_END_OF_FILE;
611                     goto done;
612                 case FD_TYPE_SERIAL:
613                     break;
614                 default:
615                     status = STATUS_PIPE_BROKEN;
616                     goto done;
617                 }
618             }
619         }
620         else
621         {
622             if (errno == EINTR) continue;
623             if (errno != EAGAIN)
624             {
625                 status = FILE_GetNtStatus();
626                 goto done;
627             }
628         }
629
630         if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
631         {
632             async_fileio_read *fileio;
633             BOOL avail_mode;
634
635             if ((status = get_io_avail_mode( hFile, type, &avail_mode )))
636                 goto err;
637             if (total && avail_mode)
638             {
639                 status = STATUS_SUCCESS;
640                 goto done;
641             }
642
643             if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
644             {
645                 status = STATUS_NO_MEMORY;
646                 goto err;
647             }
648             fileio->io.handle  = hFile;
649             fileio->io.apc     = apc;
650             fileio->io.apc_arg = apc_user;
651             fileio->already = total;
652             fileio->count = length;
653             fileio->buffer = buffer;
654             fileio->avail_mode = avail_mode;
655
656             SERVER_START_REQ( register_async )
657             {
658                 req->handle = hFile;
659                 req->type   = ASYNC_TYPE_READ;
660                 req->count  = length;
661                 req->async.callback = FILE_AsyncReadService;
662                 req->async.iosb     = io_status;
663                 req->async.arg      = fileio;
664                 req->async.apc      = fileio_apc;
665                 req->async.event    = hEvent;
666                 req->async.cvalue   = cvalue;
667                 status = wine_server_call( req );
668             }
669             SERVER_END_REQ;
670
671             if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
672             goto err;
673         }
674         else  /* synchronous read, wait for the fd to become ready */
675         {
676             struct pollfd pfd;
677             int ret, timeout;
678
679             if (!timeout_init_done)
680             {
681                 timeout_init_done = 1;
682                 if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts )))
683                     goto err;
684                 if (hEvent) NtResetEvent( hEvent, NULL );
685             }
686             timeout = get_next_io_timeout( &timeouts, total );
687
688             pfd.fd = unix_handle;
689             pfd.events = POLLIN;
690
691             if (!timeout || !(ret = poll( &pfd, 1, timeout )))
692             {
693                 if (total)  /* return with what we got so far */
694                     status = STATUS_SUCCESS;
695                 else
696                     status = (type == FD_TYPE_MAILSLOT) ? STATUS_IO_TIMEOUT : STATUS_TIMEOUT;
697                 goto done;
698             }
699             if (ret == -1 && errno != EINTR)
700             {
701                 status = FILE_GetNtStatus();
702                 goto done;
703             }
704             /* will now restart the read */
705         }
706     }
707
708 done:
709     if (cvalue) NTDLL_AddCompletion( hFile, cvalue, status, total );
710
711 err:
712     if (needs_close) close( unix_handle );
713     if (status == STATUS_SUCCESS)
714     {
715         io_status->u.Status = status;
716         io_status->Information = total;
717         TRACE("= SUCCESS (%u)\n", total);
718         if (hEvent) NtSetEvent( hEvent, NULL );
719         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
720                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
721     }
722     else
723     {
724         TRACE("= 0x%08x\n", status);
725         if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
726     }
727     return status;
728 }
729
730
731 /******************************************************************************
732  *  NtReadFileScatter   [NTDLL.@]
733  *  ZwReadFileScatter   [NTDLL.@]
734  */
735 NTSTATUS WINAPI NtReadFileScatter( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
736                                    PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
737                                    ULONG length, PLARGE_INTEGER offset, PULONG key )
738 {
739     size_t page_size = getpagesize();
740     int result, unix_handle, needs_close;
741     unsigned int options;
742     NTSTATUS status;
743     ULONG pos = 0, total = 0;
744     enum server_fd_type type;
745     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
746
747     TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
748            file, event, apc, apc_user, io_status, segments, length, offset, key);
749
750     if (length % page_size) return STATUS_INVALID_PARAMETER;
751     if (!io_status) return STATUS_ACCESS_VIOLATION;
752
753     status = server_get_unix_fd( file, FILE_READ_DATA, &unix_handle,
754                                  &needs_close, &type, &options );
755     if (status) return status;
756
757     if ((type != FD_TYPE_FILE) ||
758         (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
759         !(options & FILE_NO_INTERMEDIATE_BUFFERING))
760     {
761         status = STATUS_INVALID_PARAMETER;
762         goto error;
763     }
764
765     while (length)
766     {
767         if (offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */)
768             result = pread( unix_handle, (char *)segments->Buffer + pos,
769                             page_size - pos, offset->QuadPart + total );
770         else
771             result = read( unix_handle, (char *)segments->Buffer + pos, page_size - pos );
772
773         if (result == -1)
774         {
775             if (errno == EINTR) continue;
776             status = FILE_GetNtStatus();
777             break;
778         }
779         if (!result)
780         {
781             status = STATUS_END_OF_FILE;
782             break;
783         }
784         total += result;
785         length -= result;
786         if ((pos += result) == page_size)
787         {
788             pos = 0;
789             segments++;
790         }
791     }
792
793     if (cvalue) NTDLL_AddCompletion( file, cvalue, status, total );
794
795  error:
796     if (needs_close) close( unix_handle );
797     if (status == STATUS_SUCCESS)
798     {
799         io_status->u.Status = status;
800         io_status->Information = total;
801         TRACE("= SUCCESS (%u)\n", total);
802         if (event) NtSetEvent( event, NULL );
803         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
804                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
805     }
806     else
807     {
808         TRACE("= 0x%08x\n", status);
809         if (status != STATUS_PENDING && event) NtResetEvent( event, NULL );
810     }
811     return status;
812 }
813
814
815 /***********************************************************************
816  *             FILE_AsyncWriteService      (INTERNAL)
817  */
818 static NTSTATUS FILE_AsyncWriteService(void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status, ULONG_PTR *total)
819 {
820     async_fileio_write *fileio = user;
821     int result, fd, needs_close;
822     enum server_fd_type type;
823
824     switch (status)
825     {
826     case STATUS_ALERTED:
827         /* write some data (non-blocking) */
828         if ((status = server_get_unix_fd( fileio->io.handle, FILE_WRITE_DATA, &fd,
829                                           &needs_close, &type, NULL )))
830             break;
831
832         if (!fileio->count && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
833             result = send( fd, fileio->buffer, 0, 0 );
834         else
835             result = write( fd, &fileio->buffer[fileio->already], fileio->count - fileio->already );
836
837         if (needs_close) close( fd );
838
839         if (result < 0)
840         {
841             if (errno == EAGAIN || errno == EINTR) status = STATUS_PENDING;
842             else status = FILE_GetNtStatus();
843         }
844         else
845         {
846             fileio->already += result;
847             status = (fileio->already < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
848         }
849         break;
850
851     case STATUS_TIMEOUT:
852     case STATUS_IO_TIMEOUT:
853         if (fileio->already) status = STATUS_SUCCESS;
854         break;
855     }
856     if (status != STATUS_PENDING)
857     {
858         iosb->u.Status = status;
859         iosb->Information = *total = fileio->already;
860     }
861     return status;
862 }
863
864 /******************************************************************************
865  *  NtWriteFile                                 [NTDLL.@]
866  *  ZwWriteFile                                 [NTDLL.@]
867  *
868  * Write to an open file handle.
869  *
870  * PARAMS
871  *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
872  *  Event         [I] Event to signal upon completion (or NULL)
873  *  ApcRoutine    [I] Callback to call upon completion (or NULL)
874  *  ApcContext    [I] Context for ApcRoutine (or NULL)
875  *  IoStatusBlock [O] Receives information about the operation on return
876  *  Buffer        [I] Source for the data to write
877  *  Length        [I] Size of Buffer
878  *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
879  *  Key           [O] Function unknown (may be NULL)
880  *
881  * RETURNS
882  *  Success: 0. IoStatusBlock is updated, and the Information member contains
883  *           The number of bytes written.
884  *  Failure: An NTSTATUS error code describing the error.
885  */
886 NTSTATUS WINAPI NtWriteFile(HANDLE hFile, HANDLE hEvent,
887                             PIO_APC_ROUTINE apc, void* apc_user,
888                             PIO_STATUS_BLOCK io_status, 
889                             const void* buffer, ULONG length,
890                             PLARGE_INTEGER offset, PULONG key)
891 {
892     int result, unix_handle, needs_close, timeout_init_done = 0;
893     unsigned int options;
894     struct io_timeouts timeouts;
895     NTSTATUS status;
896     ULONG total = 0;
897     enum server_fd_type type;
898     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
899
900     TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p)!\n",
901           hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
902
903     if (!io_status) return STATUS_ACCESS_VIOLATION;
904
905     status = server_get_unix_fd( hFile, FILE_WRITE_DATA, &unix_handle,
906                                  &needs_close, &type, &options );
907     if (status) return status;
908
909     if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
910     {
911         /* async I/O doesn't make sense on regular files */
912         while ((result = pwrite( unix_handle, buffer, length, offset->QuadPart )) == -1)
913         {
914             if (errno != EINTR)
915             {
916                 if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
917                 else status = FILE_GetNtStatus();
918                 goto done;
919             }
920         }
921
922         if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
923             /* update file pointer position */
924             lseek( unix_handle, offset->QuadPart + result, SEEK_SET );
925
926         total = result;
927         status = STATUS_SUCCESS;
928         goto done;
929     }
930
931     for (;;)
932     {
933         /* zero-length writes on sockets may not work with plain write(2) */
934         if (!length && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
935             result = send( unix_handle, buffer, 0, 0 );
936         else
937             result = write( unix_handle, (const char *)buffer + total, length - total );
938
939         if (result >= 0)
940         {
941             total += result;
942             if (total == length)
943             {
944                 status = STATUS_SUCCESS;
945                 goto done;
946             }
947         }
948         else
949         {
950             if (errno == EINTR) continue;
951             if (errno != EAGAIN)
952             {
953                 if (errno == EFAULT)
954                 {
955                     status = STATUS_INVALID_USER_BUFFER;
956                     goto err;
957                 }
958                 status = FILE_GetNtStatus();
959                 goto done;
960             }
961         }
962
963         if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
964         {
965             async_fileio_write *fileio;
966
967             if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
968             {
969                 status = STATUS_NO_MEMORY;
970                 goto err;
971             }
972             fileio->io.handle  = hFile;
973             fileio->io.apc     = apc;
974             fileio->io.apc_arg = apc_user;
975             fileio->already = total;
976             fileio->count = length;
977             fileio->buffer = buffer;
978
979             SERVER_START_REQ( register_async )
980             {
981                 req->handle = hFile;
982                 req->type   = ASYNC_TYPE_WRITE;
983                 req->count  = length;
984                 req->async.callback = FILE_AsyncWriteService;
985                 req->async.iosb     = io_status;
986                 req->async.arg      = fileio;
987                 req->async.apc      = fileio_apc;
988                 req->async.event    = hEvent;
989                 req->async.cvalue   = cvalue;
990                 status = wine_server_call( req );
991             }
992             SERVER_END_REQ;
993
994             if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
995             goto err;
996         }
997         else  /* synchronous write, wait for the fd to become ready */
998         {
999             struct pollfd pfd;
1000             int ret, timeout;
1001
1002             if (!timeout_init_done)
1003             {
1004                 timeout_init_done = 1;
1005                 if ((status = get_io_timeouts( hFile, type, length, FALSE, &timeouts )))
1006                     goto err;
1007                 if (hEvent) NtResetEvent( hEvent, NULL );
1008             }
1009             timeout = get_next_io_timeout( &timeouts, total );
1010
1011             pfd.fd = unix_handle;
1012             pfd.events = POLLOUT;
1013
1014             if (!timeout || !(ret = poll( &pfd, 1, timeout )))
1015             {
1016                 /* return with what we got so far */
1017                 status = total ? STATUS_SUCCESS : STATUS_TIMEOUT;
1018                 goto done;
1019             }
1020             if (ret == -1 && errno != EINTR)
1021             {
1022                 status = FILE_GetNtStatus();
1023                 goto done;
1024             }
1025             /* will now restart the write */
1026         }
1027     }
1028
1029 done:
1030     if (cvalue) NTDLL_AddCompletion( hFile, cvalue, status, total );
1031
1032 err:
1033     if (needs_close) close( unix_handle );
1034     if (status == STATUS_SUCCESS)
1035     {
1036         io_status->u.Status = status;
1037         io_status->Information = total;
1038         TRACE("= SUCCESS (%u)\n", total);
1039         if (hEvent) NtSetEvent( hEvent, NULL );
1040         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1041                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1042     }
1043     else
1044     {
1045         TRACE("= 0x%08x\n", status);
1046         if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
1047     }
1048     return status;
1049 }
1050
1051
1052 /******************************************************************************
1053  *  NtWriteFileGather   [NTDLL.@]
1054  *  ZwWriteFileGather   [NTDLL.@]
1055  */
1056 NTSTATUS WINAPI NtWriteFileGather( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
1057                                    PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
1058                                    ULONG length, PLARGE_INTEGER offset, PULONG key )
1059 {
1060     size_t page_size = getpagesize();
1061     int result, unix_handle, needs_close;
1062     unsigned int options;
1063     NTSTATUS status;
1064     ULONG pos = 0, total = 0;
1065     enum server_fd_type type;
1066     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1067
1068     TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
1069            file, event, apc, apc_user, io_status, segments, length, offset, key);
1070
1071     if (length % page_size) return STATUS_INVALID_PARAMETER;
1072     if (!io_status) return STATUS_ACCESS_VIOLATION;
1073
1074     status = server_get_unix_fd( file, FILE_WRITE_DATA, &unix_handle,
1075                                  &needs_close, &type, &options );
1076     if (status) return status;
1077
1078     if ((type != FD_TYPE_FILE) ||
1079         (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
1080         !(options & FILE_NO_INTERMEDIATE_BUFFERING))
1081     {
1082         status = STATUS_INVALID_PARAMETER;
1083         goto error;
1084     }
1085
1086     while (length)
1087     {
1088         if (offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */)
1089             result = pwrite( unix_handle, (char *)segments->Buffer + pos,
1090                              page_size - pos, offset->QuadPart + total );
1091         else
1092             result = write( unix_handle, (char *)segments->Buffer + pos, page_size - pos );
1093
1094         if (result == -1)
1095         {
1096             if (errno == EINTR) continue;
1097             if (errno == EFAULT)
1098             {
1099                 status = STATUS_INVALID_USER_BUFFER;
1100                 goto error;
1101             }
1102             status = FILE_GetNtStatus();
1103             break;
1104         }
1105         if (!result)
1106         {
1107             status = STATUS_DISK_FULL;
1108             break;
1109         }
1110         total += result;
1111         length -= result;
1112         if ((pos += result) == page_size)
1113         {
1114             pos = 0;
1115             segments++;
1116         }
1117     }
1118
1119     if (cvalue) NTDLL_AddCompletion( file, cvalue, status, total );
1120
1121  error:
1122     if (needs_close) close( unix_handle );
1123     if (status == STATUS_SUCCESS)
1124     {
1125         io_status->u.Status = status;
1126         io_status->Information = total;
1127         TRACE("= SUCCESS (%u)\n", total);
1128         if (event) NtSetEvent( event, NULL );
1129         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1130                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1131     }
1132     else
1133     {
1134         TRACE("= 0x%08x\n", status);
1135         if (status != STATUS_PENDING && event) NtResetEvent( event, NULL );
1136     }
1137     return status;
1138 }
1139
1140
1141 struct async_ioctl
1142 {
1143     HANDLE          handle;   /* handle to the device */
1144     void           *buffer;   /* buffer for output */
1145     ULONG           size;     /* size of buffer */
1146     PIO_APC_ROUTINE apc;      /* user apc params */
1147     void           *apc_arg;
1148 };
1149
1150 /* callback for ioctl async I/O completion */
1151 static NTSTATUS ioctl_completion( void *arg, IO_STATUS_BLOCK *io, NTSTATUS status )
1152 {
1153     struct async_ioctl *async = arg;
1154
1155     if (status == STATUS_ALERTED)
1156     {
1157         SERVER_START_REQ( get_ioctl_result )
1158         {
1159             req->handle   = async->handle;
1160             req->user_arg = async;
1161             wine_server_set_reply( req, async->buffer, async->size );
1162             if (!(status = wine_server_call( req )))
1163                 io->Information = wine_server_reply_size( reply );
1164         }
1165         SERVER_END_REQ;
1166     }
1167     if (status != STATUS_PENDING) io->u.Status = status;
1168     return status;
1169 }
1170
1171 /* callback for ioctl user APC */
1172 static void WINAPI ioctl_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
1173 {
1174     struct async_ioctl *async = arg;
1175     if (async->apc) async->apc( async->apc_arg, io, reserved );
1176     RtlFreeHeap( GetProcessHeap(), 0, async );
1177 }
1178
1179 /* do a ioctl call through the server */
1180 static NTSTATUS server_ioctl_file( HANDLE handle, HANDLE event,
1181                                    PIO_APC_ROUTINE apc, PVOID apc_context,
1182                                    IO_STATUS_BLOCK *io, ULONG code,
1183                                    const void *in_buffer, ULONG in_size,
1184                                    PVOID out_buffer, ULONG out_size )
1185 {
1186     struct async_ioctl *async;
1187     NTSTATUS status;
1188     HANDLE wait_handle;
1189     ULONG options;
1190     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1191
1192     if (!(async = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*async) )))
1193         return STATUS_NO_MEMORY;
1194     async->handle  = handle;
1195     async->buffer  = out_buffer;
1196     async->size    = out_size;
1197     async->apc     = apc;
1198     async->apc_arg = apc_context;
1199
1200     SERVER_START_REQ( ioctl )
1201     {
1202         req->handle         = handle;
1203         req->code           = code;
1204         req->async.callback = ioctl_completion;
1205         req->async.iosb     = io;
1206         req->async.arg      = async;
1207         req->async.apc      = (apc || event) ? ioctl_apc : NULL;
1208         req->async.event    = event;
1209         req->async.cvalue   = cvalue;
1210         wine_server_add_data( req, in_buffer, in_size );
1211         wine_server_set_reply( req, out_buffer, out_size );
1212         if (!(status = wine_server_call( req )))
1213             io->Information = wine_server_reply_size( reply );
1214         wait_handle = reply->wait;
1215         options     = reply->options;
1216     }
1217     SERVER_END_REQ;
1218
1219     if (status == STATUS_NOT_SUPPORTED)
1220         FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
1221               code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1222
1223     if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
1224
1225     if (wait_handle)
1226     {
1227         NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
1228         status = io->u.Status;
1229         NtClose( wait_handle );
1230         RtlFreeHeap( GetProcessHeap(), 0, async );
1231     }
1232
1233     return status;
1234 }
1235
1236
1237 /**************************************************************************
1238  *              NtDeviceIoControlFile                   [NTDLL.@]
1239  *              ZwDeviceIoControlFile                   [NTDLL.@]
1240  *
1241  * Perform an I/O control operation on an open file handle.
1242  *
1243  * PARAMS
1244  *  handle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1245  *  event          [I] Event to signal upon completion (or NULL)
1246  *  apc            [I] Callback to call upon completion (or NULL)
1247  *  apc_context    [I] Context for ApcRoutine (or NULL)
1248  *  io             [O] Receives information about the operation on return
1249  *  code           [I] Control code for the operation to perform
1250  *  in_buffer      [I] Source for any input data required (or NULL)
1251  *  in_size        [I] Size of InputBuffer
1252  *  out_buffer     [O] Source for any output data returned (or NULL)
1253  *  out_size       [I] Size of OutputBuffer
1254  *
1255  * RETURNS
1256  *  Success: 0. IoStatusBlock is updated.
1257  *  Failure: An NTSTATUS error code describing the error.
1258  */
1259 NTSTATUS WINAPI NtDeviceIoControlFile(HANDLE handle, HANDLE event,
1260                                       PIO_APC_ROUTINE apc, PVOID apc_context,
1261                                       PIO_STATUS_BLOCK io, ULONG code,
1262                                       PVOID in_buffer, ULONG in_size,
1263                                       PVOID out_buffer, ULONG out_size)
1264 {
1265     ULONG device = (code >> 16);
1266     NTSTATUS status = STATUS_NOT_SUPPORTED;
1267
1268     TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1269           handle, event, apc, apc_context, io, code,
1270           in_buffer, in_size, out_buffer, out_size);
1271
1272     switch(device)
1273     {
1274     case FILE_DEVICE_DISK:
1275     case FILE_DEVICE_CD_ROM:
1276     case FILE_DEVICE_DVD:
1277     case FILE_DEVICE_CONTROLLER:
1278     case FILE_DEVICE_MASS_STORAGE:
1279         status = CDROM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1280                                        in_buffer, in_size, out_buffer, out_size);
1281         break;
1282     case FILE_DEVICE_SERIAL_PORT:
1283         status = COMM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1284                                       in_buffer, in_size, out_buffer, out_size);
1285         break;
1286     case FILE_DEVICE_TAPE:
1287         status = TAPE_DeviceIoControl(handle, event, apc, apc_context, io, code,
1288                                       in_buffer, in_size, out_buffer, out_size);
1289         break;
1290     }
1291
1292     if (status == STATUS_NOT_SUPPORTED || status == STATUS_BAD_DEVICE_TYPE)
1293         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1294                                     in_buffer, in_size, out_buffer, out_size );
1295
1296     if (status != STATUS_PENDING) io->u.Status = status;
1297     return status;
1298 }
1299
1300
1301 /**************************************************************************
1302  *              NtFsControlFile                 [NTDLL.@]
1303  *              ZwFsControlFile                 [NTDLL.@]
1304  *
1305  * Perform a file system control operation on an open file handle.
1306  *
1307  * PARAMS
1308  *  handle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1309  *  event          [I] Event to signal upon completion (or NULL)
1310  *  apc            [I] Callback to call upon completion (or NULL)
1311  *  apc_context    [I] Context for ApcRoutine (or NULL)
1312  *  io             [O] Receives information about the operation on return
1313  *  code           [I] Control code for the operation to perform
1314  *  in_buffer      [I] Source for any input data required (or NULL)
1315  *  in_size        [I] Size of InputBuffer
1316  *  out_buffer     [O] Source for any output data returned (or NULL)
1317  *  out_size       [I] Size of OutputBuffer
1318  *
1319  * RETURNS
1320  *  Success: 0. IoStatusBlock is updated.
1321  *  Failure: An NTSTATUS error code describing the error.
1322  */
1323 NTSTATUS WINAPI NtFsControlFile(HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc,
1324                                 PVOID apc_context, PIO_STATUS_BLOCK io, ULONG code,
1325                                 PVOID in_buffer, ULONG in_size, PVOID out_buffer, ULONG out_size)
1326 {
1327     NTSTATUS status;
1328
1329     TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1330           handle, event, apc, apc_context, io, code,
1331           in_buffer, in_size, out_buffer, out_size);
1332
1333     if (!io) return STATUS_INVALID_PARAMETER;
1334
1335     switch(code)
1336     {
1337     case FSCTL_DISMOUNT_VOLUME:
1338         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1339                                     in_buffer, in_size, out_buffer, out_size );
1340         if (!status) status = DIR_unmount_device( handle );
1341         break;
1342
1343     case FSCTL_PIPE_PEEK:
1344         {
1345             FILE_PIPE_PEEK_BUFFER *buffer = out_buffer;
1346             int avail = 0, fd, needs_close;
1347
1348             if (out_size < FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data ))
1349             {
1350                 status = STATUS_INFO_LENGTH_MISMATCH;
1351                 break;
1352             }
1353
1354             if ((status = server_get_unix_fd( handle, FILE_READ_DATA, &fd, &needs_close, NULL, NULL )))
1355                 break;
1356
1357 #ifdef FIONREAD
1358             if (ioctl( fd, FIONREAD, &avail ) != 0)
1359             {
1360                 TRACE("FIONREAD failed reason: %s\n",strerror(errno));
1361                 if (needs_close) close( fd );
1362                 status = FILE_GetNtStatus();
1363                 break;
1364             }
1365 #endif
1366             if (!avail)  /* check for closed pipe */
1367             {
1368                 struct pollfd pollfd;
1369                 int ret;
1370
1371                 pollfd.fd = fd;
1372                 pollfd.events = POLLIN;
1373                 pollfd.revents = 0;
1374                 ret = poll( &pollfd, 1, 0 );
1375                 if (ret == -1 || (ret == 1 && (pollfd.revents & (POLLHUP|POLLERR))))
1376                 {
1377                     if (needs_close) close( fd );
1378                     status = STATUS_PIPE_BROKEN;
1379                     break;
1380                 }
1381             }
1382             buffer->NamedPipeState    = 0;  /* FIXME */
1383             buffer->ReadDataAvailable = avail;
1384             buffer->NumberOfMessages  = 0;  /* FIXME */
1385             buffer->MessageLength     = 0;  /* FIXME */
1386             io->Information = FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1387             status = STATUS_SUCCESS;
1388             if (avail)
1389             {
1390                 ULONG data_size = out_size - FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1391                 if (data_size)
1392                 {
1393                     int res = recv( fd, buffer->Data, data_size, MSG_PEEK );
1394                     if (res >= 0) io->Information += res;
1395                 }
1396             }
1397             if (needs_close) close( fd );
1398         }
1399         break;
1400
1401     case FSCTL_PIPE_DISCONNECT:
1402         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1403                                     in_buffer, in_size, out_buffer, out_size );
1404         if (!status)
1405         {
1406             int fd = server_remove_fd_from_cache( handle );
1407             if (fd != -1) close( fd );
1408         }
1409         break;
1410
1411     case FSCTL_PIPE_IMPERSONATE:
1412         FIXME("FSCTL_PIPE_IMPERSONATE: impersonating self\n");
1413         status = RtlImpersonateSelf( SecurityImpersonation );
1414         break;
1415
1416     case FSCTL_LOCK_VOLUME:
1417     case FSCTL_UNLOCK_VOLUME:
1418         FIXME("stub! return success - Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1419               code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1420         status = STATUS_SUCCESS;
1421         break;
1422
1423     case FSCTL_PIPE_LISTEN:
1424     case FSCTL_PIPE_WAIT:
1425     default:
1426         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1427                                     in_buffer, in_size, out_buffer, out_size );
1428         break;
1429     }
1430
1431     if (status != STATUS_PENDING) io->u.Status = status;
1432     return status;
1433 }
1434
1435 /******************************************************************************
1436  *  NtSetVolumeInformationFile          [NTDLL.@]
1437  *  ZwSetVolumeInformationFile          [NTDLL.@]
1438  *
1439  * Set volume information for an open file handle.
1440  *
1441  * PARAMS
1442  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1443  *  IoStatusBlock      [O] Receives information about the operation on return
1444  *  FsInformation      [I] Source for volume information
1445  *  Length             [I] Size of FsInformation
1446  *  FsInformationClass [I] Type of volume information to set
1447  *
1448  * RETURNS
1449  *  Success: 0. IoStatusBlock is updated.
1450  *  Failure: An NTSTATUS error code describing the error.
1451  */
1452 NTSTATUS WINAPI NtSetVolumeInformationFile(
1453         IN HANDLE FileHandle,
1454         PIO_STATUS_BLOCK IoStatusBlock,
1455         PVOID FsInformation,
1456         ULONG Length,
1457         FS_INFORMATION_CLASS FsInformationClass)
1458 {
1459         FIXME("(%p,%p,%p,0x%08x,0x%08x) stub\n",
1460         FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
1461         return 0;
1462 }
1463
1464 /******************************************************************************
1465  *  NtQueryInformationFile              [NTDLL.@]
1466  *  ZwQueryInformationFile              [NTDLL.@]
1467  *
1468  * Get information about an open file handle.
1469  *
1470  * PARAMS
1471  *  hFile    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1472  *  io       [O] Receives information about the operation on return
1473  *  ptr      [O] Destination for file information
1474  *  len      [I] Size of FileInformation
1475  *  class    [I] Type of file information to get
1476  *
1477  * RETURNS
1478  *  Success: 0. IoStatusBlock and FileInformation are updated.
1479  *  Failure: An NTSTATUS error code describing the error.
1480  */
1481 NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
1482                                         PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
1483 {
1484     static const size_t info_sizes[] =
1485     {
1486         0,
1487         sizeof(FILE_DIRECTORY_INFORMATION),            /* FileDirectoryInformation */
1488         sizeof(FILE_FULL_DIRECTORY_INFORMATION),       /* FileFullDirectoryInformation */
1489         sizeof(FILE_BOTH_DIRECTORY_INFORMATION),       /* FileBothDirectoryInformation */
1490         sizeof(FILE_BASIC_INFORMATION),                /* FileBasicInformation */
1491         sizeof(FILE_STANDARD_INFORMATION),             /* FileStandardInformation */
1492         sizeof(FILE_INTERNAL_INFORMATION),             /* FileInternalInformation */
1493         sizeof(FILE_EA_INFORMATION),                   /* FileEaInformation */
1494         sizeof(FILE_ACCESS_INFORMATION),               /* FileAccessInformation */
1495         sizeof(FILE_NAME_INFORMATION)-sizeof(WCHAR),   /* FileNameInformation */
1496         sizeof(FILE_RENAME_INFORMATION)-sizeof(WCHAR), /* FileRenameInformation */
1497         0,                                             /* FileLinkInformation */
1498         sizeof(FILE_NAMES_INFORMATION)-sizeof(WCHAR),  /* FileNamesInformation */
1499         sizeof(FILE_DISPOSITION_INFORMATION),          /* FileDispositionInformation */
1500         sizeof(FILE_POSITION_INFORMATION),             /* FilePositionInformation */
1501         sizeof(FILE_FULL_EA_INFORMATION),              /* FileFullEaInformation */
1502         sizeof(FILE_MODE_INFORMATION),                 /* FileModeInformation */
1503         sizeof(FILE_ALIGNMENT_INFORMATION),            /* FileAlignmentInformation */
1504         sizeof(FILE_ALL_INFORMATION)-sizeof(WCHAR),    /* FileAllInformation */
1505         sizeof(FILE_ALLOCATION_INFORMATION),           /* FileAllocationInformation */
1506         sizeof(FILE_END_OF_FILE_INFORMATION),          /* FileEndOfFileInformation */
1507         0,                                             /* FileAlternateNameInformation */
1508         sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
1509         0,                                             /* FilePipeInformation */
1510         sizeof(FILE_PIPE_LOCAL_INFORMATION),           /* FilePipeLocalInformation */
1511         0,                                             /* FilePipeRemoteInformation */
1512         sizeof(FILE_MAILSLOT_QUERY_INFORMATION),       /* FileMailslotQueryInformation */
1513         0,                                             /* FileMailslotSetInformation */
1514         0,                                             /* FileCompressionInformation */
1515         0,                                             /* FileObjectIdInformation */
1516         0,                                             /* FileCompletionInformation */
1517         0,                                             /* FileMoveClusterInformation */
1518         0,                                             /* FileQuotaInformation */
1519         0,                                             /* FileReparsePointInformation */
1520         0,                                             /* FileNetworkOpenInformation */
1521         0,                                             /* FileAttributeTagInformation */
1522         0                                              /* FileTrackingInformation */
1523     };
1524
1525     struct stat st;
1526     int fd, needs_close = FALSE;
1527
1528     TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", hFile, io, ptr, len, class);
1529
1530     io->Information = 0;
1531
1532     if (class <= 0 || class >= FileMaximumInformation)
1533         return io->u.Status = STATUS_INVALID_INFO_CLASS;
1534     if (!info_sizes[class])
1535     {
1536         FIXME("Unsupported class (%d)\n", class);
1537         return io->u.Status = STATUS_NOT_IMPLEMENTED;
1538     }
1539     if (len < info_sizes[class])
1540         return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1541
1542     if (class != FilePipeLocalInformation)
1543     {
1544         if ((io->u.Status = server_get_unix_fd( hFile, 0, &fd, &needs_close, NULL, NULL )))
1545             return io->u.Status;
1546     }
1547
1548     switch (class)
1549     {
1550     case FileBasicInformation:
1551         {
1552             FILE_BASIC_INFORMATION *info = ptr;
1553
1554             if (fstat( fd, &st ) == -1)
1555                 io->u.Status = FILE_GetNtStatus();
1556             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1557                 io->u.Status = STATUS_INVALID_INFO_CLASS;
1558             else
1559             {
1560                 if (S_ISDIR(st.st_mode)) info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1561                 else info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1562                 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1563                     info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1564                 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime);
1565                 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime);
1566                 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime);
1567                 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime);
1568             }
1569         }
1570         break;
1571     case FileStandardInformation:
1572         {
1573             FILE_STANDARD_INFORMATION *info = ptr;
1574
1575             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1576             else
1577             {
1578                 if ((info->Directory = S_ISDIR(st.st_mode)))
1579                 {
1580                     info->AllocationSize.QuadPart = 0;
1581                     info->EndOfFile.QuadPart      = 0;
1582                     info->NumberOfLinks           = 1;
1583                     info->DeletePending           = FALSE;
1584                 }
1585                 else
1586                 {
1587                     info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1588                     info->EndOfFile.QuadPart      = st.st_size;
1589                     info->NumberOfLinks           = st.st_nlink;
1590                     info->DeletePending           = FALSE; /* FIXME */
1591                 }
1592             }
1593         }
1594         break;
1595     case FilePositionInformation:
1596         {
1597             FILE_POSITION_INFORMATION *info = ptr;
1598             off_t res = lseek( fd, 0, SEEK_CUR );
1599             if (res == (off_t)-1) io->u.Status = FILE_GetNtStatus();
1600             else info->CurrentByteOffset.QuadPart = res;
1601         }
1602         break;
1603     case FileInternalInformation:
1604         {
1605             FILE_INTERNAL_INFORMATION *info = ptr;
1606
1607             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1608             else info->IndexNumber.QuadPart = st.st_ino;
1609         }
1610         break;
1611     case FileEaInformation:
1612         {
1613             FILE_EA_INFORMATION *info = ptr;
1614             info->EaSize = 0;
1615         }
1616         break;
1617     case FileEndOfFileInformation:
1618         {
1619             FILE_END_OF_FILE_INFORMATION *info = ptr;
1620
1621             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1622             else info->EndOfFile.QuadPart = S_ISDIR(st.st_mode) ? 0 : st.st_size;
1623         }
1624         break;
1625     case FileAllInformation:
1626         {
1627             FILE_ALL_INFORMATION *info = ptr;
1628
1629             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1630             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1631                 io->u.Status = STATUS_INVALID_INFO_CLASS;
1632             else
1633             {
1634                 if ((info->StandardInformation.Directory = S_ISDIR(st.st_mode)))
1635                 {
1636                     info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1637                     info->StandardInformation.AllocationSize.QuadPart = 0;
1638                     info->StandardInformation.EndOfFile.QuadPart      = 0;
1639                     info->StandardInformation.NumberOfLinks           = 1;
1640                     info->StandardInformation.DeletePending           = FALSE;
1641                 }
1642                 else
1643                 {
1644                     info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1645                     info->StandardInformation.AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1646                     info->StandardInformation.EndOfFile.QuadPart      = st.st_size;
1647                     info->StandardInformation.NumberOfLinks           = st.st_nlink;
1648                     info->StandardInformation.DeletePending           = FALSE; /* FIXME */
1649                 }
1650                 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1651                     info->BasicInformation.FileAttributes |= FILE_ATTRIBUTE_READONLY;
1652                 RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.CreationTime);
1653                 RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.LastWriteTime);
1654                 RtlSecondsSince1970ToTime( st.st_ctime, &info->BasicInformation.ChangeTime);
1655                 RtlSecondsSince1970ToTime( st.st_atime, &info->BasicInformation.LastAccessTime);
1656                 info->InternalInformation.IndexNumber.QuadPart = st.st_ino;
1657                 info->EaInformation.EaSize = 0;
1658                 info->AccessInformation.AccessFlags = 0;  /* FIXME */
1659                 info->PositionInformation.CurrentByteOffset.QuadPart = lseek( fd, 0, SEEK_CUR );
1660                 info->ModeInformation.Mode = 0;  /* FIXME */
1661                 info->AlignmentInformation.AlignmentRequirement = 1;  /* FIXME */
1662                 info->NameInformation.FileNameLength = 0;
1663                 io->Information = sizeof(*info) - sizeof(WCHAR);
1664             }
1665         }
1666         break;
1667     case FileMailslotQueryInformation:
1668         {
1669             FILE_MAILSLOT_QUERY_INFORMATION *info = ptr;
1670
1671             SERVER_START_REQ( set_mailslot_info )
1672             {
1673                 req->handle = hFile;
1674                 req->flags = 0;
1675                 io->u.Status = wine_server_call( req );
1676                 if( io->u.Status == STATUS_SUCCESS )
1677                 {
1678                     info->MaximumMessageSize = reply->max_msgsize;
1679                     info->MailslotQuota = 0;
1680                     info->NextMessageSize = 0;
1681                     info->MessagesAvailable = 0;
1682                     info->ReadTimeout.QuadPart = reply->read_timeout;
1683                 }
1684             }
1685             SERVER_END_REQ;
1686             if (!io->u.Status)
1687             {
1688                 char *tmpbuf;
1689                 ULONG size = info->MaximumMessageSize ? info->MaximumMessageSize : 0x10000;
1690                 if (size > 0x10000) size = 0x10000;
1691                 if ((tmpbuf = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1692                 {
1693                     int fd, needs_close;
1694                     if (!server_get_unix_fd( hFile, FILE_READ_DATA, &fd, &needs_close, NULL, NULL ))
1695                     {
1696                         int res = recv( fd, tmpbuf, size, MSG_PEEK );
1697                         info->MessagesAvailable = (res > 0);
1698                         info->NextMessageSize = (res >= 0) ? res : MAILSLOT_NO_MESSAGE;
1699                         if (needs_close) close( fd );
1700                     }
1701                     RtlFreeHeap( GetProcessHeap(), 0, tmpbuf );
1702                 }
1703             }
1704         }
1705         break;
1706     case FilePipeLocalInformation:
1707         {
1708             FILE_PIPE_LOCAL_INFORMATION* pli = ptr;
1709
1710             SERVER_START_REQ( get_named_pipe_info )
1711             {
1712                 req->handle = hFile;
1713                 if (!(io->u.Status = wine_server_call( req )))
1714                 {
1715                     pli->NamedPipeType = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_WRITE) ? 
1716                         FILE_PIPE_TYPE_MESSAGE : FILE_PIPE_TYPE_BYTE;
1717                     pli->NamedPipeConfiguration = 0; /* FIXME */
1718                     pli->MaximumInstances = reply->maxinstances;
1719                     pli->CurrentInstances = reply->instances;
1720                     pli->InboundQuota = reply->insize;
1721                     pli->ReadDataAvailable = 0; /* FIXME */
1722                     pli->OutboundQuota = reply->outsize;
1723                     pli->WriteQuotaAvailable = 0; /* FIXME */
1724                     pli->NamedPipeState = 0; /* FIXME */
1725                     pli->NamedPipeEnd = (reply->flags & NAMED_PIPE_SERVER_END) ?
1726                         FILE_PIPE_SERVER_END : FILE_PIPE_CLIENT_END;
1727                 }
1728             }
1729             SERVER_END_REQ;
1730         }
1731         break;
1732     default:
1733         FIXME("Unsupported class (%d)\n", class);
1734         io->u.Status = STATUS_NOT_IMPLEMENTED;
1735         break;
1736     }
1737     if (needs_close) close( fd );
1738     if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
1739     return io->u.Status;
1740 }
1741
1742 /******************************************************************************
1743  *  NtSetInformationFile                [NTDLL.@]
1744  *  ZwSetInformationFile                [NTDLL.@]
1745  *
1746  * Set information about an open file handle.
1747  *
1748  * PARAMS
1749  *  handle  [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1750  *  io      [O] Receives information about the operation on return
1751  *  ptr     [I] Source for file information
1752  *  len     [I] Size of FileInformation
1753  *  class   [I] Type of file information to set
1754  *
1755  * RETURNS
1756  *  Success: 0. io is updated.
1757  *  Failure: An NTSTATUS error code describing the error.
1758  */
1759 NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
1760                                      PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
1761 {
1762     int fd, needs_close;
1763
1764     TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", handle, io, ptr, len, class);
1765
1766     io->u.Status = STATUS_SUCCESS;
1767     switch (class)
1768     {
1769     case FileBasicInformation:
1770         if (len >= sizeof(FILE_BASIC_INFORMATION))
1771         {
1772             struct stat st;
1773             const FILE_BASIC_INFORMATION *info = ptr;
1774
1775             if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
1776                 return io->u.Status;
1777
1778             if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
1779             {
1780                 ULONGLONG sec, nsec;
1781                 struct timeval tv[2];
1782
1783                 if (!info->LastAccessTime.QuadPart || !info->LastWriteTime.QuadPart)
1784                 {
1785
1786                     tv[0].tv_sec = tv[0].tv_usec = 0;
1787                     tv[1].tv_sec = tv[1].tv_usec = 0;
1788                     if (!fstat( fd, &st ))
1789                     {
1790                         tv[0].tv_sec = st.st_atime;
1791                         tv[1].tv_sec = st.st_mtime;
1792                     }
1793                 }
1794                 if (info->LastAccessTime.QuadPart)
1795                 {
1796                     sec = RtlLargeIntegerDivide( info->LastAccessTime.QuadPart, 10000000, &nsec );
1797                     tv[0].tv_sec = sec - SECS_1601_TO_1970;
1798                     tv[0].tv_usec = (UINT)nsec / 10;
1799                 }
1800                 if (info->LastWriteTime.QuadPart)
1801                 {
1802                     sec = RtlLargeIntegerDivide( info->LastWriteTime.QuadPart, 10000000, &nsec );
1803                     tv[1].tv_sec = sec - SECS_1601_TO_1970;
1804                     tv[1].tv_usec = (UINT)nsec / 10;
1805                 }
1806                 if (futimes( fd, tv ) == -1) io->u.Status = FILE_GetNtStatus();
1807             }
1808
1809             if (io->u.Status == STATUS_SUCCESS && info->FileAttributes)
1810             {
1811                 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1812                 else
1813                 {
1814                     if (info->FileAttributes & FILE_ATTRIBUTE_READONLY)
1815                     {
1816                         if (S_ISDIR( st.st_mode))
1817                             WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
1818                         else
1819                             st.st_mode &= ~0222; /* clear write permission bits */
1820                     }
1821                     else
1822                     {
1823                         /* add write permission only where we already have read permission */
1824                         st.st_mode |= (0600 | ((st.st_mode & 044) >> 1)) & (~FILE_umask);
1825                     }
1826                     if (fchmod( fd, st.st_mode ) == -1) io->u.Status = FILE_GetNtStatus();
1827                 }
1828             }
1829
1830             if (needs_close) close( fd );
1831         }
1832         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1833         break;
1834
1835     case FilePositionInformation:
1836         if (len >= sizeof(FILE_POSITION_INFORMATION))
1837         {
1838             const FILE_POSITION_INFORMATION *info = ptr;
1839
1840             if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
1841                 return io->u.Status;
1842
1843             if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
1844                 io->u.Status = FILE_GetNtStatus();
1845
1846             if (needs_close) close( fd );
1847         }
1848         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1849         break;
1850
1851     case FileEndOfFileInformation:
1852         if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
1853         {
1854             struct stat st;
1855             const FILE_END_OF_FILE_INFORMATION *info = ptr;
1856
1857             if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
1858                 return io->u.Status;
1859
1860             /* first try normal truncate */
1861             if (ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1862
1863             /* now check for the need to extend the file */
1864             if (fstat( fd, &st ) != -1 && (off_t)info->EndOfFile.QuadPart > st.st_size)
1865             {
1866                 static const char zero;
1867
1868                 /* extend the file one byte beyond the requested size and then truncate it */
1869                 /* this should work around ftruncate implementations that can't extend files */
1870                 if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
1871                     ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1872             }
1873             io->u.Status = FILE_GetNtStatus();
1874
1875             if (needs_close) close( fd );
1876         }
1877         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1878         break;
1879
1880     case FileMailslotSetInformation:
1881         {
1882             FILE_MAILSLOT_SET_INFORMATION *info = ptr;
1883
1884             SERVER_START_REQ( set_mailslot_info )
1885             {
1886                 req->handle = handle;
1887                 req->flags = MAILSLOT_SET_READ_TIMEOUT;
1888                 req->read_timeout = info->ReadTimeout.QuadPart;
1889                 io->u.Status = wine_server_call( req );
1890             }
1891             SERVER_END_REQ;
1892         }
1893         break;
1894
1895     case FileCompletionInformation:
1896         if (len >= sizeof(FILE_COMPLETION_INFORMATION))
1897         {
1898             FILE_COMPLETION_INFORMATION *info = (FILE_COMPLETION_INFORMATION *)ptr;
1899
1900             SERVER_START_REQ( set_completion_info )
1901             {
1902                 req->handle   = handle;
1903                 req->chandle  = info->CompletionPort;
1904                 req->ckey     = info->CompletionKey;
1905                 io->u.Status  = wine_server_call( req );
1906             }
1907             SERVER_END_REQ;
1908         } else
1909             io->u.Status = STATUS_INVALID_PARAMETER_3;
1910         break;
1911
1912     default:
1913         FIXME("Unsupported class (%d)\n", class);
1914         io->u.Status = STATUS_NOT_IMPLEMENTED;
1915         break;
1916     }
1917     io->Information = 0;
1918     return io->u.Status;
1919 }
1920
1921
1922 /******************************************************************************
1923  *              NtQueryFullAttributesFile   (NTDLL.@)
1924  */
1925 NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
1926                                            FILE_NETWORK_OPEN_INFORMATION *info )
1927 {
1928     ANSI_STRING unix_name;
1929     NTSTATUS status;
1930
1931     if (!(status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, FILE_OPEN,
1932                                               !(attr->Attributes & OBJ_CASE_INSENSITIVE) )))
1933     {
1934         struct stat st;
1935
1936         if (stat( unix_name.Buffer, &st ) == -1)
1937             status = FILE_GetNtStatus();
1938         else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1939             status = STATUS_INVALID_INFO_CLASS;
1940         else
1941         {
1942             if (S_ISDIR(st.st_mode))
1943             {
1944                 info->FileAttributes          = FILE_ATTRIBUTE_DIRECTORY;
1945                 info->AllocationSize.QuadPart = 0;
1946                 info->EndOfFile.QuadPart      = 0;
1947             }
1948             else
1949             {
1950                 info->FileAttributes          = FILE_ATTRIBUTE_ARCHIVE;
1951                 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1952                 info->EndOfFile.QuadPart      = st.st_size;
1953             }
1954             if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1955                 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1956             RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
1957             RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
1958             RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
1959             RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
1960             if (DIR_is_hidden_file( attr->ObjectName ))
1961                 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
1962         }
1963         RtlFreeAnsiString( &unix_name );
1964     }
1965     else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
1966     return status;
1967 }
1968
1969
1970 /******************************************************************************
1971  *              NtQueryAttributesFile   (NTDLL.@)
1972  *              ZwQueryAttributesFile   (NTDLL.@)
1973  */
1974 NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
1975 {
1976     FILE_NETWORK_OPEN_INFORMATION full_info;
1977     NTSTATUS status;
1978
1979     if (!(status = NtQueryFullAttributesFile( attr, &full_info )))
1980     {
1981         info->CreationTime.QuadPart   = full_info.CreationTime.QuadPart;
1982         info->LastAccessTime.QuadPart = full_info.LastAccessTime.QuadPart;
1983         info->LastWriteTime.QuadPart  = full_info.LastWriteTime.QuadPart;
1984         info->ChangeTime.QuadPart     = full_info.ChangeTime.QuadPart;
1985         info->FileAttributes          = full_info.FileAttributes;
1986     }
1987     return status;
1988 }
1989
1990
1991 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__APPLE__)
1992 /* helper for FILE_GetDeviceInfo to hide some platform differences in fstatfs */
1993 static inline void get_device_info_fstatfs( FILE_FS_DEVICE_INFORMATION *info, const char *fstypename,
1994                                             unsigned int flags )
1995 {
1996     if (!strcmp("cd9660", fstypename) || !strcmp("udf", fstypename))
1997     {
1998         info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
1999         /* Don't assume read-only, let the mount options set it below */
2000         info->Characteristics |= FILE_REMOVABLE_MEDIA;
2001     }
2002     else if (!strcmp("nfs", fstypename) || !strcmp("nwfs", fstypename) ||
2003              !strcmp("smbfs", fstypename) || !strcmp("afpfs", fstypename))
2004     {
2005         info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
2006         info->Characteristics |= FILE_REMOTE_DEVICE;
2007     }
2008     else if (!strcmp("procfs", fstypename))
2009         info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
2010     else
2011         info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2012
2013     if (flags & MNT_RDONLY)
2014         info->Characteristics |= FILE_READ_ONLY_DEVICE;
2015
2016     if (!(flags & MNT_LOCAL))
2017     {
2018         info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
2019         info->Characteristics |= FILE_REMOTE_DEVICE;
2020     }
2021 }
2022 #endif
2023
2024 static inline int is_device_placeholder( int fd )
2025 {
2026     static const char wine_placeholder[] = "Wine device placeholder";
2027     char buffer[sizeof(wine_placeholder)-1];
2028
2029     if (pread( fd, buffer, sizeof(wine_placeholder) - 1, 0 ) != sizeof(wine_placeholder) - 1)
2030         return 0;
2031     return !memcmp( buffer, wine_placeholder, sizeof(wine_placeholder) - 1 );
2032 }
2033
2034 /******************************************************************************
2035  *              get_device_info
2036  *
2037  * Implementation of the FileFsDeviceInformation query for NtQueryVolumeInformationFile.
2038  */
2039 static NTSTATUS get_device_info( int fd, FILE_FS_DEVICE_INFORMATION *info )
2040 {
2041     struct stat st;
2042
2043     info->Characteristics = 0;
2044     if (fstat( fd, &st ) < 0) return FILE_GetNtStatus();
2045     if (S_ISCHR( st.st_mode ))
2046     {
2047         info->DeviceType = FILE_DEVICE_UNKNOWN;
2048 #ifdef linux
2049         switch(major(st.st_rdev))
2050         {
2051         case MEM_MAJOR:
2052             info->DeviceType = FILE_DEVICE_NULL;
2053             break;
2054         case TTY_MAJOR:
2055             info->DeviceType = FILE_DEVICE_SERIAL_PORT;
2056             break;
2057         case LP_MAJOR:
2058             info->DeviceType = FILE_DEVICE_PARALLEL_PORT;
2059             break;
2060         case SCSI_TAPE_MAJOR:
2061             info->DeviceType = FILE_DEVICE_TAPE;
2062             break;
2063         }
2064 #endif
2065     }
2066     else if (S_ISBLK( st.st_mode ))
2067     {
2068         info->DeviceType = FILE_DEVICE_DISK;
2069     }
2070     else if (S_ISFIFO( st.st_mode ) || S_ISSOCK( st.st_mode ))
2071     {
2072         info->DeviceType = FILE_DEVICE_NAMED_PIPE;
2073     }
2074     else if (is_device_placeholder( fd ))
2075     {
2076         info->DeviceType = FILE_DEVICE_DISK;
2077     }
2078     else  /* regular file or directory */
2079     {
2080 #if defined(linux) && defined(HAVE_FSTATFS)
2081         struct statfs stfs;
2082
2083         /* check for floppy disk */
2084         if (major(st.st_dev) == FLOPPY_MAJOR)
2085             info->Characteristics |= FILE_REMOVABLE_MEDIA;
2086
2087         if (fstatfs( fd, &stfs ) < 0) stfs.f_type = 0;
2088         switch (stfs.f_type)
2089         {
2090         case 0x9660:      /* iso9660 */
2091         case 0x9fa1:      /* supermount */
2092         case 0x15013346:  /* udf */
2093             info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
2094             info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
2095             break;
2096         case 0x6969:  /* nfs */
2097         case 0x517B:  /* smbfs */
2098         case 0x564c:  /* ncpfs */
2099             info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
2100             info->Characteristics |= FILE_REMOTE_DEVICE;
2101             break;
2102         case 0x01021994:  /* tmpfs */
2103         case 0x28cd3d45:  /* cramfs */
2104         case 0x1373:      /* devfs */
2105         case 0x9fa0:      /* procfs */
2106             info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
2107             break;
2108         default:
2109             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2110             break;
2111         }
2112 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
2113         struct statfs stfs;
2114
2115         if (fstatfs( fd, &stfs ) < 0)
2116             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2117         else
2118             get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flags );
2119 #elif defined(__NetBSD__)
2120         struct statvfs stfs;
2121
2122         if (fstatvfs( fd, &stfs) < 0)
2123             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2124         else
2125             get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flag );
2126 #elif defined(sun)
2127         /* Use dkio to work out device types */
2128         {
2129 # include <sys/dkio.h>
2130 # include <sys/vtoc.h>
2131             struct dk_cinfo dkinf;
2132             int retval = ioctl(fd, DKIOCINFO, &dkinf);
2133             if(retval==-1){
2134                 WARN("Unable to get disk device type information - assuming a disk like device\n");
2135                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2136             }
2137             switch (dkinf.dki_ctype)
2138             {
2139             case DKC_CDROM:
2140                 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
2141                 info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
2142                 break;
2143             case DKC_NCRFLOPPY:
2144             case DKC_SMSFLOPPY:
2145             case DKC_INTEL82072:
2146             case DKC_INTEL82077:
2147                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2148                 info->Characteristics |= FILE_REMOVABLE_MEDIA;
2149                 break;
2150             case DKC_MD:
2151                 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
2152                 break;
2153             default:
2154                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2155             }
2156         }
2157 #else
2158         static int warned;
2159         if (!warned++) FIXME( "device info not properly supported on this platform\n" );
2160         info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2161 #endif
2162         info->Characteristics |= FILE_DEVICE_IS_MOUNTED;
2163     }
2164     return STATUS_SUCCESS;
2165 }
2166
2167
2168 /******************************************************************************
2169  *  NtQueryVolumeInformationFile                [NTDLL.@]
2170  *  ZwQueryVolumeInformationFile                [NTDLL.@]
2171  *
2172  * Get volume information for an open file handle.
2173  *
2174  * PARAMS
2175  *  handle      [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2176  *  io          [O] Receives information about the operation on return
2177  *  buffer      [O] Destination for volume information
2178  *  length      [I] Size of FsInformation
2179  *  info_class  [I] Type of volume information to set
2180  *
2181  * RETURNS
2182  *  Success: 0. io and buffer are updated.
2183  *  Failure: An NTSTATUS error code describing the error.
2184  */
2185 NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
2186                                               PVOID buffer, ULONG length,
2187                                               FS_INFORMATION_CLASS info_class )
2188 {
2189     int fd, needs_close;
2190     struct stat st;
2191
2192     if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
2193         return io->u.Status;
2194
2195     io->u.Status = STATUS_NOT_IMPLEMENTED;
2196     io->Information = 0;
2197
2198     switch( info_class )
2199     {
2200     case FileFsVolumeInformation:
2201         FIXME( "%p: volume info not supported\n", handle );
2202         break;
2203     case FileFsLabelInformation:
2204         FIXME( "%p: label info not supported\n", handle );
2205         break;
2206     case FileFsSizeInformation:
2207         if (length < sizeof(FILE_FS_SIZE_INFORMATION))
2208             io->u.Status = STATUS_BUFFER_TOO_SMALL;
2209         else
2210         {
2211             FILE_FS_SIZE_INFORMATION *info = buffer;
2212
2213             if (fstat( fd, &st ) < 0)
2214             {
2215                 io->u.Status = FILE_GetNtStatus();
2216                 break;
2217             }
2218             if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2219             {
2220                 io->u.Status = STATUS_INVALID_DEVICE_REQUEST;
2221             }
2222             else
2223             {
2224                 /* Linux's fstatvfs is buggy */
2225 #if !defined(linux) || !defined(HAVE_FSTATFS)
2226                 struct statvfs stfs;
2227
2228                 if (fstatvfs( fd, &stfs ) < 0)
2229                 {
2230                     io->u.Status = FILE_GetNtStatus();
2231                     break;
2232                 }
2233                 info->BytesPerSector = stfs.f_frsize;
2234 #else
2235                 struct statfs stfs;
2236                 if (fstatfs( fd, &stfs ) < 0)
2237                 {
2238                     io->u.Status = FILE_GetNtStatus();
2239                     break;
2240                 }
2241                 info->BytesPerSector = stfs.f_bsize;
2242 #endif
2243                 info->TotalAllocationUnits.QuadPart = stfs.f_blocks;
2244                 info->AvailableAllocationUnits.QuadPart = stfs.f_bavail;
2245                 info->SectorsPerAllocationUnit = 1;
2246                 io->Information = sizeof(*info);
2247                 io->u.Status = STATUS_SUCCESS;
2248             }
2249         }
2250         break;
2251     case FileFsDeviceInformation:
2252         if (length < sizeof(FILE_FS_DEVICE_INFORMATION))
2253             io->u.Status = STATUS_BUFFER_TOO_SMALL;
2254         else
2255         {
2256             FILE_FS_DEVICE_INFORMATION *info = buffer;
2257
2258             if ((io->u.Status = get_device_info( fd, info )) == STATUS_SUCCESS)
2259                 io->Information = sizeof(*info);
2260         }
2261         break;
2262     case FileFsAttributeInformation:
2263         FIXME( "%p: attribute info not supported\n", handle );
2264         break;
2265     case FileFsControlInformation:
2266         FIXME( "%p: control info not supported\n", handle );
2267         break;
2268     case FileFsFullSizeInformation:
2269         FIXME( "%p: full size info not supported\n", handle );
2270         break;
2271     case FileFsObjectIdInformation:
2272         FIXME( "%p: object id info not supported\n", handle );
2273         break;
2274     case FileFsMaximumInformation:
2275         FIXME( "%p: maximum info not supported\n", handle );
2276         break;
2277     default:
2278         io->u.Status = STATUS_INVALID_PARAMETER;
2279         break;
2280     }
2281     if (needs_close) close( fd );
2282     return io->u.Status;
2283 }
2284
2285
2286 /******************************************************************
2287  *              NtFlushBuffersFile  (NTDLL.@)
2288  *
2289  * Flush any buffered data on an open file handle.
2290  *
2291  * PARAMS
2292  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2293  *  IoStatusBlock      [O] Receives information about the operation on return
2294  *
2295  * RETURNS
2296  *  Success: 0. IoStatusBlock is updated.
2297  *  Failure: An NTSTATUS error code describing the error.
2298  */
2299 NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
2300 {
2301     NTSTATUS ret;
2302     HANDLE hEvent = NULL;
2303
2304     SERVER_START_REQ( flush_file )
2305     {
2306         req->handle = hFile;
2307         ret = wine_server_call( req );
2308         hEvent = reply->event;
2309     }
2310     SERVER_END_REQ;
2311     if (!ret && hEvent)
2312     {
2313         ret = NtWaitForSingleObject( hEvent, FALSE, NULL );
2314         NtClose( hEvent );
2315     }
2316     return ret;
2317 }
2318
2319 /******************************************************************
2320  *              NtLockFile       (NTDLL.@)
2321  *
2322  *
2323  */
2324 NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
2325                             PIO_APC_ROUTINE apc, void* apc_user,
2326                             PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
2327                             PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
2328                             BOOLEAN exclusive )
2329 {
2330     NTSTATUS    ret;
2331     HANDLE      handle;
2332     BOOLEAN     async;
2333
2334     if (apc || io_status || key)
2335     {
2336         FIXME("Unimplemented yet parameter\n");
2337         return STATUS_NOT_IMPLEMENTED;
2338     }
2339
2340     if (apc_user) FIXME("I/O completion on lock not implemented yet\n");
2341
2342     for (;;)
2343     {
2344         SERVER_START_REQ( lock_file )
2345         {
2346             req->handle      = hFile;
2347             req->offset      = offset->QuadPart;
2348             req->count       = count->QuadPart;
2349             req->shared      = !exclusive;
2350             req->wait        = !dont_wait;
2351             ret = wine_server_call( req );
2352             handle = reply->handle;
2353             async  = reply->overlapped;
2354         }
2355         SERVER_END_REQ;
2356         if (ret != STATUS_PENDING)
2357         {
2358             if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
2359             return ret;
2360         }
2361
2362         if (async)
2363         {
2364             FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
2365             if (handle) NtClose( handle );
2366             return STATUS_PENDING;
2367         }
2368         if (handle)
2369         {
2370             NtWaitForSingleObject( handle, FALSE, NULL );
2371             NtClose( handle );
2372         }
2373         else
2374         {
2375             LARGE_INTEGER time;
2376     
2377             /* Unix lock conflict, sleep a bit and retry */
2378             time.QuadPart = 100 * (ULONGLONG)10000;
2379             time.QuadPart = -time.QuadPart;
2380             NtDelayExecution( FALSE, &time );
2381         }
2382     }
2383 }
2384
2385
2386 /******************************************************************
2387  *              NtUnlockFile    (NTDLL.@)
2388  *
2389  *
2390  */
2391 NTSTATUS WINAPI NtUnlockFile( HANDLE hFile, PIO_STATUS_BLOCK io_status,
2392                               PLARGE_INTEGER offset, PLARGE_INTEGER count,
2393                               PULONG key )
2394 {
2395     NTSTATUS status;
2396
2397     TRACE( "%p %x%08x %x%08x\n",
2398            hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
2399
2400     if (io_status || key)
2401     {
2402         FIXME("Unimplemented yet parameter\n");
2403         return STATUS_NOT_IMPLEMENTED;
2404     }
2405
2406     SERVER_START_REQ( unlock_file )
2407     {
2408         req->handle = hFile;
2409         req->offset = offset->QuadPart;
2410         req->count  = count->QuadPart;
2411         status = wine_server_call( req );
2412     }
2413     SERVER_END_REQ;
2414     return status;
2415 }
2416
2417 /******************************************************************
2418  *              NtCreateNamedPipeFile    (NTDLL.@)
2419  *
2420  *
2421  */
2422 NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE handle, ULONG access,
2423                                        POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK iosb,
2424                                        ULONG sharing, ULONG dispo, ULONG options,
2425                                        ULONG pipe_type, ULONG read_mode, 
2426                                        ULONG completion_mode, ULONG max_inst,
2427                                        ULONG inbound_quota, ULONG outbound_quota,
2428                                        PLARGE_INTEGER timeout)
2429 {
2430     NTSTATUS    status;
2431
2432     TRACE("(%p %x %s %p %x %d %x %d %d %d %d %d %d %p)\n",
2433           handle, access, debugstr_w(attr->ObjectName->Buffer), iosb, sharing, dispo,
2434           options, pipe_type, read_mode, completion_mode, max_inst, inbound_quota,
2435           outbound_quota, timeout);
2436
2437     /* assume we only get relative timeout */
2438     if (timeout->QuadPart > 0)
2439         FIXME("Wrong time %s\n", wine_dbgstr_longlong(timeout->QuadPart));
2440
2441     SERVER_START_REQ( create_named_pipe )
2442     {
2443         req->access  = access;
2444         req->attributes = attr->Attributes;
2445         req->rootdir = attr->RootDirectory;
2446         req->options = options;
2447         req->flags = 
2448             (pipe_type) ? NAMED_PIPE_MESSAGE_STREAM_WRITE : 0 |
2449             (read_mode) ? NAMED_PIPE_MESSAGE_STREAM_READ  : 0 |
2450             (completion_mode) ? NAMED_PIPE_NONBLOCKING_MODE  : 0;
2451         req->maxinstances = max_inst;
2452         req->outsize = outbound_quota;
2453         req->insize  = inbound_quota;
2454         req->timeout = timeout->QuadPart;
2455         wine_server_add_data( req, attr->ObjectName->Buffer,
2456                               attr->ObjectName->Length );
2457         status = wine_server_call( req );
2458         if (!status) *handle = reply->handle;
2459     }
2460     SERVER_END_REQ;
2461     return status;
2462 }
2463
2464 /******************************************************************
2465  *              NtDeleteFile    (NTDLL.@)
2466  *
2467  *
2468  */
2469 NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
2470 {
2471     NTSTATUS status;
2472     HANDLE hFile;
2473     IO_STATUS_BLOCK io;
2474
2475     TRACE("%p\n", ObjectAttributes);
2476     status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
2477                            ObjectAttributes, &io, NULL, 0,
2478                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 
2479                            FILE_OPEN, FILE_DELETE_ON_CLOSE, NULL, 0 );
2480     if (status == STATUS_SUCCESS) status = NtClose(hFile);
2481     return status;
2482 }
2483
2484 /******************************************************************
2485  *              NtCancelIoFile    (NTDLL.@)
2486  *
2487  *
2488  */
2489 NTSTATUS WINAPI NtCancelIoFile( HANDLE hFile, PIO_STATUS_BLOCK io_status )
2490 {
2491     LARGE_INTEGER timeout;
2492
2493     TRACE("%p %p\n", hFile, io_status );
2494
2495     SERVER_START_REQ( cancel_async )
2496     {
2497         req->handle = hFile;
2498         wine_server_call( req );
2499     }
2500     SERVER_END_REQ;
2501     /* Let some APC be run, so that we can run the remaining APCs on hFile
2502      * either the cancelation of the pending one, but also the execution
2503      * of the queued APC, but not yet run. This is needed to ensure proper
2504      * clean-up of allocated data.
2505      */
2506     timeout.u.LowPart = timeout.u.HighPart = 0;
2507     return io_status->u.Status = NtDelayExecution( TRUE, &timeout );
2508 }
2509
2510 /******************************************************************************
2511  *  NtCreateMailslotFile        [NTDLL.@]
2512  *  ZwCreateMailslotFile        [NTDLL.@]
2513  *
2514  * PARAMS
2515  *  pHandle          [O] pointer to receive the handle created
2516  *  DesiredAccess    [I] access mode (read, write, etc)
2517  *  ObjectAttributes [I] fully qualified NT path of the mailslot
2518  *  IoStatusBlock    [O] receives completion status and other info
2519  *  CreateOptions    [I]
2520  *  MailslotQuota    [I]
2521  *  MaxMessageSize   [I]
2522  *  TimeOut          [I]
2523  *
2524  * RETURNS
2525  *  An NT status code
2526  */
2527 NTSTATUS WINAPI NtCreateMailslotFile(PHANDLE pHandle, ULONG DesiredAccess,
2528      POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK IoStatusBlock,
2529      ULONG CreateOptions, ULONG MailslotQuota, ULONG MaxMessageSize,
2530      PLARGE_INTEGER TimeOut)
2531 {
2532     LARGE_INTEGER timeout;
2533     NTSTATUS ret;
2534
2535     TRACE("%p %08x %p %p %08x %08x %08x %p\n",
2536               pHandle, DesiredAccess, attr, IoStatusBlock,
2537               CreateOptions, MailslotQuota, MaxMessageSize, TimeOut);
2538
2539     if (!pHandle) return STATUS_ACCESS_VIOLATION;
2540     if (!attr) return STATUS_INVALID_PARAMETER;
2541     if (!attr->ObjectName) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2542
2543     /*
2544      *  For a NULL TimeOut pointer set the default timeout value
2545      */
2546     if  (!TimeOut)
2547         timeout.QuadPart = -1;
2548     else
2549         timeout.QuadPart = TimeOut->QuadPart;
2550
2551     SERVER_START_REQ( create_mailslot )
2552     {
2553         req->access = DesiredAccess;
2554         req->attributes = attr->Attributes;
2555         req->rootdir = attr->RootDirectory;
2556         req->max_msgsize = MaxMessageSize;
2557         req->read_timeout = timeout.QuadPart;
2558         wine_server_add_data( req, attr->ObjectName->Buffer,
2559                               attr->ObjectName->Length );
2560         ret = wine_server_call( req );
2561         if( ret == STATUS_SUCCESS )
2562             *pHandle = reply->handle;
2563     }
2564     SERVER_END_REQ;
2565  
2566     return ret;
2567 }