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