server: Add a default access mapping function for files, and use it for devices too.
[wine.git] / server / fd.c
blob4779475ae23ee5d502513b25f9d9996558c43c37
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_LINUX_MAJOR_H
41 #include <linux/major.h>
42 #endif
43 #ifdef HAVE_SYS_STATVFS_H
44 #include <sys/statvfs.h>
45 #endif
46 #ifdef HAVE_SYS_VFS_H
47 #include <sys/vfs.h>
48 #endif
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
51 #endif
52 #ifdef HAVE_SYS_MOUNT_H
53 #include <sys/mount.h>
54 #endif
55 #ifdef HAVE_SYS_STATFS_H
56 #include <sys/statfs.h>
57 #endif
58 #ifdef HAVE_SYS_SYSCTL_H
59 #include <sys/sysctl.h>
60 #endif
61 #ifdef HAVE_SYS_EVENT_H
62 #include <sys/event.h>
63 #undef LIST_INIT
64 #undef LIST_ENTRY
65 #endif
66 #ifdef HAVE_STDINT_H
67 #include <stdint.h>
68 #endif
69 #include <sys/stat.h>
70 #include <sys/time.h>
71 #include <sys/types.h>
72 #include <unistd.h>
74 #include "ntstatus.h"
75 #define WIN32_NO_STATUS
76 #include "object.h"
77 #include "file.h"
78 #include "handle.h"
79 #include "process.h"
80 #include "request.h"
82 #include "winternl.h"
83 #include "winioctl.h"
85 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
86 # include <sys/epoll.h>
87 # define USE_EPOLL
88 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
89 # define USE_EPOLL
90 # define EPOLLIN POLLIN
91 # define EPOLLOUT POLLOUT
92 # define EPOLLERR POLLERR
93 # define EPOLLHUP POLLHUP
94 # define EPOLL_CTL_ADD 1
95 # define EPOLL_CTL_DEL 2
96 # define EPOLL_CTL_MOD 3
98 typedef union epoll_data
100 void *ptr;
101 int fd;
102 uint32_t u32;
103 uint64_t u64;
104 } epoll_data_t;
106 struct epoll_event
108 uint32_t events;
109 epoll_data_t data;
112 #define SYSCALL_RET(ret) do { \
113 if (ret < 0) { errno = -ret; ret = -1; } \
114 return ret; \
115 } while(0)
117 static inline int epoll_create( int size )
119 int ret;
120 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
121 : "=a" (ret) : "0" (254 /*NR_epoll_create*/), "r" (size) );
122 SYSCALL_RET(ret);
125 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
127 int ret;
128 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
129 : "=a" (ret)
130 : "0" (255 /*NR_epoll_ctl*/), "r" (epfd), "c" (op), "d" (fd), "S" (event), "m" (*event) );
131 SYSCALL_RET(ret);
134 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
136 int ret;
137 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
138 : "=a" (ret)
139 : "0" (256 /*NR_epoll_wait*/), "r" (epfd), "c" (events), "d" (maxevents), "S" (timeout)
140 : "memory" );
141 SYSCALL_RET(ret);
143 #undef SYSCALL_RET
145 #endif /* linux && __i386__ && HAVE_STDINT_H */
148 /* Because of the stupid Posix locking semantics, we need to keep
149 * track of all file descriptors referencing a given file, and not
150 * close a single one until all the locks are gone (sigh).
153 /* file descriptor object */
155 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
156 struct closed_fd
158 struct list entry; /* entry in inode closed list */
159 int unix_fd; /* the unix file descriptor */
160 char unlink[1]; /* name to unlink on close (if any) */
163 struct fd
165 struct object obj; /* object header */
166 const struct fd_ops *fd_ops; /* file descriptor operations */
167 struct inode *inode; /* inode that this fd belongs to */
168 struct list inode_entry; /* entry in inode fd list */
169 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
170 struct object *user; /* object using this file descriptor */
171 struct list locks; /* list of locks on this fd */
172 unsigned int access; /* file access (FILE_READ_DATA etc.) */
173 unsigned int options; /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
174 unsigned int sharing; /* file sharing mode */
175 int unix_fd; /* unix file descriptor */
176 unsigned int no_fd_status;/* status to return when unix_fd is -1 */
177 int signaled :1; /* is the fd signaled? */
178 int fs_locks :1; /* can we use filesystem locks for this fd? */
179 int poll_index; /* index of fd in poll array */
180 struct async_queue *read_q; /* async readers of this fd */
181 struct async_queue *write_q; /* async writers of this fd */
182 struct async_queue *wait_q; /* other async waiters of this fd */
183 struct completion *completion; /* completion object attached to this fd */
184 unsigned long comp_key; /* completion key to set in completion events */
187 static void fd_dump( struct object *obj, int verbose );
188 static void fd_destroy( struct object *obj );
190 static const struct object_ops fd_ops =
192 sizeof(struct fd), /* size */
193 fd_dump, /* dump */
194 no_add_queue, /* add_queue */
195 NULL, /* remove_queue */
196 NULL, /* signaled */
197 NULL, /* satisfied */
198 no_signal, /* signal */
199 no_get_fd, /* get_fd */
200 no_map_access, /* map_access */
201 no_lookup_name, /* lookup_name */
202 no_open_file, /* open_file */
203 no_close_handle, /* close_handle */
204 fd_destroy /* destroy */
207 /* device object */
209 #define DEVICE_HASH_SIZE 7
210 #define INODE_HASH_SIZE 17
212 struct device
214 struct object obj; /* object header */
215 struct list entry; /* entry in device hash list */
216 dev_t dev; /* device number */
217 int removable; /* removable device? (or -1 if unknown) */
218 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
221 static void device_dump( struct object *obj, int verbose );
222 static void device_destroy( struct object *obj );
224 static const struct object_ops device_ops =
226 sizeof(struct device), /* size */
227 device_dump, /* dump */
228 no_add_queue, /* add_queue */
229 NULL, /* remove_queue */
230 NULL, /* signaled */
231 NULL, /* satisfied */
232 no_signal, /* signal */
233 no_get_fd, /* get_fd */
234 no_map_access, /* map_access */
235 no_lookup_name, /* lookup_name */
236 no_open_file, /* open_file */
237 no_close_handle, /* close_handle */
238 device_destroy /* destroy */
241 /* inode object */
243 struct inode
245 struct object obj; /* object header */
246 struct list entry; /* inode hash list entry */
247 struct device *device; /* device containing this inode */
248 ino_t ino; /* inode number */
249 struct list open; /* list of open file descriptors */
250 struct list locks; /* list of file locks */
251 struct list closed; /* list of file descriptors to close at destroy time */
254 static void inode_dump( struct object *obj, int verbose );
255 static void inode_destroy( struct object *obj );
257 static const struct object_ops inode_ops =
259 sizeof(struct inode), /* size */
260 inode_dump, /* dump */
261 no_add_queue, /* add_queue */
262 NULL, /* remove_queue */
263 NULL, /* signaled */
264 NULL, /* satisfied */
265 no_signal, /* signal */
266 no_get_fd, /* get_fd */
267 no_map_access, /* map_access */
268 no_lookup_name, /* lookup_name */
269 no_open_file, /* open_file */
270 no_close_handle, /* close_handle */
271 inode_destroy /* destroy */
274 /* file lock object */
276 struct file_lock
278 struct object obj; /* object header */
279 struct fd *fd; /* fd owning this lock */
280 struct list fd_entry; /* entry in list of locks on a given fd */
281 struct list inode_entry; /* entry in inode list of locks */
282 int shared; /* shared lock? */
283 file_pos_t start; /* locked region is interval [start;end) */
284 file_pos_t end;
285 struct process *process; /* process owning this lock */
286 struct list proc_entry; /* entry in list of locks owned by the process */
289 static void file_lock_dump( struct object *obj, int verbose );
290 static int file_lock_signaled( struct object *obj, struct thread *thread );
292 static const struct object_ops file_lock_ops =
294 sizeof(struct file_lock), /* size */
295 file_lock_dump, /* dump */
296 add_queue, /* add_queue */
297 remove_queue, /* remove_queue */
298 file_lock_signaled, /* signaled */
299 no_satisfied, /* satisfied */
300 no_signal, /* signal */
301 no_get_fd, /* get_fd */
302 no_map_access, /* map_access */
303 no_lookup_name, /* lookup_name */
304 no_open_file, /* open_file */
305 no_close_handle, /* close_handle */
306 no_destroy /* destroy */
310 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
311 #define FILE_POS_T_MAX (~(file_pos_t)0)
313 static file_pos_t max_unix_offset = OFF_T_MAX;
315 #define DUMP_LONG_LONG(val) do { \
316 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
317 fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
318 else \
319 fprintf( stderr, "%lx", (unsigned long)(val) ); \
320 } while (0)
324 /****************************************************************/
325 /* timeouts support */
327 struct timeout_user
329 struct list entry; /* entry in sorted timeout list */
330 timeout_t when; /* timeout expiry (absolute time) */
331 timeout_callback callback; /* callback function */
332 void *private; /* callback private data */
335 static struct list timeout_list = LIST_INIT(timeout_list); /* sorted timeouts list */
336 timeout_t current_time;
338 static inline void set_current_time(void)
340 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
341 struct timeval now;
342 gettimeofday( &now, NULL );
343 current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
346 /* add a timeout user */
347 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
349 struct timeout_user *user;
350 struct list *ptr;
352 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
353 user->when = (when > 0) ? when : current_time - when;
354 user->callback = func;
355 user->private = private;
357 /* Now insert it in the linked list */
359 LIST_FOR_EACH( ptr, &timeout_list )
361 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
362 if (timeout->when >= user->when) break;
364 list_add_before( ptr, &user->entry );
365 return user;
368 /* remove a timeout user */
369 void remove_timeout_user( struct timeout_user *user )
371 list_remove( &user->entry );
372 free( user );
375 /* return a text description of a timeout for debugging purposes */
376 const char *get_timeout_str( timeout_t timeout )
378 static char buffer[64];
379 long secs, nsecs;
381 if (!timeout) return "0";
382 if (timeout == TIMEOUT_INFINITE) return "infinite";
384 if (timeout < 0) /* relative */
386 secs = -timeout / TICKS_PER_SEC;
387 nsecs = -timeout % TICKS_PER_SEC;
388 sprintf( buffer, "+%ld.%07ld", secs, nsecs );
390 else /* absolute */
392 secs = (timeout - current_time) / TICKS_PER_SEC;
393 nsecs = (timeout - current_time) % TICKS_PER_SEC;
394 if (nsecs < 0)
396 nsecs += TICKS_PER_SEC;
397 secs--;
399 if (secs >= 0)
400 sprintf( buffer, "%x%08x (+%ld.%07ld)",
401 (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
402 else
403 sprintf( buffer, "%x%08x (-%ld.%07ld)",
404 (unsigned int)(timeout >> 32), (unsigned int)timeout,
405 -(secs + 1), TICKS_PER_SEC - nsecs );
407 return buffer;
411 /****************************************************************/
412 /* poll support */
414 static struct fd **poll_users; /* users array */
415 static struct pollfd *pollfd; /* poll fd array */
416 static int nb_users; /* count of array entries actually in use */
417 static int active_users; /* current number of active users */
418 static int allocated_users; /* count of allocated entries in the array */
419 static struct fd **freelist; /* list of free entries in the array */
421 static int get_next_timeout(void);
423 #ifdef USE_EPOLL
425 static int epoll_fd = -1;
427 static inline void init_epoll(void)
429 epoll_fd = epoll_create( 128 );
432 /* set the events that epoll waits for on this fd; helper for set_fd_events */
433 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
435 struct epoll_event ev;
436 int ctl;
438 if (epoll_fd == -1) return;
440 if (events == -1) /* stop waiting on this fd completely */
442 if (pollfd[user].fd == -1) return; /* already removed */
443 ctl = EPOLL_CTL_DEL;
445 else if (pollfd[user].fd == -1)
447 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
448 ctl = EPOLL_CTL_ADD;
450 else
452 if (pollfd[user].events == events) return; /* nothing to do */
453 ctl = EPOLL_CTL_MOD;
456 ev.events = events;
457 memset(&ev.data, 0, sizeof(ev.data));
458 ev.data.u32 = user;
460 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
462 if (errno == ENOMEM) /* not enough memory, give up on epoll */
464 close( epoll_fd );
465 epoll_fd = -1;
467 else perror( "epoll_ctl" ); /* should not happen */
471 static inline void remove_epoll_user( struct fd *fd, int user )
473 if (epoll_fd == -1) return;
475 if (pollfd[user].fd != -1)
477 struct epoll_event dummy;
478 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
482 static inline void main_loop_epoll(void)
484 int i, ret, timeout;
485 struct epoll_event events[128];
487 assert( POLLIN == EPOLLIN );
488 assert( POLLOUT == EPOLLOUT );
489 assert( POLLERR == EPOLLERR );
490 assert( POLLHUP == EPOLLHUP );
492 if (epoll_fd == -1) return;
494 while (active_users)
496 timeout = get_next_timeout();
498 if (!active_users) break; /* last user removed by a timeout */
499 if (epoll_fd == -1) break; /* an error occurred with epoll */
501 ret = epoll_wait( epoll_fd, events, sizeof(events)/sizeof(events[0]), timeout );
502 set_current_time();
504 /* put the events into the pollfd array first, like poll does */
505 for (i = 0; i < ret; i++)
507 int user = events[i].data.u32;
508 pollfd[user].revents = events[i].events;
511 /* read events from the pollfd array, as set_fd_events may modify them */
512 for (i = 0; i < ret; i++)
514 int user = events[i].data.u32;
515 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
520 #elif defined(HAVE_KQUEUE)
522 static int kqueue_fd = -1;
524 static inline void init_epoll(void)
526 #ifdef __APPLE__ /* kqueue support is broken in Mac OS < 10.5 */
527 int mib[2];
528 char release[32];
529 size_t len = sizeof(release);
531 mib[0] = CTL_KERN;
532 mib[1] = KERN_OSRELEASE;
533 if (sysctl( mib, 2, release, &len, NULL, 0 ) == -1) return;
534 if (atoi(release) < 9) return;
535 #endif
536 kqueue_fd = kqueue();
539 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
541 struct kevent ev[2];
543 if (kqueue_fd == -1) return;
545 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)user );
546 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)user );
548 if (events == -1) /* stop waiting on this fd completely */
550 if (pollfd[user].fd == -1) return; /* already removed */
551 ev[0].flags |= EV_DELETE;
552 ev[1].flags |= EV_DELETE;
554 else if (pollfd[user].fd == -1)
556 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
557 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
558 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
560 else
562 if (pollfd[user].events == events) return; /* nothing to do */
563 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
564 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
567 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
569 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
571 close( kqueue_fd );
572 kqueue_fd = -1;
574 else perror( "kevent" ); /* should not happen */
578 static inline void remove_epoll_user( struct fd *fd, int user )
580 if (kqueue_fd == -1) return;
582 if (pollfd[user].fd != -1)
584 struct kevent ev[2];
586 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
587 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
588 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
592 static inline void main_loop_epoll(void)
594 int i, ret, timeout;
595 struct kevent events[128];
597 if (kqueue_fd == -1) return;
599 while (active_users)
601 timeout = get_next_timeout();
603 if (!active_users) break; /* last user removed by a timeout */
604 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
606 if (timeout != -1)
608 struct timespec ts;
610 ts.tv_sec = timeout / 1000;
611 ts.tv_nsec = (timeout % 1000) * 1000000;
612 ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), &ts );
614 else ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), NULL );
616 set_current_time();
618 /* put the events into the pollfd array first, like poll does */
619 for (i = 0; i < ret; i++)
621 long user = (long)events[i].udata;
622 pollfd[user].revents = 0;
624 for (i = 0; i < ret; i++)
626 long user = (long)events[i].udata;
627 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
628 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
629 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
630 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
633 /* read events from the pollfd array, as set_fd_events may modify them */
634 for (i = 0; i < ret; i++)
636 long user = (long)events[i].udata;
637 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
638 pollfd[user].revents = 0;
643 #else /* HAVE_KQUEUE */
645 static inline void init_epoll(void) { }
646 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
647 static inline void remove_epoll_user( struct fd *fd, int user ) { }
648 static inline void main_loop_epoll(void) { }
650 #endif /* USE_EPOLL */
653 /* add a user in the poll array and return its index, or -1 on failure */
654 static int add_poll_user( struct fd *fd )
656 int ret;
657 if (freelist)
659 ret = freelist - poll_users;
660 freelist = (struct fd **)poll_users[ret];
662 else
664 if (nb_users == allocated_users)
666 struct fd **newusers;
667 struct pollfd *newpoll;
668 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
669 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
670 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
672 if (allocated_users)
673 poll_users = newusers;
674 else
675 free( newusers );
676 return -1;
678 poll_users = newusers;
679 pollfd = newpoll;
680 if (!allocated_users) init_epoll();
681 allocated_users = new_count;
683 ret = nb_users++;
685 pollfd[ret].fd = -1;
686 pollfd[ret].events = 0;
687 pollfd[ret].revents = 0;
688 poll_users[ret] = fd;
689 active_users++;
690 return ret;
693 /* remove a user from the poll list */
694 static void remove_poll_user( struct fd *fd, int user )
696 assert( user >= 0 );
697 assert( poll_users[user] == fd );
699 remove_epoll_user( fd, user );
700 pollfd[user].fd = -1;
701 pollfd[user].events = 0;
702 pollfd[user].revents = 0;
703 poll_users[user] = (struct fd *)freelist;
704 freelist = &poll_users[user];
705 active_users--;
708 /* process pending timeouts and return the time until the next timeout, in milliseconds */
709 static int get_next_timeout(void)
711 if (!list_empty( &timeout_list ))
713 struct list expired_list, *ptr;
715 /* first remove all expired timers from the list */
717 list_init( &expired_list );
718 while ((ptr = list_head( &timeout_list )) != NULL)
720 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
722 if (timeout->when <= current_time)
724 list_remove( &timeout->entry );
725 list_add_tail( &expired_list, &timeout->entry );
727 else break;
730 /* now call the callback for all the removed timers */
732 while ((ptr = list_head( &expired_list )) != NULL)
734 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
735 list_remove( &timeout->entry );
736 timeout->callback( timeout->private );
737 free( timeout );
740 if ((ptr = list_head( &timeout_list )) != NULL)
742 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
743 int diff = (timeout->when - current_time + 9999) / 10000;
744 if (diff < 0) diff = 0;
745 return diff;
748 return -1; /* no pending timeouts */
751 /* server main poll() loop */
752 void main_loop(void)
754 int i, ret, timeout;
756 set_current_time();
757 server_start_time = current_time;
759 main_loop_epoll();
760 /* fall through to normal poll loop */
762 while (active_users)
764 timeout = get_next_timeout();
766 if (!active_users) break; /* last user removed by a timeout */
768 ret = poll( pollfd, nb_users, timeout );
769 set_current_time();
771 if (ret > 0)
773 for (i = 0; i < nb_users; i++)
775 if (pollfd[i].revents)
777 fd_poll_event( poll_users[i], pollfd[i].revents );
778 if (!--ret) break;
786 /****************************************************************/
787 /* device functions */
789 static struct list device_hash[DEVICE_HASH_SIZE];
791 static int is_device_removable( dev_t dev, int unix_fd )
793 #if defined(linux) && defined(HAVE_FSTATFS)
794 struct statfs stfs;
796 /* check for floppy disk */
797 if (major(dev) == FLOPPY_MAJOR) return 1;
799 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
800 return (stfs.f_type == 0x9660 || /* iso9660 */
801 stfs.f_type == 0x9fa1 || /* supermount */
802 stfs.f_type == 0x15013346); /* udf */
803 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
804 struct statfs stfs;
806 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
807 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
808 #elif defined(__NetBSD__)
809 struct statvfs stfs;
811 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
812 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
813 #elif defined(sun)
814 # include <sys/dkio.h>
815 # include <sys/vtoc.h>
816 struct dk_cinfo dkinf;
817 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
818 return (dkinf.dki_ctype == DKC_CDROM ||
819 dkinf.dki_ctype == DKC_NCRFLOPPY ||
820 dkinf.dki_ctype == DKC_SMSFLOPPY ||
821 dkinf.dki_ctype == DKC_INTEL82072 ||
822 dkinf.dki_ctype == DKC_INTEL82077);
823 #else
824 return 0;
825 #endif
828 /* retrieve the device object for a given fd, creating it if needed */
829 static struct device *get_device( dev_t dev, int unix_fd )
831 struct device *device;
832 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
834 if (device_hash[hash].next)
836 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
837 if (device->dev == dev) return (struct device *)grab_object( device );
839 else list_init( &device_hash[hash] );
841 /* not found, create it */
843 if (unix_fd == -1) return NULL;
844 if ((device = alloc_object( &device_ops )))
846 device->dev = dev;
847 device->removable = is_device_removable( dev, unix_fd );
848 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
849 list_add_head( &device_hash[hash], &device->entry );
851 return device;
854 static void device_dump( struct object *obj, int verbose )
856 struct device *device = (struct device *)obj;
857 fprintf( stderr, "Device dev=" );
858 DUMP_LONG_LONG( device->dev );
859 fprintf( stderr, "\n" );
862 static void device_destroy( struct object *obj )
864 struct device *device = (struct device *)obj;
865 unsigned int i;
867 for (i = 0; i < INODE_HASH_SIZE; i++)
868 assert( list_empty(&device->inode_hash[i]) );
870 list_remove( &device->entry ); /* remove it from the hash table */
874 /****************************************************************/
875 /* inode functions */
877 /* close all pending file descriptors in the closed list */
878 static void inode_close_pending( struct inode *inode, int keep_unlinks )
880 struct list *ptr = list_head( &inode->closed );
882 while (ptr)
884 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
885 struct list *next = list_next( &inode->closed, ptr );
887 if (fd->unix_fd != -1)
889 close( fd->unix_fd );
890 fd->unix_fd = -1;
892 if (!keep_unlinks || !fd->unlink[0]) /* get rid of it unless there's an unlink pending on that file */
894 list_remove( ptr );
895 free( fd );
897 ptr = next;
901 static void inode_dump( struct object *obj, int verbose )
903 struct inode *inode = (struct inode *)obj;
904 fprintf( stderr, "Inode device=%p ino=", inode->device );
905 DUMP_LONG_LONG( inode->ino );
906 fprintf( stderr, "\n" );
909 static void inode_destroy( struct object *obj )
911 struct inode *inode = (struct inode *)obj;
912 struct list *ptr;
914 assert( list_empty(&inode->open) );
915 assert( list_empty(&inode->locks) );
917 list_remove( &inode->entry );
919 while ((ptr = list_head( &inode->closed )))
921 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
922 list_remove( ptr );
923 if (fd->unix_fd != -1) close( fd->unix_fd );
924 if (fd->unlink[0])
926 /* make sure it is still the same file */
927 struct stat st;
928 if (!stat( fd->unlink, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
930 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
931 else unlink( fd->unlink );
934 free( fd );
936 release_object( inode->device );
939 /* retrieve the inode object for a given fd, creating it if needed */
940 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
942 struct device *device;
943 struct inode *inode;
944 unsigned int hash = ino % INODE_HASH_SIZE;
946 if (!(device = get_device( dev, unix_fd ))) return NULL;
948 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
950 if (inode->ino == ino)
952 release_object( device );
953 return (struct inode *)grab_object( inode );
957 /* not found, create it */
958 if ((inode = alloc_object( &inode_ops )))
960 inode->device = device;
961 inode->ino = ino;
962 list_init( &inode->open );
963 list_init( &inode->locks );
964 list_init( &inode->closed );
965 list_add_head( &device->inode_hash[hash], &inode->entry );
967 else release_object( device );
969 return inode;
972 /* add fd to the inode list of file descriptors to close */
973 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
975 if (!list_empty( &inode->locks ))
977 list_add_head( &inode->closed, &fd->entry );
979 else if (fd->unlink[0]) /* close the fd but keep the structure around for unlink */
981 if (fd->unix_fd != -1) close( fd->unix_fd );
982 fd->unix_fd = -1;
983 list_add_head( &inode->closed, &fd->entry );
985 else /* no locks on this inode and no unlink, get rid of the fd */
987 if (fd->unix_fd != -1) close( fd->unix_fd );
988 free( fd );
993 /****************************************************************/
994 /* file lock functions */
996 static void file_lock_dump( struct object *obj, int verbose )
998 struct file_lock *lock = (struct file_lock *)obj;
999 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1000 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1001 DUMP_LONG_LONG( lock->start );
1002 fprintf( stderr, " end=" );
1003 DUMP_LONG_LONG( lock->end );
1004 fprintf( stderr, "\n" );
1007 static int file_lock_signaled( struct object *obj, struct thread *thread )
1009 struct file_lock *lock = (struct file_lock *)obj;
1010 /* lock is signaled if it has lost its owner */
1011 return !lock->process;
1014 /* set (or remove) a Unix lock if possible for the given range */
1015 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1017 struct flock fl;
1019 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1020 for (;;)
1022 if (start == end) return 1; /* can't set zero-byte lock */
1023 if (start > max_unix_offset) return 1; /* ignore it */
1024 fl.l_type = type;
1025 fl.l_whence = SEEK_SET;
1026 fl.l_start = start;
1027 if (!end || end > max_unix_offset) fl.l_len = 0;
1028 else fl.l_len = end - start;
1029 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1031 switch(errno)
1033 case EACCES:
1034 /* check whether locks work at all on this file system */
1035 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1037 set_error( STATUS_FILE_LOCK_CONFLICT );
1038 return 0;
1040 /* fall through */
1041 case EIO:
1042 case ENOLCK:
1043 /* no locking on this fs, just ignore it */
1044 fd->fs_locks = 0;
1045 return 1;
1046 case EAGAIN:
1047 set_error( STATUS_FILE_LOCK_CONFLICT );
1048 return 0;
1049 case EBADF:
1050 /* this can happen if we try to set a write lock on a read-only file */
1051 /* we just ignore that error */
1052 if (fl.l_type == F_WRLCK) return 1;
1053 set_error( STATUS_ACCESS_DENIED );
1054 return 0;
1055 #ifdef EOVERFLOW
1056 case EOVERFLOW:
1057 #endif
1058 case EINVAL:
1059 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1060 /* in that case we shrink the limit and retry */
1061 if (max_unix_offset > INT_MAX)
1063 max_unix_offset = INT_MAX;
1064 break; /* retry */
1066 /* fall through */
1067 default:
1068 file_set_error();
1069 return 0;
1074 /* check if interval [start;end) overlaps the lock */
1075 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1077 if (lock->end && start >= lock->end) return 0;
1078 if (end && lock->start >= end) return 0;
1079 return 1;
1082 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1083 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1085 struct hole
1087 struct hole *next;
1088 struct hole *prev;
1089 file_pos_t start;
1090 file_pos_t end;
1091 } *first, *cur, *next, *buffer;
1093 struct list *ptr;
1094 int count = 0;
1096 if (!fd->inode) return;
1097 if (!fd->fs_locks) return;
1098 if (start == end || start > max_unix_offset) return;
1099 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1101 /* count the number of locks overlapping the specified area */
1103 LIST_FOR_EACH( ptr, &fd->inode->locks )
1105 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1106 if (lock->start == lock->end) continue;
1107 if (lock_overlaps( lock, start, end )) count++;
1110 if (!count) /* no locks at all, we can unlock everything */
1112 set_unix_lock( fd, start, end, F_UNLCK );
1113 return;
1116 /* allocate space for the list of holes */
1117 /* max. number of holes is number of locks + 1 */
1119 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1120 first = buffer;
1121 first->next = NULL;
1122 first->prev = NULL;
1123 first->start = start;
1124 first->end = end;
1125 next = first + 1;
1127 /* build a sorted list of unlocked holes in the specified area */
1129 LIST_FOR_EACH( ptr, &fd->inode->locks )
1131 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1132 if (lock->start == lock->end) continue;
1133 if (!lock_overlaps( lock, start, end )) continue;
1135 /* go through all the holes touched by this lock */
1136 for (cur = first; cur; cur = cur->next)
1138 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1139 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1141 /* now we know that lock is overlapping hole */
1143 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1145 cur->start = lock->end;
1146 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1147 /* now hole is empty, remove it */
1148 if (cur->next) cur->next->prev = cur->prev;
1149 if (cur->prev) cur->prev->next = cur->next;
1150 else if (!(first = cur->next)) goto done; /* no more holes at all */
1152 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1154 cur->end = lock->start;
1155 assert( cur->start < cur->end );
1157 else /* lock is in the middle of hole, split hole in two */
1159 next->prev = cur;
1160 next->next = cur->next;
1161 cur->next = next;
1162 next->start = lock->end;
1163 next->end = cur->end;
1164 cur->end = lock->start;
1165 assert( next->start < next->end );
1166 assert( cur->end < next->start );
1167 next++;
1168 break; /* done with this lock */
1173 /* clear Unix locks for all the holes */
1175 for (cur = first; cur; cur = cur->next)
1176 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1178 done:
1179 free( buffer );
1182 /* create a new lock on a fd */
1183 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1185 struct file_lock *lock;
1187 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1188 lock->shared = shared;
1189 lock->start = start;
1190 lock->end = end;
1191 lock->fd = fd;
1192 lock->process = current->process;
1194 /* now try to set a Unix lock */
1195 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1197 release_object( lock );
1198 return NULL;
1200 list_add_head( &fd->locks, &lock->fd_entry );
1201 list_add_head( &fd->inode->locks, &lock->inode_entry );
1202 list_add_head( &lock->process->locks, &lock->proc_entry );
1203 return lock;
1206 /* remove an existing lock */
1207 static void remove_lock( struct file_lock *lock, int remove_unix )
1209 struct inode *inode = lock->fd->inode;
1211 list_remove( &lock->fd_entry );
1212 list_remove( &lock->inode_entry );
1213 list_remove( &lock->proc_entry );
1214 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1215 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1216 lock->process = NULL;
1217 wake_up( &lock->obj, 0 );
1218 release_object( lock );
1221 /* remove all locks owned by a given process */
1222 void remove_process_locks( struct process *process )
1224 struct list *ptr;
1226 while ((ptr = list_head( &process->locks )))
1228 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1229 remove_lock( lock, 1 ); /* this removes it from the list */
1233 /* remove all locks on a given fd */
1234 static void remove_fd_locks( struct fd *fd )
1236 file_pos_t start = FILE_POS_T_MAX, end = 0;
1237 struct list *ptr;
1239 while ((ptr = list_head( &fd->locks )))
1241 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1242 if (lock->start < start) start = lock->start;
1243 if (!lock->end || lock->end > end) end = lock->end - 1;
1244 remove_lock( lock, 0 );
1246 if (start < end) remove_unix_locks( fd, start, end + 1 );
1249 /* add a lock on an fd */
1250 /* returns handle to wait on */
1251 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1253 struct list *ptr;
1254 file_pos_t end = start + count;
1256 if (!fd->inode) /* not a regular file */
1258 set_error( STATUS_INVALID_DEVICE_REQUEST );
1259 return 0;
1262 /* don't allow wrapping locks */
1263 if (end && end < start)
1265 set_error( STATUS_INVALID_PARAMETER );
1266 return 0;
1269 /* check if another lock on that file overlaps the area */
1270 LIST_FOR_EACH( ptr, &fd->inode->locks )
1272 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1273 if (!lock_overlaps( lock, start, end )) continue;
1274 if (lock->shared && shared) continue;
1275 /* found one */
1276 if (!wait)
1278 set_error( STATUS_FILE_LOCK_CONFLICT );
1279 return 0;
1281 set_error( STATUS_PENDING );
1282 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1285 /* not found, add it */
1286 if (add_lock( fd, shared, start, end )) return 0;
1287 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1289 /* Unix lock conflict -> tell client to wait and retry */
1290 if (wait) set_error( STATUS_PENDING );
1292 return 0;
1295 /* remove a lock on an fd */
1296 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1298 struct list *ptr;
1299 file_pos_t end = start + count;
1301 /* find an existing lock with the exact same parameters */
1302 LIST_FOR_EACH( ptr, &fd->locks )
1304 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1305 if ((lock->start == start) && (lock->end == end))
1307 remove_lock( lock, 1 );
1308 return;
1311 set_error( STATUS_FILE_LOCK_CONFLICT );
1315 /****************************************************************/
1316 /* file descriptor functions */
1318 static void fd_dump( struct object *obj, int verbose )
1320 struct fd *fd = (struct fd *)obj;
1321 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1322 if (fd->inode) fprintf( stderr, " inode=%p unlink='%s'", fd->inode, fd->closed->unlink );
1323 fprintf( stderr, "\n" );
1326 static void fd_destroy( struct object *obj )
1328 struct fd *fd = (struct fd *)obj;
1330 free_async_queue( fd->read_q );
1331 free_async_queue( fd->write_q );
1332 free_async_queue( fd->wait_q );
1334 if (fd->completion) release_object( fd->completion );
1335 remove_fd_locks( fd );
1336 list_remove( &fd->inode_entry );
1337 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1338 if (fd->inode)
1340 inode_add_closed_fd( fd->inode, fd->closed );
1341 release_object( fd->inode );
1343 else /* no inode, close it right away */
1345 if (fd->unix_fd != -1) close( fd->unix_fd );
1349 /* set the events that select waits for on this fd */
1350 void set_fd_events( struct fd *fd, int events )
1352 int user = fd->poll_index;
1353 assert( poll_users[user] == fd );
1355 set_fd_epoll_events( fd, user, events );
1357 if (events == -1) /* stop waiting on this fd completely */
1359 pollfd[user].fd = -1;
1360 pollfd[user].events = POLLERR;
1361 pollfd[user].revents = 0;
1363 else if (pollfd[user].fd != -1 || !pollfd[user].events)
1365 pollfd[user].fd = fd->unix_fd;
1366 pollfd[user].events = events;
1370 /* prepare an fd for unmounting its corresponding device */
1371 static inline void unmount_fd( struct fd *fd )
1373 assert( fd->inode );
1375 async_wake_up( fd->read_q, STATUS_VOLUME_DISMOUNTED );
1376 async_wake_up( fd->write_q, STATUS_VOLUME_DISMOUNTED );
1378 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1380 if (fd->unix_fd != -1) close( fd->unix_fd );
1382 fd->unix_fd = -1;
1383 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1384 fd->closed->unix_fd = -1;
1385 fd->closed->unlink[0] = 0;
1387 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1388 fd->fs_locks = 0;
1391 /* allocate an fd object, without setting the unix fd yet */
1392 static struct fd *alloc_fd_object(void)
1394 struct fd *fd = alloc_object( &fd_ops );
1396 if (!fd) return NULL;
1398 fd->fd_ops = NULL;
1399 fd->user = NULL;
1400 fd->inode = NULL;
1401 fd->closed = NULL;
1402 fd->access = 0;
1403 fd->options = 0;
1404 fd->sharing = 0;
1405 fd->unix_fd = -1;
1406 fd->signaled = 1;
1407 fd->fs_locks = 1;
1408 fd->poll_index = -1;
1409 fd->read_q = NULL;
1410 fd->write_q = NULL;
1411 fd->wait_q = NULL;
1412 fd->completion = NULL;
1413 list_init( &fd->inode_entry );
1414 list_init( &fd->locks );
1416 if ((fd->poll_index = add_poll_user( fd )) == -1)
1418 release_object( fd );
1419 return NULL;
1421 return fd;
1424 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1425 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1427 struct fd *fd = alloc_object( &fd_ops );
1429 if (!fd) return NULL;
1431 fd->fd_ops = fd_user_ops;
1432 fd->user = user;
1433 fd->inode = NULL;
1434 fd->closed = NULL;
1435 fd->access = 0;
1436 fd->options = options;
1437 fd->sharing = 0;
1438 fd->unix_fd = -1;
1439 fd->signaled = 0;
1440 fd->fs_locks = 0;
1441 fd->poll_index = -1;
1442 fd->read_q = NULL;
1443 fd->write_q = NULL;
1444 fd->wait_q = NULL;
1445 fd->completion = NULL;
1446 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1447 list_init( &fd->inode_entry );
1448 list_init( &fd->locks );
1449 return fd;
1452 /* set the status to return when the fd has no associated unix fd */
1453 void set_no_fd_status( struct fd *fd, unsigned int status )
1455 fd->no_fd_status = status;
1458 /* check if the desired access is possible without violating */
1459 /* the sharing mode of other opens of the same file */
1460 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
1462 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1463 unsigned int existing_access = 0;
1464 struct list *ptr;
1466 /* if access mode is 0, sharing mode is ignored */
1467 if (!access) sharing = existing_sharing;
1468 fd->access = access;
1469 fd->sharing = sharing;
1471 LIST_FOR_EACH( ptr, &fd->inode->open )
1473 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1474 if (fd_ptr != fd)
1476 existing_sharing &= fd_ptr->sharing;
1477 existing_access |= fd_ptr->access;
1481 if ((access & FILE_UNIX_READ_ACCESS) && !(existing_sharing & FILE_SHARE_READ)) return 0;
1482 if ((access & FILE_UNIX_WRITE_ACCESS) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1483 if ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1484 if ((existing_access & FILE_UNIX_READ_ACCESS) && !(sharing & FILE_SHARE_READ)) return 0;
1485 if ((existing_access & FILE_UNIX_WRITE_ACCESS) && !(sharing & FILE_SHARE_WRITE)) return 0;
1486 if ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)) return 0;
1487 return 1;
1490 /* sets the user of an fd that previously had no user */
1491 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1493 assert( fd->fd_ops == NULL );
1494 fd->fd_ops = user_ops;
1495 fd->user = user;
1498 /* open() wrapper that returns a struct fd with no fd user set */
1499 struct fd *open_fd( const char *name, int flags, mode_t *mode, unsigned int access,
1500 unsigned int sharing, unsigned int options )
1502 struct stat st;
1503 struct closed_fd *closed_fd;
1504 struct fd *fd;
1505 const char *unlink_name = "";
1506 int rw_mode;
1508 if ((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE))
1510 set_error( STATUS_INVALID_PARAMETER );
1511 return NULL;
1514 if (!(fd = alloc_fd_object())) return NULL;
1516 fd->options = options;
1517 if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1518 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1520 release_object( fd );
1521 return NULL;
1524 /* create the directory if needed */
1525 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1527 if (mkdir( name, 0777 ) == -1)
1529 if (errno != EEXIST || (flags & O_EXCL))
1531 file_set_error();
1532 goto error;
1535 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1538 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1540 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1541 else rw_mode = O_WRONLY;
1543 else rw_mode = O_RDONLY;
1545 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1547 /* if we tried to open a directory for write access, retry read-only */
1548 if (errno != EISDIR ||
1549 !(access & FILE_UNIX_WRITE_ACCESS) ||
1550 (fd->unix_fd = open( name, O_RDONLY | (flags & ~O_TRUNC), *mode )) == -1)
1552 file_set_error();
1553 goto error;
1557 closed_fd->unix_fd = fd->unix_fd;
1558 closed_fd->unlink[0] = 0;
1559 fstat( fd->unix_fd, &st );
1560 *mode = st.st_mode;
1562 /* only bother with an inode for normal files and directories */
1563 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1565 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1567 if (!inode)
1569 /* we can close the fd because there are no others open on the same file,
1570 * otherwise we wouldn't have failed to allocate a new inode
1572 goto error;
1574 fd->inode = inode;
1575 fd->closed = closed_fd;
1576 list_add_head( &inode->open, &fd->inode_entry );
1578 /* check directory options */
1579 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1581 release_object( fd );
1582 set_error( STATUS_NOT_A_DIRECTORY );
1583 return NULL;
1585 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1587 release_object( fd );
1588 set_error( STATUS_FILE_IS_A_DIRECTORY );
1589 return NULL;
1591 if (!check_sharing( fd, access, sharing ))
1593 release_object( fd );
1594 set_error( STATUS_SHARING_VIOLATION );
1595 return NULL;
1597 strcpy( closed_fd->unlink, unlink_name );
1598 if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1600 else /* special file */
1602 if (options & FILE_DIRECTORY_FILE)
1604 set_error( STATUS_NOT_A_DIRECTORY );
1605 goto error;
1607 if (unlink_name[0]) /* we can't unlink special files */
1609 set_error( STATUS_INVALID_PARAMETER );
1610 goto error;
1612 free( closed_fd );
1614 return fd;
1616 error:
1617 release_object( fd );
1618 free( closed_fd );
1619 return NULL;
1622 /* create an fd for an anonymous file */
1623 /* if the function fails the unix fd is closed */
1624 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
1625 unsigned int options )
1627 struct fd *fd = alloc_fd_object();
1629 if (fd)
1631 set_fd_user( fd, fd_user_ops, user );
1632 fd->unix_fd = unix_fd;
1633 fd->options = options;
1634 return fd;
1636 close( unix_fd );
1637 return NULL;
1640 /* retrieve the object that is using an fd */
1641 void *get_fd_user( struct fd *fd )
1643 return fd->user;
1646 /* retrieve the opening options for the fd */
1647 unsigned int get_fd_options( struct fd *fd )
1649 return fd->options;
1652 /* retrieve the unix fd for an object */
1653 int get_unix_fd( struct fd *fd )
1655 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
1656 return fd->unix_fd;
1659 /* check if two file descriptors point to the same file */
1660 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1662 return fd1->inode == fd2->inode;
1665 /* check if fd is on a removable device */
1666 int is_fd_removable( struct fd *fd )
1668 return (fd->inode && fd->inode->device->removable);
1671 /* set or clear the fd signaled state */
1672 void set_fd_signaled( struct fd *fd, int signaled )
1674 fd->signaled = signaled;
1675 if (signaled) wake_up( fd->user, 0 );
1678 /* handler for close_handle that refuses to close fd-associated handles in other processes */
1679 int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
1681 return (!current || current->process == process);
1684 /* callback for event happening in the main poll() loop */
1685 void fd_poll_event( struct fd *fd, int event )
1687 return fd->fd_ops->poll_event( fd, event );
1690 /* check if events are pending and if yes return which one(s) */
1691 int check_fd_events( struct fd *fd, int events )
1693 struct pollfd pfd;
1695 if (fd->unix_fd == -1) return POLLERR;
1696 if (fd->inode) return events; /* regular files are always signaled */
1698 pfd.fd = fd->unix_fd;
1699 pfd.events = events;
1700 if (poll( &pfd, 1, 0 ) <= 0) return 0;
1701 return pfd.revents;
1704 /* default signaled() routine for objects that poll() on an fd */
1705 int default_fd_signaled( struct object *obj, struct thread *thread )
1707 struct fd *fd = get_obj_fd( obj );
1708 int ret = fd->signaled;
1709 release_object( fd );
1710 return ret;
1713 /* default map_access() routine for objects that behave like an fd */
1714 unsigned int default_fd_map_access( struct object *obj, unsigned int access )
1716 if (access & GENERIC_READ) access |= FILE_GENERIC_READ;
1717 if (access & GENERIC_WRITE) access |= FILE_GENERIC_WRITE;
1718 if (access & GENERIC_EXECUTE) access |= FILE_GENERIC_EXECUTE;
1719 if (access & GENERIC_ALL) access |= FILE_ALL_ACCESS;
1720 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
1723 int default_fd_get_poll_events( struct fd *fd )
1725 int events = 0;
1727 if (async_waiting( fd->read_q )) events |= POLLIN;
1728 if (async_waiting( fd->write_q )) events |= POLLOUT;
1729 return events;
1732 /* default handler for poll() events */
1733 void default_poll_event( struct fd *fd, int event )
1735 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( fd->read_q, STATUS_ALERTED );
1736 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( fd->write_q, STATUS_ALERTED );
1738 /* if an error occurred, stop polling this fd to avoid busy-looping */
1739 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1740 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1743 struct async *fd_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
1745 struct async_queue *queue;
1746 struct async *async;
1748 switch (type)
1750 case ASYNC_TYPE_READ:
1751 if (!fd->read_q && !(fd->read_q = create_async_queue( fd ))) return NULL;
1752 queue = fd->read_q;
1753 break;
1754 case ASYNC_TYPE_WRITE:
1755 if (!fd->write_q && !(fd->write_q = create_async_queue( fd ))) return NULL;
1756 queue = fd->write_q;
1757 break;
1758 case ASYNC_TYPE_WAIT:
1759 if (!fd->wait_q && !(fd->wait_q = create_async_queue( fd ))) return NULL;
1760 queue = fd->wait_q;
1761 break;
1762 default:
1763 queue = NULL;
1764 assert(0);
1767 if ((async = create_async( current, queue, data )) && type != ASYNC_TYPE_WAIT)
1769 if (!fd->inode)
1770 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1771 else /* regular files are always ready for read and write */
1772 async_wake_up( queue, STATUS_ALERTED );
1774 return async;
1777 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
1779 switch (type)
1781 case ASYNC_TYPE_READ:
1782 async_wake_up( fd->read_q, status );
1783 break;
1784 case ASYNC_TYPE_WRITE:
1785 async_wake_up( fd->write_q, status );
1786 break;
1787 case ASYNC_TYPE_WAIT:
1788 async_wake_up( fd->wait_q, status );
1789 break;
1790 default:
1791 assert(0);
1795 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
1797 fd->fd_ops->reselect_async( fd, queue );
1800 void default_fd_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
1802 struct async *async;
1804 if ((async = fd_queue_async( fd, data, type, count )))
1806 release_object( async );
1807 set_error( STATUS_PENDING );
1811 /* default reselect_async() fd routine */
1812 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
1814 if (queue != fd->wait_q)
1816 int poll_events = fd->fd_ops->get_poll_events( fd );
1817 int events = check_fd_events( fd, poll_events );
1818 if (events) fd->fd_ops->poll_event( fd, events );
1819 else set_fd_events( fd, poll_events );
1823 /* default cancel_async() fd routine */
1824 void default_fd_cancel_async( struct fd *fd )
1826 async_wake_up( fd->read_q, STATUS_CANCELLED );
1827 async_wake_up( fd->write_q, STATUS_CANCELLED );
1828 async_wake_up( fd->wait_q, STATUS_CANCELLED );
1831 /* default flush() routine */
1832 void no_flush( struct fd *fd, struct event **event )
1834 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1837 static inline int is_valid_mounted_device( struct stat *st )
1839 #if defined(linux) || defined(__sun__)
1840 return S_ISBLK( st->st_mode );
1841 #else
1842 /* disks are char devices on *BSD */
1843 return S_ISCHR( st->st_mode );
1844 #endif
1847 /* close all Unix file descriptors on a device to allow unmounting it */
1848 static void unmount_device( struct fd *device_fd )
1850 unsigned int i;
1851 struct stat st;
1852 struct device *device;
1853 struct inode *inode;
1854 struct fd *fd;
1855 int unix_fd = get_unix_fd( device_fd );
1857 if (unix_fd == -1) return;
1859 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
1861 set_error( STATUS_INVALID_PARAMETER );
1862 return;
1865 if (!(device = get_device( st.st_rdev, -1 ))) return;
1867 for (i = 0; i < INODE_HASH_SIZE; i++)
1869 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
1871 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
1873 unmount_fd( fd );
1875 inode_close_pending( inode, 0 );
1878 /* remove it from the hash table */
1879 list_remove( &device->entry );
1880 list_init( &device->entry );
1881 release_object( device );
1884 /* default ioctl() routine */
1885 obj_handle_t default_fd_ioctl( struct fd *fd, ioctl_code_t code, const async_data_t *async,
1886 const void *data, data_size_t size )
1888 switch(code)
1890 case FSCTL_DISMOUNT_VOLUME:
1891 unmount_device( fd );
1892 return 0;
1893 default:
1894 set_error( STATUS_NOT_SUPPORTED );
1895 return 0;
1899 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1900 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1901 unsigned int access )
1903 struct fd *fd = NULL;
1904 struct object *obj;
1906 if ((obj = get_handle_obj( process, handle, access, NULL )))
1908 fd = get_obj_fd( obj );
1909 release_object( obj );
1911 return fd;
1914 /* flush a file buffers */
1915 DECL_HANDLER(flush_file)
1917 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1918 struct event * event = NULL;
1920 if (fd)
1922 fd->fd_ops->flush( fd, &event );
1923 if ( event )
1925 reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1927 release_object( fd );
1931 /* open a file object */
1932 DECL_HANDLER(open_file_object)
1934 struct unicode_str name;
1935 struct directory *root = NULL;
1936 struct object *obj, *result;
1938 get_req_unicode_str( &name );
1939 if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
1940 return;
1942 if ((obj = open_object_dir( root, &name, req->attributes, NULL )))
1944 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
1946 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
1947 release_object( result );
1949 release_object( obj );
1952 if (root) release_object( root );
1955 /* get a Unix fd to access a file */
1956 DECL_HANDLER(get_handle_fd)
1958 struct fd *fd;
1960 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
1962 int unix_fd = get_unix_fd( fd );
1963 if (unix_fd != -1)
1965 send_client_fd( current->process, unix_fd, req->handle );
1966 reply->type = fd->fd_ops->get_fd_type( fd );
1967 reply->removable = is_fd_removable(fd);
1968 reply->options = fd->options;
1969 reply->access = get_handle_access( current->process, req->handle );
1971 release_object( fd );
1975 /* perform an ioctl on a file */
1976 DECL_HANDLER(ioctl)
1978 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
1979 struct fd *fd = get_handle_fd_obj( current->process, req->handle, access );
1981 if (fd)
1983 reply->wait = fd->fd_ops->ioctl( fd, req->code, &req->async,
1984 get_req_data(), get_req_data_size() );
1985 reply->options = fd->options;
1986 release_object( fd );
1990 /* create / reschedule an async I/O */
1991 DECL_HANDLER(register_async)
1993 unsigned int access;
1994 struct fd *fd;
1996 switch(req->type)
1998 case ASYNC_TYPE_READ:
1999 access = FILE_READ_DATA;
2000 break;
2001 case ASYNC_TYPE_WRITE:
2002 access = FILE_WRITE_DATA;
2003 break;
2004 default:
2005 set_error( STATUS_INVALID_PARAMETER );
2006 return;
2009 if ((fd = get_handle_fd_obj( current->process, req->handle, access )))
2011 if (get_unix_fd( fd ) != -1) fd->fd_ops->queue_async( fd, &req->async, req->type, req->count );
2012 release_object( fd );
2016 /* cancels all async I/O */
2017 DECL_HANDLER(cancel_async)
2019 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2021 if (fd)
2023 if (get_unix_fd( fd ) != -1) fd->fd_ops->cancel_async( fd );
2024 release_object( fd );
2028 /* attach completion object to a fd */
2029 DECL_HANDLER(set_completion_info)
2031 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2033 if (fd)
2035 if (!fd->completion)
2037 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2038 fd->comp_key = req->ckey;
2040 else set_error( STATUS_INVALID_PARAMETER );
2041 release_object( fd );