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