wine.inf: We should not override existing associations.
[wine/hacks.git] / server / fd.c
blobb7281a40510f20e9f73df3700350168eafe8dd0d
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <signal.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #ifdef HAVE_POLL_H
35 #include <poll.h>
36 #endif
37 #ifdef HAVE_SYS_POLL_H
38 #include <sys/poll.h>
39 #endif
40 #ifdef HAVE_SYS_EVENT_H
41 #include <sys/event.h>
42 #undef LIST_INIT
43 #undef LIST_ENTRY
44 #endif
45 #ifdef HAVE_STDINT_H
46 #include <stdint.h>
47 #endif
48 #include <sys/stat.h>
49 #include <sys/time.h>
50 #include <sys/types.h>
51 #include <unistd.h>
53 #include "ntstatus.h"
54 #define WIN32_NO_STATUS
55 #include "object.h"
56 #include "file.h"
57 #include "handle.h"
58 #include "process.h"
59 #include "request.h"
61 #include "winternl.h"
63 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
64 # include <sys/epoll.h>
65 # define USE_EPOLL
66 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
67 # define USE_EPOLL
68 # define EPOLLIN POLLIN
69 # define EPOLLOUT POLLOUT
70 # define EPOLLERR POLLERR
71 # define EPOLLHUP POLLHUP
72 # define EPOLL_CTL_ADD 1
73 # define EPOLL_CTL_DEL 2
74 # define EPOLL_CTL_MOD 3
76 typedef union epoll_data
78 void *ptr;
79 int fd;
80 uint32_t u32;
81 uint64_t u64;
82 } epoll_data_t;
84 struct epoll_event
86 uint32_t events;
87 epoll_data_t data;
90 #define SYSCALL_RET(ret) do { \
91 if (ret < 0) { errno = -ret; ret = -1; } \
92 return ret; \
93 } while(0)
95 static inline int epoll_create( int size )
97 int ret;
98 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
99 : "=a" (ret) : "0" (254 /*NR_epoll_create*/), "r" (size) );
100 SYSCALL_RET(ret);
103 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
105 int ret;
106 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
107 : "=a" (ret)
108 : "0" (255 /*NR_epoll_ctl*/), "r" (epfd), "c" (op), "d" (fd), "S" (event), "m" (*event) );
109 SYSCALL_RET(ret);
112 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
114 int ret;
115 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
116 : "=a" (ret)
117 : "0" (256 /*NR_epoll_wait*/), "r" (epfd), "c" (events), "d" (maxevents), "S" (timeout)
118 : "memory" );
119 SYSCALL_RET(ret);
121 #undef SYSCALL_RET
123 #endif /* linux && __i386__ && HAVE_STDINT_H */
126 /* Because of the stupid Posix locking semantics, we need to keep
127 * track of all file descriptors referencing a given file, and not
128 * close a single one until all the locks are gone (sigh).
131 /* file descriptor object */
133 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
134 struct closed_fd
136 struct list entry; /* entry in inode closed list */
137 int unix_fd; /* the unix file descriptor */
138 char unlink[1]; /* name to unlink on close (if any) */
141 struct fd
143 struct object obj; /* object header */
144 const struct fd_ops *fd_ops; /* file descriptor operations */
145 struct inode *inode; /* inode that this fd belongs to */
146 struct list inode_entry; /* entry in inode fd list */
147 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
148 struct object *user; /* object using this file descriptor */
149 struct list locks; /* list of locks on this fd */
150 unsigned int access; /* file access (FILE_READ_DATA etc.) */
151 unsigned int sharing; /* file sharing mode */
152 int unix_fd; /* unix file descriptor */
153 int fs_locks :1; /* can we use filesystem locks for this fd? */
154 int unmounted :1;/* has the device been unmounted? */
155 int poll_index; /* index of fd in poll array */
156 struct list read_q; /* async readers of this fd */
157 struct list write_q; /* async writers of this fd */
160 static void fd_dump( struct object *obj, int verbose );
161 static void fd_destroy( struct object *obj );
163 static const struct object_ops fd_ops =
165 sizeof(struct fd), /* size */
166 fd_dump, /* dump */
167 no_add_queue, /* add_queue */
168 NULL, /* remove_queue */
169 NULL, /* signaled */
170 NULL, /* satisfied */
171 no_signal, /* signal */
172 no_get_fd, /* get_fd */
173 no_map_access, /* map_access */
174 no_lookup_name, /* lookup_name */
175 no_close_handle, /* close_handle */
176 fd_destroy /* destroy */
179 /* device object */
181 #define DEVICE_HASH_SIZE 7
182 #define INODE_HASH_SIZE 17
184 struct device
186 struct object obj; /* object header */
187 struct list entry; /* entry in device hash list */
188 dev_t dev; /* device number */
189 int removable; /* removable device? (or -1 if unknown) */
190 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
193 static void device_dump( struct object *obj, int verbose );
194 static void device_destroy( struct object *obj );
196 static const struct object_ops device_ops =
198 sizeof(struct device), /* size */
199 device_dump, /* dump */
200 no_add_queue, /* add_queue */
201 NULL, /* remove_queue */
202 NULL, /* signaled */
203 NULL, /* satisfied */
204 no_signal, /* signal */
205 no_get_fd, /* get_fd */
206 no_map_access, /* map_access */
207 no_lookup_name, /* lookup_name */
208 no_close_handle, /* close_handle */
209 device_destroy /* destroy */
212 /* inode object */
214 struct inode
216 struct object obj; /* object header */
217 struct list entry; /* inode hash list entry */
218 struct device *device; /* device containing this inode */
219 ino_t ino; /* inode number */
220 struct list open; /* list of open file descriptors */
221 struct list locks; /* list of file locks */
222 struct list closed; /* list of file descriptors to close at destroy time */
225 static void inode_dump( struct object *obj, int verbose );
226 static void inode_destroy( struct object *obj );
228 static const struct object_ops inode_ops =
230 sizeof(struct inode), /* size */
231 inode_dump, /* dump */
232 no_add_queue, /* add_queue */
233 NULL, /* remove_queue */
234 NULL, /* signaled */
235 NULL, /* satisfied */
236 no_signal, /* signal */
237 no_get_fd, /* get_fd */
238 no_map_access, /* map_access */
239 no_lookup_name, /* lookup_name */
240 no_close_handle, /* close_handle */
241 inode_destroy /* destroy */
244 /* file lock object */
246 struct file_lock
248 struct object obj; /* object header */
249 struct fd *fd; /* fd owning this lock */
250 struct list fd_entry; /* entry in list of locks on a given fd */
251 struct list inode_entry; /* entry in inode list of locks */
252 int shared; /* shared lock? */
253 file_pos_t start; /* locked region is interval [start;end) */
254 file_pos_t end;
255 struct process *process; /* process owning this lock */
256 struct list proc_entry; /* entry in list of locks owned by the process */
259 static void file_lock_dump( struct object *obj, int verbose );
260 static int file_lock_signaled( struct object *obj, struct thread *thread );
262 static const struct object_ops file_lock_ops =
264 sizeof(struct file_lock), /* size */
265 file_lock_dump, /* dump */
266 add_queue, /* add_queue */
267 remove_queue, /* remove_queue */
268 file_lock_signaled, /* signaled */
269 no_satisfied, /* satisfied */
270 no_signal, /* signal */
271 no_get_fd, /* get_fd */
272 no_map_access, /* map_access */
273 no_lookup_name, /* lookup_name */
274 no_close_handle, /* close_handle */
275 no_destroy /* destroy */
279 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
280 #define FILE_POS_T_MAX (~(file_pos_t)0)
282 static file_pos_t max_unix_offset = OFF_T_MAX;
284 #define DUMP_LONG_LONG(val) do { \
285 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
286 fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
287 else \
288 fprintf( stderr, "%lx", (unsigned long)(val) ); \
289 } while (0)
293 /****************************************************************/
294 /* timeouts support */
296 struct timeout_user
298 struct list entry; /* entry in sorted timeout list */
299 struct timeval when; /* timeout expiry (absolute time) */
300 timeout_callback callback; /* callback function */
301 void *private; /* callback private data */
304 static struct list timeout_list = LIST_INIT(timeout_list); /* sorted timeouts list */
306 /* add a timeout user */
307 struct timeout_user *add_timeout_user( const struct timeval *when, timeout_callback func,
308 void *private )
310 struct timeout_user *user;
311 struct list *ptr;
313 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
314 user->when = *when;
315 user->callback = func;
316 user->private = private;
318 /* Now insert it in the linked list */
320 LIST_FOR_EACH( ptr, &timeout_list )
322 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
323 if (!time_before( &timeout->when, when )) break;
325 list_add_before( ptr, &user->entry );
326 return user;
329 /* remove a timeout user */
330 void remove_timeout_user( struct timeout_user *user )
332 list_remove( &user->entry );
333 free( user );
336 /* add a timeout in milliseconds to an absolute time */
337 void add_timeout( struct timeval *when, int timeout )
339 if (timeout)
341 long sec = timeout / 1000;
342 if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
344 when->tv_usec -= 1000000;
345 when->tv_sec++;
347 when->tv_sec += sec;
352 /****************************************************************/
353 /* poll support */
355 static struct fd **poll_users; /* users array */
356 static struct pollfd *pollfd; /* poll fd array */
357 static int nb_users; /* count of array entries actually in use */
358 static int active_users; /* current number of active users */
359 static int allocated_users; /* count of allocated entries in the array */
360 static struct fd **freelist; /* list of free entries in the array */
362 static int get_next_timeout(void);
364 #ifdef USE_EPOLL
366 static int epoll_fd = -1;
368 static inline void init_epoll(void)
370 epoll_fd = epoll_create( 128 );
373 /* set the events that epoll waits for on this fd; helper for set_fd_events */
374 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
376 struct epoll_event ev;
377 int ctl;
379 if (epoll_fd == -1) return;
381 if (events == -1) /* stop waiting on this fd completely */
383 if (pollfd[user].fd == -1) return; /* already removed */
384 ctl = EPOLL_CTL_DEL;
386 else if (pollfd[user].fd == -1)
388 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
389 ctl = EPOLL_CTL_ADD;
391 else
393 if (pollfd[user].events == events) return; /* nothing to do */
394 ctl = EPOLL_CTL_MOD;
397 ev.events = events;
398 memset(&ev.data, 0, sizeof(ev.data));
399 ev.data.u32 = user;
401 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
403 if (errno == ENOMEM) /* not enough memory, give up on epoll */
405 close( epoll_fd );
406 epoll_fd = -1;
408 else perror( "epoll_ctl" ); /* should not happen */
412 static inline void remove_epoll_user( struct fd *fd, int user )
414 if (epoll_fd == -1) return;
416 if (pollfd[user].fd != -1)
418 struct epoll_event dummy;
419 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
423 static inline void main_loop_epoll(void)
425 int i, ret, timeout;
426 struct epoll_event events[128];
428 assert( POLLIN == EPOLLIN );
429 assert( POLLOUT == EPOLLOUT );
430 assert( POLLERR == EPOLLERR );
431 assert( POLLHUP == EPOLLHUP );
433 if (epoll_fd == -1) return;
435 while (active_users)
437 timeout = get_next_timeout();
439 if (!active_users) break; /* last user removed by a timeout */
440 if (epoll_fd == -1) break; /* an error occurred with epoll */
442 ret = epoll_wait( epoll_fd, events, sizeof(events)/sizeof(events[0]), timeout );
444 /* put the events into the pollfd array first, like poll does */
445 for (i = 0; i < ret; i++)
447 int user = events[i].data.u32;
448 pollfd[user].revents = events[i].events;
451 /* read events from the pollfd array, as set_fd_events may modify them */
452 for (i = 0; i < ret; i++)
454 int user = events[i].data.u32;
455 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
460 #elif defined(HAVE_KQUEUE)
462 static int kqueue_fd = -1;
464 static inline void init_epoll(void)
466 #ifndef __APPLE__ /* kqueue support is broken in the MacOS kernel so we can't use it */
467 kqueue_fd = kqueue();
468 #endif
471 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
473 struct kevent ev[2];
475 if (kqueue_fd == -1) return;
477 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)user );
478 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)user );
480 if (events == -1) /* stop waiting on this fd completely */
482 if (pollfd[user].fd == -1) return; /* already removed */
483 ev[0].flags |= EV_DELETE;
484 ev[1].flags |= EV_DELETE;
486 else if (pollfd[user].fd == -1)
488 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
489 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
490 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
492 else
494 if (pollfd[user].events == events) return; /* nothing to do */
495 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
496 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
499 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
501 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
503 close( kqueue_fd );
504 kqueue_fd = -1;
506 else perror( "kevent" ); /* should not happen */
510 static inline void remove_epoll_user( struct fd *fd, int user )
512 if (kqueue_fd == -1) return;
514 if (pollfd[user].fd != -1)
516 struct kevent ev[2];
518 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
519 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
520 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
524 static inline void main_loop_epoll(void)
526 int i, ret, timeout;
527 struct kevent events[128];
529 if (kqueue_fd == -1) return;
531 while (active_users)
533 timeout = get_next_timeout();
535 if (!active_users) break; /* last user removed by a timeout */
536 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
538 if (timeout != -1)
540 struct timespec ts;
542 ts.tv_sec = timeout / 1000;
543 ts.tv_nsec = (timeout % 1000) * 1000000;
544 ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), &ts );
546 else ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), NULL );
548 /* put the events into the pollfd array first, like poll does */
549 for (i = 0; i < ret; i++)
551 long user = (long)events[i].udata;
552 pollfd[user].revents = 0;
554 for (i = 0; i < ret; i++)
556 long user = (long)events[i].udata;
557 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
558 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
559 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
560 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
563 /* read events from the pollfd array, as set_fd_events may modify them */
564 for (i = 0; i < ret; i++)
566 long user = (long)events[i].udata;
567 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
568 pollfd[user].revents = 0;
573 #else /* HAVE_KQUEUE */
575 static inline void init_epoll(void) { }
576 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
577 static inline void remove_epoll_user( struct fd *fd, int user ) { }
578 static inline void main_loop_epoll(void) { }
580 #endif /* USE_EPOLL */
583 /* add a user in the poll array and return its index, or -1 on failure */
584 static int add_poll_user( struct fd *fd )
586 int ret;
587 if (freelist)
589 ret = freelist - poll_users;
590 freelist = (struct fd **)poll_users[ret];
592 else
594 if (nb_users == allocated_users)
596 struct fd **newusers;
597 struct pollfd *newpoll;
598 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
599 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
600 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
602 if (allocated_users)
603 poll_users = newusers;
604 else
605 free( newusers );
606 return -1;
608 poll_users = newusers;
609 pollfd = newpoll;
610 if (!allocated_users) init_epoll();
611 allocated_users = new_count;
613 ret = nb_users++;
615 pollfd[ret].fd = -1;
616 pollfd[ret].events = 0;
617 pollfd[ret].revents = 0;
618 poll_users[ret] = fd;
619 active_users++;
620 return ret;
623 /* remove a user from the poll list */
624 static void remove_poll_user( struct fd *fd, int user )
626 assert( user >= 0 );
627 assert( poll_users[user] == fd );
629 remove_epoll_user( fd, user );
630 pollfd[user].fd = -1;
631 pollfd[user].events = 0;
632 pollfd[user].revents = 0;
633 poll_users[user] = (struct fd *)freelist;
634 freelist = &poll_users[user];
635 active_users--;
638 /* process pending timeouts and return the time until the next timeout, in milliseconds */
639 static int get_next_timeout(void)
641 if (!list_empty( &timeout_list ))
643 struct list expired_list, *ptr;
644 struct timeval now;
646 gettimeofday( &now, NULL );
648 /* first remove all expired timers from the list */
650 list_init( &expired_list );
651 while ((ptr = list_head( &timeout_list )) != NULL)
653 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
655 if (!time_before( &now, &timeout->when ))
657 list_remove( &timeout->entry );
658 list_add_tail( &expired_list, &timeout->entry );
660 else break;
663 /* now call the callback for all the removed timers */
665 while ((ptr = list_head( &expired_list )) != NULL)
667 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
668 list_remove( &timeout->entry );
669 timeout->callback( timeout->private );
670 free( timeout );
673 if ((ptr = list_head( &timeout_list )) != NULL)
675 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
676 int diff = (timeout->when.tv_sec - now.tv_sec) * 1000
677 + (timeout->when.tv_usec - now.tv_usec + 999) / 1000;
678 if (diff < 0) diff = 0;
679 return diff;
682 return -1; /* no pending timeouts */
685 /* server main poll() loop */
686 void main_loop(void)
688 int i, ret, timeout;
690 main_loop_epoll();
691 /* fall through to normal poll loop */
693 while (active_users)
695 timeout = get_next_timeout();
697 if (!active_users) break; /* last user removed by a timeout */
699 ret = poll( pollfd, nb_users, timeout );
700 if (ret > 0)
702 for (i = 0; i < nb_users; i++)
704 if (pollfd[i].revents)
706 fd_poll_event( poll_users[i], pollfd[i].revents );
707 if (!--ret) break;
715 /****************************************************************/
716 /* device functions */
718 static struct list device_hash[DEVICE_HASH_SIZE];
720 /* retrieve the device object for a given fd, creating it if needed */
721 static struct device *get_device( dev_t dev, int create )
723 struct device *device;
724 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
726 if (device_hash[hash].next)
728 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
729 if (device->dev == dev) return (struct device *)grab_object( device );
731 else list_init( &device_hash[hash] );
733 /* not found, create it */
735 if (!create) return NULL;
736 if ((device = alloc_object( &device_ops )))
738 device->dev = dev;
739 device->removable = -1;
740 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
741 list_add_head( &device_hash[hash], &device->entry );
743 return device;
746 static void device_dump( struct object *obj, int verbose )
748 struct device *device = (struct device *)obj;
749 fprintf( stderr, "Device dev=" );
750 DUMP_LONG_LONG( device->dev );
751 fprintf( stderr, "\n" );
754 static void device_destroy( struct object *obj )
756 struct device *device = (struct device *)obj;
757 unsigned int i;
759 for (i = 0; i < INODE_HASH_SIZE; i++)
760 assert( list_empty(&device->inode_hash[i]) );
762 list_remove( &device->entry ); /* remove it from the hash table */
766 /****************************************************************/
767 /* inode functions */
769 /* close all pending file descriptors in the closed list */
770 static void inode_close_pending( struct inode *inode, int keep_unlinks )
772 struct list *ptr = list_head( &inode->closed );
774 while (ptr)
776 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
777 struct list *next = list_next( &inode->closed, ptr );
779 if (fd->unix_fd != -1)
781 close( fd->unix_fd );
782 fd->unix_fd = -1;
784 if (!keep_unlinks || !fd->unlink[0]) /* get rid of it unless there's an unlink pending on that file */
786 list_remove( ptr );
787 free( fd );
789 ptr = next;
793 static void inode_dump( struct object *obj, int verbose )
795 struct inode *inode = (struct inode *)obj;
796 fprintf( stderr, "Inode device=%p ino=", inode->device );
797 DUMP_LONG_LONG( inode->ino );
798 fprintf( stderr, "\n" );
801 static void inode_destroy( struct object *obj )
803 struct inode *inode = (struct inode *)obj;
804 struct list *ptr;
806 assert( list_empty(&inode->open) );
807 assert( list_empty(&inode->locks) );
809 list_remove( &inode->entry );
811 while ((ptr = list_head( &inode->closed )))
813 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
814 list_remove( ptr );
815 if (fd->unix_fd != -1) close( fd->unix_fd );
816 if (fd->unlink[0])
818 /* make sure it is still the same file */
819 struct stat st;
820 if (!stat( fd->unlink, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
822 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
823 else unlink( fd->unlink );
826 free( fd );
828 release_object( inode->device );
831 /* retrieve the inode object for a given fd, creating it if needed */
832 static struct inode *get_inode( dev_t dev, ino_t ino )
834 struct device *device;
835 struct inode *inode;
836 unsigned int hash = ino % INODE_HASH_SIZE;
838 if (!(device = get_device( dev, 1 ))) return NULL;
840 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
842 if (inode->ino == ino)
844 release_object( device );
845 return (struct inode *)grab_object( inode );
849 /* not found, create it */
850 if ((inode = alloc_object( &inode_ops )))
852 inode->device = device;
853 inode->ino = ino;
854 list_init( &inode->open );
855 list_init( &inode->locks );
856 list_init( &inode->closed );
857 list_add_head( &device->inode_hash[hash], &inode->entry );
859 else release_object( device );
861 return inode;
864 /* add fd to the inode list of file descriptors to close */
865 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
867 if (!list_empty( &inode->locks ))
869 list_add_head( &inode->closed, &fd->entry );
871 else if (fd->unlink[0]) /* close the fd but keep the structure around for unlink */
873 if (fd->unix_fd != -1) close( fd->unix_fd );
874 fd->unix_fd = -1;
875 list_add_head( &inode->closed, &fd->entry );
877 else /* no locks on this inode and no unlink, get rid of the fd */
879 if (fd->unix_fd != -1) close( fd->unix_fd );
880 free( fd );
885 /****************************************************************/
886 /* file lock functions */
888 static void file_lock_dump( struct object *obj, int verbose )
890 struct file_lock *lock = (struct file_lock *)obj;
891 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
892 lock->shared ? "shared" : "excl", lock->fd, lock->process );
893 DUMP_LONG_LONG( lock->start );
894 fprintf( stderr, " end=" );
895 DUMP_LONG_LONG( lock->end );
896 fprintf( stderr, "\n" );
899 static int file_lock_signaled( struct object *obj, struct thread *thread )
901 struct file_lock *lock = (struct file_lock *)obj;
902 /* lock is signaled if it has lost its owner */
903 return !lock->process;
906 /* set (or remove) a Unix lock if possible for the given range */
907 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
909 struct flock fl;
911 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
912 for (;;)
914 if (start == end) return 1; /* can't set zero-byte lock */
915 if (start > max_unix_offset) return 1; /* ignore it */
916 fl.l_type = type;
917 fl.l_whence = SEEK_SET;
918 fl.l_start = start;
919 if (!end || end > max_unix_offset) fl.l_len = 0;
920 else fl.l_len = end - start;
921 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
923 switch(errno)
925 case EACCES:
926 /* check whether locks work at all on this file system */
927 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
929 set_error( STATUS_FILE_LOCK_CONFLICT );
930 return 0;
932 /* fall through */
933 case EIO:
934 case ENOLCK:
935 /* no locking on this fs, just ignore it */
936 fd->fs_locks = 0;
937 return 1;
938 case EAGAIN:
939 set_error( STATUS_FILE_LOCK_CONFLICT );
940 return 0;
941 case EBADF:
942 /* this can happen if we try to set a write lock on a read-only file */
943 /* we just ignore that error */
944 if (fl.l_type == F_WRLCK) return 1;
945 set_error( STATUS_ACCESS_DENIED );
946 return 0;
947 #ifdef EOVERFLOW
948 case EOVERFLOW:
949 #endif
950 case EINVAL:
951 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
952 /* in that case we shrink the limit and retry */
953 if (max_unix_offset > INT_MAX)
955 max_unix_offset = INT_MAX;
956 break; /* retry */
958 /* fall through */
959 default:
960 file_set_error();
961 return 0;
966 /* check if interval [start;end) overlaps the lock */
967 inline static int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
969 if (lock->end && start >= lock->end) return 0;
970 if (end && lock->start >= end) return 0;
971 return 1;
974 /* remove Unix locks for all bytes in the specified area that are no longer locked */
975 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
977 struct hole
979 struct hole *next;
980 struct hole *prev;
981 file_pos_t start;
982 file_pos_t end;
983 } *first, *cur, *next, *buffer;
985 struct list *ptr;
986 int count = 0;
988 if (!fd->inode) return;
989 if (!fd->fs_locks) return;
990 if (start == end || start > max_unix_offset) return;
991 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
993 /* count the number of locks overlapping the specified area */
995 LIST_FOR_EACH( ptr, &fd->inode->locks )
997 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
998 if (lock->start == lock->end) continue;
999 if (lock_overlaps( lock, start, end )) count++;
1002 if (!count) /* no locks at all, we can unlock everything */
1004 set_unix_lock( fd, start, end, F_UNLCK );
1005 return;
1008 /* allocate space for the list of holes */
1009 /* max. number of holes is number of locks + 1 */
1011 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1012 first = buffer;
1013 first->next = NULL;
1014 first->prev = NULL;
1015 first->start = start;
1016 first->end = end;
1017 next = first + 1;
1019 /* build a sorted list of unlocked holes in the specified area */
1021 LIST_FOR_EACH( ptr, &fd->inode->locks )
1023 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1024 if (lock->start == lock->end) continue;
1025 if (!lock_overlaps( lock, start, end )) continue;
1027 /* go through all the holes touched by this lock */
1028 for (cur = first; cur; cur = cur->next)
1030 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1031 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1033 /* now we know that lock is overlapping hole */
1035 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1037 cur->start = lock->end;
1038 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1039 /* now hole is empty, remove it */
1040 if (cur->next) cur->next->prev = cur->prev;
1041 if (cur->prev) cur->prev->next = cur->next;
1042 else if (!(first = cur->next)) goto done; /* no more holes at all */
1044 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1046 cur->end = lock->start;
1047 assert( cur->start < cur->end );
1049 else /* lock is in the middle of hole, split hole in two */
1051 next->prev = cur;
1052 next->next = cur->next;
1053 cur->next = next;
1054 next->start = lock->end;
1055 next->end = cur->end;
1056 cur->end = lock->start;
1057 assert( next->start < next->end );
1058 assert( cur->end < next->start );
1059 next++;
1060 break; /* done with this lock */
1065 /* clear Unix locks for all the holes */
1067 for (cur = first; cur; cur = cur->next)
1068 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1070 done:
1071 free( buffer );
1074 /* create a new lock on a fd */
1075 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1077 struct file_lock *lock;
1079 if (!fd->inode) /* not a regular file */
1081 set_error( STATUS_INVALID_HANDLE );
1082 return NULL;
1085 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1086 lock->shared = shared;
1087 lock->start = start;
1088 lock->end = end;
1089 lock->fd = fd;
1090 lock->process = current->process;
1092 /* now try to set a Unix lock */
1093 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1095 release_object( lock );
1096 return NULL;
1098 list_add_head( &fd->locks, &lock->fd_entry );
1099 list_add_head( &fd->inode->locks, &lock->inode_entry );
1100 list_add_head( &lock->process->locks, &lock->proc_entry );
1101 return lock;
1104 /* remove an existing lock */
1105 static void remove_lock( struct file_lock *lock, int remove_unix )
1107 struct inode *inode = lock->fd->inode;
1109 list_remove( &lock->fd_entry );
1110 list_remove( &lock->inode_entry );
1111 list_remove( &lock->proc_entry );
1112 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1113 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1114 lock->process = NULL;
1115 wake_up( &lock->obj, 0 );
1116 release_object( lock );
1119 /* remove all locks owned by a given process */
1120 void remove_process_locks( struct process *process )
1122 struct list *ptr;
1124 while ((ptr = list_head( &process->locks )))
1126 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1127 remove_lock( lock, 1 ); /* this removes it from the list */
1131 /* remove all locks on a given fd */
1132 static void remove_fd_locks( struct fd *fd )
1134 file_pos_t start = FILE_POS_T_MAX, end = 0;
1135 struct list *ptr;
1137 while ((ptr = list_head( &fd->locks )))
1139 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1140 if (lock->start < start) start = lock->start;
1141 if (!lock->end || lock->end > end) end = lock->end - 1;
1142 remove_lock( lock, 0 );
1144 if (start < end) remove_unix_locks( fd, start, end + 1 );
1147 /* add a lock on an fd */
1148 /* returns handle to wait on */
1149 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1151 struct list *ptr;
1152 file_pos_t end = start + count;
1154 /* don't allow wrapping locks */
1155 if (end && end < start)
1157 set_error( STATUS_INVALID_PARAMETER );
1158 return 0;
1161 /* check if another lock on that file overlaps the area */
1162 LIST_FOR_EACH( ptr, &fd->inode->locks )
1164 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1165 if (!lock_overlaps( lock, start, end )) continue;
1166 if (lock->shared && shared) continue;
1167 /* found one */
1168 if (!wait)
1170 set_error( STATUS_FILE_LOCK_CONFLICT );
1171 return 0;
1173 set_error( STATUS_PENDING );
1174 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1177 /* not found, add it */
1178 if (add_lock( fd, shared, start, end )) return 0;
1179 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1181 /* Unix lock conflict -> tell client to wait and retry */
1182 if (wait) set_error( STATUS_PENDING );
1184 return 0;
1187 /* remove a lock on an fd */
1188 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1190 struct list *ptr;
1191 file_pos_t end = start + count;
1193 /* find an existing lock with the exact same parameters */
1194 LIST_FOR_EACH( ptr, &fd->locks )
1196 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1197 if ((lock->start == start) && (lock->end == end))
1199 remove_lock( lock, 1 );
1200 return;
1203 set_error( STATUS_FILE_LOCK_CONFLICT );
1207 /****************************************************************/
1208 /* asynchronous operations support */
1210 struct async
1212 struct thread *thread;
1213 void *apc;
1214 void *user;
1215 void *sb;
1216 struct timeout_user *timeout;
1217 struct list entry;
1220 /* notifies client thread of new status of its async request */
1221 /* destroys the server side of it */
1222 static void async_terminate( struct async *async, int status )
1224 thread_queue_apc( async->thread, NULL, async->apc, APC_ASYNC_IO,
1225 1, async->user, async->sb, (void *)status );
1227 if (async->timeout) remove_timeout_user( async->timeout );
1228 async->timeout = NULL;
1229 list_remove( &async->entry );
1230 release_object( async->thread );
1231 free( async );
1234 /* cb for timeout on an async request */
1235 static void async_callback(void *private)
1237 struct async *async = (struct async *)private;
1239 /* fprintf(stderr, "async timeout out %p\n", async); */
1240 async->timeout = NULL;
1241 async_terminate( async, STATUS_TIMEOUT );
1244 /* create an async on a given queue of a fd */
1245 struct async *create_async( struct thread *thread, const struct timeval *timeout,
1246 struct list *queue, void *io_apc, void *io_user, void* io_sb )
1248 struct async *async = mem_alloc( sizeof(struct async) );
1250 if (!async) return NULL;
1252 async->thread = (struct thread *)grab_object(thread);
1253 async->apc = io_apc;
1254 async->user = io_user;
1255 async->sb = io_sb;
1257 list_add_tail( queue, &async->entry );
1259 if (timeout) async->timeout = add_timeout_user( timeout, async_callback, async );
1260 else async->timeout = NULL;
1262 return async;
1265 /* terminate the async operation at the head of the queue */
1266 void async_terminate_head( struct list *queue, int status )
1268 struct list *ptr = list_head( queue );
1269 if (ptr) async_terminate( LIST_ENTRY( ptr, struct async, entry ), status );
1272 /****************************************************************/
1273 /* file descriptor functions */
1275 static void fd_dump( struct object *obj, int verbose )
1277 struct fd *fd = (struct fd *)obj;
1278 fprintf( stderr, "Fd unix_fd=%d user=%p", fd->unix_fd, fd->user );
1279 if (fd->inode) fprintf( stderr, " inode=%p unlink='%s'", fd->inode, fd->closed->unlink );
1280 fprintf( stderr, "\n" );
1283 static void fd_destroy( struct object *obj )
1285 struct fd *fd = (struct fd *)obj;
1287 async_terminate_queue( &fd->read_q, STATUS_CANCELLED );
1288 async_terminate_queue( &fd->write_q, STATUS_CANCELLED );
1290 remove_fd_locks( fd );
1291 list_remove( &fd->inode_entry );
1292 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1293 if (fd->inode)
1295 inode_add_closed_fd( fd->inode, fd->closed );
1296 release_object( fd->inode );
1298 else /* no inode, close it right away */
1300 if (fd->unix_fd != -1) close( fd->unix_fd );
1304 /* set the events that select waits for on this fd */
1305 void set_fd_events( struct fd *fd, int events )
1307 int user = fd->poll_index;
1308 assert( poll_users[user] == fd );
1310 set_fd_epoll_events( fd, user, events );
1312 if (events == -1) /* stop waiting on this fd completely */
1314 pollfd[user].fd = -1;
1315 pollfd[user].events = POLLERR;
1316 pollfd[user].revents = 0;
1318 else if (pollfd[user].fd != -1 || !pollfd[user].events)
1320 pollfd[user].fd = fd->unix_fd;
1321 pollfd[user].events = events;
1325 /* prepare an fd for unmounting its corresponding device */
1326 static inline void unmount_fd( struct fd *fd )
1328 assert( fd->inode );
1330 async_terminate_queue( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1331 async_terminate_queue( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1333 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1335 if (fd->unix_fd != -1) close( fd->unix_fd );
1337 fd->unix_fd = -1;
1338 fd->unmounted = 1;
1339 fd->closed->unix_fd = -1;
1340 fd->closed->unlink[0] = 0;
1342 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1343 fd->fs_locks = 0;
1346 /* allocate an fd object, without setting the unix fd yet */
1347 static struct fd *alloc_fd_object(void)
1349 struct fd *fd = alloc_object( &fd_ops );
1351 if (!fd) return NULL;
1353 fd->fd_ops = NULL;
1354 fd->user = NULL;
1355 fd->inode = NULL;
1356 fd->closed = NULL;
1357 fd->access = 0;
1358 fd->sharing = 0;
1359 fd->unix_fd = -1;
1360 fd->fs_locks = 1;
1361 fd->unmounted = 0;
1362 fd->poll_index = -1;
1363 list_init( &fd->inode_entry );
1364 list_init( &fd->locks );
1365 list_init( &fd->read_q );
1366 list_init( &fd->write_q );
1368 if ((fd->poll_index = add_poll_user( fd )) == -1)
1370 release_object( fd );
1371 return NULL;
1373 return fd;
1376 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1377 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user )
1379 struct fd *fd = alloc_object( &fd_ops );
1381 if (!fd) return NULL;
1383 fd->fd_ops = fd_user_ops;
1384 fd->user = user;
1385 fd->inode = NULL;
1386 fd->closed = NULL;
1387 fd->access = 0;
1388 fd->sharing = 0;
1389 fd->unix_fd = -1;
1390 fd->fs_locks = 0;
1391 fd->unmounted = 0;
1392 fd->poll_index = -1;
1393 list_init( &fd->inode_entry );
1394 list_init( &fd->locks );
1395 list_init( &fd->read_q );
1396 list_init( &fd->write_q );
1397 return fd;
1400 /* check if the desired access is possible without violating */
1401 /* the sharing mode of other opens of the same file */
1402 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
1404 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1405 unsigned int existing_access = 0;
1406 struct list *ptr;
1408 /* if access mode is 0, sharing mode is ignored */
1409 if (!access) sharing = existing_sharing;
1410 fd->access = access;
1411 fd->sharing = sharing;
1413 LIST_FOR_EACH( ptr, &fd->inode->open )
1415 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1416 if (fd_ptr != fd)
1418 existing_sharing &= fd_ptr->sharing;
1419 existing_access |= fd_ptr->access;
1423 if ((access & FILE_UNIX_READ_ACCESS) && !(existing_sharing & FILE_SHARE_READ)) return 0;
1424 if ((access & FILE_UNIX_WRITE_ACCESS) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1425 if ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1426 if ((existing_access & FILE_UNIX_READ_ACCESS) && !(sharing & FILE_SHARE_READ)) return 0;
1427 if ((existing_access & FILE_UNIX_WRITE_ACCESS) && !(sharing & FILE_SHARE_WRITE)) return 0;
1428 if ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)) return 0;
1429 return 1;
1432 /* sets the user of an fd that previously had no user */
1433 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1435 assert( fd->fd_ops == NULL );
1436 fd->fd_ops = user_ops;
1437 fd->user = user;
1440 /* open() wrapper that returns a struct fd with no fd user set */
1441 struct fd *open_fd( const char *name, int flags, mode_t *mode, unsigned int access,
1442 unsigned int sharing, unsigned int options )
1444 struct stat st;
1445 struct closed_fd *closed_fd;
1446 struct fd *fd;
1447 const char *unlink_name = "";
1448 int rw_mode;
1450 if ((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE))
1452 set_error( STATUS_INVALID_PARAMETER );
1453 return NULL;
1456 if (!(fd = alloc_fd_object())) return NULL;
1458 if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1459 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1461 release_object( fd );
1462 return NULL;
1465 /* create the directory if needed */
1466 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1468 if (mkdir( name, 0777 ) == -1)
1470 if (errno != EEXIST || (flags & O_EXCL))
1472 file_set_error();
1473 goto error;
1476 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1479 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1481 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1482 else rw_mode = O_WRONLY;
1484 else rw_mode = O_RDONLY;
1486 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1488 /* if we tried to open a directory for write access, retry read-only */
1489 if (errno != EISDIR ||
1490 !(access & FILE_UNIX_WRITE_ACCESS) ||
1491 (fd->unix_fd = open( name, O_RDONLY | (flags & ~O_TRUNC), *mode )) == -1)
1493 file_set_error();
1494 goto error;
1498 closed_fd->unix_fd = fd->unix_fd;
1499 closed_fd->unlink[0] = 0;
1500 fstat( fd->unix_fd, &st );
1501 *mode = st.st_mode;
1503 /* only bother with an inode for normal files and directories */
1504 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1506 struct inode *inode = get_inode( st.st_dev, st.st_ino );
1508 if (!inode)
1510 /* we can close the fd because there are no others open on the same file,
1511 * otherwise we wouldn't have failed to allocate a new inode
1513 goto error;
1515 fd->inode = inode;
1516 fd->closed = closed_fd;
1517 list_add_head( &inode->open, &fd->inode_entry );
1519 /* check directory options */
1520 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1522 release_object( fd );
1523 set_error( STATUS_NOT_A_DIRECTORY );
1524 return NULL;
1526 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1528 release_object( fd );
1529 set_error( STATUS_FILE_IS_A_DIRECTORY );
1530 return NULL;
1532 if (!check_sharing( fd, access, sharing ))
1534 release_object( fd );
1535 set_error( STATUS_SHARING_VIOLATION );
1536 return NULL;
1538 strcpy( closed_fd->unlink, unlink_name );
1539 if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1541 else /* special file */
1543 if (options & FILE_DIRECTORY_FILE)
1545 set_error( STATUS_NOT_A_DIRECTORY );
1546 goto error;
1548 if (unlink_name[0]) /* we can't unlink special files */
1550 set_error( STATUS_INVALID_PARAMETER );
1551 goto error;
1553 free( closed_fd );
1555 return fd;
1557 error:
1558 release_object( fd );
1559 free( closed_fd );
1560 return NULL;
1563 /* create an fd for an anonymous file */
1564 /* if the function fails the unix fd is closed */
1565 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user )
1567 struct fd *fd = alloc_fd_object();
1569 if (fd)
1571 set_fd_user( fd, fd_user_ops, user );
1572 fd->unix_fd = unix_fd;
1573 return fd;
1575 close( unix_fd );
1576 return NULL;
1579 /* retrieve the object that is using an fd */
1580 void *get_fd_user( struct fd *fd )
1582 return fd->user;
1585 /* retrieve the unix fd for an object */
1586 int get_unix_fd( struct fd *fd )
1588 if (fd->unix_fd == -1)
1590 if (fd->unmounted) set_error( STATUS_VOLUME_DISMOUNTED );
1591 else set_error( STATUS_BAD_DEVICE_TYPE );
1593 return fd->unix_fd;
1596 /* check if two file descriptors point to the same file */
1597 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1599 return fd1->inode == fd2->inode;
1602 /* callback for event happening in the main poll() loop */
1603 void fd_poll_event( struct fd *fd, int event )
1605 return fd->fd_ops->poll_event( fd, event );
1608 /* check if events are pending and if yes return which one(s) */
1609 int check_fd_events( struct fd *fd, int events )
1611 struct pollfd pfd;
1613 if (fd->unix_fd == -1) return POLLERR;
1615 pfd.fd = fd->unix_fd;
1616 pfd.events = events;
1617 if (poll( &pfd, 1, 0 ) <= 0) return 0;
1618 return pfd.revents;
1621 /* default add_queue() routine for objects that poll() on an fd */
1622 int default_fd_add_queue( struct object *obj, struct wait_queue_entry *entry )
1624 struct fd *fd = get_obj_fd( obj );
1626 if (!fd) return 0;
1627 if (!fd->inode && list_empty( &obj->wait_queue )) /* first on the queue */
1628 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1629 add_queue( obj, entry );
1630 release_object( fd );
1631 return 1;
1634 /* default remove_queue() routine for objects that poll() on an fd */
1635 void default_fd_remove_queue( struct object *obj, struct wait_queue_entry *entry )
1637 struct fd *fd = get_obj_fd( obj );
1639 grab_object( obj );
1640 remove_queue( obj, entry );
1641 if (!fd->inode && list_empty( &obj->wait_queue )) /* last on the queue is gone */
1642 set_fd_events( fd, 0 );
1643 release_object( obj );
1644 release_object( fd );
1647 /* default signaled() routine for objects that poll() on an fd */
1648 int default_fd_signaled( struct object *obj, struct thread *thread )
1650 int events, ret;
1651 struct fd *fd = get_obj_fd( obj );
1653 if (fd->inode) ret = 1; /* regular files are always signaled */
1654 else
1656 events = fd->fd_ops->get_poll_events( fd );
1657 ret = check_fd_events( fd, events ) != 0;
1659 if (ret)
1661 /* stop waiting on select() if we are signaled */
1662 set_fd_events( fd, 0 );
1664 else if (!list_empty( &obj->wait_queue ))
1666 /* restart waiting on poll() if we are no longer signaled */
1667 set_fd_events( fd, events );
1670 release_object( fd );
1671 return ret;
1674 int default_fd_get_poll_events( struct fd *fd )
1676 int events = 0;
1678 if (!list_empty( &fd->read_q ))
1679 events |= POLLIN;
1680 if (!list_empty( &fd->write_q ))
1681 events |= POLLOUT;
1683 return events;
1686 /* default handler for poll() events */
1687 void default_poll_event( struct fd *fd, int event )
1689 if (!list_empty( &fd->read_q ) && (POLLIN & event) )
1691 async_terminate_head( &fd->read_q, STATUS_ALERTED );
1692 return;
1694 if (!list_empty( &fd->write_q ) && (POLLOUT & event) )
1696 async_terminate_head( &fd->write_q, STATUS_ALERTED );
1697 return;
1700 /* if an error occurred, stop polling this fd to avoid busy-looping */
1701 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1702 wake_up( fd->user, 0 );
1705 void fd_queue_async_timeout( struct fd *fd, void *apc, void *user, void *io_sb, int type, int count,
1706 const struct timeval *timeout )
1708 struct list *queue;
1709 int events;
1711 if (!(fd->fd_ops->get_file_info( fd ) & (FD_FLAG_OVERLAPPED|FD_FLAG_TIMEOUT)))
1713 set_error( STATUS_INVALID_HANDLE );
1714 return;
1717 switch (type)
1719 case ASYNC_TYPE_READ:
1720 queue = &fd->read_q;
1721 break;
1722 case ASYNC_TYPE_WRITE:
1723 queue = &fd->write_q;
1724 break;
1725 default:
1726 set_error( STATUS_INVALID_PARAMETER );
1727 return;
1730 if (!create_async( current, timeout, queue, apc, user, io_sb ))
1731 return;
1733 /* Check if the new pending request can be served immediately */
1734 events = check_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1735 if (events) fd->fd_ops->poll_event( fd, events );
1737 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1740 void default_fd_queue_async( struct fd *fd, void *apc, void *user, void *io_sb, int type, int count )
1742 fd_queue_async_timeout( fd, apc, user, io_sb, type, count, NULL );
1745 void default_fd_cancel_async( struct fd *fd )
1747 async_terminate_queue( &fd->read_q, STATUS_CANCELLED );
1748 async_terminate_queue( &fd->write_q, STATUS_CANCELLED );
1751 /* default flush() routine */
1752 int no_flush( struct fd *fd, struct event **event )
1754 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1755 return 0;
1758 /* default get_file_info() routine */
1759 int no_get_file_info( struct fd *fd )
1761 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1762 return 0;
1765 /* default queue_async() routine */
1766 void no_queue_async( struct fd *fd, void* apc, void* user, void* io_sb,
1767 int type, int count)
1769 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1772 /* default cancel_async() routine */
1773 void no_cancel_async( struct fd *fd )
1775 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1778 /* close all Unix file descriptors on a device to allow unmounting it */
1779 static void unmount_device( struct fd *device_fd )
1781 unsigned int i;
1782 struct stat st;
1783 struct device *device;
1784 struct inode *inode;
1785 struct fd *fd;
1786 int unix_fd = get_unix_fd( device_fd );
1788 if (unix_fd == -1) return;
1790 if (fstat( unix_fd, &st ) == -1 || !S_ISBLK( st.st_mode ))
1792 set_error( STATUS_INVALID_PARAMETER );
1793 return;
1796 if (!(device = get_device( st.st_rdev, 0 ))) return;
1798 for (i = 0; i < INODE_HASH_SIZE; i++)
1800 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
1802 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
1804 unmount_fd( fd );
1806 inode_close_pending( inode, 0 );
1809 /* remove it from the hash table */
1810 list_remove( &device->entry );
1811 list_init( &device->entry );
1812 release_object( device );
1815 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1816 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1817 unsigned int access )
1819 struct fd *fd = NULL;
1820 struct object *obj;
1822 if ((obj = get_handle_obj( process, handle, access, NULL )))
1824 fd = get_obj_fd( obj );
1825 release_object( obj );
1827 return fd;
1830 /* flush a file buffers */
1831 DECL_HANDLER(flush_file)
1833 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1834 struct event * event = NULL;
1836 if (fd)
1838 fd->fd_ops->flush( fd, &event );
1839 if ( event )
1841 reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1843 release_object( fd );
1847 /* open a file object */
1848 DECL_HANDLER(open_file_object)
1850 struct unicode_str name;
1851 struct directory *root = NULL;
1852 struct object *obj;
1854 get_req_unicode_str( &name );
1855 if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
1856 return;
1858 if ((obj = open_object_dir( root, &name, req->attributes, NULL )))
1860 /* make sure this is a valid file object */
1861 struct fd *fd = get_obj_fd( obj );
1862 if (fd)
1864 reply->handle = alloc_handle( current->process, obj, req->access, req->attributes );
1865 release_object( fd );
1867 release_object( obj );
1870 if (root) release_object( root );
1873 /* get a Unix fd to access a file */
1874 DECL_HANDLER(get_handle_fd)
1876 struct fd *fd;
1878 reply->fd = -1;
1880 if ((fd = get_handle_fd_obj( current->process, req->handle, req->access )))
1882 int unix_fd = get_unix_fd( fd );
1883 if (unix_fd != -1)
1885 int cached_fd = get_handle_unix_fd( current->process, req->handle, req->access );
1886 if (cached_fd != -1) reply->fd = cached_fd;
1887 else if (!get_error()) send_client_fd( current->process, unix_fd, req->handle );
1889 if (fd->inode) reply->removable = fd->inode->device->removable;
1890 reply->flags = fd->fd_ops->get_file_info( fd );
1891 release_object( fd );
1895 /* set the cached file descriptor of a handle */
1896 DECL_HANDLER(set_handle_fd)
1898 struct fd *fd;
1900 reply->cur_fd = -1;
1901 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
1903 struct device *device = fd->inode ? fd->inode->device : NULL;
1905 if (device && device->removable == -1) device->removable = req->removable;
1907 /* only cache the fd on non-removable devices */
1908 if (!device || !device->removable)
1909 reply->cur_fd = set_handle_unix_fd( current->process, req->handle, req->fd );
1910 release_object( fd );
1914 /* get ready to unmount a Unix device */
1915 DECL_HANDLER(unmount_device)
1917 struct fd *fd;
1919 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
1921 unmount_device( fd );
1922 release_object( fd );
1926 /* create / reschedule an async I/O */
1927 DECL_HANDLER(register_async)
1929 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1932 * The queue_async method must do the following:
1934 * 1. Get the async_queue for the request of given type.
1935 * 2. Create a new asynchronous request for the selected queue
1936 * 3. Carry out any operations necessary to adjust the object's poll events
1937 * Usually: set_elect_events (obj, obj->ops->get_poll_events()).
1938 * 4. When the async request is triggered, then send back (with a proper APC)
1939 * the trigger (STATUS_ALERTED) to the thread that posted the request.
1940 * async_destroy() is to be called: it will both notify the sender about
1941 * the trigger and destroy the request by itself
1942 * See also the implementations in file.c, serial.c, and sock.c.
1945 if (fd)
1947 fd->fd_ops->queue_async( fd, req->io_apc, req->io_user, req->io_sb,
1948 req->type, req->count );
1949 release_object( fd );
1953 /* cancels all async I/O */
1954 DECL_HANDLER(cancel_async)
1956 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1957 if (fd)
1959 /* Note: we don't kill the queued APC_ASYNC_IO on this thread because
1960 * NtCancelIoFile() will force the pending APC to be run. Since,
1961 * Windows only guarantees that the current thread will have no async
1962 * operation on the current fd when NtCancelIoFile returns, this shall
1963 * do the work.
1965 fd->fd_ops->cancel_async( fd );
1966 release_object( fd );