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