quartz/vmr9: Implement IVMRFilterConfig9::GetNumberOfStreams().
[wine.git] / server / fd.c
blob39fb419f25f47663dd44518c841166db1e29f461
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 abstime_t when; /* timeout expiry */
368 timeout_callback callback; /* callback function */
369 void *private; /* callback private data */
372 static struct list abs_timeout_list = LIST_INIT(abs_timeout_list); /* sorted absolute timeouts list */
373 static struct list rel_timeout_list = LIST_INIT(rel_timeout_list); /* sorted relative timeouts list */
374 timeout_t current_time;
375 timeout_t monotonic_time;
377 void set_current_time(void)
379 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
380 struct timeval now;
381 gettimeofday( &now, NULL );
382 current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
383 monotonic_time = monotonic_counter();
386 /* add a timeout user */
387 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
389 struct timeout_user *user;
390 struct list *ptr;
392 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
393 user->when = timeout_to_abstime( when );
394 user->callback = func;
395 user->private = private;
397 /* Now insert it in the linked list */
399 if (user->when > 0)
401 LIST_FOR_EACH( ptr, &abs_timeout_list )
403 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
404 if (timeout->when >= user->when) break;
407 else
409 LIST_FOR_EACH( ptr, &rel_timeout_list )
411 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
412 if (timeout->when <= user->when) break;
415 list_add_before( ptr, &user->entry );
416 return user;
419 /* remove a timeout user */
420 void remove_timeout_user( struct timeout_user *user )
422 list_remove( &user->entry );
423 free( user );
426 /* return a text description of a timeout for debugging purposes */
427 const char *get_timeout_str( timeout_t timeout )
429 static char buffer[64];
430 long secs, nsecs;
432 if (!timeout) return "0";
433 if (timeout == TIMEOUT_INFINITE) return "infinite";
435 if (timeout < 0) /* relative */
437 secs = -timeout / TICKS_PER_SEC;
438 nsecs = -timeout % TICKS_PER_SEC;
439 sprintf( buffer, "+%ld.%07ld", secs, nsecs );
441 else /* absolute */
443 secs = (timeout - current_time) / TICKS_PER_SEC;
444 nsecs = (timeout - current_time) % TICKS_PER_SEC;
445 if (nsecs < 0)
447 nsecs += TICKS_PER_SEC;
448 secs--;
450 if (secs >= 0)
451 sprintf( buffer, "%x%08x (+%ld.%07ld)",
452 (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
453 else
454 sprintf( buffer, "%x%08x (-%ld.%07ld)",
455 (unsigned int)(timeout >> 32), (unsigned int)timeout,
456 -(secs + 1), TICKS_PER_SEC - nsecs );
458 return buffer;
462 /****************************************************************/
463 /* poll support */
465 static struct fd **poll_users; /* users array */
466 static struct pollfd *pollfd; /* poll fd array */
467 static int nb_users; /* count of array entries actually in use */
468 static int active_users; /* current number of active users */
469 static int allocated_users; /* count of allocated entries in the array */
470 static struct fd **freelist; /* list of free entries in the array */
472 static int get_next_timeout(void);
474 static inline void fd_poll_event( struct fd *fd, int event )
476 fd->fd_ops->poll_event( fd, event );
479 #ifdef USE_EPOLL
481 static int epoll_fd = -1;
483 static inline void init_epoll(void)
485 epoll_fd = epoll_create( 128 );
488 /* set the events that epoll waits for on this fd; helper for set_fd_events */
489 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
491 struct epoll_event ev;
492 int ctl;
494 if (epoll_fd == -1) return;
496 if (events == -1) /* stop waiting on this fd completely */
498 if (pollfd[user].fd == -1) return; /* already removed */
499 ctl = EPOLL_CTL_DEL;
501 else if (pollfd[user].fd == -1)
503 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
504 ctl = EPOLL_CTL_ADD;
506 else
508 if (pollfd[user].events == events) return; /* nothing to do */
509 ctl = EPOLL_CTL_MOD;
512 ev.events = events;
513 memset(&ev.data, 0, sizeof(ev.data));
514 ev.data.u32 = user;
516 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
518 if (errno == ENOMEM) /* not enough memory, give up on epoll */
520 close( epoll_fd );
521 epoll_fd = -1;
523 else perror( "epoll_ctl" ); /* should not happen */
527 static inline void remove_epoll_user( struct fd *fd, int user )
529 if (epoll_fd == -1) return;
531 if (pollfd[user].fd != -1)
533 struct epoll_event dummy;
534 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
538 static inline void main_loop_epoll(void)
540 int i, ret, timeout;
541 struct epoll_event events[128];
543 assert( POLLIN == EPOLLIN );
544 assert( POLLOUT == EPOLLOUT );
545 assert( POLLERR == EPOLLERR );
546 assert( POLLHUP == EPOLLHUP );
548 if (epoll_fd == -1) return;
550 while (active_users)
552 timeout = get_next_timeout();
554 if (!active_users) break; /* last user removed by a timeout */
555 if (epoll_fd == -1) break; /* an error occurred with epoll */
557 ret = epoll_wait( epoll_fd, events, ARRAY_SIZE( events ), timeout );
558 set_current_time();
560 /* put the events into the pollfd array first, like poll does */
561 for (i = 0; i < ret; i++)
563 int user = events[i].data.u32;
564 pollfd[user].revents = events[i].events;
567 /* read events from the pollfd array, as set_fd_events may modify them */
568 for (i = 0; i < ret; i++)
570 int user = events[i].data.u32;
571 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
576 #elif defined(HAVE_KQUEUE)
578 static int kqueue_fd = -1;
580 static inline void init_epoll(void)
582 #ifdef __APPLE__ /* kqueue support is broken in Mac OS < 10.5 */
583 int mib[2];
584 char release[32];
585 size_t len = sizeof(release);
587 mib[0] = CTL_KERN;
588 mib[1] = KERN_OSRELEASE;
589 if (sysctl( mib, 2, release, &len, NULL, 0 ) == -1) return;
590 if (atoi(release) < 9) return;
591 #endif
592 kqueue_fd = kqueue();
595 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
597 struct kevent ev[2];
599 if (kqueue_fd == -1) return;
601 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)(long)user );
602 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)(long)user );
604 if (events == -1) /* stop waiting on this fd completely */
606 if (pollfd[user].fd == -1) return; /* already removed */
607 ev[0].flags |= EV_DELETE;
608 ev[1].flags |= EV_DELETE;
610 else if (pollfd[user].fd == -1)
612 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
613 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
614 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
616 else
618 if (pollfd[user].events == events) return; /* nothing to do */
619 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
620 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
623 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
625 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
627 close( kqueue_fd );
628 kqueue_fd = -1;
630 else perror( "kevent" ); /* should not happen */
634 static inline void remove_epoll_user( struct fd *fd, int user )
636 if (kqueue_fd == -1) return;
638 if (pollfd[user].fd != -1)
640 struct kevent ev[2];
642 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
643 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
644 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
648 static inline void main_loop_epoll(void)
650 int i, ret, timeout;
651 struct kevent events[128];
653 if (kqueue_fd == -1) return;
655 while (active_users)
657 timeout = get_next_timeout();
659 if (!active_users) break; /* last user removed by a timeout */
660 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
662 if (timeout != -1)
664 struct timespec ts;
666 ts.tv_sec = timeout / 1000;
667 ts.tv_nsec = (timeout % 1000) * 1000000;
668 ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), &ts );
670 else ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), NULL );
672 set_current_time();
674 /* put the events into the pollfd array first, like poll does */
675 for (i = 0; i < ret; i++)
677 long user = (long)events[i].udata;
678 pollfd[user].revents = 0;
680 for (i = 0; i < ret; i++)
682 long user = (long)events[i].udata;
683 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
684 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
685 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
686 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
689 /* read events from the pollfd array, as set_fd_events may modify them */
690 for (i = 0; i < ret; i++)
692 long user = (long)events[i].udata;
693 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
694 pollfd[user].revents = 0;
699 #elif defined(USE_EVENT_PORTS)
701 static int port_fd = -1;
703 static inline void init_epoll(void)
705 port_fd = port_create();
708 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
710 int ret;
712 if (port_fd == -1) return;
714 if (events == -1) /* stop waiting on this fd completely */
716 if (pollfd[user].fd == -1) return; /* already removed */
717 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
719 else if (pollfd[user].fd == -1)
721 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
722 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
724 else
726 if (pollfd[user].events == events) return; /* nothing to do */
727 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
730 if (ret == -1)
732 if (errno == ENOMEM) /* not enough memory, give up on port_associate */
734 close( port_fd );
735 port_fd = -1;
737 else perror( "port_associate" ); /* should not happen */
741 static inline void remove_epoll_user( struct fd *fd, int user )
743 if (port_fd == -1) return;
745 if (pollfd[user].fd != -1)
747 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
751 static inline void main_loop_epoll(void)
753 int i, nget, ret, timeout;
754 port_event_t events[128];
756 if (port_fd == -1) return;
758 while (active_users)
760 timeout = get_next_timeout();
761 nget = 1;
763 if (!active_users) break; /* last user removed by a timeout */
764 if (port_fd == -1) break; /* an error occurred with event completion */
766 if (timeout != -1)
768 struct timespec ts;
770 ts.tv_sec = timeout / 1000;
771 ts.tv_nsec = (timeout % 1000) * 1000000;
772 ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, &ts );
774 else ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, NULL );
776 if (ret == -1) break; /* an error occurred with event completion */
778 set_current_time();
780 /* put the events into the pollfd array first, like poll does */
781 for (i = 0; i < nget; i++)
783 long user = (long)events[i].portev_user;
784 pollfd[user].revents = events[i].portev_events;
787 /* read events from the pollfd array, as set_fd_events may modify them */
788 for (i = 0; i < nget; i++)
790 long user = (long)events[i].portev_user;
791 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
792 /* if we are still interested, reassociate the fd */
793 if (pollfd[user].fd != -1) {
794 port_associate( port_fd, PORT_SOURCE_FD, pollfd[user].fd, pollfd[user].events, (void *)user );
800 #else /* HAVE_KQUEUE */
802 static inline void init_epoll(void) { }
803 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
804 static inline void remove_epoll_user( struct fd *fd, int user ) { }
805 static inline void main_loop_epoll(void) { }
807 #endif /* USE_EPOLL */
810 /* add a user in the poll array and return its index, or -1 on failure */
811 static int add_poll_user( struct fd *fd )
813 int ret;
814 if (freelist)
816 ret = freelist - poll_users;
817 freelist = (struct fd **)poll_users[ret];
819 else
821 if (nb_users == allocated_users)
823 struct fd **newusers;
824 struct pollfd *newpoll;
825 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
826 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
827 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
829 if (allocated_users)
830 poll_users = newusers;
831 else
832 free( newusers );
833 return -1;
835 poll_users = newusers;
836 pollfd = newpoll;
837 if (!allocated_users) init_epoll();
838 allocated_users = new_count;
840 ret = nb_users++;
842 pollfd[ret].fd = -1;
843 pollfd[ret].events = 0;
844 pollfd[ret].revents = 0;
845 poll_users[ret] = fd;
846 active_users++;
847 return ret;
850 /* remove a user from the poll list */
851 static void remove_poll_user( struct fd *fd, int user )
853 assert( user >= 0 );
854 assert( poll_users[user] == fd );
856 remove_epoll_user( fd, user );
857 pollfd[user].fd = -1;
858 pollfd[user].events = 0;
859 pollfd[user].revents = 0;
860 poll_users[user] = (struct fd *)freelist;
861 freelist = &poll_users[user];
862 active_users--;
865 /* process pending timeouts and return the time until the next timeout, in milliseconds */
866 static int get_next_timeout(void)
868 if (!list_empty( &abs_timeout_list ) || !list_empty( &rel_timeout_list ))
870 struct list expired_list, *ptr;
871 int ret = -1;
873 /* first remove all expired timers from the list */
875 list_init( &expired_list );
876 while ((ptr = list_head( &abs_timeout_list )) != NULL)
878 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
880 if (timeout->when <= current_time)
882 list_remove( &timeout->entry );
883 list_add_tail( &expired_list, &timeout->entry );
885 else break;
887 while ((ptr = list_head( &rel_timeout_list )) != NULL)
889 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
891 if (-timeout->when <= monotonic_time)
893 list_remove( &timeout->entry );
894 list_add_tail( &expired_list, &timeout->entry );
896 else break;
899 /* now call the callback for all the removed timers */
901 while ((ptr = list_head( &expired_list )) != NULL)
903 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
904 list_remove( &timeout->entry );
905 timeout->callback( timeout->private );
906 free( timeout );
909 if ((ptr = list_head( &abs_timeout_list )) != NULL)
911 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
912 int diff = (timeout->when - current_time + 9999) / 10000;
913 if (diff < 0) diff = 0;
914 ret = diff;
917 if ((ptr = list_head( &rel_timeout_list )) != NULL)
919 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
920 int diff = (-timeout->when - monotonic_time + 9999) / 10000;
921 if (diff < 0) diff = 0;
922 if (ret == -1 || diff < ret) ret = diff;
924 return ret;
926 return -1; /* no pending timeouts */
929 /* server main poll() loop */
930 void main_loop(void)
932 int i, ret, timeout;
934 set_current_time();
935 server_start_time = current_time;
937 main_loop_epoll();
938 /* fall through to normal poll loop */
940 while (active_users)
942 timeout = get_next_timeout();
944 if (!active_users) break; /* last user removed by a timeout */
946 ret = poll( pollfd, nb_users, timeout );
947 set_current_time();
949 if (ret > 0)
951 for (i = 0; i < nb_users; i++)
953 if (pollfd[i].revents)
955 fd_poll_event( poll_users[i], pollfd[i].revents );
956 if (!--ret) break;
964 /****************************************************************/
965 /* device functions */
967 static struct list device_hash[DEVICE_HASH_SIZE];
969 static int is_device_removable( dev_t dev, int unix_fd )
971 #if defined(linux) && defined(HAVE_FSTATFS)
972 struct statfs stfs;
974 /* check for floppy disk */
975 if (major(dev) == FLOPPY_MAJOR) return 1;
977 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
978 return (stfs.f_type == 0x9660 || /* iso9660 */
979 stfs.f_type == 0x9fa1 || /* supermount */
980 stfs.f_type == 0x15013346); /* udf */
981 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
982 struct statfs stfs;
984 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
985 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
986 #elif defined(__NetBSD__)
987 struct statvfs stfs;
989 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
990 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
991 #elif defined(sun)
992 # include <sys/dkio.h>
993 # include <sys/vtoc.h>
994 struct dk_cinfo dkinf;
995 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
996 return (dkinf.dki_ctype == DKC_CDROM ||
997 dkinf.dki_ctype == DKC_NCRFLOPPY ||
998 dkinf.dki_ctype == DKC_SMSFLOPPY ||
999 dkinf.dki_ctype == DKC_INTEL82072 ||
1000 dkinf.dki_ctype == DKC_INTEL82077);
1001 #else
1002 return 0;
1003 #endif
1006 /* retrieve the device object for a given fd, creating it if needed */
1007 static struct device *get_device( dev_t dev, int unix_fd )
1009 struct device *device;
1010 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
1012 if (device_hash[hash].next)
1014 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
1015 if (device->dev == dev) return (struct device *)grab_object( device );
1017 else list_init( &device_hash[hash] );
1019 /* not found, create it */
1021 if (unix_fd == -1) return NULL;
1022 if ((device = alloc_object( &device_ops )))
1024 device->dev = dev;
1025 device->removable = is_device_removable( dev, unix_fd );
1026 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
1027 list_add_head( &device_hash[hash], &device->entry );
1029 return device;
1032 static void device_dump( struct object *obj, int verbose )
1034 struct device *device = (struct device *)obj;
1035 fprintf( stderr, "Device dev=" );
1036 DUMP_LONG_LONG( device->dev );
1037 fprintf( stderr, "\n" );
1040 static void device_destroy( struct object *obj )
1042 struct device *device = (struct device *)obj;
1043 unsigned int i;
1045 for (i = 0; i < INODE_HASH_SIZE; i++)
1046 assert( list_empty(&device->inode_hash[i]) );
1048 list_remove( &device->entry ); /* remove it from the hash table */
1052 /****************************************************************/
1053 /* inode functions */
1055 /* close all pending file descriptors in the closed list */
1056 static void inode_close_pending( struct inode *inode, int keep_unlinks )
1058 struct list *ptr = list_head( &inode->closed );
1060 while (ptr)
1062 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1063 struct list *next = list_next( &inode->closed, ptr );
1065 if (fd->unix_fd != -1)
1067 close( fd->unix_fd );
1068 fd->unix_fd = -1;
1070 if (!keep_unlinks || !fd->unlink) /* get rid of it unless there's an unlink pending on that file */
1072 list_remove( ptr );
1073 free( fd->unix_name );
1074 free( fd );
1076 ptr = next;
1080 static void inode_dump( struct object *obj, int verbose )
1082 struct inode *inode = (struct inode *)obj;
1083 fprintf( stderr, "Inode device=%p ino=", inode->device );
1084 DUMP_LONG_LONG( inode->ino );
1085 fprintf( stderr, "\n" );
1088 static void inode_destroy( struct object *obj )
1090 struct inode *inode = (struct inode *)obj;
1091 struct list *ptr;
1093 assert( list_empty(&inode->open) );
1094 assert( list_empty(&inode->locks) );
1096 list_remove( &inode->entry );
1098 while ((ptr = list_head( &inode->closed )))
1100 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1101 list_remove( ptr );
1102 if (fd->unix_fd != -1) close( fd->unix_fd );
1103 if (fd->unlink)
1105 /* make sure it is still the same file */
1106 struct stat st;
1107 if (!stat( fd->unix_name, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
1109 if (S_ISDIR(st.st_mode)) rmdir( fd->unix_name );
1110 else unlink( fd->unix_name );
1113 free( fd->unix_name );
1114 free( fd );
1116 release_object( inode->device );
1119 /* retrieve the inode object for a given fd, creating it if needed */
1120 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
1122 struct device *device;
1123 struct inode *inode;
1124 unsigned int hash = ino % INODE_HASH_SIZE;
1126 if (!(device = get_device( dev, unix_fd ))) return NULL;
1128 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
1130 if (inode->ino == ino)
1132 release_object( device );
1133 return (struct inode *)grab_object( inode );
1137 /* not found, create it */
1138 if ((inode = alloc_object( &inode_ops )))
1140 inode->device = device;
1141 inode->ino = ino;
1142 list_init( &inode->open );
1143 list_init( &inode->locks );
1144 list_init( &inode->closed );
1145 list_add_head( &device->inode_hash[hash], &inode->entry );
1147 else release_object( device );
1149 return inode;
1152 /* add fd to the inode list of file descriptors to close */
1153 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1155 if (!list_empty( &inode->locks ))
1157 list_add_head( &inode->closed, &fd->entry );
1159 else if (fd->unlink) /* close the fd but keep the structure around for unlink */
1161 if (fd->unix_fd != -1) close( fd->unix_fd );
1162 fd->unix_fd = -1;
1163 list_add_head( &inode->closed, &fd->entry );
1165 else /* no locks on this inode and no unlink, get rid of the fd */
1167 if (fd->unix_fd != -1) close( fd->unix_fd );
1168 free( fd->unix_name );
1169 free( fd );
1174 /****************************************************************/
1175 /* file lock functions */
1177 static void file_lock_dump( struct object *obj, int verbose )
1179 struct file_lock *lock = (struct file_lock *)obj;
1180 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1181 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1182 DUMP_LONG_LONG( lock->start );
1183 fprintf( stderr, " end=" );
1184 DUMP_LONG_LONG( lock->end );
1185 fprintf( stderr, "\n" );
1188 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry )
1190 struct file_lock *lock = (struct file_lock *)obj;
1191 /* lock is signaled if it has lost its owner */
1192 return !lock->process;
1195 /* set (or remove) a Unix lock if possible for the given range */
1196 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1198 struct flock fl;
1200 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1201 for (;;)
1203 if (start == end) return 1; /* can't set zero-byte lock */
1204 if (start > max_unix_offset) return 1; /* ignore it */
1205 fl.l_type = type;
1206 fl.l_whence = SEEK_SET;
1207 fl.l_start = start;
1208 if (!end || end > max_unix_offset) fl.l_len = 0;
1209 else fl.l_len = end - start;
1210 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1212 switch(errno)
1214 case EACCES:
1215 /* check whether locks work at all on this file system */
1216 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1218 set_error( STATUS_FILE_LOCK_CONFLICT );
1219 return 0;
1221 /* fall through */
1222 case EIO:
1223 case ENOLCK:
1224 case ENOTSUP:
1225 /* no locking on this fs, just ignore it */
1226 fd->fs_locks = 0;
1227 return 1;
1228 case EAGAIN:
1229 set_error( STATUS_FILE_LOCK_CONFLICT );
1230 return 0;
1231 case EBADF:
1232 /* this can happen if we try to set a write lock on a read-only file */
1233 /* try to at least grab a read lock */
1234 if (fl.l_type == F_WRLCK)
1236 type = F_RDLCK;
1237 break; /* retry */
1239 set_error( STATUS_ACCESS_DENIED );
1240 return 0;
1241 #ifdef EOVERFLOW
1242 case EOVERFLOW:
1243 #endif
1244 case EINVAL:
1245 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1246 /* in that case we shrink the limit and retry */
1247 if (max_unix_offset > INT_MAX)
1249 max_unix_offset = INT_MAX;
1250 break; /* retry */
1252 /* fall through */
1253 default:
1254 file_set_error();
1255 return 0;
1260 /* check if interval [start;end) overlaps the lock */
1261 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1263 if (lock->end && start >= lock->end) return 0;
1264 if (end && lock->start >= end) return 0;
1265 return 1;
1268 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1269 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1271 struct hole
1273 struct hole *next;
1274 struct hole *prev;
1275 file_pos_t start;
1276 file_pos_t end;
1277 } *first, *cur, *next, *buffer;
1279 struct list *ptr;
1280 int count = 0;
1282 if (!fd->inode) return;
1283 if (!fd->fs_locks) return;
1284 if (start == end || start > max_unix_offset) return;
1285 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1287 /* count the number of locks overlapping the specified area */
1289 LIST_FOR_EACH( ptr, &fd->inode->locks )
1291 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1292 if (lock->start == lock->end) continue;
1293 if (lock_overlaps( lock, start, end )) count++;
1296 if (!count) /* no locks at all, we can unlock everything */
1298 set_unix_lock( fd, start, end, F_UNLCK );
1299 return;
1302 /* allocate space for the list of holes */
1303 /* max. number of holes is number of locks + 1 */
1305 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1306 first = buffer;
1307 first->next = NULL;
1308 first->prev = NULL;
1309 first->start = start;
1310 first->end = end;
1311 next = first + 1;
1313 /* build a sorted list of unlocked holes in the specified area */
1315 LIST_FOR_EACH( ptr, &fd->inode->locks )
1317 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1318 if (lock->start == lock->end) continue;
1319 if (!lock_overlaps( lock, start, end )) continue;
1321 /* go through all the holes touched by this lock */
1322 for (cur = first; cur; cur = cur->next)
1324 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1325 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1327 /* now we know that lock is overlapping hole */
1329 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1331 cur->start = lock->end;
1332 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1333 /* now hole is empty, remove it */
1334 if (cur->next) cur->next->prev = cur->prev;
1335 if (cur->prev) cur->prev->next = cur->next;
1336 else if (!(first = cur->next)) goto done; /* no more holes at all */
1338 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1340 cur->end = lock->start;
1341 assert( cur->start < cur->end );
1343 else /* lock is in the middle of hole, split hole in two */
1345 next->prev = cur;
1346 next->next = cur->next;
1347 cur->next = next;
1348 next->start = lock->end;
1349 next->end = cur->end;
1350 cur->end = lock->start;
1351 assert( next->start < next->end );
1352 assert( cur->end < next->start );
1353 next++;
1354 break; /* done with this lock */
1359 /* clear Unix locks for all the holes */
1361 for (cur = first; cur; cur = cur->next)
1362 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1364 done:
1365 free( buffer );
1368 /* create a new lock on a fd */
1369 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1371 struct file_lock *lock;
1373 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1374 lock->shared = shared;
1375 lock->start = start;
1376 lock->end = end;
1377 lock->fd = fd;
1378 lock->process = current->process;
1380 /* now try to set a Unix lock */
1381 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1383 release_object( lock );
1384 return NULL;
1386 list_add_tail( &fd->locks, &lock->fd_entry );
1387 list_add_tail( &fd->inode->locks, &lock->inode_entry );
1388 list_add_tail( &lock->process->locks, &lock->proc_entry );
1389 return lock;
1392 /* remove an existing lock */
1393 static void remove_lock( struct file_lock *lock, int remove_unix )
1395 struct inode *inode = lock->fd->inode;
1397 list_remove( &lock->fd_entry );
1398 list_remove( &lock->inode_entry );
1399 list_remove( &lock->proc_entry );
1400 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1401 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1402 lock->process = NULL;
1403 wake_up( &lock->obj, 0 );
1404 release_object( lock );
1407 /* remove all locks owned by a given process */
1408 void remove_process_locks( struct process *process )
1410 struct list *ptr;
1412 while ((ptr = list_head( &process->locks )))
1414 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1415 remove_lock( lock, 1 ); /* this removes it from the list */
1419 /* remove all locks on a given fd */
1420 static void remove_fd_locks( struct fd *fd )
1422 file_pos_t start = FILE_POS_T_MAX, end = 0;
1423 struct list *ptr;
1425 while ((ptr = list_head( &fd->locks )))
1427 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1428 if (lock->start < start) start = lock->start;
1429 if (!lock->end || lock->end > end) end = lock->end - 1;
1430 remove_lock( lock, 0 );
1432 if (start < end) remove_unix_locks( fd, start, end + 1 );
1435 /* add a lock on an fd */
1436 /* returns handle to wait on */
1437 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1439 struct list *ptr;
1440 file_pos_t end = start + count;
1442 if (!fd->inode) /* not a regular file */
1444 set_error( STATUS_INVALID_DEVICE_REQUEST );
1445 return 0;
1448 /* don't allow wrapping locks */
1449 if (end && end < start)
1451 set_error( STATUS_INVALID_PARAMETER );
1452 return 0;
1455 /* check if another lock on that file overlaps the area */
1456 LIST_FOR_EACH( ptr, &fd->inode->locks )
1458 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1459 if (!lock_overlaps( lock, start, end )) continue;
1460 if (shared && (lock->shared || lock->fd == fd)) continue;
1461 /* found one */
1462 if (!wait)
1464 set_error( STATUS_FILE_LOCK_CONFLICT );
1465 return 0;
1467 set_error( STATUS_PENDING );
1468 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1471 /* not found, add it */
1472 if (add_lock( fd, shared, start, end )) return 0;
1473 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1475 /* Unix lock conflict -> tell client to wait and retry */
1476 if (wait) set_error( STATUS_PENDING );
1478 return 0;
1481 /* remove a lock on an fd */
1482 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1484 struct list *ptr;
1485 file_pos_t end = start + count;
1487 /* find an existing lock with the exact same parameters */
1488 LIST_FOR_EACH( ptr, &fd->locks )
1490 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1491 if ((lock->start == start) && (lock->end == end))
1493 remove_lock( lock, 1 );
1494 return;
1497 set_error( STATUS_FILE_LOCK_CONFLICT );
1501 /****************************************************************/
1502 /* file descriptor functions */
1504 static void fd_dump( struct object *obj, int verbose )
1506 struct fd *fd = (struct fd *)obj;
1507 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1508 if (fd->inode) fprintf( stderr, " inode=%p unlink=%d", fd->inode, fd->closed->unlink );
1509 fprintf( stderr, "\n" );
1512 static void fd_destroy( struct object *obj )
1514 struct fd *fd = (struct fd *)obj;
1516 free_async_queue( &fd->read_q );
1517 free_async_queue( &fd->write_q );
1518 free_async_queue( &fd->wait_q );
1520 if (fd->completion) release_object( fd->completion );
1521 remove_fd_locks( fd );
1522 list_remove( &fd->inode_entry );
1523 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1524 if (fd->inode)
1526 inode_add_closed_fd( fd->inode, fd->closed );
1527 release_object( fd->inode );
1529 else /* no inode, close it right away */
1531 if (fd->unix_fd != -1) close( fd->unix_fd );
1532 free( fd->unix_name );
1536 /* check if the desired access is possible without violating */
1537 /* the sharing mode of other opens of the same file */
1538 static unsigned int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing,
1539 unsigned int open_flags, unsigned int options )
1541 /* only a few access bits are meaningful wrt sharing */
1542 const unsigned int read_access = FILE_READ_DATA | FILE_EXECUTE;
1543 const unsigned int write_access = FILE_WRITE_DATA | FILE_APPEND_DATA;
1544 const unsigned int all_access = read_access | write_access | DELETE;
1546 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1547 unsigned int existing_access = 0;
1548 struct list *ptr;
1550 fd->access = access;
1551 fd->sharing = sharing;
1553 LIST_FOR_EACH( ptr, &fd->inode->open )
1555 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1556 if (fd_ptr != fd)
1558 /* if access mode is 0, sharing mode is ignored */
1559 if (fd_ptr->access & all_access) existing_sharing &= fd_ptr->sharing;
1560 existing_access |= fd_ptr->access;
1564 if (((access & read_access) && !(existing_sharing & FILE_SHARE_READ)) ||
1565 ((access & write_access) && !(existing_sharing & FILE_SHARE_WRITE)) ||
1566 ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)))
1567 return STATUS_SHARING_VIOLATION;
1568 if (((existing_access & FILE_MAPPING_WRITE) && !(sharing & FILE_SHARE_WRITE)) ||
1569 ((existing_access & FILE_MAPPING_IMAGE) && (access & FILE_WRITE_DATA)))
1570 return STATUS_SHARING_VIOLATION;
1571 if ((existing_access & FILE_MAPPING_IMAGE) && (options & FILE_DELETE_ON_CLOSE))
1572 return STATUS_CANNOT_DELETE;
1573 if ((existing_access & FILE_MAPPING_ACCESS) && (open_flags & O_TRUNC))
1574 return STATUS_USER_MAPPED_FILE;
1575 if (!(access & all_access))
1576 return 0; /* if access mode is 0, sharing mode is ignored (except for mappings) */
1577 if (((existing_access & read_access) && !(sharing & FILE_SHARE_READ)) ||
1578 ((existing_access & write_access) && !(sharing & FILE_SHARE_WRITE)) ||
1579 ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)))
1580 return STATUS_SHARING_VIOLATION;
1581 return 0;
1584 /* set the events that select waits for on this fd */
1585 void set_fd_events( struct fd *fd, int events )
1587 int user = fd->poll_index;
1588 assert( poll_users[user] == fd );
1590 set_fd_epoll_events( fd, user, events );
1592 if (events == -1) /* stop waiting on this fd completely */
1594 pollfd[user].fd = -1;
1595 pollfd[user].events = POLLERR;
1596 pollfd[user].revents = 0;
1598 else if (pollfd[user].fd != -1 || !pollfd[user].events)
1600 pollfd[user].fd = fd->unix_fd;
1601 pollfd[user].events = events;
1605 /* prepare an fd for unmounting its corresponding device */
1606 static inline void unmount_fd( struct fd *fd )
1608 assert( fd->inode );
1610 async_wake_up( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1611 async_wake_up( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1613 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1615 if (fd->unix_fd != -1) close( fd->unix_fd );
1617 fd->unix_fd = -1;
1618 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1619 fd->closed->unix_fd = -1;
1620 fd->closed->unlink = 0;
1622 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1623 fd->fs_locks = 0;
1626 /* allocate an fd object, without setting the unix fd yet */
1627 static struct fd *alloc_fd_object(void)
1629 struct fd *fd = alloc_object( &fd_ops );
1631 if (!fd) return NULL;
1633 fd->fd_ops = NULL;
1634 fd->user = NULL;
1635 fd->inode = NULL;
1636 fd->closed = NULL;
1637 fd->access = 0;
1638 fd->options = 0;
1639 fd->sharing = 0;
1640 fd->unix_fd = -1;
1641 fd->unix_name = NULL;
1642 fd->cacheable = 0;
1643 fd->signaled = 1;
1644 fd->fs_locks = 1;
1645 fd->poll_index = -1;
1646 fd->completion = NULL;
1647 fd->comp_flags = 0;
1648 init_async_queue( &fd->read_q );
1649 init_async_queue( &fd->write_q );
1650 init_async_queue( &fd->wait_q );
1651 list_init( &fd->inode_entry );
1652 list_init( &fd->locks );
1654 if ((fd->poll_index = add_poll_user( fd )) == -1)
1656 release_object( fd );
1657 return NULL;
1659 return fd;
1662 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1663 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1665 struct fd *fd = alloc_object( &fd_ops );
1667 if (!fd) return NULL;
1669 fd->fd_ops = fd_user_ops;
1670 fd->user = user;
1671 fd->inode = NULL;
1672 fd->closed = NULL;
1673 fd->access = 0;
1674 fd->options = options;
1675 fd->sharing = 0;
1676 fd->unix_name = NULL;
1677 fd->unix_fd = -1;
1678 fd->cacheable = 0;
1679 fd->signaled = 0;
1680 fd->fs_locks = 0;
1681 fd->poll_index = -1;
1682 fd->completion = NULL;
1683 fd->comp_flags = 0;
1684 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1685 init_async_queue( &fd->read_q );
1686 init_async_queue( &fd->write_q );
1687 init_async_queue( &fd->wait_q );
1688 list_init( &fd->inode_entry );
1689 list_init( &fd->locks );
1690 return fd;
1693 /* duplicate an fd object for a different user */
1694 struct fd *dup_fd_object( struct fd *orig, unsigned int access, unsigned int sharing, unsigned int options )
1696 unsigned int err;
1697 struct fd *fd = alloc_fd_object();
1699 if (!fd) return NULL;
1701 fd->options = options;
1702 fd->cacheable = orig->cacheable;
1704 if (orig->unix_name)
1706 if (!(fd->unix_name = mem_alloc( strlen(orig->unix_name) + 1 ))) goto failed;
1707 strcpy( fd->unix_name, orig->unix_name );
1710 if (orig->inode)
1712 struct closed_fd *closed = mem_alloc( sizeof(*closed) );
1713 if (!closed) goto failed;
1714 if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1716 file_set_error();
1717 free( closed );
1718 goto failed;
1720 closed->unix_fd = fd->unix_fd;
1721 closed->unlink = 0;
1722 closed->unix_name = fd->unix_name;
1723 fd->closed = closed;
1724 fd->inode = (struct inode *)grab_object( orig->inode );
1725 list_add_head( &fd->inode->open, &fd->inode_entry );
1726 if ((err = check_sharing( fd, access, sharing, 0, options )))
1728 set_error( err );
1729 goto failed;
1732 else if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1734 file_set_error();
1735 goto failed;
1737 return fd;
1739 failed:
1740 release_object( fd );
1741 return NULL;
1744 /* find an existing fd object that can be reused for a mapping */
1745 struct fd *get_fd_object_for_mapping( struct fd *fd, unsigned int access, unsigned int sharing )
1747 struct fd *fd_ptr;
1749 if (!fd->inode) return NULL;
1751 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
1752 if (fd_ptr->access == access && fd_ptr->sharing == sharing)
1753 return (struct fd *)grab_object( fd_ptr );
1755 return NULL;
1758 /* sets the user of an fd that previously had no user */
1759 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1761 assert( fd->fd_ops == NULL );
1762 fd->fd_ops = user_ops;
1763 fd->user = user;
1766 char *dup_fd_name( struct fd *root, const char *name )
1768 char *ret;
1770 if (!root) return strdup( name );
1771 if (!root->unix_name) return NULL;
1773 /* skip . prefix */
1774 if (name[0] == '.' && (!name[1] || name[1] == '/')) name++;
1776 if ((ret = malloc( strlen(root->unix_name) + strlen(name) + 2 )))
1778 strcpy( ret, root->unix_name );
1779 if (name[0] && name[0] != '/') strcat( ret, "/" );
1780 strcat( ret, name );
1782 return ret;
1785 /* open() wrapper that returns a struct fd with no fd user set */
1786 struct fd *open_fd( struct fd *root, const char *name, int flags, mode_t *mode, unsigned int access,
1787 unsigned int sharing, unsigned int options )
1789 struct stat st;
1790 struct closed_fd *closed_fd;
1791 struct fd *fd;
1792 int root_fd = -1;
1793 int rw_mode;
1794 char *path;
1796 if (((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE)) ||
1797 ((options & FILE_DIRECTORY_FILE) && (flags & O_TRUNC)))
1799 set_error( STATUS_INVALID_PARAMETER );
1800 return NULL;
1803 if (!(fd = alloc_fd_object())) return NULL;
1805 fd->options = options;
1806 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
1808 release_object( fd );
1809 return NULL;
1812 if (root)
1814 if ((root_fd = get_unix_fd( root )) == -1) goto error;
1815 if (fchdir( root_fd ) == -1)
1817 file_set_error();
1818 root_fd = -1;
1819 goto error;
1823 /* create the directory if needed */
1824 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1826 if (mkdir( name, *mode ) == -1)
1828 if (errno != EEXIST || (flags & O_EXCL))
1830 file_set_error();
1831 goto error;
1834 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1837 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1839 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1840 else rw_mode = O_WRONLY;
1842 else rw_mode = O_RDONLY;
1844 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1846 /* if we tried to open a directory for write access, retry read-only */
1847 if (errno == EISDIR)
1849 if ((access & FILE_UNIX_WRITE_ACCESS) || (flags & O_CREAT))
1850 fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode );
1853 if (fd->unix_fd == -1)
1855 file_set_error();
1856 goto error;
1860 fd->unix_name = NULL;
1861 if ((path = dup_fd_name( root, name )))
1863 fd->unix_name = realpath( path, NULL );
1864 free( path );
1867 closed_fd->unix_fd = fd->unix_fd;
1868 closed_fd->unlink = 0;
1869 closed_fd->unix_name = fd->unix_name;
1870 fstat( fd->unix_fd, &st );
1871 *mode = st.st_mode;
1873 /* only bother with an inode for normal files and directories */
1874 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1876 unsigned int err;
1877 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1879 if (!inode)
1881 /* we can close the fd because there are no others open on the same file,
1882 * otherwise we wouldn't have failed to allocate a new inode
1884 goto error;
1886 fd->inode = inode;
1887 fd->closed = closed_fd;
1888 fd->cacheable = !inode->device->removable;
1889 list_add_head( &inode->open, &fd->inode_entry );
1890 closed_fd = NULL;
1892 /* check directory options */
1893 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1895 set_error( STATUS_NOT_A_DIRECTORY );
1896 goto error;
1898 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1900 set_error( STATUS_FILE_IS_A_DIRECTORY );
1901 goto error;
1903 if ((err = check_sharing( fd, access, sharing, flags, options )))
1905 set_error( err );
1906 goto error;
1909 /* can't unlink files if we don't have permission to access */
1910 if ((options & FILE_DELETE_ON_CLOSE) && !(flags & O_CREAT) &&
1911 !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1913 set_error( STATUS_CANNOT_DELETE );
1914 goto error;
1917 fd->closed->unlink = (options & FILE_DELETE_ON_CLOSE) ? -1 : 0;
1918 if (flags & O_TRUNC)
1920 if (S_ISDIR(st.st_mode))
1922 set_error( STATUS_OBJECT_NAME_COLLISION );
1923 goto error;
1925 ftruncate( fd->unix_fd, 0 );
1928 else /* special file */
1930 if (options & FILE_DELETE_ON_CLOSE) /* we can't unlink special files */
1932 set_error( STATUS_INVALID_PARAMETER );
1933 goto error;
1935 free( closed_fd );
1936 fd->cacheable = 1;
1938 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1939 return fd;
1941 error:
1942 release_object( fd );
1943 free( closed_fd );
1944 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1945 return NULL;
1948 /* create an fd for an anonymous file */
1949 /* if the function fails the unix fd is closed */
1950 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
1951 unsigned int options )
1953 struct fd *fd = alloc_fd_object();
1955 if (fd)
1957 set_fd_user( fd, fd_user_ops, user );
1958 fd->unix_fd = unix_fd;
1959 fd->options = options;
1960 return fd;
1962 close( unix_fd );
1963 return NULL;
1966 /* retrieve the object that is using an fd */
1967 void *get_fd_user( struct fd *fd )
1969 return fd->user;
1972 /* retrieve the opening options for the fd */
1973 unsigned int get_fd_options( struct fd *fd )
1975 return fd->options;
1978 /* check if fd is in overlapped mode */
1979 int is_fd_overlapped( struct fd *fd )
1981 return !(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
1984 /* retrieve the unix fd for an object */
1985 int get_unix_fd( struct fd *fd )
1987 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
1988 return fd->unix_fd;
1991 /* check if two file descriptors point to the same file */
1992 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1994 return fd1->inode == fd2->inode;
1997 /* allow the fd to be cached (can't be reset once set) */
1998 void allow_fd_caching( struct fd *fd )
2000 fd->cacheable = 1;
2003 /* check if fd is on a removable device */
2004 int is_fd_removable( struct fd *fd )
2006 return (fd->inode && fd->inode->device->removable);
2009 /* set or clear the fd signaled state */
2010 void set_fd_signaled( struct fd *fd, int signaled )
2012 if (fd->comp_flags & FILE_SKIP_SET_EVENT_ON_HANDLE) return;
2013 fd->signaled = signaled;
2014 if (signaled) wake_up( fd->user, 0 );
2017 /* check if fd is signaled */
2018 int is_fd_signaled( struct fd *fd )
2020 return fd->signaled;
2023 /* handler for close_handle that refuses to close fd-associated handles in other processes */
2024 int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
2026 return (!current || current->process == process);
2029 /* check if events are pending and if yes return which one(s) */
2030 int check_fd_events( struct fd *fd, int events )
2032 struct pollfd pfd;
2034 if (fd->unix_fd == -1) return POLLERR;
2035 if (fd->inode) return events; /* regular files are always signaled */
2037 pfd.fd = fd->unix_fd;
2038 pfd.events = events;
2039 if (poll( &pfd, 1, 0 ) <= 0) return 0;
2040 return pfd.revents;
2043 /* default signaled() routine for objects that poll() on an fd */
2044 int default_fd_signaled( struct object *obj, struct wait_queue_entry *entry )
2046 struct fd *fd = get_obj_fd( obj );
2047 int ret = fd->signaled;
2048 release_object( fd );
2049 return ret;
2052 /* default map_access() routine for objects that behave like an fd */
2053 unsigned int default_fd_map_access( struct object *obj, unsigned int access )
2055 if (access & GENERIC_READ) access |= FILE_GENERIC_READ;
2056 if (access & GENERIC_WRITE) access |= FILE_GENERIC_WRITE;
2057 if (access & GENERIC_EXECUTE) access |= FILE_GENERIC_EXECUTE;
2058 if (access & GENERIC_ALL) access |= FILE_ALL_ACCESS;
2059 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
2062 int default_fd_get_poll_events( struct fd *fd )
2064 int events = 0;
2066 if (async_waiting( &fd->read_q )) events |= POLLIN;
2067 if (async_waiting( &fd->write_q )) events |= POLLOUT;
2068 return events;
2071 /* default handler for poll() events */
2072 void default_poll_event( struct fd *fd, int event )
2074 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( &fd->read_q, STATUS_ALERTED );
2075 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( &fd->write_q, STATUS_ALERTED );
2077 /* if an error occurred, stop polling this fd to avoid busy-looping */
2078 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
2079 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2082 void fd_queue_async( struct fd *fd, struct async *async, int type )
2084 struct async_queue *queue;
2086 switch (type)
2088 case ASYNC_TYPE_READ:
2089 queue = &fd->read_q;
2090 break;
2091 case ASYNC_TYPE_WRITE:
2092 queue = &fd->write_q;
2093 break;
2094 case ASYNC_TYPE_WAIT:
2095 queue = &fd->wait_q;
2096 break;
2097 default:
2098 queue = NULL;
2099 assert(0);
2102 queue_async( queue, async );
2104 if (type != ASYNC_TYPE_WAIT)
2106 if (!fd->inode)
2107 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2108 else /* regular files are always ready for read and write */
2109 async_wake_up( queue, STATUS_ALERTED );
2113 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
2115 switch (type)
2117 case ASYNC_TYPE_READ:
2118 async_wake_up( &fd->read_q, status );
2119 break;
2120 case ASYNC_TYPE_WRITE:
2121 async_wake_up( &fd->write_q, status );
2122 break;
2123 case ASYNC_TYPE_WAIT:
2124 async_wake_up( &fd->wait_q, status );
2125 break;
2126 default:
2127 assert(0);
2131 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
2133 fd->fd_ops->reselect_async( fd, queue );
2136 void no_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2138 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2141 void default_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2143 fd_queue_async( fd, async, type );
2144 set_error( STATUS_PENDING );
2147 /* default reselect_async() fd routine */
2148 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
2150 if (queue == &fd->read_q || queue == &fd->write_q)
2152 int poll_events = fd->fd_ops->get_poll_events( fd );
2153 int events = check_fd_events( fd, poll_events );
2154 if (events) fd->fd_ops->poll_event( fd, events );
2155 else set_fd_events( fd, poll_events );
2159 static inline int is_valid_mounted_device( struct stat *st )
2161 #if defined(linux) || defined(__sun__)
2162 return S_ISBLK( st->st_mode );
2163 #else
2164 /* disks are char devices on *BSD */
2165 return S_ISCHR( st->st_mode );
2166 #endif
2169 /* close all Unix file descriptors on a device to allow unmounting it */
2170 static void unmount_device( struct fd *device_fd )
2172 unsigned int i;
2173 struct stat st;
2174 struct device *device;
2175 struct inode *inode;
2176 struct fd *fd;
2177 int unix_fd = get_unix_fd( device_fd );
2179 if (unix_fd == -1) return;
2181 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2183 set_error( STATUS_INVALID_PARAMETER );
2184 return;
2187 if (!(device = get_device( st.st_rdev, -1 ))) return;
2189 for (i = 0; i < INODE_HASH_SIZE; i++)
2191 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
2193 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
2195 unmount_fd( fd );
2197 inode_close_pending( inode, 0 );
2200 /* remove it from the hash table */
2201 list_remove( &device->entry );
2202 list_init( &device->entry );
2203 release_object( device );
2206 /* default read() routine */
2207 int no_fd_read( struct fd *fd, struct async *async, file_pos_t pos )
2209 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2210 return 0;
2213 /* default write() routine */
2214 int no_fd_write( struct fd *fd, struct async *async, file_pos_t pos )
2216 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2217 return 0;
2220 /* default flush() routine */
2221 int no_fd_flush( struct fd *fd, struct async *async )
2223 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2224 return 0;
2227 /* default get_file_info() routine */
2228 void no_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2230 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2233 /* default get_file_info() routine */
2234 void default_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2236 switch (info_class)
2238 case FileAccessInformation:
2240 FILE_ACCESS_INFORMATION info;
2241 if (get_reply_max_size() < sizeof(info))
2243 set_error( STATUS_INFO_LENGTH_MISMATCH );
2244 return;
2246 info.AccessFlags = get_handle_access( current->process, handle );
2247 set_reply_data( &info, sizeof(info) );
2248 break;
2250 case FileModeInformation:
2252 FILE_MODE_INFORMATION info;
2253 if (get_reply_max_size() < sizeof(info))
2255 set_error( STATUS_INFO_LENGTH_MISMATCH );
2256 return;
2258 info.Mode = fd->options & ( FILE_WRITE_THROUGH
2259 | FILE_SEQUENTIAL_ONLY
2260 | FILE_NO_INTERMEDIATE_BUFFERING
2261 | FILE_SYNCHRONOUS_IO_ALERT
2262 | FILE_SYNCHRONOUS_IO_NONALERT );
2263 set_reply_data( &info, sizeof(info) );
2264 break;
2266 case FileIoCompletionNotificationInformation:
2268 FILE_IO_COMPLETION_NOTIFICATION_INFORMATION info;
2269 if (get_reply_max_size() < sizeof(info))
2271 set_error( STATUS_INFO_LENGTH_MISMATCH );
2272 return;
2274 info.Flags = fd->comp_flags;
2275 set_reply_data( &info, sizeof(info) );
2276 break;
2278 default:
2279 set_error( STATUS_NOT_IMPLEMENTED );
2283 /* default get_volume_info() routine */
2284 void no_fd_get_volume_info( struct fd *fd, unsigned int info_class )
2286 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2289 /* default ioctl() routine */
2290 int no_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2292 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2293 return 0;
2296 /* default ioctl() routine */
2297 int default_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2299 switch(code)
2301 case FSCTL_DISMOUNT_VOLUME:
2302 unmount_device( fd );
2303 return 1;
2304 default:
2305 set_error( STATUS_NOT_SUPPORTED );
2306 return 0;
2310 /* same as get_handle_obj but retrieve the struct fd associated to the object */
2311 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
2312 unsigned int access )
2314 struct fd *fd = NULL;
2315 struct object *obj;
2317 if ((obj = get_handle_obj( process, handle, access, NULL )))
2319 fd = get_obj_fd( obj );
2320 release_object( obj );
2322 return fd;
2325 /* set disposition for the fd */
2326 static void set_fd_disposition( struct fd *fd, int unlink )
2328 struct stat st;
2330 if (!fd->inode)
2332 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2333 return;
2336 if (fd->unix_fd == -1)
2338 set_error( fd->no_fd_status );
2339 return;
2342 if (fstat( fd->unix_fd, &st ) == -1)
2344 file_set_error();
2345 return;
2348 /* can't unlink special files */
2349 if (unlink && !S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
2351 set_error( STATUS_INVALID_PARAMETER );
2352 return;
2355 /* can't unlink files we don't have permission to write */
2356 if (unlink && !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) && !S_ISDIR(st.st_mode))
2358 set_error( STATUS_CANNOT_DELETE );
2359 return;
2362 fd->closed->unlink = unlink ? 1 : 0;
2363 if (fd->options & FILE_DELETE_ON_CLOSE)
2364 fd->closed->unlink = -1;
2367 /* set new name for the fd */
2368 static void set_fd_name( struct fd *fd, struct fd *root, const char *nameptr,
2369 data_size_t len, int create_link, int replace )
2371 struct inode *inode;
2372 struct stat st, st2;
2373 char *name;
2375 if (!fd->inode || !fd->unix_name)
2377 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2378 return;
2380 if (fd->unix_fd == -1)
2382 set_error( fd->no_fd_status );
2383 return;
2386 if (!len || ((nameptr[0] == '/') ^ !root))
2388 set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
2389 return;
2391 if (!(name = mem_alloc( len + 1 ))) return;
2392 memcpy( name, nameptr, len );
2393 name[len] = 0;
2395 if (root)
2397 char *combined_name = dup_fd_name( root, name );
2398 if (!combined_name)
2400 set_error( STATUS_NO_MEMORY );
2401 goto failed;
2403 free( name );
2404 name = combined_name;
2407 /* when creating a hard link, source cannot be a dir */
2408 if (create_link && !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode ))
2410 set_error( STATUS_FILE_IS_A_DIRECTORY );
2411 goto failed;
2414 if (!stat( name, &st ))
2416 if (!fstat( fd->unix_fd, &st2 ) && st.st_ino == st2.st_ino && st.st_dev == st2.st_dev)
2418 if (create_link && !replace) set_error( STATUS_OBJECT_NAME_COLLISION );
2419 free( name );
2420 return;
2423 if (!replace)
2425 set_error( STATUS_OBJECT_NAME_COLLISION );
2426 goto failed;
2429 /* can't replace directories or special files */
2430 if (!S_ISREG( st.st_mode ))
2432 set_error( STATUS_ACCESS_DENIED );
2433 goto failed;
2436 /* can't replace an opened file */
2437 if ((inode = get_inode( st.st_dev, st.st_ino, -1 )))
2439 int is_empty = list_empty( &inode->open );
2440 release_object( inode );
2441 if (!is_empty)
2443 set_error( STATUS_ACCESS_DENIED );
2444 goto failed;
2448 /* link() expects that the target doesn't exist */
2449 /* rename() cannot replace files with directories */
2450 if (create_link || S_ISDIR( st2.st_mode ))
2452 if (unlink( name ))
2454 file_set_error();
2455 goto failed;
2460 if (create_link)
2462 if (link( fd->unix_name, name ))
2463 file_set_error();
2464 free( name );
2465 return;
2468 if (rename( fd->unix_name, name ))
2470 file_set_error();
2471 goto failed;
2474 if (is_file_executable( fd->unix_name ) != is_file_executable( name ) && !fstat( fd->unix_fd, &st ))
2476 if (is_file_executable( name ))
2477 /* set executable bit where read bit is set */
2478 st.st_mode |= (st.st_mode & 0444) >> 2;
2479 else
2480 st.st_mode &= ~0111;
2481 fchmod( fd->unix_fd, st.st_mode );
2484 free( fd->unix_name );
2485 fd->closed->unix_name = fd->unix_name = realpath( name, NULL );
2486 free( name );
2487 if (!fd->unix_name)
2488 set_error( STATUS_NO_MEMORY );
2489 return;
2491 failed:
2492 free( name );
2495 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
2497 *p_key = fd->comp_key;
2498 return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
2501 void fd_copy_completion( struct fd *src, struct fd *dst )
2503 assert( !dst->completion );
2504 dst->completion = fd_get_completion( src, &dst->comp_key );
2505 dst->comp_flags = src->comp_flags;
2508 /* flush a file buffers */
2509 DECL_HANDLER(flush)
2511 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, 0 );
2512 struct async *async;
2514 if (!fd) return;
2516 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2518 reply->event = async_handoff( async, fd->fd_ops->flush( fd, async ), NULL, 1 );
2519 release_object( async );
2521 release_object( fd );
2524 /* query file info */
2525 DECL_HANDLER(get_file_info)
2527 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2529 if (fd)
2531 fd->fd_ops->get_file_info( fd, req->handle, req->info_class );
2532 release_object( fd );
2536 /* query volume info */
2537 DECL_HANDLER(get_volume_info)
2539 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2541 if (fd)
2543 fd->fd_ops->get_volume_info( fd, req->info_class );
2544 release_object( fd );
2548 /* open a file object */
2549 DECL_HANDLER(open_file_object)
2551 struct unicode_str name = get_req_unicode_str();
2552 struct object *obj, *result, *root = NULL;
2554 if (req->rootdir && !(root = get_handle_obj( current->process, req->rootdir, 0, NULL ))) return;
2556 obj = open_named_object( root, NULL, &name, req->attributes );
2557 if (root) release_object( root );
2558 if (!obj) return;
2560 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
2562 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
2563 release_object( result );
2565 release_object( obj );
2568 /* get the Unix name from a file handle */
2569 DECL_HANDLER(get_handle_unix_name)
2571 struct fd *fd;
2573 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2575 if (fd->unix_name)
2577 data_size_t name_len = strlen( fd->unix_name );
2578 reply->name_len = name_len;
2579 if (name_len <= get_reply_max_size()) set_reply_data( fd->unix_name, name_len );
2580 else set_error( STATUS_BUFFER_OVERFLOW );
2582 else set_error( STATUS_OBJECT_TYPE_MISMATCH );
2583 release_object( fd );
2587 /* get a Unix fd to access a file */
2588 DECL_HANDLER(get_handle_fd)
2590 struct fd *fd;
2592 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2594 int unix_fd = get_unix_fd( fd );
2595 reply->cacheable = fd->cacheable;
2596 if (unix_fd != -1)
2598 reply->type = fd->fd_ops->get_fd_type( fd );
2599 reply->options = fd->options;
2600 reply->access = get_handle_access( current->process, req->handle );
2601 send_client_fd( current->process, unix_fd, req->handle );
2603 release_object( fd );
2607 /* perform a read on a file object */
2608 DECL_HANDLER(read)
2610 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_READ_DATA );
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->read( fd, async, req->pos ), NULL, 0 );
2618 reply->options = fd->options;
2619 release_object( async );
2621 release_object( fd );
2624 /* perform a write on a file object */
2625 DECL_HANDLER(write)
2627 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_WRITE_DATA );
2628 struct async *async;
2630 if (!fd) return;
2632 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2634 reply->wait = async_handoff( async, fd->fd_ops->write( fd, async, req->pos ), &reply->size, 0 );
2635 reply->options = fd->options;
2636 release_object( async );
2638 release_object( fd );
2641 /* perform an ioctl on a file */
2642 DECL_HANDLER(ioctl)
2644 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2645 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2646 struct async *async;
2648 if (!fd) return;
2650 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2652 reply->wait = async_handoff( async, fd->fd_ops->ioctl( fd, req->code, async ), NULL, 0 );
2653 reply->options = fd->options;
2654 release_object( async );
2656 release_object( fd );
2659 /* create / reschedule an async I/O */
2660 DECL_HANDLER(register_async)
2662 unsigned int access;
2663 struct async *async;
2664 struct fd *fd;
2666 switch(req->type)
2668 case ASYNC_TYPE_READ:
2669 access = FILE_READ_DATA;
2670 break;
2671 case ASYNC_TYPE_WRITE:
2672 access = FILE_WRITE_DATA;
2673 break;
2674 default:
2675 set_error( STATUS_INVALID_PARAMETER );
2676 return;
2679 if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2681 if (get_unix_fd( fd ) != -1 && (async = create_async( fd, current, &req->async, NULL )))
2683 fd->fd_ops->queue_async( fd, async, req->type, req->count );
2684 release_object( async );
2686 release_object( fd );
2690 /* attach completion object to a fd */
2691 DECL_HANDLER(set_completion_info)
2693 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2695 if (fd)
2697 if (is_fd_overlapped( fd ) && !fd->completion)
2699 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2700 fd->comp_key = req->ckey;
2702 else set_error( STATUS_INVALID_PARAMETER );
2703 release_object( fd );
2707 /* push new completion msg into a completion queue attached to the fd */
2708 DECL_HANDLER(add_fd_completion)
2710 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2711 if (fd)
2713 if (fd->completion && (req->async || !(fd->comp_flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS)))
2714 add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2715 release_object( fd );
2719 /* set fd completion information */
2720 DECL_HANDLER(set_fd_completion_mode)
2722 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2723 if (fd)
2725 if (is_fd_overlapped( fd ))
2727 if (req->flags & FILE_SKIP_SET_EVENT_ON_HANDLE)
2728 set_fd_signaled( fd, 0 );
2729 /* removing flags is not allowed */
2730 fd->comp_flags |= req->flags & ( FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
2731 | FILE_SKIP_SET_EVENT_ON_HANDLE
2732 | FILE_SKIP_SET_USER_EVENT_ON_FAST_IO );
2734 else
2735 set_error( STATUS_INVALID_PARAMETER );
2736 release_object( fd );
2740 /* set fd disposition information */
2741 DECL_HANDLER(set_fd_disp_info)
2743 struct fd *fd = get_handle_fd_obj( current->process, req->handle, DELETE );
2744 if (fd)
2746 set_fd_disposition( fd, req->unlink );
2747 release_object( fd );
2751 /* set fd name information */
2752 DECL_HANDLER(set_fd_name_info)
2754 struct fd *fd, *root_fd = NULL;
2756 if (req->rootdir)
2758 struct dir *root;
2760 if (!(root = get_dir_obj( current->process, req->rootdir, 0 ))) return;
2761 root_fd = get_obj_fd( (struct object *)root );
2762 release_object( root );
2763 if (!root_fd) return;
2766 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2768 set_fd_name( fd, root_fd, get_req_data(), get_req_data_size(), req->link, req->replace );
2769 release_object( fd );
2771 if (root_fd) release_object( root_fd );