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