Take care to not close the file handle if there are outstanding locks
[wine/multimedia.git] / server / fd.c
blobb87e9aa726988f15b7ef9a7ac3c87abf72e44409
1 /*
2 * Server-side file descriptor management
4 * Copyright (C) 2000, 2003 Alexandre Julliard
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.
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.
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
22 #include "config.h"
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>
41 #include "object.h"
42 #include "file.h"
43 #include "handle.h"
44 #include "process.h"
45 #include "request.h"
47 #include "winbase.h"
48 #include "winreg.h"
49 #include "winternl.h"
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).
56 /* file descriptor object */
58 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
59 struct closed_fd
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) */
66 struct fd
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 */
82 static void fd_dump( struct object *obj, int verbose );
83 static void fd_destroy( struct object *obj );
85 static const struct object_ops fd_ops =
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 */
97 /* inode object */
99 struct inode
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 */
111 static void inode_dump( struct object *obj, int verbose );
112 static void inode_destroy( struct object *obj );
114 static const struct object_ops inode_ops =
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 */
126 /* file lock object */
128 struct file_lock
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 */
141 static void file_lock_dump( struct object *obj, int verbose );
142 static int file_lock_signaled( struct object *obj, struct thread *thread );
144 static const struct object_ops file_lock_ops =
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 */
157 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
158 #define FILE_POS_T_MAX (~(file_pos_t)0)
160 static file_pos_t max_unix_offset = OFF_T_MAX;
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)
171 /****************************************************************/
172 /* timeouts support */
174 struct timeout_user
176 struct list entry; /* entry in sorted timeout list */
177 struct timeval when; /* timeout expiry (absolute time) */
178 timeout_callback callback; /* callback function */
179 void *private; /* callback private data */
182 static struct list timeout_list = LIST_INIT(timeout_list); /* sorted timeouts list */
184 /* add a timeout user */
185 struct timeout_user *add_timeout_user( struct timeval *when, timeout_callback func, void *private )
187 struct timeout_user *user;
188 struct list *ptr;
190 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
191 user->when = *when;
192 user->callback = func;
193 user->private = private;
195 /* Now insert it in the linked list */
197 LIST_FOR_EACH( ptr, &timeout_list )
199 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
200 if (!time_before( &timeout->when, when )) break;
202 list_add_before( ptr, &user->entry );
203 return user;
206 /* remove a timeout user */
207 void remove_timeout_user( struct timeout_user *user )
209 list_remove( &user->entry );
210 free( user );
213 /* add a timeout in milliseconds to an absolute time */
214 void add_timeout( struct timeval *when, int timeout )
216 if (timeout)
218 long sec = timeout / 1000;
219 if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
221 when->tv_usec -= 1000000;
222 when->tv_sec++;
224 when->tv_sec += sec;
229 /****************************************************************/
230 /* poll support */
232 static struct fd **poll_users; /* users array */
233 static struct pollfd *pollfd; /* poll fd array */
234 static int nb_users; /* count of array entries actually in use */
235 static int active_users; /* current number of active users */
236 static int allocated_users; /* count of allocated entries in the array */
237 static struct fd **freelist; /* list of free entries in the array */
239 /* add a user in the poll array and return its index, or -1 on failure */
240 static int add_poll_user( struct fd *fd )
242 int ret;
243 if (freelist)
245 ret = freelist - poll_users;
246 freelist = (struct fd **)poll_users[ret];
248 else
250 if (nb_users == allocated_users)
252 struct fd **newusers;
253 struct pollfd *newpoll;
254 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
255 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
256 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
258 if (allocated_users)
259 poll_users = newusers;
260 else
261 free( newusers );
262 return -1;
264 poll_users = newusers;
265 pollfd = newpoll;
266 allocated_users = new_count;
268 ret = nb_users++;
270 pollfd[ret].fd = -1;
271 pollfd[ret].events = 0;
272 pollfd[ret].revents = 0;
273 poll_users[ret] = fd;
274 active_users++;
275 return ret;
278 /* remove a user from the poll list */
279 static void remove_poll_user( struct fd *fd, int user )
281 assert( user >= 0 );
282 assert( poll_users[user] == fd );
283 pollfd[user].fd = -1;
284 pollfd[user].events = 0;
285 pollfd[user].revents = 0;
286 poll_users[user] = (struct fd *)freelist;
287 freelist = &poll_users[user];
288 active_users--;
292 /* server main poll() loop */
293 void main_loop(void)
295 int ret;
297 while (active_users)
299 long diff = -1;
300 if (!list_empty( &timeout_list ))
302 struct list expired_list, *ptr;
303 struct timeval now;
304 gettimeofday( &now, NULL );
306 /* first remove all expired timers from the list */
308 list_init( &expired_list );
309 while ((ptr = list_head( &timeout_list )) != NULL)
311 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
313 if (!time_before( &now, &timeout->when ))
315 list_remove( &timeout->entry );
316 list_add_tail( &expired_list, &timeout->entry );
318 else break;
321 /* now call the callback for all the removed timers */
323 while ((ptr = list_head( &expired_list )) != NULL)
325 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
326 list_remove( &timeout->entry );
327 timeout->callback( timeout->private );
328 free( timeout );
331 if (!active_users) break; /* last user removed by a timeout */
333 if ((ptr = list_head( &timeout_list )) != NULL)
335 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
336 diff = (timeout->when.tv_sec - now.tv_sec) * 1000
337 + (timeout->when.tv_usec - now.tv_usec) / 1000;
338 if (diff < 0) diff = 0;
342 ret = poll( pollfd, nb_users, diff );
343 if (ret > 0)
345 int i;
346 for (i = 0; i < nb_users; i++)
348 if (pollfd[i].revents)
350 fd_poll_event( poll_users[i], pollfd[i].revents );
351 if (!--ret) break;
359 /****************************************************************/
360 /* inode functions */
362 #define HASH_SIZE 37
364 static struct list inode_hash[HASH_SIZE];
366 /* close all pending file descriptors in the closed list */
367 static void inode_close_pending( struct inode *inode )
369 struct list *ptr = list_head( &inode->closed );
371 while (ptr)
373 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
374 struct list *next = list_next( &inode->closed, ptr );
376 if (fd->fd != -1)
378 close( fd->fd );
379 fd->fd = -1;
381 if (!fd->unlink) /* get rid of it unless there's an unlink pending on that file */
383 list_remove( ptr );
384 free( fd );
386 ptr = next;
391 static void inode_dump( struct object *obj, int verbose )
393 struct inode *inode = (struct inode *)obj;
394 fprintf( stderr, "Inode dev=" );
395 DUMP_LONG_LONG( inode->dev );
396 fprintf( stderr, " ino=" );
397 DUMP_LONG_LONG( inode->ino );
398 fprintf( stderr, "\n" );
401 static void inode_destroy( struct object *obj )
403 struct inode *inode = (struct inode *)obj;
404 struct list *ptr;
406 assert( list_empty(&inode->open) );
407 assert( list_empty(&inode->locks) );
409 list_remove( &inode->entry );
411 while ((ptr = list_head( &inode->closed )))
413 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
414 list_remove( ptr );
415 if (fd->fd != -1) close( fd->fd );
416 if (fd->unlink[0])
418 /* make sure it is still the same file */
419 struct stat st;
420 if (!stat( fd->unlink, &st ) && st.st_dev == inode->dev && st.st_ino == inode->ino)
422 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
423 else unlink( fd->unlink );
426 free( fd );
430 /* retrieve the inode object for a given fd, creating it if needed */
431 static struct inode *get_inode( dev_t dev, ino_t ino )
433 struct list *ptr;
434 struct inode *inode;
435 unsigned int hash = (dev ^ ino) % HASH_SIZE;
437 if (inode_hash[hash].next)
439 LIST_FOR_EACH( ptr, &inode_hash[hash] )
441 inode = LIST_ENTRY( ptr, struct inode, entry );
442 if (inode->dev == dev && inode->ino == ino)
443 return (struct inode *)grab_object( inode );
446 else list_init( &inode_hash[hash] );
448 /* not found, create it */
449 if ((inode = alloc_object( &inode_ops )))
451 inode->hash = hash;
452 inode->dev = dev;
453 inode->ino = ino;
454 list_init( &inode->open );
455 list_init( &inode->locks );
456 list_init( &inode->closed );
457 list_add_head( &inode_hash[hash], &inode->entry );
459 return inode;
462 /* add fd to the indoe list of file descriptors to close */
463 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
465 if (!list_empty( &inode->locks ))
467 list_add_head( &inode->closed, &fd->entry );
469 else if (fd->unlink[0]) /* close the fd but keep the structure around for unlink */
471 close( fd->fd );
472 fd->fd = -1;
473 list_add_head( &inode->closed, &fd->entry );
475 else /* no locks on this inode and no unlink, get rid of the fd */
477 close( fd->fd );
478 free( fd );
483 /****************************************************************/
484 /* file lock functions */
486 static void file_lock_dump( struct object *obj, int verbose )
488 struct file_lock *lock = (struct file_lock *)obj;
489 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
490 lock->shared ? "shared" : "excl", lock->fd, lock->process );
491 DUMP_LONG_LONG( lock->start );
492 fprintf( stderr, " end=" );
493 DUMP_LONG_LONG( lock->end );
494 fprintf( stderr, "\n" );
497 static int file_lock_signaled( struct object *obj, struct thread *thread )
499 struct file_lock *lock = (struct file_lock *)obj;
500 /* lock is signaled if it has lost its owner */
501 return !lock->process;
504 /* set (or remove) a Unix lock if possible for the given range */
505 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
507 struct flock fl;
509 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
510 for (;;)
512 if (start == end) return 1; /* can't set zero-byte lock */
513 if (start > max_unix_offset) return 1; /* ignore it */
514 fl.l_type = type;
515 fl.l_whence = SEEK_SET;
516 fl.l_start = start;
517 if (!end || end > max_unix_offset) fl.l_len = 0;
518 else fl.l_len = end - start;
519 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
521 switch(errno)
523 case EACCES:
524 /* check whether locks work at all on this file system */
525 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
527 set_error( STATUS_FILE_LOCK_CONFLICT );
528 return 0;
530 /* fall through */
531 case EIO:
532 case ENOLCK:
533 /* no locking on this fs, just ignore it */
534 fd->fs_locks = 0;
535 return 1;
536 case EAGAIN:
537 set_error( STATUS_FILE_LOCK_CONFLICT );
538 return 0;
539 case EBADF:
540 /* this can happen if we try to set a write lock on a read-only file */
541 /* we just ignore that error */
542 if (fl.l_type == F_WRLCK) return 1;
543 set_error( STATUS_ACCESS_DENIED );
544 return 0;
545 #ifdef EOVERFLOW
546 case EOVERFLOW:
547 #endif
548 case EINVAL:
549 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
550 /* in that case we shrink the limit and retry */
551 if (max_unix_offset > INT_MAX)
553 max_unix_offset = INT_MAX;
554 break; /* retry */
556 /* fall through */
557 default:
558 file_set_error();
559 return 0;
564 /* check if interval [start;end) overlaps the lock */
565 inline static int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
567 if (lock->end && start >= lock->end) return 0;
568 if (end && lock->start >= end) return 0;
569 return 1;
572 /* remove Unix locks for all bytes in the specified area that are no longer locked */
573 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
575 struct hole
577 struct hole *next;
578 struct hole *prev;
579 file_pos_t start;
580 file_pos_t end;
581 } *first, *cur, *next, *buffer;
583 struct list *ptr;
584 int count = 0;
586 if (!fd->inode) return;
587 if (!fd->fs_locks) return;
588 if (start == end || start > max_unix_offset) return;
589 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
591 /* count the number of locks overlapping the specified area */
593 LIST_FOR_EACH( ptr, &fd->inode->locks )
595 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
596 if (lock->start == lock->end) continue;
597 if (lock_overlaps( lock, start, end )) count++;
600 if (!count) /* no locks at all, we can unlock everything */
602 set_unix_lock( fd, start, end, F_UNLCK );
603 return;
606 /* allocate space for the list of holes */
607 /* max. number of holes is number of locks + 1 */
609 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
610 first = buffer;
611 first->next = NULL;
612 first->prev = NULL;
613 first->start = start;
614 first->end = end;
615 next = first + 1;
617 /* build a sorted list of unlocked holes in the specified area */
619 LIST_FOR_EACH( ptr, &fd->inode->locks )
621 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
622 if (lock->start == lock->end) continue;
623 if (!lock_overlaps( lock, start, end )) continue;
625 /* go through all the holes touched by this lock */
626 for (cur = first; cur; cur = cur->next)
628 if (cur->end <= lock->start) continue; /* hole is before start of lock */
629 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
631 /* now we know that lock is overlapping hole */
633 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
635 cur->start = lock->end;
636 if (cur->start && cur->start < cur->end) break; /* done with this lock */
637 /* now hole is empty, remove it */
638 if (cur->next) cur->next->prev = cur->prev;
639 if (cur->prev) cur->prev->next = cur->next;
640 else if (!(first = cur->next)) goto done; /* no more holes at all */
642 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
644 cur->end = lock->start;
645 assert( cur->start < cur->end );
647 else /* lock is in the middle of hole, split hole in two */
649 next->prev = cur;
650 next->next = cur->next;
651 cur->next = next;
652 next->start = lock->end;
653 next->end = cur->end;
654 cur->end = lock->start;
655 assert( next->start < next->end );
656 assert( cur->end < next->start );
657 next++;
658 break; /* done with this lock */
663 /* clear Unix locks for all the holes */
665 for (cur = first; cur; cur = cur->next)
666 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
668 done:
669 free( buffer );
672 /* create a new lock on a fd */
673 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
675 struct file_lock *lock;
677 if (!fd->inode) /* not a regular file */
679 set_error( STATUS_INVALID_HANDLE );
680 return NULL;
683 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
684 lock->shared = shared;
685 lock->start = start;
686 lock->end = end;
687 lock->fd = fd;
688 lock->process = current->process;
690 /* now try to set a Unix lock */
691 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
693 release_object( lock );
694 return NULL;
696 list_add_head( &fd->locks, &lock->fd_entry );
697 list_add_head( &fd->inode->locks, &lock->inode_entry );
698 list_add_head( &lock->process->locks, &lock->proc_entry );
699 return lock;
702 /* remove an existing lock */
703 static void remove_lock( struct file_lock *lock, int remove_unix )
705 struct inode *inode = lock->fd->inode;
707 list_remove( &lock->fd_entry );
708 list_remove( &lock->inode_entry );
709 list_remove( &lock->proc_entry );
710 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
711 if (list_empty( &inode->locks )) inode_close_pending( inode );
712 lock->process = NULL;
713 wake_up( &lock->obj, 0 );
714 release_object( lock );
717 /* remove all locks owned by a given process */
718 void remove_process_locks( struct process *process )
720 struct list *ptr;
722 while ((ptr = list_head( &process->locks )))
724 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
725 remove_lock( lock, 1 ); /* this removes it from the list */
729 /* remove all locks on a given fd */
730 static void remove_fd_locks( struct fd *fd )
732 file_pos_t start = FILE_POS_T_MAX, end = 0;
733 struct list *ptr;
735 while ((ptr = list_head( &fd->locks )))
737 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
738 if (lock->start < start) start = lock->start;
739 if (!lock->end || lock->end > end) end = lock->end - 1;
740 remove_lock( lock, 0 );
742 if (start < end) remove_unix_locks( fd, start, end + 1 );
745 /* add a lock on an fd */
746 /* returns handle to wait on */
747 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
749 struct list *ptr;
750 file_pos_t end = start + count;
752 /* don't allow wrapping locks */
753 if (end && end < start)
755 set_error( STATUS_INVALID_PARAMETER );
756 return 0;
759 /* check if another lock on that file overlaps the area */
760 LIST_FOR_EACH( ptr, &fd->inode->locks )
762 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
763 if (!lock_overlaps( lock, start, end )) continue;
764 if (lock->shared && shared) continue;
765 /* found one */
766 if (!wait)
768 set_error( STATUS_FILE_LOCK_CONFLICT );
769 return 0;
771 set_error( STATUS_PENDING );
772 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
775 /* not found, add it */
776 if (add_lock( fd, shared, start, end )) return 0;
777 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
779 /* Unix lock conflict -> tell client to wait and retry */
780 if (wait) set_error( STATUS_PENDING );
782 return 0;
785 /* remove a lock on an fd */
786 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
788 struct list *ptr;
789 file_pos_t end = start + count;
791 /* find an existing lock with the exact same parameters */
792 LIST_FOR_EACH( ptr, &fd->locks )
794 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
795 if ((lock->start == start) && (lock->end == end))
797 remove_lock( lock, 1 );
798 return;
801 set_error( STATUS_FILE_LOCK_CONFLICT );
805 /****************************************************************/
806 /* file descriptor functions */
808 static void fd_dump( struct object *obj, int verbose )
810 struct fd *fd = (struct fd *)obj;
811 fprintf( stderr, "Fd unix_fd=%d user=%p unlink='%s'\n",
812 fd->unix_fd, fd->user, fd->closed->unlink );
815 static void fd_destroy( struct object *obj )
817 struct fd *fd = (struct fd *)obj;
819 remove_fd_locks( fd );
820 list_remove( &fd->inode_entry );
821 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
822 if (fd->inode)
824 inode_add_closed_fd( fd->inode, fd->closed );
825 release_object( fd->inode );
827 else /* no inode, close it right away */
829 if (fd->unix_fd != -1) close( fd->unix_fd );
833 /* set the events that select waits for on this fd */
834 void set_fd_events( struct fd *fd, int events )
836 int user = fd->poll_index;
837 assert( poll_users[user] == fd );
838 if (events == -1) /* stop waiting on this fd completely */
840 pollfd[user].fd = -1;
841 pollfd[user].events = POLLERR;
842 pollfd[user].revents = 0;
844 else if (pollfd[user].fd != -1 || !pollfd[user].events)
846 pollfd[user].fd = fd->unix_fd;
847 pollfd[user].events = events;
851 /* allocate an fd object, without setting the unix fd yet */
852 struct fd *alloc_fd( const struct fd_ops *fd_user_ops, struct object *user )
854 struct fd *fd = alloc_object( &fd_ops );
856 if (!fd) return NULL;
858 fd->fd_ops = fd_user_ops;
859 fd->user = user;
860 fd->inode = NULL;
861 fd->closed = NULL;
862 fd->access = 0;
863 fd->sharing = 0;
864 fd->unix_fd = -1;
865 fd->fs_locks = 1;
866 fd->poll_index = -1;
867 list_init( &fd->inode_entry );
868 list_init( &fd->locks );
870 if ((fd->poll_index = add_poll_user( fd )) == -1)
872 release_object( fd );
873 return NULL;
875 return fd;
878 /* check if the desired access is possible without violating */
879 /* the sharing mode of other opens of the same file */
880 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
882 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
883 unsigned int existing_access = 0;
884 int unlink = 0;
885 struct list *ptr;
887 /* if access mode is 0, sharing mode is ignored */
888 if (!access) sharing = existing_sharing;
889 fd->access = access;
890 fd->sharing = sharing;
892 LIST_FOR_EACH( ptr, &fd->inode->open )
894 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
895 if (fd_ptr != fd)
897 existing_sharing &= fd_ptr->sharing;
898 existing_access |= fd_ptr->access;
899 if (fd_ptr->closed->unlink[0]) unlink = 1;
903 if ((access & GENERIC_READ) && !(existing_sharing & FILE_SHARE_READ)) return 0;
904 if ((access & GENERIC_WRITE) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
905 if ((existing_access & GENERIC_READ) && !(sharing & FILE_SHARE_READ)) return 0;
906 if ((existing_access & GENERIC_WRITE) && !(sharing & FILE_SHARE_WRITE)) return 0;
907 if (fd->closed->unlink[0] && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
908 if (unlink && !(sharing & FILE_SHARE_DELETE)) return 0;
909 return 1;
912 /* open() wrapper using a struct fd */
913 /* the fd must have been created with alloc_fd */
914 /* on error the fd object is released */
915 struct fd *open_fd( struct fd *fd, const char *name, int flags, mode_t *mode,
916 unsigned int access, unsigned int sharing, unsigned int options )
918 struct stat st;
919 struct closed_fd *closed_fd;
920 const char *unlink_name = "";
922 assert( fd->unix_fd == -1 );
924 if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
925 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
927 release_object( fd );
928 return NULL;
930 /* create the directory if needed */
931 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
933 if (mkdir( name, 0777 ) == -1)
935 if (errno != EEXIST || (flags & O_EXCL))
937 file_set_error();
938 release_object( fd );
939 free( closed_fd );
940 return NULL;
943 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
945 if ((fd->unix_fd = open( name, flags & ~O_TRUNC, *mode )) == -1)
947 file_set_error();
948 release_object( fd );
949 free( closed_fd );
950 return NULL;
952 closed_fd->fd = fd->unix_fd;
953 closed_fd->unlink[0] = 0;
954 fstat( fd->unix_fd, &st );
955 *mode = st.st_mode;
957 /* only bother with an inode for normal files and directories */
958 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
960 struct inode *inode = get_inode( st.st_dev, st.st_ino );
962 if (!inode)
964 /* we can close the fd because there are no others open on the same file,
965 * otherwise we wouldn't have failed to allocate a new inode
967 goto error;
969 fd->inode = inode;
970 fd->closed = closed_fd;
971 list_add_head( &inode->open, &fd->inode_entry );
973 /* check directory options */
974 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
976 release_object( fd );
977 set_error( STATUS_NOT_A_DIRECTORY );
978 return NULL;
980 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
982 release_object( fd );
983 set_error( STATUS_FILE_IS_A_DIRECTORY );
984 return NULL;
986 if (!check_sharing( fd, access, sharing ))
988 release_object( fd );
989 set_error( STATUS_SHARING_VIOLATION );
990 return NULL;
992 strcpy( closed_fd->unlink, unlink_name );
993 if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
995 else /* special file */
997 if (options & FILE_DIRECTORY_FILE)
999 set_error( STATUS_NOT_A_DIRECTORY );
1000 goto error;
1002 if (unlink_name[0]) /* we can't unlink special files */
1004 set_error( STATUS_INVALID_PARAMETER );
1005 goto error;
1007 free( closed_fd );
1009 return fd;
1011 error:
1012 release_object( fd );
1013 free( closed_fd );
1014 return NULL;
1017 /* create an fd for an anonymous file */
1018 /* if the function fails the unix fd is closed */
1019 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user )
1021 struct fd *fd = alloc_fd( fd_user_ops, user );
1023 if (fd)
1025 fd->unix_fd = unix_fd;
1026 return fd;
1028 close( unix_fd );
1029 return NULL;
1032 /* retrieve the object that is using an fd */
1033 void *get_fd_user( struct fd *fd )
1035 return fd->user;
1038 /* retrieve the unix fd for an object */
1039 int get_unix_fd( struct fd *fd )
1041 return fd->unix_fd;
1044 /* check if two file descriptors point to the same file */
1045 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1047 return fd1->inode == fd2->inode;
1050 /* callback for event happening in the main poll() loop */
1051 void fd_poll_event( struct fd *fd, int event )
1053 return fd->fd_ops->poll_event( fd, event );
1056 /* check if events are pending and if yes return which one(s) */
1057 int check_fd_events( struct fd *fd, int events )
1059 struct pollfd pfd;
1061 pfd.fd = fd->unix_fd;
1062 pfd.events = events;
1063 if (poll( &pfd, 1, 0 ) <= 0) return 0;
1064 return pfd.revents;
1067 /* default add_queue() routine for objects that poll() on an fd */
1068 int default_fd_add_queue( struct object *obj, struct wait_queue_entry *entry )
1070 struct fd *fd = get_obj_fd( obj );
1072 if (!fd) return 0;
1073 if (!obj->head) /* first on the queue */
1074 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1075 add_queue( obj, entry );
1076 release_object( fd );
1077 return 1;
1080 /* default remove_queue() routine for objects that poll() on an fd */
1081 void default_fd_remove_queue( struct object *obj, struct wait_queue_entry *entry )
1083 struct fd *fd = get_obj_fd( obj );
1085 grab_object( obj );
1086 remove_queue( obj, entry );
1087 if (!obj->head) /* last on the queue is gone */
1088 set_fd_events( fd, 0 );
1089 release_object( obj );
1090 release_object( fd );
1093 /* default signaled() routine for objects that poll() on an fd */
1094 int default_fd_signaled( struct object *obj, struct thread *thread )
1096 struct fd *fd = get_obj_fd( obj );
1097 int events = fd->fd_ops->get_poll_events( fd );
1098 int ret = check_fd_events( fd, events ) != 0;
1100 if (ret)
1101 set_fd_events( fd, 0 ); /* stop waiting on select() if we are signaled */
1102 else if (obj->head)
1103 set_fd_events( fd, events ); /* restart waiting on poll() if we are no longer signaled */
1105 release_object( fd );
1106 return ret;
1109 /* default handler for poll() events */
1110 void default_poll_event( struct fd *fd, int event )
1112 /* an error occurred, stop polling this fd to avoid busy-looping */
1113 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1114 wake_up( fd->user, 0 );
1117 /* default flush() routine */
1118 int no_flush( struct fd *fd, struct event **event )
1120 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1121 return 0;
1124 /* default get_file_info() routine */
1125 int no_get_file_info( struct fd *fd )
1127 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1128 return 0;
1131 /* default queue_async() routine */
1132 void no_queue_async( struct fd *fd, void* ptr, unsigned int status, int type, int count )
1134 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1137 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1138 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1139 unsigned int access )
1141 struct fd *fd = NULL;
1142 struct object *obj;
1144 if ((obj = get_handle_obj( process, handle, access, NULL )))
1146 fd = get_obj_fd( obj );
1147 release_object( obj );
1149 return fd;
1152 /* flush a file buffers */
1153 DECL_HANDLER(flush_file)
1155 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1156 struct event * event = NULL;
1158 if (fd)
1160 fd->fd_ops->flush( fd, &event );
1161 if( event )
1163 reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1165 release_object( fd );
1169 /* get a Unix fd to access a file */
1170 DECL_HANDLER(get_handle_fd)
1172 struct fd *fd;
1174 reply->fd = -1;
1176 if ((fd = get_handle_fd_obj( current->process, req->handle, req->access )))
1178 int unix_fd = get_handle_unix_fd( current->process, req->handle, req->access );
1179 if (unix_fd != -1) reply->fd = unix_fd;
1180 else if (!get_error())
1182 assert( fd->unix_fd != -1 );
1183 send_client_fd( current->process, fd->unix_fd, req->handle );
1185 reply->flags = fd->fd_ops->get_file_info( fd );
1186 release_object( fd );
1190 /* create / reschedule an async I/O */
1191 DECL_HANDLER(register_async)
1193 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1196 * The queue_async method must do the following:
1198 * 1. Get the async_queue for the request of given type.
1199 * 2. Call find_async() to look for the specific client request in the queue (=> NULL if not found).
1200 * 3. If status is STATUS_PENDING:
1201 * a) If no async request found in step 2 (new request): call create_async() to initialize one.
1202 * b) Set request's status to STATUS_PENDING.
1203 * c) If the "queue" field of the async request is NULL: call async_insert() to put it into the queue.
1204 * Otherwise:
1205 * If the async request was found in step 2, destroy it by calling destroy_async().
1206 * 4. Carry out any operations necessary to adjust the object's poll events
1207 * Usually: set_elect_events (obj, obj->ops->get_poll_events()).
1209 * See also the implementations in file.c, serial.c, and sock.c.
1212 if (fd)
1214 fd->fd_ops->queue_async( fd, req->overlapped, req->status, req->type, req->count );
1215 release_object( fd );