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