ntdll: Moved the check for removable file in load_dll to the server.
[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 inline static 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 /* asynchronous operations support */
1271
1272 struct async
1273 {
1274     struct thread       *thread;
1275     void                *apc;
1276     void                *user;
1277     void                *sb;
1278     struct timeout_user *timeout;
1279     struct list          entry;
1280 };
1281
1282 /* notifies client thread of new status of its async request */
1283 /* destroys the server side of it */
1284 static void async_terminate( struct async *async, int status )
1285 {
1286     apc_call_t data;
1287
1288     memset( &data, 0, sizeof(data) );
1289     data.type            = APC_ASYNC_IO;
1290     data.async_io.func   = async->apc;
1291     data.async_io.user   = async->user;
1292     data.async_io.sb     = async->sb;
1293     data.async_io.status = status;
1294     thread_queue_apc( async->thread, NULL, &data );
1295
1296     if (async->timeout) remove_timeout_user( async->timeout );
1297     async->timeout = NULL;
1298     list_remove( &async->entry );
1299     release_object( async->thread );
1300     free( async );
1301 }
1302
1303 /* cb for timeout on an async request */
1304 static void async_callback(void *private)
1305 {
1306     struct async *async = (struct async *)private;
1307
1308     /* fprintf(stderr, "async timeout out %p\n", async); */
1309     async->timeout = NULL;
1310     async_terminate( async, STATUS_TIMEOUT );
1311 }
1312
1313 /* create an async on a given queue of a fd */
1314 struct async *create_async( struct thread *thread, const struct timeval *timeout,
1315                             struct list *queue, void *io_apc, void *io_user, void* io_sb )
1316 {
1317     struct async *async = mem_alloc( sizeof(struct async) );
1318
1319     if (!async) return NULL;
1320
1321     async->thread = (struct thread *)grab_object(thread);
1322     async->apc = io_apc;
1323     async->user = io_user;
1324     async->sb = io_sb;
1325
1326     list_add_tail( queue, &async->entry );
1327
1328     if (timeout) async->timeout = add_timeout_user( timeout, async_callback, async );
1329     else async->timeout = NULL;
1330
1331     return async;
1332 }
1333
1334 /* terminate the async operation at the head of the queue */
1335 void async_terminate_head( struct list *queue, int status )
1336 {
1337     struct list *ptr = list_head( queue );
1338     if (ptr) async_terminate( LIST_ENTRY( ptr, struct async, entry ), status );
1339 }
1340
1341 /****************************************************************/
1342 /* file descriptor functions */
1343
1344 static void fd_dump( struct object *obj, int verbose )
1345 {
1346     struct fd *fd = (struct fd *)obj;
1347     fprintf( stderr, "Fd unix_fd=%d user=%p", fd->unix_fd, fd->user );
1348     if (fd->inode) fprintf( stderr, " inode=%p unlink='%s'", fd->inode, fd->closed->unlink );
1349     fprintf( stderr, "\n" );
1350 }
1351
1352 static void fd_destroy( struct object *obj )
1353 {
1354     struct fd *fd = (struct fd *)obj;
1355
1356     async_terminate_queue( &fd->read_q, STATUS_CANCELLED );
1357     async_terminate_queue( &fd->write_q, STATUS_CANCELLED );
1358
1359     remove_fd_locks( fd );
1360     list_remove( &fd->inode_entry );
1361     if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1362     if (fd->inode)
1363     {
1364         inode_add_closed_fd( fd->inode, fd->closed );
1365         release_object( fd->inode );
1366     }
1367     else  /* no inode, close it right away */
1368     {
1369         if (fd->unix_fd != -1) close( fd->unix_fd );
1370     }
1371 }
1372
1373 /* set the events that select waits for on this fd */
1374 void set_fd_events( struct fd *fd, int events )
1375 {
1376     int user = fd->poll_index;
1377     assert( poll_users[user] == fd );
1378
1379     set_fd_epoll_events( fd, user, events );
1380
1381     if (events == -1)  /* stop waiting on this fd completely */
1382     {
1383         pollfd[user].fd = -1;
1384         pollfd[user].events = POLLERR;
1385         pollfd[user].revents = 0;
1386     }
1387     else if (pollfd[user].fd != -1 || !pollfd[user].events)
1388     {
1389         pollfd[user].fd = fd->unix_fd;
1390         pollfd[user].events = events;
1391     }
1392 }
1393
1394 /* prepare an fd for unmounting its corresponding device */
1395 static inline void unmount_fd( struct fd *fd )
1396 {
1397     assert( fd->inode );
1398
1399     async_terminate_queue( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1400     async_terminate_queue( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1401
1402     if (fd->poll_index != -1) set_fd_events( fd, -1 );
1403
1404     if (fd->unix_fd != -1) close( fd->unix_fd );
1405
1406     fd->unix_fd = -1;
1407     fd->unmounted = 1;
1408     fd->closed->unix_fd = -1;
1409     fd->closed->unlink[0] = 0;
1410
1411     /* stop using Unix locks on this fd (existing locks have been removed by close) */
1412     fd->fs_locks = 0;
1413 }
1414
1415 /* allocate an fd object, without setting the unix fd yet */
1416 static struct fd *alloc_fd_object(void)
1417 {
1418     struct fd *fd = alloc_object( &fd_ops );
1419
1420     if (!fd) return NULL;
1421
1422     fd->fd_ops     = NULL;
1423     fd->user       = NULL;
1424     fd->inode      = NULL;
1425     fd->closed     = NULL;
1426     fd->access     = 0;
1427     fd->sharing    = 0;
1428     fd->unix_fd    = -1;
1429     fd->fs_locks   = 1;
1430     fd->unmounted  = 0;
1431     fd->poll_index = -1;
1432     list_init( &fd->inode_entry );
1433     list_init( &fd->locks );
1434     list_init( &fd->read_q );
1435     list_init( &fd->write_q );
1436
1437     if ((fd->poll_index = add_poll_user( fd )) == -1)
1438     {
1439         release_object( fd );
1440         return NULL;
1441     }
1442     return fd;
1443 }
1444
1445 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1446 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user )
1447 {
1448     struct fd *fd = alloc_object( &fd_ops );
1449
1450     if (!fd) return NULL;
1451
1452     fd->fd_ops     = fd_user_ops;
1453     fd->user       = user;
1454     fd->inode      = NULL;
1455     fd->closed     = NULL;
1456     fd->access     = 0;
1457     fd->sharing    = 0;
1458     fd->unix_fd    = -1;
1459     fd->fs_locks   = 0;
1460     fd->unmounted  = 0;
1461     fd->poll_index = -1;
1462     list_init( &fd->inode_entry );
1463     list_init( &fd->locks );
1464     list_init( &fd->read_q );
1465     list_init( &fd->write_q );
1466     return fd;
1467 }
1468
1469 /* check if the desired access is possible without violating */
1470 /* the sharing mode of other opens of the same file */
1471 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
1472 {
1473     unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1474     unsigned int existing_access = 0;
1475     struct list *ptr;
1476
1477     /* if access mode is 0, sharing mode is ignored */
1478     if (!access) sharing = existing_sharing;
1479     fd->access = access;
1480     fd->sharing = sharing;
1481
1482     LIST_FOR_EACH( ptr, &fd->inode->open )
1483     {
1484         struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1485         if (fd_ptr != fd)
1486         {
1487             existing_sharing &= fd_ptr->sharing;
1488             existing_access  |= fd_ptr->access;
1489         }
1490     }
1491
1492     if ((access & FILE_UNIX_READ_ACCESS) && !(existing_sharing & FILE_SHARE_READ)) return 0;
1493     if ((access & FILE_UNIX_WRITE_ACCESS) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1494     if ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1495     if ((existing_access & FILE_UNIX_READ_ACCESS) && !(sharing & FILE_SHARE_READ)) return 0;
1496     if ((existing_access & FILE_UNIX_WRITE_ACCESS) && !(sharing & FILE_SHARE_WRITE)) return 0;
1497     if ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)) return 0;
1498     return 1;
1499 }
1500
1501 /* sets the user of an fd that previously had no user */
1502 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1503 {
1504     assert( fd->fd_ops == NULL );
1505     fd->fd_ops = user_ops;
1506     fd->user   = user;
1507 }
1508
1509 /* open() wrapper that returns a struct fd with no fd user set */
1510 struct fd *open_fd( const char *name, int flags, mode_t *mode, unsigned int access,
1511                     unsigned int sharing, unsigned int options )
1512 {
1513     struct stat st;
1514     struct closed_fd *closed_fd;
1515     struct fd *fd;
1516     const char *unlink_name = "";
1517     int rw_mode;
1518
1519     if ((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE))
1520     {
1521         set_error( STATUS_INVALID_PARAMETER );
1522         return NULL;
1523     }
1524
1525     if (!(fd = alloc_fd_object())) return NULL;
1526
1527     if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1528     if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1529     {
1530         release_object( fd );
1531         return NULL;
1532     }
1533
1534     /* create the directory if needed */
1535     if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1536     {
1537         if (mkdir( name, 0777 ) == -1)
1538         {
1539             if (errno != EEXIST || (flags & O_EXCL))
1540             {
1541                 file_set_error();
1542                 goto error;
1543             }
1544         }
1545         flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1546     }
1547
1548     if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1549     {
1550         if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1551         else rw_mode = O_WRONLY;
1552     }
1553     else rw_mode = O_RDONLY;
1554
1555     if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1556     {
1557         /* if we tried to open a directory for write access, retry read-only */
1558         if (errno != EISDIR ||
1559             !(access & FILE_UNIX_WRITE_ACCESS) ||
1560             (fd->unix_fd = open( name, O_RDONLY | (flags & ~O_TRUNC), *mode )) == -1)
1561         {
1562             file_set_error();
1563             goto error;
1564         }
1565     }
1566
1567     closed_fd->unix_fd = fd->unix_fd;
1568     closed_fd->unlink[0] = 0;
1569     fstat( fd->unix_fd, &st );
1570     *mode = st.st_mode;
1571
1572     /* only bother with an inode for normal files and directories */
1573     if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1574     {
1575         struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1576
1577         if (!inode)
1578         {
1579             /* we can close the fd because there are no others open on the same file,
1580              * otherwise we wouldn't have failed to allocate a new inode
1581              */
1582             goto error;
1583         }
1584         fd->inode = inode;
1585         fd->closed = closed_fd;
1586         list_add_head( &inode->open, &fd->inode_entry );
1587
1588         /* check directory options */
1589         if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1590         {
1591             release_object( fd );
1592             set_error( STATUS_NOT_A_DIRECTORY );
1593             return NULL;
1594         }
1595         if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1596         {
1597             release_object( fd );
1598             set_error( STATUS_FILE_IS_A_DIRECTORY );
1599             return NULL;
1600         }
1601         if (!check_sharing( fd, access, sharing ))
1602         {
1603             release_object( fd );
1604             set_error( STATUS_SHARING_VIOLATION );
1605             return NULL;
1606         }
1607         strcpy( closed_fd->unlink, unlink_name );
1608         if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1609     }
1610     else  /* special file */
1611     {
1612         if (options & FILE_DIRECTORY_FILE)
1613         {
1614             set_error( STATUS_NOT_A_DIRECTORY );
1615             goto error;
1616         }
1617         if (unlink_name[0])  /* we can't unlink special files */
1618         {
1619             set_error( STATUS_INVALID_PARAMETER );
1620             goto error;
1621         }
1622         free( closed_fd );
1623     }
1624     return fd;
1625
1626 error:
1627     release_object( fd );
1628     free( closed_fd );
1629     return NULL;
1630 }
1631
1632 /* create an fd for an anonymous file */
1633 /* if the function fails the unix fd is closed */
1634 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user )
1635 {
1636     struct fd *fd = alloc_fd_object();
1637
1638     if (fd)
1639     {
1640         set_fd_user( fd, fd_user_ops, user );
1641         fd->unix_fd = unix_fd;
1642         return fd;
1643     }
1644     close( unix_fd );
1645     return NULL;
1646 }
1647
1648 /* retrieve the object that is using an fd */
1649 void *get_fd_user( struct fd *fd )
1650 {
1651     return fd->user;
1652 }
1653
1654 /* retrieve the unix fd for an object */
1655 int get_unix_fd( struct fd *fd )
1656 {
1657     if (fd->unix_fd == -1)
1658     {
1659         if (fd->unmounted) set_error( STATUS_VOLUME_DISMOUNTED );
1660         else set_error( STATUS_BAD_DEVICE_TYPE );
1661     }
1662     return fd->unix_fd;
1663 }
1664
1665 /* check if two file descriptors point to the same file */
1666 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1667 {
1668     return fd1->inode == fd2->inode;
1669 }
1670
1671 /* check if fd is on a removable device */
1672 int is_fd_removable( struct fd *fd )
1673 {
1674     return (fd->inode && fd->inode->device->removable);
1675 }
1676
1677 /* handler for close_handle that refuses to close fd-associated handles in other processes */
1678 int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
1679 {
1680     return (!current || current->process == process);
1681 }
1682
1683 /* callback for event happening in the main poll() loop */
1684 void fd_poll_event( struct fd *fd, int event )
1685 {
1686     return fd->fd_ops->poll_event( fd, event );
1687 }
1688
1689 /* check if events are pending and if yes return which one(s) */
1690 int check_fd_events( struct fd *fd, int events )
1691 {
1692     struct pollfd pfd;
1693
1694     if (fd->unix_fd == -1) return POLLERR;
1695
1696     pfd.fd     = fd->unix_fd;
1697     pfd.events = events;
1698     if (poll( &pfd, 1, 0 ) <= 0) return 0;
1699     return pfd.revents;
1700 }
1701
1702 /* default add_queue() routine for objects that poll() on an fd */
1703 int default_fd_add_queue( struct object *obj, struct wait_queue_entry *entry )
1704 {
1705     struct fd *fd = get_obj_fd( obj );
1706
1707     if (!fd) return 0;
1708     if (!fd->inode && list_empty( &obj->wait_queue ))  /* first on the queue */
1709         set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1710     add_queue( obj, entry );
1711     release_object( fd );
1712     return 1;
1713 }
1714
1715 /* default remove_queue() routine for objects that poll() on an fd */
1716 void default_fd_remove_queue( struct object *obj, struct wait_queue_entry *entry )
1717 {
1718     struct fd *fd = get_obj_fd( obj );
1719
1720     grab_object( obj );
1721     remove_queue( obj, entry );
1722     if (!fd->inode && list_empty( &obj->wait_queue ))  /* last on the queue is gone */
1723         set_fd_events( fd, 0 );
1724     release_object( obj );
1725     release_object( fd );
1726 }
1727
1728 /* default signaled() routine for objects that poll() on an fd */
1729 int default_fd_signaled( struct object *obj, struct thread *thread )
1730 {
1731     int events, ret;
1732     struct fd *fd = get_obj_fd( obj );
1733
1734     if (fd->inode) ret = 1; /* regular files are always signaled */
1735     else
1736     {
1737         events = fd->fd_ops->get_poll_events( fd );
1738         ret = check_fd_events( fd, events ) != 0;
1739
1740         if (ret)
1741         {
1742             /* stop waiting on select() if we are signaled */
1743             set_fd_events( fd, 0 );
1744         }
1745         else if (!list_empty( &obj->wait_queue ))
1746         {
1747             /* restart waiting on poll() if we are no longer signaled */
1748             set_fd_events( fd, events );
1749         }
1750     }
1751     release_object( fd );
1752     return ret;
1753 }
1754
1755 int default_fd_get_poll_events( struct fd *fd )
1756 {
1757     int events = 0;
1758
1759     if (!list_empty( &fd->read_q ))
1760         events |= POLLIN;
1761     if (!list_empty( &fd->write_q ))
1762         events |= POLLOUT;
1763
1764     return events;
1765 }
1766
1767 /* default handler for poll() events */
1768 void default_poll_event( struct fd *fd, int event )
1769 {
1770     if (!list_empty( &fd->read_q ) && (POLLIN & event) )
1771     {
1772         async_terminate_head( &fd->read_q, STATUS_ALERTED );
1773         return;
1774     }
1775     if (!list_empty( &fd->write_q ) && (POLLOUT & event) )
1776     {
1777         async_terminate_head( &fd->write_q, STATUS_ALERTED );
1778         return;
1779     }
1780
1781     /* if an error occurred, stop polling this fd to avoid busy-looping */
1782     if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1783     wake_up( fd->user, 0 );
1784 }
1785
1786 void fd_queue_async_timeout( struct fd *fd, void *apc, void *user, void *io_sb, int type, int count,
1787                              const struct timeval *timeout )
1788 {
1789     struct list *queue;
1790     int events, flags;
1791
1792     fd->fd_ops->get_file_info( fd, &flags );
1793     if (!(flags & (FD_FLAG_OVERLAPPED|FD_FLAG_TIMEOUT)))
1794     {
1795         set_error( STATUS_INVALID_HANDLE );
1796         return;
1797     }
1798
1799     switch (type)
1800     {
1801     case ASYNC_TYPE_READ:
1802         queue = &fd->read_q;
1803         break;
1804     case ASYNC_TYPE_WRITE:
1805         queue = &fd->write_q;
1806         break;
1807     default:
1808         set_error( STATUS_INVALID_PARAMETER );
1809         return;
1810     }
1811
1812     if (!create_async( current, timeout, queue, apc, user, io_sb ))
1813         return;
1814
1815     /* Check if the new pending request can be served immediately */
1816     events = check_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1817     if (events) fd->fd_ops->poll_event( fd, events );
1818
1819     set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1820 }
1821
1822 void default_fd_queue_async( struct fd *fd, void *apc, void *user, void *io_sb, int type, int count )
1823 {
1824     fd_queue_async_timeout( fd, apc, user, io_sb, type, count, NULL );
1825 }
1826
1827 void default_fd_cancel_async( struct fd *fd )
1828 {
1829     async_terminate_queue( &fd->read_q, STATUS_CANCELLED );
1830     async_terminate_queue( &fd->write_q, STATUS_CANCELLED );
1831 }
1832
1833 /* default flush() routine */
1834 int no_flush( struct fd *fd, struct event **event )
1835 {
1836     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1837     return 0;
1838 }
1839
1840 /* default get_file_info() routine */
1841 enum server_fd_type no_get_file_info( struct fd *fd, int *flags )
1842 {
1843     *flags = 0;
1844     return FD_TYPE_INVALID;
1845 }
1846
1847 /* default queue_async() routine */
1848 void no_queue_async( struct fd *fd, void* apc, void* user, void* io_sb, 
1849                      int type, int count)
1850 {
1851     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1852 }
1853
1854 /* default cancel_async() routine */
1855 void no_cancel_async( struct fd *fd )
1856 {
1857     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1858 }
1859
1860 static inline int is_valid_mounted_device( struct stat *st )
1861 {
1862 #if defined(linux) || defined(__sun__)
1863     return S_ISBLK( st->st_mode );
1864 #else
1865     /* disks are char devices on *BSD */
1866     return S_ISCHR( st->st_mode );
1867 #endif
1868 }
1869
1870 /* close all Unix file descriptors on a device to allow unmounting it */
1871 static void unmount_device( struct fd *device_fd )
1872 {
1873     unsigned int i;
1874     struct stat st;
1875     struct device *device;
1876     struct inode *inode;
1877     struct fd *fd;
1878     int unix_fd = get_unix_fd( device_fd );
1879
1880     if (unix_fd == -1) return;
1881
1882     if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
1883     {
1884         set_error( STATUS_INVALID_PARAMETER );
1885         return;
1886     }
1887
1888     if (!(device = get_device( st.st_rdev, -1 ))) return;
1889
1890     for (i = 0; i < INODE_HASH_SIZE; i++)
1891     {
1892         LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
1893         {
1894             LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
1895             {
1896                 unmount_fd( fd );
1897             }
1898             inode_close_pending( inode, 0 );
1899         }
1900     }
1901     /* remove it from the hash table */
1902     list_remove( &device->entry );
1903     list_init( &device->entry );
1904     release_object( device );
1905 }
1906
1907 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1908 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1909                                      unsigned int access )
1910 {
1911     struct fd *fd = NULL;
1912     struct object *obj;
1913
1914     if ((obj = get_handle_obj( process, handle, access, NULL )))
1915     {
1916         fd = get_obj_fd( obj );
1917         release_object( obj );
1918     }
1919     return fd;
1920 }
1921
1922 /* flush a file buffers */
1923 DECL_HANDLER(flush_file)
1924 {
1925     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1926     struct event * event = NULL;
1927
1928     if (fd)
1929     {
1930         fd->fd_ops->flush( fd, &event );
1931         if ( event )
1932         {
1933             reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1934         }
1935         release_object( fd );
1936     }
1937 }
1938
1939 /* open a file object */
1940 DECL_HANDLER(open_file_object)
1941 {
1942     struct unicode_str name;
1943     struct directory *root = NULL;
1944     struct object *obj;
1945
1946     get_req_unicode_str( &name );
1947     if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
1948         return;
1949
1950     if ((obj = open_object_dir( root, &name, req->attributes, NULL )))
1951     {
1952         /* make sure this is a valid file object */
1953         struct fd *fd = get_obj_fd( obj );
1954         if (fd)
1955         {
1956             reply->handle = alloc_handle( current->process, obj, req->access, req->attributes );
1957             release_object( fd );
1958         }
1959         release_object( obj );
1960     }
1961
1962     if (root) release_object( root );
1963 }
1964
1965 /* get a Unix fd to access a file */
1966 DECL_HANDLER(get_handle_fd)
1967 {
1968     struct fd *fd;
1969
1970     if ((fd = get_handle_fd_obj( current->process, req->handle, req->access )))
1971     {
1972         reply->type = fd->fd_ops->get_file_info( fd, &reply->flags );
1973         if (reply->type != FD_TYPE_INVALID)
1974         {
1975             if (is_fd_removable(fd)) reply->flags |= FD_FLAG_REMOVABLE;
1976             if (!req->cached)
1977             {
1978                 int unix_fd = get_unix_fd( fd );
1979                 if (unix_fd != -1) send_client_fd( current->process, unix_fd, req->handle );
1980             }
1981         }
1982         else set_error( STATUS_OBJECT_TYPE_MISMATCH );
1983         release_object( fd );
1984     }
1985 }
1986
1987 /* get ready to unmount a Unix device */
1988 DECL_HANDLER(unmount_device)
1989 {
1990     struct fd *fd;
1991
1992     if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
1993     {
1994         unmount_device( fd );
1995         release_object( fd );
1996     }
1997 }
1998
1999 /* create / reschedule an async I/O */
2000 DECL_HANDLER(register_async)
2001 {
2002     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2003
2004     /*
2005      * The queue_async method must do the following:
2006      *
2007      * 1. Get the async_queue for the request of given type.
2008      * 2. Create a new asynchronous request for the selected queue
2009      * 3. Carry out any operations necessary to adjust the object's poll events
2010      *    Usually: set_elect_events (obj, obj->ops->get_poll_events()).
2011      * 4. When the async request is triggered, then send back (with a proper APC)
2012      *    the trigger (STATUS_ALERTED) to the thread that posted the request. 
2013      *    async_destroy() is to be called: it will both notify the sender about
2014      *    the trigger and destroy the request by itself
2015      * See also the implementations in file.c, serial.c, and sock.c.
2016      */
2017
2018     if (fd)
2019     {
2020         fd->fd_ops->queue_async( fd, req->io_apc, req->io_user, req->io_sb, 
2021                                  req->type, req->count );
2022         release_object( fd );
2023     }
2024 }
2025
2026 /* cancels all async I/O */
2027 DECL_HANDLER(cancel_async)
2028 {
2029     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2030     if (fd)
2031     {
2032         /* Note: we don't kill the queued APC_ASYNC_IO on this thread because
2033          * NtCancelIoFile() will force the pending APC to be run. Since, 
2034          * Windows only guarantees that the current thread will have no async 
2035          * operation on the current fd when NtCancelIoFile returns, this shall
2036          * do the work.
2037          */
2038         fd->fd_ops->cancel_async( fd );
2039         release_object( fd );
2040     }        
2041 }