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