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