server: Avoid a crash when trying to wait on a disconnected pipe client.
[wine] / server / fd.c
1 /*
2  * Server-side file descriptor management
3  *
4  * Copyright (C) 2000, 2003 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <assert.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <signal.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #ifdef HAVE_POLL_H
35 #include <poll.h>
36 #endif
37 #ifdef HAVE_SYS_POLL_H
38 #include <sys/poll.h>
39 #endif
40 #ifdef HAVE_LINUX_MAJOR_H
41 #include <linux/major.h>
42 #endif
43 #ifdef HAVE_SYS_STATVFS_H
44 #include <sys/statvfs.h>
45 #endif
46 #ifdef HAVE_SYS_VFS_H
47 /*
48  * Solaris defines its system list in sys/list.h.
49  * This need to be workaround it here.
50  */
51 #define list SYSLIST
52 #define list_next SYSLIST_NEXT
53 #define list_prev SYSLIST_PREV
54 #define list_head SYSLIST_HEAD
55 #define list_tail SYSLIST_TAIL
56 #define list_move_tail SYSLIST_MOVE_TAIL
57 #define list_remove SYSLIST_REMOVE
58 #include <sys/vfs.h>
59 #undef list
60 #undef list_next
61 #undef list_prev
62 #undef list_head
63 #undef list_tail
64 #undef list_move_tail
65 #undef list_remove
66 #endif
67 #ifdef HAVE_SYS_PARAM_H
68 #include <sys/param.h>
69 #endif
70 #ifdef HAVE_SYS_MOUNT_H
71 #include <sys/mount.h>
72 #endif
73 #ifdef HAVE_SYS_STATFS_H
74 #include <sys/statfs.h>
75 #endif
76 #ifdef HAVE_SYS_SYSCTL_H
77 #include <sys/sysctl.h>
78 #endif
79 #ifdef HAVE_SYS_EVENT_H
80 #include <sys/event.h>
81 #undef LIST_INIT
82 #undef LIST_ENTRY
83 #endif
84 #ifdef HAVE_STDINT_H
85 #include <stdint.h>
86 #endif
87 #include <sys/stat.h>
88 #include <sys/time.h>
89 #include <sys/types.h>
90 #include <unistd.h>
91
92 #include "ntstatus.h"
93 #define WIN32_NO_STATUS
94 #include "object.h"
95 #include "file.h"
96 #include "handle.h"
97 #include "process.h"
98 #include "request.h"
99
100 #include "winternl.h"
101 #include "winioctl.h"
102
103 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
104 # include <sys/epoll.h>
105 # define USE_EPOLL
106 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
107 # define USE_EPOLL
108 # define EPOLLIN POLLIN
109 # define EPOLLOUT POLLOUT
110 # define EPOLLERR POLLERR
111 # define EPOLLHUP POLLHUP
112 # define EPOLL_CTL_ADD 1
113 # define EPOLL_CTL_DEL 2
114 # define EPOLL_CTL_MOD 3
115
116 typedef union epoll_data
117 {
118   void *ptr;
119   int fd;
120   uint32_t u32;
121   uint64_t u64;
122 } epoll_data_t;
123
124 struct epoll_event
125 {
126   uint32_t events;
127   epoll_data_t data;
128 };
129
130 #define SYSCALL_RET(ret) do { \
131         if (ret < 0) { errno = -ret; ret = -1; } \
132         return ret; \
133     } while(0)
134
135 static inline int epoll_create( int size )
136 {
137     int ret;
138     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
139              : "=a" (ret) : "0" (254 /*NR_epoll_create*/), "r" (size) );
140     SYSCALL_RET(ret);
141 }
142
143 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
144 {
145     int ret;
146     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
147              : "=a" (ret)
148              : "0" (255 /*NR_epoll_ctl*/), "r" (epfd), "c" (op), "d" (fd), "S" (event), "m" (*event) );
149     SYSCALL_RET(ret);
150 }
151
152 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
153 {
154     int ret;
155     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
156              : "=a" (ret)
157              : "0" (256 /*NR_epoll_wait*/), "r" (epfd), "c" (events), "d" (maxevents), "S" (timeout)
158              : "memory" );
159     SYSCALL_RET(ret);
160 }
161 #undef SYSCALL_RET
162
163 #endif /* linux && __i386__ && HAVE_STDINT_H */
164
165
166 /* Because of the stupid Posix locking semantics, we need to keep
167  * track of all file descriptors referencing a given file, and not
168  * close a single one until all the locks are gone (sigh).
169  */
170
171 /* file descriptor object */
172
173 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
174 struct closed_fd
175 {
176     struct list entry;       /* entry in inode closed list */
177     int         unix_fd;     /* the unix file descriptor */
178     char        unlink[1];   /* name to unlink on close (if any) */
179 };
180
181 struct fd
182 {
183     struct object        obj;         /* object header */
184     const struct fd_ops *fd_ops;      /* file descriptor operations */
185     struct inode        *inode;       /* inode that this fd belongs to */
186     struct list          inode_entry; /* entry in inode fd list */
187     struct closed_fd    *closed;      /* structure to store the unix fd at destroy time */
188     struct object       *user;        /* object using this file descriptor */
189     struct list          locks;       /* list of locks on this fd */
190     unsigned int         access;      /* file access (FILE_READ_DATA etc.) */
191     unsigned int         options;     /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
192     unsigned int         sharing;     /* file sharing mode */
193     int                  unix_fd;     /* unix file descriptor */
194     unsigned int         no_fd_status;/* status to return when unix_fd is -1 */
195     int                  signaled :1; /* is the fd signaled? */
196     int                  fs_locks :1; /* can we use filesystem locks for this fd? */
197     int                  poll_index;  /* index of fd in poll array */
198     struct async_queue  *read_q;      /* async readers of this fd */
199     struct async_queue  *write_q;     /* async writers of this fd */
200     struct async_queue  *wait_q;      /* other async waiters of this fd */
201     struct completion   *completion;  /* completion object attached to this fd */
202     apc_param_t          comp_key;    /* completion key to set in completion events */
203 };
204
205 static void fd_dump( struct object *obj, int verbose );
206 static void fd_destroy( struct object *obj );
207
208 static const struct object_ops fd_ops =
209 {
210     sizeof(struct fd),        /* size */
211     fd_dump,                  /* dump */
212     no_get_type,              /* get_type */
213     no_add_queue,             /* add_queue */
214     NULL,                     /* remove_queue */
215     NULL,                     /* signaled */
216     NULL,                     /* satisfied */
217     no_signal,                /* signal */
218     no_get_fd,                /* get_fd */
219     no_map_access,            /* map_access */
220     default_get_sd,           /* get_sd */
221     default_set_sd,           /* set_sd */
222     no_lookup_name,           /* lookup_name */
223     no_open_file,             /* open_file */
224     no_close_handle,          /* close_handle */
225     fd_destroy                /* destroy */
226 };
227
228 /* device object */
229
230 #define DEVICE_HASH_SIZE 7
231 #define INODE_HASH_SIZE 17
232
233 struct device
234 {
235     struct object       obj;        /* object header */
236     struct list         entry;      /* entry in device hash list */
237     dev_t               dev;        /* device number */
238     int                 removable;  /* removable device? (or -1 if unknown) */
239     struct list         inode_hash[INODE_HASH_SIZE];  /* inodes hash table */
240 };
241
242 static void device_dump( struct object *obj, int verbose );
243 static void device_destroy( struct object *obj );
244
245 static const struct object_ops device_ops =
246 {
247     sizeof(struct device),    /* size */
248     device_dump,              /* dump */
249     no_get_type,              /* get_type */
250     no_add_queue,             /* add_queue */
251     NULL,                     /* remove_queue */
252     NULL,                     /* signaled */
253     NULL,                     /* satisfied */
254     no_signal,                /* signal */
255     no_get_fd,                /* get_fd */
256     no_map_access,            /* map_access */
257     default_get_sd,           /* get_sd */
258     default_set_sd,           /* set_sd */
259     no_lookup_name,           /* lookup_name */
260     no_open_file,             /* open_file */
261     no_close_handle,          /* close_handle */
262     device_destroy            /* destroy */
263 };
264
265 /* inode object */
266
267 struct inode
268 {
269     struct object       obj;        /* object header */
270     struct list         entry;      /* inode hash list entry */
271     struct device      *device;     /* device containing this inode */
272     ino_t               ino;        /* inode number */
273     struct list         open;       /* list of open file descriptors */
274     struct list         locks;      /* list of file locks */
275     struct list         closed;     /* list of file descriptors to close at destroy time */
276 };
277
278 static void inode_dump( struct object *obj, int verbose );
279 static void inode_destroy( struct object *obj );
280
281 static const struct object_ops inode_ops =
282 {
283     sizeof(struct inode),     /* size */
284     inode_dump,               /* dump */
285     no_get_type,              /* get_type */
286     no_add_queue,             /* add_queue */
287     NULL,                     /* remove_queue */
288     NULL,                     /* signaled */
289     NULL,                     /* satisfied */
290     no_signal,                /* signal */
291     no_get_fd,                /* get_fd */
292     no_map_access,            /* map_access */
293     default_get_sd,           /* get_sd */
294     default_set_sd,           /* set_sd */
295     no_lookup_name,           /* lookup_name */
296     no_open_file,             /* open_file */
297     no_close_handle,          /* close_handle */
298     inode_destroy             /* destroy */
299 };
300
301 /* file lock object */
302
303 struct file_lock
304 {
305     struct object       obj;         /* object header */
306     struct fd          *fd;          /* fd owning this lock */
307     struct list         fd_entry;    /* entry in list of locks on a given fd */
308     struct list         inode_entry; /* entry in inode list of locks */
309     int                 shared;      /* shared lock? */
310     file_pos_t          start;       /* locked region is interval [start;end) */
311     file_pos_t          end;
312     struct process     *process;     /* process owning this lock */
313     struct list         proc_entry;  /* entry in list of locks owned by the process */
314 };
315
316 static void file_lock_dump( struct object *obj, int verbose );
317 static int file_lock_signaled( struct object *obj, struct thread *thread );
318
319 static const struct object_ops file_lock_ops =
320 {
321     sizeof(struct file_lock),   /* size */
322     file_lock_dump,             /* dump */
323     no_get_type,                /* get_type */
324     add_queue,                  /* add_queue */
325     remove_queue,               /* remove_queue */
326     file_lock_signaled,         /* signaled */
327     no_satisfied,               /* satisfied */
328     no_signal,                  /* signal */
329     no_get_fd,                  /* get_fd */
330     no_map_access,              /* map_access */
331     default_get_sd,             /* get_sd */
332     default_set_sd,             /* set_sd */
333     no_lookup_name,             /* lookup_name */
334     no_open_file,               /* open_file */
335     no_close_handle,            /* close_handle */
336     no_destroy                  /* destroy */
337 };
338
339
340 #define OFF_T_MAX       (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
341 #define FILE_POS_T_MAX  (~(file_pos_t)0)
342
343 static file_pos_t max_unix_offset = OFF_T_MAX;
344
345 #define DUMP_LONG_LONG(val) do { \
346     if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
347         fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
348     else \
349         fprintf( stderr, "%lx", (unsigned long)(val) ); \
350   } while (0)
351
352
353
354 /****************************************************************/
355 /* timeouts support */
356
357 struct timeout_user
358 {
359     struct list           entry;      /* entry in sorted timeout list */
360     timeout_t             when;       /* timeout expiry (absolute time) */
361     timeout_callback      callback;   /* callback function */
362     void                 *private;    /* callback private data */
363 };
364
365 static struct list timeout_list = LIST_INIT(timeout_list);   /* sorted timeouts list */
366 timeout_t current_time;
367
368 static inline void set_current_time(void)
369 {
370     static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
371     struct timeval now;
372     gettimeofday( &now, NULL );
373     current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
374 }
375
376 /* add a timeout user */
377 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
378 {
379     struct timeout_user *user;
380     struct list *ptr;
381
382     if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
383     user->when     = (when > 0) ? when : current_time - when;
384     user->callback = func;
385     user->private  = private;
386
387     /* Now insert it in the linked list */
388
389     LIST_FOR_EACH( ptr, &timeout_list )
390     {
391         struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
392         if (timeout->when >= user->when) break;
393     }
394     list_add_before( ptr, &user->entry );
395     return user;
396 }
397
398 /* remove a timeout user */
399 void remove_timeout_user( struct timeout_user *user )
400 {
401     list_remove( &user->entry );
402     free( user );
403 }
404
405 /* return a text description of a timeout for debugging purposes */
406 const char *get_timeout_str( timeout_t timeout )
407 {
408     static char buffer[64];
409     long secs, nsecs;
410
411     if (!timeout) return "0";
412     if (timeout == TIMEOUT_INFINITE) return "infinite";
413
414     if (timeout < 0)  /* relative */
415     {
416         secs = -timeout / TICKS_PER_SEC;
417         nsecs = -timeout % TICKS_PER_SEC;
418         sprintf( buffer, "+%ld.%07ld", secs, nsecs );
419     }
420     else  /* absolute */
421     {
422         secs = (timeout - current_time) / TICKS_PER_SEC;
423         nsecs = (timeout - current_time) % TICKS_PER_SEC;
424         if (nsecs < 0)
425         {
426             nsecs += TICKS_PER_SEC;
427             secs--;
428         }
429         if (secs >= 0)
430             sprintf( buffer, "%x%08x (+%ld.%07ld)",
431                      (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
432         else
433             sprintf( buffer, "%x%08x (-%ld.%07ld)",
434                      (unsigned int)(timeout >> 32), (unsigned int)timeout,
435                      -(secs + 1), TICKS_PER_SEC - nsecs );
436     }
437     return buffer;
438 }
439
440
441 /****************************************************************/
442 /* poll support */
443
444 static struct fd **poll_users;              /* users array */
445 static struct pollfd *pollfd;               /* poll fd array */
446 static int nb_users;                        /* count of array entries actually in use */
447 static int active_users;                    /* current number of active users */
448 static int allocated_users;                 /* count of allocated entries in the array */
449 static struct fd **freelist;                /* list of free entries in the array */
450
451 static int get_next_timeout(void);
452
453 static inline void fd_poll_event( struct fd *fd, int event )
454 {
455     fd->fd_ops->poll_event( fd, event );
456 }
457
458 #ifdef USE_EPOLL
459
460 static int epoll_fd = -1;
461
462 static inline void init_epoll(void)
463 {
464     epoll_fd = epoll_create( 128 );
465 }
466
467 /* set the events that epoll waits for on this fd; helper for set_fd_events */
468 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
469 {
470     struct epoll_event ev;
471     int ctl;
472
473     if (epoll_fd == -1) return;
474
475     if (events == -1)  /* stop waiting on this fd completely */
476     {
477         if (pollfd[user].fd == -1) return;  /* already removed */
478         ctl = EPOLL_CTL_DEL;
479     }
480     else if (pollfd[user].fd == -1)
481     {
482         if (pollfd[user].events) return;  /* stopped waiting on it, don't restart */
483         ctl = EPOLL_CTL_ADD;
484     }
485     else
486     {
487         if (pollfd[user].events == events) return;  /* nothing to do */
488         ctl = EPOLL_CTL_MOD;
489     }
490
491     ev.events = events;
492     memset(&ev.data, 0, sizeof(ev.data));
493     ev.data.u32 = user;
494
495     if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
496     {
497         if (errno == ENOMEM)  /* not enough memory, give up on epoll */
498         {
499             close( epoll_fd );
500             epoll_fd = -1;
501         }
502         else perror( "epoll_ctl" );  /* should not happen */
503     }
504 }
505
506 static inline void remove_epoll_user( struct fd *fd, int user )
507 {
508     if (epoll_fd == -1) return;
509
510     if (pollfd[user].fd != -1)
511     {
512         struct epoll_event dummy;
513         epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
514     }
515 }
516
517 static inline void main_loop_epoll(void)
518 {
519     int i, ret, timeout;
520     struct epoll_event events[128];
521
522     assert( POLLIN == EPOLLIN );
523     assert( POLLOUT == EPOLLOUT );
524     assert( POLLERR == EPOLLERR );
525     assert( POLLHUP == EPOLLHUP );
526
527     if (epoll_fd == -1) return;
528
529     while (active_users)
530     {
531         timeout = get_next_timeout();
532
533         if (!active_users) break;  /* last user removed by a timeout */
534         if (epoll_fd == -1) break;  /* an error occurred with epoll */
535
536         ret = epoll_wait( epoll_fd, events, sizeof(events)/sizeof(events[0]), timeout );
537         set_current_time();
538
539         /* put the events into the pollfd array first, like poll does */
540         for (i = 0; i < ret; i++)
541         {
542             int user = events[i].data.u32;
543             pollfd[user].revents = events[i].events;
544         }
545
546         /* read events from the pollfd array, as set_fd_events may modify them */
547         for (i = 0; i < ret; i++)
548         {
549             int user = events[i].data.u32;
550             if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
551         }
552     }
553 }
554
555 #elif defined(HAVE_KQUEUE)
556
557 static int kqueue_fd = -1;
558
559 static inline void init_epoll(void)
560 {
561 #ifdef __APPLE__ /* kqueue support is broken in Mac OS < 10.5 */
562     int mib[2];
563     char release[32];
564     size_t len = sizeof(release);
565
566     mib[0] = CTL_KERN;
567     mib[1] = KERN_OSRELEASE;
568     if (sysctl( mib, 2, release, &len, NULL, 0 ) == -1) return;
569     if (atoi(release) < 9) return;
570 #endif
571     kqueue_fd = kqueue();
572 }
573
574 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
575 {
576     struct kevent ev[2];
577
578     if (kqueue_fd == -1) return;
579
580     EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)user );
581     EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)user );
582
583     if (events == -1)  /* stop waiting on this fd completely */
584     {
585         if (pollfd[user].fd == -1) return;  /* already removed */
586         ev[0].flags |= EV_DELETE;
587         ev[1].flags |= EV_DELETE;
588     }
589     else if (pollfd[user].fd == -1)
590     {
591         if (pollfd[user].events) return;  /* stopped waiting on it, don't restart */
592         ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
593         ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
594     }
595     else
596     {
597         if (pollfd[user].events == events) return;  /* nothing to do */
598         ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
599         ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
600     }
601
602     if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
603     {
604         if (errno == ENOMEM)  /* not enough memory, give up on kqueue */
605         {
606             close( kqueue_fd );
607             kqueue_fd = -1;
608         }
609         else perror( "kevent" );  /* should not happen */
610     }
611 }
612
613 static inline void remove_epoll_user( struct fd *fd, int user )
614 {
615     if (kqueue_fd == -1) return;
616
617     if (pollfd[user].fd != -1)
618     {
619         struct kevent ev[2];
620
621         EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
622         EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
623         kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
624     }
625 }
626
627 static inline void main_loop_epoll(void)
628 {
629     int i, ret, timeout;
630     struct kevent events[128];
631
632     if (kqueue_fd == -1) return;
633
634     while (active_users)
635     {
636         timeout = get_next_timeout();
637
638         if (!active_users) break;  /* last user removed by a timeout */
639         if (kqueue_fd == -1) break;  /* an error occurred with kqueue */
640
641         if (timeout != -1)
642         {
643             struct timespec ts;
644
645             ts.tv_sec = timeout / 1000;
646             ts.tv_nsec = (timeout % 1000) * 1000000;
647             ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), &ts );
648         }
649         else ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), NULL );
650
651         set_current_time();
652
653         /* put the events into the pollfd array first, like poll does */
654         for (i = 0; i < ret; i++)
655         {
656             long user = (long)events[i].udata;
657             pollfd[user].revents = 0;
658         }
659         for (i = 0; i < ret; i++)
660         {
661             long user = (long)events[i].udata;
662             if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
663             else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
664             if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
665             if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
666         }
667
668         /* read events from the pollfd array, as set_fd_events may modify them */
669         for (i = 0; i < ret; i++)
670         {
671             long user = (long)events[i].udata;
672             if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
673             pollfd[user].revents = 0;
674         }
675     }
676 }
677
678 #else /* HAVE_KQUEUE */
679
680 static inline void init_epoll(void) { }
681 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
682 static inline void remove_epoll_user( struct fd *fd, int user ) { }
683 static inline void main_loop_epoll(void) { }
684
685 #endif /* USE_EPOLL */
686
687
688 /* add a user in the poll array and return its index, or -1 on failure */
689 static int add_poll_user( struct fd *fd )
690 {
691     int ret;
692     if (freelist)
693     {
694         ret = freelist - poll_users;
695         freelist = (struct fd **)poll_users[ret];
696     }
697     else
698     {
699         if (nb_users == allocated_users)
700         {
701             struct fd **newusers;
702             struct pollfd *newpoll;
703             int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
704             if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
705             if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
706             {
707                 if (allocated_users)
708                     poll_users = newusers;
709                 else
710                     free( newusers );
711                 return -1;
712             }
713             poll_users = newusers;
714             pollfd = newpoll;
715             if (!allocated_users) init_epoll();
716             allocated_users = new_count;
717         }
718         ret = nb_users++;
719     }
720     pollfd[ret].fd = -1;
721     pollfd[ret].events = 0;
722     pollfd[ret].revents = 0;
723     poll_users[ret] = fd;
724     active_users++;
725     return ret;
726 }
727
728 /* remove a user from the poll list */
729 static void remove_poll_user( struct fd *fd, int user )
730 {
731     assert( user >= 0 );
732     assert( poll_users[user] == fd );
733
734     remove_epoll_user( fd, user );
735     pollfd[user].fd = -1;
736     pollfd[user].events = 0;
737     pollfd[user].revents = 0;
738     poll_users[user] = (struct fd *)freelist;
739     freelist = &poll_users[user];
740     active_users--;
741 }
742
743 /* process pending timeouts and return the time until the next timeout, in milliseconds */
744 static int get_next_timeout(void)
745 {
746     if (!list_empty( &timeout_list ))
747     {
748         struct list expired_list, *ptr;
749
750         /* first remove all expired timers from the list */
751
752         list_init( &expired_list );
753         while ((ptr = list_head( &timeout_list )) != NULL)
754         {
755             struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
756
757             if (timeout->when <= current_time)
758             {
759                 list_remove( &timeout->entry );
760                 list_add_tail( &expired_list, &timeout->entry );
761             }
762             else break;
763         }
764
765         /* now call the callback for all the removed timers */
766
767         while ((ptr = list_head( &expired_list )) != NULL)
768         {
769             struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
770             list_remove( &timeout->entry );
771             timeout->callback( timeout->private );
772             free( timeout );
773         }
774
775         if ((ptr = list_head( &timeout_list )) != NULL)
776         {
777             struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
778             int diff = (timeout->when - current_time + 9999) / 10000;
779             if (diff < 0) diff = 0;
780             return diff;
781         }
782     }
783     return -1;  /* no pending timeouts */
784 }
785
786 /* server main poll() loop */
787 void main_loop(void)
788 {
789     int i, ret, timeout;
790
791     set_current_time();
792     server_start_time = current_time;
793
794     main_loop_epoll();
795     /* fall through to normal poll loop */
796
797     while (active_users)
798     {
799         timeout = get_next_timeout();
800
801         if (!active_users) break;  /* last user removed by a timeout */
802
803         ret = poll( pollfd, nb_users, timeout );
804         set_current_time();
805
806         if (ret > 0)
807         {
808             for (i = 0; i < nb_users; i++)
809             {
810                 if (pollfd[i].revents)
811                 {
812                     fd_poll_event( poll_users[i], pollfd[i].revents );
813                     if (!--ret) break;
814                 }
815             }
816         }
817     }
818 }
819
820
821 /****************************************************************/
822 /* device functions */
823
824 static struct list device_hash[DEVICE_HASH_SIZE];
825
826 static int is_device_removable( dev_t dev, int unix_fd )
827 {
828 #if defined(linux) && defined(HAVE_FSTATFS)
829     struct statfs stfs;
830
831     /* check for floppy disk */
832     if (major(dev) == FLOPPY_MAJOR) return 1;
833
834     if (fstatfs( unix_fd, &stfs ) == -1) return 0;
835     return (stfs.f_type == 0x9660 ||    /* iso9660 */
836             stfs.f_type == 0x9fa1 ||    /* supermount */
837             stfs.f_type == 0x15013346); /* udf */
838 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
839     struct statfs stfs;
840
841     if (fstatfs( unix_fd, &stfs ) == -1) return 0;
842     return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
843 #elif defined(__NetBSD__)
844     struct statvfs stfs;
845
846     if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
847     return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
848 #elif defined(sun)
849 # include <sys/dkio.h>
850 # include <sys/vtoc.h>
851     struct dk_cinfo dkinf;
852     if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
853     return (dkinf.dki_ctype == DKC_CDROM ||
854             dkinf.dki_ctype == DKC_NCRFLOPPY ||
855             dkinf.dki_ctype == DKC_SMSFLOPPY ||
856             dkinf.dki_ctype == DKC_INTEL82072 ||
857             dkinf.dki_ctype == DKC_INTEL82077);
858 #else
859     return 0;
860 #endif
861 }
862
863 /* retrieve the device object for a given fd, creating it if needed */
864 static struct device *get_device( dev_t dev, int unix_fd )
865 {
866     struct device *device;
867     unsigned int i, hash = dev % DEVICE_HASH_SIZE;
868
869     if (device_hash[hash].next)
870     {
871         LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
872             if (device->dev == dev) return (struct device *)grab_object( device );
873     }
874     else list_init( &device_hash[hash] );
875
876     /* not found, create it */
877
878     if (unix_fd == -1) return NULL;
879     if ((device = alloc_object( &device_ops )))
880     {
881         device->dev = dev;
882         device->removable = is_device_removable( dev, unix_fd );
883         for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
884         list_add_head( &device_hash[hash], &device->entry );
885     }
886     return device;
887 }
888
889 static void device_dump( struct object *obj, int verbose )
890 {
891     struct device *device = (struct device *)obj;
892     fprintf( stderr, "Device dev=" );
893     DUMP_LONG_LONG( device->dev );
894     fprintf( stderr, "\n" );
895 }
896
897 static void device_destroy( struct object *obj )
898 {
899     struct device *device = (struct device *)obj;
900     unsigned int i;
901
902     for (i = 0; i < INODE_HASH_SIZE; i++)
903         assert( list_empty(&device->inode_hash[i]) );
904
905     list_remove( &device->entry );  /* remove it from the hash table */
906 }
907
908
909 /****************************************************************/
910 /* inode functions */
911
912 /* close all pending file descriptors in the closed list */
913 static void inode_close_pending( struct inode *inode, int keep_unlinks )
914 {
915     struct list *ptr = list_head( &inode->closed );
916
917     while (ptr)
918     {
919         struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
920         struct list *next = list_next( &inode->closed, ptr );
921
922         if (fd->unix_fd != -1)
923         {
924             close( fd->unix_fd );
925             fd->unix_fd = -1;
926         }
927         if (!keep_unlinks || !fd->unlink[0])  /* get rid of it unless there's an unlink pending on that file */
928         {
929             list_remove( ptr );
930             free( fd );
931         }
932         ptr = next;
933     }
934 }
935
936 static void inode_dump( struct object *obj, int verbose )
937 {
938     struct inode *inode = (struct inode *)obj;
939     fprintf( stderr, "Inode device=%p ino=", inode->device );
940     DUMP_LONG_LONG( inode->ino );
941     fprintf( stderr, "\n" );
942 }
943
944 static void inode_destroy( struct object *obj )
945 {
946     struct inode *inode = (struct inode *)obj;
947     struct list *ptr;
948
949     assert( list_empty(&inode->open) );
950     assert( list_empty(&inode->locks) );
951
952     list_remove( &inode->entry );
953
954     while ((ptr = list_head( &inode->closed )))
955     {
956         struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
957         list_remove( ptr );
958         if (fd->unix_fd != -1) close( fd->unix_fd );
959         if (fd->unlink[0])
960         {
961             /* make sure it is still the same file */
962             struct stat st;
963             if (!stat( fd->unlink, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
964             {
965                 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
966                 else unlink( fd->unlink );
967             }
968         }
969         free( fd );
970     }
971     release_object( inode->device );
972 }
973
974 /* retrieve the inode object for a given fd, creating it if needed */
975 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
976 {
977     struct device *device;
978     struct inode *inode;
979     unsigned int hash = ino % INODE_HASH_SIZE;
980
981     if (!(device = get_device( dev, unix_fd ))) return NULL;
982
983     LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
984     {
985         if (inode->ino == ino)
986         {
987             release_object( device );
988             return (struct inode *)grab_object( inode );
989         }
990     }
991
992     /* not found, create it */
993     if ((inode = alloc_object( &inode_ops )))
994     {
995         inode->device = device;
996         inode->ino    = ino;
997         list_init( &inode->open );
998         list_init( &inode->locks );
999         list_init( &inode->closed );
1000         list_add_head( &device->inode_hash[hash], &inode->entry );
1001     }
1002     else release_object( device );
1003
1004     return inode;
1005 }
1006
1007 /* add fd to the inode list of file descriptors to close */
1008 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1009 {
1010     if (!list_empty( &inode->locks ))
1011     {
1012         list_add_head( &inode->closed, &fd->entry );
1013     }
1014     else if (fd->unlink[0])  /* close the fd but keep the structure around for unlink */
1015     {
1016         if (fd->unix_fd != -1) close( fd->unix_fd );
1017         fd->unix_fd = -1;
1018         list_add_head( &inode->closed, &fd->entry );
1019     }
1020     else  /* no locks on this inode and no unlink, get rid of the fd */
1021     {
1022         if (fd->unix_fd != -1) close( fd->unix_fd );
1023         free( fd );
1024     }
1025 }
1026
1027
1028 /****************************************************************/
1029 /* file lock functions */
1030
1031 static void file_lock_dump( struct object *obj, int verbose )
1032 {
1033     struct file_lock *lock = (struct file_lock *)obj;
1034     fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1035              lock->shared ? "shared" : "excl", lock->fd, lock->process );
1036     DUMP_LONG_LONG( lock->start );
1037     fprintf( stderr, " end=" );
1038     DUMP_LONG_LONG( lock->end );
1039     fprintf( stderr, "\n" );
1040 }
1041
1042 static int file_lock_signaled( struct object *obj, struct thread *thread )
1043 {
1044     struct file_lock *lock = (struct file_lock *)obj;
1045     /* lock is signaled if it has lost its owner */
1046     return !lock->process;
1047 }
1048
1049 /* set (or remove) a Unix lock if possible for the given range */
1050 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1051 {
1052     struct flock fl;
1053
1054     if (!fd->fs_locks) return 1;  /* no fs locks possible for this fd */
1055     for (;;)
1056     {
1057         if (start == end) return 1;  /* can't set zero-byte lock */
1058         if (start > max_unix_offset) return 1;  /* ignore it */
1059         fl.l_type   = type;
1060         fl.l_whence = SEEK_SET;
1061         fl.l_start  = start;
1062         if (!end || end > max_unix_offset) fl.l_len = 0;
1063         else fl.l_len = end - start;
1064         if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1065
1066         switch(errno)
1067         {
1068         case EACCES:
1069             /* check whether locks work at all on this file system */
1070             if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1071             {
1072                 set_error( STATUS_FILE_LOCK_CONFLICT );
1073                 return 0;
1074             }
1075             /* fall through */
1076         case EIO:
1077         case ENOLCK:
1078             /* no locking on this fs, just ignore it */
1079             fd->fs_locks = 0;
1080             return 1;
1081         case EAGAIN:
1082             set_error( STATUS_FILE_LOCK_CONFLICT );
1083             return 0;
1084         case EBADF:
1085             /* this can happen if we try to set a write lock on a read-only file */
1086             /* we just ignore that error */
1087             if (fl.l_type == F_WRLCK) return 1;
1088             set_error( STATUS_ACCESS_DENIED );
1089             return 0;
1090 #ifdef EOVERFLOW
1091         case EOVERFLOW:
1092 #endif
1093         case EINVAL:
1094             /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1095             /* in that case we shrink the limit and retry */
1096             if (max_unix_offset > INT_MAX)
1097             {
1098                 max_unix_offset = INT_MAX;
1099                 break;  /* retry */
1100             }
1101             /* fall through */
1102         default:
1103             file_set_error();
1104             return 0;
1105         }
1106     }
1107 }
1108
1109 /* check if interval [start;end) overlaps the lock */
1110 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1111 {
1112     if (lock->end && start >= lock->end) return 0;
1113     if (end && lock->start >= end) return 0;
1114     return 1;
1115 }
1116
1117 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1118 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1119 {
1120     struct hole
1121     {
1122         struct hole *next;
1123         struct hole *prev;
1124         file_pos_t   start;
1125         file_pos_t   end;
1126     } *first, *cur, *next, *buffer;
1127
1128     struct list *ptr;
1129     int count = 0;
1130
1131     if (!fd->inode) return;
1132     if (!fd->fs_locks) return;
1133     if (start == end || start > max_unix_offset) return;
1134     if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1135
1136     /* count the number of locks overlapping the specified area */
1137
1138     LIST_FOR_EACH( ptr, &fd->inode->locks )
1139     {
1140         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1141         if (lock->start == lock->end) continue;
1142         if (lock_overlaps( lock, start, end )) count++;
1143     }
1144
1145     if (!count)  /* no locks at all, we can unlock everything */
1146     {
1147         set_unix_lock( fd, start, end, F_UNLCK );
1148         return;
1149     }
1150
1151     /* allocate space for the list of holes */
1152     /* max. number of holes is number of locks + 1 */
1153
1154     if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1155     first = buffer;
1156     first->next  = NULL;
1157     first->prev  = NULL;
1158     first->start = start;
1159     first->end   = end;
1160     next = first + 1;
1161
1162     /* build a sorted list of unlocked holes in the specified area */
1163
1164     LIST_FOR_EACH( ptr, &fd->inode->locks )
1165     {
1166         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1167         if (lock->start == lock->end) continue;
1168         if (!lock_overlaps( lock, start, end )) continue;
1169
1170         /* go through all the holes touched by this lock */
1171         for (cur = first; cur; cur = cur->next)
1172         {
1173             if (cur->end <= lock->start) continue; /* hole is before start of lock */
1174             if (lock->end && cur->start >= lock->end) break;  /* hole is after end of lock */
1175
1176             /* now we know that lock is overlapping hole */
1177
1178             if (cur->start >= lock->start)  /* lock starts before hole, shrink from start */
1179             {
1180                 cur->start = lock->end;
1181                 if (cur->start && cur->start < cur->end) break;  /* done with this lock */
1182                 /* now hole is empty, remove it */
1183                 if (cur->next) cur->next->prev = cur->prev;
1184                 if (cur->prev) cur->prev->next = cur->next;
1185                 else if (!(first = cur->next)) goto done;  /* no more holes at all */
1186             }
1187             else if (!lock->end || cur->end <= lock->end)  /* lock larger than hole, shrink from end */
1188             {
1189                 cur->end = lock->start;
1190                 assert( cur->start < cur->end );
1191             }
1192             else  /* lock is in the middle of hole, split hole in two */
1193             {
1194                 next->prev = cur;
1195                 next->next = cur->next;
1196                 cur->next = next;
1197                 next->start = lock->end;
1198                 next->end = cur->end;
1199                 cur->end = lock->start;
1200                 assert( next->start < next->end );
1201                 assert( cur->end < next->start );
1202                 next++;
1203                 break;  /* done with this lock */
1204             }
1205         }
1206     }
1207
1208     /* clear Unix locks for all the holes */
1209
1210     for (cur = first; cur; cur = cur->next)
1211         set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1212
1213  done:
1214     free( buffer );
1215 }
1216
1217 /* create a new lock on a fd */
1218 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1219 {
1220     struct file_lock *lock;
1221
1222     if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1223     lock->shared  = shared;
1224     lock->start   = start;
1225     lock->end     = end;
1226     lock->fd      = fd;
1227     lock->process = current->process;
1228
1229     /* now try to set a Unix lock */
1230     if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1231     {
1232         release_object( lock );
1233         return NULL;
1234     }
1235     list_add_head( &fd->locks, &lock->fd_entry );
1236     list_add_head( &fd->inode->locks, &lock->inode_entry );
1237     list_add_head( &lock->process->locks, &lock->proc_entry );
1238     return lock;
1239 }
1240
1241 /* remove an existing lock */
1242 static void remove_lock( struct file_lock *lock, int remove_unix )
1243 {
1244     struct inode *inode = lock->fd->inode;
1245
1246     list_remove( &lock->fd_entry );
1247     list_remove( &lock->inode_entry );
1248     list_remove( &lock->proc_entry );
1249     if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1250     if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1251     lock->process = NULL;
1252     wake_up( &lock->obj, 0 );
1253     release_object( lock );
1254 }
1255
1256 /* remove all locks owned by a given process */
1257 void remove_process_locks( struct process *process )
1258 {
1259     struct list *ptr;
1260
1261     while ((ptr = list_head( &process->locks )))
1262     {
1263         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1264         remove_lock( lock, 1 );  /* this removes it from the list */
1265     }
1266 }
1267
1268 /* remove all locks on a given fd */
1269 static void remove_fd_locks( struct fd *fd )
1270 {
1271     file_pos_t start = FILE_POS_T_MAX, end = 0;
1272     struct list *ptr;
1273
1274     while ((ptr = list_head( &fd->locks )))
1275     {
1276         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1277         if (lock->start < start) start = lock->start;
1278         if (!lock->end || lock->end > end) end = lock->end - 1;
1279         remove_lock( lock, 0 );
1280     }
1281     if (start < end) remove_unix_locks( fd, start, end + 1 );
1282 }
1283
1284 /* add a lock on an fd */
1285 /* returns handle to wait on */
1286 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1287 {
1288     struct list *ptr;
1289     file_pos_t end = start + count;
1290
1291     if (!fd->inode)  /* not a regular file */
1292     {
1293         set_error( STATUS_INVALID_DEVICE_REQUEST );
1294         return 0;
1295     }
1296
1297     /* don't allow wrapping locks */
1298     if (end && end < start)
1299     {
1300         set_error( STATUS_INVALID_PARAMETER );
1301         return 0;
1302     }
1303
1304     /* check if another lock on that file overlaps the area */
1305     LIST_FOR_EACH( ptr, &fd->inode->locks )
1306     {
1307         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1308         if (!lock_overlaps( lock, start, end )) continue;
1309         if (lock->shared && shared) continue;
1310         /* found one */
1311         if (!wait)
1312         {
1313             set_error( STATUS_FILE_LOCK_CONFLICT );
1314             return 0;
1315         }
1316         set_error( STATUS_PENDING );
1317         return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1318     }
1319
1320     /* not found, add it */
1321     if (add_lock( fd, shared, start, end )) return 0;
1322     if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1323     {
1324         /* Unix lock conflict -> tell client to wait and retry */
1325         if (wait) set_error( STATUS_PENDING );
1326     }
1327     return 0;
1328 }
1329
1330 /* remove a lock on an fd */
1331 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1332 {
1333     struct list *ptr;
1334     file_pos_t end = start + count;
1335
1336     /* find an existing lock with the exact same parameters */
1337     LIST_FOR_EACH( ptr, &fd->locks )
1338     {
1339         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1340         if ((lock->start == start) && (lock->end == end))
1341         {
1342             remove_lock( lock, 1 );
1343             return;
1344         }
1345     }
1346     set_error( STATUS_FILE_LOCK_CONFLICT );
1347 }
1348
1349
1350 /****************************************************************/
1351 /* file descriptor functions */
1352
1353 static void fd_dump( struct object *obj, int verbose )
1354 {
1355     struct fd *fd = (struct fd *)obj;
1356     fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1357     if (fd->inode) fprintf( stderr, " inode=%p unlink='%s'", fd->inode, fd->closed->unlink );
1358     fprintf( stderr, "\n" );
1359 }
1360
1361 static void fd_destroy( struct object *obj )
1362 {
1363     struct fd *fd = (struct fd *)obj;
1364
1365     free_async_queue( fd->read_q );
1366     free_async_queue( fd->write_q );
1367     free_async_queue( fd->wait_q );
1368
1369     if (fd->completion) release_object( fd->completion );
1370     remove_fd_locks( fd );
1371     list_remove( &fd->inode_entry );
1372     if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1373     if (fd->inode)
1374     {
1375         inode_add_closed_fd( fd->inode, fd->closed );
1376         release_object( fd->inode );
1377     }
1378     else  /* no inode, close it right away */
1379     {
1380         if (fd->unix_fd != -1) close( fd->unix_fd );
1381     }
1382 }
1383
1384 /* set the events that select waits for on this fd */
1385 void set_fd_events( struct fd *fd, int events )
1386 {
1387     int user = fd->poll_index;
1388     assert( poll_users[user] == fd );
1389
1390     set_fd_epoll_events( fd, user, events );
1391
1392     if (events == -1)  /* stop waiting on this fd completely */
1393     {
1394         pollfd[user].fd = -1;
1395         pollfd[user].events = POLLERR;
1396         pollfd[user].revents = 0;
1397     }
1398     else if (pollfd[user].fd != -1 || !pollfd[user].events)
1399     {
1400         pollfd[user].fd = fd->unix_fd;
1401         pollfd[user].events = events;
1402     }
1403 }
1404
1405 /* prepare an fd for unmounting its corresponding device */
1406 static inline void unmount_fd( struct fd *fd )
1407 {
1408     assert( fd->inode );
1409
1410     async_wake_up( fd->read_q, STATUS_VOLUME_DISMOUNTED );
1411     async_wake_up( fd->write_q, STATUS_VOLUME_DISMOUNTED );
1412
1413     if (fd->poll_index != -1) set_fd_events( fd, -1 );
1414
1415     if (fd->unix_fd != -1) close( fd->unix_fd );
1416
1417     fd->unix_fd = -1;
1418     fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1419     fd->closed->unix_fd = -1;
1420     fd->closed->unlink[0] = 0;
1421
1422     /* stop using Unix locks on this fd (existing locks have been removed by close) */
1423     fd->fs_locks = 0;
1424 }
1425
1426 /* allocate an fd object, without setting the unix fd yet */
1427 static struct fd *alloc_fd_object(void)
1428 {
1429     struct fd *fd = alloc_object( &fd_ops );
1430
1431     if (!fd) return NULL;
1432
1433     fd->fd_ops     = NULL;
1434     fd->user       = NULL;
1435     fd->inode      = NULL;
1436     fd->closed     = NULL;
1437     fd->access     = 0;
1438     fd->options    = 0;
1439     fd->sharing    = 0;
1440     fd->unix_fd    = -1;
1441     fd->signaled   = 1;
1442     fd->fs_locks   = 1;
1443     fd->poll_index = -1;
1444     fd->read_q     = NULL;
1445     fd->write_q    = NULL;
1446     fd->wait_q     = NULL;
1447     fd->completion = NULL;
1448     list_init( &fd->inode_entry );
1449     list_init( &fd->locks );
1450
1451     if ((fd->poll_index = add_poll_user( fd )) == -1)
1452     {
1453         release_object( fd );
1454         return NULL;
1455     }
1456     return fd;
1457 }
1458
1459 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1460 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1461 {
1462     struct fd *fd = alloc_object( &fd_ops );
1463
1464     if (!fd) return NULL;
1465
1466     fd->fd_ops     = fd_user_ops;
1467     fd->user       = user;
1468     fd->inode      = NULL;
1469     fd->closed     = NULL;
1470     fd->access     = 0;
1471     fd->options    = options;
1472     fd->sharing    = 0;
1473     fd->unix_fd    = -1;
1474     fd->signaled   = 0;
1475     fd->fs_locks   = 0;
1476     fd->poll_index = -1;
1477     fd->read_q     = NULL;
1478     fd->write_q    = NULL;
1479     fd->wait_q     = NULL;
1480     fd->completion = NULL;
1481     fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1482     list_init( &fd->inode_entry );
1483     list_init( &fd->locks );
1484     return fd;
1485 }
1486
1487 /* set the status to return when the fd has no associated unix fd */
1488 void set_no_fd_status( struct fd *fd, unsigned int status )
1489 {
1490     fd->no_fd_status = status;
1491 }
1492
1493 /* check if the desired access is possible without violating */
1494 /* the sharing mode of other opens of the same file */
1495 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
1496 {
1497     unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1498     unsigned int existing_access = 0;
1499     struct list *ptr;
1500
1501     /* if access mode is 0, sharing mode is ignored */
1502     if (!access) sharing = existing_sharing;
1503     fd->access = access;
1504     fd->sharing = sharing;
1505
1506     LIST_FOR_EACH( ptr, &fd->inode->open )
1507     {
1508         struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1509         if (fd_ptr != fd)
1510         {
1511             existing_sharing &= fd_ptr->sharing;
1512             existing_access  |= fd_ptr->access;
1513         }
1514     }
1515
1516     if ((access & FILE_UNIX_READ_ACCESS) && !(existing_sharing & FILE_SHARE_READ)) return 0;
1517     if ((access & FILE_UNIX_WRITE_ACCESS) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1518     if ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1519     if ((existing_access & FILE_UNIX_READ_ACCESS) && !(sharing & FILE_SHARE_READ)) return 0;
1520     if ((existing_access & FILE_UNIX_WRITE_ACCESS) && !(sharing & FILE_SHARE_WRITE)) return 0;
1521     if ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)) return 0;
1522     return 1;
1523 }
1524
1525 /* sets the user of an fd that previously had no user */
1526 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1527 {
1528     assert( fd->fd_ops == NULL );
1529     fd->fd_ops = user_ops;
1530     fd->user   = user;
1531 }
1532
1533 /* open() wrapper that returns a struct fd with no fd user set */
1534 struct fd *open_fd( const char *name, int flags, mode_t *mode, unsigned int access,
1535                     unsigned int sharing, unsigned int options )
1536 {
1537     struct stat st;
1538     struct closed_fd *closed_fd;
1539     struct fd *fd;
1540     const char *unlink_name = "";
1541     int rw_mode;
1542
1543     if ((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE))
1544     {
1545         set_error( STATUS_INVALID_PARAMETER );
1546         return NULL;
1547     }
1548
1549     if (!(fd = alloc_fd_object())) return NULL;
1550
1551     fd->options = options;
1552     if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1553     if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1554     {
1555         release_object( fd );
1556         return NULL;
1557     }
1558
1559     /* create the directory if needed */
1560     if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1561     {
1562         if (mkdir( name, 0777 ) == -1)
1563         {
1564             if (errno != EEXIST || (flags & O_EXCL))
1565             {
1566                 file_set_error();
1567                 goto error;
1568             }
1569         }
1570         flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1571     }
1572
1573     if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1574     {
1575         if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1576         else rw_mode = O_WRONLY;
1577     }
1578     else rw_mode = O_RDONLY;
1579
1580     if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1581     {
1582         /* if we tried to open a directory for write access, retry read-only */
1583         if (errno != EISDIR ||
1584             !(access & FILE_UNIX_WRITE_ACCESS) ||
1585             (fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode )) == -1)
1586         {
1587             file_set_error();
1588             goto error;
1589         }
1590     }
1591
1592     closed_fd->unix_fd = fd->unix_fd;
1593     closed_fd->unlink[0] = 0;
1594     fstat( fd->unix_fd, &st );
1595     *mode = st.st_mode;
1596
1597     /* only bother with an inode for normal files and directories */
1598     if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1599     {
1600         struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1601
1602         if (!inode)
1603         {
1604             /* we can close the fd because there are no others open on the same file,
1605              * otherwise we wouldn't have failed to allocate a new inode
1606              */
1607             goto error;
1608         }
1609         fd->inode = inode;
1610         fd->closed = closed_fd;
1611         list_add_head( &inode->open, &fd->inode_entry );
1612
1613         /* check directory options */
1614         if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1615         {
1616             release_object( fd );
1617             set_error( STATUS_NOT_A_DIRECTORY );
1618             return NULL;
1619         }
1620         if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1621         {
1622             release_object( fd );
1623             set_error( STATUS_FILE_IS_A_DIRECTORY );
1624             return NULL;
1625         }
1626         if (!check_sharing( fd, access, sharing ))
1627         {
1628             release_object( fd );
1629             set_error( STATUS_SHARING_VIOLATION );
1630             return NULL;
1631         }
1632         strcpy( closed_fd->unlink, unlink_name );
1633         if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1634     }
1635     else  /* special file */
1636     {
1637         if (options & FILE_DIRECTORY_FILE)
1638         {
1639             set_error( STATUS_NOT_A_DIRECTORY );
1640             goto error;
1641         }
1642         if (unlink_name[0])  /* we can't unlink special files */
1643         {
1644             set_error( STATUS_INVALID_PARAMETER );
1645             goto error;
1646         }
1647         free( closed_fd );
1648     }
1649     return fd;
1650
1651 error:
1652     release_object( fd );
1653     free( closed_fd );
1654     return NULL;
1655 }
1656
1657 /* create an fd for an anonymous file */
1658 /* if the function fails the unix fd is closed */
1659 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
1660                                 unsigned int options )
1661 {
1662     struct fd *fd = alloc_fd_object();
1663
1664     if (fd)
1665     {
1666         set_fd_user( fd, fd_user_ops, user );
1667         fd->unix_fd = unix_fd;
1668         fd->options = options;
1669         return fd;
1670     }
1671     close( unix_fd );
1672     return NULL;
1673 }
1674
1675 /* retrieve the object that is using an fd */
1676 void *get_fd_user( struct fd *fd )
1677 {
1678     return fd->user;
1679 }
1680
1681 /* retrieve the opening options for the fd */
1682 unsigned int get_fd_options( struct fd *fd )
1683 {
1684     return fd->options;
1685 }
1686
1687 /* retrieve the unix fd for an object */
1688 int get_unix_fd( struct fd *fd )
1689 {
1690     if (fd->unix_fd == -1) set_error( fd->no_fd_status );
1691     return fd->unix_fd;
1692 }
1693
1694 /* check if two file descriptors point to the same file */
1695 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1696 {
1697     return fd1->inode == fd2->inode;
1698 }
1699
1700 /* check if fd is on a removable device */
1701 int is_fd_removable( struct fd *fd )
1702 {
1703     return (fd->inode && fd->inode->device->removable);
1704 }
1705
1706 /* set or clear the fd signaled state */
1707 void set_fd_signaled( struct fd *fd, int signaled )
1708 {
1709     fd->signaled = signaled;
1710     if (signaled) wake_up( fd->user, 0 );
1711 }
1712
1713 /* set or clear the fd signaled state */
1714 int is_fd_signaled( struct fd *fd )
1715 {
1716     return fd->signaled;
1717 }
1718
1719 /* handler for close_handle that refuses to close fd-associated handles in other processes */
1720 int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
1721 {
1722     return (!current || current->process == process);
1723 }
1724
1725 /* check if events are pending and if yes return which one(s) */
1726 int check_fd_events( struct fd *fd, int events )
1727 {
1728     struct pollfd pfd;
1729
1730     if (fd->unix_fd == -1) return POLLERR;
1731     if (fd->inode) return events;  /* regular files are always signaled */
1732
1733     pfd.fd     = fd->unix_fd;
1734     pfd.events = events;
1735     if (poll( &pfd, 1, 0 ) <= 0) return 0;
1736     return pfd.revents;
1737 }
1738
1739 /* default signaled() routine for objects that poll() on an fd */
1740 int default_fd_signaled( struct object *obj, struct thread *thread )
1741 {
1742     struct fd *fd = get_obj_fd( obj );
1743     int ret = fd->signaled;
1744     release_object( fd );
1745     return ret;
1746 }
1747
1748 /* default map_access() routine for objects that behave like an fd */
1749 unsigned int default_fd_map_access( struct object *obj, unsigned int access )
1750 {
1751     if (access & GENERIC_READ)    access |= FILE_GENERIC_READ;
1752     if (access & GENERIC_WRITE)   access |= FILE_GENERIC_WRITE;
1753     if (access & GENERIC_EXECUTE) access |= FILE_GENERIC_EXECUTE;
1754     if (access & GENERIC_ALL)     access |= FILE_ALL_ACCESS;
1755     return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
1756 }
1757
1758 int default_fd_get_poll_events( struct fd *fd )
1759 {
1760     int events = 0;
1761
1762     if (async_waiting( fd->read_q )) events |= POLLIN;
1763     if (async_waiting( fd->write_q )) events |= POLLOUT;
1764     return events;
1765 }
1766
1767 /* default handler for poll() events */
1768 void default_poll_event( struct fd *fd, int event )
1769 {
1770     if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( fd->read_q, STATUS_ALERTED );
1771     if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( fd->write_q, STATUS_ALERTED );
1772
1773     /* if an error occurred, stop polling this fd to avoid busy-looping */
1774     if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1775     else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1776 }
1777
1778 struct async *fd_queue_async( struct fd *fd, const async_data_t *data, int type )
1779 {
1780     struct async_queue *queue;
1781     struct async *async;
1782
1783     switch (type)
1784     {
1785     case ASYNC_TYPE_READ:
1786         if (!fd->read_q && !(fd->read_q = create_async_queue( fd ))) return NULL;
1787         queue = fd->read_q;
1788         break;
1789     case ASYNC_TYPE_WRITE:
1790         if (!fd->write_q && !(fd->write_q = create_async_queue( fd ))) return NULL;
1791         queue = fd->write_q;
1792         break;
1793     case ASYNC_TYPE_WAIT:
1794         if (!fd->wait_q && !(fd->wait_q = create_async_queue( fd ))) return NULL;
1795         queue = fd->wait_q;
1796         break;
1797     default:
1798         queue = NULL;
1799         assert(0);
1800     }
1801
1802     if ((async = create_async( current, queue, data )) && type != ASYNC_TYPE_WAIT)
1803     {
1804         if (!fd->inode)
1805             set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1806         else  /* regular files are always ready for read and write */
1807             async_wake_up( queue, STATUS_ALERTED );
1808     }
1809     return async;
1810 }
1811
1812 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
1813 {
1814     switch (type)
1815     {
1816     case ASYNC_TYPE_READ:
1817         async_wake_up( fd->read_q, status );
1818         break;
1819     case ASYNC_TYPE_WRITE:
1820         async_wake_up( fd->write_q, status );
1821         break;
1822     case ASYNC_TYPE_WAIT:
1823         async_wake_up( fd->wait_q, status );
1824         break;
1825     default:
1826         assert(0);
1827     }
1828 }
1829
1830 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
1831 {
1832     fd->fd_ops->reselect_async( fd, queue );
1833 }
1834
1835 void default_fd_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
1836 {
1837     struct async *async;
1838
1839     if ((async = fd_queue_async( fd, data, type )))
1840     {
1841         release_object( async );
1842         set_error( STATUS_PENDING );
1843     }
1844 }
1845
1846 /* default reselect_async() fd routine */
1847 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
1848 {
1849     if (queue != fd->wait_q)
1850     {
1851         int poll_events = fd->fd_ops->get_poll_events( fd );
1852         int events = check_fd_events( fd, poll_events );
1853         if (events) fd->fd_ops->poll_event( fd, events );
1854         else set_fd_events( fd, poll_events );
1855     }
1856 }
1857
1858 /* default cancel_async() fd routine */
1859 void default_fd_cancel_async( struct fd *fd )
1860 {
1861     async_wake_up( fd->read_q, STATUS_CANCELLED );
1862     async_wake_up( fd->write_q, STATUS_CANCELLED );
1863     async_wake_up( fd->wait_q, STATUS_CANCELLED );
1864 }
1865
1866 /* default flush() routine */
1867 void no_flush( struct fd *fd, struct event **event )
1868 {
1869     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1870 }
1871
1872 static inline int is_valid_mounted_device( struct stat *st )
1873 {
1874 #if defined(linux) || defined(__sun__)
1875     return S_ISBLK( st->st_mode );
1876 #else
1877     /* disks are char devices on *BSD */
1878     return S_ISCHR( st->st_mode );
1879 #endif
1880 }
1881
1882 /* close all Unix file descriptors on a device to allow unmounting it */
1883 static void unmount_device( struct fd *device_fd )
1884 {
1885     unsigned int i;
1886     struct stat st;
1887     struct device *device;
1888     struct inode *inode;
1889     struct fd *fd;
1890     int unix_fd = get_unix_fd( device_fd );
1891
1892     if (unix_fd == -1) return;
1893
1894     if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
1895     {
1896         set_error( STATUS_INVALID_PARAMETER );
1897         return;
1898     }
1899
1900     if (!(device = get_device( st.st_rdev, -1 ))) return;
1901
1902     for (i = 0; i < INODE_HASH_SIZE; i++)
1903     {
1904         LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
1905         {
1906             LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
1907             {
1908                 unmount_fd( fd );
1909             }
1910             inode_close_pending( inode, 0 );
1911         }
1912     }
1913     /* remove it from the hash table */
1914     list_remove( &device->entry );
1915     list_init( &device->entry );
1916     release_object( device );
1917 }
1918
1919 /* default ioctl() routine */
1920 obj_handle_t default_fd_ioctl( struct fd *fd, ioctl_code_t code, const async_data_t *async,
1921                                int blocking, const void *data, data_size_t size )
1922 {
1923     switch(code)
1924     {
1925     case FSCTL_DISMOUNT_VOLUME:
1926         unmount_device( fd );
1927         return 0;
1928     default:
1929         set_error( STATUS_NOT_SUPPORTED );
1930         return 0;
1931     }
1932 }
1933
1934 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1935 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1936                                      unsigned int access )
1937 {
1938     struct fd *fd = NULL;
1939     struct object *obj;
1940
1941     if ((obj = get_handle_obj( process, handle, access, NULL )))
1942     {
1943         fd = get_obj_fd( obj );
1944         release_object( obj );
1945     }
1946     return fd;
1947 }
1948
1949 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
1950 {
1951     *p_key = fd->comp_key;
1952     return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
1953 }
1954
1955 void fd_copy_completion( struct fd *src, struct fd *dst )
1956 {
1957     assert( !dst->completion );
1958     dst->completion = fd_get_completion( src, &dst->comp_key );
1959 }
1960
1961 /* flush a file buffers */
1962 DECL_HANDLER(flush_file)
1963 {
1964     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1965     struct event * event = NULL;
1966
1967     if (fd)
1968     {
1969         fd->fd_ops->flush( fd, &event );
1970         if ( event )
1971         {
1972             reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1973         }
1974         release_object( fd );
1975     }
1976 }
1977
1978 /* open a file object */
1979 DECL_HANDLER(open_file_object)
1980 {
1981     struct unicode_str name;
1982     struct directory *root = NULL;
1983     struct object *obj, *result;
1984
1985     get_req_unicode_str( &name );
1986     if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
1987         return;
1988
1989     if ((obj = open_object_dir( root, &name, req->attributes, NULL )))
1990     {
1991         if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
1992         {
1993             reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
1994             release_object( result );
1995         }
1996         release_object( obj );
1997     }
1998
1999     if (root) release_object( root );
2000 }
2001
2002 /* get a Unix fd to access a file */
2003 DECL_HANDLER(get_handle_fd)
2004 {
2005     struct fd *fd;
2006
2007     if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2008     {
2009         int unix_fd = get_unix_fd( fd );
2010         if (unix_fd != -1)
2011         {
2012             reply->type = fd->fd_ops->get_fd_type( fd );
2013             reply->removable = is_fd_removable(fd);
2014             reply->options = fd->options;
2015             reply->access = get_handle_access( current->process, req->handle );
2016             send_client_fd( current->process, unix_fd, req->handle );
2017         }
2018         release_object( fd );
2019     }
2020 }
2021
2022 /* perform an ioctl on a file */
2023 DECL_HANDLER(ioctl)
2024 {
2025     unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2026     struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2027
2028     if (fd)
2029     {
2030         reply->wait = fd->fd_ops->ioctl( fd, req->code, &req->async, req->blocking,
2031                                          get_req_data(), get_req_data_size() );
2032         reply->options = fd->options;
2033         release_object( fd );
2034     }
2035 }
2036
2037 /* create / reschedule an async I/O */
2038 DECL_HANDLER(register_async)
2039 {
2040     unsigned int access;
2041     struct fd *fd;
2042
2043     switch(req->type)
2044     {
2045     case ASYNC_TYPE_READ:
2046         access = FILE_READ_DATA;
2047         break;
2048     case ASYNC_TYPE_WRITE:
2049         access = FILE_WRITE_DATA;
2050         break;
2051     default:
2052         set_error( STATUS_INVALID_PARAMETER );
2053         return;
2054     }
2055
2056     if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2057     {
2058         if (get_unix_fd( fd ) != -1) fd->fd_ops->queue_async( fd, &req->async, req->type, req->count );
2059         release_object( fd );
2060     }
2061 }
2062
2063 /* cancels all async I/O */
2064 DECL_HANDLER(cancel_async)
2065 {
2066     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2067
2068     if (fd)
2069     {
2070         if (get_unix_fd( fd ) != -1) fd->fd_ops->cancel_async( fd );
2071         release_object( fd );
2072     }
2073 }
2074
2075 /* attach completion object to a fd */
2076 DECL_HANDLER(set_completion_info)
2077 {
2078     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2079
2080     if (fd)
2081     {
2082         if (!(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) && !fd->completion)
2083         {
2084             fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2085             fd->comp_key = req->ckey;
2086         }
2087         else set_error( STATUS_INVALID_PARAMETER );
2088         release_object( fd );
2089     }
2090 }
2091
2092 /* push new completion msg into a completion queue attached to the fd */
2093 DECL_HANDLER(add_fd_completion)
2094 {
2095     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2096     if (fd)
2097     {
2098         if (fd->completion)
2099             add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2100         release_object( fd );
2101     }
2102 }