TESTING -- override pthreads to fix gstreamer v5
[wine/multimedia.git] / server / fd.c
blobe3fe292adeff4a07d9c1d6c39de9803ba61bb6e3
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 /* Work around a conflict with Solaris' system list defined in sys/list.h. */
48 #define list SYSLIST
49 #define list_next SYSLIST_NEXT
50 #define list_prev SYSLIST_PREV
51 #define list_head SYSLIST_HEAD
52 #define list_tail SYSLIST_TAIL
53 #define list_move_tail SYSLIST_MOVE_TAIL
54 #define list_remove SYSLIST_REMOVE
55 #include <sys/vfs.h>
56 #undef list
57 #undef list_next
58 #undef list_prev
59 #undef list_head
60 #undef list_tail
61 #undef list_move_tail
62 #undef list_remove
63 #endif
64 #ifdef HAVE_SYS_PARAM_H
65 #include <sys/param.h>
66 #endif
67 #ifdef HAVE_SYS_MOUNT_H
68 #include <sys/mount.h>
69 #endif
70 #ifdef HAVE_SYS_STATFS_H
71 #include <sys/statfs.h>
72 #endif
73 #ifdef HAVE_SYS_SYSCTL_H
74 #include <sys/sysctl.h>
75 #endif
76 #ifdef HAVE_SYS_EVENT_H
77 #include <sys/event.h>
78 #undef LIST_INIT
79 #undef LIST_ENTRY
80 #endif
81 #ifdef HAVE_STDINT_H
82 #include <stdint.h>
83 #endif
84 #include <sys/stat.h>
85 #include <sys/time.h>
86 #include <sys/types.h>
87 #include <unistd.h>
88 #ifdef HAVE_SYS_SYSCALL_H
89 #include <sys/syscall.h>
90 #endif
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 static inline int epoll_create( int size )
132 return syscall( 254 /*NR_epoll_create*/, size );
135 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
137 return syscall( 255 /*NR_epoll_ctl*/, epfd, op, fd, event );
140 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
142 return syscall( 256 /*NR_epoll_wait*/, epfd, events, maxevents, timeout );
145 #endif /* linux && __i386__ && HAVE_STDINT_H */
147 #if defined(HAVE_PORT_H) && defined(HAVE_PORT_CREATE)
148 # include <port.h>
149 # define USE_EVENT_PORTS
150 #endif /* HAVE_PORT_H && HAVE_PORT_CREATE */
152 /* Because of the stupid Posix locking semantics, we need to keep
153 * track of all file descriptors referencing a given file, and not
154 * close a single one until all the locks are gone (sigh).
157 /* file descriptor object */
159 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
160 struct closed_fd
162 struct list entry; /* entry in inode closed list */
163 int unix_fd; /* the unix file descriptor */
164 int unlink; /* whether to unlink on close */
165 char *unix_name; /* name to unlink on close, points to parent fd unix_name */
168 struct fd
170 struct object obj; /* object header */
171 const struct fd_ops *fd_ops; /* file descriptor operations */
172 struct inode *inode; /* inode that this fd belongs to */
173 struct list inode_entry; /* entry in inode fd list */
174 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
175 struct object *user; /* object using this file descriptor */
176 struct list locks; /* list of locks on this fd */
177 unsigned int access; /* file access (FILE_READ_DATA etc.) */
178 unsigned int options; /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
179 unsigned int sharing; /* file sharing mode */
180 char *unix_name; /* unix file name */
181 int unix_fd; /* unix file descriptor */
182 unsigned int no_fd_status;/* status to return when unix_fd is -1 */
183 unsigned int cacheable :1;/* can the fd be cached on the client side? */
184 unsigned int signaled :1; /* is the fd signaled? */
185 unsigned int fs_locks :1; /* can we use filesystem locks for this fd? */
186 int poll_index; /* index of fd in poll array */
187 struct async_queue *read_q; /* async readers of this fd */
188 struct async_queue *write_q; /* async writers of this fd */
189 struct async_queue *wait_q; /* other async waiters of this fd */
190 struct completion *completion; /* completion object attached to this fd */
191 apc_param_t comp_key; /* completion key to set in completion events */
194 static void fd_dump( struct object *obj, int verbose );
195 static void fd_destroy( struct object *obj );
197 static const struct object_ops fd_ops =
199 sizeof(struct fd), /* size */
200 fd_dump, /* dump */
201 no_get_type, /* get_type */
202 no_add_queue, /* add_queue */
203 NULL, /* remove_queue */
204 NULL, /* signaled */
205 NULL, /* satisfied */
206 no_signal, /* signal */
207 no_get_fd, /* get_fd */
208 no_map_access, /* map_access */
209 default_get_sd, /* get_sd */
210 default_set_sd, /* set_sd */
211 no_lookup_name, /* lookup_name */
212 no_open_file, /* open_file */
213 no_close_handle, /* close_handle */
214 fd_destroy /* destroy */
217 /* device object */
219 #define DEVICE_HASH_SIZE 7
220 #define INODE_HASH_SIZE 17
222 struct device
224 struct object obj; /* object header */
225 struct list entry; /* entry in device hash list */
226 dev_t dev; /* device number */
227 int removable; /* removable device? (or -1 if unknown) */
228 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
231 static void device_dump( struct object *obj, int verbose );
232 static void device_destroy( struct object *obj );
234 static const struct object_ops device_ops =
236 sizeof(struct device), /* size */
237 device_dump, /* dump */
238 no_get_type, /* get_type */
239 no_add_queue, /* add_queue */
240 NULL, /* remove_queue */
241 NULL, /* signaled */
242 NULL, /* satisfied */
243 no_signal, /* signal */
244 no_get_fd, /* get_fd */
245 no_map_access, /* map_access */
246 default_get_sd, /* get_sd */
247 default_set_sd, /* set_sd */
248 no_lookup_name, /* lookup_name */
249 no_open_file, /* open_file */
250 no_close_handle, /* close_handle */
251 device_destroy /* destroy */
254 /* inode object */
256 struct inode
258 struct object obj; /* object header */
259 struct list entry; /* inode hash list entry */
260 struct device *device; /* device containing this inode */
261 ino_t ino; /* inode number */
262 struct list open; /* list of open file descriptors */
263 struct list locks; /* list of file locks */
264 struct list closed; /* list of file descriptors to close at destroy time */
267 static void inode_dump( struct object *obj, int verbose );
268 static void inode_destroy( struct object *obj );
270 static const struct object_ops inode_ops =
272 sizeof(struct inode), /* size */
273 inode_dump, /* dump */
274 no_get_type, /* get_type */
275 no_add_queue, /* add_queue */
276 NULL, /* remove_queue */
277 NULL, /* signaled */
278 NULL, /* satisfied */
279 no_signal, /* signal */
280 no_get_fd, /* get_fd */
281 no_map_access, /* map_access */
282 default_get_sd, /* get_sd */
283 default_set_sd, /* set_sd */
284 no_lookup_name, /* lookup_name */
285 no_open_file, /* open_file */
286 no_close_handle, /* close_handle */
287 inode_destroy /* destroy */
290 /* file lock object */
292 struct file_lock
294 struct object obj; /* object header */
295 struct fd *fd; /* fd owning this lock */
296 struct list fd_entry; /* entry in list of locks on a given fd */
297 struct list inode_entry; /* entry in inode list of locks */
298 int shared; /* shared lock? */
299 file_pos_t start; /* locked region is interval [start;end) */
300 file_pos_t end;
301 struct process *process; /* process owning this lock */
302 struct list proc_entry; /* entry in list of locks owned by the process */
305 static void file_lock_dump( struct object *obj, int verbose );
306 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry );
308 static const struct object_ops file_lock_ops =
310 sizeof(struct file_lock), /* size */
311 file_lock_dump, /* dump */
312 no_get_type, /* get_type */
313 add_queue, /* add_queue */
314 remove_queue, /* remove_queue */
315 file_lock_signaled, /* signaled */
316 no_satisfied, /* satisfied */
317 no_signal, /* signal */
318 no_get_fd, /* get_fd */
319 no_map_access, /* map_access */
320 default_get_sd, /* get_sd */
321 default_set_sd, /* set_sd */
322 no_lookup_name, /* lookup_name */
323 no_open_file, /* open_file */
324 no_close_handle, /* close_handle */
325 no_destroy /* destroy */
329 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
330 #define FILE_POS_T_MAX (~(file_pos_t)0)
332 static file_pos_t max_unix_offset = OFF_T_MAX;
334 #define DUMP_LONG_LONG(val) do { \
335 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
336 fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
337 else \
338 fprintf( stderr, "%lx", (unsigned long)(val) ); \
339 } while (0)
343 /****************************************************************/
344 /* timeouts support */
346 struct timeout_user
348 struct list entry; /* entry in sorted timeout list */
349 timeout_t when; /* timeout expiry (absolute time) */
350 timeout_callback callback; /* callback function */
351 void *private; /* callback private data */
354 static struct list timeout_list = LIST_INIT(timeout_list); /* sorted timeouts list */
355 timeout_t current_time;
357 static inline void set_current_time(void)
359 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
360 struct timeval now;
361 gettimeofday( &now, NULL );
362 current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
365 /* add a timeout user */
366 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
368 struct timeout_user *user;
369 struct list *ptr;
371 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
372 user->when = (when > 0) ? when : current_time - when;
373 user->callback = func;
374 user->private = private;
376 /* Now insert it in the linked list */
378 LIST_FOR_EACH( ptr, &timeout_list )
380 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
381 if (timeout->when >= user->when) break;
383 list_add_before( ptr, &user->entry );
384 return user;
387 /* remove a timeout user */
388 void remove_timeout_user( struct timeout_user *user )
390 list_remove( &user->entry );
391 free( user );
394 /* return a text description of a timeout for debugging purposes */
395 const char *get_timeout_str( timeout_t timeout )
397 static char buffer[64];
398 long secs, nsecs;
400 if (!timeout) return "0";
401 if (timeout == TIMEOUT_INFINITE) return "infinite";
403 if (timeout < 0) /* relative */
405 secs = -timeout / TICKS_PER_SEC;
406 nsecs = -timeout % TICKS_PER_SEC;
407 sprintf( buffer, "+%ld.%07ld", secs, nsecs );
409 else /* absolute */
411 secs = (timeout - current_time) / TICKS_PER_SEC;
412 nsecs = (timeout - current_time) % TICKS_PER_SEC;
413 if (nsecs < 0)
415 nsecs += TICKS_PER_SEC;
416 secs--;
418 if (secs >= 0)
419 sprintf( buffer, "%x%08x (+%ld.%07ld)",
420 (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
421 else
422 sprintf( buffer, "%x%08x (-%ld.%07ld)",
423 (unsigned int)(timeout >> 32), (unsigned int)timeout,
424 -(secs + 1), TICKS_PER_SEC - nsecs );
426 return buffer;
430 /****************************************************************/
431 /* poll support */
433 static struct fd **poll_users; /* users array */
434 static struct pollfd *pollfd; /* poll fd array */
435 static int nb_users; /* count of array entries actually in use */
436 static int active_users; /* current number of active users */
437 static int allocated_users; /* count of allocated entries in the array */
438 static struct fd **freelist; /* list of free entries in the array */
440 static int get_next_timeout(void);
442 static inline void fd_poll_event( struct fd *fd, int event )
444 fd->fd_ops->poll_event( fd, event );
447 #ifdef USE_EPOLL
449 static int epoll_fd = -1;
451 static inline void init_epoll(void)
453 epoll_fd = epoll_create( 128 );
456 /* set the events that epoll waits for on this fd; helper for set_fd_events */
457 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
459 struct epoll_event ev;
460 int ctl;
462 if (epoll_fd == -1) return;
464 if (events == -1) /* stop waiting on this fd completely */
466 if (pollfd[user].fd == -1) return; /* already removed */
467 ctl = EPOLL_CTL_DEL;
469 else if (pollfd[user].fd == -1)
471 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
472 ctl = EPOLL_CTL_ADD;
474 else
476 if (pollfd[user].events == events) return; /* nothing to do */
477 ctl = EPOLL_CTL_MOD;
480 ev.events = events;
481 memset(&ev.data, 0, sizeof(ev.data));
482 ev.data.u32 = user;
484 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
486 if (errno == ENOMEM) /* not enough memory, give up on epoll */
488 close( epoll_fd );
489 epoll_fd = -1;
491 else perror( "epoll_ctl" ); /* should not happen */
495 static inline void remove_epoll_user( struct fd *fd, int user )
497 if (epoll_fd == -1) return;
499 if (pollfd[user].fd != -1)
501 struct epoll_event dummy;
502 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
506 static inline void main_loop_epoll(void)
508 int i, ret, timeout;
509 struct epoll_event events[128];
511 assert( POLLIN == EPOLLIN );
512 assert( POLLOUT == EPOLLOUT );
513 assert( POLLERR == EPOLLERR );
514 assert( POLLHUP == EPOLLHUP );
516 if (epoll_fd == -1) return;
518 while (active_users)
520 timeout = get_next_timeout();
522 if (!active_users) break; /* last user removed by a timeout */
523 if (epoll_fd == -1) break; /* an error occurred with epoll */
525 ret = epoll_wait( epoll_fd, events, sizeof(events)/sizeof(events[0]), timeout );
526 set_current_time();
528 /* put the events into the pollfd array first, like poll does */
529 for (i = 0; i < ret; i++)
531 int user = events[i].data.u32;
532 pollfd[user].revents = events[i].events;
535 /* read events from the pollfd array, as set_fd_events may modify them */
536 for (i = 0; i < ret; i++)
538 int user = events[i].data.u32;
539 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
544 #elif defined(HAVE_KQUEUE)
546 static int kqueue_fd = -1;
548 static inline void init_epoll(void)
550 #ifdef __APPLE__ /* kqueue support is broken in Mac OS < 10.5 */
551 int mib[2];
552 char release[32];
553 size_t len = sizeof(release);
555 mib[0] = CTL_KERN;
556 mib[1] = KERN_OSRELEASE;
557 if (sysctl( mib, 2, release, &len, NULL, 0 ) == -1) return;
558 if (atoi(release) < 9) return;
559 #endif
560 kqueue_fd = kqueue();
563 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
565 struct kevent ev[2];
567 if (kqueue_fd == -1) return;
569 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)user );
570 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)user );
572 if (events == -1) /* stop waiting on this fd completely */
574 if (pollfd[user].fd == -1) return; /* already removed */
575 ev[0].flags |= EV_DELETE;
576 ev[1].flags |= EV_DELETE;
578 else if (pollfd[user].fd == -1)
580 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
581 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
582 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
584 else
586 if (pollfd[user].events == events) return; /* nothing to do */
587 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
588 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
591 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
593 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
595 close( kqueue_fd );
596 kqueue_fd = -1;
598 else perror( "kevent" ); /* should not happen */
602 static inline void remove_epoll_user( struct fd *fd, int user )
604 if (kqueue_fd == -1) return;
606 if (pollfd[user].fd != -1)
608 struct kevent ev[2];
610 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
611 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
612 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
616 static inline void main_loop_epoll(void)
618 int i, ret, timeout;
619 struct kevent events[128];
621 if (kqueue_fd == -1) return;
623 while (active_users)
625 timeout = get_next_timeout();
627 if (!active_users) break; /* last user removed by a timeout */
628 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
630 if (timeout != -1)
632 struct timespec ts;
634 ts.tv_sec = timeout / 1000;
635 ts.tv_nsec = (timeout % 1000) * 1000000;
636 ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), &ts );
638 else ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), NULL );
640 set_current_time();
642 /* put the events into the pollfd array first, like poll does */
643 for (i = 0; i < ret; i++)
645 long user = (long)events[i].udata;
646 pollfd[user].revents = 0;
648 for (i = 0; i < ret; i++)
650 long user = (long)events[i].udata;
651 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
652 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
653 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
654 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
657 /* read events from the pollfd array, as set_fd_events may modify them */
658 for (i = 0; i < ret; i++)
660 long user = (long)events[i].udata;
661 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
662 pollfd[user].revents = 0;
667 #elif defined(USE_EVENT_PORTS)
669 static int port_fd = -1;
671 static inline void init_epoll(void)
673 port_fd = port_create();
676 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
678 int ret;
680 if (port_fd == -1) return;
682 if (events == -1) /* stop waiting on this fd completely */
684 if (pollfd[user].fd == -1) return; /* already removed */
685 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
687 else if (pollfd[user].fd == -1)
689 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
690 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
692 else
694 if (pollfd[user].events == events) return; /* nothing to do */
695 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
698 if (ret == -1)
700 if (errno == ENOMEM) /* not enough memory, give up on port_associate */
702 close( port_fd );
703 port_fd = -1;
705 else perror( "port_associate" ); /* should not happen */
709 static inline void remove_epoll_user( struct fd *fd, int user )
711 if (port_fd == -1) return;
713 if (pollfd[user].fd != -1)
715 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
719 static inline void main_loop_epoll(void)
721 int i, nget, ret, timeout;
722 port_event_t events[128];
724 if (port_fd == -1) return;
726 while (active_users)
728 timeout = get_next_timeout();
729 nget = 1;
731 if (!active_users) break; /* last user removed by a timeout */
732 if (port_fd == -1) break; /* an error occurred with event completion */
734 if (timeout != -1)
736 struct timespec ts;
738 ts.tv_sec = timeout / 1000;
739 ts.tv_nsec = (timeout % 1000) * 1000000;
740 ret = port_getn( port_fd, events, sizeof(events)/sizeof(events[0]), &nget, &ts );
742 else ret = port_getn( port_fd, events, sizeof(events)/sizeof(events[0]), &nget, NULL );
744 if (ret == -1) break; /* an error occurred with event completion */
746 set_current_time();
748 /* put the events into the pollfd array first, like poll does */
749 for (i = 0; i < nget; i++)
751 long user = (long)events[i].portev_user;
752 pollfd[user].revents = events[i].portev_events;
755 /* read events from the pollfd array, as set_fd_events may modify them */
756 for (i = 0; i < nget; i++)
758 long user = (long)events[i].portev_user;
759 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
760 /* if we are still interested, reassociate the fd */
761 if (pollfd[user].fd != -1) {
762 port_associate( port_fd, PORT_SOURCE_FD, pollfd[user].fd, pollfd[user].events, (void *)user );
768 #else /* HAVE_KQUEUE */
770 static inline void init_epoll(void) { }
771 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
772 static inline void remove_epoll_user( struct fd *fd, int user ) { }
773 static inline void main_loop_epoll(void) { }
775 #endif /* USE_EPOLL */
778 /* add a user in the poll array and return its index, or -1 on failure */
779 static int add_poll_user( struct fd *fd )
781 int ret;
782 if (freelist)
784 ret = freelist - poll_users;
785 freelist = (struct fd **)poll_users[ret];
787 else
789 if (nb_users == allocated_users)
791 struct fd **newusers;
792 struct pollfd *newpoll;
793 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
794 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
795 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
797 if (allocated_users)
798 poll_users = newusers;
799 else
800 free( newusers );
801 return -1;
803 poll_users = newusers;
804 pollfd = newpoll;
805 if (!allocated_users) init_epoll();
806 allocated_users = new_count;
808 ret = nb_users++;
810 pollfd[ret].fd = -1;
811 pollfd[ret].events = 0;
812 pollfd[ret].revents = 0;
813 poll_users[ret] = fd;
814 active_users++;
815 return ret;
818 /* remove a user from the poll list */
819 static void remove_poll_user( struct fd *fd, int user )
821 assert( user >= 0 );
822 assert( poll_users[user] == fd );
824 remove_epoll_user( fd, user );
825 pollfd[user].fd = -1;
826 pollfd[user].events = 0;
827 pollfd[user].revents = 0;
828 poll_users[user] = (struct fd *)freelist;
829 freelist = &poll_users[user];
830 active_users--;
833 /* process pending timeouts and return the time until the next timeout, in milliseconds */
834 static int get_next_timeout(void)
836 if (!list_empty( &timeout_list ))
838 struct list expired_list, *ptr;
840 /* first remove all expired timers from the list */
842 list_init( &expired_list );
843 while ((ptr = list_head( &timeout_list )) != NULL)
845 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
847 if (timeout->when <= current_time)
849 list_remove( &timeout->entry );
850 list_add_tail( &expired_list, &timeout->entry );
852 else break;
855 /* now call the callback for all the removed timers */
857 while ((ptr = list_head( &expired_list )) != NULL)
859 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
860 list_remove( &timeout->entry );
861 timeout->callback( timeout->private );
862 free( timeout );
865 if ((ptr = list_head( &timeout_list )) != NULL)
867 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
868 int diff = (timeout->when - current_time + 9999) / 10000;
869 if (diff < 0) diff = 0;
870 return diff;
873 return -1; /* no pending timeouts */
876 /* server main poll() loop */
877 void main_loop(void)
879 int i, ret, timeout;
881 set_current_time();
882 server_start_time = current_time;
884 main_loop_epoll();
885 /* fall through to normal poll loop */
887 while (active_users)
889 timeout = get_next_timeout();
891 if (!active_users) break; /* last user removed by a timeout */
893 ret = poll( pollfd, nb_users, timeout );
894 set_current_time();
896 if (ret > 0)
898 for (i = 0; i < nb_users; i++)
900 if (pollfd[i].revents)
902 fd_poll_event( poll_users[i], pollfd[i].revents );
903 if (!--ret) break;
911 /****************************************************************/
912 /* device functions */
914 static struct list device_hash[DEVICE_HASH_SIZE];
916 static int is_device_removable( dev_t dev, int unix_fd )
918 #if defined(linux) && defined(HAVE_FSTATFS)
919 struct statfs stfs;
921 /* check for floppy disk */
922 if (major(dev) == FLOPPY_MAJOR) return 1;
924 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
925 return (stfs.f_type == 0x9660 || /* iso9660 */
926 stfs.f_type == 0x9fa1 || /* supermount */
927 stfs.f_type == 0x15013346); /* udf */
928 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
929 struct statfs stfs;
931 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
932 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
933 #elif defined(__NetBSD__)
934 struct statvfs stfs;
936 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
937 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
938 #elif defined(sun)
939 # include <sys/dkio.h>
940 # include <sys/vtoc.h>
941 struct dk_cinfo dkinf;
942 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
943 return (dkinf.dki_ctype == DKC_CDROM ||
944 dkinf.dki_ctype == DKC_NCRFLOPPY ||
945 dkinf.dki_ctype == DKC_SMSFLOPPY ||
946 dkinf.dki_ctype == DKC_INTEL82072 ||
947 dkinf.dki_ctype == DKC_INTEL82077);
948 #else
949 return 0;
950 #endif
953 /* retrieve the device object for a given fd, creating it if needed */
954 static struct device *get_device( dev_t dev, int unix_fd )
956 struct device *device;
957 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
959 if (device_hash[hash].next)
961 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
962 if (device->dev == dev) return (struct device *)grab_object( device );
964 else list_init( &device_hash[hash] );
966 /* not found, create it */
968 if (unix_fd == -1) return NULL;
969 if ((device = alloc_object( &device_ops )))
971 device->dev = dev;
972 device->removable = is_device_removable( dev, unix_fd );
973 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
974 list_add_head( &device_hash[hash], &device->entry );
976 return device;
979 static void device_dump( struct object *obj, int verbose )
981 struct device *device = (struct device *)obj;
982 fprintf( stderr, "Device dev=" );
983 DUMP_LONG_LONG( device->dev );
984 fprintf( stderr, "\n" );
987 static void device_destroy( struct object *obj )
989 struct device *device = (struct device *)obj;
990 unsigned int i;
992 for (i = 0; i < INODE_HASH_SIZE; i++)
993 assert( list_empty(&device->inode_hash[i]) );
995 list_remove( &device->entry ); /* remove it from the hash table */
999 /****************************************************************/
1000 /* inode functions */
1002 /* close all pending file descriptors in the closed list */
1003 static void inode_close_pending( struct inode *inode, int keep_unlinks )
1005 struct list *ptr = list_head( &inode->closed );
1007 while (ptr)
1009 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1010 struct list *next = list_next( &inode->closed, ptr );
1012 if (fd->unix_fd != -1)
1014 close( fd->unix_fd );
1015 fd->unix_fd = -1;
1017 if (!keep_unlinks || !fd->unlink) /* get rid of it unless there's an unlink pending on that file */
1019 list_remove( ptr );
1020 free( fd->unix_name );
1021 free( fd );
1023 ptr = next;
1027 static void inode_dump( struct object *obj, int verbose )
1029 struct inode *inode = (struct inode *)obj;
1030 fprintf( stderr, "Inode device=%p ino=", inode->device );
1031 DUMP_LONG_LONG( inode->ino );
1032 fprintf( stderr, "\n" );
1035 static void inode_destroy( struct object *obj )
1037 struct inode *inode = (struct inode *)obj;
1038 struct list *ptr;
1040 assert( list_empty(&inode->open) );
1041 assert( list_empty(&inode->locks) );
1043 list_remove( &inode->entry );
1045 while ((ptr = list_head( &inode->closed )))
1047 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1048 list_remove( ptr );
1049 if (fd->unix_fd != -1) close( fd->unix_fd );
1050 if (fd->unlink)
1052 /* make sure it is still the same file */
1053 struct stat st;
1054 if (!stat( fd->unix_name, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
1056 if (S_ISDIR(st.st_mode)) rmdir( fd->unix_name );
1057 else unlink( fd->unix_name );
1060 free( fd->unix_name );
1061 free( fd );
1063 release_object( inode->device );
1066 /* retrieve the inode object for a given fd, creating it if needed */
1067 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
1069 struct device *device;
1070 struct inode *inode;
1071 unsigned int hash = ino % INODE_HASH_SIZE;
1073 if (!(device = get_device( dev, unix_fd ))) return NULL;
1075 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
1077 if (inode->ino == ino)
1079 release_object( device );
1080 return (struct inode *)grab_object( inode );
1084 /* not found, create it */
1085 if ((inode = alloc_object( &inode_ops )))
1087 inode->device = device;
1088 inode->ino = ino;
1089 list_init( &inode->open );
1090 list_init( &inode->locks );
1091 list_init( &inode->closed );
1092 list_add_head( &device->inode_hash[hash], &inode->entry );
1094 else release_object( device );
1096 return inode;
1099 /* add fd to the inode list of file descriptors to close */
1100 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1102 if (!list_empty( &inode->locks ))
1104 list_add_head( &inode->closed, &fd->entry );
1106 else if (fd->unlink) /* close the fd but keep the structure around for unlink */
1108 if (fd->unix_fd != -1) close( fd->unix_fd );
1109 fd->unix_fd = -1;
1110 list_add_head( &inode->closed, &fd->entry );
1112 else /* no locks on this inode and no unlink, get rid of the fd */
1114 if (fd->unix_fd != -1) close( fd->unix_fd );
1115 free( fd->unix_name );
1116 free( fd );
1121 /****************************************************************/
1122 /* file lock functions */
1124 static void file_lock_dump( struct object *obj, int verbose )
1126 struct file_lock *lock = (struct file_lock *)obj;
1127 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1128 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1129 DUMP_LONG_LONG( lock->start );
1130 fprintf( stderr, " end=" );
1131 DUMP_LONG_LONG( lock->end );
1132 fprintf( stderr, "\n" );
1135 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry )
1137 struct file_lock *lock = (struct file_lock *)obj;
1138 /* lock is signaled if it has lost its owner */
1139 return !lock->process;
1142 /* set (or remove) a Unix lock if possible for the given range */
1143 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1145 struct flock fl;
1147 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1148 for (;;)
1150 if (start == end) return 1; /* can't set zero-byte lock */
1151 if (start > max_unix_offset) return 1; /* ignore it */
1152 fl.l_type = type;
1153 fl.l_whence = SEEK_SET;
1154 fl.l_start = start;
1155 if (!end || end > max_unix_offset) fl.l_len = 0;
1156 else fl.l_len = end - start;
1157 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1159 switch(errno)
1161 case EACCES:
1162 /* check whether locks work at all on this file system */
1163 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1165 set_error( STATUS_FILE_LOCK_CONFLICT );
1166 return 0;
1168 /* fall through */
1169 case EIO:
1170 case ENOLCK:
1171 case ENOTSUP:
1172 /* no locking on this fs, just ignore it */
1173 fd->fs_locks = 0;
1174 return 1;
1175 case EAGAIN:
1176 set_error( STATUS_FILE_LOCK_CONFLICT );
1177 return 0;
1178 case EBADF:
1179 /* this can happen if we try to set a write lock on a read-only file */
1180 /* try to at least grab a read lock */
1181 if (fl.l_type == F_WRLCK)
1183 type = F_RDLCK;
1184 break; /* retry */
1186 set_error( STATUS_ACCESS_DENIED );
1187 return 0;
1188 #ifdef EOVERFLOW
1189 case EOVERFLOW:
1190 #endif
1191 case EINVAL:
1192 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1193 /* in that case we shrink the limit and retry */
1194 if (max_unix_offset > INT_MAX)
1196 max_unix_offset = INT_MAX;
1197 break; /* retry */
1199 /* fall through */
1200 default:
1201 file_set_error();
1202 return 0;
1207 /* check if interval [start;end) overlaps the lock */
1208 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1210 if (lock->end && start >= lock->end) return 0;
1211 if (end && lock->start >= end) return 0;
1212 return 1;
1215 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1216 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1218 struct hole
1220 struct hole *next;
1221 struct hole *prev;
1222 file_pos_t start;
1223 file_pos_t end;
1224 } *first, *cur, *next, *buffer;
1226 struct list *ptr;
1227 int count = 0;
1229 if (!fd->inode) return;
1230 if (!fd->fs_locks) return;
1231 if (start == end || start > max_unix_offset) return;
1232 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1234 /* count the number of locks overlapping the specified area */
1236 LIST_FOR_EACH( ptr, &fd->inode->locks )
1238 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1239 if (lock->start == lock->end) continue;
1240 if (lock_overlaps( lock, start, end )) count++;
1243 if (!count) /* no locks at all, we can unlock everything */
1245 set_unix_lock( fd, start, end, F_UNLCK );
1246 return;
1249 /* allocate space for the list of holes */
1250 /* max. number of holes is number of locks + 1 */
1252 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1253 first = buffer;
1254 first->next = NULL;
1255 first->prev = NULL;
1256 first->start = start;
1257 first->end = end;
1258 next = first + 1;
1260 /* build a sorted list of unlocked holes in the specified area */
1262 LIST_FOR_EACH( ptr, &fd->inode->locks )
1264 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1265 if (lock->start == lock->end) continue;
1266 if (!lock_overlaps( lock, start, end )) continue;
1268 /* go through all the holes touched by this lock */
1269 for (cur = first; cur; cur = cur->next)
1271 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1272 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1274 /* now we know that lock is overlapping hole */
1276 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1278 cur->start = lock->end;
1279 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1280 /* now hole is empty, remove it */
1281 if (cur->next) cur->next->prev = cur->prev;
1282 if (cur->prev) cur->prev->next = cur->next;
1283 else if (!(first = cur->next)) goto done; /* no more holes at all */
1285 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1287 cur->end = lock->start;
1288 assert( cur->start < cur->end );
1290 else /* lock is in the middle of hole, split hole in two */
1292 next->prev = cur;
1293 next->next = cur->next;
1294 cur->next = next;
1295 next->start = lock->end;
1296 next->end = cur->end;
1297 cur->end = lock->start;
1298 assert( next->start < next->end );
1299 assert( cur->end < next->start );
1300 next++;
1301 break; /* done with this lock */
1306 /* clear Unix locks for all the holes */
1308 for (cur = first; cur; cur = cur->next)
1309 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1311 done:
1312 free( buffer );
1315 /* create a new lock on a fd */
1316 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1318 struct file_lock *lock;
1320 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1321 lock->shared = shared;
1322 lock->start = start;
1323 lock->end = end;
1324 lock->fd = fd;
1325 lock->process = current->process;
1327 /* now try to set a Unix lock */
1328 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1330 release_object( lock );
1331 return NULL;
1333 list_add_tail( &fd->locks, &lock->fd_entry );
1334 list_add_tail( &fd->inode->locks, &lock->inode_entry );
1335 list_add_tail( &lock->process->locks, &lock->proc_entry );
1336 return lock;
1339 /* remove an existing lock */
1340 static void remove_lock( struct file_lock *lock, int remove_unix )
1342 struct inode *inode = lock->fd->inode;
1344 list_remove( &lock->fd_entry );
1345 list_remove( &lock->inode_entry );
1346 list_remove( &lock->proc_entry );
1347 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1348 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1349 lock->process = NULL;
1350 wake_up( &lock->obj, 0 );
1351 release_object( lock );
1354 /* remove all locks owned by a given process */
1355 void remove_process_locks( struct process *process )
1357 struct list *ptr;
1359 while ((ptr = list_head( &process->locks )))
1361 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1362 remove_lock( lock, 1 ); /* this removes it from the list */
1366 /* remove all locks on a given fd */
1367 static void remove_fd_locks( struct fd *fd )
1369 file_pos_t start = FILE_POS_T_MAX, end = 0;
1370 struct list *ptr;
1372 while ((ptr = list_head( &fd->locks )))
1374 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1375 if (lock->start < start) start = lock->start;
1376 if (!lock->end || lock->end > end) end = lock->end - 1;
1377 remove_lock( lock, 0 );
1379 if (start < end) remove_unix_locks( fd, start, end + 1 );
1382 /* add a lock on an fd */
1383 /* returns handle to wait on */
1384 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1386 struct list *ptr;
1387 file_pos_t end = start + count;
1389 if (!fd->inode) /* not a regular file */
1391 set_error( STATUS_INVALID_DEVICE_REQUEST );
1392 return 0;
1395 /* don't allow wrapping locks */
1396 if (end && end < start)
1398 set_error( STATUS_INVALID_PARAMETER );
1399 return 0;
1402 /* check if another lock on that file overlaps the area */
1403 LIST_FOR_EACH( ptr, &fd->inode->locks )
1405 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1406 if (!lock_overlaps( lock, start, end )) continue;
1407 if (shared && (lock->shared || lock->fd == fd)) continue;
1408 /* found one */
1409 if (!wait)
1411 set_error( STATUS_FILE_LOCK_CONFLICT );
1412 return 0;
1414 set_error( STATUS_PENDING );
1415 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1418 /* not found, add it */
1419 if (add_lock( fd, shared, start, end )) return 0;
1420 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1422 /* Unix lock conflict -> tell client to wait and retry */
1423 if (wait) set_error( STATUS_PENDING );
1425 return 0;
1428 /* remove a lock on an fd */
1429 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1431 struct list *ptr;
1432 file_pos_t end = start + count;
1434 /* find an existing lock with the exact same parameters */
1435 LIST_FOR_EACH( ptr, &fd->locks )
1437 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1438 if ((lock->start == start) && (lock->end == end))
1440 remove_lock( lock, 1 );
1441 return;
1444 set_error( STATUS_FILE_LOCK_CONFLICT );
1448 /****************************************************************/
1449 /* file descriptor functions */
1451 static void fd_dump( struct object *obj, int verbose )
1453 struct fd *fd = (struct fd *)obj;
1454 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1455 if (fd->inode) fprintf( stderr, " inode=%p unlink=%d", fd->inode, fd->closed->unlink );
1456 fprintf( stderr, "\n" );
1459 static void fd_destroy( struct object *obj )
1461 struct fd *fd = (struct fd *)obj;
1463 free_async_queue( fd->read_q );
1464 free_async_queue( fd->write_q );
1465 free_async_queue( fd->wait_q );
1467 if (fd->completion) release_object( fd->completion );
1468 remove_fd_locks( fd );
1469 list_remove( &fd->inode_entry );
1470 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1471 if (fd->inode)
1473 inode_add_closed_fd( fd->inode, fd->closed );
1474 release_object( fd->inode );
1476 else /* no inode, close it right away */
1478 if (fd->unix_fd != -1) close( fd->unix_fd );
1479 free( fd->unix_name );
1483 /* check if the desired access is possible without violating */
1484 /* the sharing mode of other opens of the same file */
1485 static unsigned int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing,
1486 unsigned int open_flags, unsigned int options )
1488 /* only a few access bits are meaningful wrt sharing */
1489 const unsigned int read_access = FILE_READ_DATA | FILE_EXECUTE;
1490 const unsigned int write_access = FILE_WRITE_DATA | FILE_APPEND_DATA;
1491 const unsigned int all_access = read_access | write_access | DELETE;
1493 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1494 unsigned int existing_access = 0;
1495 struct list *ptr;
1497 fd->access = access;
1498 fd->sharing = sharing;
1500 LIST_FOR_EACH( ptr, &fd->inode->open )
1502 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1503 if (fd_ptr != fd)
1505 /* if access mode is 0, sharing mode is ignored */
1506 if (fd_ptr->access & all_access) existing_sharing &= fd_ptr->sharing;
1507 existing_access |= fd_ptr->access;
1511 if (((access & read_access) && !(existing_sharing & FILE_SHARE_READ)) ||
1512 ((access & write_access) && !(existing_sharing & FILE_SHARE_WRITE)) ||
1513 ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)))
1514 return STATUS_SHARING_VIOLATION;
1515 if (((existing_access & FILE_MAPPING_WRITE) && !(sharing & FILE_SHARE_WRITE)) ||
1516 ((existing_access & FILE_MAPPING_IMAGE) && (access & FILE_WRITE_DATA)))
1517 return STATUS_SHARING_VIOLATION;
1518 if ((existing_access & FILE_MAPPING_IMAGE) && (options & FILE_DELETE_ON_CLOSE))
1519 return STATUS_CANNOT_DELETE;
1520 if ((existing_access & FILE_MAPPING_ACCESS) && (open_flags & O_TRUNC))
1521 return STATUS_USER_MAPPED_FILE;
1522 if (!(access & all_access))
1523 return 0; /* if access mode is 0, sharing mode is ignored (except for mappings) */
1524 if (((existing_access & read_access) && !(sharing & FILE_SHARE_READ)) ||
1525 ((existing_access & write_access) && !(sharing & FILE_SHARE_WRITE)) ||
1526 ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)))
1527 return STATUS_SHARING_VIOLATION;
1528 return 0;
1531 /* set the events that select waits for on this fd */
1532 void set_fd_events( struct fd *fd, int events )
1534 int user = fd->poll_index;
1535 assert( poll_users[user] == fd );
1537 set_fd_epoll_events( fd, user, events );
1539 if (events == -1) /* stop waiting on this fd completely */
1541 pollfd[user].fd = -1;
1542 pollfd[user].events = POLLERR;
1543 pollfd[user].revents = 0;
1545 else if (pollfd[user].fd != -1 || !pollfd[user].events)
1547 pollfd[user].fd = fd->unix_fd;
1548 pollfd[user].events = events;
1552 /* prepare an fd for unmounting its corresponding device */
1553 static inline void unmount_fd( struct fd *fd )
1555 assert( fd->inode );
1557 async_wake_up( fd->read_q, STATUS_VOLUME_DISMOUNTED );
1558 async_wake_up( fd->write_q, STATUS_VOLUME_DISMOUNTED );
1560 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1562 if (fd->unix_fd != -1) close( fd->unix_fd );
1564 fd->unix_fd = -1;
1565 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1566 fd->closed->unix_fd = -1;
1567 fd->closed->unlink = 0;
1569 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1570 fd->fs_locks = 0;
1573 /* allocate an fd object, without setting the unix fd yet */
1574 static struct fd *alloc_fd_object(void)
1576 struct fd *fd = alloc_object( &fd_ops );
1578 if (!fd) return NULL;
1580 fd->fd_ops = NULL;
1581 fd->user = NULL;
1582 fd->inode = NULL;
1583 fd->closed = NULL;
1584 fd->access = 0;
1585 fd->options = 0;
1586 fd->sharing = 0;
1587 fd->unix_fd = -1;
1588 fd->unix_name = NULL;
1589 fd->cacheable = 0;
1590 fd->signaled = 1;
1591 fd->fs_locks = 1;
1592 fd->poll_index = -1;
1593 fd->read_q = NULL;
1594 fd->write_q = NULL;
1595 fd->wait_q = NULL;
1596 fd->completion = NULL;
1597 list_init( &fd->inode_entry );
1598 list_init( &fd->locks );
1600 if ((fd->poll_index = add_poll_user( fd )) == -1)
1602 release_object( fd );
1603 return NULL;
1605 return fd;
1608 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1609 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1611 struct fd *fd = alloc_object( &fd_ops );
1613 if (!fd) return NULL;
1615 fd->fd_ops = fd_user_ops;
1616 fd->user = user;
1617 fd->inode = NULL;
1618 fd->closed = NULL;
1619 fd->access = 0;
1620 fd->options = options;
1621 fd->sharing = 0;
1622 fd->unix_name = NULL;
1623 fd->unix_fd = -1;
1624 fd->cacheable = 0;
1625 fd->signaled = 0;
1626 fd->fs_locks = 0;
1627 fd->poll_index = -1;
1628 fd->read_q = NULL;
1629 fd->write_q = NULL;
1630 fd->wait_q = NULL;
1631 fd->completion = NULL;
1632 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1633 list_init( &fd->inode_entry );
1634 list_init( &fd->locks );
1635 return fd;
1638 /* duplicate an fd object for a different user */
1639 struct fd *dup_fd_object( struct fd *orig, unsigned int access, unsigned int sharing, unsigned int options )
1641 unsigned int err;
1642 struct fd *fd = alloc_fd_object();
1644 if (!fd) return NULL;
1646 fd->options = options;
1647 fd->cacheable = orig->cacheable;
1649 if (orig->unix_name)
1651 if (!(fd->unix_name = mem_alloc( strlen(orig->unix_name) + 1 ))) goto failed;
1652 strcpy( fd->unix_name, orig->unix_name );
1655 if (orig->inode)
1657 struct closed_fd *closed = mem_alloc( sizeof(*closed) );
1658 if (!closed) goto failed;
1659 if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1661 file_set_error();
1662 free( closed );
1663 goto failed;
1665 closed->unix_fd = fd->unix_fd;
1666 closed->unlink = 0;
1667 closed->unix_name = fd->unix_name;
1668 fd->closed = closed;
1669 fd->inode = (struct inode *)grab_object( orig->inode );
1670 list_add_head( &fd->inode->open, &fd->inode_entry );
1671 if ((err = check_sharing( fd, access, sharing, 0, options )))
1673 set_error( err );
1674 goto failed;
1677 else if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1679 file_set_error();
1680 goto failed;
1682 return fd;
1684 failed:
1685 release_object( fd );
1686 return NULL;
1689 /* find an existing fd object that can be reused for a mapping */
1690 struct fd *get_fd_object_for_mapping( struct fd *fd, unsigned int access, unsigned int sharing )
1692 struct fd *fd_ptr;
1694 if (!fd->inode) return NULL;
1696 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
1697 if (fd_ptr->access == access && fd_ptr->sharing == sharing)
1698 return (struct fd *)grab_object( fd_ptr );
1700 return NULL;
1703 /* set the status to return when the fd has no associated unix fd */
1704 void set_no_fd_status( struct fd *fd, unsigned int status )
1706 fd->no_fd_status = status;
1709 /* sets the user of an fd that previously had no user */
1710 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1712 assert( fd->fd_ops == NULL );
1713 fd->fd_ops = user_ops;
1714 fd->user = user;
1717 char *dup_fd_name( struct fd *root, const char *name )
1719 char *ret;
1721 if (!root) return strdup( name );
1722 if (!root->unix_name) return NULL;
1724 /* skip . prefix */
1725 if (name[0] == '.' && (!name[1] || name[1] == '/')) name++;
1727 if ((ret = malloc( strlen(root->unix_name) + strlen(name) + 2 )))
1729 strcpy( ret, root->unix_name );
1730 if (name[0] && name[0] != '/') strcat( ret, "/" );
1731 strcat( ret, name );
1733 return ret;
1736 /* open() wrapper that returns a struct fd with no fd user set */
1737 struct fd *open_fd( struct fd *root, const char *name, int flags, mode_t *mode, unsigned int access,
1738 unsigned int sharing, unsigned int options )
1740 struct stat st;
1741 struct closed_fd *closed_fd;
1742 struct fd *fd;
1743 int root_fd = -1;
1744 int rw_mode;
1746 if (((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE)) ||
1747 ((options & FILE_DIRECTORY_FILE) && (flags & O_TRUNC)))
1749 set_error( STATUS_INVALID_PARAMETER );
1750 return NULL;
1753 if (!(fd = alloc_fd_object())) return NULL;
1755 fd->options = options;
1756 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
1758 release_object( fd );
1759 return NULL;
1762 if (root)
1764 if ((root_fd = get_unix_fd( root )) == -1) goto error;
1765 if (fchdir( root_fd ) == -1)
1767 file_set_error();
1768 root_fd = -1;
1769 goto error;
1773 /* create the directory if needed */
1774 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1776 if (mkdir( name, *mode ) == -1)
1778 if (errno != EEXIST || (flags & O_EXCL))
1780 file_set_error();
1781 goto error;
1784 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1787 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1789 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1790 else rw_mode = O_WRONLY;
1792 else rw_mode = O_RDONLY;
1794 fd->unix_name = dup_fd_name( root, name );
1796 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1798 /* if we tried to open a directory for write access, retry read-only */
1799 if (errno == EISDIR)
1801 if ((access & FILE_UNIX_WRITE_ACCESS) || (flags & O_CREAT))
1802 fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode );
1805 if (fd->unix_fd == -1)
1807 file_set_error();
1808 goto error;
1812 closed_fd->unix_fd = fd->unix_fd;
1813 closed_fd->unlink = 0;
1814 closed_fd->unix_name = fd->unix_name;
1815 fstat( fd->unix_fd, &st );
1816 *mode = st.st_mode;
1818 /* only bother with an inode for normal files and directories */
1819 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1821 unsigned int err;
1822 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1824 if (!inode)
1826 /* we can close the fd because there are no others open on the same file,
1827 * otherwise we wouldn't have failed to allocate a new inode
1829 goto error;
1831 fd->inode = inode;
1832 fd->closed = closed_fd;
1833 fd->cacheable = !inode->device->removable;
1834 list_add_head( &inode->open, &fd->inode_entry );
1835 closed_fd = NULL;
1837 /* check directory options */
1838 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1840 set_error( STATUS_NOT_A_DIRECTORY );
1841 goto error;
1843 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1845 set_error( STATUS_FILE_IS_A_DIRECTORY );
1846 goto error;
1848 if ((err = check_sharing( fd, access, sharing, flags, options )))
1850 set_error( err );
1851 goto error;
1854 /* can't unlink files if we don't have permission to access */
1855 if ((options & FILE_DELETE_ON_CLOSE) && !(flags & O_CREAT) &&
1856 !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1858 set_error( STATUS_CANNOT_DELETE );
1859 goto error;
1862 fd->closed->unlink = (options & FILE_DELETE_ON_CLOSE) != 0;
1863 if (flags & O_TRUNC)
1865 if (S_ISDIR(st.st_mode))
1867 set_error( STATUS_OBJECT_NAME_COLLISION );
1868 goto error;
1870 ftruncate( fd->unix_fd, 0 );
1873 else /* special file */
1875 if (options & FILE_DELETE_ON_CLOSE) /* we can't unlink special files */
1877 set_error( STATUS_INVALID_PARAMETER );
1878 goto error;
1880 free( closed_fd );
1881 fd->cacheable = 1;
1883 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1884 return fd;
1886 error:
1887 release_object( fd );
1888 free( closed_fd );
1889 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1890 return NULL;
1893 /* create an fd for an anonymous file */
1894 /* if the function fails the unix fd is closed */
1895 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
1896 unsigned int options )
1898 struct fd *fd = alloc_fd_object();
1900 if (fd)
1902 set_fd_user( fd, fd_user_ops, user );
1903 fd->unix_fd = unix_fd;
1904 fd->options = options;
1905 return fd;
1907 close( unix_fd );
1908 return NULL;
1911 /* retrieve the object that is using an fd */
1912 void *get_fd_user( struct fd *fd )
1914 return fd->user;
1917 /* retrieve the opening options for the fd */
1918 unsigned int get_fd_options( struct fd *fd )
1920 return fd->options;
1923 /* retrieve the unix fd for an object */
1924 int get_unix_fd( struct fd *fd )
1926 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
1927 return fd->unix_fd;
1930 /* check if two file descriptors point to the same file */
1931 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1933 return fd1->inode == fd2->inode;
1936 /* allow the fd to be cached (can't be reset once set) */
1937 void allow_fd_caching( struct fd *fd )
1939 fd->cacheable = 1;
1942 /* check if fd is on a removable device */
1943 int is_fd_removable( struct fd *fd )
1945 return (fd->inode && fd->inode->device->removable);
1948 /* set or clear the fd signaled state */
1949 void set_fd_signaled( struct fd *fd, int signaled )
1951 fd->signaled = signaled;
1952 if (signaled) wake_up( fd->user, 0 );
1955 /* set or clear the fd signaled state */
1956 int is_fd_signaled( struct fd *fd )
1958 return fd->signaled;
1961 /* handler for close_handle that refuses to close fd-associated handles in other processes */
1962 int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
1964 return (!current || current->process == process);
1967 /* check if events are pending and if yes return which one(s) */
1968 int check_fd_events( struct fd *fd, int events )
1970 struct pollfd pfd;
1972 if (fd->unix_fd == -1) return POLLERR;
1973 if (fd->inode) return events; /* regular files are always signaled */
1975 pfd.fd = fd->unix_fd;
1976 pfd.events = events;
1977 if (poll( &pfd, 1, 0 ) <= 0) return 0;
1978 return pfd.revents;
1981 /* default signaled() routine for objects that poll() on an fd */
1982 int default_fd_signaled( struct object *obj, struct wait_queue_entry *entry )
1984 struct fd *fd = get_obj_fd( obj );
1985 int ret = fd->signaled;
1986 release_object( fd );
1987 return ret;
1990 /* default map_access() routine for objects that behave like an fd */
1991 unsigned int default_fd_map_access( struct object *obj, unsigned int access )
1993 if (access & GENERIC_READ) access |= FILE_GENERIC_READ;
1994 if (access & GENERIC_WRITE) access |= FILE_GENERIC_WRITE;
1995 if (access & GENERIC_EXECUTE) access |= FILE_GENERIC_EXECUTE;
1996 if (access & GENERIC_ALL) access |= FILE_ALL_ACCESS;
1997 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
2000 int default_fd_get_poll_events( struct fd *fd )
2002 int events = 0;
2004 if (async_waiting( fd->read_q )) events |= POLLIN;
2005 if (async_waiting( fd->write_q )) events |= POLLOUT;
2006 return events;
2009 /* default handler for poll() events */
2010 void default_poll_event( struct fd *fd, int event )
2012 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( fd->read_q, STATUS_ALERTED );
2013 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( fd->write_q, STATUS_ALERTED );
2015 /* if an error occurred, stop polling this fd to avoid busy-looping */
2016 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
2017 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2020 struct async *fd_queue_async( struct fd *fd, const async_data_t *data, int type )
2022 struct async_queue *queue;
2023 struct async *async;
2025 switch (type)
2027 case ASYNC_TYPE_READ:
2028 if (!fd->read_q && !(fd->read_q = create_async_queue( fd ))) return NULL;
2029 queue = fd->read_q;
2030 break;
2031 case ASYNC_TYPE_WRITE:
2032 if (!fd->write_q && !(fd->write_q = create_async_queue( fd ))) return NULL;
2033 queue = fd->write_q;
2034 break;
2035 case ASYNC_TYPE_WAIT:
2036 if (!fd->wait_q && !(fd->wait_q = create_async_queue( fd ))) return NULL;
2037 queue = fd->wait_q;
2038 break;
2039 default:
2040 queue = NULL;
2041 assert(0);
2044 if ((async = create_async( current, queue, data )) && type != ASYNC_TYPE_WAIT)
2046 if (!fd->inode)
2047 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2048 else /* regular files are always ready for read and write */
2049 async_wake_up( queue, STATUS_ALERTED );
2051 return async;
2054 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
2056 switch (type)
2058 case ASYNC_TYPE_READ:
2059 async_wake_up( fd->read_q, status );
2060 break;
2061 case ASYNC_TYPE_WRITE:
2062 async_wake_up( fd->write_q, status );
2063 break;
2064 case ASYNC_TYPE_WAIT:
2065 async_wake_up( fd->wait_q, status );
2066 break;
2067 default:
2068 assert(0);
2072 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
2074 fd->fd_ops->reselect_async( fd, queue );
2077 void no_fd_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
2079 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2082 void default_fd_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
2084 struct async *async;
2086 if ((async = fd_queue_async( fd, data, type )))
2088 release_object( async );
2089 set_error( STATUS_PENDING );
2093 /* default reselect_async() fd routine */
2094 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
2096 if (queue != fd->wait_q)
2098 int poll_events = fd->fd_ops->get_poll_events( fd );
2099 int events = check_fd_events( fd, poll_events );
2100 if (events) fd->fd_ops->poll_event( fd, events );
2101 else set_fd_events( fd, poll_events );
2105 /* default cancel_async() fd routine */
2106 int default_fd_cancel_async( struct fd *fd, struct process *process, struct thread *thread, client_ptr_t iosb )
2108 int n = 0;
2110 n += async_wake_up_by( fd->read_q, process, thread, iosb, STATUS_CANCELLED );
2111 n += async_wake_up_by( fd->write_q, process, thread, iosb, STATUS_CANCELLED );
2112 n += async_wake_up_by( fd->wait_q, process, thread, iosb, STATUS_CANCELLED );
2113 return n;
2116 static inline int is_valid_mounted_device( struct stat *st )
2118 #if defined(linux) || defined(__sun__)
2119 return S_ISBLK( st->st_mode );
2120 #else
2121 /* disks are char devices on *BSD */
2122 return S_ISCHR( st->st_mode );
2123 #endif
2126 /* close all Unix file descriptors on a device to allow unmounting it */
2127 static void unmount_device( struct fd *device_fd )
2129 unsigned int i;
2130 struct stat st;
2131 struct device *device;
2132 struct inode *inode;
2133 struct fd *fd;
2134 int unix_fd = get_unix_fd( device_fd );
2136 if (unix_fd == -1) return;
2138 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2140 set_error( STATUS_INVALID_PARAMETER );
2141 return;
2144 if (!(device = get_device( st.st_rdev, -1 ))) return;
2146 for (i = 0; i < INODE_HASH_SIZE; i++)
2148 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
2150 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
2152 unmount_fd( fd );
2154 inode_close_pending( inode, 0 );
2157 /* remove it from the hash table */
2158 list_remove( &device->entry );
2159 list_init( &device->entry );
2160 release_object( device );
2163 /* default read() routine */
2164 obj_handle_t no_fd_read( struct fd *fd, const async_data_t *async, int blocking, file_pos_t pos )
2166 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2167 return 0;
2170 /* default write() routine */
2171 obj_handle_t no_fd_write( struct fd *fd, const async_data_t *async, int blocking,
2172 file_pos_t pos, data_size_t *written )
2174 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2175 return 0;
2178 /* default flush() routine */
2179 obj_handle_t no_fd_flush( struct fd *fd, const async_data_t *async, int blocking )
2181 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2182 return 0;
2185 /* default ioctl() routine */
2186 obj_handle_t no_fd_ioctl( struct fd *fd, ioctl_code_t code, const async_data_t *async, int blocking )
2188 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2189 return 0;
2192 /* default ioctl() routine */
2193 obj_handle_t default_fd_ioctl( struct fd *fd, ioctl_code_t code, const async_data_t *async, int blocking )
2195 switch(code)
2197 case FSCTL_DISMOUNT_VOLUME:
2198 unmount_device( fd );
2199 return 0;
2200 default:
2201 set_error( STATUS_NOT_SUPPORTED );
2202 return 0;
2206 /* same as get_handle_obj but retrieve the struct fd associated to the object */
2207 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
2208 unsigned int access )
2210 struct fd *fd = NULL;
2211 struct object *obj;
2213 if ((obj = get_handle_obj( process, handle, access, NULL )))
2215 fd = get_obj_fd( obj );
2216 release_object( obj );
2218 return fd;
2221 /* set disposition for the fd */
2222 static void set_fd_disposition( struct fd *fd, int unlink )
2224 struct stat st;
2226 if (!fd->inode)
2228 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2229 return;
2232 if (fd->unix_fd == -1)
2234 set_error( fd->no_fd_status );
2235 return;
2238 if (fstat( fd->unix_fd, &st ) == -1)
2240 file_set_error();
2241 return;
2244 /* can't unlink special files */
2245 if (unlink && !S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
2247 set_error( STATUS_INVALID_PARAMETER );
2248 return;
2251 /* can't unlink files we don't have permission to access */
2252 if (unlink && !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2254 set_error( STATUS_CANNOT_DELETE );
2255 return;
2258 fd->closed->unlink = unlink || (fd->options & FILE_DELETE_ON_CLOSE);
2261 /* set new name for the fd */
2262 static void set_fd_name( struct fd *fd, struct fd *root, const char *nameptr,
2263 data_size_t len, int create_link )
2265 struct inode *inode;
2266 struct stat st;
2267 char *name;
2269 if (!fd->inode || !fd->unix_name)
2271 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2272 return;
2274 if (!len || ((nameptr[0] == '/') ^ !root))
2276 set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
2277 return;
2279 if (!(name = mem_alloc( len + 1 ))) return;
2280 memcpy( name, nameptr, len );
2281 name[len] = 0;
2283 if (root)
2285 char *combined_name = dup_fd_name( root, name );
2286 if (!combined_name)
2288 set_error( STATUS_NO_MEMORY );
2289 goto failed;
2291 free( name );
2292 name = combined_name;
2295 /* when creating a hard link, source cannot be a dir */
2296 if (create_link && fd->unix_fd != -1 &&
2297 !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode ))
2299 set_error( STATUS_FILE_IS_A_DIRECTORY );
2300 goto failed;
2303 if (!stat( name, &st ))
2305 /* can't replace directories or special files */
2306 if (!S_ISREG( st.st_mode ))
2308 set_error( STATUS_ACCESS_DENIED );
2309 goto failed;
2312 /* can't replace an opened file */
2313 if ((inode = get_inode( st.st_dev, st.st_ino, -1 )))
2315 int is_empty = list_empty( &inode->open );
2316 release_object( inode );
2317 if (!is_empty)
2319 set_error( STATUS_ACCESS_DENIED );
2320 goto failed;
2324 /* link() expects that the target doesn't exist */
2325 /* rename() cannot replace files with directories */
2326 if (create_link || (fd->unix_fd != -1 &&
2327 !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode )))
2329 if (unlink( name ))
2331 file_set_error();
2332 goto failed;
2337 if (create_link)
2339 if (link( fd->unix_name, name ))
2340 file_set_error();
2341 free( name );
2342 return;
2345 if (rename( fd->unix_name, name ))
2347 file_set_error();
2348 goto failed;
2351 free( fd->unix_name );
2352 fd->unix_name = name;
2353 fd->closed->unix_name = name;
2354 return;
2356 failed:
2357 free( name );
2360 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
2362 *p_key = fd->comp_key;
2363 return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
2366 void fd_copy_completion( struct fd *src, struct fd *dst )
2368 assert( !dst->completion );
2369 dst->completion = fd_get_completion( src, &dst->comp_key );
2372 /* flush a file buffers */
2373 DECL_HANDLER(flush)
2375 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, 0 );
2377 if (fd)
2379 reply->event = fd->fd_ops->flush( fd, &req->async, req->blocking );
2380 release_object( fd );
2384 /* open a file object */
2385 DECL_HANDLER(open_file_object)
2387 struct unicode_str name;
2388 struct directory *root = NULL;
2389 struct object *obj, *result;
2391 get_req_unicode_str( &name );
2392 if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
2394 if (get_error() != STATUS_OBJECT_TYPE_MISMATCH) return;
2395 if (!(obj = (struct object *)get_file_obj( current->process, req->rootdir, 0 ))) return;
2396 if (name.len)
2398 release_object( obj );
2399 set_error( STATUS_OBJECT_PATH_NOT_FOUND );
2400 return;
2402 clear_error();
2404 else
2406 obj = open_object_dir( root, &name, req->attributes, NULL );
2407 if (root) release_object( root );
2408 if (!obj) return;
2411 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
2413 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
2414 release_object( result );
2416 release_object( obj );
2419 /* get the Unix name from a file handle */
2420 DECL_HANDLER(get_handle_unix_name)
2422 struct fd *fd;
2424 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2426 if (fd->unix_name)
2428 data_size_t name_len = strlen( fd->unix_name );
2429 reply->name_len = name_len;
2430 if (name_len <= get_reply_max_size()) set_reply_data( fd->unix_name, name_len );
2431 else set_error( STATUS_BUFFER_OVERFLOW );
2433 else set_error( STATUS_OBJECT_TYPE_MISMATCH );
2434 release_object( fd );
2438 /* get a Unix fd to access a file */
2439 DECL_HANDLER(get_handle_fd)
2441 struct fd *fd;
2443 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2445 int unix_fd = get_unix_fd( fd );
2446 if (unix_fd != -1)
2448 reply->type = fd->fd_ops->get_fd_type( fd );
2449 reply->cacheable = fd->cacheable;
2450 reply->options = fd->options;
2451 reply->access = get_handle_access( current->process, req->handle );
2452 send_client_fd( current->process, unix_fd, req->handle );
2454 release_object( fd );
2458 /* perform a read on a file object */
2459 DECL_HANDLER(read)
2461 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_READ_DATA );
2463 if (fd)
2465 reply->wait = fd->fd_ops->read( fd, &req->async, req->blocking, req->pos );
2466 reply->options = fd->options;
2467 release_object( fd );
2471 /* perform a write on a file object */
2472 DECL_HANDLER(write)
2474 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_WRITE_DATA );
2476 if (fd)
2478 reply->wait = fd->fd_ops->write( fd, &req->async, req->blocking, req->pos, &reply->size );
2479 reply->options = fd->options;
2480 release_object( fd );
2484 /* perform an ioctl on a file */
2485 DECL_HANDLER(ioctl)
2487 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2488 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2490 if (fd)
2492 reply->wait = fd->fd_ops->ioctl( fd, req->code, &req->async, req->blocking );
2493 reply->options = fd->options;
2494 release_object( fd );
2498 /* create / reschedule an async I/O */
2499 DECL_HANDLER(register_async)
2501 unsigned int access;
2502 struct fd *fd;
2504 switch(req->type)
2506 case ASYNC_TYPE_READ:
2507 access = FILE_READ_DATA;
2508 break;
2509 case ASYNC_TYPE_WRITE:
2510 access = FILE_WRITE_DATA;
2511 break;
2512 default:
2513 set_error( STATUS_INVALID_PARAMETER );
2514 return;
2517 if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2519 if (get_unix_fd( fd ) != -1) fd->fd_ops->queue_async( fd, &req->async, req->type, req->count );
2520 release_object( fd );
2524 /* cancels all async I/O */
2525 DECL_HANDLER(cancel_async)
2527 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2528 struct thread *thread = req->only_thread ? current : NULL;
2530 if (fd)
2532 int count = fd->fd_ops->cancel_async( fd, current->process, thread, req->iosb );
2533 if (!count && req->iosb) set_error( STATUS_NOT_FOUND );
2534 release_object( fd );
2538 /* attach completion object to a fd */
2539 DECL_HANDLER(set_completion_info)
2541 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2543 if (fd)
2545 if (!(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) && !fd->completion)
2547 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2548 fd->comp_key = req->ckey;
2550 else set_error( STATUS_INVALID_PARAMETER );
2551 release_object( fd );
2555 /* push new completion msg into a completion queue attached to the fd */
2556 DECL_HANDLER(add_fd_completion)
2558 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2559 if (fd)
2561 if (fd->completion)
2562 add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2563 release_object( fd );
2567 /* set fd disposition information */
2568 DECL_HANDLER(set_fd_disp_info)
2570 struct fd *fd = get_handle_fd_obj( current->process, req->handle, DELETE );
2571 if (fd)
2573 set_fd_disposition( fd, req->unlink );
2574 release_object( fd );
2578 /* set fd name information */
2579 DECL_HANDLER(set_fd_name_info)
2581 struct fd *fd, *root_fd = NULL;
2583 if (req->rootdir)
2585 struct dir *root;
2587 if (!(root = get_dir_obj( current->process, req->rootdir, 0 ))) return;
2588 root_fd = get_obj_fd( (struct object *)root );
2589 release_object( root );
2590 if (!root_fd) return;
2593 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2595 set_fd_name( fd, root_fd, get_req_data(), get_req_data_size(), req->link );
2596 release_object( fd );
2598 if (root_fd) release_object( root_fd );