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