Be more strict and verbose while testing
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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_STDINT_H
41 #include <stdint.h>
42 #endif
43 #include <sys/stat.h>
44 #include <sys/time.h>
45 #include <sys/types.h>
46 #include <unistd.h>
47
48 #include "object.h"
49 #include "file.h"
50 #include "handle.h"
51 #include "process.h"
52 #include "request.h"
53
54 #include "winternl.h"
55
56 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
57 # include <sys/epoll.h>
58 # define USE_EPOLL
59 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
60 # define USE_EPOLL
61 # define EPOLLIN POLLIN
62 # define EPOLLOUT POLLOUT
63 # define EPOLLERR POLLERR
64 # define EPOLLHUP POLLHUP
65 # define EPOLL_CTL_ADD 1
66 # define EPOLL_CTL_DEL 2
67 # define EPOLL_CTL_MOD 3
68
69 typedef union epoll_data
70 {
71   void *ptr;
72   int fd;
73   uint32_t u32;
74   uint64_t u64;
75 } epoll_data_t;
76
77 struct epoll_event
78 {
79   uint32_t events;
80   epoll_data_t data;
81 };
82
83 #define SYSCALL_RET(ret) do { \
84         if (ret < 0) { errno = -ret; ret = -1; } \
85         return ret; \
86     } while(0)
87
88 static inline int epoll_create( int size )
89 {
90     int ret;
91     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
92              : "=a" (ret) : "0" (254 /*NR_epoll_create*/), "r" (size) );
93     SYSCALL_RET(ret);
94 }
95
96 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
97 {
98     int ret;
99     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
100              : "=a" (ret)
101              : "0" (255 /*NR_epoll_ctl*/), "r" (epfd), "c" (op), "d" (fd), "S" (event), "m" (*event) );
102     SYSCALL_RET(ret);
103 }
104
105 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
106 {
107     int ret;
108     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
109              : "=a" (ret)
110              : "0" (256 /*NR_epoll_wait*/), "r" (epfd), "c" (events), "d" (maxevents), "S" (timeout)
111              : "memory" );
112     SYSCALL_RET(ret);
113 }
114 #undef SYSCALL_RET
115
116 #endif /* linux && __i386__ && HAVE_STDINT_H */
117
118
119 /* Because of the stupid Posix locking semantics, we need to keep
120  * track of all file descriptors referencing a given file, and not
121  * close a single one until all the locks are gone (sigh).
122  */
123
124 /* file descriptor object */
125
126 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
127 struct closed_fd
128 {
129     struct list entry;       /* entry in inode closed list */
130     int         unix_fd;     /* the unix file descriptor */
131     char        unlink[1];   /* name to unlink on close (if any) */
132 };
133
134 struct fd
135 {
136     struct object        obj;         /* object header */
137     const struct fd_ops *fd_ops;      /* file descriptor operations */
138     struct inode        *inode;       /* inode that this fd belongs to */
139     struct list          inode_entry; /* entry in inode fd list */
140     struct closed_fd    *closed;      /* structure to store the unix fd at destroy time */
141     struct object       *user;        /* object using this file descriptor */
142     struct list          locks;       /* list of locks on this fd */
143     unsigned int         access;      /* file access (GENERIC_READ/WRITE) */
144     unsigned int         sharing;     /* file sharing mode */
145     int                  unix_fd;     /* unix file descriptor */
146     int                  fs_locks;    /* can we use filesystem locks for this fd? */
147     int                  poll_index;  /* index of fd in poll array */
148     struct list          read_q;      /* async readers of this fd */
149     struct list          write_q;     /* async writers of this fd */
150 };
151
152 static void fd_dump( struct object *obj, int verbose );
153 static void fd_destroy( struct object *obj );
154
155 static const struct object_ops fd_ops =
156 {
157     sizeof(struct fd),        /* size */
158     fd_dump,                  /* dump */
159     no_add_queue,             /* add_queue */
160     NULL,                     /* remove_queue */
161     NULL,                     /* signaled */
162     NULL,                     /* satisfied */
163     no_signal,                /* signal */
164     no_get_fd,                /* get_fd */
165     no_lookup_name,           /* lookup_name */
166     no_close_handle,          /* close_handle */
167     fd_destroy                /* destroy */
168 };
169
170 /* device object */
171
172 #define DEVICE_HASH_SIZE 7
173 #define INODE_HASH_SIZE 17
174
175 struct device
176 {
177     struct object       obj;        /* object header */
178     struct list         entry;      /* entry in device hash list */
179     dev_t               dev;        /* device number */
180     int                 removable;  /* removable device? (or -1 if unknown) */
181     struct list         inode_hash[INODE_HASH_SIZE];  /* inodes hash table */
182 };
183
184 static void device_dump( struct object *obj, int verbose );
185 static void device_destroy( struct object *obj );
186
187 static const struct object_ops device_ops =
188 {
189     sizeof(struct device),    /* size */
190     device_dump,              /* dump */
191     no_add_queue,             /* add_queue */
192     NULL,                     /* remove_queue */
193     NULL,                     /* signaled */
194     NULL,                     /* satisfied */
195     no_signal,                /* signal */
196     no_get_fd,                /* get_fd */
197     no_lookup_name,           /* lookup_name */
198     no_close_handle,          /* close_handle */
199     device_destroy            /* destroy */
200 };
201
202 /* inode object */
203
204 struct inode
205 {
206     struct object       obj;        /* object header */
207     struct list         entry;      /* inode hash list entry */
208     struct device      *device;     /* device containing this inode */
209     ino_t               ino;        /* inode number */
210     struct list         open;       /* list of open file descriptors */
211     struct list         locks;      /* list of file locks */
212     struct list         closed;     /* list of file descriptors to close at destroy time */
213 };
214
215 static void inode_dump( struct object *obj, int verbose );
216 static void inode_destroy( struct object *obj );
217
218 static const struct object_ops inode_ops =
219 {
220     sizeof(struct inode),     /* size */
221     inode_dump,               /* dump */
222     no_add_queue,             /* add_queue */
223     NULL,                     /* remove_queue */
224     NULL,                     /* signaled */
225     NULL,                     /* satisfied */
226     no_signal,                /* signal */
227     no_get_fd,                /* get_fd */
228     no_lookup_name,           /* lookup_name */
229     no_close_handle,          /* close_handle */
230     inode_destroy             /* destroy */
231 };
232
233 /* file lock object */
234
235 struct file_lock
236 {
237     struct object       obj;         /* object header */
238     struct fd          *fd;          /* fd owning this lock */
239     struct list         fd_entry;    /* entry in list of locks on a given fd */
240     struct list         inode_entry; /* entry in inode list of locks */
241     int                 shared;      /* shared lock? */
242     file_pos_t          start;       /* locked region is interval [start;end) */
243     file_pos_t          end;
244     struct process     *process;     /* process owning this lock */
245     struct list         proc_entry;  /* entry in list of locks owned by the process */
246 };
247
248 static void file_lock_dump( struct object *obj, int verbose );
249 static int file_lock_signaled( struct object *obj, struct thread *thread );
250
251 static const struct object_ops file_lock_ops =
252 {
253     sizeof(struct file_lock),   /* size */
254     file_lock_dump,             /* dump */
255     add_queue,                  /* add_queue */
256     remove_queue,               /* remove_queue */
257     file_lock_signaled,         /* signaled */
258     no_satisfied,               /* satisfied */
259     no_signal,                  /* signal */
260     no_get_fd,                  /* get_fd */
261     no_lookup_name,             /* lookup_name */
262     no_close_handle,            /* close_handle */
263     no_destroy                  /* destroy */
264 };
265
266
267 #define OFF_T_MAX       (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
268 #define FILE_POS_T_MAX  (~(file_pos_t)0)
269
270 static file_pos_t max_unix_offset = OFF_T_MAX;
271
272 #define DUMP_LONG_LONG(val) do { \
273     if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
274         fprintf( stderr, "%lx%08lx", (unsigned long)((val) >> 32), (unsigned long)(val) ); \
275     else \
276         fprintf( stderr, "%lx", (unsigned long)(val) ); \
277   } while (0)
278
279
280
281 /****************************************************************/
282 /* timeouts support */
283
284 struct timeout_user
285 {
286     struct list           entry;      /* entry in sorted timeout list */
287     struct timeval        when;       /* timeout expiry (absolute time) */
288     timeout_callback      callback;   /* callback function */
289     void                 *private;    /* callback private data */
290 };
291
292 static struct list timeout_list = LIST_INIT(timeout_list);   /* sorted timeouts list */
293
294 /* add a timeout user */
295 struct timeout_user *add_timeout_user( const struct timeval *when, timeout_callback func,
296                                        void *private )
297 {
298     struct timeout_user *user;
299     struct list *ptr;
300
301     if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
302     user->when     = *when;
303     user->callback = func;
304     user->private  = private;
305
306     /* Now insert it in the linked list */
307
308     LIST_FOR_EACH( ptr, &timeout_list )
309     {
310         struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
311         if (!time_before( &timeout->when, when )) break;
312     }
313     list_add_before( ptr, &user->entry );
314     return user;
315 }
316
317 /* remove a timeout user */
318 void remove_timeout_user( struct timeout_user *user )
319 {
320     list_remove( &user->entry );
321     free( user );
322 }
323
324 /* add a timeout in milliseconds to an absolute time */
325 void add_timeout( struct timeval *when, int timeout )
326 {
327     if (timeout)
328     {
329         long sec = timeout / 1000;
330         if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
331         {
332             when->tv_usec -= 1000000;
333             when->tv_sec++;
334         }
335         when->tv_sec += sec;
336     }
337 }
338
339
340 /****************************************************************/
341 /* poll support */
342
343 static struct fd **poll_users;              /* users array */
344 static struct pollfd *pollfd;               /* poll fd array */
345 static int nb_users;                        /* count of array entries actually in use */
346 static int active_users;                    /* current number of active users */
347 static int allocated_users;                 /* count of allocated entries in the array */
348 static struct fd **freelist;                /* list of free entries in the array */
349
350 #ifdef USE_EPOLL
351
352 static int epoll_fd;
353 static struct epoll_event *epoll_events;
354
355 /* set the events that epoll waits for on this fd; helper for set_fd_events */
356 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
357 {
358     struct epoll_event ev;
359     int ctl;
360
361     if (epoll_fd == -1) return;
362
363     if (events == -1)  /* stop waiting on this fd completely */
364     {
365         if (pollfd[user].fd == -1) return;  /* already removed */
366         ctl = EPOLL_CTL_DEL;
367     }
368     else if (pollfd[user].fd == -1)
369     {
370         if (pollfd[user].events) return;  /* stopped waiting on it, don't restart */
371         ctl = EPOLL_CTL_ADD;
372     }
373     else
374     {
375         if (pollfd[user].events == events) return;  /* nothing to do */
376         ctl = EPOLL_CTL_MOD;
377     }
378
379     ev.events = events;
380     ev.data.u32 = user;
381
382     if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
383     {
384         if (errno == ENOMEM)  /* not enough memory, give up on epoll */
385         {
386             close( epoll_fd );
387             epoll_fd = -1;
388         }
389         else perror( "epoll_ctl" );  /* should not happen */
390     }
391 }
392
393 #else /* USE_EPOLL */
394
395 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
396 {
397 }
398
399 #endif /* USE_EPOLL */
400
401
402 /* add a user in the poll array and return its index, or -1 on failure */
403 static int add_poll_user( struct fd *fd )
404 {
405     int ret;
406     if (freelist)
407     {
408         ret = freelist - poll_users;
409         freelist = (struct fd **)poll_users[ret];
410     }
411     else
412     {
413         if (nb_users == allocated_users)
414         {
415             struct fd **newusers;
416             struct pollfd *newpoll;
417             int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
418             if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
419             if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
420             {
421                 if (allocated_users)
422                     poll_users = newusers;
423                 else
424                     free( newusers );
425                 return -1;
426             }
427             poll_users = newusers;
428             pollfd = newpoll;
429 #ifdef USE_EPOLL
430             if (!allocated_users) epoll_fd = epoll_create( new_count );
431             if (epoll_fd != -1)
432             {
433                 struct epoll_event *new_events;
434                 if (!(new_events = realloc( epoll_events, new_count * sizeof(*epoll_events) )))
435                     return -1;
436                 epoll_events = new_events;
437             }
438 #endif
439             allocated_users = new_count;
440         }
441         ret = nb_users++;
442     }
443     pollfd[ret].fd = -1;
444     pollfd[ret].events = 0;
445     pollfd[ret].revents = 0;
446     poll_users[ret] = fd;
447     active_users++;
448     return ret;
449 }
450
451 /* remove a user from the poll list */
452 static void remove_poll_user( struct fd *fd, int user )
453 {
454     assert( user >= 0 );
455     assert( poll_users[user] == fd );
456
457 #ifdef USE_EPOLL
458     if (epoll_fd != -1 && pollfd[user].fd != -1)
459     {
460         struct epoll_event dummy;
461         epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
462     }
463 #endif
464     pollfd[user].fd = -1;
465     pollfd[user].events = 0;
466     pollfd[user].revents = 0;
467     poll_users[user] = (struct fd *)freelist;
468     freelist = &poll_users[user];
469     active_users--;
470 }
471
472 /* process pending timeouts and return the time until the next timeout, in milliseconds */
473 static int get_next_timeout(void)
474 {
475     if (!list_empty( &timeout_list ))
476     {
477         struct list expired_list, *ptr;
478         struct timeval now;
479
480         gettimeofday( &now, NULL );
481
482         /* first remove all expired timers from the list */
483
484         list_init( &expired_list );
485         while ((ptr = list_head( &timeout_list )) != NULL)
486         {
487             struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
488
489             if (!time_before( &now, &timeout->when ))
490             {
491                 list_remove( &timeout->entry );
492                 list_add_tail( &expired_list, &timeout->entry );
493             }
494             else break;
495         }
496
497         /* now call the callback for all the removed timers */
498
499         while ((ptr = list_head( &expired_list )) != NULL)
500         {
501             struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
502             list_remove( &timeout->entry );
503             timeout->callback( timeout->private );
504             free( timeout );
505         }
506
507         if ((ptr = list_head( &timeout_list )) != NULL)
508         {
509             struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
510             int diff = (timeout->when.tv_sec - now.tv_sec) * 1000
511                      + (timeout->when.tv_usec - now.tv_usec) / 1000;
512             if (diff < 0) diff = 0;
513             return diff;
514         }
515     }
516     return -1;  /* no pending timeouts */
517 }
518
519 /* server main poll() loop */
520 void main_loop(void)
521 {
522     int i, ret, timeout;
523
524 #ifdef USE_EPOLL
525     assert( POLLIN == EPOLLIN );
526     assert( POLLOUT == EPOLLOUT );
527     assert( POLLERR == EPOLLERR );
528     assert( POLLHUP == EPOLLHUP );
529
530     if (epoll_fd != -1)
531     {
532         while (active_users)
533         {
534             timeout = get_next_timeout();
535
536             if (!active_users) break;  /* last user removed by a timeout */
537             if (epoll_fd == -1) break;  /* an error occurred with epoll */
538
539             ret = epoll_wait( epoll_fd, epoll_events, allocated_users, timeout );
540
541             /* put the events into the pollfd array first, like poll does */
542             for (i = 0; i < ret; i++)
543             {
544                 int user = epoll_events[i].data.u32;
545                 pollfd[user].revents = epoll_events[i].events;
546             }
547
548             /* read events from the pollfd array, as set_fd_events may modify them */
549             for (i = 0; i < ret; i++)
550             {
551                 int user = epoll_events[i].data.u32;
552                 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
553             }
554         }
555     }
556     /* fall through to normal poll loop */
557 #endif  /* USE_EPOLL */
558
559     while (active_users)
560     {
561         timeout = get_next_timeout();
562
563         if (!active_users) break;  /* last user removed by a timeout */
564
565         ret = poll( pollfd, nb_users, timeout );
566         if (ret > 0)
567         {
568             for (i = 0; i < nb_users; i++)
569             {
570                 if (pollfd[i].revents)
571                 {
572                     fd_poll_event( poll_users[i], pollfd[i].revents );
573                     if (!--ret) break;
574                 }
575             }
576         }
577     }
578 }
579
580
581 /****************************************************************/
582 /* device functions */
583
584 static struct list device_hash[DEVICE_HASH_SIZE];
585
586 /* retrieve the device object for a given fd, creating it if needed */
587 static struct device *get_device( dev_t dev, int create )
588 {
589     struct device *device;
590     unsigned int i, hash = dev % DEVICE_HASH_SIZE;
591
592     if (device_hash[hash].next)
593     {
594         LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
595             if (device->dev == dev) return (struct device *)grab_object( device );
596     }
597     else list_init( &device_hash[hash] );
598
599     /* not found, create it */
600
601     if (!create) return NULL;
602     if ((device = alloc_object( &device_ops )))
603     {
604         device->dev = dev;
605         device->removable = -1;
606         for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
607         list_add_head( &device_hash[hash], &device->entry );
608     }
609     return device;
610 }
611
612 static void device_dump( struct object *obj, int verbose )
613 {
614     struct device *device = (struct device *)obj;
615     fprintf( stderr, "Device dev=" );
616     DUMP_LONG_LONG( device->dev );
617     fprintf( stderr, "\n" );
618 }
619
620 static void device_destroy( struct object *obj )
621 {
622     struct device *device = (struct device *)obj;
623     unsigned int i;
624
625     for (i = 0; i < INODE_HASH_SIZE; i++)
626         assert( list_empty(&device->inode_hash[i]) );
627
628     list_remove( &device->entry );  /* remove it from the hash table */
629 }
630
631
632 /****************************************************************/
633 /* inode functions */
634
635 /* close all pending file descriptors in the closed list */
636 static void inode_close_pending( struct inode *inode, int keep_unlinks )
637 {
638     struct list *ptr = list_head( &inode->closed );
639
640     while (ptr)
641     {
642         struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
643         struct list *next = list_next( &inode->closed, ptr );
644
645         if (fd->unix_fd != -1)
646         {
647             close( fd->unix_fd );
648             fd->unix_fd = -1;
649         }
650         if (!keep_unlinks || !fd->unlink[0])  /* get rid of it unless there's an unlink pending on that file */
651         {
652             list_remove( ptr );
653             free( fd );
654         }
655         ptr = next;
656     }
657 }
658
659 static void inode_dump( struct object *obj, int verbose )
660 {
661     struct inode *inode = (struct inode *)obj;
662     fprintf( stderr, "Inode device=%p ino=", inode->device );
663     DUMP_LONG_LONG( inode->ino );
664     fprintf( stderr, "\n" );
665 }
666
667 static void inode_destroy( struct object *obj )
668 {
669     struct inode *inode = (struct inode *)obj;
670     struct list *ptr;
671
672     assert( list_empty(&inode->open) );
673     assert( list_empty(&inode->locks) );
674
675     list_remove( &inode->entry );
676
677     while ((ptr = list_head( &inode->closed )))
678     {
679         struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
680         list_remove( ptr );
681         if (fd->unix_fd != -1) close( fd->unix_fd );
682         if (fd->unlink[0])
683         {
684             /* make sure it is still the same file */
685             struct stat st;
686             if (!stat( fd->unlink, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
687             {
688                 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
689                 else unlink( fd->unlink );
690             }
691         }
692         free( fd );
693     }
694     release_object( inode->device );
695 }
696
697 /* retrieve the inode object for a given fd, creating it if needed */
698 static struct inode *get_inode( dev_t dev, ino_t ino )
699 {
700     struct device *device;
701     struct inode *inode;
702     unsigned int hash = ino % INODE_HASH_SIZE;
703
704     if (!(device = get_device( dev, 1 ))) return NULL;
705
706     LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
707     {
708         if (inode->ino == ino)
709         {
710             release_object( device );
711             return (struct inode *)grab_object( inode );
712         }
713     }
714
715     /* not found, create it */
716     if ((inode = alloc_object( &inode_ops )))
717     {
718         inode->device = device;
719         inode->ino    = ino;
720         list_init( &inode->open );
721         list_init( &inode->locks );
722         list_init( &inode->closed );
723         list_add_head( &device->inode_hash[hash], &inode->entry );
724     }
725     else release_object( device );
726
727     return inode;
728 }
729
730 /* add fd to the inode list of file descriptors to close */
731 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
732 {
733     if (!list_empty( &inode->locks ))
734     {
735         list_add_head( &inode->closed, &fd->entry );
736     }
737     else if (fd->unlink[0])  /* close the fd but keep the structure around for unlink */
738     {
739         if (fd->unix_fd != -1) close( fd->unix_fd );
740         fd->unix_fd = -1;
741         list_add_head( &inode->closed, &fd->entry );
742     }
743     else  /* no locks on this inode and no unlink, get rid of the fd */
744     {
745         if (fd->unix_fd != -1) close( fd->unix_fd );
746         free( fd );
747     }
748 }
749
750
751 /****************************************************************/
752 /* file lock functions */
753
754 static void file_lock_dump( struct object *obj, int verbose )
755 {
756     struct file_lock *lock = (struct file_lock *)obj;
757     fprintf( stderr, "Lock %s fd=%p proc=%p start=",
758              lock->shared ? "shared" : "excl", lock->fd, lock->process );
759     DUMP_LONG_LONG( lock->start );
760     fprintf( stderr, " end=" );
761     DUMP_LONG_LONG( lock->end );
762     fprintf( stderr, "\n" );
763 }
764
765 static int file_lock_signaled( struct object *obj, struct thread *thread )
766 {
767     struct file_lock *lock = (struct file_lock *)obj;
768     /* lock is signaled if it has lost its owner */
769     return !lock->process;
770 }
771
772 /* set (or remove) a Unix lock if possible for the given range */
773 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
774 {
775     struct flock fl;
776
777     if (!fd->fs_locks) return 1;  /* no fs locks possible for this fd */
778     for (;;)
779     {
780         if (start == end) return 1;  /* can't set zero-byte lock */
781         if (start > max_unix_offset) return 1;  /* ignore it */
782         fl.l_type   = type;
783         fl.l_whence = SEEK_SET;
784         fl.l_start  = start;
785         if (!end || end > max_unix_offset) fl.l_len = 0;
786         else fl.l_len = end - start;
787         if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
788
789         switch(errno)
790         {
791         case EACCES:
792             /* check whether locks work at all on this file system */
793             if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
794             {
795                 set_error( STATUS_FILE_LOCK_CONFLICT );
796                 return 0;
797             }
798             /* fall through */
799         case EIO:
800         case ENOLCK:
801             /* no locking on this fs, just ignore it */
802             fd->fs_locks = 0;
803             return 1;
804         case EAGAIN:
805             set_error( STATUS_FILE_LOCK_CONFLICT );
806             return 0;
807         case EBADF:
808             /* this can happen if we try to set a write lock on a read-only file */
809             /* we just ignore that error */
810             if (fl.l_type == F_WRLCK) return 1;
811             set_error( STATUS_ACCESS_DENIED );
812             return 0;
813 #ifdef EOVERFLOW
814         case EOVERFLOW:
815 #endif
816         case EINVAL:
817             /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
818             /* in that case we shrink the limit and retry */
819             if (max_unix_offset > INT_MAX)
820             {
821                 max_unix_offset = INT_MAX;
822                 break;  /* retry */
823             }
824             /* fall through */
825         default:
826             file_set_error();
827             return 0;
828         }
829     }
830 }
831
832 /* check if interval [start;end) overlaps the lock */
833 inline static int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
834 {
835     if (lock->end && start >= lock->end) return 0;
836     if (end && lock->start >= end) return 0;
837     return 1;
838 }
839
840 /* remove Unix locks for all bytes in the specified area that are no longer locked */
841 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
842 {
843     struct hole
844     {
845         struct hole *next;
846         struct hole *prev;
847         file_pos_t   start;
848         file_pos_t   end;
849     } *first, *cur, *next, *buffer;
850
851     struct list *ptr;
852     int count = 0;
853
854     if (!fd->inode) return;
855     if (!fd->fs_locks) return;
856     if (start == end || start > max_unix_offset) return;
857     if (!end || end > max_unix_offset) end = max_unix_offset + 1;
858
859     /* count the number of locks overlapping the specified area */
860
861     LIST_FOR_EACH( ptr, &fd->inode->locks )
862     {
863         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
864         if (lock->start == lock->end) continue;
865         if (lock_overlaps( lock, start, end )) count++;
866     }
867
868     if (!count)  /* no locks at all, we can unlock everything */
869     {
870         set_unix_lock( fd, start, end, F_UNLCK );
871         return;
872     }
873
874     /* allocate space for the list of holes */
875     /* max. number of holes is number of locks + 1 */
876
877     if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
878     first = buffer;
879     first->next  = NULL;
880     first->prev  = NULL;
881     first->start = start;
882     first->end   = end;
883     next = first + 1;
884
885     /* build a sorted list of unlocked holes in the specified area */
886
887     LIST_FOR_EACH( ptr, &fd->inode->locks )
888     {
889         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
890         if (lock->start == lock->end) continue;
891         if (!lock_overlaps( lock, start, end )) continue;
892
893         /* go through all the holes touched by this lock */
894         for (cur = first; cur; cur = cur->next)
895         {
896             if (cur->end <= lock->start) continue; /* hole is before start of lock */
897             if (lock->end && cur->start >= lock->end) break;  /* hole is after end of lock */
898
899             /* now we know that lock is overlapping hole */
900
901             if (cur->start >= lock->start)  /* lock starts before hole, shrink from start */
902             {
903                 cur->start = lock->end;
904                 if (cur->start && cur->start < cur->end) break;  /* done with this lock */
905                 /* now hole is empty, remove it */
906                 if (cur->next) cur->next->prev = cur->prev;
907                 if (cur->prev) cur->prev->next = cur->next;
908                 else if (!(first = cur->next)) goto done;  /* no more holes at all */
909             }
910             else if (!lock->end || cur->end <= lock->end)  /* lock larger than hole, shrink from end */
911             {
912                 cur->end = lock->start;
913                 assert( cur->start < cur->end );
914             }
915             else  /* lock is in the middle of hole, split hole in two */
916             {
917                 next->prev = cur;
918                 next->next = cur->next;
919                 cur->next = next;
920                 next->start = lock->end;
921                 next->end = cur->end;
922                 cur->end = lock->start;
923                 assert( next->start < next->end );
924                 assert( cur->end < next->start );
925                 next++;
926                 break;  /* done with this lock */
927             }
928         }
929     }
930
931     /* clear Unix locks for all the holes */
932
933     for (cur = first; cur; cur = cur->next)
934         set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
935
936  done:
937     free( buffer );
938 }
939
940 /* create a new lock on a fd */
941 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
942 {
943     struct file_lock *lock;
944
945     if (!fd->inode)  /* not a regular file */
946     {
947         set_error( STATUS_INVALID_HANDLE );
948         return NULL;
949     }
950
951     if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
952     lock->shared  = shared;
953     lock->start   = start;
954     lock->end     = end;
955     lock->fd      = fd;
956     lock->process = current->process;
957
958     /* now try to set a Unix lock */
959     if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
960     {
961         release_object( lock );
962         return NULL;
963     }
964     list_add_head( &fd->locks, &lock->fd_entry );
965     list_add_head( &fd->inode->locks, &lock->inode_entry );
966     list_add_head( &lock->process->locks, &lock->proc_entry );
967     return lock;
968 }
969
970 /* remove an existing lock */
971 static void remove_lock( struct file_lock *lock, int remove_unix )
972 {
973     struct inode *inode = lock->fd->inode;
974
975     list_remove( &lock->fd_entry );
976     list_remove( &lock->inode_entry );
977     list_remove( &lock->proc_entry );
978     if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
979     if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
980     lock->process = NULL;
981     wake_up( &lock->obj, 0 );
982     release_object( lock );
983 }
984
985 /* remove all locks owned by a given process */
986 void remove_process_locks( struct process *process )
987 {
988     struct list *ptr;
989
990     while ((ptr = list_head( &process->locks )))
991     {
992         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
993         remove_lock( lock, 1 );  /* this removes it from the list */
994     }
995 }
996
997 /* remove all locks on a given fd */
998 static void remove_fd_locks( struct fd *fd )
999 {
1000     file_pos_t start = FILE_POS_T_MAX, end = 0;
1001     struct list *ptr;
1002
1003     while ((ptr = list_head( &fd->locks )))
1004     {
1005         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1006         if (lock->start < start) start = lock->start;
1007         if (!lock->end || lock->end > end) end = lock->end - 1;
1008         remove_lock( lock, 0 );
1009     }
1010     if (start < end) remove_unix_locks( fd, start, end + 1 );
1011 }
1012
1013 /* add a lock on an fd */
1014 /* returns handle to wait on */
1015 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1016 {
1017     struct list *ptr;
1018     file_pos_t end = start + count;
1019
1020     /* don't allow wrapping locks */
1021     if (end && end < start)
1022     {
1023         set_error( STATUS_INVALID_PARAMETER );
1024         return 0;
1025     }
1026
1027     /* check if another lock on that file overlaps the area */
1028     LIST_FOR_EACH( ptr, &fd->inode->locks )
1029     {
1030         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1031         if (!lock_overlaps( lock, start, end )) continue;
1032         if (lock->shared && shared) continue;
1033         /* found one */
1034         if (!wait)
1035         {
1036             set_error( STATUS_FILE_LOCK_CONFLICT );
1037             return 0;
1038         }
1039         set_error( STATUS_PENDING );
1040         return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1041     }
1042
1043     /* not found, add it */
1044     if (add_lock( fd, shared, start, end )) return 0;
1045     if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1046     {
1047         /* Unix lock conflict -> tell client to wait and retry */
1048         if (wait) set_error( STATUS_PENDING );
1049     }
1050     return 0;
1051 }
1052
1053 /* remove a lock on an fd */
1054 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1055 {
1056     struct list *ptr;
1057     file_pos_t end = start + count;
1058
1059     /* find an existing lock with the exact same parameters */
1060     LIST_FOR_EACH( ptr, &fd->locks )
1061     {
1062         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1063         if ((lock->start == start) && (lock->end == end))
1064         {
1065             remove_lock( lock, 1 );
1066             return;
1067         }
1068     }
1069     set_error( STATUS_FILE_LOCK_CONFLICT );
1070 }
1071
1072
1073 /****************************************************************/
1074 /* asynchronous operations support */
1075
1076 struct async
1077 {
1078     struct thread       *thread;
1079     void                *apc;
1080     void                *user;
1081     void                *sb;
1082     struct timeout_user *timeout;
1083     struct list          entry;
1084 };
1085
1086 /* notifies client thread of new status of its async request */
1087 /* destroys the server side of it */
1088 static void async_terminate( struct async *async, int status )
1089 {
1090     thread_queue_apc( async->thread, NULL, async->apc, APC_ASYNC_IO,
1091                       1, async->user, async->sb, (void *)status );
1092
1093     if (async->timeout) remove_timeout_user( async->timeout );
1094     async->timeout = NULL;
1095     list_remove( &async->entry );
1096     release_object( async->thread );
1097     free( async );
1098 }
1099
1100 /* cb for timeout on an async request */
1101 static void async_callback(void *private)
1102 {
1103     struct async *async = (struct async *)private;
1104
1105     /* fprintf(stderr, "async timeout out %p\n", async); */
1106     async->timeout = NULL;
1107     async_terminate( async, STATUS_TIMEOUT );
1108 }
1109
1110 /* create an async on a given queue of a fd */
1111 struct async *create_async(struct thread *thread, int* timeout, struct list *queue,
1112                            void *io_apc, void *io_user, void* io_sb)
1113 {
1114     struct async *async = mem_alloc( sizeof(struct async) );
1115
1116     if (!async) return NULL;
1117
1118     async->thread = (struct thread *)grab_object(thread);
1119     async->apc = io_apc;
1120     async->user = io_user;
1121     async->sb = io_sb;
1122
1123     list_add_tail( queue, &async->entry );
1124
1125     if (timeout)
1126     {
1127         struct timeval when;
1128
1129         gettimeofday( &when, NULL );
1130         add_timeout( &when, *timeout );
1131         async->timeout = add_timeout_user( &when, async_callback, async );
1132     }
1133     else async->timeout = NULL;
1134
1135     return async;
1136 }
1137
1138 /* terminate the async operation at the head of the queue */
1139 void async_terminate_head( struct list *queue, int status )
1140 {
1141     struct list *ptr = list_head( queue );
1142     if (ptr) async_terminate( LIST_ENTRY( ptr, struct async, entry ), status );
1143 }
1144
1145 /****************************************************************/
1146 /* file descriptor functions */
1147
1148 static void fd_dump( struct object *obj, int verbose )
1149 {
1150     struct fd *fd = (struct fd *)obj;
1151     fprintf( stderr, "Fd unix_fd=%d user=%p", fd->unix_fd, fd->user );
1152     if (fd->inode) fprintf( stderr, " inode=%p unlink='%s'", fd->inode, fd->closed->unlink );
1153     fprintf( stderr, "\n" );
1154 }
1155
1156 static void fd_destroy( struct object *obj )
1157 {
1158     struct fd *fd = (struct fd *)obj;
1159
1160     async_terminate_queue( &fd->read_q, STATUS_CANCELLED );
1161     async_terminate_queue( &fd->write_q, STATUS_CANCELLED );
1162
1163     remove_fd_locks( fd );
1164     list_remove( &fd->inode_entry );
1165     if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1166     if (fd->inode)
1167     {
1168         inode_add_closed_fd( fd->inode, fd->closed );
1169         release_object( fd->inode );
1170     }
1171     else  /* no inode, close it right away */
1172     {
1173         if (fd->unix_fd != -1) close( fd->unix_fd );
1174     }
1175 }
1176
1177 /* set the events that select waits for on this fd */
1178 void set_fd_events( struct fd *fd, int events )
1179 {
1180     int user = fd->poll_index;
1181     assert( poll_users[user] == fd );
1182
1183     set_fd_epoll_events( fd, user, events );
1184
1185     if (events == -1)  /* stop waiting on this fd completely */
1186     {
1187         pollfd[user].fd = -1;
1188         pollfd[user].events = POLLERR;
1189         pollfd[user].revents = 0;
1190     }
1191     else if (pollfd[user].fd != -1 || !pollfd[user].events)
1192     {
1193         pollfd[user].fd = fd->unix_fd;
1194         pollfd[user].events = events;
1195     }
1196 }
1197
1198 /* prepare an fd for unmounting its corresponding device */
1199 static inline void unmount_fd( struct fd *fd )
1200 {
1201     assert( fd->inode );
1202
1203     async_terminate_queue( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1204     async_terminate_queue( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1205
1206     if (fd->poll_index != -1) set_fd_events( fd, -1 );
1207
1208     if (fd->unix_fd != -1) close( fd->unix_fd );
1209
1210     fd->unix_fd = -1;
1211     fd->closed->unix_fd = -1;
1212     fd->closed->unlink[0] = 0;
1213
1214     /* stop using Unix locks on this fd (existing locks have been removed by close) */
1215     fd->fs_locks = 0;
1216 }
1217
1218 /* allocate an fd object, without setting the unix fd yet */
1219 struct fd *alloc_fd( const struct fd_ops *fd_user_ops, struct object *user )
1220 {
1221     struct fd *fd = alloc_object( &fd_ops );
1222
1223     if (!fd) return NULL;
1224
1225     fd->fd_ops     = fd_user_ops;
1226     fd->user       = user;
1227     fd->inode      = NULL;
1228     fd->closed     = NULL;
1229     fd->access     = 0;
1230     fd->sharing    = 0;
1231     fd->unix_fd    = -1;
1232     fd->fs_locks   = 1;
1233     fd->poll_index = -1;
1234     list_init( &fd->inode_entry );
1235     list_init( &fd->locks );
1236     list_init( &fd->read_q );
1237     list_init( &fd->write_q );
1238
1239     if ((fd->poll_index = add_poll_user( fd )) == -1)
1240     {
1241         release_object( fd );
1242         return NULL;
1243     }
1244     return fd;
1245 }
1246
1247 /* check if the desired access is possible without violating */
1248 /* the sharing mode of other opens of the same file */
1249 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
1250 {
1251     unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1252     unsigned int existing_access = 0;
1253     int unlink = 0;
1254     struct list *ptr;
1255
1256     /* if access mode is 0, sharing mode is ignored */
1257     if (!access) sharing = existing_sharing;
1258     fd->access = access;
1259     fd->sharing = sharing;
1260
1261     LIST_FOR_EACH( ptr, &fd->inode->open )
1262     {
1263         struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1264         if (fd_ptr != fd)
1265         {
1266             existing_sharing &= fd_ptr->sharing;
1267             existing_access  |= fd_ptr->access;
1268             if (fd_ptr->closed->unlink[0]) unlink = 1;
1269         }
1270     }
1271
1272     if ((access & GENERIC_READ) && !(existing_sharing & FILE_SHARE_READ)) return 0;
1273     if ((access & GENERIC_WRITE) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1274     if ((existing_access & GENERIC_READ) && !(sharing & FILE_SHARE_READ)) return 0;
1275     if ((existing_access & GENERIC_WRITE) && !(sharing & FILE_SHARE_WRITE)) return 0;
1276     if (fd->closed->unlink[0] && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1277     if (unlink && !(sharing & FILE_SHARE_DELETE)) return 0;
1278     return 1;
1279 }
1280
1281 /* open() wrapper using a struct fd */
1282 /* the fd must have been created with alloc_fd */
1283 /* on error the fd object is released */
1284 struct fd *open_fd( struct fd *fd, const char *name, int flags, mode_t *mode,
1285                     unsigned int access, unsigned int sharing, unsigned int options )
1286 {
1287     struct stat st;
1288     struct closed_fd *closed_fd;
1289     const char *unlink_name = "";
1290
1291     assert( fd->unix_fd == -1 );
1292
1293     if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1294     if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1295     {
1296         release_object( fd );
1297         return NULL;
1298     }
1299     /* create the directory if needed */
1300     if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1301     {
1302         if (mkdir( name, 0777 ) == -1)
1303         {
1304             if (errno != EEXIST || (flags & O_EXCL))
1305             {
1306                 file_set_error();
1307                 release_object( fd );
1308                 free( closed_fd );
1309                 return NULL;
1310             }
1311         }
1312         flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1313     }
1314     if ((fd->unix_fd = open( name, flags & ~O_TRUNC, *mode )) == -1)
1315     {
1316         file_set_error();
1317         release_object( fd );
1318         free( closed_fd );
1319         return NULL;
1320     }
1321     closed_fd->unix_fd = fd->unix_fd;
1322     closed_fd->unlink[0] = 0;
1323     fstat( fd->unix_fd, &st );
1324     *mode = st.st_mode;
1325
1326     /* only bother with an inode for normal files and directories */
1327     if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1328     {
1329         struct inode *inode = get_inode( st.st_dev, st.st_ino );
1330
1331         if (!inode)
1332         {
1333             /* we can close the fd because there are no others open on the same file,
1334              * otherwise we wouldn't have failed to allocate a new inode
1335              */
1336             goto error;
1337         }
1338         fd->inode = inode;
1339         fd->closed = closed_fd;
1340         list_add_head( &inode->open, &fd->inode_entry );
1341
1342         /* check directory options */
1343         if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1344         {
1345             release_object( fd );
1346             set_error( STATUS_NOT_A_DIRECTORY );
1347             return NULL;
1348         }
1349         if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1350         {
1351             release_object( fd );
1352             set_error( STATUS_FILE_IS_A_DIRECTORY );
1353             return NULL;
1354         }
1355         if (!check_sharing( fd, access, sharing ))
1356         {
1357             release_object( fd );
1358             set_error( STATUS_SHARING_VIOLATION );
1359             return NULL;
1360         }
1361         strcpy( closed_fd->unlink, unlink_name );
1362         if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1363     }
1364     else  /* special file */
1365     {
1366         if (options & FILE_DIRECTORY_FILE)
1367         {
1368             set_error( STATUS_NOT_A_DIRECTORY );
1369             goto error;
1370         }
1371         if (unlink_name[0])  /* we can't unlink special files */
1372         {
1373             set_error( STATUS_INVALID_PARAMETER );
1374             goto error;
1375         }
1376         free( closed_fd );
1377     }
1378     return fd;
1379
1380 error:
1381     release_object( fd );
1382     free( closed_fd );
1383     return NULL;
1384 }
1385
1386 /* create an fd for an anonymous file */
1387 /* if the function fails the unix fd is closed */
1388 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user )
1389 {
1390     struct fd *fd = alloc_fd( fd_user_ops, user );
1391
1392     if (fd)
1393     {
1394         fd->unix_fd = unix_fd;
1395         return fd;
1396     }
1397     close( unix_fd );
1398     return NULL;
1399 }
1400
1401 /* retrieve the object that is using an fd */
1402 void *get_fd_user( struct fd *fd )
1403 {
1404     return fd->user;
1405 }
1406
1407 /* retrieve the unix fd for an object */
1408 int get_unix_fd( struct fd *fd )
1409 {
1410     if (fd->unix_fd == -1) set_error( STATUS_VOLUME_DISMOUNTED );
1411     return fd->unix_fd;
1412 }
1413
1414 /* check if two file descriptors point to the same file */
1415 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1416 {
1417     return fd1->inode == fd2->inode;
1418 }
1419
1420 /* callback for event happening in the main poll() loop */
1421 void fd_poll_event( struct fd *fd, int event )
1422 {
1423     return fd->fd_ops->poll_event( fd, event );
1424 }
1425
1426 /* check if events are pending and if yes return which one(s) */
1427 int check_fd_events( struct fd *fd, int events )
1428 {
1429     struct pollfd pfd;
1430
1431     if (fd->unix_fd == -1) return POLLERR;
1432
1433     pfd.fd     = fd->unix_fd;
1434     pfd.events = events;
1435     if (poll( &pfd, 1, 0 ) <= 0) return 0;
1436     return pfd.revents;
1437 }
1438
1439 /* default add_queue() routine for objects that poll() on an fd */
1440 int default_fd_add_queue( struct object *obj, struct wait_queue_entry *entry )
1441 {
1442     struct fd *fd = get_obj_fd( obj );
1443
1444     if (!fd) return 0;
1445     if (list_empty( &obj->wait_queue ))  /* first on the queue */
1446         set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1447     add_queue( obj, entry );
1448     release_object( fd );
1449     return 1;
1450 }
1451
1452 /* default remove_queue() routine for objects that poll() on an fd */
1453 void default_fd_remove_queue( struct object *obj, struct wait_queue_entry *entry )
1454 {
1455     struct fd *fd = get_obj_fd( obj );
1456
1457     grab_object( obj );
1458     remove_queue( obj, entry );
1459     if (list_empty( &obj->wait_queue ))  /* last on the queue is gone */
1460         set_fd_events( fd, 0 );
1461     release_object( obj );
1462     release_object( fd );
1463 }
1464
1465 /* default signaled() routine for objects that poll() on an fd */
1466 int default_fd_signaled( struct object *obj, struct thread *thread )
1467 {
1468     int events, ret;
1469     struct fd *fd = get_obj_fd( obj );
1470
1471     if (fd->inode) return 1;  /* regular files are always signaled */
1472
1473     events = fd->fd_ops->get_poll_events( fd );
1474     ret = check_fd_events( fd, events ) != 0;
1475
1476     if (ret)
1477         set_fd_events( fd, 0 ); /* stop waiting on select() if we are signaled */
1478     else if (!list_empty( &obj->wait_queue ))
1479         set_fd_events( fd, events ); /* restart waiting on poll() if we are no longer signaled */
1480
1481     release_object( fd );
1482     return ret;
1483 }
1484
1485 int default_fd_get_poll_events( struct fd *fd )
1486 {
1487     int events = 0;
1488
1489     if (!list_empty( &fd->read_q ))
1490         events |= POLLIN;
1491     if (!list_empty( &fd->write_q ))
1492         events |= POLLOUT;
1493
1494     return events;
1495 }
1496
1497 /* default handler for poll() events */
1498 void default_poll_event( struct fd *fd, int event )
1499 {
1500     if (!list_empty( &fd->read_q ) && (POLLIN & event) )
1501     {
1502         async_terminate_head( &fd->read_q, STATUS_ALERTED );
1503         return;
1504     }
1505     if (!list_empty( &fd->write_q ) && (POLLOUT & event) )
1506     {
1507         async_terminate_head( &fd->write_q, STATUS_ALERTED );
1508         return;
1509     }
1510
1511     /* if an error occurred, stop polling this fd to avoid busy-looping */
1512     if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1513     wake_up( fd->user, 0 );
1514 }
1515
1516 void fd_queue_async_timeout( struct fd *fd, void *apc, void *user, void *io_sb, int type, int count, int *timeout )
1517 {
1518     struct list *queue;
1519     int events;
1520
1521     if (!(fd->fd_ops->get_file_info( fd ) & (FD_FLAG_OVERLAPPED|FD_FLAG_TIMEOUT)))
1522     {
1523         set_error( STATUS_INVALID_HANDLE );
1524         return;
1525     }
1526
1527     switch (type)
1528     {
1529     case ASYNC_TYPE_READ:
1530         queue = &fd->read_q;
1531         break;
1532     case ASYNC_TYPE_WRITE:
1533         queue = &fd->write_q;
1534         break;
1535     default:
1536         set_error( STATUS_INVALID_PARAMETER );
1537         return;
1538     }
1539
1540     if (!create_async( current, timeout, queue, apc, user, io_sb ))
1541         return;
1542
1543     /* Check if the new pending request can be served immediately */
1544     events = check_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1545     if (events) fd->fd_ops->poll_event( fd, events );
1546
1547     set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1548 }
1549
1550 void default_fd_queue_async( struct fd *fd, void *apc, void *user, void *io_sb, int type, int count )
1551 {
1552     fd_queue_async_timeout( fd, apc, user, io_sb, type, count, NULL );
1553 }
1554
1555 void default_fd_cancel_async( struct fd *fd )
1556 {
1557     async_terminate_queue( &fd->read_q, STATUS_CANCELLED );
1558     async_terminate_queue( &fd->write_q, STATUS_CANCELLED );
1559 }
1560
1561 /* default flush() routine */
1562 int no_flush( struct fd *fd, struct event **event )
1563 {
1564     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1565     return 0;
1566 }
1567
1568 /* default get_file_info() routine */
1569 int no_get_file_info( struct fd *fd )
1570 {
1571     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1572     return 0;
1573 }
1574
1575 /* default queue_async() routine */
1576 void no_queue_async( struct fd *fd, void* apc, void* user, void* io_sb, 
1577                      int type, int count)
1578 {
1579     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1580 }
1581
1582 /* default cancel_async() routine */
1583 void no_cancel_async( struct fd *fd )
1584 {
1585     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1586 }
1587
1588 /* close all Unix file descriptors on a device to allow unmounting it */
1589 static void unmount_device( struct fd *device_fd )
1590 {
1591     unsigned int i;
1592     struct stat st;
1593     struct device *device;
1594     struct inode *inode;
1595     struct fd *fd;
1596
1597     if (device_fd->unix_fd == -1 || fstat( device_fd->unix_fd, &st ) == -1 || !S_ISBLK( st.st_mode ))
1598     {
1599         set_error( STATUS_INVALID_PARAMETER );
1600         return;
1601     }
1602
1603     if (!(device = get_device( st.st_rdev, 0 ))) return;
1604
1605     for (i = 0; i < INODE_HASH_SIZE; i++)
1606     {
1607         LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
1608         {
1609             LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
1610             {
1611                 unmount_fd( fd );
1612             }
1613             inode_close_pending( inode, 0 );
1614         }
1615     }
1616     /* remove it from the hash table */
1617     list_remove( &device->entry );
1618     list_init( &device->entry );
1619     release_object( device );
1620 }
1621
1622 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1623 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1624                                      unsigned int access )
1625 {
1626     struct fd *fd = NULL;
1627     struct object *obj;
1628
1629     if ((obj = get_handle_obj( process, handle, access, NULL )))
1630     {
1631         fd = get_obj_fd( obj );
1632         release_object( obj );
1633     }
1634     return fd;
1635 }
1636
1637 /* flush a file buffers */
1638 DECL_HANDLER(flush_file)
1639 {
1640     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1641     struct event * event = NULL;
1642
1643     if (fd)
1644     {
1645         fd->fd_ops->flush( fd, &event );
1646         if ( event )
1647         {
1648             reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1649         }
1650         release_object( fd );
1651     }
1652 }
1653
1654 /* get a Unix fd to access a file */
1655 DECL_HANDLER(get_handle_fd)
1656 {
1657     struct fd *fd;
1658
1659     reply->fd = -1;
1660
1661     if ((fd = get_handle_fd_obj( current->process, req->handle, req->access )))
1662     {
1663         int unix_fd = get_unix_fd( fd );
1664         if (unix_fd != -1)
1665         {
1666             int cached_fd = get_handle_unix_fd( current->process, req->handle, req->access );
1667             if (cached_fd != -1) reply->fd = cached_fd;
1668             else if (!get_error()) send_client_fd( current->process, unix_fd, req->handle );
1669         }
1670         if (fd->inode) reply->removable = fd->inode->device->removable;
1671         reply->flags = fd->fd_ops->get_file_info( fd );
1672         release_object( fd );
1673     }
1674 }
1675
1676 /* set the cached file descriptor of a handle */
1677 DECL_HANDLER(set_handle_fd)
1678 {
1679     struct fd *fd;
1680
1681     reply->cur_fd = -1;
1682     if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
1683     {
1684         struct device *device = fd->inode ? fd->inode->device : NULL;
1685
1686         if (device && device->removable == -1) device->removable = req->removable;
1687
1688         /* only cache the fd on non-removable devices */
1689         if (!device || !device->removable)
1690             reply->cur_fd = set_handle_unix_fd( current->process, req->handle, req->fd );
1691         release_object( fd );
1692     }
1693 }
1694
1695 /* get ready to unmount a Unix device */
1696 DECL_HANDLER(unmount_device)
1697 {
1698     struct fd *fd;
1699
1700     if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
1701     {
1702         unmount_device( fd );
1703         release_object( fd );
1704     }
1705 }
1706
1707 /* create / reschedule an async I/O */
1708 DECL_HANDLER(register_async)
1709 {
1710     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1711
1712     /*
1713      * The queue_async method must do the following:
1714      *
1715      * 1. Get the async_queue for the request of given type.
1716      * 2. Create a new asynchronous request for the selected queue
1717      * 3. Carry out any operations necessary to adjust the object's poll events
1718      *    Usually: set_elect_events (obj, obj->ops->get_poll_events()).
1719      * 4. When the async request is triggered, then send back (with a proper APC)
1720      *    the trigger (STATUS_ALERTED) to the thread that posted the request. 
1721      *    async_destroy() is to be called: it will both notify the sender about
1722      *    the trigger and destroy the request by itself
1723      * See also the implementations in file.c, serial.c, and sock.c.
1724      */
1725
1726     if (fd)
1727     {
1728         fd->fd_ops->queue_async( fd, req->io_apc, req->io_user, req->io_sb, 
1729                                  req->type, req->count );
1730         release_object( fd );
1731     }
1732 }
1733
1734 /* cancels all async I/O */
1735 DECL_HANDLER(cancel_async)
1736 {
1737     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1738     if (fd)
1739     {
1740         /* Note: we don't kill the queued APC_ASYNC_IO on this thread because
1741          * NtCancelIoFile() will force the pending APC to be run. Since, 
1742          * Windows only guarantees that the current thread will have no async 
1743          * operation on the current fd when NtCancelIoFile returns, this shall
1744          * do the work.
1745          */
1746         fd->fd_ops->cancel_async( fd );
1747         release_object( fd );
1748     }        
1749 }