makefiles: Don't use standard libs for programs that specify -nodefaultlibs.
[wine/zf.git] / server / fd.c
blobd4584f73268f0f26d527ffa76222370ec9ae21ef
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: -1 - implicit FILE_DELETE_ON_CLOSE, 1 - explicit disposition */
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_kernel_obj_list, /* get_kernel_obj_list */
222 no_close_handle, /* close_handle */
223 fd_destroy /* destroy */
226 /* device object */
228 #define DEVICE_HASH_SIZE 7
229 #define INODE_HASH_SIZE 17
231 struct device
233 struct object obj; /* object header */
234 struct list entry; /* entry in device hash list */
235 dev_t dev; /* device number */
236 int removable; /* removable device? (or -1 if unknown) */
237 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
240 static void device_dump( struct object *obj, int verbose );
241 static void device_destroy( struct object *obj );
243 static const struct object_ops device_ops =
245 sizeof(struct device), /* size */
246 device_dump, /* dump */
247 no_get_type, /* get_type */
248 no_add_queue, /* add_queue */
249 NULL, /* remove_queue */
250 NULL, /* signaled */
251 NULL, /* satisfied */
252 no_signal, /* signal */
253 no_get_fd, /* get_fd */
254 no_map_access, /* map_access */
255 default_get_sd, /* get_sd */
256 default_set_sd, /* set_sd */
257 no_lookup_name, /* lookup_name */
258 no_link_name, /* link_name */
259 NULL, /* unlink_name */
260 no_open_file, /* open_file */
261 no_kernel_obj_list, /* get_kernel_obj_list */
262 no_close_handle, /* close_handle */
263 device_destroy /* destroy */
266 /* inode object */
268 struct inode
270 struct object obj; /* object header */
271 struct list entry; /* inode hash list entry */
272 struct device *device; /* device containing this inode */
273 ino_t ino; /* inode number */
274 struct list open; /* list of open file descriptors */
275 struct list locks; /* list of file locks */
276 struct list closed; /* list of file descriptors to close at destroy time */
279 static void inode_dump( struct object *obj, int verbose );
280 static void inode_destroy( struct object *obj );
282 static const struct object_ops inode_ops =
284 sizeof(struct inode), /* size */
285 inode_dump, /* dump */
286 no_get_type, /* get_type */
287 no_add_queue, /* add_queue */
288 NULL, /* remove_queue */
289 NULL, /* signaled */
290 NULL, /* satisfied */
291 no_signal, /* signal */
292 no_get_fd, /* get_fd */
293 no_map_access, /* map_access */
294 default_get_sd, /* get_sd */
295 default_set_sd, /* set_sd */
296 no_lookup_name, /* lookup_name */
297 no_link_name, /* link_name */
298 NULL, /* unlink_name */
299 no_open_file, /* open_file */
300 no_kernel_obj_list, /* get_kernel_obj_list */
301 no_close_handle, /* close_handle */
302 inode_destroy /* destroy */
305 /* file lock object */
307 struct file_lock
309 struct object obj; /* object header */
310 struct fd *fd; /* fd owning this lock */
311 struct list fd_entry; /* entry in list of locks on a given fd */
312 struct list inode_entry; /* entry in inode list of locks */
313 int shared; /* shared lock? */
314 file_pos_t start; /* locked region is interval [start;end) */
315 file_pos_t end;
316 struct process *process; /* process owning this lock */
317 struct list proc_entry; /* entry in list of locks owned by the process */
320 static void file_lock_dump( struct object *obj, int verbose );
321 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry );
323 static const struct object_ops file_lock_ops =
325 sizeof(struct file_lock), /* size */
326 file_lock_dump, /* dump */
327 no_get_type, /* get_type */
328 add_queue, /* add_queue */
329 remove_queue, /* remove_queue */
330 file_lock_signaled, /* signaled */
331 no_satisfied, /* satisfied */
332 no_signal, /* signal */
333 no_get_fd, /* get_fd */
334 no_map_access, /* map_access */
335 default_get_sd, /* get_sd */
336 default_set_sd, /* set_sd */
337 no_lookup_name, /* lookup_name */
338 no_link_name, /* link_name */
339 NULL, /* unlink_name */
340 no_open_file, /* open_file */
341 no_kernel_obj_list, /* get_kernel_obj_list */
342 no_close_handle, /* close_handle */
343 no_destroy /* destroy */
347 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
348 #define FILE_POS_T_MAX (~(file_pos_t)0)
350 static file_pos_t max_unix_offset = OFF_T_MAX;
352 #define DUMP_LONG_LONG(val) do { \
353 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
354 fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
355 else \
356 fprintf( stderr, "%lx", (unsigned long)(val) ); \
357 } while (0)
361 /****************************************************************/
362 /* timeouts support */
364 struct timeout_user
366 struct list entry; /* entry in sorted timeout list */
367 timeout_t when; /* timeout expiry (absolute time) */
368 timeout_callback callback; /* callback function */
369 void *private; /* callback private data */
372 static struct list timeout_list = LIST_INIT(timeout_list); /* sorted timeouts list */
373 timeout_t current_time;
375 static inline void set_current_time(void)
377 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
378 struct timeval now;
379 gettimeofday( &now, NULL );
380 current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
383 /* add a timeout user */
384 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
386 struct timeout_user *user;
387 struct list *ptr;
389 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
390 user->when = (when > 0) ? when : current_time - when;
391 user->callback = func;
392 user->private = private;
394 /* Now insert it in the linked list */
396 LIST_FOR_EACH( ptr, &timeout_list )
398 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
399 if (timeout->when >= user->when) break;
401 list_add_before( ptr, &user->entry );
402 return user;
405 /* remove a timeout user */
406 void remove_timeout_user( struct timeout_user *user )
408 list_remove( &user->entry );
409 free( user );
412 /* return a text description of a timeout for debugging purposes */
413 const char *get_timeout_str( timeout_t timeout )
415 static char buffer[64];
416 long secs, nsecs;
418 if (!timeout) return "0";
419 if (timeout == TIMEOUT_INFINITE) return "infinite";
421 if (timeout < 0) /* relative */
423 secs = -timeout / TICKS_PER_SEC;
424 nsecs = -timeout % TICKS_PER_SEC;
425 sprintf( buffer, "+%ld.%07ld", secs, nsecs );
427 else /* absolute */
429 secs = (timeout - current_time) / TICKS_PER_SEC;
430 nsecs = (timeout - current_time) % TICKS_PER_SEC;
431 if (nsecs < 0)
433 nsecs += TICKS_PER_SEC;
434 secs--;
436 if (secs >= 0)
437 sprintf( buffer, "%x%08x (+%ld.%07ld)",
438 (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
439 else
440 sprintf( buffer, "%x%08x (-%ld.%07ld)",
441 (unsigned int)(timeout >> 32), (unsigned int)timeout,
442 -(secs + 1), TICKS_PER_SEC - nsecs );
444 return buffer;
448 /****************************************************************/
449 /* poll support */
451 static struct fd **poll_users; /* users array */
452 static struct pollfd *pollfd; /* poll fd array */
453 static int nb_users; /* count of array entries actually in use */
454 static int active_users; /* current number of active users */
455 static int allocated_users; /* count of allocated entries in the array */
456 static struct fd **freelist; /* list of free entries in the array */
458 static int get_next_timeout(void);
460 static inline void fd_poll_event( struct fd *fd, int event )
462 fd->fd_ops->poll_event( fd, event );
465 #ifdef USE_EPOLL
467 static int epoll_fd = -1;
469 static inline void init_epoll(void)
471 epoll_fd = epoll_create( 128 );
474 /* set the events that epoll waits for on this fd; helper for set_fd_events */
475 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
477 struct epoll_event ev;
478 int ctl;
480 if (epoll_fd == -1) return;
482 if (events == -1) /* stop waiting on this fd completely */
484 if (pollfd[user].fd == -1) return; /* already removed */
485 ctl = EPOLL_CTL_DEL;
487 else if (pollfd[user].fd == -1)
489 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
490 ctl = EPOLL_CTL_ADD;
492 else
494 if (pollfd[user].events == events) return; /* nothing to do */
495 ctl = EPOLL_CTL_MOD;
498 ev.events = events;
499 memset(&ev.data, 0, sizeof(ev.data));
500 ev.data.u32 = user;
502 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
504 if (errno == ENOMEM) /* not enough memory, give up on epoll */
506 close( epoll_fd );
507 epoll_fd = -1;
509 else perror( "epoll_ctl" ); /* should not happen */
513 static inline void remove_epoll_user( struct fd *fd, int user )
515 if (epoll_fd == -1) return;
517 if (pollfd[user].fd != -1)
519 struct epoll_event dummy;
520 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
524 static inline void main_loop_epoll(void)
526 int i, ret, timeout;
527 struct epoll_event events[128];
529 assert( POLLIN == EPOLLIN );
530 assert( POLLOUT == EPOLLOUT );
531 assert( POLLERR == EPOLLERR );
532 assert( POLLHUP == EPOLLHUP );
534 if (epoll_fd == -1) return;
536 while (active_users)
538 timeout = get_next_timeout();
540 if (!active_users) break; /* last user removed by a timeout */
541 if (epoll_fd == -1) break; /* an error occurred with epoll */
543 ret = epoll_wait( epoll_fd, events, ARRAY_SIZE( events ), timeout );
544 set_current_time();
546 /* put the events into the pollfd array first, like poll does */
547 for (i = 0; i < ret; i++)
549 int user = events[i].data.u32;
550 pollfd[user].revents = events[i].events;
553 /* read events from the pollfd array, as set_fd_events may modify them */
554 for (i = 0; i < ret; i++)
556 int user = events[i].data.u32;
557 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
562 #elif defined(HAVE_KQUEUE)
564 static int kqueue_fd = -1;
566 static inline void init_epoll(void)
568 #ifdef __APPLE__ /* kqueue support is broken in Mac OS < 10.5 */
569 int mib[2];
570 char release[32];
571 size_t len = sizeof(release);
573 mib[0] = CTL_KERN;
574 mib[1] = KERN_OSRELEASE;
575 if (sysctl( mib, 2, release, &len, NULL, 0 ) == -1) return;
576 if (atoi(release) < 9) return;
577 #endif
578 kqueue_fd = kqueue();
581 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
583 struct kevent ev[2];
585 if (kqueue_fd == -1) return;
587 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)(long)user );
588 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)(long)user );
590 if (events == -1) /* stop waiting on this fd completely */
592 if (pollfd[user].fd == -1) return; /* already removed */
593 ev[0].flags |= EV_DELETE;
594 ev[1].flags |= EV_DELETE;
596 else if (pollfd[user].fd == -1)
598 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
599 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
600 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
602 else
604 if (pollfd[user].events == events) return; /* nothing to do */
605 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
606 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
609 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
611 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
613 close( kqueue_fd );
614 kqueue_fd = -1;
616 else perror( "kevent" ); /* should not happen */
620 static inline void remove_epoll_user( struct fd *fd, int user )
622 if (kqueue_fd == -1) return;
624 if (pollfd[user].fd != -1)
626 struct kevent ev[2];
628 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
629 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
630 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
634 static inline void main_loop_epoll(void)
636 int i, ret, timeout;
637 struct kevent events[128];
639 if (kqueue_fd == -1) return;
641 while (active_users)
643 timeout = get_next_timeout();
645 if (!active_users) break; /* last user removed by a timeout */
646 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
648 if (timeout != -1)
650 struct timespec ts;
652 ts.tv_sec = timeout / 1000;
653 ts.tv_nsec = (timeout % 1000) * 1000000;
654 ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), &ts );
656 else ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), NULL );
658 set_current_time();
660 /* put the events into the pollfd array first, like poll does */
661 for (i = 0; i < ret; i++)
663 long user = (long)events[i].udata;
664 pollfd[user].revents = 0;
666 for (i = 0; i < ret; i++)
668 long user = (long)events[i].udata;
669 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
670 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
671 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
672 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
675 /* read events from the pollfd array, as set_fd_events may modify them */
676 for (i = 0; i < ret; i++)
678 long user = (long)events[i].udata;
679 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
680 pollfd[user].revents = 0;
685 #elif defined(USE_EVENT_PORTS)
687 static int port_fd = -1;
689 static inline void init_epoll(void)
691 port_fd = port_create();
694 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
696 int ret;
698 if (port_fd == -1) return;
700 if (events == -1) /* stop waiting on this fd completely */
702 if (pollfd[user].fd == -1) return; /* already removed */
703 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
705 else if (pollfd[user].fd == -1)
707 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
708 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
710 else
712 if (pollfd[user].events == events) return; /* nothing to do */
713 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
716 if (ret == -1)
718 if (errno == ENOMEM) /* not enough memory, give up on port_associate */
720 close( port_fd );
721 port_fd = -1;
723 else perror( "port_associate" ); /* should not happen */
727 static inline void remove_epoll_user( struct fd *fd, int user )
729 if (port_fd == -1) return;
731 if (pollfd[user].fd != -1)
733 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
737 static inline void main_loop_epoll(void)
739 int i, nget, ret, timeout;
740 port_event_t events[128];
742 if (port_fd == -1) return;
744 while (active_users)
746 timeout = get_next_timeout();
747 nget = 1;
749 if (!active_users) break; /* last user removed by a timeout */
750 if (port_fd == -1) break; /* an error occurred with event completion */
752 if (timeout != -1)
754 struct timespec ts;
756 ts.tv_sec = timeout / 1000;
757 ts.tv_nsec = (timeout % 1000) * 1000000;
758 ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, &ts );
760 else ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, NULL );
762 if (ret == -1) break; /* an error occurred with event completion */
764 set_current_time();
766 /* put the events into the pollfd array first, like poll does */
767 for (i = 0; i < nget; i++)
769 long user = (long)events[i].portev_user;
770 pollfd[user].revents = events[i].portev_events;
773 /* read events from the pollfd array, as set_fd_events may modify them */
774 for (i = 0; i < nget; i++)
776 long user = (long)events[i].portev_user;
777 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
778 /* if we are still interested, reassociate the fd */
779 if (pollfd[user].fd != -1) {
780 port_associate( port_fd, PORT_SOURCE_FD, pollfd[user].fd, pollfd[user].events, (void *)user );
786 #else /* HAVE_KQUEUE */
788 static inline void init_epoll(void) { }
789 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
790 static inline void remove_epoll_user( struct fd *fd, int user ) { }
791 static inline void main_loop_epoll(void) { }
793 #endif /* USE_EPOLL */
796 /* add a user in the poll array and return its index, or -1 on failure */
797 static int add_poll_user( struct fd *fd )
799 int ret;
800 if (freelist)
802 ret = freelist - poll_users;
803 freelist = (struct fd **)poll_users[ret];
805 else
807 if (nb_users == allocated_users)
809 struct fd **newusers;
810 struct pollfd *newpoll;
811 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
812 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
813 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
815 if (allocated_users)
816 poll_users = newusers;
817 else
818 free( newusers );
819 return -1;
821 poll_users = newusers;
822 pollfd = newpoll;
823 if (!allocated_users) init_epoll();
824 allocated_users = new_count;
826 ret = nb_users++;
828 pollfd[ret].fd = -1;
829 pollfd[ret].events = 0;
830 pollfd[ret].revents = 0;
831 poll_users[ret] = fd;
832 active_users++;
833 return ret;
836 /* remove a user from the poll list */
837 static void remove_poll_user( struct fd *fd, int user )
839 assert( user >= 0 );
840 assert( poll_users[user] == fd );
842 remove_epoll_user( fd, user );
843 pollfd[user].fd = -1;
844 pollfd[user].events = 0;
845 pollfd[user].revents = 0;
846 poll_users[user] = (struct fd *)freelist;
847 freelist = &poll_users[user];
848 active_users--;
851 /* process pending timeouts and return the time until the next timeout, in milliseconds */
852 static int get_next_timeout(void)
854 if (!list_empty( &timeout_list ))
856 struct list expired_list, *ptr;
858 /* first remove all expired timers from the list */
860 list_init( &expired_list );
861 while ((ptr = list_head( &timeout_list )) != NULL)
863 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
865 if (timeout->when <= current_time)
867 list_remove( &timeout->entry );
868 list_add_tail( &expired_list, &timeout->entry );
870 else break;
873 /* now call the callback for all the removed timers */
875 while ((ptr = list_head( &expired_list )) != NULL)
877 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
878 list_remove( &timeout->entry );
879 timeout->callback( timeout->private );
880 free( timeout );
883 if ((ptr = list_head( &timeout_list )) != NULL)
885 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
886 int diff = (timeout->when - current_time + 9999) / 10000;
887 if (diff < 0) diff = 0;
888 return diff;
891 return -1; /* no pending timeouts */
894 /* server main poll() loop */
895 void main_loop(void)
897 int i, ret, timeout;
899 set_current_time();
900 server_start_time = current_time;
902 main_loop_epoll();
903 /* fall through to normal poll loop */
905 while (active_users)
907 timeout = get_next_timeout();
909 if (!active_users) break; /* last user removed by a timeout */
911 ret = poll( pollfd, nb_users, timeout );
912 set_current_time();
914 if (ret > 0)
916 for (i = 0; i < nb_users; i++)
918 if (pollfd[i].revents)
920 fd_poll_event( poll_users[i], pollfd[i].revents );
921 if (!--ret) break;
929 /****************************************************************/
930 /* device functions */
932 static struct list device_hash[DEVICE_HASH_SIZE];
934 static int is_device_removable( dev_t dev, int unix_fd )
936 #if defined(linux) && defined(HAVE_FSTATFS)
937 struct statfs stfs;
939 /* check for floppy disk */
940 if (major(dev) == FLOPPY_MAJOR) return 1;
942 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
943 return (stfs.f_type == 0x9660 || /* iso9660 */
944 stfs.f_type == 0x9fa1 || /* supermount */
945 stfs.f_type == 0x15013346); /* udf */
946 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
947 struct statfs stfs;
949 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
950 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
951 #elif defined(__NetBSD__)
952 struct statvfs stfs;
954 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
955 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
956 #elif defined(sun)
957 # include <sys/dkio.h>
958 # include <sys/vtoc.h>
959 struct dk_cinfo dkinf;
960 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
961 return (dkinf.dki_ctype == DKC_CDROM ||
962 dkinf.dki_ctype == DKC_NCRFLOPPY ||
963 dkinf.dki_ctype == DKC_SMSFLOPPY ||
964 dkinf.dki_ctype == DKC_INTEL82072 ||
965 dkinf.dki_ctype == DKC_INTEL82077);
966 #else
967 return 0;
968 #endif
971 /* retrieve the device object for a given fd, creating it if needed */
972 static struct device *get_device( dev_t dev, int unix_fd )
974 struct device *device;
975 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
977 if (device_hash[hash].next)
979 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
980 if (device->dev == dev) return (struct device *)grab_object( device );
982 else list_init( &device_hash[hash] );
984 /* not found, create it */
986 if (unix_fd == -1) return NULL;
987 if ((device = alloc_object( &device_ops )))
989 device->dev = dev;
990 device->removable = is_device_removable( dev, unix_fd );
991 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
992 list_add_head( &device_hash[hash], &device->entry );
994 return device;
997 static void device_dump( struct object *obj, int verbose )
999 struct device *device = (struct device *)obj;
1000 fprintf( stderr, "Device dev=" );
1001 DUMP_LONG_LONG( device->dev );
1002 fprintf( stderr, "\n" );
1005 static void device_destroy( struct object *obj )
1007 struct device *device = (struct device *)obj;
1008 unsigned int i;
1010 for (i = 0; i < INODE_HASH_SIZE; i++)
1011 assert( list_empty(&device->inode_hash[i]) );
1013 list_remove( &device->entry ); /* remove it from the hash table */
1017 /****************************************************************/
1018 /* inode functions */
1020 /* close all pending file descriptors in the closed list */
1021 static void inode_close_pending( struct inode *inode, int keep_unlinks )
1023 struct list *ptr = list_head( &inode->closed );
1025 while (ptr)
1027 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1028 struct list *next = list_next( &inode->closed, ptr );
1030 if (fd->unix_fd != -1)
1032 close( fd->unix_fd );
1033 fd->unix_fd = -1;
1035 if (!keep_unlinks || !fd->unlink) /* get rid of it unless there's an unlink pending on that file */
1037 list_remove( ptr );
1038 free( fd->unix_name );
1039 free( fd );
1041 ptr = next;
1045 static void inode_dump( struct object *obj, int verbose )
1047 struct inode *inode = (struct inode *)obj;
1048 fprintf( stderr, "Inode device=%p ino=", inode->device );
1049 DUMP_LONG_LONG( inode->ino );
1050 fprintf( stderr, "\n" );
1053 static void inode_destroy( struct object *obj )
1055 struct inode *inode = (struct inode *)obj;
1056 struct list *ptr;
1058 assert( list_empty(&inode->open) );
1059 assert( list_empty(&inode->locks) );
1061 list_remove( &inode->entry );
1063 while ((ptr = list_head( &inode->closed )))
1065 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1066 list_remove( ptr );
1067 if (fd->unix_fd != -1) close( fd->unix_fd );
1068 if (fd->unlink)
1070 /* make sure it is still the same file */
1071 struct stat st;
1072 if (!stat( fd->unix_name, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
1074 if (S_ISDIR(st.st_mode)) rmdir( fd->unix_name );
1075 else unlink( fd->unix_name );
1078 free( fd->unix_name );
1079 free( fd );
1081 release_object( inode->device );
1084 /* retrieve the inode object for a given fd, creating it if needed */
1085 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
1087 struct device *device;
1088 struct inode *inode;
1089 unsigned int hash = ino % INODE_HASH_SIZE;
1091 if (!(device = get_device( dev, unix_fd ))) return NULL;
1093 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
1095 if (inode->ino == ino)
1097 release_object( device );
1098 return (struct inode *)grab_object( inode );
1102 /* not found, create it */
1103 if ((inode = alloc_object( &inode_ops )))
1105 inode->device = device;
1106 inode->ino = ino;
1107 list_init( &inode->open );
1108 list_init( &inode->locks );
1109 list_init( &inode->closed );
1110 list_add_head( &device->inode_hash[hash], &inode->entry );
1112 else release_object( device );
1114 return inode;
1117 /* add fd to the inode list of file descriptors to close */
1118 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1120 if (!list_empty( &inode->locks ))
1122 list_add_head( &inode->closed, &fd->entry );
1124 else if (fd->unlink) /* close the fd but keep the structure around for unlink */
1126 if (fd->unix_fd != -1) close( fd->unix_fd );
1127 fd->unix_fd = -1;
1128 list_add_head( &inode->closed, &fd->entry );
1130 else /* no locks on this inode and no unlink, get rid of the fd */
1132 if (fd->unix_fd != -1) close( fd->unix_fd );
1133 free( fd->unix_name );
1134 free( fd );
1139 /****************************************************************/
1140 /* file lock functions */
1142 static void file_lock_dump( struct object *obj, int verbose )
1144 struct file_lock *lock = (struct file_lock *)obj;
1145 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1146 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1147 DUMP_LONG_LONG( lock->start );
1148 fprintf( stderr, " end=" );
1149 DUMP_LONG_LONG( lock->end );
1150 fprintf( stderr, "\n" );
1153 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry )
1155 struct file_lock *lock = (struct file_lock *)obj;
1156 /* lock is signaled if it has lost its owner */
1157 return !lock->process;
1160 /* set (or remove) a Unix lock if possible for the given range */
1161 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1163 struct flock fl;
1165 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1166 for (;;)
1168 if (start == end) return 1; /* can't set zero-byte lock */
1169 if (start > max_unix_offset) return 1; /* ignore it */
1170 fl.l_type = type;
1171 fl.l_whence = SEEK_SET;
1172 fl.l_start = start;
1173 if (!end || end > max_unix_offset) fl.l_len = 0;
1174 else fl.l_len = end - start;
1175 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1177 switch(errno)
1179 case EACCES:
1180 /* check whether locks work at all on this file system */
1181 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1183 set_error( STATUS_FILE_LOCK_CONFLICT );
1184 return 0;
1186 /* fall through */
1187 case EIO:
1188 case ENOLCK:
1189 case ENOTSUP:
1190 /* no locking on this fs, just ignore it */
1191 fd->fs_locks = 0;
1192 return 1;
1193 case EAGAIN:
1194 set_error( STATUS_FILE_LOCK_CONFLICT );
1195 return 0;
1196 case EBADF:
1197 /* this can happen if we try to set a write lock on a read-only file */
1198 /* try to at least grab a read lock */
1199 if (fl.l_type == F_WRLCK)
1201 type = F_RDLCK;
1202 break; /* retry */
1204 set_error( STATUS_ACCESS_DENIED );
1205 return 0;
1206 #ifdef EOVERFLOW
1207 case EOVERFLOW:
1208 #endif
1209 case EINVAL:
1210 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1211 /* in that case we shrink the limit and retry */
1212 if (max_unix_offset > INT_MAX)
1214 max_unix_offset = INT_MAX;
1215 break; /* retry */
1217 /* fall through */
1218 default:
1219 file_set_error();
1220 return 0;
1225 /* check if interval [start;end) overlaps the lock */
1226 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1228 if (lock->end && start >= lock->end) return 0;
1229 if (end && lock->start >= end) return 0;
1230 return 1;
1233 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1234 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1236 struct hole
1238 struct hole *next;
1239 struct hole *prev;
1240 file_pos_t start;
1241 file_pos_t end;
1242 } *first, *cur, *next, *buffer;
1244 struct list *ptr;
1245 int count = 0;
1247 if (!fd->inode) return;
1248 if (!fd->fs_locks) return;
1249 if (start == end || start > max_unix_offset) return;
1250 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1252 /* count the number of locks overlapping the specified area */
1254 LIST_FOR_EACH( ptr, &fd->inode->locks )
1256 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1257 if (lock->start == lock->end) continue;
1258 if (lock_overlaps( lock, start, end )) count++;
1261 if (!count) /* no locks at all, we can unlock everything */
1263 set_unix_lock( fd, start, end, F_UNLCK );
1264 return;
1267 /* allocate space for the list of holes */
1268 /* max. number of holes is number of locks + 1 */
1270 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1271 first = buffer;
1272 first->next = NULL;
1273 first->prev = NULL;
1274 first->start = start;
1275 first->end = end;
1276 next = first + 1;
1278 /* build a sorted list of unlocked holes in the specified area */
1280 LIST_FOR_EACH( ptr, &fd->inode->locks )
1282 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1283 if (lock->start == lock->end) continue;
1284 if (!lock_overlaps( lock, start, end )) continue;
1286 /* go through all the holes touched by this lock */
1287 for (cur = first; cur; cur = cur->next)
1289 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1290 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1292 /* now we know that lock is overlapping hole */
1294 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1296 cur->start = lock->end;
1297 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1298 /* now hole is empty, remove it */
1299 if (cur->next) cur->next->prev = cur->prev;
1300 if (cur->prev) cur->prev->next = cur->next;
1301 else if (!(first = cur->next)) goto done; /* no more holes at all */
1303 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1305 cur->end = lock->start;
1306 assert( cur->start < cur->end );
1308 else /* lock is in the middle of hole, split hole in two */
1310 next->prev = cur;
1311 next->next = cur->next;
1312 cur->next = next;
1313 next->start = lock->end;
1314 next->end = cur->end;
1315 cur->end = lock->start;
1316 assert( next->start < next->end );
1317 assert( cur->end < next->start );
1318 next++;
1319 break; /* done with this lock */
1324 /* clear Unix locks for all the holes */
1326 for (cur = first; cur; cur = cur->next)
1327 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1329 done:
1330 free( buffer );
1333 /* create a new lock on a fd */
1334 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1336 struct file_lock *lock;
1338 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1339 lock->shared = shared;
1340 lock->start = start;
1341 lock->end = end;
1342 lock->fd = fd;
1343 lock->process = current->process;
1345 /* now try to set a Unix lock */
1346 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1348 release_object( lock );
1349 return NULL;
1351 list_add_tail( &fd->locks, &lock->fd_entry );
1352 list_add_tail( &fd->inode->locks, &lock->inode_entry );
1353 list_add_tail( &lock->process->locks, &lock->proc_entry );
1354 return lock;
1357 /* remove an existing lock */
1358 static void remove_lock( struct file_lock *lock, int remove_unix )
1360 struct inode *inode = lock->fd->inode;
1362 list_remove( &lock->fd_entry );
1363 list_remove( &lock->inode_entry );
1364 list_remove( &lock->proc_entry );
1365 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1366 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1367 lock->process = NULL;
1368 wake_up( &lock->obj, 0 );
1369 release_object( lock );
1372 /* remove all locks owned by a given process */
1373 void remove_process_locks( struct process *process )
1375 struct list *ptr;
1377 while ((ptr = list_head( &process->locks )))
1379 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1380 remove_lock( lock, 1 ); /* this removes it from the list */
1384 /* remove all locks on a given fd */
1385 static void remove_fd_locks( struct fd *fd )
1387 file_pos_t start = FILE_POS_T_MAX, end = 0;
1388 struct list *ptr;
1390 while ((ptr = list_head( &fd->locks )))
1392 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1393 if (lock->start < start) start = lock->start;
1394 if (!lock->end || lock->end > end) end = lock->end - 1;
1395 remove_lock( lock, 0 );
1397 if (start < end) remove_unix_locks( fd, start, end + 1 );
1400 /* add a lock on an fd */
1401 /* returns handle to wait on */
1402 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1404 struct list *ptr;
1405 file_pos_t end = start + count;
1407 if (!fd->inode) /* not a regular file */
1409 set_error( STATUS_INVALID_DEVICE_REQUEST );
1410 return 0;
1413 /* don't allow wrapping locks */
1414 if (end && end < start)
1416 set_error( STATUS_INVALID_PARAMETER );
1417 return 0;
1420 /* check if another lock on that file overlaps the area */
1421 LIST_FOR_EACH( ptr, &fd->inode->locks )
1423 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1424 if (!lock_overlaps( lock, start, end )) continue;
1425 if (shared && (lock->shared || lock->fd == fd)) continue;
1426 /* found one */
1427 if (!wait)
1429 set_error( STATUS_FILE_LOCK_CONFLICT );
1430 return 0;
1432 set_error( STATUS_PENDING );
1433 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1436 /* not found, add it */
1437 if (add_lock( fd, shared, start, end )) return 0;
1438 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1440 /* Unix lock conflict -> tell client to wait and retry */
1441 if (wait) set_error( STATUS_PENDING );
1443 return 0;
1446 /* remove a lock on an fd */
1447 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1449 struct list *ptr;
1450 file_pos_t end = start + count;
1452 /* find an existing lock with the exact same parameters */
1453 LIST_FOR_EACH( ptr, &fd->locks )
1455 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1456 if ((lock->start == start) && (lock->end == end))
1458 remove_lock( lock, 1 );
1459 return;
1462 set_error( STATUS_FILE_LOCK_CONFLICT );
1466 /****************************************************************/
1467 /* file descriptor functions */
1469 static void fd_dump( struct object *obj, int verbose )
1471 struct fd *fd = (struct fd *)obj;
1472 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1473 if (fd->inode) fprintf( stderr, " inode=%p unlink=%d", fd->inode, fd->closed->unlink );
1474 fprintf( stderr, "\n" );
1477 static void fd_destroy( struct object *obj )
1479 struct fd *fd = (struct fd *)obj;
1481 free_async_queue( &fd->read_q );
1482 free_async_queue( &fd->write_q );
1483 free_async_queue( &fd->wait_q );
1485 if (fd->completion) release_object( fd->completion );
1486 remove_fd_locks( fd );
1487 list_remove( &fd->inode_entry );
1488 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1489 if (fd->inode)
1491 inode_add_closed_fd( fd->inode, fd->closed );
1492 release_object( fd->inode );
1494 else /* no inode, close it right away */
1496 if (fd->unix_fd != -1) close( fd->unix_fd );
1497 free( fd->unix_name );
1501 /* check if the desired access is possible without violating */
1502 /* the sharing mode of other opens of the same file */
1503 static unsigned int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing,
1504 unsigned int open_flags, unsigned int options )
1506 /* only a few access bits are meaningful wrt sharing */
1507 const unsigned int read_access = FILE_READ_DATA | FILE_EXECUTE;
1508 const unsigned int write_access = FILE_WRITE_DATA | FILE_APPEND_DATA;
1509 const unsigned int all_access = read_access | write_access | DELETE;
1511 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1512 unsigned int existing_access = 0;
1513 struct list *ptr;
1515 fd->access = access;
1516 fd->sharing = sharing;
1518 LIST_FOR_EACH( ptr, &fd->inode->open )
1520 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1521 if (fd_ptr != fd)
1523 /* if access mode is 0, sharing mode is ignored */
1524 if (fd_ptr->access & all_access) existing_sharing &= fd_ptr->sharing;
1525 existing_access |= fd_ptr->access;
1529 if (((access & read_access) && !(existing_sharing & FILE_SHARE_READ)) ||
1530 ((access & write_access) && !(existing_sharing & FILE_SHARE_WRITE)) ||
1531 ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)))
1532 return STATUS_SHARING_VIOLATION;
1533 if (((existing_access & FILE_MAPPING_WRITE) && !(sharing & FILE_SHARE_WRITE)) ||
1534 ((existing_access & FILE_MAPPING_IMAGE) && (access & FILE_WRITE_DATA)))
1535 return STATUS_SHARING_VIOLATION;
1536 if ((existing_access & FILE_MAPPING_IMAGE) && (options & FILE_DELETE_ON_CLOSE))
1537 return STATUS_CANNOT_DELETE;
1538 if ((existing_access & FILE_MAPPING_ACCESS) && (open_flags & O_TRUNC))
1539 return STATUS_USER_MAPPED_FILE;
1540 if (!(access & all_access))
1541 return 0; /* if access mode is 0, sharing mode is ignored (except for mappings) */
1542 if (((existing_access & read_access) && !(sharing & FILE_SHARE_READ)) ||
1543 ((existing_access & write_access) && !(sharing & FILE_SHARE_WRITE)) ||
1544 ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)))
1545 return STATUS_SHARING_VIOLATION;
1546 return 0;
1549 /* set the events that select waits for on this fd */
1550 void set_fd_events( struct fd *fd, int events )
1552 int user = fd->poll_index;
1553 assert( poll_users[user] == fd );
1555 set_fd_epoll_events( fd, user, events );
1557 if (events == -1) /* stop waiting on this fd completely */
1559 pollfd[user].fd = -1;
1560 pollfd[user].events = POLLERR;
1561 pollfd[user].revents = 0;
1563 else if (pollfd[user].fd != -1 || !pollfd[user].events)
1565 pollfd[user].fd = fd->unix_fd;
1566 pollfd[user].events = events;
1570 /* prepare an fd for unmounting its corresponding device */
1571 static inline void unmount_fd( struct fd *fd )
1573 assert( fd->inode );
1575 async_wake_up( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1576 async_wake_up( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1578 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1580 if (fd->unix_fd != -1) close( fd->unix_fd );
1582 fd->unix_fd = -1;
1583 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1584 fd->closed->unix_fd = -1;
1585 fd->closed->unlink = 0;
1587 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1588 fd->fs_locks = 0;
1591 /* allocate an fd object, without setting the unix fd yet */
1592 static struct fd *alloc_fd_object(void)
1594 struct fd *fd = alloc_object( &fd_ops );
1596 if (!fd) return NULL;
1598 fd->fd_ops = NULL;
1599 fd->user = NULL;
1600 fd->inode = NULL;
1601 fd->closed = NULL;
1602 fd->access = 0;
1603 fd->options = 0;
1604 fd->sharing = 0;
1605 fd->unix_fd = -1;
1606 fd->unix_name = NULL;
1607 fd->cacheable = 0;
1608 fd->signaled = 1;
1609 fd->fs_locks = 1;
1610 fd->poll_index = -1;
1611 fd->completion = NULL;
1612 fd->comp_flags = 0;
1613 init_async_queue( &fd->read_q );
1614 init_async_queue( &fd->write_q );
1615 init_async_queue( &fd->wait_q );
1616 list_init( &fd->inode_entry );
1617 list_init( &fd->locks );
1619 if ((fd->poll_index = add_poll_user( fd )) == -1)
1621 release_object( fd );
1622 return NULL;
1624 return fd;
1627 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1628 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1630 struct fd *fd = alloc_object( &fd_ops );
1632 if (!fd) return NULL;
1634 fd->fd_ops = fd_user_ops;
1635 fd->user = user;
1636 fd->inode = NULL;
1637 fd->closed = NULL;
1638 fd->access = 0;
1639 fd->options = options;
1640 fd->sharing = 0;
1641 fd->unix_name = NULL;
1642 fd->unix_fd = -1;
1643 fd->cacheable = 0;
1644 fd->signaled = 0;
1645 fd->fs_locks = 0;
1646 fd->poll_index = -1;
1647 fd->completion = NULL;
1648 fd->comp_flags = 0;
1649 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1650 init_async_queue( &fd->read_q );
1651 init_async_queue( &fd->write_q );
1652 init_async_queue( &fd->wait_q );
1653 list_init( &fd->inode_entry );
1654 list_init( &fd->locks );
1655 return fd;
1658 /* duplicate an fd object for a different user */
1659 struct fd *dup_fd_object( struct fd *orig, unsigned int access, unsigned int sharing, unsigned int options )
1661 unsigned int err;
1662 struct fd *fd = alloc_fd_object();
1664 if (!fd) return NULL;
1666 fd->options = options;
1667 fd->cacheable = orig->cacheable;
1669 if (orig->unix_name)
1671 if (!(fd->unix_name = mem_alloc( strlen(orig->unix_name) + 1 ))) goto failed;
1672 strcpy( fd->unix_name, orig->unix_name );
1675 if (orig->inode)
1677 struct closed_fd *closed = mem_alloc( sizeof(*closed) );
1678 if (!closed) goto failed;
1679 if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1681 file_set_error();
1682 free( closed );
1683 goto failed;
1685 closed->unix_fd = fd->unix_fd;
1686 closed->unlink = 0;
1687 closed->unix_name = fd->unix_name;
1688 fd->closed = closed;
1689 fd->inode = (struct inode *)grab_object( orig->inode );
1690 list_add_head( &fd->inode->open, &fd->inode_entry );
1691 if ((err = check_sharing( fd, access, sharing, 0, options )))
1693 set_error( err );
1694 goto failed;
1697 else if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1699 file_set_error();
1700 goto failed;
1702 return fd;
1704 failed:
1705 release_object( fd );
1706 return NULL;
1709 /* find an existing fd object that can be reused for a mapping */
1710 struct fd *get_fd_object_for_mapping( struct fd *fd, unsigned int access, unsigned int sharing )
1712 struct fd *fd_ptr;
1714 if (!fd->inode) return NULL;
1716 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
1717 if (fd_ptr->access == access && fd_ptr->sharing == sharing)
1718 return (struct fd *)grab_object( fd_ptr );
1720 return NULL;
1723 /* sets the user of an fd that previously had no user */
1724 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1726 assert( fd->fd_ops == NULL );
1727 fd->fd_ops = user_ops;
1728 fd->user = user;
1731 char *dup_fd_name( struct fd *root, const char *name )
1733 char *ret;
1735 if (!root) return strdup( name );
1736 if (!root->unix_name) return NULL;
1738 /* skip . prefix */
1739 if (name[0] == '.' && (!name[1] || name[1] == '/')) name++;
1741 if ((ret = malloc( strlen(root->unix_name) + strlen(name) + 2 )))
1743 strcpy( ret, root->unix_name );
1744 if (name[0] && name[0] != '/') strcat( ret, "/" );
1745 strcat( ret, name );
1747 return ret;
1750 /* open() wrapper that returns a struct fd with no fd user set */
1751 struct fd *open_fd( struct fd *root, const char *name, int flags, mode_t *mode, unsigned int access,
1752 unsigned int sharing, unsigned int options )
1754 struct stat st;
1755 struct closed_fd *closed_fd;
1756 struct fd *fd;
1757 int root_fd = -1;
1758 int rw_mode;
1759 char *path;
1761 if (((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE)) ||
1762 ((options & FILE_DIRECTORY_FILE) && (flags & O_TRUNC)))
1764 set_error( STATUS_INVALID_PARAMETER );
1765 return NULL;
1768 if (!(fd = alloc_fd_object())) return NULL;
1770 fd->options = options;
1771 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
1773 release_object( fd );
1774 return NULL;
1777 if (root)
1779 if ((root_fd = get_unix_fd( root )) == -1) goto error;
1780 if (fchdir( root_fd ) == -1)
1782 file_set_error();
1783 root_fd = -1;
1784 goto error;
1788 /* create the directory if needed */
1789 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1791 if (mkdir( name, *mode ) == -1)
1793 if (errno != EEXIST || (flags & O_EXCL))
1795 file_set_error();
1796 goto error;
1799 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1802 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1804 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1805 else rw_mode = O_WRONLY;
1807 else rw_mode = O_RDONLY;
1809 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1811 /* if we tried to open a directory for write access, retry read-only */
1812 if (errno == EISDIR)
1814 if ((access & FILE_UNIX_WRITE_ACCESS) || (flags & O_CREAT))
1815 fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode );
1818 if (fd->unix_fd == -1)
1820 file_set_error();
1821 goto error;
1825 fd->unix_name = NULL;
1826 if ((path = dup_fd_name( root, name )))
1828 fd->unix_name = realpath( path, NULL );
1829 free( path );
1832 closed_fd->unix_fd = fd->unix_fd;
1833 closed_fd->unlink = 0;
1834 closed_fd->unix_name = fd->unix_name;
1835 fstat( fd->unix_fd, &st );
1836 *mode = st.st_mode;
1838 /* only bother with an inode for normal files and directories */
1839 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1841 unsigned int err;
1842 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1844 if (!inode)
1846 /* we can close the fd because there are no others open on the same file,
1847 * otherwise we wouldn't have failed to allocate a new inode
1849 goto error;
1851 fd->inode = inode;
1852 fd->closed = closed_fd;
1853 fd->cacheable = !inode->device->removable;
1854 list_add_head( &inode->open, &fd->inode_entry );
1855 closed_fd = NULL;
1857 /* check directory options */
1858 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1860 set_error( STATUS_NOT_A_DIRECTORY );
1861 goto error;
1863 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1865 set_error( STATUS_FILE_IS_A_DIRECTORY );
1866 goto error;
1868 if ((err = check_sharing( fd, access, sharing, flags, options )))
1870 set_error( err );
1871 goto error;
1874 /* can't unlink files if we don't have permission to access */
1875 if ((options & FILE_DELETE_ON_CLOSE) && !(flags & O_CREAT) &&
1876 !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1878 set_error( STATUS_CANNOT_DELETE );
1879 goto error;
1882 fd->closed->unlink = (options & FILE_DELETE_ON_CLOSE) ? -1 : 0;
1883 if (flags & O_TRUNC)
1885 if (S_ISDIR(st.st_mode))
1887 set_error( STATUS_OBJECT_NAME_COLLISION );
1888 goto error;
1890 ftruncate( fd->unix_fd, 0 );
1893 else /* special file */
1895 if (options & FILE_DELETE_ON_CLOSE) /* we can't unlink special files */
1897 set_error( STATUS_INVALID_PARAMETER );
1898 goto error;
1900 free( closed_fd );
1901 fd->cacheable = 1;
1903 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1904 return fd;
1906 error:
1907 release_object( fd );
1908 free( closed_fd );
1909 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1910 return NULL;
1913 /* create an fd for an anonymous file */
1914 /* if the function fails the unix fd is closed */
1915 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
1916 unsigned int options )
1918 struct fd *fd = alloc_fd_object();
1920 if (fd)
1922 set_fd_user( fd, fd_user_ops, user );
1923 fd->unix_fd = unix_fd;
1924 fd->options = options;
1925 return fd;
1927 close( unix_fd );
1928 return NULL;
1931 /* retrieve the object that is using an fd */
1932 void *get_fd_user( struct fd *fd )
1934 return fd->user;
1937 /* retrieve the opening options for the fd */
1938 unsigned int get_fd_options( struct fd *fd )
1940 return fd->options;
1943 /* check if fd is in overlapped mode */
1944 int is_fd_overlapped( struct fd *fd )
1946 return !(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
1949 /* retrieve the unix fd for an object */
1950 int get_unix_fd( struct fd *fd )
1952 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
1953 return fd->unix_fd;
1956 /* check if two file descriptors point to the same file */
1957 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1959 return fd1->inode == fd2->inode;
1962 /* allow the fd to be cached (can't be reset once set) */
1963 void allow_fd_caching( struct fd *fd )
1965 fd->cacheable = 1;
1968 /* check if fd is on a removable device */
1969 int is_fd_removable( struct fd *fd )
1971 return (fd->inode && fd->inode->device->removable);
1974 /* set or clear the fd signaled state */
1975 void set_fd_signaled( struct fd *fd, int signaled )
1977 if (fd->comp_flags & FILE_SKIP_SET_EVENT_ON_HANDLE) return;
1978 fd->signaled = signaled;
1979 if (signaled) wake_up( fd->user, 0 );
1982 /* check if fd is signaled */
1983 int is_fd_signaled( struct fd *fd )
1985 return fd->signaled;
1988 /* handler for close_handle that refuses to close fd-associated handles in other processes */
1989 int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
1991 return (!current || current->process == process);
1994 /* check if events are pending and if yes return which one(s) */
1995 int check_fd_events( struct fd *fd, int events )
1997 struct pollfd pfd;
1999 if (fd->unix_fd == -1) return POLLERR;
2000 if (fd->inode) return events; /* regular files are always signaled */
2002 pfd.fd = fd->unix_fd;
2003 pfd.events = events;
2004 if (poll( &pfd, 1, 0 ) <= 0) return 0;
2005 return pfd.revents;
2008 /* default signaled() routine for objects that poll() on an fd */
2009 int default_fd_signaled( struct object *obj, struct wait_queue_entry *entry )
2011 struct fd *fd = get_obj_fd( obj );
2012 int ret = fd->signaled;
2013 release_object( fd );
2014 return ret;
2017 /* default map_access() routine for objects that behave like an fd */
2018 unsigned int default_fd_map_access( struct object *obj, unsigned int access )
2020 if (access & GENERIC_READ) access |= FILE_GENERIC_READ;
2021 if (access & GENERIC_WRITE) access |= FILE_GENERIC_WRITE;
2022 if (access & GENERIC_EXECUTE) access |= FILE_GENERIC_EXECUTE;
2023 if (access & GENERIC_ALL) access |= FILE_ALL_ACCESS;
2024 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
2027 int default_fd_get_poll_events( struct fd *fd )
2029 int events = 0;
2031 if (async_waiting( &fd->read_q )) events |= POLLIN;
2032 if (async_waiting( &fd->write_q )) events |= POLLOUT;
2033 return events;
2036 /* default handler for poll() events */
2037 void default_poll_event( struct fd *fd, int event )
2039 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( &fd->read_q, STATUS_ALERTED );
2040 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( &fd->write_q, STATUS_ALERTED );
2042 /* if an error occurred, stop polling this fd to avoid busy-looping */
2043 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
2044 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2047 void fd_queue_async( struct fd *fd, struct async *async, int type )
2049 struct async_queue *queue;
2051 switch (type)
2053 case ASYNC_TYPE_READ:
2054 queue = &fd->read_q;
2055 break;
2056 case ASYNC_TYPE_WRITE:
2057 queue = &fd->write_q;
2058 break;
2059 case ASYNC_TYPE_WAIT:
2060 queue = &fd->wait_q;
2061 break;
2062 default:
2063 queue = NULL;
2064 assert(0);
2067 queue_async( queue, async );
2069 if (type != ASYNC_TYPE_WAIT)
2071 if (!fd->inode)
2072 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2073 else /* regular files are always ready for read and write */
2074 async_wake_up( queue, STATUS_ALERTED );
2078 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
2080 switch (type)
2082 case ASYNC_TYPE_READ:
2083 async_wake_up( &fd->read_q, status );
2084 break;
2085 case ASYNC_TYPE_WRITE:
2086 async_wake_up( &fd->write_q, status );
2087 break;
2088 case ASYNC_TYPE_WAIT:
2089 async_wake_up( &fd->wait_q, status );
2090 break;
2091 default:
2092 assert(0);
2096 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
2098 fd->fd_ops->reselect_async( fd, queue );
2101 void no_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2103 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2106 void default_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2108 fd_queue_async( fd, async, type );
2109 set_error( STATUS_PENDING );
2112 /* default reselect_async() fd routine */
2113 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
2115 if (queue == &fd->read_q || queue == &fd->write_q)
2117 int poll_events = fd->fd_ops->get_poll_events( fd );
2118 int events = check_fd_events( fd, poll_events );
2119 if (events) fd->fd_ops->poll_event( fd, events );
2120 else set_fd_events( fd, poll_events );
2124 static inline int is_valid_mounted_device( struct stat *st )
2126 #if defined(linux) || defined(__sun__)
2127 return S_ISBLK( st->st_mode );
2128 #else
2129 /* disks are char devices on *BSD */
2130 return S_ISCHR( st->st_mode );
2131 #endif
2134 /* close all Unix file descriptors on a device to allow unmounting it */
2135 static void unmount_device( struct fd *device_fd )
2137 unsigned int i;
2138 struct stat st;
2139 struct device *device;
2140 struct inode *inode;
2141 struct fd *fd;
2142 int unix_fd = get_unix_fd( device_fd );
2144 if (unix_fd == -1) return;
2146 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2148 set_error( STATUS_INVALID_PARAMETER );
2149 return;
2152 if (!(device = get_device( st.st_rdev, -1 ))) return;
2154 for (i = 0; i < INODE_HASH_SIZE; i++)
2156 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
2158 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
2160 unmount_fd( fd );
2162 inode_close_pending( inode, 0 );
2165 /* remove it from the hash table */
2166 list_remove( &device->entry );
2167 list_init( &device->entry );
2168 release_object( device );
2171 /* default read() routine */
2172 int no_fd_read( struct fd *fd, struct async *async, file_pos_t pos )
2174 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2175 return 0;
2178 /* default write() routine */
2179 int no_fd_write( struct fd *fd, struct async *async, file_pos_t pos )
2181 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2182 return 0;
2185 /* default flush() routine */
2186 int no_fd_flush( struct fd *fd, struct async *async )
2188 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2189 return 0;
2192 /* default get_file_info() routine */
2193 void no_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2195 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2198 /* default get_file_info() routine */
2199 void default_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2201 switch (info_class)
2203 case FileAccessInformation:
2205 FILE_ACCESS_INFORMATION info;
2206 if (get_reply_max_size() < sizeof(info))
2208 set_error( STATUS_INFO_LENGTH_MISMATCH );
2209 return;
2211 info.AccessFlags = get_handle_access( current->process, handle );
2212 set_reply_data( &info, sizeof(info) );
2213 break;
2215 case FileModeInformation:
2217 FILE_MODE_INFORMATION info;
2218 if (get_reply_max_size() < sizeof(info))
2220 set_error( STATUS_INFO_LENGTH_MISMATCH );
2221 return;
2223 info.Mode = fd->options & ( FILE_WRITE_THROUGH
2224 | FILE_SEQUENTIAL_ONLY
2225 | FILE_NO_INTERMEDIATE_BUFFERING
2226 | FILE_SYNCHRONOUS_IO_ALERT
2227 | FILE_SYNCHRONOUS_IO_NONALERT );
2228 set_reply_data( &info, sizeof(info) );
2229 break;
2231 case FileIoCompletionNotificationInformation:
2233 FILE_IO_COMPLETION_NOTIFICATION_INFORMATION info;
2234 if (get_reply_max_size() < sizeof(info))
2236 set_error( STATUS_INFO_LENGTH_MISMATCH );
2237 return;
2239 info.Flags = fd->comp_flags;
2240 set_reply_data( &info, sizeof(info) );
2241 break;
2243 default:
2244 set_error( STATUS_NOT_IMPLEMENTED );
2248 /* default get_volume_info() routine */
2249 void no_fd_get_volume_info( struct fd *fd, unsigned int info_class )
2251 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2254 /* default ioctl() routine */
2255 int no_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2257 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2258 return 0;
2261 /* default ioctl() routine */
2262 int default_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2264 switch(code)
2266 case FSCTL_DISMOUNT_VOLUME:
2267 unmount_device( fd );
2268 return 1;
2269 default:
2270 set_error( STATUS_NOT_SUPPORTED );
2271 return 0;
2275 /* same as get_handle_obj but retrieve the struct fd associated to the object */
2276 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
2277 unsigned int access )
2279 struct fd *fd = NULL;
2280 struct object *obj;
2282 if ((obj = get_handle_obj( process, handle, access, NULL )))
2284 fd = get_obj_fd( obj );
2285 release_object( obj );
2287 return fd;
2290 /* set disposition for the fd */
2291 static void set_fd_disposition( struct fd *fd, int unlink )
2293 struct stat st;
2295 if (!fd->inode)
2297 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2298 return;
2301 if (fd->unix_fd == -1)
2303 set_error( fd->no_fd_status );
2304 return;
2307 if (fstat( fd->unix_fd, &st ) == -1)
2309 file_set_error();
2310 return;
2313 /* can't unlink special files */
2314 if (unlink && !S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
2316 set_error( STATUS_INVALID_PARAMETER );
2317 return;
2320 /* can't unlink files we don't have permission to write */
2321 if (unlink && !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) && !S_ISDIR(st.st_mode))
2323 set_error( STATUS_CANNOT_DELETE );
2324 return;
2327 fd->closed->unlink = unlink ? 1 : 0;
2328 if (fd->options & FILE_DELETE_ON_CLOSE)
2329 fd->closed->unlink = -1;
2332 /* set new name for the fd */
2333 static void set_fd_name( struct fd *fd, struct fd *root, const char *nameptr,
2334 data_size_t len, int create_link, int replace )
2336 struct inode *inode;
2337 struct stat st, st2;
2338 char *name;
2340 if (!fd->inode || !fd->unix_name)
2342 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2343 return;
2345 if (fd->unix_fd == -1)
2347 set_error( fd->no_fd_status );
2348 return;
2351 if (!len || ((nameptr[0] == '/') ^ !root))
2353 set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
2354 return;
2356 if (!(name = mem_alloc( len + 1 ))) return;
2357 memcpy( name, nameptr, len );
2358 name[len] = 0;
2360 if (root)
2362 char *combined_name = dup_fd_name( root, name );
2363 if (!combined_name)
2365 set_error( STATUS_NO_MEMORY );
2366 goto failed;
2368 free( name );
2369 name = combined_name;
2372 /* when creating a hard link, source cannot be a dir */
2373 if (create_link && !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode ))
2375 set_error( STATUS_FILE_IS_A_DIRECTORY );
2376 goto failed;
2379 if (!stat( name, &st ))
2381 if (!fstat( fd->unix_fd, &st2 ) && st.st_ino == st2.st_ino && st.st_dev == st2.st_dev)
2383 if (create_link && !replace) set_error( STATUS_OBJECT_NAME_COLLISION );
2384 free( name );
2385 return;
2388 if (!replace)
2390 set_error( STATUS_OBJECT_NAME_COLLISION );
2391 goto failed;
2394 /* can't replace directories or special files */
2395 if (!S_ISREG( st.st_mode ))
2397 set_error( STATUS_ACCESS_DENIED );
2398 goto failed;
2401 /* can't replace an opened file */
2402 if ((inode = get_inode( st.st_dev, st.st_ino, -1 )))
2404 int is_empty = list_empty( &inode->open );
2405 release_object( inode );
2406 if (!is_empty)
2408 set_error( STATUS_ACCESS_DENIED );
2409 goto failed;
2413 /* link() expects that the target doesn't exist */
2414 /* rename() cannot replace files with directories */
2415 if (create_link || S_ISDIR( st2.st_mode ))
2417 if (unlink( name ))
2419 file_set_error();
2420 goto failed;
2425 if (create_link)
2427 if (link( fd->unix_name, name ))
2428 file_set_error();
2429 free( name );
2430 return;
2433 if (rename( fd->unix_name, name ))
2435 file_set_error();
2436 goto failed;
2439 if (is_file_executable( fd->unix_name ) != is_file_executable( name ) && !fstat( fd->unix_fd, &st ))
2441 if (is_file_executable( name ))
2442 /* set executable bit where read bit is set */
2443 st.st_mode |= (st.st_mode & 0444) >> 2;
2444 else
2445 st.st_mode &= ~0111;
2446 fchmod( fd->unix_fd, st.st_mode );
2449 free( fd->unix_name );
2450 fd->closed->unix_name = fd->unix_name = realpath( name, NULL );
2451 free( name );
2452 if (!fd->unix_name)
2453 set_error( STATUS_NO_MEMORY );
2454 return;
2456 failed:
2457 free( name );
2460 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
2462 *p_key = fd->comp_key;
2463 return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
2466 void fd_copy_completion( struct fd *src, struct fd *dst )
2468 assert( !dst->completion );
2469 dst->completion = fd_get_completion( src, &dst->comp_key );
2470 dst->comp_flags = src->comp_flags;
2473 /* flush a file buffers */
2474 DECL_HANDLER(flush)
2476 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, 0 );
2477 struct async *async;
2479 if (!fd) return;
2481 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2483 reply->event = async_handoff( async, fd->fd_ops->flush( fd, async ), NULL, 1 );
2484 release_object( async );
2486 release_object( fd );
2489 /* query file info */
2490 DECL_HANDLER(get_file_info)
2492 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2494 if (fd)
2496 fd->fd_ops->get_file_info( fd, req->handle, req->info_class );
2497 release_object( fd );
2501 /* query volume info */
2502 DECL_HANDLER(get_volume_info)
2504 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2506 if (fd)
2508 fd->fd_ops->get_volume_info( fd, req->info_class );
2509 release_object( fd );
2513 /* open a file object */
2514 DECL_HANDLER(open_file_object)
2516 struct unicode_str name = get_req_unicode_str();
2517 struct object *obj, *result, *root = NULL;
2519 if (req->rootdir && !(root = get_handle_obj( current->process, req->rootdir, 0, NULL ))) return;
2521 obj = open_named_object( root, NULL, &name, req->attributes );
2522 if (root) release_object( root );
2523 if (!obj) return;
2525 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
2527 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
2528 release_object( result );
2530 release_object( obj );
2533 /* get the Unix name from a file handle */
2534 DECL_HANDLER(get_handle_unix_name)
2536 struct fd *fd;
2538 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2540 if (fd->unix_name)
2542 data_size_t name_len = strlen( fd->unix_name );
2543 reply->name_len = name_len;
2544 if (name_len <= get_reply_max_size()) set_reply_data( fd->unix_name, name_len );
2545 else set_error( STATUS_BUFFER_OVERFLOW );
2547 else set_error( STATUS_OBJECT_TYPE_MISMATCH );
2548 release_object( fd );
2552 /* get a Unix fd to access a file */
2553 DECL_HANDLER(get_handle_fd)
2555 struct fd *fd;
2557 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2559 int unix_fd = get_unix_fd( fd );
2560 reply->cacheable = fd->cacheable;
2561 if (unix_fd != -1)
2563 reply->type = fd->fd_ops->get_fd_type( fd );
2564 reply->options = fd->options;
2565 reply->access = get_handle_access( current->process, req->handle );
2566 send_client_fd( current->process, unix_fd, req->handle );
2568 release_object( fd );
2572 /* perform a read on a file object */
2573 DECL_HANDLER(read)
2575 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_READ_DATA );
2576 struct async *async;
2578 if (!fd) return;
2580 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2582 reply->wait = async_handoff( async, fd->fd_ops->read( fd, async, req->pos ), NULL, 0 );
2583 reply->options = fd->options;
2584 release_object( async );
2586 release_object( fd );
2589 /* perform a write on a file object */
2590 DECL_HANDLER(write)
2592 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_WRITE_DATA );
2593 struct async *async;
2595 if (!fd) return;
2597 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2599 reply->wait = async_handoff( async, fd->fd_ops->write( fd, async, req->pos ), &reply->size, 0 );
2600 reply->options = fd->options;
2601 release_object( async );
2603 release_object( fd );
2606 /* perform an ioctl on a file */
2607 DECL_HANDLER(ioctl)
2609 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2610 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2611 struct async *async;
2613 if (!fd) return;
2615 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2617 reply->wait = async_handoff( async, fd->fd_ops->ioctl( fd, req->code, async ), NULL, 0 );
2618 reply->options = fd->options;
2619 release_object( async );
2621 release_object( fd );
2624 /* create / reschedule an async I/O */
2625 DECL_HANDLER(register_async)
2627 unsigned int access;
2628 struct async *async;
2629 struct fd *fd;
2631 switch(req->type)
2633 case ASYNC_TYPE_READ:
2634 access = FILE_READ_DATA;
2635 break;
2636 case ASYNC_TYPE_WRITE:
2637 access = FILE_WRITE_DATA;
2638 break;
2639 default:
2640 set_error( STATUS_INVALID_PARAMETER );
2641 return;
2644 if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2646 if (get_unix_fd( fd ) != -1 && (async = create_async( fd, current, &req->async, NULL )))
2648 fd->fd_ops->queue_async( fd, async, req->type, req->count );
2649 release_object( async );
2651 release_object( fd );
2655 /* attach completion object to a fd */
2656 DECL_HANDLER(set_completion_info)
2658 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2660 if (fd)
2662 if (is_fd_overlapped( fd ) && !fd->completion)
2664 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2665 fd->comp_key = req->ckey;
2667 else set_error( STATUS_INVALID_PARAMETER );
2668 release_object( fd );
2672 /* push new completion msg into a completion queue attached to the fd */
2673 DECL_HANDLER(add_fd_completion)
2675 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2676 if (fd)
2678 if (fd->completion && (req->async || !(fd->comp_flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS)))
2679 add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2680 release_object( fd );
2684 /* set fd completion information */
2685 DECL_HANDLER(set_fd_completion_mode)
2687 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2688 if (fd)
2690 if (is_fd_overlapped( fd ))
2692 if (req->flags & FILE_SKIP_SET_EVENT_ON_HANDLE)
2693 set_fd_signaled( fd, 0 );
2694 /* removing flags is not allowed */
2695 fd->comp_flags |= req->flags & ( FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
2696 | FILE_SKIP_SET_EVENT_ON_HANDLE
2697 | FILE_SKIP_SET_USER_EVENT_ON_FAST_IO );
2699 else
2700 set_error( STATUS_INVALID_PARAMETER );
2701 release_object( fd );
2705 /* set fd disposition information */
2706 DECL_HANDLER(set_fd_disp_info)
2708 struct fd *fd = get_handle_fd_obj( current->process, req->handle, DELETE );
2709 if (fd)
2711 set_fd_disposition( fd, req->unlink );
2712 release_object( fd );
2716 /* set fd name information */
2717 DECL_HANDLER(set_fd_name_info)
2719 struct fd *fd, *root_fd = NULL;
2721 if (req->rootdir)
2723 struct dir *root;
2725 if (!(root = get_dir_obj( current->process, req->rootdir, 0 ))) return;
2726 root_fd = get_obj_fd( (struct object *)root );
2727 release_object( root );
2728 if (!root_fd) return;
2731 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2733 set_fd_name( fd, root_fd, get_req_data(), get_req_data_size(), req->link, req->replace );
2734 release_object( fd );
2736 if (root_fd) release_object( root_fd );