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