Taking into account wavemap and midimap there can be up to 8 output
[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
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <signal.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #ifdef HAVE_SYS_POLL_H
34 #include <sys/poll.h>
35 #endif
36 #include <sys/stat.h>
37 #include <sys/time.h>
38 #include <sys/types.h>
39 #include <unistd.h>
40
41 #include "object.h"
42 #include "file.h"
43 #include "handle.h"
44 #include "process.h"
45 #include "request.h"
46
47 #include "winbase.h"
48 #include "winreg.h"
49 #include "winternl.h"
50
51 /* Because of the stupid Posix locking semantics, we need to keep
52  * track of all file descriptors referencing a given file, and not
53  * close a single one until all the locks are gone (sigh).
54  */
55
56 /* file descriptor object */
57
58 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
59 struct closed_fd
60 {
61     struct list entry;       /* entry in inode closed list */
62     int         fd;          /* the unix file descriptor */
63     char        unlink[1];   /* name to unlink on close (if any) */
64 };
65
66 struct fd
67 {
68     struct object        obj;         /* object header */
69     const struct fd_ops *fd_ops;      /* file descriptor operations */
70     struct inode        *inode;       /* inode that this fd belongs to */
71     struct list          inode_entry; /* entry in inode fd list */
72     struct closed_fd    *closed;      /* structure to store the unix fd at destroy time */
73     struct object       *user;        /* object using this file descriptor */
74     struct list          locks;       /* list of locks on this fd */
75     unsigned int         access;      /* file access (GENERIC_READ/WRITE) */
76     unsigned int         sharing;     /* file sharing mode */
77     int                  unix_fd;     /* unix file descriptor */
78     int                  fs_locks;    /* can we use filesystem locks for this fd? */
79     int                  poll_index;  /* index of fd in poll array */
80 };
81
82 static void fd_dump( struct object *obj, int verbose );
83 static void fd_destroy( struct object *obj );
84
85 static const struct object_ops fd_ops =
86 {
87     sizeof(struct fd),        /* size */
88     fd_dump,                  /* dump */
89     no_add_queue,             /* add_queue */
90     NULL,                     /* remove_queue */
91     NULL,                     /* signaled */
92     NULL,                     /* satisfied */
93     no_get_fd,                /* get_fd */
94     fd_destroy                /* destroy */
95 };
96
97 /* inode object */
98
99 struct inode
100 {
101     struct object       obj;        /* object header */
102     struct list         entry;      /* inode hash list entry */
103     unsigned int        hash;       /* hashing code */
104     dev_t               dev;        /* device number */
105     ino_t               ino;        /* inode number */
106     struct list         open;       /* list of open file descriptors */
107     struct list         locks;      /* list of file locks */
108     struct list         closed;     /* list of file descriptors to close at destroy time */
109 };
110
111 static void inode_dump( struct object *obj, int verbose );
112 static void inode_destroy( struct object *obj );
113
114 static const struct object_ops inode_ops =
115 {
116     sizeof(struct inode),     /* size */
117     inode_dump,               /* dump */
118     no_add_queue,             /* add_queue */
119     NULL,                     /* remove_queue */
120     NULL,                     /* signaled */
121     NULL,                     /* satisfied */
122     no_get_fd,                /* get_fd */
123     inode_destroy             /* destroy */
124 };
125
126 /* file lock object */
127
128 struct file_lock
129 {
130     struct object       obj;         /* object header */
131     struct fd          *fd;          /* fd owning this lock */
132     struct list         fd_entry;    /* entry in list of locks on a given fd */
133     struct list         inode_entry; /* entry in inode list of locks */
134     int                 shared;      /* shared lock? */
135     file_pos_t          start;       /* locked region is interval [start;end) */
136     file_pos_t          end;
137     struct process     *process;     /* process owning this lock */
138     struct list         proc_entry;  /* entry in list of locks owned by the process */
139 };
140
141 static void file_lock_dump( struct object *obj, int verbose );
142 static int file_lock_signaled( struct object *obj, struct thread *thread );
143
144 static const struct object_ops file_lock_ops =
145 {
146     sizeof(struct file_lock),   /* size */
147     file_lock_dump,             /* dump */
148     add_queue,                  /* add_queue */
149     remove_queue,               /* remove_queue */
150     file_lock_signaled,         /* signaled */
151     no_satisfied,               /* satisfied */
152     no_get_fd,                  /* get_fd */
153     no_destroy                  /* destroy */
154 };
155
156
157 #define OFF_T_MAX       (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
158 #define FILE_POS_T_MAX  (~(file_pos_t)0)
159
160 static file_pos_t max_unix_offset = OFF_T_MAX;
161
162 #define DUMP_LONG_LONG(val) do { \
163     if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
164         fprintf( stderr, "%lx%08lx", (unsigned long)((val) >> 32), (unsigned long)(val) ); \
165     else \
166         fprintf( stderr, "%lx", (unsigned long)(val) ); \
167   } while (0)
168
169
170
171 /****************************************************************/
172 /* timeouts support */
173
174 struct timeout_user
175 {
176     struct timeout_user  *next;       /* next in sorted timeout list */
177     struct timeout_user  *prev;       /* prev in sorted timeout list */
178     struct timeval        when;       /* timeout expiry (absolute time) */
179     timeout_callback      callback;   /* callback function */
180     void                 *private;    /* callback private data */
181 };
182
183 static struct timeout_user *timeout_head;   /* sorted timeouts list head */
184 static struct timeout_user *timeout_tail;   /* sorted timeouts list tail */
185
186 /* add a timeout user */
187 struct timeout_user *add_timeout_user( struct timeval *when, timeout_callback func, void *private )
188 {
189     struct timeout_user *user;
190     struct timeout_user *pos;
191
192     if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
193     user->when     = *when;
194     user->callback = func;
195     user->private  = private;
196
197     /* Now insert it in the linked list */
198
199     for (pos = timeout_head; pos; pos = pos->next)
200         if (!time_before( &pos->when, when )) break;
201
202     if (pos)  /* insert it before 'pos' */
203     {
204         if ((user->prev = pos->prev)) user->prev->next = user;
205         else timeout_head = user;
206         user->next = pos;
207         pos->prev = user;
208     }
209     else  /* insert it at the tail */
210     {
211         user->next = NULL;
212         if (timeout_tail) timeout_tail->next = user;
213         else timeout_head = user;
214         user->prev = timeout_tail;
215         timeout_tail = user;
216     }
217     return user;
218 }
219
220 /* remove a timeout user */
221 void remove_timeout_user( struct timeout_user *user )
222 {
223     if (user->next) user->next->prev = user->prev;
224     else timeout_tail = user->prev;
225     if (user->prev) user->prev->next = user->next;
226     else timeout_head = user->next;
227     free( user );
228 }
229
230 /* add a timeout in milliseconds to an absolute time */
231 void add_timeout( struct timeval *when, int timeout )
232 {
233     if (timeout)
234     {
235         long sec = timeout / 1000;
236         if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
237         {
238             when->tv_usec -= 1000000;
239             when->tv_sec++;
240         }
241         when->tv_sec += sec;
242     }
243 }
244
245 /* handle the next expired timeout */
246 inline static void handle_timeout(void)
247 {
248     struct timeout_user *user = timeout_head;
249     timeout_head = user->next;
250     if (user->next) user->next->prev = user->prev;
251     else timeout_tail = user->prev;
252     user->callback( user->private );
253     free( user );
254 }
255
256
257 /****************************************************************/
258 /* poll support */
259
260 static struct fd **poll_users;              /* users array */
261 static struct pollfd *pollfd;               /* poll fd array */
262 static int nb_users;                        /* count of array entries actually in use */
263 static int active_users;                    /* current number of active users */
264 static int allocated_users;                 /* count of allocated entries in the array */
265 static struct fd **freelist;                /* list of free entries in the array */
266
267 /* add a user in the poll array and return its index, or -1 on failure */
268 static int add_poll_user( struct fd *fd )
269 {
270     int ret;
271     if (freelist)
272     {
273         ret = freelist - poll_users;
274         freelist = (struct fd **)poll_users[ret];
275     }
276     else
277     {
278         if (nb_users == allocated_users)
279         {
280             struct fd **newusers;
281             struct pollfd *newpoll;
282             int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
283             if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
284             if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
285             {
286                 if (allocated_users)
287                     poll_users = newusers;
288                 else
289                     free( newusers );
290                 return -1;
291             }
292             poll_users = newusers;
293             pollfd = newpoll;
294             allocated_users = new_count;
295         }
296         ret = nb_users++;
297     }
298     pollfd[ret].fd = -1;
299     pollfd[ret].events = 0;
300     pollfd[ret].revents = 0;
301     poll_users[ret] = fd;
302     active_users++;
303     return ret;
304 }
305
306 /* remove a user from the poll list */
307 static void remove_poll_user( struct fd *fd, int user )
308 {
309     assert( user >= 0 );
310     assert( poll_users[user] == fd );
311     pollfd[user].fd = -1;
312     pollfd[user].events = 0;
313     pollfd[user].revents = 0;
314     poll_users[user] = (struct fd *)freelist;
315     freelist = &poll_users[user];
316     active_users--;
317 }
318
319
320 /* server main poll() loop */
321 void main_loop(void)
322 {
323     int ret;
324
325     while (active_users)
326     {
327         long diff = -1;
328         if (timeout_head)
329         {
330             struct timeval now;
331             gettimeofday( &now, NULL );
332             while (timeout_head)
333             {
334                 if (!time_before( &now, &timeout_head->when )) handle_timeout();
335                 else
336                 {
337                     diff = (timeout_head->when.tv_sec - now.tv_sec) * 1000
338                             + (timeout_head->when.tv_usec - now.tv_usec) / 1000;
339                     break;
340                 }
341             }
342             if (!active_users) break;  /* last user removed by a timeout */
343         }
344         ret = poll( pollfd, nb_users, diff );
345         if (ret > 0)
346         {
347             int i;
348             for (i = 0; i < nb_users; i++)
349             {
350                 if (pollfd[i].revents)
351                 {
352                     fd_poll_event( poll_users[i], pollfd[i].revents );
353                     if (!--ret) break;
354                 }
355             }
356         }
357     }
358 }
359
360
361 /****************************************************************/
362 /* inode functions */
363
364 #define HASH_SIZE 37
365
366 static struct list inode_hash[HASH_SIZE];
367
368 /* close all pending file descriptors in the closed list */
369 static void inode_close_pending( struct inode *inode )
370 {
371     struct list *ptr = list_head( &inode->closed );
372
373     while (ptr)
374     {
375         struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
376         struct list *next = list_next( &inode->closed, ptr );
377
378         if (fd->fd != -1)
379         {
380             close( fd->fd );
381             fd->fd = -1;
382         }
383         if (!fd->unlink)  /* get rid of it unless there's an unlink pending on that file */
384         {
385             list_remove( ptr );
386             free( fd );
387         }
388         ptr = next;
389     }
390 }
391
392
393 static void inode_dump( struct object *obj, int verbose )
394 {
395     struct inode *inode = (struct inode *)obj;
396     fprintf( stderr, "Inode dev=" );
397     DUMP_LONG_LONG( inode->dev );
398     fprintf( stderr, " ino=" );
399     DUMP_LONG_LONG( inode->ino );
400     fprintf( stderr, "\n" );
401 }
402
403 static void inode_destroy( struct object *obj )
404 {
405     struct inode *inode = (struct inode *)obj;
406     struct list *ptr;
407
408     assert( list_empty(&inode->open) );
409     assert( list_empty(&inode->locks) );
410
411     list_remove( &inode->entry );
412
413     while ((ptr = list_head( &inode->closed )))
414     {
415         struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
416         list_remove( ptr );
417         if (fd->fd != -1) close( fd->fd );
418         if (fd->unlink[0])
419         {
420             /* make sure it is still the same file */
421             struct stat st;
422             if (!stat( fd->unlink, &st ) && st.st_dev == inode->dev && st.st_ino == inode->ino)
423             {
424                 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
425                 else unlink( fd->unlink );
426             }
427         }
428         free( fd );
429     }
430 }
431
432 /* retrieve the inode object for a given fd, creating it if needed */
433 static struct inode *get_inode( dev_t dev, ino_t ino )
434 {
435     struct list *ptr;
436     struct inode *inode;
437     unsigned int hash = (dev ^ ino) % HASH_SIZE;
438
439     if (inode_hash[hash].next)
440     {
441         LIST_FOR_EACH( ptr, &inode_hash[hash] )
442         {
443             inode = LIST_ENTRY( ptr, struct inode, entry );
444             if (inode->dev == dev && inode->ino == ino)
445                 return (struct inode *)grab_object( inode );
446         }
447     }
448     else list_init( &inode_hash[hash] );
449
450     /* not found, create it */
451     if ((inode = alloc_object( &inode_ops )))
452     {
453         inode->hash   = hash;
454         inode->dev    = dev;
455         inode->ino    = ino;
456         list_init( &inode->open );
457         list_init( &inode->locks );
458         list_init( &inode->closed );
459         list_add_head( &inode_hash[hash], &inode->entry );
460     }
461     return inode;
462 }
463
464 /* add fd to the indoe list of file descriptors to close */
465 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
466 {
467     if (!list_empty( &inode->locks ))
468     {
469         list_add_head( &inode->closed, &fd->entry );
470     }
471     else if (fd->unlink[0])  /* close the fd but keep the structure around for unlink */
472     {
473         close( fd->fd );
474         fd->fd = -1;
475         list_add_head( &inode->closed, &fd->entry );
476     }
477     else  /* no locks on this inode and no unlink, get rid of the fd */
478     {
479         close( fd->fd );
480         free( fd );
481     }
482 }
483
484
485 /****************************************************************/
486 /* file lock functions */
487
488 static void file_lock_dump( struct object *obj, int verbose )
489 {
490     struct file_lock *lock = (struct file_lock *)obj;
491     fprintf( stderr, "Lock %s fd=%p proc=%p start=",
492              lock->shared ? "shared" : "excl", lock->fd, lock->process );
493     DUMP_LONG_LONG( lock->start );
494     fprintf( stderr, " end=" );
495     DUMP_LONG_LONG( lock->end );
496     fprintf( stderr, "\n" );
497 }
498
499 static int file_lock_signaled( struct object *obj, struct thread *thread )
500 {
501     struct file_lock *lock = (struct file_lock *)obj;
502     /* lock is signaled if it has lost its owner */
503     return !lock->process;
504 }
505
506 /* set (or remove) a Unix lock if possible for the given range */
507 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
508 {
509     struct flock fl;
510
511     if (!fd->fs_locks) return 1;  /* no fs locks possible for this fd */
512     for (;;)
513     {
514         if (start == end) return 1;  /* can't set zero-byte lock */
515         if (start > max_unix_offset) return 1;  /* ignore it */
516         fl.l_type   = type;
517         fl.l_whence = SEEK_SET;
518         fl.l_start  = start;
519         if (!end || end > max_unix_offset) fl.l_len = 0;
520         else fl.l_len = end - start;
521         if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
522
523         switch(errno)
524         {
525         case EACCES:
526             /* check whether locks work at all on this file system */
527             if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
528             {
529                 set_error( STATUS_FILE_LOCK_CONFLICT );
530                 return 0;
531             }
532             /* fall through */
533         case EIO:
534         case ENOLCK:
535             /* no locking on this fs, just ignore it */
536             fd->fs_locks = 0;
537             return 1;
538         case EAGAIN:
539             set_error( STATUS_FILE_LOCK_CONFLICT );
540             return 0;
541         case EBADF:
542             /* this can happen if we try to set a write lock on a read-only file */
543             /* we just ignore that error */
544             if (fl.l_type == F_WRLCK) return 1;
545             set_error( STATUS_ACCESS_DENIED );
546             return 0;
547 #ifdef EOVERFLOW
548         case EOVERFLOW:
549 #endif
550         case EINVAL:
551             /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
552             /* in that case we shrink the limit and retry */
553             if (max_unix_offset > INT_MAX)
554             {
555                 max_unix_offset = INT_MAX;
556                 break;  /* retry */
557             }
558             /* fall through */
559         default:
560             file_set_error();
561             return 0;
562         }
563     }
564 }
565
566 /* check if interval [start;end) overlaps the lock */
567 inline static int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
568 {
569     if (lock->end && start >= lock->end) return 0;
570     if (end && lock->start >= end) return 0;
571     return 1;
572 }
573
574 /* remove Unix locks for all bytes in the specified area that are no longer locked */
575 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
576 {
577     struct hole
578     {
579         struct hole *next;
580         struct hole *prev;
581         file_pos_t   start;
582         file_pos_t   end;
583     } *first, *cur, *next, *buffer;
584
585     struct list *ptr;
586     int count = 0;
587
588     if (!fd->inode) return;
589     if (!fd->fs_locks) return;
590     if (start == end || start > max_unix_offset) return;
591     if (!end || end > max_unix_offset) end = max_unix_offset + 1;
592
593     /* count the number of locks overlapping the specified area */
594
595     LIST_FOR_EACH( ptr, &fd->inode->locks )
596     {
597         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
598         if (lock->start == lock->end) continue;
599         if (lock_overlaps( lock, start, end )) count++;
600     }
601
602     if (!count)  /* no locks at all, we can unlock everything */
603     {
604         set_unix_lock( fd, start, end, F_UNLCK );
605         return;
606     }
607
608     /* allocate space for the list of holes */
609     /* max. number of holes is number of locks + 1 */
610
611     if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
612     first = buffer;
613     first->next  = NULL;
614     first->prev  = NULL;
615     first->start = start;
616     first->end   = end;
617     next = first + 1;
618
619     /* build a sorted list of unlocked holes in the specified area */
620
621     LIST_FOR_EACH( ptr, &fd->inode->locks )
622     {
623         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
624         if (lock->start == lock->end) continue;
625         if (!lock_overlaps( lock, start, end )) continue;
626
627         /* go through all the holes touched by this lock */
628         for (cur = first; cur; cur = cur->next)
629         {
630             if (cur->end <= lock->start) continue; /* hole is before start of lock */
631             if (lock->end && cur->start >= lock->end) break;  /* hole is after end of lock */
632
633             /* now we know that lock is overlapping hole */
634
635             if (cur->start >= lock->start)  /* lock starts before hole, shrink from start */
636             {
637                 cur->start = lock->end;
638                 if (cur->start && cur->start < cur->end) break;  /* done with this lock */
639                 /* now hole is empty, remove it */
640                 if (cur->next) cur->next->prev = cur->prev;
641                 if (cur->prev) cur->prev->next = cur->next;
642                 else if (!(first = cur->next)) goto done;  /* no more holes at all */
643             }
644             else if (!lock->end || cur->end <= lock->end)  /* lock larger than hole, shrink from end */
645             {
646                 cur->end = lock->start;
647                 assert( cur->start < cur->end );
648             }
649             else  /* lock is in the middle of hole, split hole in two */
650             {
651                 next->prev = cur;
652                 next->next = cur->next;
653                 cur->next = next;
654                 next->start = lock->end;
655                 next->end = cur->end;
656                 cur->end = lock->start;
657                 assert( next->start < next->end );
658                 assert( cur->end < next->start );
659                 next++;
660                 break;  /* done with this lock */
661             }
662         }
663     }
664
665     /* clear Unix locks for all the holes */
666
667     for (cur = first; cur; cur = cur->next)
668         set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
669
670  done:
671     free( buffer );
672 }
673
674 /* create a new lock on a fd */
675 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
676 {
677     struct file_lock *lock;
678
679     if (!fd->inode)  /* not a regular file */
680     {
681         set_error( STATUS_INVALID_HANDLE );
682         return NULL;
683     }
684
685     if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
686     lock->shared  = shared;
687     lock->start   = start;
688     lock->end     = end;
689     lock->fd      = fd;
690     lock->process = current->process;
691
692     /* now try to set a Unix lock */
693     if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
694     {
695         release_object( lock );
696         return NULL;
697     }
698     list_add_head( &fd->locks, &lock->fd_entry );
699     list_add_head( &fd->inode->locks, &lock->inode_entry );
700     list_add_head( &lock->process->locks, &lock->proc_entry );
701     return lock;
702 }
703
704 /* remove an existing lock */
705 static void remove_lock( struct file_lock *lock, int remove_unix )
706 {
707     struct inode *inode = lock->fd->inode;
708
709     list_remove( &lock->fd_entry );
710     list_remove( &lock->inode_entry );
711     list_remove( &lock->proc_entry );
712     if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
713     if (list_empty( &inode->locks )) inode_close_pending( inode );
714     lock->process = NULL;
715     wake_up( &lock->obj, 0 );
716     release_object( lock );
717 }
718
719 /* remove all locks owned by a given process */
720 void remove_process_locks( struct process *process )
721 {
722     struct list *ptr;
723
724     while ((ptr = list_head( &process->locks )))
725     {
726         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
727         remove_lock( lock, 1 );  /* this removes it from the list */
728     }
729 }
730
731 /* remove all locks on a given fd */
732 static void remove_fd_locks( struct fd *fd )
733 {
734     file_pos_t start = FILE_POS_T_MAX, end = 0;
735     struct list *ptr;
736
737     while ((ptr = list_head( &fd->locks )))
738     {
739         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
740         if (lock->start < start) start = lock->start;
741         if (!lock->end || lock->end > end) end = lock->end - 1;
742         remove_lock( lock, 0 );
743     }
744     if (start < end) remove_unix_locks( fd, start, end + 1 );
745 }
746
747 /* add a lock on an fd */
748 /* returns handle to wait on */
749 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
750 {
751     struct list *ptr;
752     file_pos_t end = start + count;
753
754     /* don't allow wrapping locks */
755     if (end && end < start)
756     {
757         set_error( STATUS_INVALID_PARAMETER );
758         return 0;
759     }
760
761     /* check if another lock on that file overlaps the area */
762     LIST_FOR_EACH( ptr, &fd->inode->locks )
763     {
764         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
765         if (!lock_overlaps( lock, start, end )) continue;
766         if (lock->shared && shared) continue;
767         /* found one */
768         if (!wait)
769         {
770             set_error( STATUS_FILE_LOCK_CONFLICT );
771             return 0;
772         }
773         set_error( STATUS_PENDING );
774         return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
775     }
776
777     /* not found, add it */
778     if (add_lock( fd, shared, start, end )) return 0;
779     if (get_error() == STATUS_FILE_LOCK_CONFLICT)
780     {
781         /* Unix lock conflict -> tell client to wait and retry */
782         if (wait) set_error( STATUS_PENDING );
783     }
784     return 0;
785 }
786
787 /* remove a lock on an fd */
788 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
789 {
790     struct list *ptr;
791     file_pos_t end = start + count;
792
793     /* find an existing lock with the exact same parameters */
794     LIST_FOR_EACH( ptr, &fd->locks )
795     {
796         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
797         if ((lock->start == start) && (lock->end == end))
798         {
799             remove_lock( lock, 1 );
800             return;
801         }
802     }
803     set_error( STATUS_FILE_LOCK_CONFLICT );
804 }
805
806
807 /****************************************************************/
808 /* file descriptor functions */
809
810 static void fd_dump( struct object *obj, int verbose )
811 {
812     struct fd *fd = (struct fd *)obj;
813     fprintf( stderr, "Fd unix_fd=%d user=%p unlink='%s'\n",
814              fd->unix_fd, fd->user, fd->closed->unlink );
815 }
816
817 static void fd_destroy( struct object *obj )
818 {
819     struct fd *fd = (struct fd *)obj;
820
821     remove_fd_locks( fd );
822     list_remove( &fd->inode_entry );
823     if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
824     if (fd->inode)
825     {
826         inode_add_closed_fd( fd->inode, fd->closed );
827         release_object( fd->inode );
828     }
829     else  /* no inode, close it right away */
830     {
831         if (fd->unix_fd != -1) close( fd->unix_fd );
832     }
833 }
834
835 /* set the events that select waits for on this fd */
836 void set_fd_events( struct fd *fd, int events )
837 {
838     int user = fd->poll_index;
839     assert( poll_users[user] == fd );
840     if (events == -1)  /* stop waiting on this fd completely */
841     {
842         pollfd[user].fd = -1;
843         pollfd[user].events = POLLERR;
844         pollfd[user].revents = 0;
845     }
846     else if (pollfd[user].fd != -1 || !pollfd[user].events)
847     {
848         pollfd[user].fd = fd->unix_fd;
849         pollfd[user].events = events;
850     }
851 }
852
853 /* allocate an fd object, without setting the unix fd yet */
854 struct fd *alloc_fd( const struct fd_ops *fd_user_ops, struct object *user )
855 {
856     struct fd *fd = alloc_object( &fd_ops );
857
858     if (!fd) return NULL;
859
860     fd->fd_ops     = fd_user_ops;
861     fd->user       = user;
862     fd->inode      = NULL;
863     fd->closed     = NULL;
864     fd->access     = 0;
865     fd->sharing    = 0;
866     fd->unix_fd    = -1;
867     fd->fs_locks   = 1;
868     fd->poll_index = -1;
869     list_init( &fd->inode_entry );
870     list_init( &fd->locks );
871
872     if ((fd->poll_index = add_poll_user( fd )) == -1)
873     {
874         release_object( fd );
875         return NULL;
876     }
877     return fd;
878 }
879
880 /* check if the desired access is possible without violating */
881 /* the sharing mode of other opens of the same file */
882 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
883 {
884     unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
885     unsigned int existing_access = 0;
886     int unlink = 0;
887     struct list *ptr;
888
889     /* if access mode is 0, sharing mode is ignored */
890     if (!access) sharing = existing_sharing;
891     fd->access = access;
892     fd->sharing = sharing;
893
894     LIST_FOR_EACH( ptr, &fd->inode->open )
895     {
896         struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
897         if (fd_ptr != fd)
898         {
899             existing_sharing &= fd_ptr->sharing;
900             existing_access  |= fd_ptr->access;
901             if (fd_ptr->closed->unlink[0]) unlink = 1;
902         }
903     }
904
905     if ((access & GENERIC_READ) && !(existing_sharing & FILE_SHARE_READ)) return 0;
906     if ((access & GENERIC_WRITE) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
907     if ((existing_access & GENERIC_READ) && !(sharing & FILE_SHARE_READ)) return 0;
908     if ((existing_access & GENERIC_WRITE) && !(sharing & FILE_SHARE_WRITE)) return 0;
909     if (fd->closed->unlink[0] && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
910     if (unlink && !(sharing & FILE_SHARE_DELETE)) return 0;
911     return 1;
912 }
913
914 /* open() wrapper using a struct fd */
915 /* the fd must have been created with alloc_fd */
916 /* on error the fd object is released */
917 struct fd *open_fd( struct fd *fd, const char *name, int flags, mode_t *mode,
918                     unsigned int access, unsigned int sharing, unsigned int options )
919 {
920     struct stat st;
921     struct closed_fd *closed_fd;
922     const char *unlink_name = "";
923
924     assert( fd->unix_fd == -1 );
925
926     if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
927     if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
928     {
929         release_object( fd );
930         return NULL;
931     }
932     /* create the directory if needed */
933     if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
934     {
935         if (mkdir( name, 0777 ) == -1)
936         {
937             if (errno != EEXIST || (flags & O_EXCL))
938             {
939                 file_set_error();
940                 release_object( fd );
941                 free( closed_fd );
942                 return NULL;
943             }
944         }
945         flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
946     }
947     if ((fd->unix_fd = open( name, flags, *mode )) == -1)
948     {
949         file_set_error();
950         release_object( fd );
951         free( closed_fd );
952         return NULL;
953     }
954     closed_fd->fd = fd->unix_fd;
955     closed_fd->unlink[0] = 0;
956     fstat( fd->unix_fd, &st );
957     *mode = st.st_mode;
958
959     /* check directory options */
960     if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
961     {
962         set_error( STATUS_NOT_A_DIRECTORY );
963         goto error;
964     }
965     if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
966     {
967         set_error( STATUS_FILE_IS_A_DIRECTORY );
968         goto error;
969     }
970
971     /* only bother with an inode for normal files and directories */
972     if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
973     {
974         struct inode *inode = get_inode( st.st_dev, st.st_ino );
975
976         if (!inode)
977         {
978             /* we can close the fd because there are no others open on the same file,
979              * otherwise we wouldn't have failed to allocate a new inode
980              */
981             goto error;
982         }
983         fd->inode = inode;
984         fd->closed = closed_fd;
985         list_add_head( &inode->open, &fd->inode_entry );
986         if (!check_sharing( fd, access, sharing ))
987         {
988             release_object( fd );
989             set_error( STATUS_SHARING_VIOLATION );
990             return NULL;
991         }
992         strcpy( closed_fd->unlink, unlink_name );
993     }
994     else
995     {
996         if (unlink_name[0])  /* we can't unlink special files */
997         {
998             set_error( STATUS_INVALID_PARAMETER );
999             goto error;
1000         }
1001         free( closed_fd );
1002     }
1003     return fd;
1004
1005 error:
1006     release_object( fd );
1007     free( closed_fd );
1008     return NULL;
1009 }
1010
1011 /* create an fd for an anonymous file */
1012 /* if the function fails the unix fd is closed */
1013 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user )
1014 {
1015     struct fd *fd = alloc_fd( fd_user_ops, user );
1016
1017     if (fd)
1018     {
1019         fd->unix_fd = unix_fd;
1020         return fd;
1021     }
1022     close( unix_fd );
1023     return NULL;
1024 }
1025
1026 /* retrieve the object that is using an fd */
1027 void *get_fd_user( struct fd *fd )
1028 {
1029     return fd->user;
1030 }
1031
1032 /* retrieve the unix fd for an object */
1033 int get_unix_fd( struct fd *fd )
1034 {
1035     return fd->unix_fd;
1036 }
1037
1038 /* check if two file descriptors point to the same file */
1039 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1040 {
1041     return fd1->inode == fd2->inode;
1042 }
1043
1044 /* callback for event happening in the main poll() loop */
1045 void fd_poll_event( struct fd *fd, int event )
1046 {
1047     return fd->fd_ops->poll_event( fd, event );
1048 }
1049
1050 /* check if events are pending and if yes return which one(s) */
1051 int check_fd_events( struct fd *fd, int events )
1052 {
1053     struct pollfd pfd;
1054
1055     pfd.fd     = fd->unix_fd;
1056     pfd.events = events;
1057     if (poll( &pfd, 1, 0 ) <= 0) return 0;
1058     return pfd.revents;
1059 }
1060
1061 /* default add_queue() routine for objects that poll() on an fd */
1062 int default_fd_add_queue( struct object *obj, struct wait_queue_entry *entry )
1063 {
1064     struct fd *fd = get_obj_fd( obj );
1065
1066     if (!fd) return 0;
1067     if (!obj->head)  /* first on the queue */
1068         set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1069     add_queue( obj, entry );
1070     release_object( fd );
1071     return 1;
1072 }
1073
1074 /* default remove_queue() routine for objects that poll() on an fd */
1075 void default_fd_remove_queue( struct object *obj, struct wait_queue_entry *entry )
1076 {
1077     struct fd *fd = get_obj_fd( obj );
1078
1079     grab_object( obj );
1080     remove_queue( obj, entry );
1081     if (!obj->head)  /* last on the queue is gone */
1082         set_fd_events( fd, 0 );
1083     release_object( obj );
1084     release_object( fd );
1085 }
1086
1087 /* default signaled() routine for objects that poll() on an fd */
1088 int default_fd_signaled( struct object *obj, struct thread *thread )
1089 {
1090     struct fd *fd = get_obj_fd( obj );
1091     int events = fd->fd_ops->get_poll_events( fd );
1092     int ret = check_fd_events( fd, events ) != 0;
1093
1094     if (ret)
1095         set_fd_events( fd, 0 ); /* stop waiting on select() if we are signaled */
1096     else if (obj->head)
1097         set_fd_events( fd, events ); /* restart waiting on poll() if we are no longer signaled */
1098
1099     release_object( fd );
1100     return ret;
1101 }
1102
1103 /* default handler for poll() events */
1104 void default_poll_event( struct fd *fd, int event )
1105 {
1106     /* an error occurred, stop polling this fd to avoid busy-looping */
1107     if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1108     wake_up( fd->user, 0 );
1109 }
1110
1111 /* default flush() routine */
1112 int no_flush( struct fd *fd, struct event **event )
1113 {
1114     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1115     return 0;
1116 }
1117
1118 /* default get_file_info() routine */
1119 int no_get_file_info( struct fd *fd, int *flags )
1120 {
1121     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1122     *flags = 0;
1123     return FD_TYPE_INVALID;
1124 }
1125
1126 /* default queue_async() routine */
1127 void no_queue_async( struct fd *fd, void* ptr, unsigned int status, int type, int count )
1128 {
1129     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1130 }
1131
1132 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1133 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1134                                      unsigned int access )
1135 {
1136     struct fd *fd = NULL;
1137     struct object *obj;
1138
1139     if ((obj = get_handle_obj( process, handle, access, NULL )))
1140     {
1141         fd = get_obj_fd( obj );
1142         release_object( obj );
1143     }
1144     return fd;
1145 }
1146
1147 /* flush a file buffers */
1148 DECL_HANDLER(flush_file)
1149 {
1150     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1151     struct event * event = NULL;
1152
1153     if (fd)
1154     {
1155         fd->fd_ops->flush( fd, &event );
1156         if( event )
1157         {
1158             reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1159         }
1160         release_object( fd );
1161     }
1162 }
1163
1164 /* get a Unix fd to access a file */
1165 DECL_HANDLER(get_handle_fd)
1166 {
1167     struct fd *fd;
1168
1169     reply->fd = -1;
1170     reply->type = FD_TYPE_INVALID;
1171
1172     if ((fd = get_handle_fd_obj( current->process, req->handle, req->access )))
1173     {
1174         int unix_fd = get_handle_unix_fd( current->process, req->handle, req->access );
1175         if (unix_fd != -1) reply->fd = unix_fd;
1176         else if (!get_error())
1177         {
1178             assert( fd->unix_fd != -1 );
1179             send_client_fd( current->process, fd->unix_fd, req->handle );
1180         }
1181         reply->type = fd->fd_ops->get_file_info( fd, &reply->flags );
1182         release_object( fd );
1183     }
1184 }
1185
1186 /* create / reschedule an async I/O */
1187 DECL_HANDLER(register_async)
1188 {
1189     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1190
1191 /*
1192  * The queue_async method must do the following:
1193  *
1194  * 1. Get the async_queue for the request of given type.
1195  * 2. Call find_async() to look for the specific client request in the queue (=> NULL if not found).
1196  * 3. If status is STATUS_PENDING:
1197  *      a) If no async request found in step 2 (new request): call create_async() to initialize one.
1198  *      b) Set request's status to STATUS_PENDING.
1199  *      c) If the "queue" field of the async request is NULL: call async_insert() to put it into the queue.
1200  *    Otherwise:
1201  *      If the async request was found in step 2, destroy it by calling destroy_async().
1202  * 4. Carry out any operations necessary to adjust the object's poll events
1203  *    Usually: set_elect_events (obj, obj->ops->get_poll_events()).
1204  *
1205  * See also the implementations in file.c, serial.c, and sock.c.
1206 */
1207
1208     if (fd)
1209     {
1210         fd->fd_ops->queue_async( fd, req->overlapped, req->status, req->type, req->count );
1211         release_object( fd );
1212     }
1213 }