Added a close_handle method to the object operations, and use it to
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21
22 #include "config.h"
23
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <signal.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #ifdef HAVE_POLL_H
34 #include <poll.h>
35 #endif
36 #ifdef HAVE_SYS_POLL_H
37 #include <sys/poll.h>
38 #endif
39 #ifdef HAVE_STDINT_H
40 #include <stdint.h>
41 #endif
42 #include <sys/stat.h>
43 #include <sys/time.h>
44 #include <sys/types.h>
45 #include <unistd.h>
46
47 #include "object.h"
48 #include "file.h"
49 #include "handle.h"
50 #include "process.h"
51 #include "request.h"
52
53 #include "winbase.h"
54 #include "winreg.h"
55 #include "winternl.h"
56
57 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
58 # include <sys/epoll.h>
59 # define USE_EPOLL
60 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
61 # define USE_EPOLL
62 # define EPOLLIN POLLIN
63 # define EPOLLOUT POLLOUT
64 # define EPOLLERR POLLERR
65 # define EPOLLHUP POLLHUP
66 # define EPOLL_CTL_ADD 1
67 # define EPOLL_CTL_DEL 2
68 # define EPOLL_CTL_MOD 3
69
70 typedef union epoll_data
71 {
72   void *ptr;
73   int fd;
74   uint32_t u32;
75   uint64_t u64;
76 } epoll_data_t;
77
78 struct epoll_event
79 {
80   uint32_t events;
81   epoll_data_t data;
82 };
83
84 #define SYSCALL_RET(ret) do { \
85         if (ret < 0) { errno = -ret; ret = -1; } \
86         return ret; \
87     } while(0)
88
89 static inline int epoll_create( int size )
90 {
91     int ret;
92     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
93              : "=a" (ret) : "0" (254 /*NR_epoll_create*/), "r" (size) );
94     SYSCALL_RET(ret);
95 }
96
97 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
98 {
99     int ret;
100     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
101              : "=a" (ret)
102              : "0" (255 /*NR_epoll_ctl*/), "r" (epfd), "c" (op), "d" (fd), "S" (event), "m" (*event) );
103     SYSCALL_RET(ret);
104 }
105
106 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
107 {
108     int ret;
109     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
110              : "=a" (ret)
111              : "0" (256 /*NR_epoll_wait*/), "r" (epfd), "c" (events), "d" (maxevents), "S" (timeout)
112              : "memory" );
113     SYSCALL_RET(ret);
114 }
115 #undef SYSCALL_RET
116
117 #endif /* linux && __i386__ && HAVE_STDINT_H */
118
119
120 /* Because of the stupid Posix locking semantics, we need to keep
121  * track of all file descriptors referencing a given file, and not
122  * close a single one until all the locks are gone (sigh).
123  */
124
125 /* file descriptor object */
126
127 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
128 struct closed_fd
129 {
130     struct list entry;       /* entry in inode closed list */
131     int         fd;          /* the unix file descriptor */
132     char        unlink[1];   /* name to unlink on close (if any) */
133 };
134
135 struct fd
136 {
137     struct object        obj;         /* object header */
138     const struct fd_ops *fd_ops;      /* file descriptor operations */
139     struct inode        *inode;       /* inode that this fd belongs to */
140     struct list          inode_entry; /* entry in inode fd list */
141     struct closed_fd    *closed;      /* structure to store the unix fd at destroy time */
142     struct object       *user;        /* object using this file descriptor */
143     struct list          locks;       /* list of locks on this fd */
144     unsigned int         access;      /* file access (GENERIC_READ/WRITE) */
145     unsigned int         sharing;     /* file sharing mode */
146     int                  unix_fd;     /* unix file descriptor */
147     int                  fs_locks;    /* can we use filesystem locks for this fd? */
148     int                  poll_index;  /* index of fd in poll array */
149     struct list          read_q;      /* async readers of this fd */
150     struct list          write_q;     /* async writers of this fd */
151 };
152
153 static void fd_dump( struct object *obj, int verbose );
154 static void fd_destroy( struct object *obj );
155
156 static const struct object_ops fd_ops =
157 {
158     sizeof(struct fd),        /* size */
159     fd_dump,                  /* dump */
160     no_add_queue,             /* add_queue */
161     NULL,                     /* remove_queue */
162     NULL,                     /* signaled */
163     NULL,                     /* satisfied */
164     no_signal,                /* signal */
165     no_get_fd,                /* get_fd */
166     no_close_handle,          /* close_handle */
167     fd_destroy                /* destroy */
168 };
169
170 /* inode object */
171
172 struct inode
173 {
174     struct object       obj;        /* object header */
175     struct list         entry;      /* inode hash list entry */
176     unsigned int        hash;       /* hashing code */
177     dev_t               dev;        /* device number */
178     ino_t               ino;        /* inode number */
179     struct list         open;       /* list of open file descriptors */
180     struct list         locks;      /* list of file locks */
181     struct list         closed;     /* list of file descriptors to close at destroy time */
182 };
183
184 static void inode_dump( struct object *obj, int verbose );
185 static void inode_destroy( struct object *obj );
186
187 static const struct object_ops inode_ops =
188 {
189     sizeof(struct inode),     /* size */
190     inode_dump,               /* dump */
191     no_add_queue,             /* add_queue */
192     NULL,                     /* remove_queue */
193     NULL,                     /* signaled */
194     NULL,                     /* satisfied */
195     no_signal,                /* signal */
196     no_get_fd,                /* get_fd */
197     no_close_handle,          /* close_handle */
198     inode_destroy             /* destroy */
199 };
200
201 /* file lock object */
202
203 struct file_lock
204 {
205     struct object       obj;         /* object header */
206     struct fd          *fd;          /* fd owning this lock */
207     struct list         fd_entry;    /* entry in list of locks on a given fd */
208     struct list         inode_entry; /* entry in inode list of locks */
209     int                 shared;      /* shared lock? */
210     file_pos_t          start;       /* locked region is interval [start;end) */
211     file_pos_t          end;
212     struct process     *process;     /* process owning this lock */
213     struct list         proc_entry;  /* entry in list of locks owned by the process */
214 };
215
216 static void file_lock_dump( struct object *obj, int verbose );
217 static int file_lock_signaled( struct object *obj, struct thread *thread );
218
219 static const struct object_ops file_lock_ops =
220 {
221     sizeof(struct file_lock),   /* size */
222     file_lock_dump,             /* dump */
223     add_queue,                  /* add_queue */
224     remove_queue,               /* remove_queue */
225     file_lock_signaled,         /* signaled */
226     no_satisfied,               /* satisfied */
227     no_signal,                  /* signal */
228     no_get_fd,                  /* get_fd */
229     no_close_handle,            /* close_handle */
230     no_destroy                  /* destroy */
231 };
232
233
234 #define OFF_T_MAX       (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
235 #define FILE_POS_T_MAX  (~(file_pos_t)0)
236
237 static file_pos_t max_unix_offset = OFF_T_MAX;
238
239 #define DUMP_LONG_LONG(val) do { \
240     if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
241         fprintf( stderr, "%lx%08lx", (unsigned long)((val) >> 32), (unsigned long)(val) ); \
242     else \
243         fprintf( stderr, "%lx", (unsigned long)(val) ); \
244   } while (0)
245
246
247
248 /****************************************************************/
249 /* timeouts support */
250
251 struct timeout_user
252 {
253     struct list           entry;      /* entry in sorted timeout list */
254     struct timeval        when;       /* timeout expiry (absolute time) */
255     timeout_callback      callback;   /* callback function */
256     void                 *private;    /* callback private data */
257 };
258
259 static struct list timeout_list = LIST_INIT(timeout_list);   /* sorted timeouts list */
260
261 /* add a timeout user */
262 struct timeout_user *add_timeout_user( const struct timeval *when, timeout_callback func,
263                                        void *private )
264 {
265     struct timeout_user *user;
266     struct list *ptr;
267
268     if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
269     user->when     = *when;
270     user->callback = func;
271     user->private  = private;
272
273     /* Now insert it in the linked list */
274
275     LIST_FOR_EACH( ptr, &timeout_list )
276     {
277         struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
278         if (!time_before( &timeout->when, when )) break;
279     }
280     list_add_before( ptr, &user->entry );
281     return user;
282 }
283
284 /* remove a timeout user */
285 void remove_timeout_user( struct timeout_user *user )
286 {
287     list_remove( &user->entry );
288     free( user );
289 }
290
291 /* add a timeout in milliseconds to an absolute time */
292 void add_timeout( struct timeval *when, int timeout )
293 {
294     if (timeout)
295     {
296         long sec = timeout / 1000;
297         if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
298         {
299             when->tv_usec -= 1000000;
300             when->tv_sec++;
301         }
302         when->tv_sec += sec;
303     }
304 }
305
306
307 /****************************************************************/
308 /* poll support */
309
310 static struct fd **poll_users;              /* users array */
311 static struct pollfd *pollfd;               /* poll fd array */
312 static int nb_users;                        /* count of array entries actually in use */
313 static int active_users;                    /* current number of active users */
314 static int allocated_users;                 /* count of allocated entries in the array */
315 static struct fd **freelist;                /* list of free entries in the array */
316
317 #ifdef USE_EPOLL
318
319 static int epoll_fd;
320 static struct epoll_event *epoll_events;
321
322 /* set the events that epoll waits for on this fd; helper for set_fd_events */
323 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
324 {
325     struct epoll_event ev;
326     int ctl;
327
328     if (epoll_fd == -1) return;
329
330     if (events == -1)  /* stop waiting on this fd completely */
331     {
332         if (pollfd[user].fd == -1) return;  /* already removed */
333         ctl = EPOLL_CTL_DEL;
334     }
335     else if (pollfd[user].fd == -1)
336     {
337         if (pollfd[user].events) return;  /* stopped waiting on it, don't restart */
338         ctl = EPOLL_CTL_ADD;
339     }
340     else
341     {
342         if (pollfd[user].events == events) return;  /* nothing to do */
343         ctl = EPOLL_CTL_MOD;
344     }
345
346     ev.events = events;
347     ev.data.u32 = user;
348
349     if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
350     {
351         if (errno == ENOMEM)  /* not enough memory, give up on epoll */
352         {
353             close( epoll_fd );
354             epoll_fd = -1;
355         }
356         else perror( "epoll_ctl" );  /* should not happen */
357     }
358 }
359
360 #else /* USE_EPOLL */
361
362 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
363 {
364 }
365
366 #endif /* USE_EPOLL */
367
368
369 /* add a user in the poll array and return its index, or -1 on failure */
370 static int add_poll_user( struct fd *fd )
371 {
372     int ret;
373     if (freelist)
374     {
375         ret = freelist - poll_users;
376         freelist = (struct fd **)poll_users[ret];
377     }
378     else
379     {
380         if (nb_users == allocated_users)
381         {
382             struct fd **newusers;
383             struct pollfd *newpoll;
384             int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
385             if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
386             if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
387             {
388                 if (allocated_users)
389                     poll_users = newusers;
390                 else
391                     free( newusers );
392                 return -1;
393             }
394             poll_users = newusers;
395             pollfd = newpoll;
396 #ifdef USE_EPOLL
397             if (!allocated_users) epoll_fd = epoll_create( new_count );
398             if (epoll_fd != -1)
399             {
400                 struct epoll_event *new_events;
401                 if (!(new_events = realloc( epoll_events, new_count * sizeof(*epoll_events) )))
402                     return -1;
403                 epoll_events = new_events;
404             }
405 #endif
406             allocated_users = new_count;
407         }
408         ret = nb_users++;
409     }
410     pollfd[ret].fd = -1;
411     pollfd[ret].events = 0;
412     pollfd[ret].revents = 0;
413     poll_users[ret] = fd;
414     active_users++;
415     return ret;
416 }
417
418 /* remove a user from the poll list */
419 static void remove_poll_user( struct fd *fd, int user )
420 {
421     assert( user >= 0 );
422     assert( poll_users[user] == fd );
423
424 #ifdef USE_EPOLL
425     if (epoll_fd != -1 && pollfd[user].fd != -1)
426     {
427         struct epoll_event dummy;
428         epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
429     }
430 #endif
431     pollfd[user].fd = -1;
432     pollfd[user].events = 0;
433     pollfd[user].revents = 0;
434     poll_users[user] = (struct fd *)freelist;
435     freelist = &poll_users[user];
436     active_users--;
437 }
438
439 /* process pending timeouts and return the time until the next timeout, in milliseconds */
440 static int get_next_timeout(void)
441 {
442     if (!list_empty( &timeout_list ))
443     {
444         struct list expired_list, *ptr;
445         struct timeval now;
446
447         gettimeofday( &now, NULL );
448
449         /* first remove all expired timers from the list */
450
451         list_init( &expired_list );
452         while ((ptr = list_head( &timeout_list )) != NULL)
453         {
454             struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
455
456             if (!time_before( &now, &timeout->when ))
457             {
458                 list_remove( &timeout->entry );
459                 list_add_tail( &expired_list, &timeout->entry );
460             }
461             else break;
462         }
463
464         /* now call the callback for all the removed timers */
465
466         while ((ptr = list_head( &expired_list )) != NULL)
467         {
468             struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
469             list_remove( &timeout->entry );
470             timeout->callback( timeout->private );
471             free( timeout );
472         }
473
474         if ((ptr = list_head( &timeout_list )) != NULL)
475         {
476             struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
477             int diff = (timeout->when.tv_sec - now.tv_sec) * 1000
478                      + (timeout->when.tv_usec - now.tv_usec) / 1000;
479             if (diff < 0) diff = 0;
480             return diff;
481         }
482     }
483     return -1;  /* no pending timeouts */
484 }
485
486 /* server main poll() loop */
487 void main_loop(void)
488 {
489     int i, ret, timeout;
490
491 #ifdef USE_EPOLL
492     assert( POLLIN == EPOLLIN );
493     assert( POLLOUT == EPOLLOUT );
494     assert( POLLERR == EPOLLERR );
495     assert( POLLHUP == EPOLLHUP );
496
497     if (epoll_fd != -1)
498     {
499         while (active_users)
500         {
501             timeout = get_next_timeout();
502
503             if (!active_users) break;  /* last user removed by a timeout */
504             if (epoll_fd == -1) break;  /* an error occurred with epoll */
505
506             ret = epoll_wait( epoll_fd, epoll_events, allocated_users, timeout );
507
508             /* put the events into the pollfd array first, like poll does */
509             for (i = 0; i < ret; i++)
510             {
511                 int user = epoll_events[i].data.u32;
512                 pollfd[user].revents = epoll_events[i].events;
513             }
514
515             /* read events from the pollfd array, as set_fd_events may modify them */
516             for (i = 0; i < ret; i++)
517             {
518                 int user = epoll_events[i].data.u32;
519                 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
520             }
521         }
522     }
523     /* fall through to normal poll loop */
524 #endif  /* USE_EPOLL */
525
526     while (active_users)
527     {
528         timeout = get_next_timeout();
529
530         if (!active_users) break;  /* last user removed by a timeout */
531
532         ret = poll( pollfd, nb_users, timeout );
533         if (ret > 0)
534         {
535             for (i = 0; i < nb_users; i++)
536             {
537                 if (pollfd[i].revents)
538                 {
539                     fd_poll_event( poll_users[i], pollfd[i].revents );
540                     if (!--ret) break;
541                 }
542             }
543         }
544     }
545 }
546
547
548 /****************************************************************/
549 /* inode functions */
550
551 #define HASH_SIZE 37
552
553 static struct list inode_hash[HASH_SIZE];
554
555 /* close all pending file descriptors in the closed list */
556 static void inode_close_pending( struct inode *inode )
557 {
558     struct list *ptr = list_head( &inode->closed );
559
560     while (ptr)
561     {
562         struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
563         struct list *next = list_next( &inode->closed, ptr );
564
565         if (fd->fd != -1)
566         {
567             close( fd->fd );
568             fd->fd = -1;
569         }
570         if (!fd->unlink)  /* get rid of it unless there's an unlink pending on that file */
571         {
572             list_remove( ptr );
573             free( fd );
574         }
575         ptr = next;
576     }
577 }
578
579
580 static void inode_dump( struct object *obj, int verbose )
581 {
582     struct inode *inode = (struct inode *)obj;
583     fprintf( stderr, "Inode dev=" );
584     DUMP_LONG_LONG( inode->dev );
585     fprintf( stderr, " ino=" );
586     DUMP_LONG_LONG( inode->ino );
587     fprintf( stderr, "\n" );
588 }
589
590 static void inode_destroy( struct object *obj )
591 {
592     struct inode *inode = (struct inode *)obj;
593     struct list *ptr;
594
595     assert( list_empty(&inode->open) );
596     assert( list_empty(&inode->locks) );
597
598     list_remove( &inode->entry );
599
600     while ((ptr = list_head( &inode->closed )))
601     {
602         struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
603         list_remove( ptr );
604         if (fd->fd != -1) close( fd->fd );
605         if (fd->unlink[0])
606         {
607             /* make sure it is still the same file */
608             struct stat st;
609             if (!stat( fd->unlink, &st ) && st.st_dev == inode->dev && st.st_ino == inode->ino)
610             {
611                 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
612                 else unlink( fd->unlink );
613             }
614         }
615         free( fd );
616     }
617 }
618
619 /* retrieve the inode object for a given fd, creating it if needed */
620 static struct inode *get_inode( dev_t dev, ino_t ino )
621 {
622     struct list *ptr;
623     struct inode *inode;
624     unsigned int hash = (dev ^ ino) % HASH_SIZE;
625
626     if (inode_hash[hash].next)
627     {
628         LIST_FOR_EACH( ptr, &inode_hash[hash] )
629         {
630             inode = LIST_ENTRY( ptr, struct inode, entry );
631             if (inode->dev == dev && inode->ino == ino)
632                 return (struct inode *)grab_object( inode );
633         }
634     }
635     else list_init( &inode_hash[hash] );
636
637     /* not found, create it */
638     if ((inode = alloc_object( &inode_ops )))
639     {
640         inode->hash   = hash;
641         inode->dev    = dev;
642         inode->ino    = ino;
643         list_init( &inode->open );
644         list_init( &inode->locks );
645         list_init( &inode->closed );
646         list_add_head( &inode_hash[hash], &inode->entry );
647     }
648     return inode;
649 }
650
651 /* add fd to the indoe list of file descriptors to close */
652 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
653 {
654     if (!list_empty( &inode->locks ))
655     {
656         list_add_head( &inode->closed, &fd->entry );
657     }
658     else if (fd->unlink[0])  /* close the fd but keep the structure around for unlink */
659     {
660         close( fd->fd );
661         fd->fd = -1;
662         list_add_head( &inode->closed, &fd->entry );
663     }
664     else  /* no locks on this inode and no unlink, get rid of the fd */
665     {
666         close( fd->fd );
667         free( fd );
668     }
669 }
670
671
672 /****************************************************************/
673 /* file lock functions */
674
675 static void file_lock_dump( struct object *obj, int verbose )
676 {
677     struct file_lock *lock = (struct file_lock *)obj;
678     fprintf( stderr, "Lock %s fd=%p proc=%p start=",
679              lock->shared ? "shared" : "excl", lock->fd, lock->process );
680     DUMP_LONG_LONG( lock->start );
681     fprintf( stderr, " end=" );
682     DUMP_LONG_LONG( lock->end );
683     fprintf( stderr, "\n" );
684 }
685
686 static int file_lock_signaled( struct object *obj, struct thread *thread )
687 {
688     struct file_lock *lock = (struct file_lock *)obj;
689     /* lock is signaled if it has lost its owner */
690     return !lock->process;
691 }
692
693 /* set (or remove) a Unix lock if possible for the given range */
694 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
695 {
696     struct flock fl;
697
698     if (!fd->fs_locks) return 1;  /* no fs locks possible for this fd */
699     for (;;)
700     {
701         if (start == end) return 1;  /* can't set zero-byte lock */
702         if (start > max_unix_offset) return 1;  /* ignore it */
703         fl.l_type   = type;
704         fl.l_whence = SEEK_SET;
705         fl.l_start  = start;
706         if (!end || end > max_unix_offset) fl.l_len = 0;
707         else fl.l_len = end - start;
708         if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
709
710         switch(errno)
711         {
712         case EACCES:
713             /* check whether locks work at all on this file system */
714             if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
715             {
716                 set_error( STATUS_FILE_LOCK_CONFLICT );
717                 return 0;
718             }
719             /* fall through */
720         case EIO:
721         case ENOLCK:
722             /* no locking on this fs, just ignore it */
723             fd->fs_locks = 0;
724             return 1;
725         case EAGAIN:
726             set_error( STATUS_FILE_LOCK_CONFLICT );
727             return 0;
728         case EBADF:
729             /* this can happen if we try to set a write lock on a read-only file */
730             /* we just ignore that error */
731             if (fl.l_type == F_WRLCK) return 1;
732             set_error( STATUS_ACCESS_DENIED );
733             return 0;
734 #ifdef EOVERFLOW
735         case EOVERFLOW:
736 #endif
737         case EINVAL:
738             /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
739             /* in that case we shrink the limit and retry */
740             if (max_unix_offset > INT_MAX)
741             {
742                 max_unix_offset = INT_MAX;
743                 break;  /* retry */
744             }
745             /* fall through */
746         default:
747             file_set_error();
748             return 0;
749         }
750     }
751 }
752
753 /* check if interval [start;end) overlaps the lock */
754 inline static int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
755 {
756     if (lock->end && start >= lock->end) return 0;
757     if (end && lock->start >= end) return 0;
758     return 1;
759 }
760
761 /* remove Unix locks for all bytes in the specified area that are no longer locked */
762 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
763 {
764     struct hole
765     {
766         struct hole *next;
767         struct hole *prev;
768         file_pos_t   start;
769         file_pos_t   end;
770     } *first, *cur, *next, *buffer;
771
772     struct list *ptr;
773     int count = 0;
774
775     if (!fd->inode) return;
776     if (!fd->fs_locks) return;
777     if (start == end || start > max_unix_offset) return;
778     if (!end || end > max_unix_offset) end = max_unix_offset + 1;
779
780     /* count the number of locks overlapping the specified area */
781
782     LIST_FOR_EACH( ptr, &fd->inode->locks )
783     {
784         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
785         if (lock->start == lock->end) continue;
786         if (lock_overlaps( lock, start, end )) count++;
787     }
788
789     if (!count)  /* no locks at all, we can unlock everything */
790     {
791         set_unix_lock( fd, start, end, F_UNLCK );
792         return;
793     }
794
795     /* allocate space for the list of holes */
796     /* max. number of holes is number of locks + 1 */
797
798     if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
799     first = buffer;
800     first->next  = NULL;
801     first->prev  = NULL;
802     first->start = start;
803     first->end   = end;
804     next = first + 1;
805
806     /* build a sorted list of unlocked holes in the specified area */
807
808     LIST_FOR_EACH( ptr, &fd->inode->locks )
809     {
810         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
811         if (lock->start == lock->end) continue;
812         if (!lock_overlaps( lock, start, end )) continue;
813
814         /* go through all the holes touched by this lock */
815         for (cur = first; cur; cur = cur->next)
816         {
817             if (cur->end <= lock->start) continue; /* hole is before start of lock */
818             if (lock->end && cur->start >= lock->end) break;  /* hole is after end of lock */
819
820             /* now we know that lock is overlapping hole */
821
822             if (cur->start >= lock->start)  /* lock starts before hole, shrink from start */
823             {
824                 cur->start = lock->end;
825                 if (cur->start && cur->start < cur->end) break;  /* done with this lock */
826                 /* now hole is empty, remove it */
827                 if (cur->next) cur->next->prev = cur->prev;
828                 if (cur->prev) cur->prev->next = cur->next;
829                 else if (!(first = cur->next)) goto done;  /* no more holes at all */
830             }
831             else if (!lock->end || cur->end <= lock->end)  /* lock larger than hole, shrink from end */
832             {
833                 cur->end = lock->start;
834                 assert( cur->start < cur->end );
835             }
836             else  /* lock is in the middle of hole, split hole in two */
837             {
838                 next->prev = cur;
839                 next->next = cur->next;
840                 cur->next = next;
841                 next->start = lock->end;
842                 next->end = cur->end;
843                 cur->end = lock->start;
844                 assert( next->start < next->end );
845                 assert( cur->end < next->start );
846                 next++;
847                 break;  /* done with this lock */
848             }
849         }
850     }
851
852     /* clear Unix locks for all the holes */
853
854     for (cur = first; cur; cur = cur->next)
855         set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
856
857  done:
858     free( buffer );
859 }
860
861 /* create a new lock on a fd */
862 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
863 {
864     struct file_lock *lock;
865
866     if (!fd->inode)  /* not a regular file */
867     {
868         set_error( STATUS_INVALID_HANDLE );
869         return NULL;
870     }
871
872     if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
873     lock->shared  = shared;
874     lock->start   = start;
875     lock->end     = end;
876     lock->fd      = fd;
877     lock->process = current->process;
878
879     /* now try to set a Unix lock */
880     if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
881     {
882         release_object( lock );
883         return NULL;
884     }
885     list_add_head( &fd->locks, &lock->fd_entry );
886     list_add_head( &fd->inode->locks, &lock->inode_entry );
887     list_add_head( &lock->process->locks, &lock->proc_entry );
888     return lock;
889 }
890
891 /* remove an existing lock */
892 static void remove_lock( struct file_lock *lock, int remove_unix )
893 {
894     struct inode *inode = lock->fd->inode;
895
896     list_remove( &lock->fd_entry );
897     list_remove( &lock->inode_entry );
898     list_remove( &lock->proc_entry );
899     if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
900     if (list_empty( &inode->locks )) inode_close_pending( inode );
901     lock->process = NULL;
902     wake_up( &lock->obj, 0 );
903     release_object( lock );
904 }
905
906 /* remove all locks owned by a given process */
907 void remove_process_locks( struct process *process )
908 {
909     struct list *ptr;
910
911     while ((ptr = list_head( &process->locks )))
912     {
913         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
914         remove_lock( lock, 1 );  /* this removes it from the list */
915     }
916 }
917
918 /* remove all locks on a given fd */
919 static void remove_fd_locks( struct fd *fd )
920 {
921     file_pos_t start = FILE_POS_T_MAX, end = 0;
922     struct list *ptr;
923
924     while ((ptr = list_head( &fd->locks )))
925     {
926         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
927         if (lock->start < start) start = lock->start;
928         if (!lock->end || lock->end > end) end = lock->end - 1;
929         remove_lock( lock, 0 );
930     }
931     if (start < end) remove_unix_locks( fd, start, end + 1 );
932 }
933
934 /* add a lock on an fd */
935 /* returns handle to wait on */
936 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
937 {
938     struct list *ptr;
939     file_pos_t end = start + count;
940
941     /* don't allow wrapping locks */
942     if (end && end < start)
943     {
944         set_error( STATUS_INVALID_PARAMETER );
945         return 0;
946     }
947
948     /* check if another lock on that file overlaps the area */
949     LIST_FOR_EACH( ptr, &fd->inode->locks )
950     {
951         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
952         if (!lock_overlaps( lock, start, end )) continue;
953         if (lock->shared && shared) continue;
954         /* found one */
955         if (!wait)
956         {
957             set_error( STATUS_FILE_LOCK_CONFLICT );
958             return 0;
959         }
960         set_error( STATUS_PENDING );
961         return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
962     }
963
964     /* not found, add it */
965     if (add_lock( fd, shared, start, end )) return 0;
966     if (get_error() == STATUS_FILE_LOCK_CONFLICT)
967     {
968         /* Unix lock conflict -> tell client to wait and retry */
969         if (wait) set_error( STATUS_PENDING );
970     }
971     return 0;
972 }
973
974 /* remove a lock on an fd */
975 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
976 {
977     struct list *ptr;
978     file_pos_t end = start + count;
979
980     /* find an existing lock with the exact same parameters */
981     LIST_FOR_EACH( ptr, &fd->locks )
982     {
983         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
984         if ((lock->start == start) && (lock->end == end))
985         {
986             remove_lock( lock, 1 );
987             return;
988         }
989     }
990     set_error( STATUS_FILE_LOCK_CONFLICT );
991 }
992
993
994 /****************************************************************/
995 /* asynchronous operations support */
996
997 struct async
998 {
999     struct thread       *thread;
1000     void                *apc;
1001     void                *user;
1002     void                *sb;
1003     struct timeout_user *timeout;
1004     struct list          entry;
1005 };
1006
1007 /* notifies client thread of new status of its async request */
1008 /* destroys the server side of it */
1009 static void async_terminate( struct async *async, int status )
1010 {
1011     thread_queue_apc( async->thread, NULL, async->apc, APC_ASYNC_IO,
1012                       1, async->user, async->sb, (void *)status );
1013
1014     if (async->timeout) remove_timeout_user( async->timeout );
1015     async->timeout = NULL;
1016     list_remove( &async->entry );
1017     release_object( async->thread );
1018     free( async );
1019 }
1020
1021 /* cb for timeout on an async request */
1022 static void async_callback(void *private)
1023 {
1024     struct async *async = (struct async *)private;
1025
1026     /* fprintf(stderr, "async timeout out %p\n", async); */
1027     async->timeout = NULL;
1028     async_terminate( async, STATUS_TIMEOUT );
1029 }
1030
1031 /* create an async on a given queue of a fd */
1032 struct async *create_async(struct thread *thread, int* timeout, struct list *queue,
1033                            void *io_apc, void *io_user, void* io_sb)
1034 {
1035     struct async *async = mem_alloc( sizeof(struct async) );
1036
1037     if (!async) return NULL;
1038
1039     async->thread = (struct thread *)grab_object(thread);
1040     async->apc = io_apc;
1041     async->user = io_user;
1042     async->sb = io_sb;
1043
1044     list_add_tail( queue, &async->entry );
1045
1046     if (timeout)
1047     {
1048         struct timeval when;
1049
1050         gettimeofday( &when, NULL );
1051         add_timeout( &when, *timeout );
1052         async->timeout = add_timeout_user( &when, async_callback, async );
1053     }
1054     else async->timeout = NULL;
1055
1056     return async;
1057 }
1058
1059 /* terminate the async operation at the head of the queue */
1060 void async_terminate_head( struct list *queue, int status )
1061 {
1062     struct list *ptr = list_head( queue );
1063     if (ptr) async_terminate( LIST_ENTRY( ptr, struct async, entry ), status );
1064 }
1065
1066 /****************************************************************/
1067 /* file descriptor functions */
1068
1069 static void fd_dump( struct object *obj, int verbose )
1070 {
1071     struct fd *fd = (struct fd *)obj;
1072     fprintf( stderr, "Fd unix_fd=%d user=%p", fd->unix_fd, fd->user );
1073     if (fd->inode) fprintf( stderr, " inode=%p unlink='%s'", fd->inode, fd->closed->unlink );
1074     fprintf( stderr, "\n" );
1075 }
1076
1077 static void fd_destroy( struct object *obj )
1078 {
1079     struct fd *fd = (struct fd *)obj;
1080
1081     async_terminate_queue( &fd->read_q, STATUS_CANCELLED );
1082     async_terminate_queue( &fd->write_q, STATUS_CANCELLED );
1083
1084     remove_fd_locks( fd );
1085     list_remove( &fd->inode_entry );
1086     if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1087     if (fd->inode)
1088     {
1089         inode_add_closed_fd( fd->inode, fd->closed );
1090         release_object( fd->inode );
1091     }
1092     else  /* no inode, close it right away */
1093     {
1094         if (fd->unix_fd != -1) close( fd->unix_fd );
1095     }
1096 }
1097
1098 /* set the events that select waits for on this fd */
1099 void set_fd_events( struct fd *fd, int events )
1100 {
1101     int user = fd->poll_index;
1102     assert( poll_users[user] == fd );
1103
1104     set_fd_epoll_events( fd, user, events );
1105
1106     if (events == -1)  /* stop waiting on this fd completely */
1107     {
1108         pollfd[user].fd = -1;
1109         pollfd[user].events = POLLERR;
1110         pollfd[user].revents = 0;
1111     }
1112     else if (pollfd[user].fd != -1 || !pollfd[user].events)
1113     {
1114         pollfd[user].fd = fd->unix_fd;
1115         pollfd[user].events = events;
1116     }
1117 }
1118
1119 /* allocate an fd object, without setting the unix fd yet */
1120 struct fd *alloc_fd( const struct fd_ops *fd_user_ops, struct object *user )
1121 {
1122     struct fd *fd = alloc_object( &fd_ops );
1123
1124     if (!fd) return NULL;
1125
1126     fd->fd_ops     = fd_user_ops;
1127     fd->user       = user;
1128     fd->inode      = NULL;
1129     fd->closed     = NULL;
1130     fd->access     = 0;
1131     fd->sharing    = 0;
1132     fd->unix_fd    = -1;
1133     fd->fs_locks   = 1;
1134     fd->poll_index = -1;
1135     list_init( &fd->inode_entry );
1136     list_init( &fd->locks );
1137     list_init( &fd->read_q );
1138     list_init( &fd->write_q );
1139
1140     if ((fd->poll_index = add_poll_user( fd )) == -1)
1141     {
1142         release_object( fd );
1143         return NULL;
1144     }
1145     return fd;
1146 }
1147
1148 /* check if the desired access is possible without violating */
1149 /* the sharing mode of other opens of the same file */
1150 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
1151 {
1152     unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1153     unsigned int existing_access = 0;
1154     int unlink = 0;
1155     struct list *ptr;
1156
1157     /* if access mode is 0, sharing mode is ignored */
1158     if (!access) sharing = existing_sharing;
1159     fd->access = access;
1160     fd->sharing = sharing;
1161
1162     LIST_FOR_EACH( ptr, &fd->inode->open )
1163     {
1164         struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1165         if (fd_ptr != fd)
1166         {
1167             existing_sharing &= fd_ptr->sharing;
1168             existing_access  |= fd_ptr->access;
1169             if (fd_ptr->closed->unlink[0]) unlink = 1;
1170         }
1171     }
1172
1173     if ((access & GENERIC_READ) && !(existing_sharing & FILE_SHARE_READ)) return 0;
1174     if ((access & GENERIC_WRITE) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1175     if ((existing_access & GENERIC_READ) && !(sharing & FILE_SHARE_READ)) return 0;
1176     if ((existing_access & GENERIC_WRITE) && !(sharing & FILE_SHARE_WRITE)) return 0;
1177     if (fd->closed->unlink[0] && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1178     if (unlink && !(sharing & FILE_SHARE_DELETE)) return 0;
1179     return 1;
1180 }
1181
1182 /* open() wrapper using a struct fd */
1183 /* the fd must have been created with alloc_fd */
1184 /* on error the fd object is released */
1185 struct fd *open_fd( struct fd *fd, const char *name, int flags, mode_t *mode,
1186                     unsigned int access, unsigned int sharing, unsigned int options )
1187 {
1188     struct stat st;
1189     struct closed_fd *closed_fd;
1190     const char *unlink_name = "";
1191
1192     assert( fd->unix_fd == -1 );
1193
1194     if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1195     if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1196     {
1197         release_object( fd );
1198         return NULL;
1199     }
1200     /* create the directory if needed */
1201     if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1202     {
1203         if (mkdir( name, 0777 ) == -1)
1204         {
1205             if (errno != EEXIST || (flags & O_EXCL))
1206             {
1207                 file_set_error();
1208                 release_object( fd );
1209                 free( closed_fd );
1210                 return NULL;
1211             }
1212         }
1213         flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1214     }
1215     if ((fd->unix_fd = open( name, flags & ~O_TRUNC, *mode )) == -1)
1216     {
1217         file_set_error();
1218         release_object( fd );
1219         free( closed_fd );
1220         return NULL;
1221     }
1222     closed_fd->fd = fd->unix_fd;
1223     closed_fd->unlink[0] = 0;
1224     fstat( fd->unix_fd, &st );
1225     *mode = st.st_mode;
1226
1227     /* only bother with an inode for normal files and directories */
1228     if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1229     {
1230         struct inode *inode = get_inode( st.st_dev, st.st_ino );
1231
1232         if (!inode)
1233         {
1234             /* we can close the fd because there are no others open on the same file,
1235              * otherwise we wouldn't have failed to allocate a new inode
1236              */
1237             goto error;
1238         }
1239         fd->inode = inode;
1240         fd->closed = closed_fd;
1241         list_add_head( &inode->open, &fd->inode_entry );
1242
1243         /* check directory options */
1244         if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1245         {
1246             release_object( fd );
1247             set_error( STATUS_NOT_A_DIRECTORY );
1248             return NULL;
1249         }
1250         if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1251         {
1252             release_object( fd );
1253             set_error( STATUS_FILE_IS_A_DIRECTORY );
1254             return NULL;
1255         }
1256         if (!check_sharing( fd, access, sharing ))
1257         {
1258             release_object( fd );
1259             set_error( STATUS_SHARING_VIOLATION );
1260             return NULL;
1261         }
1262         strcpy( closed_fd->unlink, unlink_name );
1263         if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1264     }
1265     else  /* special file */
1266     {
1267         if (options & FILE_DIRECTORY_FILE)
1268         {
1269             set_error( STATUS_NOT_A_DIRECTORY );
1270             goto error;
1271         }
1272         if (unlink_name[0])  /* we can't unlink special files */
1273         {
1274             set_error( STATUS_INVALID_PARAMETER );
1275             goto error;
1276         }
1277         free( closed_fd );
1278     }
1279     return fd;
1280
1281 error:
1282     release_object( fd );
1283     free( closed_fd );
1284     return NULL;
1285 }
1286
1287 /* create an fd for an anonymous file */
1288 /* if the function fails the unix fd is closed */
1289 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user )
1290 {
1291     struct fd *fd = alloc_fd( fd_user_ops, user );
1292
1293     if (fd)
1294     {
1295         fd->unix_fd = unix_fd;
1296         return fd;
1297     }
1298     close( unix_fd );
1299     return NULL;
1300 }
1301
1302 /* retrieve the object that is using an fd */
1303 void *get_fd_user( struct fd *fd )
1304 {
1305     return fd->user;
1306 }
1307
1308 /* retrieve the unix fd for an object */
1309 int get_unix_fd( struct fd *fd )
1310 {
1311     return fd->unix_fd;
1312 }
1313
1314 /* check if two file descriptors point to the same file */
1315 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1316 {
1317     return fd1->inode == fd2->inode;
1318 }
1319
1320 /* callback for event happening in the main poll() loop */
1321 void fd_poll_event( struct fd *fd, int event )
1322 {
1323     return fd->fd_ops->poll_event( fd, event );
1324 }
1325
1326 /* check if events are pending and if yes return which one(s) */
1327 int check_fd_events( struct fd *fd, int events )
1328 {
1329     struct pollfd pfd;
1330
1331     pfd.fd     = fd->unix_fd;
1332     pfd.events = events;
1333     if (poll( &pfd, 1, 0 ) <= 0) return 0;
1334     return pfd.revents;
1335 }
1336
1337 /* default add_queue() routine for objects that poll() on an fd */
1338 int default_fd_add_queue( struct object *obj, struct wait_queue_entry *entry )
1339 {
1340     struct fd *fd = get_obj_fd( obj );
1341
1342     if (!fd) return 0;
1343     if (list_empty( &obj->wait_queue ))  /* first on the queue */
1344         set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1345     add_queue( obj, entry );
1346     release_object( fd );
1347     return 1;
1348 }
1349
1350 /* default remove_queue() routine for objects that poll() on an fd */
1351 void default_fd_remove_queue( struct object *obj, struct wait_queue_entry *entry )
1352 {
1353     struct fd *fd = get_obj_fd( obj );
1354
1355     grab_object( obj );
1356     remove_queue( obj, entry );
1357     if (list_empty( &obj->wait_queue ))  /* last on the queue is gone */
1358         set_fd_events( fd, 0 );
1359     release_object( obj );
1360     release_object( fd );
1361 }
1362
1363 /* default signaled() routine for objects that poll() on an fd */
1364 int default_fd_signaled( struct object *obj, struct thread *thread )
1365 {
1366     int events, ret;
1367     struct fd *fd = get_obj_fd( obj );
1368
1369     if (fd->inode) return 1;  /* regular files are always signaled */
1370
1371     events = fd->fd_ops->get_poll_events( fd );
1372     ret = check_fd_events( fd, events ) != 0;
1373
1374     if (ret)
1375         set_fd_events( fd, 0 ); /* stop waiting on select() if we are signaled */
1376     else if (!list_empty( &obj->wait_queue ))
1377         set_fd_events( fd, events ); /* restart waiting on poll() if we are no longer signaled */
1378
1379     release_object( fd );
1380     return ret;
1381 }
1382
1383 int default_fd_get_poll_events( struct fd *fd )
1384 {
1385     int events = 0;
1386
1387     if( !list_empty( &fd->read_q ))
1388         events |= POLLIN;
1389     if( !list_empty( &fd->write_q ))
1390         events |= POLLOUT;
1391
1392     return events;
1393 }
1394
1395 /* default handler for poll() events */
1396 void default_poll_event( struct fd *fd, int event )
1397 {
1398     if (!list_empty( &fd->read_q ) && (POLLIN & event) )
1399     {
1400         async_terminate_head( &fd->read_q, STATUS_ALERTED );
1401         return;
1402     }
1403     if (!list_empty( &fd->write_q ) && (POLLOUT & event) )
1404     {
1405         async_terminate_head( &fd->write_q, STATUS_ALERTED );
1406         return;
1407     }
1408
1409     /* if an error occurred, stop polling this fd to avoid busy-looping */
1410     if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1411     wake_up( fd->user, 0 );
1412 }
1413
1414 void default_fd_queue_async( struct fd *fd, void *apc, void *user, void *io_sb, int type, int count )
1415 {
1416     struct list *queue;
1417     int events;
1418
1419     if (!(fd->fd_ops->get_file_info( fd ) & FD_FLAG_OVERLAPPED))
1420     {
1421         set_error( STATUS_INVALID_HANDLE );
1422         return;
1423     }
1424
1425     switch (type)
1426     {
1427     case ASYNC_TYPE_READ:
1428         queue = &fd->read_q;
1429         break;
1430     case ASYNC_TYPE_WRITE:
1431         queue = &fd->write_q;
1432         break;
1433     default:
1434         set_error( STATUS_INVALID_PARAMETER );
1435         return;
1436     }
1437
1438     if (!create_async( current, NULL, queue, apc, user, io_sb ))
1439         return;
1440
1441     /* Check if the new pending request can be served immediately */
1442     events = check_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1443     if (events) fd->fd_ops->poll_event( fd, events );
1444
1445     set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1446 }
1447
1448 void default_fd_cancel_async( struct fd *fd )
1449 {
1450     async_terminate_queue( &fd->read_q, STATUS_CANCELLED );
1451     async_terminate_queue( &fd->write_q, STATUS_CANCELLED );
1452 }
1453
1454 /* default flush() routine */
1455 int no_flush( struct fd *fd, struct event **event )
1456 {
1457     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1458     return 0;
1459 }
1460
1461 /* default get_file_info() routine */
1462 int no_get_file_info( struct fd *fd )
1463 {
1464     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1465     return 0;
1466 }
1467
1468 /* default queue_async() routine */
1469 void no_queue_async( struct fd *fd, void* apc, void* user, void* io_sb, 
1470                      int type, int count)
1471 {
1472     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1473 }
1474
1475 /* default cancel_async() routine */
1476 void no_cancel_async( struct fd *fd )
1477 {
1478     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1479 }
1480
1481 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1482 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1483                                      unsigned int access )
1484 {
1485     struct fd *fd = NULL;
1486     struct object *obj;
1487
1488     if ((obj = get_handle_obj( process, handle, access, NULL )))
1489     {
1490         fd = get_obj_fd( obj );
1491         release_object( obj );
1492     }
1493     return fd;
1494 }
1495
1496 /* flush a file buffers */
1497 DECL_HANDLER(flush_file)
1498 {
1499     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1500     struct event * event = NULL;
1501
1502     if (fd)
1503     {
1504         fd->fd_ops->flush( fd, &event );
1505         if ( event )
1506         {
1507             reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1508         }
1509         release_object( fd );
1510     }
1511 }
1512
1513 /* get a Unix fd to access a file */
1514 DECL_HANDLER(get_handle_fd)
1515 {
1516     struct fd *fd;
1517
1518     reply->fd = -1;
1519
1520     if ((fd = get_handle_fd_obj( current->process, req->handle, req->access )))
1521     {
1522         int unix_fd = get_handle_unix_fd( current->process, req->handle, req->access );
1523         if (unix_fd != -1) reply->fd = unix_fd;
1524         else if (!get_error())
1525         {
1526             assert( fd->unix_fd != -1 );
1527             send_client_fd( current->process, fd->unix_fd, req->handle );
1528         }
1529         reply->flags = fd->fd_ops->get_file_info( fd );
1530         release_object( fd );
1531     }
1532 }
1533
1534 /* create / reschedule an async I/O */
1535 DECL_HANDLER(register_async)
1536 {
1537     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1538
1539     /*
1540      * The queue_async method must do the following:
1541      *
1542      * 1. Get the async_queue for the request of given type.
1543      * 2. Create a new asynchronous request for the selected queue
1544      * 3. Carry out any operations necessary to adjust the object's poll events
1545      *    Usually: set_elect_events (obj, obj->ops->get_poll_events()).
1546      * 4. When the async request is triggered, then send back (with a proper APC)
1547      *    the trigger (STATUS_ALERTED) to the thread that posted the request. 
1548      *    async_destroy() is to be called: it will both notify the sender about
1549      *    the trigger and destroy the request by itself
1550      * See also the implementations in file.c, serial.c, and sock.c.
1551      */
1552
1553     if (fd)
1554     {
1555         fd->fd_ops->queue_async( fd, req->io_apc, req->io_user, req->io_sb, 
1556                                  req->type, req->count );
1557         release_object( fd );
1558     }
1559 }
1560
1561 /* cancels all async I/O */
1562 DECL_HANDLER(cancel_async)
1563 {
1564     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1565     if (fd)
1566     {
1567         /* Note: we don't kill the queued APC_ASYNC_IO on this thread because
1568          * NtCancelIoFile() will force the pending APC to be run. Since, 
1569          * Windows only guarantees that the current thread will have no async 
1570          * operation on the current fd when NtCancelIoFile returns, this shall
1571          * do the work.
1572          */
1573         fd->fd_ops->cancel_async( fd );
1574         release_object( fd );
1575     }        
1576 }