include: Use the ARRAY_SIZE() macro in debug.h.
[wine.git] / server / fd.c
blob117fad82f3ca89b4e7a986fe435fb0ce4324ad93
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 #ifdef MAJOR_IN_MKDEV
87 #include <sys/mkdev.h>
88 #elif defined(MAJOR_IN_SYSMACROS)
89 #include <sys/sysmacros.h>
90 #endif
91 #include <sys/types.h>
92 #include <unistd.h>
93 #ifdef HAVE_SYS_SYSCALL_H
94 #include <sys/syscall.h>
95 #endif
97 #include "ntstatus.h"
98 #define WIN32_NO_STATUS
99 #include "object.h"
100 #include "file.h"
101 #include "handle.h"
102 #include "process.h"
103 #include "request.h"
105 #include "winternl.h"
106 #include "winioctl.h"
108 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
109 # include <sys/epoll.h>
110 # define USE_EPOLL
111 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
112 # define USE_EPOLL
113 # define EPOLLIN POLLIN
114 # define EPOLLOUT POLLOUT
115 # define EPOLLERR POLLERR
116 # define EPOLLHUP POLLHUP
117 # define EPOLL_CTL_ADD 1
118 # define EPOLL_CTL_DEL 2
119 # define EPOLL_CTL_MOD 3
121 typedef union epoll_data
123 void *ptr;
124 int fd;
125 uint32_t u32;
126 uint64_t u64;
127 } epoll_data_t;
129 struct epoll_event
131 uint32_t events;
132 epoll_data_t data;
135 static inline int epoll_create( int size )
137 return syscall( 254 /*NR_epoll_create*/, size );
140 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
142 return syscall( 255 /*NR_epoll_ctl*/, epfd, op, fd, event );
145 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
147 return syscall( 256 /*NR_epoll_wait*/, epfd, events, maxevents, timeout );
150 #endif /* linux && __i386__ && HAVE_STDINT_H */
152 #if defined(HAVE_PORT_H) && defined(HAVE_PORT_CREATE)
153 # include <port.h>
154 # define USE_EVENT_PORTS
155 #endif /* HAVE_PORT_H && HAVE_PORT_CREATE */
157 /* Because of the stupid Posix locking semantics, we need to keep
158 * track of all file descriptors referencing a given file, and not
159 * close a single one until all the locks are gone (sigh).
162 /* file descriptor object */
164 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
165 struct closed_fd
167 struct list entry; /* entry in inode closed list */
168 int unix_fd; /* the unix file descriptor */
169 int unlink; /* whether to unlink on close */
170 char *unix_name; /* name to unlink on close, points to parent fd unix_name */
173 struct fd
175 struct object obj; /* object header */
176 const struct fd_ops *fd_ops; /* file descriptor operations */
177 struct inode *inode; /* inode that this fd belongs to */
178 struct list inode_entry; /* entry in inode fd list */
179 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
180 struct object *user; /* object using this file descriptor */
181 struct list locks; /* list of locks on this fd */
182 unsigned int access; /* file access (FILE_READ_DATA etc.) */
183 unsigned int options; /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
184 unsigned int sharing; /* file sharing mode */
185 char *unix_name; /* unix file name */
186 int unix_fd; /* unix file descriptor */
187 unsigned int no_fd_status;/* status to return when unix_fd is -1 */
188 unsigned int cacheable :1;/* can the fd be cached on the client side? */
189 unsigned int signaled :1; /* is the fd signaled? */
190 unsigned int fs_locks :1; /* can we use filesystem locks for this fd? */
191 int poll_index; /* index of fd in poll array */
192 struct async_queue read_q; /* async readers of this fd */
193 struct async_queue write_q; /* async writers of this fd */
194 struct async_queue wait_q; /* other async waiters of this fd */
195 struct completion *completion; /* completion object attached to this fd */
196 apc_param_t comp_key; /* completion key to set in completion events */
197 unsigned int comp_flags; /* completion flags */
200 static void fd_dump( struct object *obj, int verbose );
201 static void fd_destroy( struct object *obj );
203 static const struct object_ops fd_ops =
205 sizeof(struct fd), /* size */
206 fd_dump, /* dump */
207 no_get_type, /* get_type */
208 no_add_queue, /* add_queue */
209 NULL, /* remove_queue */
210 NULL, /* signaled */
211 NULL, /* satisfied */
212 no_signal, /* signal */
213 no_get_fd, /* get_fd */
214 no_map_access, /* map_access */
215 default_get_sd, /* get_sd */
216 default_set_sd, /* set_sd */
217 no_lookup_name, /* lookup_name */
218 no_link_name, /* link_name */
219 NULL, /* unlink_name */
220 no_open_file, /* open_file */
221 no_close_handle, /* close_handle */
222 fd_destroy /* destroy */
225 /* device object */
227 #define DEVICE_HASH_SIZE 7
228 #define INODE_HASH_SIZE 17
230 struct device
232 struct object obj; /* object header */
233 struct list entry; /* entry in device hash list */
234 dev_t dev; /* device number */
235 int removable; /* removable device? (or -1 if unknown) */
236 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
239 static void device_dump( struct object *obj, int verbose );
240 static void device_destroy( struct object *obj );
242 static const struct object_ops device_ops =
244 sizeof(struct device), /* size */
245 device_dump, /* dump */
246 no_get_type, /* get_type */
247 no_add_queue, /* add_queue */
248 NULL, /* remove_queue */
249 NULL, /* signaled */
250 NULL, /* satisfied */
251 no_signal, /* signal */
252 no_get_fd, /* get_fd */
253 no_map_access, /* map_access */
254 default_get_sd, /* get_sd */
255 default_set_sd, /* set_sd */
256 no_lookup_name, /* lookup_name */
257 no_link_name, /* link_name */
258 NULL, /* unlink_name */
259 no_open_file, /* open_file */
260 no_close_handle, /* close_handle */
261 device_destroy /* destroy */
264 /* inode object */
266 struct inode
268 struct object obj; /* object header */
269 struct list entry; /* inode hash list entry */
270 struct device *device; /* device containing this inode */
271 ino_t ino; /* inode number */
272 struct list open; /* list of open file descriptors */
273 struct list locks; /* list of file locks */
274 struct list closed; /* list of file descriptors to close at destroy time */
277 static void inode_dump( struct object *obj, int verbose );
278 static void inode_destroy( struct object *obj );
280 static const struct object_ops inode_ops =
282 sizeof(struct inode), /* size */
283 inode_dump, /* dump */
284 no_get_type, /* get_type */
285 no_add_queue, /* add_queue */
286 NULL, /* remove_queue */
287 NULL, /* signaled */
288 NULL, /* satisfied */
289 no_signal, /* signal */
290 no_get_fd, /* get_fd */
291 no_map_access, /* map_access */
292 default_get_sd, /* get_sd */
293 default_set_sd, /* set_sd */
294 no_lookup_name, /* lookup_name */
295 no_link_name, /* link_name */
296 NULL, /* unlink_name */
297 no_open_file, /* open_file */
298 no_close_handle, /* close_handle */
299 inode_destroy /* destroy */
302 /* file lock object */
304 struct file_lock
306 struct object obj; /* object header */
307 struct fd *fd; /* fd owning this lock */
308 struct list fd_entry; /* entry in list of locks on a given fd */
309 struct list inode_entry; /* entry in inode list of locks */
310 int shared; /* shared lock? */
311 file_pos_t start; /* locked region is interval [start;end) */
312 file_pos_t end;
313 struct process *process; /* process owning this lock */
314 struct list proc_entry; /* entry in list of locks owned by the process */
317 static void file_lock_dump( struct object *obj, int verbose );
318 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry );
320 static const struct object_ops file_lock_ops =
322 sizeof(struct file_lock), /* size */
323 file_lock_dump, /* dump */
324 no_get_type, /* get_type */
325 add_queue, /* add_queue */
326 remove_queue, /* remove_queue */
327 file_lock_signaled, /* signaled */
328 no_satisfied, /* satisfied */
329 no_signal, /* signal */
330 no_get_fd, /* get_fd */
331 no_map_access, /* map_access */
332 default_get_sd, /* get_sd */
333 default_set_sd, /* set_sd */
334 no_lookup_name, /* lookup_name */
335 no_link_name, /* link_name */
336 NULL, /* unlink_name */
337 no_open_file, /* open_file */
338 no_close_handle, /* close_handle */
339 no_destroy /* destroy */
343 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
344 #define FILE_POS_T_MAX (~(file_pos_t)0)
346 static file_pos_t max_unix_offset = OFF_T_MAX;
348 #define DUMP_LONG_LONG(val) do { \
349 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
350 fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
351 else \
352 fprintf( stderr, "%lx", (unsigned long)(val) ); \
353 } while (0)
357 /****************************************************************/
358 /* timeouts support */
360 struct timeout_user
362 struct list entry; /* entry in sorted timeout list */
363 timeout_t when; /* timeout expiry (absolute time) */
364 timeout_callback callback; /* callback function */
365 void *private; /* callback private data */
368 static struct list timeout_list = LIST_INIT(timeout_list); /* sorted timeouts list */
369 timeout_t current_time;
371 static inline void set_current_time(void)
373 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
374 struct timeval now;
375 gettimeofday( &now, NULL );
376 current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
379 /* add a timeout user */
380 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
382 struct timeout_user *user;
383 struct list *ptr;
385 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
386 user->when = (when > 0) ? when : current_time - when;
387 user->callback = func;
388 user->private = private;
390 /* Now insert it in the linked list */
392 LIST_FOR_EACH( ptr, &timeout_list )
394 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
395 if (timeout->when >= user->when) break;
397 list_add_before( ptr, &user->entry );
398 return user;
401 /* remove a timeout user */
402 void remove_timeout_user( struct timeout_user *user )
404 list_remove( &user->entry );
405 free( user );
408 /* return a text description of a timeout for debugging purposes */
409 const char *get_timeout_str( timeout_t timeout )
411 static char buffer[64];
412 long secs, nsecs;
414 if (!timeout) return "0";
415 if (timeout == TIMEOUT_INFINITE) return "infinite";
417 if (timeout < 0) /* relative */
419 secs = -timeout / TICKS_PER_SEC;
420 nsecs = -timeout % TICKS_PER_SEC;
421 sprintf( buffer, "+%ld.%07ld", secs, nsecs );
423 else /* absolute */
425 secs = (timeout - current_time) / TICKS_PER_SEC;
426 nsecs = (timeout - current_time) % TICKS_PER_SEC;
427 if (nsecs < 0)
429 nsecs += TICKS_PER_SEC;
430 secs--;
432 if (secs >= 0)
433 sprintf( buffer, "%x%08x (+%ld.%07ld)",
434 (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
435 else
436 sprintf( buffer, "%x%08x (-%ld.%07ld)",
437 (unsigned int)(timeout >> 32), (unsigned int)timeout,
438 -(secs + 1), TICKS_PER_SEC - nsecs );
440 return buffer;
444 /****************************************************************/
445 /* poll support */
447 static struct fd **poll_users; /* users array */
448 static struct pollfd *pollfd; /* poll fd array */
449 static int nb_users; /* count of array entries actually in use */
450 static int active_users; /* current number of active users */
451 static int allocated_users; /* count of allocated entries in the array */
452 static struct fd **freelist; /* list of free entries in the array */
454 static int get_next_timeout(void);
456 static inline void fd_poll_event( struct fd *fd, int event )
458 fd->fd_ops->poll_event( fd, event );
461 #ifdef USE_EPOLL
463 static int epoll_fd = -1;
465 static inline void init_epoll(void)
467 epoll_fd = epoll_create( 128 );
470 /* set the events that epoll waits for on this fd; helper for set_fd_events */
471 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
473 struct epoll_event ev;
474 int ctl;
476 if (epoll_fd == -1) return;
478 if (events == -1) /* stop waiting on this fd completely */
480 if (pollfd[user].fd == -1) return; /* already removed */
481 ctl = EPOLL_CTL_DEL;
483 else if (pollfd[user].fd == -1)
485 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
486 ctl = EPOLL_CTL_ADD;
488 else
490 if (pollfd[user].events == events) return; /* nothing to do */
491 ctl = EPOLL_CTL_MOD;
494 ev.events = events;
495 memset(&ev.data, 0, sizeof(ev.data));
496 ev.data.u32 = user;
498 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
500 if (errno == ENOMEM) /* not enough memory, give up on epoll */
502 close( epoll_fd );
503 epoll_fd = -1;
505 else perror( "epoll_ctl" ); /* should not happen */
509 static inline void remove_epoll_user( struct fd *fd, int user )
511 if (epoll_fd == -1) return;
513 if (pollfd[user].fd != -1)
515 struct epoll_event dummy;
516 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
520 static inline void main_loop_epoll(void)
522 int i, ret, timeout;
523 struct epoll_event events[128];
525 assert( POLLIN == EPOLLIN );
526 assert( POLLOUT == EPOLLOUT );
527 assert( POLLERR == EPOLLERR );
528 assert( POLLHUP == EPOLLHUP );
530 if (epoll_fd == -1) return;
532 while (active_users)
534 timeout = get_next_timeout();
536 if (!active_users) break; /* last user removed by a timeout */
537 if (epoll_fd == -1) break; /* an error occurred with epoll */
539 ret = epoll_wait( epoll_fd, events, ARRAY_SIZE( events ), timeout );
540 set_current_time();
542 /* put the events into the pollfd array first, like poll does */
543 for (i = 0; i < ret; i++)
545 int user = events[i].data.u32;
546 pollfd[user].revents = events[i].events;
549 /* read events from the pollfd array, as set_fd_events may modify them */
550 for (i = 0; i < ret; i++)
552 int user = events[i].data.u32;
553 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
558 #elif defined(HAVE_KQUEUE)
560 static int kqueue_fd = -1;
562 static inline void init_epoll(void)
564 #ifdef __APPLE__ /* kqueue support is broken in Mac OS < 10.5 */
565 int mib[2];
566 char release[32];
567 size_t len = sizeof(release);
569 mib[0] = CTL_KERN;
570 mib[1] = KERN_OSRELEASE;
571 if (sysctl( mib, 2, release, &len, NULL, 0 ) == -1) return;
572 if (atoi(release) < 9) return;
573 #endif
574 kqueue_fd = kqueue();
577 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
579 struct kevent ev[2];
581 if (kqueue_fd == -1) return;
583 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)(long)user );
584 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)(long)user );
586 if (events == -1) /* stop waiting on this fd completely */
588 if (pollfd[user].fd == -1) return; /* already removed */
589 ev[0].flags |= EV_DELETE;
590 ev[1].flags |= EV_DELETE;
592 else if (pollfd[user].fd == -1)
594 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
595 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
596 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
598 else
600 if (pollfd[user].events == events) return; /* nothing to do */
601 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
602 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
605 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
607 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
609 close( kqueue_fd );
610 kqueue_fd = -1;
612 else perror( "kevent" ); /* should not happen */
616 static inline void remove_epoll_user( struct fd *fd, int user )
618 if (kqueue_fd == -1) return;
620 if (pollfd[user].fd != -1)
622 struct kevent ev[2];
624 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
625 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
626 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
630 static inline void main_loop_epoll(void)
632 int i, ret, timeout;
633 struct kevent events[128];
635 if (kqueue_fd == -1) return;
637 while (active_users)
639 timeout = get_next_timeout();
641 if (!active_users) break; /* last user removed by a timeout */
642 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
644 if (timeout != -1)
646 struct timespec ts;
648 ts.tv_sec = timeout / 1000;
649 ts.tv_nsec = (timeout % 1000) * 1000000;
650 ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), &ts );
652 else ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), NULL );
654 set_current_time();
656 /* put the events into the pollfd array first, like poll does */
657 for (i = 0; i < ret; i++)
659 long user = (long)events[i].udata;
660 pollfd[user].revents = 0;
662 for (i = 0; i < ret; i++)
664 long user = (long)events[i].udata;
665 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
666 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
667 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
668 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
671 /* read events from the pollfd array, as set_fd_events may modify them */
672 for (i = 0; i < ret; i++)
674 long user = (long)events[i].udata;
675 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
676 pollfd[user].revents = 0;
681 #elif defined(USE_EVENT_PORTS)
683 static int port_fd = -1;
685 static inline void init_epoll(void)
687 port_fd = port_create();
690 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
692 int ret;
694 if (port_fd == -1) return;
696 if (events == -1) /* stop waiting on this fd completely */
698 if (pollfd[user].fd == -1) return; /* already removed */
699 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
701 else if (pollfd[user].fd == -1)
703 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
704 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
706 else
708 if (pollfd[user].events == events) return; /* nothing to do */
709 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
712 if (ret == -1)
714 if (errno == ENOMEM) /* not enough memory, give up on port_associate */
716 close( port_fd );
717 port_fd = -1;
719 else perror( "port_associate" ); /* should not happen */
723 static inline void remove_epoll_user( struct fd *fd, int user )
725 if (port_fd == -1) return;
727 if (pollfd[user].fd != -1)
729 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
733 static inline void main_loop_epoll(void)
735 int i, nget, ret, timeout;
736 port_event_t events[128];
738 if (port_fd == -1) return;
740 while (active_users)
742 timeout = get_next_timeout();
743 nget = 1;
745 if (!active_users) break; /* last user removed by a timeout */
746 if (port_fd == -1) break; /* an error occurred with event completion */
748 if (timeout != -1)
750 struct timespec ts;
752 ts.tv_sec = timeout / 1000;
753 ts.tv_nsec = (timeout % 1000) * 1000000;
754 ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, &ts );
756 else ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, NULL );
758 if (ret == -1) break; /* an error occurred with event completion */
760 set_current_time();
762 /* put the events into the pollfd array first, like poll does */
763 for (i = 0; i < nget; i++)
765 long user = (long)events[i].portev_user;
766 pollfd[user].revents = events[i].portev_events;
769 /* read events from the pollfd array, as set_fd_events may modify them */
770 for (i = 0; i < nget; i++)
772 long user = (long)events[i].portev_user;
773 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
774 /* if we are still interested, reassociate the fd */
775 if (pollfd[user].fd != -1) {
776 port_associate( port_fd, PORT_SOURCE_FD, pollfd[user].fd, pollfd[user].events, (void *)user );
782 #else /* HAVE_KQUEUE */
784 static inline void init_epoll(void) { }
785 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
786 static inline void remove_epoll_user( struct fd *fd, int user ) { }
787 static inline void main_loop_epoll(void) { }
789 #endif /* USE_EPOLL */
792 /* add a user in the poll array and return its index, or -1 on failure */
793 static int add_poll_user( struct fd *fd )
795 int ret;
796 if (freelist)
798 ret = freelist - poll_users;
799 freelist = (struct fd **)poll_users[ret];
801 else
803 if (nb_users == allocated_users)
805 struct fd **newusers;
806 struct pollfd *newpoll;
807 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
808 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
809 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
811 if (allocated_users)
812 poll_users = newusers;
813 else
814 free( newusers );
815 return -1;
817 poll_users = newusers;
818 pollfd = newpoll;
819 if (!allocated_users) init_epoll();
820 allocated_users = new_count;
822 ret = nb_users++;
824 pollfd[ret].fd = -1;
825 pollfd[ret].events = 0;
826 pollfd[ret].revents = 0;
827 poll_users[ret] = fd;
828 active_users++;
829 return ret;
832 /* remove a user from the poll list */
833 static void remove_poll_user( struct fd *fd, int user )
835 assert( user >= 0 );
836 assert( poll_users[user] == fd );
838 remove_epoll_user( fd, user );
839 pollfd[user].fd = -1;
840 pollfd[user].events = 0;
841 pollfd[user].revents = 0;
842 poll_users[user] = (struct fd *)freelist;
843 freelist = &poll_users[user];
844 active_users--;
847 /* process pending timeouts and return the time until the next timeout, in milliseconds */
848 static int get_next_timeout(void)
850 if (!list_empty( &timeout_list ))
852 struct list expired_list, *ptr;
854 /* first remove all expired timers from the list */
856 list_init( &expired_list );
857 while ((ptr = list_head( &timeout_list )) != NULL)
859 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
861 if (timeout->when <= current_time)
863 list_remove( &timeout->entry );
864 list_add_tail( &expired_list, &timeout->entry );
866 else break;
869 /* now call the callback for all the removed timers */
871 while ((ptr = list_head( &expired_list )) != NULL)
873 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
874 list_remove( &timeout->entry );
875 timeout->callback( timeout->private );
876 free( timeout );
879 if ((ptr = list_head( &timeout_list )) != NULL)
881 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
882 int diff = (timeout->when - current_time + 9999) / 10000;
883 if (diff < 0) diff = 0;
884 return diff;
887 return -1; /* no pending timeouts */
890 /* server main poll() loop */
891 void main_loop(void)
893 int i, ret, timeout;
895 set_current_time();
896 server_start_time = current_time;
898 main_loop_epoll();
899 /* fall through to normal poll loop */
901 while (active_users)
903 timeout = get_next_timeout();
905 if (!active_users) break; /* last user removed by a timeout */
907 ret = poll( pollfd, nb_users, timeout );
908 set_current_time();
910 if (ret > 0)
912 for (i = 0; i < nb_users; i++)
914 if (pollfd[i].revents)
916 fd_poll_event( poll_users[i], pollfd[i].revents );
917 if (!--ret) break;
925 /****************************************************************/
926 /* device functions */
928 static struct list device_hash[DEVICE_HASH_SIZE];
930 static int is_device_removable( dev_t dev, int unix_fd )
932 #if defined(linux) && defined(HAVE_FSTATFS)
933 struct statfs stfs;
935 /* check for floppy disk */
936 if (major(dev) == FLOPPY_MAJOR) return 1;
938 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
939 return (stfs.f_type == 0x9660 || /* iso9660 */
940 stfs.f_type == 0x9fa1 || /* supermount */
941 stfs.f_type == 0x15013346); /* udf */
942 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
943 struct statfs stfs;
945 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
946 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
947 #elif defined(__NetBSD__)
948 struct statvfs stfs;
950 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
951 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
952 #elif defined(sun)
953 # include <sys/dkio.h>
954 # include <sys/vtoc.h>
955 struct dk_cinfo dkinf;
956 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
957 return (dkinf.dki_ctype == DKC_CDROM ||
958 dkinf.dki_ctype == DKC_NCRFLOPPY ||
959 dkinf.dki_ctype == DKC_SMSFLOPPY ||
960 dkinf.dki_ctype == DKC_INTEL82072 ||
961 dkinf.dki_ctype == DKC_INTEL82077);
962 #else
963 return 0;
964 #endif
967 /* retrieve the device object for a given fd, creating it if needed */
968 static struct device *get_device( dev_t dev, int unix_fd )
970 struct device *device;
971 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
973 if (device_hash[hash].next)
975 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
976 if (device->dev == dev) return (struct device *)grab_object( device );
978 else list_init( &device_hash[hash] );
980 /* not found, create it */
982 if (unix_fd == -1) return NULL;
983 if ((device = alloc_object( &device_ops )))
985 device->dev = dev;
986 device->removable = is_device_removable( dev, unix_fd );
987 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
988 list_add_head( &device_hash[hash], &device->entry );
990 return device;
993 static void device_dump( struct object *obj, int verbose )
995 struct device *device = (struct device *)obj;
996 fprintf( stderr, "Device dev=" );
997 DUMP_LONG_LONG( device->dev );
998 fprintf( stderr, "\n" );
1001 static void device_destroy( struct object *obj )
1003 struct device *device = (struct device *)obj;
1004 unsigned int i;
1006 for (i = 0; i < INODE_HASH_SIZE; i++)
1007 assert( list_empty(&device->inode_hash[i]) );
1009 list_remove( &device->entry ); /* remove it from the hash table */
1013 /****************************************************************/
1014 /* inode functions */
1016 /* close all pending file descriptors in the closed list */
1017 static void inode_close_pending( struct inode *inode, int keep_unlinks )
1019 struct list *ptr = list_head( &inode->closed );
1021 while (ptr)
1023 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1024 struct list *next = list_next( &inode->closed, ptr );
1026 if (fd->unix_fd != -1)
1028 close( fd->unix_fd );
1029 fd->unix_fd = -1;
1031 if (!keep_unlinks || !fd->unlink) /* get rid of it unless there's an unlink pending on that file */
1033 list_remove( ptr );
1034 free( fd->unix_name );
1035 free( fd );
1037 ptr = next;
1041 static void inode_dump( struct object *obj, int verbose )
1043 struct inode *inode = (struct inode *)obj;
1044 fprintf( stderr, "Inode device=%p ino=", inode->device );
1045 DUMP_LONG_LONG( inode->ino );
1046 fprintf( stderr, "\n" );
1049 static void inode_destroy( struct object *obj )
1051 struct inode *inode = (struct inode *)obj;
1052 struct list *ptr;
1054 assert( list_empty(&inode->open) );
1055 assert( list_empty(&inode->locks) );
1057 list_remove( &inode->entry );
1059 while ((ptr = list_head( &inode->closed )))
1061 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1062 list_remove( ptr );
1063 if (fd->unix_fd != -1) close( fd->unix_fd );
1064 if (fd->unlink)
1066 /* make sure it is still the same file */
1067 struct stat st;
1068 if (!stat( fd->unix_name, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
1070 if (S_ISDIR(st.st_mode)) rmdir( fd->unix_name );
1071 else unlink( fd->unix_name );
1074 free( fd->unix_name );
1075 free( fd );
1077 release_object( inode->device );
1080 /* retrieve the inode object for a given fd, creating it if needed */
1081 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
1083 struct device *device;
1084 struct inode *inode;
1085 unsigned int hash = ino % INODE_HASH_SIZE;
1087 if (!(device = get_device( dev, unix_fd ))) return NULL;
1089 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
1091 if (inode->ino == ino)
1093 release_object( device );
1094 return (struct inode *)grab_object( inode );
1098 /* not found, create it */
1099 if ((inode = alloc_object( &inode_ops )))
1101 inode->device = device;
1102 inode->ino = ino;
1103 list_init( &inode->open );
1104 list_init( &inode->locks );
1105 list_init( &inode->closed );
1106 list_add_head( &device->inode_hash[hash], &inode->entry );
1108 else release_object( device );
1110 return inode;
1113 /* add fd to the inode list of file descriptors to close */
1114 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1116 if (!list_empty( &inode->locks ))
1118 list_add_head( &inode->closed, &fd->entry );
1120 else if (fd->unlink) /* close the fd but keep the structure around for unlink */
1122 if (fd->unix_fd != -1) close( fd->unix_fd );
1123 fd->unix_fd = -1;
1124 list_add_head( &inode->closed, &fd->entry );
1126 else /* no locks on this inode and no unlink, get rid of the fd */
1128 if (fd->unix_fd != -1) close( fd->unix_fd );
1129 free( fd->unix_name );
1130 free( fd );
1135 /****************************************************************/
1136 /* file lock functions */
1138 static void file_lock_dump( struct object *obj, int verbose )
1140 struct file_lock *lock = (struct file_lock *)obj;
1141 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1142 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1143 DUMP_LONG_LONG( lock->start );
1144 fprintf( stderr, " end=" );
1145 DUMP_LONG_LONG( lock->end );
1146 fprintf( stderr, "\n" );
1149 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry )
1151 struct file_lock *lock = (struct file_lock *)obj;
1152 /* lock is signaled if it has lost its owner */
1153 return !lock->process;
1156 /* set (or remove) a Unix lock if possible for the given range */
1157 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1159 struct flock fl;
1161 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1162 for (;;)
1164 if (start == end) return 1; /* can't set zero-byte lock */
1165 if (start > max_unix_offset) return 1; /* ignore it */
1166 fl.l_type = type;
1167 fl.l_whence = SEEK_SET;
1168 fl.l_start = start;
1169 if (!end || end > max_unix_offset) fl.l_len = 0;
1170 else fl.l_len = end - start;
1171 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1173 switch(errno)
1175 case EACCES:
1176 /* check whether locks work at all on this file system */
1177 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1179 set_error( STATUS_FILE_LOCK_CONFLICT );
1180 return 0;
1182 /* fall through */
1183 case EIO:
1184 case ENOLCK:
1185 case ENOTSUP:
1186 /* no locking on this fs, just ignore it */
1187 fd->fs_locks = 0;
1188 return 1;
1189 case EAGAIN:
1190 set_error( STATUS_FILE_LOCK_CONFLICT );
1191 return 0;
1192 case EBADF:
1193 /* this can happen if we try to set a write lock on a read-only file */
1194 /* try to at least grab a read lock */
1195 if (fl.l_type == F_WRLCK)
1197 type = F_RDLCK;
1198 break; /* retry */
1200 set_error( STATUS_ACCESS_DENIED );
1201 return 0;
1202 #ifdef EOVERFLOW
1203 case EOVERFLOW:
1204 #endif
1205 case EINVAL:
1206 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1207 /* in that case we shrink the limit and retry */
1208 if (max_unix_offset > INT_MAX)
1210 max_unix_offset = INT_MAX;
1211 break; /* retry */
1213 /* fall through */
1214 default:
1215 file_set_error();
1216 return 0;
1221 /* check if interval [start;end) overlaps the lock */
1222 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1224 if (lock->end && start >= lock->end) return 0;
1225 if (end && lock->start >= end) return 0;
1226 return 1;
1229 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1230 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1232 struct hole
1234 struct hole *next;
1235 struct hole *prev;
1236 file_pos_t start;
1237 file_pos_t end;
1238 } *first, *cur, *next, *buffer;
1240 struct list *ptr;
1241 int count = 0;
1243 if (!fd->inode) return;
1244 if (!fd->fs_locks) return;
1245 if (start == end || start > max_unix_offset) return;
1246 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1248 /* count the number of locks overlapping the specified area */
1250 LIST_FOR_EACH( ptr, &fd->inode->locks )
1252 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1253 if (lock->start == lock->end) continue;
1254 if (lock_overlaps( lock, start, end )) count++;
1257 if (!count) /* no locks at all, we can unlock everything */
1259 set_unix_lock( fd, start, end, F_UNLCK );
1260 return;
1263 /* allocate space for the list of holes */
1264 /* max. number of holes is number of locks + 1 */
1266 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1267 first = buffer;
1268 first->next = NULL;
1269 first->prev = NULL;
1270 first->start = start;
1271 first->end = end;
1272 next = first + 1;
1274 /* build a sorted list of unlocked holes in the specified area */
1276 LIST_FOR_EACH( ptr, &fd->inode->locks )
1278 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1279 if (lock->start == lock->end) continue;
1280 if (!lock_overlaps( lock, start, end )) continue;
1282 /* go through all the holes touched by this lock */
1283 for (cur = first; cur; cur = cur->next)
1285 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1286 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1288 /* now we know that lock is overlapping hole */
1290 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1292 cur->start = lock->end;
1293 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1294 /* now hole is empty, remove it */
1295 if (cur->next) cur->next->prev = cur->prev;
1296 if (cur->prev) cur->prev->next = cur->next;
1297 else if (!(first = cur->next)) goto done; /* no more holes at all */
1299 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1301 cur->end = lock->start;
1302 assert( cur->start < cur->end );
1304 else /* lock is in the middle of hole, split hole in two */
1306 next->prev = cur;
1307 next->next = cur->next;
1308 cur->next = next;
1309 next->start = lock->end;
1310 next->end = cur->end;
1311 cur->end = lock->start;
1312 assert( next->start < next->end );
1313 assert( cur->end < next->start );
1314 next++;
1315 break; /* done with this lock */
1320 /* clear Unix locks for all the holes */
1322 for (cur = first; cur; cur = cur->next)
1323 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1325 done:
1326 free( buffer );
1329 /* create a new lock on a fd */
1330 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1332 struct file_lock *lock;
1334 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1335 lock->shared = shared;
1336 lock->start = start;
1337 lock->end = end;
1338 lock->fd = fd;
1339 lock->process = current->process;
1341 /* now try to set a Unix lock */
1342 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1344 release_object( lock );
1345 return NULL;
1347 list_add_tail( &fd->locks, &lock->fd_entry );
1348 list_add_tail( &fd->inode->locks, &lock->inode_entry );
1349 list_add_tail( &lock->process->locks, &lock->proc_entry );
1350 return lock;
1353 /* remove an existing lock */
1354 static void remove_lock( struct file_lock *lock, int remove_unix )
1356 struct inode *inode = lock->fd->inode;
1358 list_remove( &lock->fd_entry );
1359 list_remove( &lock->inode_entry );
1360 list_remove( &lock->proc_entry );
1361 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1362 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1363 lock->process = NULL;
1364 wake_up( &lock->obj, 0 );
1365 release_object( lock );
1368 /* remove all locks owned by a given process */
1369 void remove_process_locks( struct process *process )
1371 struct list *ptr;
1373 while ((ptr = list_head( &process->locks )))
1375 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1376 remove_lock( lock, 1 ); /* this removes it from the list */
1380 /* remove all locks on a given fd */
1381 static void remove_fd_locks( struct fd *fd )
1383 file_pos_t start = FILE_POS_T_MAX, end = 0;
1384 struct list *ptr;
1386 while ((ptr = list_head( &fd->locks )))
1388 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1389 if (lock->start < start) start = lock->start;
1390 if (!lock->end || lock->end > end) end = lock->end - 1;
1391 remove_lock( lock, 0 );
1393 if (start < end) remove_unix_locks( fd, start, end + 1 );
1396 /* add a lock on an fd */
1397 /* returns handle to wait on */
1398 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1400 struct list *ptr;
1401 file_pos_t end = start + count;
1403 if (!fd->inode) /* not a regular file */
1405 set_error( STATUS_INVALID_DEVICE_REQUEST );
1406 return 0;
1409 /* don't allow wrapping locks */
1410 if (end && end < start)
1412 set_error( STATUS_INVALID_PARAMETER );
1413 return 0;
1416 /* check if another lock on that file overlaps the area */
1417 LIST_FOR_EACH( ptr, &fd->inode->locks )
1419 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1420 if (!lock_overlaps( lock, start, end )) continue;
1421 if (shared && (lock->shared || lock->fd == fd)) continue;
1422 /* found one */
1423 if (!wait)
1425 set_error( STATUS_FILE_LOCK_CONFLICT );
1426 return 0;
1428 set_error( STATUS_PENDING );
1429 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1432 /* not found, add it */
1433 if (add_lock( fd, shared, start, end )) return 0;
1434 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1436 /* Unix lock conflict -> tell client to wait and retry */
1437 if (wait) set_error( STATUS_PENDING );
1439 return 0;
1442 /* remove a lock on an fd */
1443 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1445 struct list *ptr;
1446 file_pos_t end = start + count;
1448 /* find an existing lock with the exact same parameters */
1449 LIST_FOR_EACH( ptr, &fd->locks )
1451 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1452 if ((lock->start == start) && (lock->end == end))
1454 remove_lock( lock, 1 );
1455 return;
1458 set_error( STATUS_FILE_LOCK_CONFLICT );
1462 /****************************************************************/
1463 /* file descriptor functions */
1465 static void fd_dump( struct object *obj, int verbose )
1467 struct fd *fd = (struct fd *)obj;
1468 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1469 if (fd->inode) fprintf( stderr, " inode=%p unlink=%d", fd->inode, fd->closed->unlink );
1470 fprintf( stderr, "\n" );
1473 static void fd_destroy( struct object *obj )
1475 struct fd *fd = (struct fd *)obj;
1477 free_async_queue( &fd->read_q );
1478 free_async_queue( &fd->write_q );
1479 free_async_queue( &fd->wait_q );
1481 if (fd->completion) release_object( fd->completion );
1482 remove_fd_locks( fd );
1483 list_remove( &fd->inode_entry );
1484 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1485 if (fd->inode)
1487 inode_add_closed_fd( fd->inode, fd->closed );
1488 release_object( fd->inode );
1490 else /* no inode, close it right away */
1492 if (fd->unix_fd != -1) close( fd->unix_fd );
1493 free( fd->unix_name );
1497 /* check if the desired access is possible without violating */
1498 /* the sharing mode of other opens of the same file */
1499 static unsigned int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing,
1500 unsigned int open_flags, unsigned int options )
1502 /* only a few access bits are meaningful wrt sharing */
1503 const unsigned int read_access = FILE_READ_DATA | FILE_EXECUTE;
1504 const unsigned int write_access = FILE_WRITE_DATA | FILE_APPEND_DATA;
1505 const unsigned int all_access = read_access | write_access | DELETE;
1507 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1508 unsigned int existing_access = 0;
1509 struct list *ptr;
1511 fd->access = access;
1512 fd->sharing = sharing;
1514 LIST_FOR_EACH( ptr, &fd->inode->open )
1516 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1517 if (fd_ptr != fd)
1519 /* if access mode is 0, sharing mode is ignored */
1520 if (fd_ptr->access & all_access) existing_sharing &= fd_ptr->sharing;
1521 existing_access |= fd_ptr->access;
1525 if (((access & read_access) && !(existing_sharing & FILE_SHARE_READ)) ||
1526 ((access & write_access) && !(existing_sharing & FILE_SHARE_WRITE)) ||
1527 ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)))
1528 return STATUS_SHARING_VIOLATION;
1529 if (((existing_access & FILE_MAPPING_WRITE) && !(sharing & FILE_SHARE_WRITE)) ||
1530 ((existing_access & FILE_MAPPING_IMAGE) && (access & FILE_WRITE_DATA)))
1531 return STATUS_SHARING_VIOLATION;
1532 if ((existing_access & FILE_MAPPING_IMAGE) && (options & FILE_DELETE_ON_CLOSE))
1533 return STATUS_CANNOT_DELETE;
1534 if ((existing_access & FILE_MAPPING_ACCESS) && (open_flags & O_TRUNC))
1535 return STATUS_USER_MAPPED_FILE;
1536 if (!(access & all_access))
1537 return 0; /* if access mode is 0, sharing mode is ignored (except for mappings) */
1538 if (((existing_access & read_access) && !(sharing & FILE_SHARE_READ)) ||
1539 ((existing_access & write_access) && !(sharing & FILE_SHARE_WRITE)) ||
1540 ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)))
1541 return STATUS_SHARING_VIOLATION;
1542 return 0;
1545 /* set the events that select waits for on this fd */
1546 void set_fd_events( struct fd *fd, int events )
1548 int user = fd->poll_index;
1549 assert( poll_users[user] == fd );
1551 set_fd_epoll_events( fd, user, events );
1553 if (events == -1) /* stop waiting on this fd completely */
1555 pollfd[user].fd = -1;
1556 pollfd[user].events = POLLERR;
1557 pollfd[user].revents = 0;
1559 else if (pollfd[user].fd != -1 || !pollfd[user].events)
1561 pollfd[user].fd = fd->unix_fd;
1562 pollfd[user].events = events;
1566 /* prepare an fd for unmounting its corresponding device */
1567 static inline void unmount_fd( struct fd *fd )
1569 assert( fd->inode );
1571 async_wake_up( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1572 async_wake_up( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1574 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1576 if (fd->unix_fd != -1) close( fd->unix_fd );
1578 fd->unix_fd = -1;
1579 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1580 fd->closed->unix_fd = -1;
1581 fd->closed->unlink = 0;
1583 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1584 fd->fs_locks = 0;
1587 /* allocate an fd object, without setting the unix fd yet */
1588 static struct fd *alloc_fd_object(void)
1590 struct fd *fd = alloc_object( &fd_ops );
1592 if (!fd) return NULL;
1594 fd->fd_ops = NULL;
1595 fd->user = NULL;
1596 fd->inode = NULL;
1597 fd->closed = NULL;
1598 fd->access = 0;
1599 fd->options = 0;
1600 fd->sharing = 0;
1601 fd->unix_fd = -1;
1602 fd->unix_name = NULL;
1603 fd->cacheable = 0;
1604 fd->signaled = 1;
1605 fd->fs_locks = 1;
1606 fd->poll_index = -1;
1607 fd->completion = NULL;
1608 fd->comp_flags = 0;
1609 init_async_queue( &fd->read_q );
1610 init_async_queue( &fd->write_q );
1611 init_async_queue( &fd->wait_q );
1612 list_init( &fd->inode_entry );
1613 list_init( &fd->locks );
1615 if ((fd->poll_index = add_poll_user( fd )) == -1)
1617 release_object( fd );
1618 return NULL;
1620 return fd;
1623 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1624 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1626 struct fd *fd = alloc_object( &fd_ops );
1628 if (!fd) return NULL;
1630 fd->fd_ops = fd_user_ops;
1631 fd->user = user;
1632 fd->inode = NULL;
1633 fd->closed = NULL;
1634 fd->access = 0;
1635 fd->options = options;
1636 fd->sharing = 0;
1637 fd->unix_name = NULL;
1638 fd->unix_fd = -1;
1639 fd->cacheable = 0;
1640 fd->signaled = 0;
1641 fd->fs_locks = 0;
1642 fd->poll_index = -1;
1643 fd->completion = NULL;
1644 fd->comp_flags = 0;
1645 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1646 init_async_queue( &fd->read_q );
1647 init_async_queue( &fd->write_q );
1648 init_async_queue( &fd->wait_q );
1649 list_init( &fd->inode_entry );
1650 list_init( &fd->locks );
1651 return fd;
1654 /* duplicate an fd object for a different user */
1655 struct fd *dup_fd_object( struct fd *orig, unsigned int access, unsigned int sharing, unsigned int options )
1657 unsigned int err;
1658 struct fd *fd = alloc_fd_object();
1660 if (!fd) return NULL;
1662 fd->options = options;
1663 fd->cacheable = orig->cacheable;
1665 if (orig->unix_name)
1667 if (!(fd->unix_name = mem_alloc( strlen(orig->unix_name) + 1 ))) goto failed;
1668 strcpy( fd->unix_name, orig->unix_name );
1671 if (orig->inode)
1673 struct closed_fd *closed = mem_alloc( sizeof(*closed) );
1674 if (!closed) goto failed;
1675 if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1677 file_set_error();
1678 free( closed );
1679 goto failed;
1681 closed->unix_fd = fd->unix_fd;
1682 closed->unlink = 0;
1683 closed->unix_name = fd->unix_name;
1684 fd->closed = closed;
1685 fd->inode = (struct inode *)grab_object( orig->inode );
1686 list_add_head( &fd->inode->open, &fd->inode_entry );
1687 if ((err = check_sharing( fd, access, sharing, 0, options )))
1689 set_error( err );
1690 goto failed;
1693 else if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1695 file_set_error();
1696 goto failed;
1698 return fd;
1700 failed:
1701 release_object( fd );
1702 return NULL;
1705 /* find an existing fd object that can be reused for a mapping */
1706 struct fd *get_fd_object_for_mapping( struct fd *fd, unsigned int access, unsigned int sharing )
1708 struct fd *fd_ptr;
1710 if (!fd->inode) return NULL;
1712 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
1713 if (fd_ptr->access == access && fd_ptr->sharing == sharing)
1714 return (struct fd *)grab_object( fd_ptr );
1716 return NULL;
1719 /* sets the user of an fd that previously had no user */
1720 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1722 assert( fd->fd_ops == NULL );
1723 fd->fd_ops = user_ops;
1724 fd->user = user;
1727 char *dup_fd_name( struct fd *root, const char *name )
1729 char *ret;
1731 if (!root) return strdup( name );
1732 if (!root->unix_name) return NULL;
1734 /* skip . prefix */
1735 if (name[0] == '.' && (!name[1] || name[1] == '/')) name++;
1737 if ((ret = malloc( strlen(root->unix_name) + strlen(name) + 2 )))
1739 strcpy( ret, root->unix_name );
1740 if (name[0] && name[0] != '/') strcat( ret, "/" );
1741 strcat( ret, name );
1743 return ret;
1746 /* open() wrapper that returns a struct fd with no fd user set */
1747 struct fd *open_fd( struct fd *root, const char *name, int flags, mode_t *mode, unsigned int access,
1748 unsigned int sharing, unsigned int options )
1750 struct stat st;
1751 struct closed_fd *closed_fd;
1752 struct fd *fd;
1753 int root_fd = -1;
1754 int rw_mode;
1756 if (((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE)) ||
1757 ((options & FILE_DIRECTORY_FILE) && (flags & O_TRUNC)))
1759 set_error( STATUS_INVALID_PARAMETER );
1760 return NULL;
1763 if (!(fd = alloc_fd_object())) return NULL;
1765 fd->options = options;
1766 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
1768 release_object( fd );
1769 return NULL;
1772 if (root)
1774 if ((root_fd = get_unix_fd( root )) == -1) goto error;
1775 if (fchdir( root_fd ) == -1)
1777 file_set_error();
1778 root_fd = -1;
1779 goto error;
1783 /* create the directory if needed */
1784 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1786 if (mkdir( name, *mode ) == -1)
1788 if (errno != EEXIST || (flags & O_EXCL))
1790 file_set_error();
1791 goto error;
1794 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1797 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1799 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1800 else rw_mode = O_WRONLY;
1802 else rw_mode = O_RDONLY;
1804 fd->unix_name = dup_fd_name( root, name );
1806 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1808 /* if we tried to open a directory for write access, retry read-only */
1809 if (errno == EISDIR)
1811 if ((access & FILE_UNIX_WRITE_ACCESS) || (flags & O_CREAT))
1812 fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode );
1815 if (fd->unix_fd == -1)
1817 file_set_error();
1818 goto error;
1822 closed_fd->unix_fd = fd->unix_fd;
1823 closed_fd->unlink = 0;
1824 closed_fd->unix_name = fd->unix_name;
1825 fstat( fd->unix_fd, &st );
1826 *mode = st.st_mode;
1828 /* only bother with an inode for normal files and directories */
1829 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1831 unsigned int err;
1832 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1834 if (!inode)
1836 /* we can close the fd because there are no others open on the same file,
1837 * otherwise we wouldn't have failed to allocate a new inode
1839 goto error;
1841 fd->inode = inode;
1842 fd->closed = closed_fd;
1843 fd->cacheable = !inode->device->removable;
1844 list_add_head( &inode->open, &fd->inode_entry );
1845 closed_fd = NULL;
1847 /* check directory options */
1848 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1850 set_error( STATUS_NOT_A_DIRECTORY );
1851 goto error;
1853 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1855 set_error( STATUS_FILE_IS_A_DIRECTORY );
1856 goto error;
1858 if ((err = check_sharing( fd, access, sharing, flags, options )))
1860 set_error( err );
1861 goto error;
1864 /* can't unlink files if we don't have permission to access */
1865 if ((options & FILE_DELETE_ON_CLOSE) && !(flags & O_CREAT) &&
1866 !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1868 set_error( STATUS_CANNOT_DELETE );
1869 goto error;
1872 fd->closed->unlink = (options & FILE_DELETE_ON_CLOSE) != 0;
1873 if (flags & O_TRUNC)
1875 if (S_ISDIR(st.st_mode))
1877 set_error( STATUS_OBJECT_NAME_COLLISION );
1878 goto error;
1880 ftruncate( fd->unix_fd, 0 );
1883 else /* special file */
1885 if (options & FILE_DELETE_ON_CLOSE) /* we can't unlink special files */
1887 set_error( STATUS_INVALID_PARAMETER );
1888 goto error;
1890 free( closed_fd );
1891 fd->cacheable = 1;
1893 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1894 return fd;
1896 error:
1897 release_object( fd );
1898 free( closed_fd );
1899 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1900 return NULL;
1903 /* create an fd for an anonymous file */
1904 /* if the function fails the unix fd is closed */
1905 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
1906 unsigned int options )
1908 struct fd *fd = alloc_fd_object();
1910 if (fd)
1912 set_fd_user( fd, fd_user_ops, user );
1913 fd->unix_fd = unix_fd;
1914 fd->options = options;
1915 return fd;
1917 close( unix_fd );
1918 return NULL;
1921 /* retrieve the object that is using an fd */
1922 void *get_fd_user( struct fd *fd )
1924 return fd->user;
1927 /* retrieve the opening options for the fd */
1928 unsigned int get_fd_options( struct fd *fd )
1930 return fd->options;
1933 /* retrieve the unix fd for an object */
1934 int get_unix_fd( struct fd *fd )
1936 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
1937 return fd->unix_fd;
1940 /* check if two file descriptors point to the same file */
1941 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1943 return fd1->inode == fd2->inode;
1946 /* allow the fd to be cached (can't be reset once set) */
1947 void allow_fd_caching( struct fd *fd )
1949 fd->cacheable = 1;
1952 /* check if fd is on a removable device */
1953 int is_fd_removable( struct fd *fd )
1955 return (fd->inode && fd->inode->device->removable);
1958 /* set or clear the fd signaled state */
1959 void set_fd_signaled( struct fd *fd, int signaled )
1961 fd->signaled = signaled;
1962 if (signaled) wake_up( fd->user, 0 );
1965 /* check if fd is signaled */
1966 int is_fd_signaled( struct fd *fd )
1968 return fd->signaled;
1971 /* handler for close_handle that refuses to close fd-associated handles in other processes */
1972 int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
1974 return (!current || current->process == process);
1977 /* check if events are pending and if yes return which one(s) */
1978 int check_fd_events( struct fd *fd, int events )
1980 struct pollfd pfd;
1982 if (fd->unix_fd == -1) return POLLERR;
1983 if (fd->inode) return events; /* regular files are always signaled */
1985 pfd.fd = fd->unix_fd;
1986 pfd.events = events;
1987 if (poll( &pfd, 1, 0 ) <= 0) return 0;
1988 return pfd.revents;
1991 /* default signaled() routine for objects that poll() on an fd */
1992 int default_fd_signaled( struct object *obj, struct wait_queue_entry *entry )
1994 struct fd *fd = get_obj_fd( obj );
1995 int ret = fd->signaled;
1996 release_object( fd );
1997 return ret;
2000 /* default map_access() routine for objects that behave like an fd */
2001 unsigned int default_fd_map_access( struct object *obj, unsigned int access )
2003 if (access & GENERIC_READ) access |= FILE_GENERIC_READ;
2004 if (access & GENERIC_WRITE) access |= FILE_GENERIC_WRITE;
2005 if (access & GENERIC_EXECUTE) access |= FILE_GENERIC_EXECUTE;
2006 if (access & GENERIC_ALL) access |= FILE_ALL_ACCESS;
2007 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
2010 int default_fd_get_poll_events( struct fd *fd )
2012 int events = 0;
2014 if (async_waiting( &fd->read_q )) events |= POLLIN;
2015 if (async_waiting( &fd->write_q )) events |= POLLOUT;
2016 return events;
2019 /* default handler for poll() events */
2020 void default_poll_event( struct fd *fd, int event )
2022 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( &fd->read_q, STATUS_ALERTED );
2023 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( &fd->write_q, STATUS_ALERTED );
2025 /* if an error occurred, stop polling this fd to avoid busy-looping */
2026 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
2027 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2030 void fd_queue_async( struct fd *fd, struct async *async, int type )
2032 struct async_queue *queue;
2034 switch (type)
2036 case ASYNC_TYPE_READ:
2037 queue = &fd->read_q;
2038 break;
2039 case ASYNC_TYPE_WRITE:
2040 queue = &fd->write_q;
2041 break;
2042 case ASYNC_TYPE_WAIT:
2043 queue = &fd->wait_q;
2044 break;
2045 default:
2046 queue = NULL;
2047 assert(0);
2050 queue_async( queue, async );
2052 if (type != ASYNC_TYPE_WAIT)
2054 if (!fd->inode)
2055 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2056 else /* regular files are always ready for read and write */
2057 async_wake_up( queue, STATUS_ALERTED );
2061 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
2063 switch (type)
2065 case ASYNC_TYPE_READ:
2066 async_wake_up( &fd->read_q, status );
2067 break;
2068 case ASYNC_TYPE_WRITE:
2069 async_wake_up( &fd->write_q, status );
2070 break;
2071 case ASYNC_TYPE_WAIT:
2072 async_wake_up( &fd->wait_q, status );
2073 break;
2074 default:
2075 assert(0);
2079 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
2081 fd->fd_ops->reselect_async( fd, queue );
2084 void no_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2086 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2089 void default_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2091 fd_queue_async( fd, async, type );
2092 set_error( STATUS_PENDING );
2095 /* default reselect_async() fd routine */
2096 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
2098 if (queue == &fd->read_q || queue == &fd->write_q)
2100 int poll_events = fd->fd_ops->get_poll_events( fd );
2101 int events = check_fd_events( fd, poll_events );
2102 if (events) fd->fd_ops->poll_event( fd, events );
2103 else set_fd_events( fd, poll_events );
2107 static inline int is_valid_mounted_device( struct stat *st )
2109 #if defined(linux) || defined(__sun__)
2110 return S_ISBLK( st->st_mode );
2111 #else
2112 /* disks are char devices on *BSD */
2113 return S_ISCHR( st->st_mode );
2114 #endif
2117 /* close all Unix file descriptors on a device to allow unmounting it */
2118 static void unmount_device( struct fd *device_fd )
2120 unsigned int i;
2121 struct stat st;
2122 struct device *device;
2123 struct inode *inode;
2124 struct fd *fd;
2125 int unix_fd = get_unix_fd( device_fd );
2127 if (unix_fd == -1) return;
2129 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2131 set_error( STATUS_INVALID_PARAMETER );
2132 return;
2135 if (!(device = get_device( st.st_rdev, -1 ))) return;
2137 for (i = 0; i < INODE_HASH_SIZE; i++)
2139 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
2141 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
2143 unmount_fd( fd );
2145 inode_close_pending( inode, 0 );
2148 /* remove it from the hash table */
2149 list_remove( &device->entry );
2150 list_init( &device->entry );
2151 release_object( device );
2154 /* default read() routine */
2155 int no_fd_read( struct fd *fd, struct async *async, file_pos_t pos )
2157 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2158 return 0;
2161 /* default write() routine */
2162 int no_fd_write( struct fd *fd, struct async *async, file_pos_t pos )
2164 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2165 return 0;
2168 /* default flush() routine */
2169 int no_fd_flush( struct fd *fd, struct async *async )
2171 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2172 return 0;
2175 /* default get_file_info() routine */
2176 void no_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2178 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2181 /* default get_file_info() routine */
2182 void default_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2184 switch (info_class)
2186 case FileAccessInformation:
2188 FILE_ACCESS_INFORMATION info;
2189 if (get_reply_max_size() < sizeof(info))
2191 set_error( STATUS_INFO_LENGTH_MISMATCH );
2192 return;
2194 info.AccessFlags = get_handle_access( current->process, handle );
2195 set_reply_data( &info, sizeof(info) );
2196 break;
2198 case FileIoCompletionNotificationInformation:
2200 FILE_IO_COMPLETION_NOTIFICATION_INFORMATION info;
2201 if (get_reply_max_size() < sizeof(info))
2203 set_error( STATUS_INFO_LENGTH_MISMATCH );
2204 return;
2206 info.Flags = fd->comp_flags;
2207 set_reply_data( &info, sizeof(info) );
2208 break;
2210 default:
2211 set_error( STATUS_NOT_IMPLEMENTED );
2215 /* default get_volume_info() routine */
2216 void no_fd_get_volume_info( struct fd *fd, unsigned int info_class )
2218 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2221 /* default ioctl() routine */
2222 int no_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2224 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2225 return 0;
2228 /* default ioctl() routine */
2229 int default_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2231 switch(code)
2233 case FSCTL_DISMOUNT_VOLUME:
2234 unmount_device( fd );
2235 return 1;
2236 default:
2237 set_error( STATUS_NOT_SUPPORTED );
2238 return 0;
2242 /* same as get_handle_obj but retrieve the struct fd associated to the object */
2243 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
2244 unsigned int access )
2246 struct fd *fd = NULL;
2247 struct object *obj;
2249 if ((obj = get_handle_obj( process, handle, access, NULL )))
2251 fd = get_obj_fd( obj );
2252 release_object( obj );
2254 return fd;
2257 /* set disposition for the fd */
2258 static void set_fd_disposition( struct fd *fd, int unlink )
2260 struct stat st;
2262 if (!fd->inode)
2264 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2265 return;
2268 if (fd->unix_fd == -1)
2270 set_error( fd->no_fd_status );
2271 return;
2274 if (fstat( fd->unix_fd, &st ) == -1)
2276 file_set_error();
2277 return;
2280 /* can't unlink special files */
2281 if (unlink && !S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
2283 set_error( STATUS_INVALID_PARAMETER );
2284 return;
2287 /* can't unlink files we don't have permission to access */
2288 if (unlink && !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2290 set_error( STATUS_CANNOT_DELETE );
2291 return;
2294 fd->closed->unlink = unlink || (fd->options & FILE_DELETE_ON_CLOSE);
2297 /* set new name for the fd */
2298 static void set_fd_name( struct fd *fd, struct fd *root, const char *nameptr,
2299 data_size_t len, int create_link )
2301 struct inode *inode;
2302 struct stat st;
2303 char *name;
2305 if (!fd->inode || !fd->unix_name)
2307 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2308 return;
2310 if (!len || ((nameptr[0] == '/') ^ !root))
2312 set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
2313 return;
2315 if (!(name = mem_alloc( len + 1 ))) return;
2316 memcpy( name, nameptr, len );
2317 name[len] = 0;
2319 if (root)
2321 char *combined_name = dup_fd_name( root, name );
2322 if (!combined_name)
2324 set_error( STATUS_NO_MEMORY );
2325 goto failed;
2327 free( name );
2328 name = combined_name;
2331 /* when creating a hard link, source cannot be a dir */
2332 if (create_link && fd->unix_fd != -1 &&
2333 !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode ))
2335 set_error( STATUS_FILE_IS_A_DIRECTORY );
2336 goto failed;
2339 if (!stat( name, &st ))
2341 /* can't replace directories or special files */
2342 if (!S_ISREG( st.st_mode ))
2344 set_error( STATUS_ACCESS_DENIED );
2345 goto failed;
2348 /* can't replace an opened file */
2349 if ((inode = get_inode( st.st_dev, st.st_ino, -1 )))
2351 int is_empty = list_empty( &inode->open );
2352 release_object( inode );
2353 if (!is_empty)
2355 set_error( STATUS_ACCESS_DENIED );
2356 goto failed;
2360 /* link() expects that the target doesn't exist */
2361 /* rename() cannot replace files with directories */
2362 if (create_link || (fd->unix_fd != -1 &&
2363 !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode )))
2365 if (unlink( name ))
2367 file_set_error();
2368 goto failed;
2373 if (create_link)
2375 if (link( fd->unix_name, name ))
2376 file_set_error();
2377 free( name );
2378 return;
2381 if (rename( fd->unix_name, name ))
2383 file_set_error();
2384 goto failed;
2387 free( fd->unix_name );
2388 fd->unix_name = name;
2389 fd->closed->unix_name = name;
2390 return;
2392 failed:
2393 free( name );
2396 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
2398 *p_key = fd->comp_key;
2399 return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
2402 void fd_copy_completion( struct fd *src, struct fd *dst )
2404 assert( !dst->completion );
2405 dst->completion = fd_get_completion( src, &dst->comp_key );
2406 dst->comp_flags = src->comp_flags;
2409 /* flush a file buffers */
2410 DECL_HANDLER(flush)
2412 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, 0 );
2413 struct async *async;
2415 if (!fd) return;
2417 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2419 reply->event = async_handoff( async, fd->fd_ops->flush( fd, async ), NULL );
2420 release_object( async );
2422 release_object( fd );
2425 /* query file info */
2426 DECL_HANDLER(get_file_info)
2428 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2430 if (fd)
2432 fd->fd_ops->get_file_info( fd, req->handle, req->info_class );
2433 release_object( fd );
2437 /* query volume info */
2438 DECL_HANDLER(get_volume_info)
2440 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2442 if (fd)
2444 fd->fd_ops->get_volume_info( fd, req->info_class );
2445 release_object( fd );
2449 /* open a file object */
2450 DECL_HANDLER(open_file_object)
2452 struct unicode_str name = get_req_unicode_str();
2453 struct object *obj, *result, *root = NULL;
2455 if (req->rootdir && !(root = get_handle_obj( current->process, req->rootdir, 0, NULL ))) return;
2457 obj = open_named_object( root, NULL, &name, req->attributes );
2458 if (root) release_object( root );
2459 if (!obj) return;
2461 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
2463 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
2464 release_object( result );
2466 release_object( obj );
2469 /* get the Unix name from a file handle */
2470 DECL_HANDLER(get_handle_unix_name)
2472 struct fd *fd;
2474 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2476 if (fd->unix_name)
2478 data_size_t name_len = strlen( fd->unix_name );
2479 reply->name_len = name_len;
2480 if (name_len <= get_reply_max_size()) set_reply_data( fd->unix_name, name_len );
2481 else set_error( STATUS_BUFFER_OVERFLOW );
2483 else set_error( STATUS_OBJECT_TYPE_MISMATCH );
2484 release_object( fd );
2488 /* get a Unix fd to access a file */
2489 DECL_HANDLER(get_handle_fd)
2491 struct fd *fd;
2493 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2495 int unix_fd = get_unix_fd( fd );
2496 reply->cacheable = fd->cacheable;
2497 if (unix_fd != -1)
2499 reply->type = fd->fd_ops->get_fd_type( fd );
2500 reply->options = fd->options;
2501 reply->access = get_handle_access( current->process, req->handle );
2502 send_client_fd( current->process, unix_fd, req->handle );
2504 release_object( fd );
2508 /* perform a read on a file object */
2509 DECL_HANDLER(read)
2511 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_READ_DATA );
2512 struct async *async;
2514 if (!fd) return;
2516 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2518 reply->wait = async_handoff( async, fd->fd_ops->read( fd, async, req->pos ), NULL );
2519 reply->options = fd->options;
2520 release_object( async );
2522 release_object( fd );
2525 /* perform a write on a file object */
2526 DECL_HANDLER(write)
2528 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_WRITE_DATA );
2529 struct async *async;
2531 if (!fd) return;
2533 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2535 reply->wait = async_handoff( async, fd->fd_ops->write( fd, async, req->pos ), &reply->size );
2536 reply->options = fd->options;
2537 release_object( async );
2539 release_object( fd );
2542 /* perform an ioctl on a file */
2543 DECL_HANDLER(ioctl)
2545 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2546 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2547 struct async *async;
2549 if (!fd) return;
2551 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2553 reply->wait = async_handoff( async, fd->fd_ops->ioctl( fd, req->code, async ), NULL );
2554 reply->options = fd->options;
2555 release_object( async );
2557 release_object( fd );
2560 /* create / reschedule an async I/O */
2561 DECL_HANDLER(register_async)
2563 unsigned int access;
2564 struct async *async;
2565 struct fd *fd;
2567 switch(req->type)
2569 case ASYNC_TYPE_READ:
2570 access = FILE_READ_DATA;
2571 break;
2572 case ASYNC_TYPE_WRITE:
2573 access = FILE_WRITE_DATA;
2574 break;
2575 default:
2576 set_error( STATUS_INVALID_PARAMETER );
2577 return;
2580 if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2582 if (get_unix_fd( fd ) != -1 && (async = create_async( fd, current, &req->async, NULL )))
2584 fd->fd_ops->queue_async( fd, async, req->type, req->count );
2585 release_object( async );
2587 release_object( fd );
2591 /* attach completion object to a fd */
2592 DECL_HANDLER(set_completion_info)
2594 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2596 if (fd)
2598 if (!(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) && !fd->completion)
2600 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2601 fd->comp_key = req->ckey;
2603 else set_error( STATUS_INVALID_PARAMETER );
2604 release_object( fd );
2608 /* push new completion msg into a completion queue attached to the fd */
2609 DECL_HANDLER(add_fd_completion)
2611 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2612 if (fd)
2614 if (fd->completion && (req->async || !(fd->comp_flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS)))
2615 add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2616 release_object( fd );
2620 /* set fd completion information */
2621 DECL_HANDLER(set_fd_completion_mode)
2623 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2624 if (fd)
2626 if (!(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2628 /* removing COMPLETION_SKIP_ON_SUCCESS is not allowed */
2629 fd->comp_flags |= req->flags & ( FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
2630 | FILE_SKIP_SET_EVENT_ON_HANDLE
2631 | FILE_SKIP_SET_USER_EVENT_ON_FAST_IO );
2633 else
2634 set_error( STATUS_INVALID_PARAMETER );
2635 release_object( fd );
2639 /* set fd disposition information */
2640 DECL_HANDLER(set_fd_disp_info)
2642 struct fd *fd = get_handle_fd_obj( current->process, req->handle, DELETE );
2643 if (fd)
2645 set_fd_disposition( fd, req->unlink );
2646 release_object( fd );
2650 /* set fd name information */
2651 DECL_HANDLER(set_fd_name_info)
2653 struct fd *fd, *root_fd = NULL;
2655 if (req->rootdir)
2657 struct dir *root;
2659 if (!(root = get_dir_obj( current->process, req->rootdir, 0 ))) return;
2660 root_fd = get_obj_fd( (struct object *)root );
2661 release_object( root );
2662 if (!root_fd) return;
2665 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2667 set_fd_name( fd, root_fd, get_req_data(), get_req_data_size(), req->link );
2668 release_object( fd );
2670 if (root_fd) release_object( root_fd );