widl: Add support for interfaces to SLTG typelib generator.
[wine.git] / server / fd.c
blobfc7f7be92b9a45d1044a43abe7f30060dde90ba7
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"
24 #include <assert.h>
25 #include <dirent.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 #include <poll.h>
35 #ifdef HAVE_LINUX_MAJOR_H
36 #include <linux/major.h>
37 #endif
38 #ifdef HAVE_SYS_STATVFS_H
39 #include <sys/statvfs.h>
40 #endif
41 #ifdef HAVE_SYS_VFS_H
42 /* Work around a conflict with Solaris' system list defined in sys/list.h. */
43 #define list SYSLIST
44 #define list_next SYSLIST_NEXT
45 #define list_prev SYSLIST_PREV
46 #define list_head SYSLIST_HEAD
47 #define list_tail SYSLIST_TAIL
48 #define list_move_tail SYSLIST_MOVE_TAIL
49 #define list_remove SYSLIST_REMOVE
50 #include <sys/vfs.h>
51 #undef list
52 #undef list_next
53 #undef list_prev
54 #undef list_head
55 #undef list_tail
56 #undef list_move_tail
57 #undef list_remove
58 #endif
59 #ifdef HAVE_SYS_PARAM_H
60 #include <sys/param.h>
61 #endif
62 #ifdef HAVE_SYS_MOUNT_H
63 #include <sys/mount.h>
64 #endif
65 #ifdef HAVE_SYS_STATFS_H
66 #include <sys/statfs.h>
67 #endif
68 #ifdef HAVE_SYS_SYSCTL_H
69 #include <sys/sysctl.h>
70 #endif
71 #ifdef HAVE_SYS_EVENT_H
72 #include <sys/event.h>
73 #undef LIST_INIT
74 #undef LIST_ENTRY
75 #endif
76 #ifdef HAVE_STDINT_H
77 #include <stdint.h>
78 #endif
79 #include <sys/stat.h>
80 #include <sys/time.h>
81 #ifdef MAJOR_IN_MKDEV
82 #include <sys/mkdev.h>
83 #elif defined(MAJOR_IN_SYSMACROS)
84 #include <sys/sysmacros.h>
85 #endif
86 #include <sys/types.h>
87 #include <unistd.h>
88 #ifdef HAVE_SYS_SYSCALL_H
89 #include <sys/syscall.h>
90 #endif
92 #include "ntstatus.h"
93 #define WIN32_NO_STATUS
94 #include "object.h"
95 #include "file.h"
96 #include "handle.h"
97 #include "process.h"
98 #include "request.h"
100 #include "winternl.h"
101 #include "winioctl.h"
102 #include "ddk/wdm.h"
104 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
105 # include <sys/epoll.h>
106 # define USE_EPOLL
107 #endif /* HAVE_SYS_EPOLL_H && HAVE_EPOLL_CREATE */
109 #if defined(HAVE_PORT_H) && defined(HAVE_PORT_CREATE)
110 # include <port.h>
111 # define USE_EVENT_PORTS
112 #endif /* HAVE_PORT_H && HAVE_PORT_CREATE */
114 /* Because of the stupid Posix locking semantics, we need to keep
115 * track of all file descriptors referencing a given file, and not
116 * close a single one until all the locks are gone (sigh).
119 /* file descriptor object */
121 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
122 struct closed_fd
124 struct list entry; /* entry in inode closed list */
125 int unix_fd; /* the unix file descriptor */
126 unsigned int disp_flags; /* the disposition flags */
127 char *unix_name; /* name to unlink on close, points to parent fd unix_name */
130 struct fd
132 struct object obj; /* object header */
133 const struct fd_ops *fd_ops; /* file descriptor operations */
134 struct inode *inode; /* inode that this fd belongs to */
135 struct list inode_entry; /* entry in inode fd list */
136 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
137 struct object *user; /* object using this file descriptor */
138 struct list locks; /* list of locks on this fd */
139 client_ptr_t map_addr; /* default mapping address for PE files */
140 mem_size_t map_size; /* mapping size for PE files */
141 unsigned int access; /* file access (FILE_READ_DATA etc.) */
142 unsigned int options; /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
143 unsigned int sharing; /* file sharing mode */
144 char *unix_name; /* unix file name */
145 WCHAR *nt_name; /* NT file name */
146 data_size_t nt_namelen; /* length of NT file name */
147 int unix_fd; /* unix file descriptor */
148 unsigned int no_fd_status;/* status to return when unix_fd is -1 */
149 unsigned int cacheable :1;/* can the fd be cached on the client side? */
150 unsigned int signaled :1; /* is the fd signaled? */
151 unsigned int fs_locks :1; /* can we use filesystem locks for this fd? */
152 int poll_index; /* index of fd in poll array */
153 struct async_queue read_q; /* async readers of this fd */
154 struct async_queue write_q; /* async writers of this fd */
155 struct async_queue wait_q; /* other async waiters of this fd */
156 struct completion *completion; /* completion object attached to this fd */
157 apc_param_t comp_key; /* completion key to set in completion events */
158 unsigned int comp_flags; /* completion flags */
161 static void fd_dump( struct object *obj, int verbose );
162 static void fd_destroy( struct object *obj );
164 static const struct object_ops fd_ops =
166 sizeof(struct fd), /* size */
167 &no_type, /* type */
168 fd_dump, /* dump */
169 no_add_queue, /* add_queue */
170 NULL, /* remove_queue */
171 NULL, /* signaled */
172 NULL, /* satisfied */
173 no_signal, /* signal */
174 no_get_fd, /* get_fd */
175 default_map_access, /* map_access */
176 default_get_sd, /* get_sd */
177 default_set_sd, /* set_sd */
178 no_get_full_name, /* get_full_name */
179 no_lookup_name, /* lookup_name */
180 no_link_name, /* link_name */
181 NULL, /* unlink_name */
182 no_open_file, /* open_file */
183 no_kernel_obj_list, /* get_kernel_obj_list */
184 no_close_handle, /* close_handle */
185 fd_destroy /* destroy */
188 /* device object */
190 #define DEVICE_HASH_SIZE 7
191 #define INODE_HASH_SIZE 17
193 struct device
195 struct object obj; /* object header */
196 struct list entry; /* entry in device hash list */
197 dev_t dev; /* device number */
198 int removable; /* removable device? (or -1 if unknown) */
199 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
202 static void device_dump( struct object *obj, int verbose );
203 static void device_destroy( struct object *obj );
205 static const struct object_ops device_ops =
207 sizeof(struct device), /* size */
208 &no_type, /* type */
209 device_dump, /* dump */
210 no_add_queue, /* add_queue */
211 NULL, /* remove_queue */
212 NULL, /* signaled */
213 NULL, /* satisfied */
214 no_signal, /* signal */
215 no_get_fd, /* get_fd */
216 default_map_access, /* map_access */
217 default_get_sd, /* get_sd */
218 default_set_sd, /* set_sd */
219 no_get_full_name, /* get_full_name */
220 no_lookup_name, /* lookup_name */
221 no_link_name, /* link_name */
222 NULL, /* unlink_name */
223 no_open_file, /* open_file */
224 no_kernel_obj_list, /* get_kernel_obj_list */
225 no_close_handle, /* close_handle */
226 device_destroy /* destroy */
229 /* inode object */
231 struct inode
233 struct object obj; /* object header */
234 struct list entry; /* inode hash list entry */
235 struct device *device; /* device containing this inode */
236 ino_t ino; /* inode number */
237 struct list open; /* list of open file descriptors */
238 struct list locks; /* list of file locks */
239 struct list closed; /* list of file descriptors to close at destroy time */
242 static void inode_dump( struct object *obj, int verbose );
243 static void inode_destroy( struct object *obj );
245 static const struct object_ops inode_ops =
247 sizeof(struct inode), /* size */
248 &no_type, /* type */
249 inode_dump, /* dump */
250 no_add_queue, /* add_queue */
251 NULL, /* remove_queue */
252 NULL, /* signaled */
253 NULL, /* satisfied */
254 no_signal, /* signal */
255 no_get_fd, /* get_fd */
256 default_map_access, /* map_access */
257 default_get_sd, /* get_sd */
258 default_set_sd, /* set_sd */
259 no_get_full_name, /* get_full_name */
260 no_lookup_name, /* lookup_name */
261 no_link_name, /* link_name */
262 NULL, /* unlink_name */
263 no_open_file, /* open_file */
264 no_kernel_obj_list, /* get_kernel_obj_list */
265 no_close_handle, /* close_handle */
266 inode_destroy /* destroy */
269 /* file lock object */
271 struct file_lock
273 struct object obj; /* object header */
274 struct fd *fd; /* fd owning this lock */
275 struct list fd_entry; /* entry in list of locks on a given fd */
276 struct list inode_entry; /* entry in inode list of locks */
277 int shared; /* shared lock? */
278 file_pos_t start; /* locked region is interval [start;end) */
279 file_pos_t end;
280 struct process *process; /* process owning this lock */
281 struct list proc_entry; /* entry in list of locks owned by the process */
284 static void file_lock_dump( struct object *obj, int verbose );
285 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry );
287 static const struct object_ops file_lock_ops =
289 sizeof(struct file_lock), /* size */
290 &no_type, /* type */
291 file_lock_dump, /* dump */
292 add_queue, /* add_queue */
293 remove_queue, /* remove_queue */
294 file_lock_signaled, /* signaled */
295 no_satisfied, /* satisfied */
296 no_signal, /* signal */
297 no_get_fd, /* get_fd */
298 default_map_access, /* map_access */
299 default_get_sd, /* get_sd */
300 default_set_sd, /* set_sd */
301 no_get_full_name, /* get_full_name */
302 no_lookup_name, /* lookup_name */
303 no_link_name, /* link_name */
304 NULL, /* unlink_name */
305 no_open_file, /* open_file */
306 no_kernel_obj_list, /* get_kernel_obj_list */
307 no_close_handle, /* close_handle */
308 no_destroy /* destroy */
312 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
313 #define FILE_POS_T_MAX (~(file_pos_t)0)
315 static file_pos_t max_unix_offset = OFF_T_MAX;
317 #define DUMP_LONG_LONG(val) do { \
318 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
319 fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
320 else \
321 fprintf( stderr, "%lx", (unsigned long)(val) ); \
322 } while (0)
326 /****************************************************************/
327 /* timeouts support */
329 struct timeout_user
331 struct list entry; /* entry in sorted timeout list */
332 abstime_t when; /* timeout expiry */
333 timeout_callback callback; /* callback function */
334 void *private; /* callback private data */
337 static struct list abs_timeout_list = LIST_INIT(abs_timeout_list); /* sorted absolute timeouts list */
338 static struct list rel_timeout_list = LIST_INIT(rel_timeout_list); /* sorted relative timeouts list */
339 timeout_t current_time;
340 timeout_t monotonic_time;
342 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
343 static const int user_shared_data_timeout = 16;
345 static void atomic_store_ulong(volatile ULONG *ptr, ULONG value)
347 /* on x86 there should be total store order guarantees, so volatile is
348 * enough to ensure the stores aren't reordered by the compiler, and then
349 * they will always be seen in-order from other CPUs. On other archs, we
350 * need atomic intrinsics to guarantee that. */
351 #if defined(__i386__) || defined(__x86_64__)
352 *ptr = value;
353 #else
354 __atomic_store_n(ptr, value, __ATOMIC_SEQ_CST);
355 #endif
358 static void atomic_store_long(volatile LONG *ptr, LONG value)
360 #if defined(__i386__) || defined(__x86_64__)
361 *ptr = value;
362 #else
363 __atomic_store_n(ptr, value, __ATOMIC_SEQ_CST);
364 #endif
367 static void set_user_shared_data_time(void)
369 timeout_t tick_count = monotonic_time / 10000;
370 static timeout_t last_timezone_update;
371 timeout_t timezone_bias;
372 struct tm *tm;
373 time_t now;
375 if (monotonic_time - last_timezone_update > TICKS_PER_SEC)
377 now = time( NULL );
378 tm = gmtime( &now );
379 timezone_bias = mktime( tm ) - now;
380 tm = localtime( &now );
381 if (tm->tm_isdst) timezone_bias -= 3600;
382 timezone_bias *= TICKS_PER_SEC;
384 atomic_store_long(&user_shared_data->TimeZoneBias.High2Time, timezone_bias >> 32);
385 atomic_store_ulong(&user_shared_data->TimeZoneBias.LowPart, timezone_bias);
386 atomic_store_long(&user_shared_data->TimeZoneBias.High1Time, timezone_bias >> 32);
388 last_timezone_update = monotonic_time;
391 atomic_store_long(&user_shared_data->SystemTime.High2Time, current_time >> 32);
392 atomic_store_ulong(&user_shared_data->SystemTime.LowPart, current_time);
393 atomic_store_long(&user_shared_data->SystemTime.High1Time, current_time >> 32);
395 atomic_store_long(&user_shared_data->InterruptTime.High2Time, monotonic_time >> 32);
396 atomic_store_ulong(&user_shared_data->InterruptTime.LowPart, monotonic_time);
397 atomic_store_long(&user_shared_data->InterruptTime.High1Time, monotonic_time >> 32);
399 atomic_store_long(&user_shared_data->TickCount.High2Time, tick_count >> 32);
400 atomic_store_ulong(&user_shared_data->TickCount.LowPart, tick_count);
401 atomic_store_long(&user_shared_data->TickCount.High1Time, tick_count >> 32);
402 atomic_store_ulong(&user_shared_data->TickCountLowDeprecated, tick_count);
405 void set_current_time(void)
407 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
408 struct timeval now;
409 gettimeofday( &now, NULL );
410 current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
411 monotonic_time = monotonic_counter();
412 if (user_shared_data) set_user_shared_data_time();
415 /* add a timeout user */
416 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
418 struct timeout_user *user;
419 struct list *ptr;
421 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
422 user->when = timeout_to_abstime( when );
423 user->callback = func;
424 user->private = private;
426 /* Now insert it in the linked list */
428 if (user->when > 0)
430 LIST_FOR_EACH( ptr, &abs_timeout_list )
432 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
433 if (timeout->when >= user->when) break;
436 else
438 LIST_FOR_EACH( ptr, &rel_timeout_list )
440 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
441 if (timeout->when <= user->when) break;
444 list_add_before( ptr, &user->entry );
445 return user;
448 /* remove a timeout user */
449 void remove_timeout_user( struct timeout_user *user )
451 list_remove( &user->entry );
452 free( user );
455 /* return a text description of a timeout for debugging purposes */
456 const char *get_timeout_str( timeout_t timeout )
458 static char buffer[64];
459 long secs, nsecs;
461 if (!timeout) return "0";
462 if (timeout == TIMEOUT_INFINITE) return "infinite";
464 if (timeout < 0) /* relative */
466 secs = -timeout / TICKS_PER_SEC;
467 nsecs = -timeout % TICKS_PER_SEC;
468 snprintf( buffer, sizeof(buffer), "+%ld.%07ld", secs, nsecs );
470 else /* absolute */
472 secs = (timeout - current_time) / TICKS_PER_SEC;
473 nsecs = (timeout - current_time) % TICKS_PER_SEC;
474 if (nsecs < 0)
476 nsecs += TICKS_PER_SEC;
477 secs--;
479 if (secs >= 0)
480 snprintf( buffer, sizeof(buffer), "%x%08x (+%ld.%07ld)",
481 (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
482 else
483 snprintf( buffer, sizeof(buffer), "%x%08x (-%ld.%07ld)",
484 (unsigned int)(timeout >> 32), (unsigned int)timeout,
485 -(secs + 1), TICKS_PER_SEC - nsecs );
487 return buffer;
491 /****************************************************************/
492 /* poll support */
494 static struct fd **poll_users; /* users array */
495 static struct pollfd *pollfd; /* poll fd array */
496 static int nb_users; /* count of array entries actually in use */
497 static int active_users; /* current number of active users */
498 static int allocated_users; /* count of allocated entries in the array */
499 static struct fd **freelist; /* list of free entries in the array */
501 static int get_next_timeout(void);
503 static inline void fd_poll_event( struct fd *fd, int event )
505 fd->fd_ops->poll_event( fd, event );
508 #ifdef USE_EPOLL
510 static int epoll_fd = -1;
512 static inline void init_epoll(void)
514 epoll_fd = epoll_create( 128 );
517 /* set the events that epoll waits for on this fd; helper for set_fd_events */
518 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
520 struct epoll_event ev;
521 int ctl;
523 if (epoll_fd == -1) return;
525 if (events == -1) /* stop waiting on this fd completely */
527 if (pollfd[user].fd == -1) return; /* already removed */
528 ctl = EPOLL_CTL_DEL;
530 else if (pollfd[user].fd == -1)
532 ctl = EPOLL_CTL_ADD;
534 else
536 if (pollfd[user].events == events) return; /* nothing to do */
537 ctl = EPOLL_CTL_MOD;
540 ev.events = events;
541 memset(&ev.data, 0, sizeof(ev.data));
542 ev.data.u32 = user;
544 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
546 if (errno == ENOMEM) /* not enough memory, give up on epoll */
548 close( epoll_fd );
549 epoll_fd = -1;
551 else perror( "epoll_ctl" ); /* should not happen */
555 static inline void remove_epoll_user( struct fd *fd, int user )
557 if (epoll_fd == -1) return;
559 if (pollfd[user].fd != -1)
561 struct epoll_event dummy;
562 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
566 static inline void main_loop_epoll(void)
568 int i, ret, timeout;
569 struct epoll_event events[128];
571 assert( POLLIN == EPOLLIN );
572 assert( POLLOUT == EPOLLOUT );
573 assert( POLLERR == EPOLLERR );
574 assert( POLLHUP == EPOLLHUP );
576 if (epoll_fd == -1) return;
578 while (active_users)
580 timeout = get_next_timeout();
582 if (!active_users) break; /* last user removed by a timeout */
583 if (epoll_fd == -1) break; /* an error occurred with epoll */
585 ret = epoll_wait( epoll_fd, events, ARRAY_SIZE( events ), timeout );
586 set_current_time();
588 /* put the events into the pollfd array first, like poll does */
589 for (i = 0; i < ret; i++)
591 int user = events[i].data.u32;
592 pollfd[user].revents = events[i].events;
595 /* read events from the pollfd array, as set_fd_events may modify them */
596 for (i = 0; i < ret; i++)
598 int user = events[i].data.u32;
599 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
604 #elif defined(HAVE_KQUEUE)
606 static int kqueue_fd = -1;
608 static inline void init_epoll(void)
610 kqueue_fd = kqueue();
613 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
615 struct kevent ev[2];
617 if (kqueue_fd == -1) return;
619 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)(long)user );
620 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)(long)user );
622 if (events == -1) /* stop waiting on this fd completely */
624 if (pollfd[user].fd == -1) return; /* already removed */
625 ev[0].flags |= EV_DELETE;
626 ev[1].flags |= EV_DELETE;
628 else if (pollfd[user].fd == -1)
630 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
631 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
633 else
635 if (pollfd[user].events == events) return; /* nothing to do */
636 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
637 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
640 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
642 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
644 close( kqueue_fd );
645 kqueue_fd = -1;
647 else perror( "kevent" ); /* should not happen */
651 static inline void remove_epoll_user( struct fd *fd, int user )
653 if (kqueue_fd == -1) return;
655 if (pollfd[user].fd != -1)
657 struct kevent ev[2];
659 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
660 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
661 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
665 static inline void main_loop_epoll(void)
667 int i, ret, timeout;
668 struct kevent events[128];
670 if (kqueue_fd == -1) return;
672 while (active_users)
674 timeout = get_next_timeout();
676 if (!active_users) break; /* last user removed by a timeout */
677 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
679 if (timeout != -1)
681 struct timespec ts;
683 ts.tv_sec = timeout / 1000;
684 ts.tv_nsec = (timeout % 1000) * 1000000;
685 ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), &ts );
687 else ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), NULL );
689 set_current_time();
691 /* put the events into the pollfd array first, like poll does */
692 for (i = 0; i < ret; i++)
694 long user = (long)events[i].udata;
695 pollfd[user].revents = 0;
697 for (i = 0; i < ret; i++)
699 long user = (long)events[i].udata;
700 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
701 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
702 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
703 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
706 /* read events from the pollfd array, as set_fd_events may modify them */
707 for (i = 0; i < ret; i++)
709 long user = (long)events[i].udata;
710 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
711 pollfd[user].revents = 0;
716 #elif defined(USE_EVENT_PORTS)
718 static int port_fd = -1;
720 static inline void init_epoll(void)
722 port_fd = port_create();
725 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
727 int ret;
729 if (port_fd == -1) return;
731 if (events == -1) /* stop waiting on this fd completely */
733 if (pollfd[user].fd == -1) return; /* already removed */
734 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
736 else if (pollfd[user].fd == -1)
738 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
740 else
742 if (pollfd[user].events == events) return; /* nothing to do */
743 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
746 if (ret == -1)
748 if (errno == ENOMEM) /* not enough memory, give up on port_associate */
750 close( port_fd );
751 port_fd = -1;
753 else perror( "port_associate" ); /* should not happen */
757 static inline void remove_epoll_user( struct fd *fd, int user )
759 if (port_fd == -1) return;
761 if (pollfd[user].fd != -1)
763 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
767 static inline void main_loop_epoll(void)
769 int i, nget, ret, timeout;
770 port_event_t events[128];
772 if (port_fd == -1) return;
774 while (active_users)
776 timeout = get_next_timeout();
777 nget = 1;
779 if (!active_users) break; /* last user removed by a timeout */
780 if (port_fd == -1) break; /* an error occurred with event completion */
782 if (timeout != -1)
784 struct timespec ts;
786 ts.tv_sec = timeout / 1000;
787 ts.tv_nsec = (timeout % 1000) * 1000000;
788 ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, &ts );
790 else ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, NULL );
792 if (ret == -1) break; /* an error occurred with event completion */
794 set_current_time();
796 /* put the events into the pollfd array first, like poll does */
797 for (i = 0; i < nget; i++)
799 long user = (long)events[i].portev_user;
800 pollfd[user].revents = events[i].portev_events;
803 /* read events from the pollfd array, as set_fd_events may modify them */
804 for (i = 0; i < nget; i++)
806 long user = (long)events[i].portev_user;
807 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
808 /* if we are still interested, reassociate the fd */
809 if (pollfd[user].fd != -1) {
810 port_associate( port_fd, PORT_SOURCE_FD, pollfd[user].fd, pollfd[user].events, (void *)user );
816 #else /* HAVE_KQUEUE */
818 static inline void init_epoll(void) { }
819 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
820 static inline void remove_epoll_user( struct fd *fd, int user ) { }
821 static inline void main_loop_epoll(void) { }
823 #endif /* USE_EPOLL */
826 /* add a user in the poll array and return its index, or -1 on failure */
827 static int add_poll_user( struct fd *fd )
829 int ret;
830 if (freelist)
832 ret = freelist - poll_users;
833 freelist = (struct fd **)poll_users[ret];
835 else
837 if (nb_users == allocated_users)
839 struct fd **newusers;
840 struct pollfd *newpoll;
841 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
842 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
843 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
845 if (allocated_users)
846 poll_users = newusers;
847 else
848 free( newusers );
849 return -1;
851 poll_users = newusers;
852 pollfd = newpoll;
853 if (!allocated_users) init_epoll();
854 allocated_users = new_count;
856 ret = nb_users++;
858 pollfd[ret].fd = -1;
859 pollfd[ret].events = 0;
860 pollfd[ret].revents = 0;
861 poll_users[ret] = fd;
862 active_users++;
863 return ret;
866 /* remove a user from the poll list */
867 static void remove_poll_user( struct fd *fd, int user )
869 assert( user >= 0 );
870 assert( poll_users[user] == fd );
872 remove_epoll_user( fd, user );
873 pollfd[user].fd = -1;
874 pollfd[user].events = 0;
875 pollfd[user].revents = 0;
876 poll_users[user] = (struct fd *)freelist;
877 freelist = &poll_users[user];
878 active_users--;
881 /* process pending timeouts and return the time until the next timeout, in milliseconds */
882 static int get_next_timeout(void)
884 int ret = user_shared_data ? user_shared_data_timeout : -1;
886 if (!list_empty( &abs_timeout_list ) || !list_empty( &rel_timeout_list ))
888 struct list expired_list, *ptr;
890 /* first remove all expired timers from the list */
892 list_init( &expired_list );
893 while ((ptr = list_head( &abs_timeout_list )) != NULL)
895 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
897 if (timeout->when <= current_time)
899 list_remove( &timeout->entry );
900 list_add_tail( &expired_list, &timeout->entry );
902 else break;
904 while ((ptr = list_head( &rel_timeout_list )) != NULL)
906 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
908 if (-timeout->when <= monotonic_time)
910 list_remove( &timeout->entry );
911 list_add_tail( &expired_list, &timeout->entry );
913 else break;
916 /* now call the callback for all the removed timers */
918 while ((ptr = list_head( &expired_list )) != NULL)
920 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
921 list_remove( &timeout->entry );
922 timeout->callback( timeout->private );
923 free( timeout );
926 if ((ptr = list_head( &abs_timeout_list )) != NULL)
928 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
929 timeout_t diff = (timeout->when - current_time + 9999) / 10000;
930 if (diff > INT_MAX) diff = INT_MAX;
931 else if (diff < 0) diff = 0;
932 if (ret == -1 || diff < ret) ret = diff;
935 if ((ptr = list_head( &rel_timeout_list )) != NULL)
937 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
938 timeout_t diff = (-timeout->when - monotonic_time + 9999) / 10000;
939 if (diff > INT_MAX) diff = INT_MAX;
940 else if (diff < 0) diff = 0;
941 if (ret == -1 || diff < ret) ret = diff;
944 return ret;
947 /* server main poll() loop */
948 void main_loop(void)
950 int i, ret, timeout;
952 set_current_time();
953 server_start_time = current_time;
955 main_loop_epoll();
956 /* fall through to normal poll loop */
958 while (active_users)
960 timeout = get_next_timeout();
962 if (!active_users) break; /* last user removed by a timeout */
964 ret = poll( pollfd, nb_users, timeout );
965 set_current_time();
967 if (ret > 0)
969 for (i = 0; i < nb_users; i++)
971 if (pollfd[i].revents)
973 fd_poll_event( poll_users[i], pollfd[i].revents );
974 if (!--ret) break;
982 /****************************************************************/
983 /* device functions */
985 static struct list device_hash[DEVICE_HASH_SIZE];
987 static int is_device_removable( dev_t dev, int unix_fd )
989 #if defined(linux) && defined(HAVE_FSTATFS)
990 struct statfs stfs;
992 /* check for floppy disk */
993 if (major(dev) == FLOPPY_MAJOR) return 1;
995 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
996 return (stfs.f_type == 0x9660 || /* iso9660 */
997 stfs.f_type == 0x9fa1 || /* supermount */
998 stfs.f_type == 0x15013346); /* udf */
999 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
1000 struct statfs stfs;
1002 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
1003 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
1004 #elif defined(__NetBSD__)
1005 struct statvfs stfs;
1007 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
1008 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
1009 #elif defined(sun)
1010 # include <sys/dkio.h>
1011 # include <sys/vtoc.h>
1012 struct dk_cinfo dkinf;
1013 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
1014 return (dkinf.dki_ctype == DKC_CDROM ||
1015 dkinf.dki_ctype == DKC_NCRFLOPPY ||
1016 dkinf.dki_ctype == DKC_SMSFLOPPY ||
1017 dkinf.dki_ctype == DKC_INTEL82072 ||
1018 dkinf.dki_ctype == DKC_INTEL82077);
1019 #else
1020 return 0;
1021 #endif
1024 /* retrieve the device object for a given fd, creating it if needed */
1025 static struct device *get_device( dev_t dev, int unix_fd )
1027 struct device *device;
1028 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
1030 if (device_hash[hash].next)
1032 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
1033 if (device->dev == dev) return (struct device *)grab_object( device );
1035 else list_init( &device_hash[hash] );
1037 /* not found, create it */
1039 if (unix_fd == -1) return NULL;
1040 if ((device = alloc_object( &device_ops )))
1042 device->dev = dev;
1043 device->removable = is_device_removable( dev, unix_fd );
1044 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
1045 list_add_head( &device_hash[hash], &device->entry );
1047 return device;
1050 static void device_dump( struct object *obj, int verbose )
1052 struct device *device = (struct device *)obj;
1053 fprintf( stderr, "Device dev=" );
1054 DUMP_LONG_LONG( device->dev );
1055 fprintf( stderr, "\n" );
1058 static void device_destroy( struct object *obj )
1060 struct device *device = (struct device *)obj;
1061 unsigned int i;
1063 for (i = 0; i < INODE_HASH_SIZE; i++)
1064 assert( list_empty(&device->inode_hash[i]) );
1066 list_remove( &device->entry ); /* remove it from the hash table */
1069 /****************************************************************/
1070 /* inode functions */
1072 static void unlink_closed_fd( struct inode *inode, struct closed_fd *fd )
1074 /* make sure it is still the same file */
1075 struct stat st;
1076 if (!stat( fd->unix_name, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
1078 if (S_ISDIR(st.st_mode)) rmdir( fd->unix_name );
1079 else unlink( fd->unix_name );
1083 /* close all pending file descriptors in the closed list */
1084 static void inode_close_pending( struct inode *inode, int keep_unlinks )
1086 struct list *ptr = list_head( &inode->closed );
1088 while (ptr)
1090 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1091 struct list *next = list_next( &inode->closed, ptr );
1093 if (fd->unix_fd != -1)
1095 close( fd->unix_fd );
1096 fd->unix_fd = -1;
1099 /* get rid of it unless there's an unlink pending on that file */
1100 if (!keep_unlinks || !(fd->disp_flags & FILE_DISPOSITION_DELETE))
1102 list_remove( ptr );
1103 free( fd->unix_name );
1104 free( fd );
1106 ptr = next;
1110 static void inode_dump( struct object *obj, int verbose )
1112 struct inode *inode = (struct inode *)obj;
1113 fprintf( stderr, "Inode device=%p ino=", inode->device );
1114 DUMP_LONG_LONG( inode->ino );
1115 fprintf( stderr, "\n" );
1118 static void inode_destroy( struct object *obj )
1120 struct inode *inode = (struct inode *)obj;
1121 struct list *ptr;
1123 assert( list_empty(&inode->open) );
1124 assert( list_empty(&inode->locks) );
1126 list_remove( &inode->entry );
1128 while ((ptr = list_head( &inode->closed )))
1130 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1131 list_remove( ptr );
1132 if (fd->unix_fd != -1) close( fd->unix_fd );
1133 if (fd->disp_flags & FILE_DISPOSITION_DELETE)
1134 unlink_closed_fd( inode, fd );
1135 free( fd->unix_name );
1136 free( fd );
1138 release_object( inode->device );
1141 /* retrieve the inode object for a given fd, creating it if needed */
1142 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
1144 struct device *device;
1145 struct inode *inode;
1146 unsigned int hash = ino % INODE_HASH_SIZE;
1148 if (!(device = get_device( dev, unix_fd ))) return NULL;
1150 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
1152 if (inode->ino == ino)
1154 release_object( device );
1155 return (struct inode *)grab_object( inode );
1159 /* not found, create it */
1160 if ((inode = alloc_object( &inode_ops )))
1162 inode->device = device;
1163 inode->ino = ino;
1164 list_init( &inode->open );
1165 list_init( &inode->locks );
1166 list_init( &inode->closed );
1167 list_add_head( &device->inode_hash[hash], &inode->entry );
1169 else release_object( device );
1171 return inode;
1174 /* add fd to the inode list of file descriptors to close */
1175 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1177 if (!list_empty( &inode->locks ))
1179 list_add_head( &inode->closed, &fd->entry );
1181 else if ((fd->disp_flags & FILE_DISPOSITION_DELETE) &&
1182 (fd->disp_flags & FILE_DISPOSITION_POSIX_SEMANTICS))
1184 /* close the fd and unlink it at once */
1185 if (fd->unix_fd != -1) close( fd->unix_fd );
1186 unlink_closed_fd( inode, fd );
1187 free( fd->unix_name );
1188 free( fd );
1190 else if (fd->disp_flags & FILE_DISPOSITION_DELETE)
1192 /* close the fd but keep the structure around for unlink */
1193 if (fd->unix_fd != -1) close( fd->unix_fd );
1194 fd->unix_fd = -1;
1195 list_add_head( &inode->closed, &fd->entry );
1197 else /* no locks on this inode and no unlink, get rid of the fd */
1199 if (fd->unix_fd != -1) close( fd->unix_fd );
1200 free( fd->unix_name );
1201 free( fd );
1206 /****************************************************************/
1207 /* file lock functions */
1209 static void file_lock_dump( struct object *obj, int verbose )
1211 struct file_lock *lock = (struct file_lock *)obj;
1212 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1213 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1214 DUMP_LONG_LONG( lock->start );
1215 fprintf( stderr, " end=" );
1216 DUMP_LONG_LONG( lock->end );
1217 fprintf( stderr, "\n" );
1220 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry )
1222 struct file_lock *lock = (struct file_lock *)obj;
1223 /* lock is signaled if it has lost its owner */
1224 return !lock->process;
1227 /* set (or remove) a Unix lock if possible for the given range */
1228 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1230 struct flock fl;
1232 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1233 for (;;)
1235 if (start == end) return 1; /* can't set zero-byte lock */
1236 if (start > max_unix_offset) return 1; /* ignore it */
1237 fl.l_type = type;
1238 fl.l_whence = SEEK_SET;
1239 fl.l_start = start;
1240 if (!end || end > max_unix_offset) fl.l_len = 0;
1241 else fl.l_len = end - start;
1242 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1244 switch(errno)
1246 case EACCES:
1247 /* check whether locks work at all on this file system */
1248 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1250 set_error( STATUS_FILE_LOCK_CONFLICT );
1251 return 0;
1253 /* fall through */
1254 case EIO:
1255 case ENOLCK:
1256 case ENOTSUP:
1257 /* no locking on this fs, just ignore it */
1258 fd->fs_locks = 0;
1259 return 1;
1260 case EAGAIN:
1261 set_error( STATUS_FILE_LOCK_CONFLICT );
1262 return 0;
1263 case EBADF:
1264 /* this can happen if we try to set a write lock on a read-only file */
1265 /* try to at least grab a read lock */
1266 if (fl.l_type == F_WRLCK)
1268 type = F_RDLCK;
1269 break; /* retry */
1271 set_error( STATUS_ACCESS_DENIED );
1272 return 0;
1273 #ifdef EOVERFLOW
1274 case EOVERFLOW:
1275 #endif
1276 case EINVAL:
1277 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1278 /* in that case we shrink the limit and retry */
1279 if (max_unix_offset > INT_MAX)
1281 max_unix_offset = INT_MAX;
1282 break; /* retry */
1284 /* fall through */
1285 default:
1286 file_set_error();
1287 return 0;
1292 /* check if interval [start;end) overlaps the lock */
1293 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1295 if (lock->end && start >= lock->end) return 0;
1296 if (end && lock->start >= end) return 0;
1297 return 1;
1300 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1301 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1303 struct hole
1305 struct hole *next;
1306 struct hole *prev;
1307 file_pos_t start;
1308 file_pos_t end;
1309 } *first, *cur, *next, *buffer;
1311 struct list *ptr;
1312 int count = 0;
1314 if (!fd->inode) return;
1315 if (!fd->fs_locks) return;
1316 if (start == end || start > max_unix_offset) return;
1317 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1319 /* count the number of locks overlapping the specified area */
1321 LIST_FOR_EACH( ptr, &fd->inode->locks )
1323 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1324 if (lock->start == lock->end) continue;
1325 if (lock_overlaps( lock, start, end )) count++;
1328 if (!count) /* no locks at all, we can unlock everything */
1330 set_unix_lock( fd, start, end, F_UNLCK );
1331 return;
1334 /* allocate space for the list of holes */
1335 /* max. number of holes is number of locks + 1 */
1337 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1338 first = buffer;
1339 first->next = NULL;
1340 first->prev = NULL;
1341 first->start = start;
1342 first->end = end;
1343 next = first + 1;
1345 /* build a sorted list of unlocked holes in the specified area */
1347 LIST_FOR_EACH( ptr, &fd->inode->locks )
1349 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1350 if (lock->start == lock->end) continue;
1351 if (!lock_overlaps( lock, start, end )) continue;
1353 /* go through all the holes touched by this lock */
1354 for (cur = first; cur; cur = cur->next)
1356 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1357 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1359 /* now we know that lock is overlapping hole */
1361 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1363 cur->start = lock->end;
1364 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1365 /* now hole is empty, remove it */
1366 if (cur->next) cur->next->prev = cur->prev;
1367 if (cur->prev) cur->prev->next = cur->next;
1368 else if (!(first = cur->next)) goto done; /* no more holes at all */
1370 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1372 cur->end = lock->start;
1373 assert( cur->start < cur->end );
1375 else /* lock is in the middle of hole, split hole in two */
1377 next->prev = cur;
1378 next->next = cur->next;
1379 cur->next = next;
1380 next->start = lock->end;
1381 next->end = cur->end;
1382 cur->end = lock->start;
1383 assert( next->start < next->end );
1384 assert( cur->end < next->start );
1385 next++;
1386 break; /* done with this lock */
1391 /* clear Unix locks for all the holes */
1393 for (cur = first; cur; cur = cur->next)
1394 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1396 done:
1397 free( buffer );
1400 /* create a new lock on a fd */
1401 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1403 struct file_lock *lock;
1405 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1406 lock->shared = shared;
1407 lock->start = start;
1408 lock->end = end;
1409 lock->fd = fd;
1410 lock->process = current->process;
1412 /* now try to set a Unix lock */
1413 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1415 release_object( lock );
1416 return NULL;
1418 list_add_tail( &fd->locks, &lock->fd_entry );
1419 list_add_tail( &fd->inode->locks, &lock->inode_entry );
1420 list_add_tail( &lock->process->locks, &lock->proc_entry );
1421 return lock;
1424 /* remove an existing lock */
1425 static void remove_lock( struct file_lock *lock, int remove_unix )
1427 struct inode *inode = lock->fd->inode;
1429 list_remove( &lock->fd_entry );
1430 list_remove( &lock->inode_entry );
1431 list_remove( &lock->proc_entry );
1432 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1433 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1434 lock->process = NULL;
1435 wake_up( &lock->obj, 0 );
1436 release_object( lock );
1439 /* remove all locks owned by a given process */
1440 void remove_process_locks( struct process *process )
1442 struct list *ptr;
1444 while ((ptr = list_head( &process->locks )))
1446 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1447 remove_lock( lock, 1 ); /* this removes it from the list */
1451 /* remove all locks on a given fd */
1452 static void remove_fd_locks( struct fd *fd )
1454 file_pos_t start = FILE_POS_T_MAX, end = 0;
1455 struct list *ptr;
1457 while ((ptr = list_head( &fd->locks )))
1459 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1460 if (lock->start < start) start = lock->start;
1461 if (!lock->end || lock->end > end) end = lock->end - 1;
1462 remove_lock( lock, 0 );
1464 if (start < end) remove_unix_locks( fd, start, end + 1 );
1467 /* add a lock on an fd */
1468 /* returns handle to wait on */
1469 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1471 struct list *ptr;
1472 file_pos_t end = start + count;
1474 if (!fd->inode) /* not a regular file */
1476 set_error( STATUS_INVALID_DEVICE_REQUEST );
1477 return 0;
1480 /* don't allow wrapping locks */
1481 if (end && end < start)
1483 set_error( STATUS_INVALID_PARAMETER );
1484 return 0;
1487 /* check if another lock on that file overlaps the area */
1488 LIST_FOR_EACH( ptr, &fd->inode->locks )
1490 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1491 if (!lock_overlaps( lock, start, end )) continue;
1492 if (shared && (lock->shared || lock->fd == fd)) continue;
1493 /* found one */
1494 if (!wait)
1496 set_error( STATUS_FILE_LOCK_CONFLICT );
1497 return 0;
1499 set_error( STATUS_PENDING );
1500 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1503 /* not found, add it */
1504 if (add_lock( fd, shared, start, end )) return 0;
1505 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1507 /* Unix lock conflict -> tell client to wait and retry */
1508 if (wait) set_error( STATUS_PENDING );
1510 return 0;
1513 /* remove a lock on an fd */
1514 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1516 struct list *ptr;
1517 file_pos_t end = start + count;
1519 /* find an existing lock with the exact same parameters */
1520 LIST_FOR_EACH( ptr, &fd->locks )
1522 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1523 if ((lock->start == start) && (lock->end == end))
1525 remove_lock( lock, 1 );
1526 return;
1529 set_error( STATUS_FILE_LOCK_CONFLICT );
1533 /****************************************************************/
1534 /* file descriptor functions */
1536 static void fd_dump( struct object *obj, int verbose )
1538 struct fd *fd = (struct fd *)obj;
1539 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1540 if (fd->inode) fprintf( stderr, " inode=%p disp_flags=%x", fd->inode, fd->closed->disp_flags );
1541 fprintf( stderr, "\n" );
1544 static void fd_destroy( struct object *obj )
1546 struct fd *fd = (struct fd *)obj;
1548 free_async_queue( &fd->read_q );
1549 free_async_queue( &fd->write_q );
1550 free_async_queue( &fd->wait_q );
1552 if (fd->map_addr) free_map_addr( fd->map_addr, fd->map_size );
1553 if (fd->completion) release_object( fd->completion );
1554 remove_fd_locks( fd );
1555 list_remove( &fd->inode_entry );
1556 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1557 free( fd->nt_name );
1558 if (fd->inode)
1560 inode_add_closed_fd( fd->inode, fd->closed );
1561 release_object( fd->inode );
1563 else /* no inode, close it right away */
1565 if (fd->unix_fd != -1) close( fd->unix_fd );
1566 free( fd->unix_name );
1570 /* check if the desired access is possible without violating */
1571 /* the sharing mode of other opens of the same file */
1572 static unsigned int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing,
1573 unsigned int open_flags, unsigned int options )
1575 /* only a few access bits are meaningful wrt sharing */
1576 const unsigned int read_access = FILE_READ_DATA | FILE_EXECUTE;
1577 const unsigned int write_access = FILE_WRITE_DATA | FILE_APPEND_DATA;
1578 const unsigned int all_access = read_access | write_access | DELETE;
1580 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1581 unsigned int existing_access = 0;
1582 struct list *ptr;
1584 fd->access = access;
1585 fd->sharing = sharing;
1587 LIST_FOR_EACH( ptr, &fd->inode->open )
1589 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1590 if (fd_ptr != fd)
1592 /* if access mode is 0, sharing mode is ignored */
1593 if (fd_ptr->access & all_access) existing_sharing &= fd_ptr->sharing;
1594 existing_access |= fd_ptr->access;
1598 if (((access & read_access) && !(existing_sharing & FILE_SHARE_READ)) ||
1599 ((access & write_access) && !(existing_sharing & FILE_SHARE_WRITE)) ||
1600 ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)))
1601 return STATUS_SHARING_VIOLATION;
1602 if (((existing_access & FILE_MAPPING_WRITE) && !(sharing & FILE_SHARE_WRITE)) ||
1603 ((existing_access & FILE_MAPPING_IMAGE) && (access & FILE_WRITE_DATA)))
1604 return STATUS_SHARING_VIOLATION;
1605 if ((existing_access & FILE_MAPPING_IMAGE) && (options & FILE_DELETE_ON_CLOSE))
1606 return STATUS_CANNOT_DELETE;
1607 if ((existing_access & FILE_MAPPING_ACCESS) && (open_flags & O_TRUNC))
1608 return STATUS_USER_MAPPED_FILE;
1609 if (!(access & all_access))
1610 return 0; /* if access mode is 0, sharing mode is ignored (except for mappings) */
1611 if (((existing_access & read_access) && !(sharing & FILE_SHARE_READ)) ||
1612 ((existing_access & write_access) && !(sharing & FILE_SHARE_WRITE)) ||
1613 ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)))
1614 return STATUS_SHARING_VIOLATION;
1615 return 0;
1618 /* set the events that select waits for on this fd */
1619 void set_fd_events( struct fd *fd, int events )
1621 int user = fd->poll_index;
1622 assert( poll_users[user] == fd );
1624 set_fd_epoll_events( fd, user, events );
1626 if (events == -1) /* stop waiting on this fd completely */
1628 pollfd[user].fd = -1;
1629 pollfd[user].events = POLLERR;
1630 pollfd[user].revents = 0;
1632 else
1634 pollfd[user].fd = fd->unix_fd;
1635 pollfd[user].events = events;
1639 /* prepare an fd for unmounting its corresponding device */
1640 static inline void unmount_fd( struct fd *fd )
1642 assert( fd->inode );
1644 async_wake_up( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1645 async_wake_up( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1647 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1649 if (fd->unix_fd != -1) close( fd->unix_fd );
1651 fd->unix_fd = -1;
1652 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1653 fd->closed->unix_fd = -1;
1654 fd->closed->disp_flags = 0;
1656 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1657 fd->fs_locks = 0;
1660 /* allocate an fd object, without setting the unix fd yet */
1661 static struct fd *alloc_fd_object(void)
1663 struct fd *fd = alloc_object( &fd_ops );
1665 if (!fd) return NULL;
1667 fd->fd_ops = NULL;
1668 fd->user = NULL;
1669 fd->inode = NULL;
1670 fd->closed = NULL;
1671 fd->map_addr = 0;
1672 fd->map_size = 0;
1673 fd->access = 0;
1674 fd->options = 0;
1675 fd->sharing = 0;
1676 fd->unix_fd = -1;
1677 fd->unix_name = NULL;
1678 fd->nt_name = NULL;
1679 fd->nt_namelen = 0;
1680 fd->cacheable = 0;
1681 fd->signaled = 1;
1682 fd->fs_locks = 1;
1683 fd->poll_index = -1;
1684 fd->completion = NULL;
1685 fd->comp_flags = 0;
1686 init_async_queue( &fd->read_q );
1687 init_async_queue( &fd->write_q );
1688 init_async_queue( &fd->wait_q );
1689 list_init( &fd->inode_entry );
1690 list_init( &fd->locks );
1692 if ((fd->poll_index = add_poll_user( fd )) == -1)
1694 release_object( fd );
1695 return NULL;
1697 return fd;
1700 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1701 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1703 struct fd *fd = alloc_object( &fd_ops );
1705 if (!fd) return NULL;
1707 fd->fd_ops = fd_user_ops;
1708 fd->user = user;
1709 fd->inode = NULL;
1710 fd->closed = NULL;
1711 fd->map_addr = 0;
1712 fd->map_size = 0;
1713 fd->access = 0;
1714 fd->options = options;
1715 fd->sharing = 0;
1716 fd->unix_name = NULL;
1717 fd->nt_name = NULL;
1718 fd->nt_namelen = 0;
1719 fd->unix_fd = -1;
1720 fd->cacheable = 0;
1721 fd->signaled = 1;
1722 fd->fs_locks = 0;
1723 fd->poll_index = -1;
1724 fd->completion = NULL;
1725 fd->comp_flags = 0;
1726 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1727 init_async_queue( &fd->read_q );
1728 init_async_queue( &fd->write_q );
1729 init_async_queue( &fd->wait_q );
1730 list_init( &fd->inode_entry );
1731 list_init( &fd->locks );
1732 return fd;
1735 /* duplicate an fd object for a different user */
1736 struct fd *dup_fd_object( struct fd *orig, unsigned int access, unsigned int sharing, unsigned int options )
1738 unsigned int err;
1739 struct fd *fd = alloc_fd_object();
1741 if (!fd) return NULL;
1743 fd->options = options;
1744 fd->cacheable = orig->cacheable;
1746 if (orig->unix_name)
1748 if (!(fd->unix_name = mem_alloc( strlen(orig->unix_name) + 1 ))) goto failed;
1749 strcpy( fd->unix_name, orig->unix_name );
1751 if (orig->nt_namelen)
1753 if (!(fd->nt_name = memdup( orig->nt_name, orig->nt_namelen ))) goto failed;
1754 fd->nt_namelen = orig->nt_namelen;
1757 if (orig->inode)
1759 struct closed_fd *closed = mem_alloc( sizeof(*closed) );
1760 if (!closed) goto failed;
1761 if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1763 file_set_error();
1764 free( closed );
1765 goto failed;
1767 closed->unix_fd = fd->unix_fd;
1768 closed->disp_flags = 0;
1769 closed->unix_name = fd->unix_name;
1770 fd->closed = closed;
1771 fd->inode = (struct inode *)grab_object( orig->inode );
1772 list_add_head( &fd->inode->open, &fd->inode_entry );
1773 if ((err = check_sharing( fd, access, sharing, 0, options )))
1775 set_error( err );
1776 goto failed;
1779 else if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1781 file_set_error();
1782 goto failed;
1784 return fd;
1786 failed:
1787 release_object( fd );
1788 return NULL;
1791 /* find an existing fd object that can be reused for a mapping */
1792 struct fd *get_fd_object_for_mapping( struct fd *fd, unsigned int access, unsigned int sharing )
1794 struct fd *fd_ptr;
1796 if (!fd->inode) return NULL;
1798 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
1799 if (fd_ptr->access == access && fd_ptr->sharing == sharing)
1800 return (struct fd *)grab_object( fd_ptr );
1802 return NULL;
1805 /* sets the user of an fd that previously had no user */
1806 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1808 assert( fd->fd_ops == NULL );
1809 fd->fd_ops = user_ops;
1810 fd->user = user;
1813 char *dup_fd_name( struct fd *root, const char *name )
1815 char *ret;
1817 if (!root) return strdup( name );
1818 if (!root->unix_name) return NULL;
1820 /* skip . prefix */
1821 if (name[0] == '.' && (!name[1] || name[1] == '/')) name++;
1823 if ((ret = malloc( strlen(root->unix_name) + strlen(name) + 2 )))
1825 strcpy( ret, root->unix_name );
1826 if (name[0] && name[0] != '/') strcat( ret, "/" );
1827 strcat( ret, name );
1829 return ret;
1832 static WCHAR *dup_nt_name( struct fd *root, struct unicode_str name, data_size_t *len )
1834 WCHAR *ret;
1835 data_size_t retlen;
1837 if (!root)
1839 *len = name.len;
1840 if (!name.len) return NULL;
1841 return memdup( name.str, name.len );
1843 if (!root->nt_namelen) return NULL;
1844 retlen = root->nt_namelen;
1846 /* skip . prefix */
1847 if (name.len && name.str[0] == '.' && (name.len == sizeof(WCHAR) || name.str[1] == '\\'))
1849 name.str++;
1850 name.len -= sizeof(WCHAR);
1852 if ((ret = malloc( retlen + name.len + sizeof(WCHAR) )))
1854 memcpy( ret, root->nt_name, root->nt_namelen );
1855 if (name.len && name.str[0] != '\\' &&
1856 root->nt_namelen && root->nt_name[root->nt_namelen / sizeof(WCHAR) - 1] != '\\')
1858 ret[retlen / sizeof(WCHAR)] = '\\';
1859 retlen += sizeof(WCHAR);
1861 memcpy( ret + retlen / sizeof(WCHAR), name.str, name.len );
1862 *len = retlen + name.len;
1864 return ret;
1867 void get_nt_name( struct fd *fd, struct unicode_str *name )
1869 name->str = fd->nt_name;
1870 name->len = fd->nt_namelen;
1873 /* open() wrapper that returns a struct fd with no fd user set */
1874 struct fd *open_fd( struct fd *root, const char *name, struct unicode_str nt_name,
1875 int flags, mode_t *mode, unsigned int access,
1876 unsigned int sharing, unsigned int options )
1878 struct stat st;
1879 struct closed_fd *closed_fd;
1880 struct fd *fd;
1881 int root_fd = -1;
1882 int rw_mode;
1883 char *path;
1885 if (((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE)) ||
1886 ((options & FILE_DIRECTORY_FILE) && (flags & O_TRUNC)))
1888 set_error( STATUS_INVALID_PARAMETER );
1889 return NULL;
1892 if (!(fd = alloc_fd_object())) return NULL;
1894 fd->options = options;
1895 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
1897 release_object( fd );
1898 return NULL;
1901 if (root)
1903 if ((root_fd = get_unix_fd( root )) == -1) goto error;
1904 if (fchdir( root_fd ) == -1)
1906 file_set_error();
1907 root_fd = -1;
1908 goto error;
1912 /* create the directory if needed */
1913 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1915 if (mkdir( name, *mode ) == -1)
1917 if (errno != EEXIST || (flags & O_EXCL))
1919 file_set_error();
1920 goto error;
1923 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1926 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1928 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1929 else rw_mode = O_WRONLY;
1931 else rw_mode = O_RDONLY;
1933 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1935 /* if we tried to open a directory for write access, retry read-only */
1936 if (errno == EISDIR)
1938 if ((access & FILE_UNIX_WRITE_ACCESS) || (flags & O_CREAT))
1939 fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode );
1942 if (fd->unix_fd == -1)
1944 /* check for trailing slash on file path */
1945 if ((errno == ENOENT || errno == ENOTDIR) && name[strlen(name) - 1] == '/')
1946 set_error( STATUS_OBJECT_NAME_INVALID );
1947 else
1948 file_set_error();
1949 goto error;
1953 fd->nt_name = dup_nt_name( root, nt_name, &fd->nt_namelen );
1954 fd->unix_name = NULL;
1955 if ((path = dup_fd_name( root, name )))
1957 fd->unix_name = realpath( path, NULL );
1958 free( path );
1961 closed_fd->unix_fd = fd->unix_fd;
1962 closed_fd->disp_flags = 0;
1963 closed_fd->unix_name = fd->unix_name;
1964 fstat( fd->unix_fd, &st );
1965 *mode = st.st_mode;
1967 /* only bother with an inode for normal files and directories */
1968 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1970 unsigned int err;
1971 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1973 if (!inode)
1975 /* we can close the fd because there are no others open on the same file,
1976 * otherwise we wouldn't have failed to allocate a new inode
1978 goto error;
1980 fd->inode = inode;
1981 fd->closed = closed_fd;
1982 fd->cacheable = !inode->device->removable;
1983 list_add_head( &inode->open, &fd->inode_entry );
1984 closed_fd = NULL;
1986 /* check directory options */
1987 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1989 set_error( STATUS_NOT_A_DIRECTORY );
1990 goto error;
1992 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1994 set_error( STATUS_FILE_IS_A_DIRECTORY );
1995 goto error;
1997 if ((err = check_sharing( fd, access, sharing, flags, options )))
1999 set_error( err );
2000 goto error;
2003 /* can't unlink files if we don't have permission to access */
2004 if ((options & FILE_DELETE_ON_CLOSE) && !(flags & O_CREAT) &&
2005 !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2007 set_error( STATUS_CANNOT_DELETE );
2008 goto error;
2011 fd->closed->disp_flags = (options & FILE_DELETE_ON_CLOSE) ?
2012 FILE_DISPOSITION_DELETE : 0;
2013 if (flags & O_TRUNC)
2015 if (S_ISDIR(st.st_mode))
2017 set_error( STATUS_OBJECT_NAME_COLLISION );
2018 goto error;
2020 ftruncate( fd->unix_fd, 0 );
2023 else /* special file */
2025 if (options & FILE_DELETE_ON_CLOSE) /* we can't unlink special files */
2027 set_error( STATUS_INVALID_PARAMETER );
2028 goto error;
2030 free( closed_fd );
2031 fd->cacheable = 1;
2034 #ifdef HAVE_POSIX_FADVISE
2035 switch (options & (FILE_SEQUENTIAL_ONLY | FILE_RANDOM_ACCESS))
2037 case FILE_SEQUENTIAL_ONLY:
2038 posix_fadvise( fd->unix_fd, 0, 0, POSIX_FADV_SEQUENTIAL );
2039 break;
2040 case FILE_RANDOM_ACCESS:
2041 posix_fadvise( fd->unix_fd, 0, 0, POSIX_FADV_RANDOM );
2042 break;
2044 #endif
2046 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
2047 return fd;
2049 error:
2050 release_object( fd );
2051 free( closed_fd );
2052 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
2053 return NULL;
2056 /* create an fd for an anonymous file */
2057 /* if the function fails the unix fd is closed */
2058 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
2059 unsigned int options )
2061 struct fd *fd = alloc_fd_object();
2063 if (fd)
2065 set_fd_user( fd, fd_user_ops, user );
2066 fd->unix_fd = unix_fd;
2067 fd->options = options;
2068 return fd;
2070 close( unix_fd );
2071 return NULL;
2074 /* retrieve the object that is using an fd */
2075 void *get_fd_user( struct fd *fd )
2077 return fd->user;
2080 /* retrieve the opening options for the fd */
2081 unsigned int get_fd_options( struct fd *fd )
2083 return fd->options;
2086 /* retrieve the completion flags for the fd */
2087 unsigned int get_fd_comp_flags( struct fd *fd )
2089 return fd->comp_flags;
2092 /* check if fd is in overlapped mode */
2093 int is_fd_overlapped( struct fd *fd )
2095 return !(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
2098 /* retrieve the unix fd for an object */
2099 int get_unix_fd( struct fd *fd )
2101 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
2102 return fd->unix_fd;
2105 /* retrieve the suggested mapping address for the fd */
2106 client_ptr_t get_fd_map_address( struct fd *fd )
2108 return fd->map_addr;
2111 /* set the suggested mapping address for the fd */
2112 void set_fd_map_address( struct fd *fd, client_ptr_t addr, mem_size_t size )
2114 assert( !fd->map_addr );
2115 fd->map_addr = addr;
2116 fd->map_size = size;
2119 /* check if two file descriptors point to the same file */
2120 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
2122 return fd1->inode == fd2->inode;
2125 /* allow the fd to be cached (can't be reset once set) */
2126 void allow_fd_caching( struct fd *fd )
2128 fd->cacheable = 1;
2131 /* check if fd is on a removable device */
2132 int is_fd_removable( struct fd *fd )
2134 return (fd->inode && fd->inode->device->removable);
2137 /* set or clear the fd signaled state */
2138 void set_fd_signaled( struct fd *fd, int signaled )
2140 if (fd->comp_flags & FILE_SKIP_SET_EVENT_ON_HANDLE) return;
2141 fd->signaled = signaled;
2142 if (signaled) wake_up( fd->user, 0 );
2145 /* check if events are pending and if yes return which one(s) */
2146 int check_fd_events( struct fd *fd, int events )
2148 struct pollfd pfd;
2150 if (fd->unix_fd == -1) return POLLERR;
2151 if (fd->inode) return events; /* regular files are always signaled */
2153 pfd.fd = fd->unix_fd;
2154 pfd.events = events;
2155 if (poll( &pfd, 1, 0 ) <= 0) return 0;
2156 return pfd.revents;
2159 /* default signaled() routine for objects that poll() on an fd */
2160 int default_fd_signaled( struct object *obj, struct wait_queue_entry *entry )
2162 struct fd *fd = get_obj_fd( obj );
2163 int ret = fd->signaled;
2164 release_object( fd );
2165 return ret;
2168 int default_fd_get_poll_events( struct fd *fd )
2170 int events = 0;
2172 if (async_waiting( &fd->read_q )) events |= POLLIN;
2173 if (async_waiting( &fd->write_q )) events |= POLLOUT;
2174 return events;
2177 /* default handler for poll() events */
2178 void default_poll_event( struct fd *fd, int event )
2180 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( &fd->read_q, STATUS_ALERTED );
2181 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( &fd->write_q, STATUS_ALERTED );
2183 /* if an error occurred, stop polling this fd to avoid busy-looping */
2184 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
2185 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2188 void fd_queue_async( struct fd *fd, struct async *async, int type )
2190 struct async_queue *queue;
2192 switch (type)
2194 case ASYNC_TYPE_READ:
2195 queue = &fd->read_q;
2196 break;
2197 case ASYNC_TYPE_WRITE:
2198 queue = &fd->write_q;
2199 break;
2200 case ASYNC_TYPE_WAIT:
2201 queue = &fd->wait_q;
2202 break;
2203 default:
2204 queue = NULL;
2205 assert(0);
2208 queue_async( queue, async );
2210 if (type != ASYNC_TYPE_WAIT)
2212 if (!fd->inode)
2213 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2214 else /* regular files are always ready for read and write */
2215 async_wake_up( queue, STATUS_ALERTED );
2219 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
2221 switch (type)
2223 case ASYNC_TYPE_READ:
2224 async_wake_up( &fd->read_q, status );
2225 break;
2226 case ASYNC_TYPE_WRITE:
2227 async_wake_up( &fd->write_q, status );
2228 break;
2229 case ASYNC_TYPE_WAIT:
2230 async_wake_up( &fd->wait_q, status );
2231 break;
2232 default:
2233 assert(0);
2237 void fd_cancel_async( struct fd *fd, struct async *async )
2239 fd->fd_ops->cancel_async( fd, async );
2242 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
2244 fd->fd_ops->reselect_async( fd, queue );
2247 void no_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2249 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2252 void default_fd_cancel_async( struct fd *fd, struct async *async )
2254 async_terminate( async, STATUS_CANCELLED );
2257 void default_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2259 fd_queue_async( fd, async, type );
2260 set_error( STATUS_PENDING );
2263 /* default reselect_async() fd routine */
2264 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
2266 if (queue == &fd->read_q || queue == &fd->write_q)
2268 int poll_events = fd->fd_ops->get_poll_events( fd );
2269 int events = check_fd_events( fd, poll_events );
2270 if (events) fd->fd_ops->poll_event( fd, events );
2271 else set_fd_events( fd, poll_events );
2275 static inline int is_valid_mounted_device( struct stat *st )
2277 #if defined(linux) || defined(__sun__)
2278 return S_ISBLK( st->st_mode );
2279 #else
2280 /* disks are char devices on *BSD */
2281 return S_ISCHR( st->st_mode );
2282 #endif
2285 /* close all Unix file descriptors on a device to allow unmounting it */
2286 static void unmount_device( struct fd *device_fd )
2288 unsigned int i;
2289 struct stat st;
2290 struct device *device;
2291 struct inode *inode;
2292 struct fd *fd;
2293 int unix_fd = get_unix_fd( device_fd );
2295 if (unix_fd == -1) return;
2297 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2299 set_error( STATUS_INVALID_PARAMETER );
2300 return;
2303 if (!(device = get_device( st.st_rdev, -1 ))) return;
2305 for (i = 0; i < INODE_HASH_SIZE; i++)
2307 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
2309 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
2311 unmount_fd( fd );
2313 inode_close_pending( inode, 0 );
2316 /* remove it from the hash table */
2317 list_remove( &device->entry );
2318 list_init( &device->entry );
2319 release_object( device );
2322 /* default read() routine */
2323 void no_fd_read( struct fd *fd, struct async *async, file_pos_t pos )
2325 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2328 /* default write() routine */
2329 void no_fd_write( struct fd *fd, struct async *async, file_pos_t pos )
2331 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2334 /* default flush() routine */
2335 void no_fd_flush( struct fd *fd, struct async *async )
2337 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2340 /* default get_file_info() routine */
2341 void no_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2343 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2346 /* default get_file_info() routine */
2347 void default_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2349 switch (info_class)
2351 case FileAccessInformation:
2353 FILE_ACCESS_INFORMATION info;
2354 if (get_reply_max_size() < sizeof(info))
2356 set_error( STATUS_INFO_LENGTH_MISMATCH );
2357 return;
2359 info.AccessFlags = get_handle_access( current->process, handle );
2360 set_reply_data( &info, sizeof(info) );
2361 break;
2363 case FileModeInformation:
2365 FILE_MODE_INFORMATION info;
2366 if (get_reply_max_size() < sizeof(info))
2368 set_error( STATUS_INFO_LENGTH_MISMATCH );
2369 return;
2371 info.Mode = fd->options & ( FILE_WRITE_THROUGH
2372 | FILE_SEQUENTIAL_ONLY
2373 | FILE_NO_INTERMEDIATE_BUFFERING
2374 | FILE_SYNCHRONOUS_IO_ALERT
2375 | FILE_SYNCHRONOUS_IO_NONALERT );
2376 set_reply_data( &info, sizeof(info) );
2377 break;
2379 case FileIoCompletionNotificationInformation:
2381 FILE_IO_COMPLETION_NOTIFICATION_INFORMATION info;
2382 if (get_reply_max_size() < sizeof(info))
2384 set_error( STATUS_INFO_LENGTH_MISMATCH );
2385 return;
2387 info.Flags = fd->comp_flags;
2388 set_reply_data( &info, sizeof(info) );
2389 break;
2391 default:
2392 set_error( STATUS_NOT_IMPLEMENTED );
2396 /* default get_volume_info() routine */
2397 void no_fd_get_volume_info( struct fd *fd, struct async *async, unsigned int info_class )
2399 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2402 /* default ioctl() routine */
2403 void no_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2405 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2408 /* default ioctl() routine */
2409 void default_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2411 switch(code)
2413 case FSCTL_DISMOUNT_VOLUME:
2414 unmount_device( fd );
2415 break;
2417 default:
2418 set_error( STATUS_NOT_SUPPORTED );
2422 /* same as get_handle_obj but retrieve the struct fd associated to the object */
2423 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
2424 unsigned int access )
2426 struct fd *fd = NULL;
2427 struct object *obj;
2429 if ((obj = get_handle_obj( process, handle, access, NULL )))
2431 fd = get_obj_fd( obj );
2432 release_object( obj );
2434 return fd;
2437 static int is_dir_empty( int fd )
2439 DIR *dir;
2440 int empty;
2441 struct dirent *de;
2443 if ((fd = dup( fd )) == -1)
2444 return -1;
2446 if (!(dir = fdopendir( fd )))
2448 close( fd );
2449 return -1;
2452 empty = 1;
2453 while (empty && (de = readdir( dir )))
2455 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2456 empty = 0;
2458 closedir( dir );
2459 return empty;
2462 /* set disposition for the fd */
2463 static void set_fd_disposition( struct fd *fd, unsigned int flags )
2465 struct stat st;
2467 if (!fd->inode)
2469 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2470 return;
2473 if (fd->unix_fd == -1)
2475 set_error( fd->no_fd_status );
2476 return;
2479 if (flags & FILE_DISPOSITION_DELETE)
2481 struct fd *fd_ptr;
2483 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
2485 if (fd_ptr->access & FILE_MAPPING_ACCESS)
2487 set_error( STATUS_CANNOT_DELETE );
2488 return;
2492 if (fstat( fd->unix_fd, &st ) == -1)
2494 file_set_error();
2495 return;
2497 if (S_ISREG( st.st_mode )) /* can't unlink files we don't have permission to write */
2499 if (!(flags & FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE) &&
2500 !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2502 set_error( STATUS_CANNOT_DELETE );
2503 return;
2506 else if (S_ISDIR( st.st_mode )) /* can't remove non-empty directories */
2508 switch (is_dir_empty( fd->unix_fd ))
2510 case -1:
2511 file_set_error();
2512 return;
2513 case 0:
2514 set_error( STATUS_DIRECTORY_NOT_EMPTY );
2515 return;
2518 else /* can't unlink special files */
2520 set_error( STATUS_INVALID_PARAMETER );
2521 return;
2525 if (flags & FILE_DISPOSITION_ON_CLOSE)
2526 fd->options &= ~FILE_DELETE_ON_CLOSE;
2528 fd->closed->disp_flags =
2529 (flags & (FILE_DISPOSITION_DELETE | FILE_DISPOSITION_POSIX_SEMANTICS)) |
2530 ((fd->options & FILE_DELETE_ON_CLOSE) ? FILE_DISPOSITION_DELETE : 0);
2533 /* set new name for the fd */
2534 static void set_fd_name( struct fd *fd, struct fd *root, const char *nameptr, data_size_t len,
2535 struct unicode_str nt_name, int create_link, unsigned int flags )
2537 struct inode *inode;
2538 struct stat st, st2;
2539 char *name;
2540 const unsigned int replace = flags & FILE_RENAME_REPLACE_IF_EXISTS;
2542 if (!fd->inode || !fd->unix_name)
2544 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2545 return;
2547 if (fd->unix_fd == -1)
2549 set_error( fd->no_fd_status );
2550 return;
2553 if (!len || ((nameptr[0] == '/') ^ !root))
2555 set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
2556 return;
2558 if (!(name = mem_alloc( len + 1 ))) return;
2559 memcpy( name, nameptr, len );
2560 name[len] = 0;
2562 if (root)
2564 char *combined_name = dup_fd_name( root, name );
2565 if (!combined_name)
2567 set_error( STATUS_NO_MEMORY );
2568 goto failed;
2570 free( name );
2571 name = combined_name;
2574 /* when creating a hard link, source cannot be a dir */
2575 if (create_link && !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode ))
2577 set_error( STATUS_FILE_IS_A_DIRECTORY );
2578 goto failed;
2581 if (!stat( name, &st ))
2583 if (!fstat( fd->unix_fd, &st2 ) && st.st_ino == st2.st_ino && st.st_dev == st2.st_dev)
2585 if (create_link && !replace) set_error( STATUS_OBJECT_NAME_COLLISION );
2586 free( name );
2587 return;
2590 if (!replace)
2592 set_error( STATUS_OBJECT_NAME_COLLISION );
2593 goto failed;
2596 /* can't replace directories or special files */
2597 if (!S_ISREG( st.st_mode ))
2599 set_error( STATUS_ACCESS_DENIED );
2600 goto failed;
2603 /* read-only files cannot be replaced */
2604 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) &&
2605 !(flags & FILE_RENAME_IGNORE_READONLY_ATTRIBUTE))
2607 set_error( STATUS_ACCESS_DENIED );
2608 goto failed;
2611 /* can't replace an opened file */
2612 if ((inode = get_inode( st.st_dev, st.st_ino, -1 )))
2614 int is_empty = list_empty( &inode->open );
2615 release_object( inode );
2616 if (!is_empty)
2618 set_error( STATUS_ACCESS_DENIED );
2619 goto failed;
2623 /* link() expects that the target doesn't exist */
2624 /* rename() cannot replace files with directories */
2625 if (create_link || S_ISDIR( st2.st_mode ))
2627 if (unlink( name ))
2629 file_set_error();
2630 goto failed;
2635 if (create_link)
2637 if (link( fd->unix_name, name ))
2638 file_set_error();
2639 free( name );
2640 return;
2643 if (rename( fd->unix_name, name ))
2645 file_set_error();
2646 goto failed;
2649 if (is_file_executable( fd->unix_name ) != is_file_executable( name ) && !fstat( fd->unix_fd, &st ))
2651 if (is_file_executable( name ))
2652 /* set executable bit where read bit is set */
2653 st.st_mode |= (st.st_mode & 0444) >> 2;
2654 else
2655 st.st_mode &= ~0111;
2656 fchmod( fd->unix_fd, st.st_mode );
2659 free( fd->nt_name );
2660 fd->nt_name = dup_nt_name( root, nt_name, &fd->nt_namelen );
2661 free( fd->unix_name );
2662 fd->closed->unix_name = fd->unix_name = realpath( name, NULL );
2663 free( name );
2664 if (!fd->unix_name)
2665 set_error( STATUS_NO_MEMORY );
2666 return;
2668 failed:
2669 free( name );
2672 static void set_fd_eof( struct fd *fd, file_pos_t eof )
2674 struct stat st;
2676 if (!fd->inode)
2678 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2679 return;
2682 if (fd->unix_fd == -1)
2684 set_error( fd->no_fd_status );
2685 return;
2687 if (fstat( fd->unix_fd, &st) == -1)
2689 file_set_error();
2690 return;
2692 if (eof < st.st_size)
2694 struct fd *fd_ptr;
2695 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
2697 if (fd_ptr->access & FILE_MAPPING_ACCESS)
2699 set_error( STATUS_USER_MAPPED_FILE );
2700 return;
2703 if (ftruncate( fd->unix_fd, eof ) == -1) file_set_error();
2705 else grow_file( fd->unix_fd, eof );
2708 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
2710 *p_key = fd->comp_key;
2711 return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
2714 void fd_copy_completion( struct fd *src, struct fd *dst )
2716 assert( !dst->completion );
2717 dst->completion = fd_get_completion( src, &dst->comp_key );
2718 dst->comp_flags = src->comp_flags;
2721 /* flush a file buffers */
2722 DECL_HANDLER(flush)
2724 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, 0 );
2725 struct async *async;
2727 if (!fd) return;
2729 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2731 fd->fd_ops->flush( fd, async );
2732 reply->event = async_handoff( async, NULL, 1 );
2733 release_object( async );
2735 release_object( fd );
2738 /* query file info */
2739 DECL_HANDLER(get_file_info)
2741 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2743 if (fd)
2745 fd->fd_ops->get_file_info( fd, req->handle, req->info_class );
2746 release_object( fd );
2750 /* query volume info */
2751 DECL_HANDLER(get_volume_info)
2753 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2754 struct async *async;
2756 if (!fd) return;
2758 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2760 fd->fd_ops->get_volume_info( fd, async, req->info_class );
2761 reply->wait = async_handoff( async, NULL, 1 );
2762 release_object( async );
2764 release_object( fd );
2767 /* open a file object */
2768 DECL_HANDLER(open_file_object)
2770 struct unicode_str name = get_req_unicode_str();
2771 struct object *obj, *result, *root = NULL;
2773 if (req->rootdir && !(root = get_handle_obj( current->process, req->rootdir, 0, NULL ))) return;
2775 obj = open_named_object( root, NULL, &name, req->attributes );
2776 if (root) release_object( root );
2777 if (!obj) return;
2779 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
2781 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
2782 release_object( result );
2784 release_object( obj );
2787 /* get the Unix name from a file handle */
2788 DECL_HANDLER(get_handle_unix_name)
2790 struct fd *fd;
2792 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2794 if (fd->unix_name)
2796 data_size_t name_len = strlen( fd->unix_name );
2797 reply->name_len = name_len;
2798 if (name_len <= get_reply_max_size()) set_reply_data( fd->unix_name, name_len );
2799 else set_error( STATUS_BUFFER_OVERFLOW );
2801 else set_error( STATUS_OBJECT_TYPE_MISMATCH );
2802 release_object( fd );
2806 /* get a Unix fd to access a file */
2807 DECL_HANDLER(get_handle_fd)
2809 struct fd *fd;
2811 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2813 int unix_fd = get_unix_fd( fd );
2814 reply->cacheable = fd->cacheable;
2815 if (unix_fd != -1)
2817 reply->type = fd->fd_ops->get_fd_type( fd );
2818 reply->options = fd->options;
2819 reply->access = get_handle_access( current->process, req->handle );
2820 send_client_fd( current->process, unix_fd, req->handle );
2822 release_object( fd );
2826 /* perform a read on a file object */
2827 DECL_HANDLER(read)
2829 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_READ_DATA );
2830 struct async *async;
2832 if (!fd) return;
2834 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2836 fd->fd_ops->read( fd, async, req->pos );
2837 reply->wait = async_handoff( async, NULL, 0 );
2838 reply->options = fd->options;
2839 release_object( async );
2841 release_object( fd );
2844 /* perform a write on a file object */
2845 DECL_HANDLER(write)
2847 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_WRITE_DATA );
2848 struct async *async;
2850 if (!fd) return;
2852 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2854 fd->fd_ops->write( fd, async, req->pos );
2855 reply->wait = async_handoff( async, &reply->size, 0 );
2856 reply->options = fd->options;
2857 release_object( async );
2859 release_object( fd );
2862 /* perform an ioctl on a file */
2863 DECL_HANDLER(ioctl)
2865 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2866 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2867 struct async *async;
2869 if (!fd) return;
2871 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2873 fd->fd_ops->ioctl( fd, req->code, async );
2874 reply->wait = async_handoff( async, NULL, 0 );
2875 reply->options = fd->options;
2876 release_object( async );
2878 release_object( fd );
2881 /* create / reschedule an async I/O */
2882 DECL_HANDLER(register_async)
2884 unsigned int access;
2885 struct async *async;
2886 struct fd *fd;
2888 switch(req->type)
2890 case ASYNC_TYPE_READ:
2891 access = FILE_READ_DATA;
2892 break;
2893 case ASYNC_TYPE_WRITE:
2894 access = FILE_WRITE_DATA;
2895 break;
2896 default:
2897 set_error( STATUS_INVALID_PARAMETER );
2898 return;
2901 if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2903 if (get_unix_fd( fd ) != -1 && (async = create_async( fd, current, &req->async, NULL )))
2905 fd->fd_ops->queue_async( fd, async, req->type, req->count );
2906 release_object( async );
2908 release_object( fd );
2912 /* attach completion object to a fd */
2913 DECL_HANDLER(set_completion_info)
2915 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2917 if (fd)
2919 if (is_fd_overlapped( fd ) && !fd->completion)
2921 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2922 fd->comp_key = req->ckey;
2924 else set_error( STATUS_INVALID_PARAMETER );
2925 release_object( fd );
2929 /* push new completion msg into a completion queue attached to the fd */
2930 DECL_HANDLER(add_fd_completion)
2932 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2933 if (fd)
2935 if (fd->completion && (req->async || !(fd->comp_flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS)))
2936 add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2937 release_object( fd );
2941 /* set fd completion information */
2942 DECL_HANDLER(set_fd_completion_mode)
2944 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2945 if (fd)
2947 if (is_fd_overlapped( fd ))
2949 if (req->flags & FILE_SKIP_SET_EVENT_ON_HANDLE)
2950 set_fd_signaled( fd, 0 );
2951 /* removing flags is not allowed */
2952 fd->comp_flags |= req->flags & ( FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
2953 | FILE_SKIP_SET_EVENT_ON_HANDLE
2954 | FILE_SKIP_SET_USER_EVENT_ON_FAST_IO );
2956 else
2957 set_error( STATUS_INVALID_PARAMETER );
2958 release_object( fd );
2962 /* set fd disposition information */
2963 DECL_HANDLER(set_fd_disp_info)
2965 struct fd *fd = get_handle_fd_obj( current->process, req->handle, DELETE );
2966 if (fd)
2968 set_fd_disposition( fd, req->flags );
2969 release_object( fd );
2973 /* set fd name information */
2974 DECL_HANDLER(set_fd_name_info)
2976 struct fd *fd, *root_fd = NULL;
2977 struct unicode_str nt_name;
2979 if (req->namelen > get_req_data_size())
2981 set_error( STATUS_INVALID_PARAMETER );
2982 return;
2984 nt_name.str = get_req_data();
2985 nt_name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
2987 if (req->rootdir)
2989 struct dir *root;
2991 if (!(root = get_dir_obj( current->process, req->rootdir, 0 ))) return;
2992 root_fd = get_obj_fd( (struct object *)root );
2993 release_object( root );
2994 if (!root_fd) return;
2997 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2999 set_fd_name( fd, root_fd, (const char *)get_req_data() + req->namelen,
3000 get_req_data_size() - req->namelen, nt_name, req->link, req->flags );
3001 release_object( fd );
3003 if (root_fd) release_object( root_fd );
3006 /* set fd eof information */
3007 DECL_HANDLER(set_fd_eof_info)
3009 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
3010 if (fd)
3012 set_fd_eof( fd, req->eof );
3013 release_object( fd );