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