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