jscript: Added JSGlobal_unescape implementation.
[wine/multimedia.git] / server / fd.c
blobd2da6247ad796a02e6675b60c32abb3634dd1a38
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
48 * Solaris defines its system list in sys/list.h.
49 * This need to be workaround it here.
51 #define list SYSLIST
52 #define list_next SYSLIST_NEXT
53 #define list_prev SYSLIST_PREV
54 #define list_head SYSLIST_HEAD
55 #define list_tail SYSLIST_TAIL
56 #define list_move_tail SYSLIST_MOVE_TAIL
57 #define list_remove SYSLIST_REMOVE
58 #include <sys/vfs.h>
59 #undef list
60 #undef list_next
61 #undef list_prev
62 #undef list_head
63 #undef list_tail
64 #undef list_move_tail
65 #undef list_remove
66 #endif
67 #ifdef HAVE_SYS_PARAM_H
68 #include <sys/param.h>
69 #endif
70 #ifdef HAVE_SYS_MOUNT_H
71 #include <sys/mount.h>
72 #endif
73 #ifdef HAVE_SYS_STATFS_H
74 #include <sys/statfs.h>
75 #endif
76 #ifdef HAVE_SYS_SYSCTL_H
77 #include <sys/sysctl.h>
78 #endif
79 #ifdef HAVE_SYS_EVENT_H
80 #include <sys/event.h>
81 #undef LIST_INIT
82 #undef LIST_ENTRY
83 #endif
84 #ifdef HAVE_STDINT_H
85 #include <stdint.h>
86 #endif
87 #include <sys/stat.h>
88 #include <sys/time.h>
89 #include <sys/types.h>
90 #include <unistd.h>
92 #include "ntstatus.h"
93 #define WIN32_NO_STATUS
94 #include "object.h"
95 #include "file.h"
96 #include "handle.h"
97 #include "process.h"
98 #include "request.h"
100 #include "winternl.h"
101 #include "winioctl.h"
103 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
104 # include <sys/epoll.h>
105 # define USE_EPOLL
106 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
107 # define USE_EPOLL
108 # define EPOLLIN POLLIN
109 # define EPOLLOUT POLLOUT
110 # define EPOLLERR POLLERR
111 # define EPOLLHUP POLLHUP
112 # define EPOLL_CTL_ADD 1
113 # define EPOLL_CTL_DEL 2
114 # define EPOLL_CTL_MOD 3
116 typedef union epoll_data
118 void *ptr;
119 int fd;
120 uint32_t u32;
121 uint64_t u64;
122 } epoll_data_t;
124 struct epoll_event
126 uint32_t events;
127 epoll_data_t data;
130 #define SYSCALL_RET(ret) do { \
131 if (ret < 0) { errno = -ret; ret = -1; } \
132 return ret; \
133 } while(0)
135 static inline int epoll_create( int size )
137 int ret;
138 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
139 : "=a" (ret) : "0" (254 /*NR_epoll_create*/), "r" (size) );
140 SYSCALL_RET(ret);
143 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
145 int ret;
146 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
147 : "=a" (ret)
148 : "0" (255 /*NR_epoll_ctl*/), "r" (epfd), "c" (op), "d" (fd), "S" (event), "m" (*event) );
149 SYSCALL_RET(ret);
152 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
154 int ret;
155 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
156 : "=a" (ret)
157 : "0" (256 /*NR_epoll_wait*/), "r" (epfd), "c" (events), "d" (maxevents), "S" (timeout)
158 : "memory" );
159 SYSCALL_RET(ret);
161 #undef SYSCALL_RET
163 #endif /* linux && __i386__ && HAVE_STDINT_H */
166 /* Because of the stupid Posix locking semantics, we need to keep
167 * track of all file descriptors referencing a given file, and not
168 * close a single one until all the locks are gone (sigh).
171 /* file descriptor object */
173 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
174 struct closed_fd
176 struct list entry; /* entry in inode closed list */
177 int unix_fd; /* the unix file descriptor */
178 char unlink[1]; /* name to unlink on close (if any) */
181 struct fd
183 struct object obj; /* object header */
184 const struct fd_ops *fd_ops; /* file descriptor operations */
185 struct inode *inode; /* inode that this fd belongs to */
186 struct list inode_entry; /* entry in inode fd list */
187 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
188 struct object *user; /* object using this file descriptor */
189 struct list locks; /* list of locks on this fd */
190 unsigned int access; /* file access (FILE_READ_DATA etc.) */
191 unsigned int options; /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
192 unsigned int sharing; /* file sharing mode */
193 int unix_fd; /* unix file descriptor */
194 unsigned int no_fd_status;/* status to return when unix_fd is -1 */
195 int signaled :1; /* is the fd signaled? */
196 int fs_locks :1; /* can we use filesystem locks for this fd? */
197 int poll_index; /* index of fd in poll array */
198 struct async_queue *read_q; /* async readers of this fd */
199 struct async_queue *write_q; /* async writers of this fd */
200 struct async_queue *wait_q; /* other async waiters of this fd */
201 struct completion *completion; /* completion object attached to this fd */
202 apc_param_t comp_key; /* completion key to set in completion events */
205 static void fd_dump( struct object *obj, int verbose );
206 static void fd_destroy( struct object *obj );
208 static const struct object_ops fd_ops =
210 sizeof(struct fd), /* size */
211 fd_dump, /* dump */
212 no_get_type, /* get_type */
213 no_add_queue, /* add_queue */
214 NULL, /* remove_queue */
215 NULL, /* signaled */
216 NULL, /* satisfied */
217 no_signal, /* signal */
218 no_get_fd, /* get_fd */
219 no_map_access, /* map_access */
220 default_get_sd, /* get_sd */
221 default_set_sd, /* set_sd */
222 no_lookup_name, /* lookup_name */
223 no_open_file, /* open_file */
224 no_close_handle, /* close_handle */
225 fd_destroy /* destroy */
228 /* device object */
230 #define DEVICE_HASH_SIZE 7
231 #define INODE_HASH_SIZE 17
233 struct device
235 struct object obj; /* object header */
236 struct list entry; /* entry in device hash list */
237 dev_t dev; /* device number */
238 int removable; /* removable device? (or -1 if unknown) */
239 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
242 static void device_dump( struct object *obj, int verbose );
243 static void device_destroy( struct object *obj );
245 static const struct object_ops device_ops =
247 sizeof(struct device), /* size */
248 device_dump, /* dump */
249 no_get_type, /* get_type */
250 no_add_queue, /* add_queue */
251 NULL, /* remove_queue */
252 NULL, /* signaled */
253 NULL, /* satisfied */
254 no_signal, /* signal */
255 no_get_fd, /* get_fd */
256 no_map_access, /* map_access */
257 default_get_sd, /* get_sd */
258 default_set_sd, /* set_sd */
259 no_lookup_name, /* lookup_name */
260 no_open_file, /* open_file */
261 no_close_handle, /* close_handle */
262 device_destroy /* destroy */
265 /* inode object */
267 struct inode
269 struct object obj; /* object header */
270 struct list entry; /* inode hash list entry */
271 struct device *device; /* device containing this inode */
272 ino_t ino; /* inode number */
273 struct list open; /* list of open file descriptors */
274 struct list locks; /* list of file locks */
275 struct list closed; /* list of file descriptors to close at destroy time */
278 static void inode_dump( struct object *obj, int verbose );
279 static void inode_destroy( struct object *obj );
281 static const struct object_ops inode_ops =
283 sizeof(struct inode), /* size */
284 inode_dump, /* dump */
285 no_get_type, /* get_type */
286 no_add_queue, /* add_queue */
287 NULL, /* remove_queue */
288 NULL, /* signaled */
289 NULL, /* satisfied */
290 no_signal, /* signal */
291 no_get_fd, /* get_fd */
292 no_map_access, /* map_access */
293 default_get_sd, /* get_sd */
294 default_set_sd, /* set_sd */
295 no_lookup_name, /* lookup_name */
296 no_open_file, /* open_file */
297 no_close_handle, /* close_handle */
298 inode_destroy /* destroy */
301 /* file lock object */
303 struct file_lock
305 struct object obj; /* object header */
306 struct fd *fd; /* fd owning this lock */
307 struct list fd_entry; /* entry in list of locks on a given fd */
308 struct list inode_entry; /* entry in inode list of locks */
309 int shared; /* shared lock? */
310 file_pos_t start; /* locked region is interval [start;end) */
311 file_pos_t end;
312 struct process *process; /* process owning this lock */
313 struct list proc_entry; /* entry in list of locks owned by the process */
316 static void file_lock_dump( struct object *obj, int verbose );
317 static int file_lock_signaled( struct object *obj, struct thread *thread );
319 static const struct object_ops file_lock_ops =
321 sizeof(struct file_lock), /* size */
322 file_lock_dump, /* dump */
323 no_get_type, /* get_type */
324 add_queue, /* add_queue */
325 remove_queue, /* remove_queue */
326 file_lock_signaled, /* signaled */
327 no_satisfied, /* satisfied */
328 no_signal, /* signal */
329 no_get_fd, /* get_fd */
330 no_map_access, /* map_access */
331 default_get_sd, /* get_sd */
332 default_set_sd, /* set_sd */
333 no_lookup_name, /* lookup_name */
334 no_open_file, /* open_file */
335 no_close_handle, /* close_handle */
336 no_destroy /* destroy */
340 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
341 #define FILE_POS_T_MAX (~(file_pos_t)0)
343 static file_pos_t max_unix_offset = OFF_T_MAX;
345 #define DUMP_LONG_LONG(val) do { \
346 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
347 fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
348 else \
349 fprintf( stderr, "%lx", (unsigned long)(val) ); \
350 } while (0)
354 /****************************************************************/
355 /* timeouts support */
357 struct timeout_user
359 struct list entry; /* entry in sorted timeout list */
360 timeout_t when; /* timeout expiry (absolute time) */
361 timeout_callback callback; /* callback function */
362 void *private; /* callback private data */
365 static struct list timeout_list = LIST_INIT(timeout_list); /* sorted timeouts list */
366 timeout_t current_time;
368 static inline void set_current_time(void)
370 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
371 struct timeval now;
372 gettimeofday( &now, NULL );
373 current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
376 /* add a timeout user */
377 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
379 struct timeout_user *user;
380 struct list *ptr;
382 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
383 user->when = (when > 0) ? when : current_time - when;
384 user->callback = func;
385 user->private = private;
387 /* Now insert it in the linked list */
389 LIST_FOR_EACH( ptr, &timeout_list )
391 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
392 if (timeout->when >= user->when) break;
394 list_add_before( ptr, &user->entry );
395 return user;
398 /* remove a timeout user */
399 void remove_timeout_user( struct timeout_user *user )
401 list_remove( &user->entry );
402 free( user );
405 /* return a text description of a timeout for debugging purposes */
406 const char *get_timeout_str( timeout_t timeout )
408 static char buffer[64];
409 long secs, nsecs;
411 if (!timeout) return "0";
412 if (timeout == TIMEOUT_INFINITE) return "infinite";
414 if (timeout < 0) /* relative */
416 secs = -timeout / TICKS_PER_SEC;
417 nsecs = -timeout % TICKS_PER_SEC;
418 sprintf( buffer, "+%ld.%07ld", secs, nsecs );
420 else /* absolute */
422 secs = (timeout - current_time) / TICKS_PER_SEC;
423 nsecs = (timeout - current_time) % TICKS_PER_SEC;
424 if (nsecs < 0)
426 nsecs += TICKS_PER_SEC;
427 secs--;
429 if (secs >= 0)
430 sprintf( buffer, "%x%08x (+%ld.%07ld)",
431 (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
432 else
433 sprintf( buffer, "%x%08x (-%ld.%07ld)",
434 (unsigned int)(timeout >> 32), (unsigned int)timeout,
435 -(secs + 1), TICKS_PER_SEC - nsecs );
437 return buffer;
441 /****************************************************************/
442 /* poll support */
444 static struct fd **poll_users; /* users array */
445 static struct pollfd *pollfd; /* poll fd array */
446 static int nb_users; /* count of array entries actually in use */
447 static int active_users; /* current number of active users */
448 static int allocated_users; /* count of allocated entries in the array */
449 static struct fd **freelist; /* list of free entries in the array */
451 static int get_next_timeout(void);
453 static inline void fd_poll_event( struct fd *fd, int event )
455 fd->fd_ops->poll_event( fd, event );
458 #ifdef USE_EPOLL
460 static int epoll_fd = -1;
462 static inline void init_epoll(void)
464 epoll_fd = epoll_create( 128 );
467 /* set the events that epoll waits for on this fd; helper for set_fd_events */
468 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
470 struct epoll_event ev;
471 int ctl;
473 if (epoll_fd == -1) return;
475 if (events == -1) /* stop waiting on this fd completely */
477 if (pollfd[user].fd == -1) return; /* already removed */
478 ctl = EPOLL_CTL_DEL;
480 else if (pollfd[user].fd == -1)
482 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
483 ctl = EPOLL_CTL_ADD;
485 else
487 if (pollfd[user].events == events) return; /* nothing to do */
488 ctl = EPOLL_CTL_MOD;
491 ev.events = events;
492 memset(&ev.data, 0, sizeof(ev.data));
493 ev.data.u32 = user;
495 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
497 if (errno == ENOMEM) /* not enough memory, give up on epoll */
499 close( epoll_fd );
500 epoll_fd = -1;
502 else perror( "epoll_ctl" ); /* should not happen */
506 static inline void remove_epoll_user( struct fd *fd, int user )
508 if (epoll_fd == -1) return;
510 if (pollfd[user].fd != -1)
512 struct epoll_event dummy;
513 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
517 static inline void main_loop_epoll(void)
519 int i, ret, timeout;
520 struct epoll_event events[128];
522 assert( POLLIN == EPOLLIN );
523 assert( POLLOUT == EPOLLOUT );
524 assert( POLLERR == EPOLLERR );
525 assert( POLLHUP == EPOLLHUP );
527 if (epoll_fd == -1) return;
529 while (active_users)
531 timeout = get_next_timeout();
533 if (!active_users) break; /* last user removed by a timeout */
534 if (epoll_fd == -1) break; /* an error occurred with epoll */
536 ret = epoll_wait( epoll_fd, events, sizeof(events)/sizeof(events[0]), timeout );
537 set_current_time();
539 /* put the events into the pollfd array first, like poll does */
540 for (i = 0; i < ret; i++)
542 int user = events[i].data.u32;
543 pollfd[user].revents = events[i].events;
546 /* read events from the pollfd array, as set_fd_events may modify them */
547 for (i = 0; i < ret; i++)
549 int user = events[i].data.u32;
550 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
555 #elif defined(HAVE_KQUEUE)
557 static int kqueue_fd = -1;
559 static inline void init_epoll(void)
561 #ifdef __APPLE__ /* kqueue support is broken in Mac OS < 10.5 */
562 int mib[2];
563 char release[32];
564 size_t len = sizeof(release);
566 mib[0] = CTL_KERN;
567 mib[1] = KERN_OSRELEASE;
568 if (sysctl( mib, 2, release, &len, NULL, 0 ) == -1) return;
569 if (atoi(release) < 9) return;
570 #endif
571 kqueue_fd = kqueue();
574 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
576 struct kevent ev[2];
578 if (kqueue_fd == -1) return;
580 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)user );
581 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)user );
583 if (events == -1) /* stop waiting on this fd completely */
585 if (pollfd[user].fd == -1) return; /* already removed */
586 ev[0].flags |= EV_DELETE;
587 ev[1].flags |= EV_DELETE;
589 else if (pollfd[user].fd == -1)
591 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
592 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
593 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
595 else
597 if (pollfd[user].events == events) return; /* nothing to do */
598 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
599 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
602 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
604 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
606 close( kqueue_fd );
607 kqueue_fd = -1;
609 else perror( "kevent" ); /* should not happen */
613 static inline void remove_epoll_user( struct fd *fd, int user )
615 if (kqueue_fd == -1) return;
617 if (pollfd[user].fd != -1)
619 struct kevent ev[2];
621 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
622 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
623 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
627 static inline void main_loop_epoll(void)
629 int i, ret, timeout;
630 struct kevent events[128];
632 if (kqueue_fd == -1) return;
634 while (active_users)
636 timeout = get_next_timeout();
638 if (!active_users) break; /* last user removed by a timeout */
639 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
641 if (timeout != -1)
643 struct timespec ts;
645 ts.tv_sec = timeout / 1000;
646 ts.tv_nsec = (timeout % 1000) * 1000000;
647 ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), &ts );
649 else ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), NULL );
651 set_current_time();
653 /* put the events into the pollfd array first, like poll does */
654 for (i = 0; i < ret; i++)
656 long user = (long)events[i].udata;
657 pollfd[user].revents = 0;
659 for (i = 0; i < ret; i++)
661 long user = (long)events[i].udata;
662 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
663 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
664 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
665 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
668 /* read events from the pollfd array, as set_fd_events may modify them */
669 for (i = 0; i < ret; i++)
671 long user = (long)events[i].udata;
672 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
673 pollfd[user].revents = 0;
678 #else /* HAVE_KQUEUE */
680 static inline void init_epoll(void) { }
681 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
682 static inline void remove_epoll_user( struct fd *fd, int user ) { }
683 static inline void main_loop_epoll(void) { }
685 #endif /* USE_EPOLL */
688 /* add a user in the poll array and return its index, or -1 on failure */
689 static int add_poll_user( struct fd *fd )
691 int ret;
692 if (freelist)
694 ret = freelist - poll_users;
695 freelist = (struct fd **)poll_users[ret];
697 else
699 if (nb_users == allocated_users)
701 struct fd **newusers;
702 struct pollfd *newpoll;
703 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
704 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
705 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
707 if (allocated_users)
708 poll_users = newusers;
709 else
710 free( newusers );
711 return -1;
713 poll_users = newusers;
714 pollfd = newpoll;
715 if (!allocated_users) init_epoll();
716 allocated_users = new_count;
718 ret = nb_users++;
720 pollfd[ret].fd = -1;
721 pollfd[ret].events = 0;
722 pollfd[ret].revents = 0;
723 poll_users[ret] = fd;
724 active_users++;
725 return ret;
728 /* remove a user from the poll list */
729 static void remove_poll_user( struct fd *fd, int user )
731 assert( user >= 0 );
732 assert( poll_users[user] == fd );
734 remove_epoll_user( fd, user );
735 pollfd[user].fd = -1;
736 pollfd[user].events = 0;
737 pollfd[user].revents = 0;
738 poll_users[user] = (struct fd *)freelist;
739 freelist = &poll_users[user];
740 active_users--;
743 /* process pending timeouts and return the time until the next timeout, in milliseconds */
744 static int get_next_timeout(void)
746 if (!list_empty( &timeout_list ))
748 struct list expired_list, *ptr;
750 /* first remove all expired timers from the list */
752 list_init( &expired_list );
753 while ((ptr = list_head( &timeout_list )) != NULL)
755 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
757 if (timeout->when <= current_time)
759 list_remove( &timeout->entry );
760 list_add_tail( &expired_list, &timeout->entry );
762 else break;
765 /* now call the callback for all the removed timers */
767 while ((ptr = list_head( &expired_list )) != NULL)
769 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
770 list_remove( &timeout->entry );
771 timeout->callback( timeout->private );
772 free( timeout );
775 if ((ptr = list_head( &timeout_list )) != NULL)
777 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
778 int diff = (timeout->when - current_time + 9999) / 10000;
779 if (diff < 0) diff = 0;
780 return diff;
783 return -1; /* no pending timeouts */
786 /* server main poll() loop */
787 void main_loop(void)
789 int i, ret, timeout;
791 set_current_time();
792 server_start_time = current_time;
794 main_loop_epoll();
795 /* fall through to normal poll loop */
797 while (active_users)
799 timeout = get_next_timeout();
801 if (!active_users) break; /* last user removed by a timeout */
803 ret = poll( pollfd, nb_users, timeout );
804 set_current_time();
806 if (ret > 0)
808 for (i = 0; i < nb_users; i++)
810 if (pollfd[i].revents)
812 fd_poll_event( poll_users[i], pollfd[i].revents );
813 if (!--ret) break;
821 /****************************************************************/
822 /* device functions */
824 static struct list device_hash[DEVICE_HASH_SIZE];
826 static int is_device_removable( dev_t dev, int unix_fd )
828 #if defined(linux) && defined(HAVE_FSTATFS)
829 struct statfs stfs;
831 /* check for floppy disk */
832 if (major(dev) == FLOPPY_MAJOR) return 1;
834 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
835 return (stfs.f_type == 0x9660 || /* iso9660 */
836 stfs.f_type == 0x9fa1 || /* supermount */
837 stfs.f_type == 0x15013346); /* udf */
838 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
839 struct statfs stfs;
841 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
842 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
843 #elif defined(__NetBSD__)
844 struct statvfs stfs;
846 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
847 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
848 #elif defined(sun)
849 # include <sys/dkio.h>
850 # include <sys/vtoc.h>
851 struct dk_cinfo dkinf;
852 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
853 return (dkinf.dki_ctype == DKC_CDROM ||
854 dkinf.dki_ctype == DKC_NCRFLOPPY ||
855 dkinf.dki_ctype == DKC_SMSFLOPPY ||
856 dkinf.dki_ctype == DKC_INTEL82072 ||
857 dkinf.dki_ctype == DKC_INTEL82077);
858 #else
859 return 0;
860 #endif
863 /* retrieve the device object for a given fd, creating it if needed */
864 static struct device *get_device( dev_t dev, int unix_fd )
866 struct device *device;
867 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
869 if (device_hash[hash].next)
871 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
872 if (device->dev == dev) return (struct device *)grab_object( device );
874 else list_init( &device_hash[hash] );
876 /* not found, create it */
878 if (unix_fd == -1) return NULL;
879 if ((device = alloc_object( &device_ops )))
881 device->dev = dev;
882 device->removable = is_device_removable( dev, unix_fd );
883 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
884 list_add_head( &device_hash[hash], &device->entry );
886 return device;
889 static void device_dump( struct object *obj, int verbose )
891 struct device *device = (struct device *)obj;
892 fprintf( stderr, "Device dev=" );
893 DUMP_LONG_LONG( device->dev );
894 fprintf( stderr, "\n" );
897 static void device_destroy( struct object *obj )
899 struct device *device = (struct device *)obj;
900 unsigned int i;
902 for (i = 0; i < INODE_HASH_SIZE; i++)
903 assert( list_empty(&device->inode_hash[i]) );
905 list_remove( &device->entry ); /* remove it from the hash table */
909 /****************************************************************/
910 /* inode functions */
912 /* close all pending file descriptors in the closed list */
913 static void inode_close_pending( struct inode *inode, int keep_unlinks )
915 struct list *ptr = list_head( &inode->closed );
917 while (ptr)
919 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
920 struct list *next = list_next( &inode->closed, ptr );
922 if (fd->unix_fd != -1)
924 close( fd->unix_fd );
925 fd->unix_fd = -1;
927 if (!keep_unlinks || !fd->unlink[0]) /* get rid of it unless there's an unlink pending on that file */
929 list_remove( ptr );
930 free( fd );
932 ptr = next;
936 static void inode_dump( struct object *obj, int verbose )
938 struct inode *inode = (struct inode *)obj;
939 fprintf( stderr, "Inode device=%p ino=", inode->device );
940 DUMP_LONG_LONG( inode->ino );
941 fprintf( stderr, "\n" );
944 static void inode_destroy( struct object *obj )
946 struct inode *inode = (struct inode *)obj;
947 struct list *ptr;
949 assert( list_empty(&inode->open) );
950 assert( list_empty(&inode->locks) );
952 list_remove( &inode->entry );
954 while ((ptr = list_head( &inode->closed )))
956 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
957 list_remove( ptr );
958 if (fd->unix_fd != -1) close( fd->unix_fd );
959 if (fd->unlink[0])
961 /* make sure it is still the same file */
962 struct stat st;
963 if (!stat( fd->unlink, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
965 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
966 else unlink( fd->unlink );
969 free( fd );
971 release_object( inode->device );
974 /* retrieve the inode object for a given fd, creating it if needed */
975 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
977 struct device *device;
978 struct inode *inode;
979 unsigned int hash = ino % INODE_HASH_SIZE;
981 if (!(device = get_device( dev, unix_fd ))) return NULL;
983 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
985 if (inode->ino == ino)
987 release_object( device );
988 return (struct inode *)grab_object( inode );
992 /* not found, create it */
993 if ((inode = alloc_object( &inode_ops )))
995 inode->device = device;
996 inode->ino = ino;
997 list_init( &inode->open );
998 list_init( &inode->locks );
999 list_init( &inode->closed );
1000 list_add_head( &device->inode_hash[hash], &inode->entry );
1002 else release_object( device );
1004 return inode;
1007 /* add fd to the inode list of file descriptors to close */
1008 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1010 if (!list_empty( &inode->locks ))
1012 list_add_head( &inode->closed, &fd->entry );
1014 else if (fd->unlink[0]) /* close the fd but keep the structure around for unlink */
1016 if (fd->unix_fd != -1) close( fd->unix_fd );
1017 fd->unix_fd = -1;
1018 list_add_head( &inode->closed, &fd->entry );
1020 else /* no locks on this inode and no unlink, get rid of the fd */
1022 if (fd->unix_fd != -1) close( fd->unix_fd );
1023 free( fd );
1028 /****************************************************************/
1029 /* file lock functions */
1031 static void file_lock_dump( struct object *obj, int verbose )
1033 struct file_lock *lock = (struct file_lock *)obj;
1034 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1035 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1036 DUMP_LONG_LONG( lock->start );
1037 fprintf( stderr, " end=" );
1038 DUMP_LONG_LONG( lock->end );
1039 fprintf( stderr, "\n" );
1042 static int file_lock_signaled( struct object *obj, struct thread *thread )
1044 struct file_lock *lock = (struct file_lock *)obj;
1045 /* lock is signaled if it has lost its owner */
1046 return !lock->process;
1049 /* set (or remove) a Unix lock if possible for the given range */
1050 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1052 struct flock fl;
1054 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1055 for (;;)
1057 if (start == end) return 1; /* can't set zero-byte lock */
1058 if (start > max_unix_offset) return 1; /* ignore it */
1059 fl.l_type = type;
1060 fl.l_whence = SEEK_SET;
1061 fl.l_start = start;
1062 if (!end || end > max_unix_offset) fl.l_len = 0;
1063 else fl.l_len = end - start;
1064 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1066 switch(errno)
1068 case EACCES:
1069 /* check whether locks work at all on this file system */
1070 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1072 set_error( STATUS_FILE_LOCK_CONFLICT );
1073 return 0;
1075 /* fall through */
1076 case EIO:
1077 case ENOLCK:
1078 /* no locking on this fs, just ignore it */
1079 fd->fs_locks = 0;
1080 return 1;
1081 case EAGAIN:
1082 set_error( STATUS_FILE_LOCK_CONFLICT );
1083 return 0;
1084 case EBADF:
1085 /* this can happen if we try to set a write lock on a read-only file */
1086 /* we just ignore that error */
1087 if (fl.l_type == F_WRLCK) return 1;
1088 set_error( STATUS_ACCESS_DENIED );
1089 return 0;
1090 #ifdef EOVERFLOW
1091 case EOVERFLOW:
1092 #endif
1093 case EINVAL:
1094 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1095 /* in that case we shrink the limit and retry */
1096 if (max_unix_offset > INT_MAX)
1098 max_unix_offset = INT_MAX;
1099 break; /* retry */
1101 /* fall through */
1102 default:
1103 file_set_error();
1104 return 0;
1109 /* check if interval [start;end) overlaps the lock */
1110 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1112 if (lock->end && start >= lock->end) return 0;
1113 if (end && lock->start >= end) return 0;
1114 return 1;
1117 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1118 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1120 struct hole
1122 struct hole *next;
1123 struct hole *prev;
1124 file_pos_t start;
1125 file_pos_t end;
1126 } *first, *cur, *next, *buffer;
1128 struct list *ptr;
1129 int count = 0;
1131 if (!fd->inode) return;
1132 if (!fd->fs_locks) return;
1133 if (start == end || start > max_unix_offset) return;
1134 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1136 /* count the number of locks overlapping the specified area */
1138 LIST_FOR_EACH( ptr, &fd->inode->locks )
1140 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1141 if (lock->start == lock->end) continue;
1142 if (lock_overlaps( lock, start, end )) count++;
1145 if (!count) /* no locks at all, we can unlock everything */
1147 set_unix_lock( fd, start, end, F_UNLCK );
1148 return;
1151 /* allocate space for the list of holes */
1152 /* max. number of holes is number of locks + 1 */
1154 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1155 first = buffer;
1156 first->next = NULL;
1157 first->prev = NULL;
1158 first->start = start;
1159 first->end = end;
1160 next = first + 1;
1162 /* build a sorted list of unlocked holes in the specified area */
1164 LIST_FOR_EACH( ptr, &fd->inode->locks )
1166 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1167 if (lock->start == lock->end) continue;
1168 if (!lock_overlaps( lock, start, end )) continue;
1170 /* go through all the holes touched by this lock */
1171 for (cur = first; cur; cur = cur->next)
1173 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1174 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1176 /* now we know that lock is overlapping hole */
1178 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1180 cur->start = lock->end;
1181 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1182 /* now hole is empty, remove it */
1183 if (cur->next) cur->next->prev = cur->prev;
1184 if (cur->prev) cur->prev->next = cur->next;
1185 else if (!(first = cur->next)) goto done; /* no more holes at all */
1187 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1189 cur->end = lock->start;
1190 assert( cur->start < cur->end );
1192 else /* lock is in the middle of hole, split hole in two */
1194 next->prev = cur;
1195 next->next = cur->next;
1196 cur->next = next;
1197 next->start = lock->end;
1198 next->end = cur->end;
1199 cur->end = lock->start;
1200 assert( next->start < next->end );
1201 assert( cur->end < next->start );
1202 next++;
1203 break; /* done with this lock */
1208 /* clear Unix locks for all the holes */
1210 for (cur = first; cur; cur = cur->next)
1211 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1213 done:
1214 free( buffer );
1217 /* create a new lock on a fd */
1218 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1220 struct file_lock *lock;
1222 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1223 lock->shared = shared;
1224 lock->start = start;
1225 lock->end = end;
1226 lock->fd = fd;
1227 lock->process = current->process;
1229 /* now try to set a Unix lock */
1230 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1232 release_object( lock );
1233 return NULL;
1235 list_add_head( &fd->locks, &lock->fd_entry );
1236 list_add_head( &fd->inode->locks, &lock->inode_entry );
1237 list_add_head( &lock->process->locks, &lock->proc_entry );
1238 return lock;
1241 /* remove an existing lock */
1242 static void remove_lock( struct file_lock *lock, int remove_unix )
1244 struct inode *inode = lock->fd->inode;
1246 list_remove( &lock->fd_entry );
1247 list_remove( &lock->inode_entry );
1248 list_remove( &lock->proc_entry );
1249 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1250 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1251 lock->process = NULL;
1252 wake_up( &lock->obj, 0 );
1253 release_object( lock );
1256 /* remove all locks owned by a given process */
1257 void remove_process_locks( struct process *process )
1259 struct list *ptr;
1261 while ((ptr = list_head( &process->locks )))
1263 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1264 remove_lock( lock, 1 ); /* this removes it from the list */
1268 /* remove all locks on a given fd */
1269 static void remove_fd_locks( struct fd *fd )
1271 file_pos_t start = FILE_POS_T_MAX, end = 0;
1272 struct list *ptr;
1274 while ((ptr = list_head( &fd->locks )))
1276 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1277 if (lock->start < start) start = lock->start;
1278 if (!lock->end || lock->end > end) end = lock->end - 1;
1279 remove_lock( lock, 0 );
1281 if (start < end) remove_unix_locks( fd, start, end + 1 );
1284 /* add a lock on an fd */
1285 /* returns handle to wait on */
1286 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1288 struct list *ptr;
1289 file_pos_t end = start + count;
1291 if (!fd->inode) /* not a regular file */
1293 set_error( STATUS_INVALID_DEVICE_REQUEST );
1294 return 0;
1297 /* don't allow wrapping locks */
1298 if (end && end < start)
1300 set_error( STATUS_INVALID_PARAMETER );
1301 return 0;
1304 /* check if another lock on that file overlaps the area */
1305 LIST_FOR_EACH( ptr, &fd->inode->locks )
1307 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1308 if (!lock_overlaps( lock, start, end )) continue;
1309 if (lock->shared && shared) continue;
1310 /* found one */
1311 if (!wait)
1313 set_error( STATUS_FILE_LOCK_CONFLICT );
1314 return 0;
1316 set_error( STATUS_PENDING );
1317 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1320 /* not found, add it */
1321 if (add_lock( fd, shared, start, end )) return 0;
1322 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1324 /* Unix lock conflict -> tell client to wait and retry */
1325 if (wait) set_error( STATUS_PENDING );
1327 return 0;
1330 /* remove a lock on an fd */
1331 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1333 struct list *ptr;
1334 file_pos_t end = start + count;
1336 /* find an existing lock with the exact same parameters */
1337 LIST_FOR_EACH( ptr, &fd->locks )
1339 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1340 if ((lock->start == start) && (lock->end == end))
1342 remove_lock( lock, 1 );
1343 return;
1346 set_error( STATUS_FILE_LOCK_CONFLICT );
1350 /****************************************************************/
1351 /* file descriptor functions */
1353 static void fd_dump( struct object *obj, int verbose )
1355 struct fd *fd = (struct fd *)obj;
1356 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1357 if (fd->inode) fprintf( stderr, " inode=%p unlink='%s'", fd->inode, fd->closed->unlink );
1358 fprintf( stderr, "\n" );
1361 static void fd_destroy( struct object *obj )
1363 struct fd *fd = (struct fd *)obj;
1365 free_async_queue( fd->read_q );
1366 free_async_queue( fd->write_q );
1367 free_async_queue( fd->wait_q );
1369 if (fd->completion) release_object( fd->completion );
1370 remove_fd_locks( fd );
1371 list_remove( &fd->inode_entry );
1372 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1373 if (fd->inode)
1375 inode_add_closed_fd( fd->inode, fd->closed );
1376 release_object( fd->inode );
1378 else /* no inode, close it right away */
1380 if (fd->unix_fd != -1) close( fd->unix_fd );
1384 /* set the events that select waits for on this fd */
1385 void set_fd_events( struct fd *fd, int events )
1387 int user = fd->poll_index;
1388 assert( poll_users[user] == fd );
1390 set_fd_epoll_events( fd, user, events );
1392 if (events == -1) /* stop waiting on this fd completely */
1394 pollfd[user].fd = -1;
1395 pollfd[user].events = POLLERR;
1396 pollfd[user].revents = 0;
1398 else if (pollfd[user].fd != -1 || !pollfd[user].events)
1400 pollfd[user].fd = fd->unix_fd;
1401 pollfd[user].events = events;
1405 /* prepare an fd for unmounting its corresponding device */
1406 static inline void unmount_fd( struct fd *fd )
1408 assert( fd->inode );
1410 async_wake_up( fd->read_q, STATUS_VOLUME_DISMOUNTED );
1411 async_wake_up( fd->write_q, STATUS_VOLUME_DISMOUNTED );
1413 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1415 if (fd->unix_fd != -1) close( fd->unix_fd );
1417 fd->unix_fd = -1;
1418 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1419 fd->closed->unix_fd = -1;
1420 fd->closed->unlink[0] = 0;
1422 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1423 fd->fs_locks = 0;
1426 /* allocate an fd object, without setting the unix fd yet */
1427 static struct fd *alloc_fd_object(void)
1429 struct fd *fd = alloc_object( &fd_ops );
1431 if (!fd) return NULL;
1433 fd->fd_ops = NULL;
1434 fd->user = NULL;
1435 fd->inode = NULL;
1436 fd->closed = NULL;
1437 fd->access = 0;
1438 fd->options = 0;
1439 fd->sharing = 0;
1440 fd->unix_fd = -1;
1441 fd->signaled = 1;
1442 fd->fs_locks = 1;
1443 fd->poll_index = -1;
1444 fd->read_q = NULL;
1445 fd->write_q = NULL;
1446 fd->wait_q = NULL;
1447 fd->completion = NULL;
1448 list_init( &fd->inode_entry );
1449 list_init( &fd->locks );
1451 if ((fd->poll_index = add_poll_user( fd )) == -1)
1453 release_object( fd );
1454 return NULL;
1456 return fd;
1459 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1460 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1462 struct fd *fd = alloc_object( &fd_ops );
1464 if (!fd) return NULL;
1466 fd->fd_ops = fd_user_ops;
1467 fd->user = user;
1468 fd->inode = NULL;
1469 fd->closed = NULL;
1470 fd->access = 0;
1471 fd->options = options;
1472 fd->sharing = 0;
1473 fd->unix_fd = -1;
1474 fd->signaled = 0;
1475 fd->fs_locks = 0;
1476 fd->poll_index = -1;
1477 fd->read_q = NULL;
1478 fd->write_q = NULL;
1479 fd->wait_q = NULL;
1480 fd->completion = NULL;
1481 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1482 list_init( &fd->inode_entry );
1483 list_init( &fd->locks );
1484 return fd;
1487 /* set the status to return when the fd has no associated unix fd */
1488 void set_no_fd_status( struct fd *fd, unsigned int status )
1490 fd->no_fd_status = status;
1493 /* check if the desired access is possible without violating */
1494 /* the sharing mode of other opens of the same file */
1495 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
1497 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1498 unsigned int existing_access = 0;
1499 struct list *ptr;
1501 /* if access mode is 0, sharing mode is ignored */
1502 if (!access) sharing = existing_sharing;
1503 fd->access = access;
1504 fd->sharing = sharing;
1506 LIST_FOR_EACH( ptr, &fd->inode->open )
1508 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1509 if (fd_ptr != fd)
1511 existing_sharing &= fd_ptr->sharing;
1512 existing_access |= fd_ptr->access;
1516 if ((access & FILE_UNIX_READ_ACCESS) && !(existing_sharing & FILE_SHARE_READ)) return 0;
1517 if ((access & FILE_UNIX_WRITE_ACCESS) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1518 if ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1519 if ((existing_access & FILE_UNIX_READ_ACCESS) && !(sharing & FILE_SHARE_READ)) return 0;
1520 if ((existing_access & FILE_UNIX_WRITE_ACCESS) && !(sharing & FILE_SHARE_WRITE)) return 0;
1521 if ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)) return 0;
1522 return 1;
1525 /* sets the user of an fd that previously had no user */
1526 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1528 assert( fd->fd_ops == NULL );
1529 fd->fd_ops = user_ops;
1530 fd->user = user;
1533 /* open() wrapper that returns a struct fd with no fd user set */
1534 struct fd *open_fd( const char *name, int flags, mode_t *mode, unsigned int access,
1535 unsigned int sharing, unsigned int options )
1537 struct stat st;
1538 struct closed_fd *closed_fd;
1539 struct fd *fd;
1540 const char *unlink_name = "";
1541 int rw_mode;
1543 if ((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE))
1545 set_error( STATUS_INVALID_PARAMETER );
1546 return NULL;
1549 if (!(fd = alloc_fd_object())) return NULL;
1551 fd->options = options;
1552 if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1553 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1555 release_object( fd );
1556 return NULL;
1559 /* create the directory if needed */
1560 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1562 if (mkdir( name, 0777 ) == -1)
1564 if (errno != EEXIST || (flags & O_EXCL))
1566 file_set_error();
1567 goto error;
1570 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1573 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1575 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1576 else rw_mode = O_WRONLY;
1578 else rw_mode = O_RDONLY;
1580 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1582 /* if we tried to open a directory for write access, retry read-only */
1583 if (errno != EISDIR ||
1584 !(access & FILE_UNIX_WRITE_ACCESS) ||
1585 (fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode )) == -1)
1587 file_set_error();
1588 goto error;
1592 closed_fd->unix_fd = fd->unix_fd;
1593 closed_fd->unlink[0] = 0;
1594 fstat( fd->unix_fd, &st );
1595 *mode = st.st_mode;
1597 /* only bother with an inode for normal files and directories */
1598 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1600 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1602 if (!inode)
1604 /* we can close the fd because there are no others open on the same file,
1605 * otherwise we wouldn't have failed to allocate a new inode
1607 goto error;
1609 fd->inode = inode;
1610 fd->closed = closed_fd;
1611 list_add_head( &inode->open, &fd->inode_entry );
1613 /* check directory options */
1614 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1616 release_object( fd );
1617 set_error( STATUS_NOT_A_DIRECTORY );
1618 return NULL;
1620 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1622 release_object( fd );
1623 set_error( STATUS_FILE_IS_A_DIRECTORY );
1624 return NULL;
1626 if (!check_sharing( fd, access, sharing ))
1628 release_object( fd );
1629 set_error( STATUS_SHARING_VIOLATION );
1630 return NULL;
1632 strcpy( closed_fd->unlink, unlink_name );
1633 if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1635 else /* special file */
1637 if (options & FILE_DIRECTORY_FILE)
1639 set_error( STATUS_NOT_A_DIRECTORY );
1640 goto error;
1642 if (unlink_name[0]) /* we can't unlink special files */
1644 set_error( STATUS_INVALID_PARAMETER );
1645 goto error;
1647 free( closed_fd );
1649 return fd;
1651 error:
1652 release_object( fd );
1653 free( closed_fd );
1654 return NULL;
1657 /* create an fd for an anonymous file */
1658 /* if the function fails the unix fd is closed */
1659 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
1660 unsigned int options )
1662 struct fd *fd = alloc_fd_object();
1664 if (fd)
1666 set_fd_user( fd, fd_user_ops, user );
1667 fd->unix_fd = unix_fd;
1668 fd->options = options;
1669 return fd;
1671 close( unix_fd );
1672 return NULL;
1675 /* retrieve the object that is using an fd */
1676 void *get_fd_user( struct fd *fd )
1678 return fd->user;
1681 /* retrieve the opening options for the fd */
1682 unsigned int get_fd_options( struct fd *fd )
1684 return fd->options;
1687 /* retrieve the unix fd for an object */
1688 int get_unix_fd( struct fd *fd )
1690 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
1691 return fd->unix_fd;
1694 /* check if two file descriptors point to the same file */
1695 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1697 return fd1->inode == fd2->inode;
1700 /* check if fd is on a removable device */
1701 int is_fd_removable( struct fd *fd )
1703 return (fd->inode && fd->inode->device->removable);
1706 /* set or clear the fd signaled state */
1707 void set_fd_signaled( struct fd *fd, int signaled )
1709 fd->signaled = signaled;
1710 if (signaled) wake_up( fd->user, 0 );
1713 /* set or clear the fd signaled state */
1714 int is_fd_signaled( struct fd *fd )
1716 return fd->signaled;
1719 /* handler for close_handle that refuses to close fd-associated handles in other processes */
1720 int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
1722 return (!current || current->process == process);
1725 /* check if events are pending and if yes return which one(s) */
1726 int check_fd_events( struct fd *fd, int events )
1728 struct pollfd pfd;
1730 if (fd->unix_fd == -1) return POLLERR;
1731 if (fd->inode) return events; /* regular files are always signaled */
1733 pfd.fd = fd->unix_fd;
1734 pfd.events = events;
1735 if (poll( &pfd, 1, 0 ) <= 0) return 0;
1736 return pfd.revents;
1739 /* default signaled() routine for objects that poll() on an fd */
1740 int default_fd_signaled( struct object *obj, struct thread *thread )
1742 struct fd *fd = get_obj_fd( obj );
1743 int ret = fd->signaled;
1744 release_object( fd );
1745 return ret;
1748 /* default map_access() routine for objects that behave like an fd */
1749 unsigned int default_fd_map_access( struct object *obj, unsigned int access )
1751 if (access & GENERIC_READ) access |= FILE_GENERIC_READ;
1752 if (access & GENERIC_WRITE) access |= FILE_GENERIC_WRITE;
1753 if (access & GENERIC_EXECUTE) access |= FILE_GENERIC_EXECUTE;
1754 if (access & GENERIC_ALL) access |= FILE_ALL_ACCESS;
1755 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
1758 int default_fd_get_poll_events( struct fd *fd )
1760 int events = 0;
1762 if (async_waiting( fd->read_q )) events |= POLLIN;
1763 if (async_waiting( fd->write_q )) events |= POLLOUT;
1764 return events;
1767 /* default handler for poll() events */
1768 void default_poll_event( struct fd *fd, int event )
1770 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( fd->read_q, STATUS_ALERTED );
1771 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( fd->write_q, STATUS_ALERTED );
1773 /* if an error occurred, stop polling this fd to avoid busy-looping */
1774 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1775 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1778 struct async *fd_queue_async( struct fd *fd, const async_data_t *data, int type )
1780 struct async_queue *queue;
1781 struct async *async;
1783 switch (type)
1785 case ASYNC_TYPE_READ:
1786 if (!fd->read_q && !(fd->read_q = create_async_queue( fd ))) return NULL;
1787 queue = fd->read_q;
1788 break;
1789 case ASYNC_TYPE_WRITE:
1790 if (!fd->write_q && !(fd->write_q = create_async_queue( fd ))) return NULL;
1791 queue = fd->write_q;
1792 break;
1793 case ASYNC_TYPE_WAIT:
1794 if (!fd->wait_q && !(fd->wait_q = create_async_queue( fd ))) return NULL;
1795 queue = fd->wait_q;
1796 break;
1797 default:
1798 queue = NULL;
1799 assert(0);
1802 if ((async = create_async( current, queue, data )) && type != ASYNC_TYPE_WAIT)
1804 if (!fd->inode)
1805 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1806 else /* regular files are always ready for read and write */
1807 async_wake_up( queue, STATUS_ALERTED );
1809 return async;
1812 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
1814 switch (type)
1816 case ASYNC_TYPE_READ:
1817 async_wake_up( fd->read_q, status );
1818 break;
1819 case ASYNC_TYPE_WRITE:
1820 async_wake_up( fd->write_q, status );
1821 break;
1822 case ASYNC_TYPE_WAIT:
1823 async_wake_up( fd->wait_q, status );
1824 break;
1825 default:
1826 assert(0);
1830 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
1832 fd->fd_ops->reselect_async( fd, queue );
1835 void default_fd_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
1837 struct async *async;
1839 if ((async = fd_queue_async( fd, data, type )))
1841 release_object( async );
1842 set_error( STATUS_PENDING );
1846 /* default reselect_async() fd routine */
1847 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
1849 if (queue != fd->wait_q)
1851 int poll_events = fd->fd_ops->get_poll_events( fd );
1852 int events = check_fd_events( fd, poll_events );
1853 if (events) fd->fd_ops->poll_event( fd, events );
1854 else set_fd_events( fd, poll_events );
1858 /* default cancel_async() fd routine */
1859 void default_fd_cancel_async( struct fd *fd, struct process *process, struct thread *thread, client_ptr_t iosb )
1861 int n = 0;
1863 n += async_wake_up_by( fd->read_q, process, thread, iosb, STATUS_CANCELLED );
1864 n += async_wake_up_by( fd->write_q, process, thread, iosb, STATUS_CANCELLED );
1865 n += async_wake_up_by( fd->wait_q, process, thread, iosb, STATUS_CANCELLED );
1866 if (!n && iosb)
1867 set_error( STATUS_NOT_FOUND );
1870 /* default flush() routine */
1871 void no_flush( struct fd *fd, struct event **event )
1873 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1876 static inline int is_valid_mounted_device( struct stat *st )
1878 #if defined(linux) || defined(__sun__)
1879 return S_ISBLK( st->st_mode );
1880 #else
1881 /* disks are char devices on *BSD */
1882 return S_ISCHR( st->st_mode );
1883 #endif
1886 /* close all Unix file descriptors on a device to allow unmounting it */
1887 static void unmount_device( struct fd *device_fd )
1889 unsigned int i;
1890 struct stat st;
1891 struct device *device;
1892 struct inode *inode;
1893 struct fd *fd;
1894 int unix_fd = get_unix_fd( device_fd );
1896 if (unix_fd == -1) return;
1898 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
1900 set_error( STATUS_INVALID_PARAMETER );
1901 return;
1904 if (!(device = get_device( st.st_rdev, -1 ))) return;
1906 for (i = 0; i < INODE_HASH_SIZE; i++)
1908 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
1910 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
1912 unmount_fd( fd );
1914 inode_close_pending( inode, 0 );
1917 /* remove it from the hash table */
1918 list_remove( &device->entry );
1919 list_init( &device->entry );
1920 release_object( device );
1923 /* default ioctl() routine */
1924 obj_handle_t default_fd_ioctl( struct fd *fd, ioctl_code_t code, const async_data_t *async,
1925 int blocking, const void *data, data_size_t size )
1927 switch(code)
1929 case FSCTL_DISMOUNT_VOLUME:
1930 unmount_device( fd );
1931 return 0;
1932 default:
1933 set_error( STATUS_NOT_SUPPORTED );
1934 return 0;
1938 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1939 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1940 unsigned int access )
1942 struct fd *fd = NULL;
1943 struct object *obj;
1945 if ((obj = get_handle_obj( process, handle, access, NULL )))
1947 fd = get_obj_fd( obj );
1948 release_object( obj );
1950 return fd;
1953 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
1955 *p_key = fd->comp_key;
1956 return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
1959 void fd_copy_completion( struct fd *src, struct fd *dst )
1961 assert( !dst->completion );
1962 dst->completion = fd_get_completion( src, &dst->comp_key );
1965 /* flush a file buffers */
1966 DECL_HANDLER(flush_file)
1968 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1969 struct event * event = NULL;
1971 if (fd)
1973 fd->fd_ops->flush( fd, &event );
1974 if ( event )
1976 reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1978 release_object( fd );
1982 /* open a file object */
1983 DECL_HANDLER(open_file_object)
1985 struct unicode_str name;
1986 struct directory *root = NULL;
1987 struct object *obj, *result;
1989 get_req_unicode_str( &name );
1990 if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
1991 return;
1993 if ((obj = open_object_dir( root, &name, req->attributes, NULL )))
1995 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
1997 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
1998 release_object( result );
2000 release_object( obj );
2003 if (root) release_object( root );
2006 /* get a Unix fd to access a file */
2007 DECL_HANDLER(get_handle_fd)
2009 struct fd *fd;
2011 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2013 int unix_fd = get_unix_fd( fd );
2014 if (unix_fd != -1)
2016 reply->type = fd->fd_ops->get_fd_type( fd );
2017 reply->removable = is_fd_removable(fd);
2018 reply->options = fd->options;
2019 reply->access = get_handle_access( current->process, req->handle );
2020 send_client_fd( current->process, unix_fd, req->handle );
2022 release_object( fd );
2026 /* perform an ioctl on a file */
2027 DECL_HANDLER(ioctl)
2029 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2030 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2032 if (fd)
2034 reply->wait = fd->fd_ops->ioctl( fd, req->code, &req->async, req->blocking,
2035 get_req_data(), get_req_data_size() );
2036 reply->options = fd->options;
2037 release_object( fd );
2041 /* create / reschedule an async I/O */
2042 DECL_HANDLER(register_async)
2044 unsigned int access;
2045 struct fd *fd;
2047 switch(req->type)
2049 case ASYNC_TYPE_READ:
2050 access = FILE_READ_DATA;
2051 break;
2052 case ASYNC_TYPE_WRITE:
2053 access = FILE_WRITE_DATA;
2054 break;
2055 default:
2056 set_error( STATUS_INVALID_PARAMETER );
2057 return;
2060 if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2062 if (get_unix_fd( fd ) != -1) fd->fd_ops->queue_async( fd, &req->async, req->type, req->count );
2063 release_object( fd );
2067 /* cancels all async I/O */
2068 DECL_HANDLER(cancel_async)
2070 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2071 struct thread *thread = req->only_thread ? current : NULL;
2073 if (fd)
2075 if (get_unix_fd( fd ) != -1) fd->fd_ops->cancel_async( fd, current->process, thread, req->iosb );
2076 release_object( fd );
2080 /* attach completion object to a fd */
2081 DECL_HANDLER(set_completion_info)
2083 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2085 if (fd)
2087 if (!(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) && !fd->completion)
2089 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2090 fd->comp_key = req->ckey;
2092 else set_error( STATUS_INVALID_PARAMETER );
2093 release_object( fd );
2097 /* push new completion msg into a completion queue attached to the fd */
2098 DECL_HANDLER(add_fd_completion)
2100 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2101 if (fd)
2103 if (fd->completion)
2104 add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2105 release_object( fd );