kernelbase: Correctly handle new process group flag in CreateProcess.
[wine.git] / server / fd.c
blob0b0e91ebfbb46d7a41cc48d748ec4cf146323ae4
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 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
108 # define USE_EPOLL
109 # define EPOLLIN POLLIN
110 # define EPOLLOUT POLLOUT
111 # define EPOLLERR POLLERR
112 # define EPOLLHUP POLLHUP
113 # define EPOLL_CTL_ADD 1
114 # define EPOLL_CTL_DEL 2
115 # define EPOLL_CTL_MOD 3
117 typedef union epoll_data
119 void *ptr;
120 int fd;
121 uint32_t u32;
122 uint64_t u64;
123 } epoll_data_t;
125 struct epoll_event
127 uint32_t events;
128 epoll_data_t data;
131 static inline int epoll_create( int size )
133 return syscall( 254 /*NR_epoll_create*/, size );
136 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
138 return syscall( 255 /*NR_epoll_ctl*/, epfd, op, fd, event );
141 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
143 return syscall( 256 /*NR_epoll_wait*/, epfd, events, maxevents, timeout );
146 #endif /* linux && __i386__ && HAVE_STDINT_H */
148 #if defined(HAVE_PORT_H) && defined(HAVE_PORT_CREATE)
149 # include <port.h>
150 # define USE_EVENT_PORTS
151 #endif /* HAVE_PORT_H && HAVE_PORT_CREATE */
153 /* Because of the stupid Posix locking semantics, we need to keep
154 * track of all file descriptors referencing a given file, and not
155 * close a single one until all the locks are gone (sigh).
158 /* file descriptor object */
160 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
161 struct closed_fd
163 struct list entry; /* entry in inode closed list */
164 int unix_fd; /* the unix file descriptor */
165 unsigned int disp_flags; /* the disposition flags */
166 char *unix_name; /* name to unlink on close, points to parent fd unix_name */
169 struct fd
171 struct object obj; /* object header */
172 const struct fd_ops *fd_ops; /* file descriptor operations */
173 struct inode *inode; /* inode that this fd belongs to */
174 struct list inode_entry; /* entry in inode fd list */
175 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
176 struct object *user; /* object using this file descriptor */
177 struct list locks; /* list of locks on this fd */
178 unsigned int access; /* file access (FILE_READ_DATA etc.) */
179 unsigned int options; /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
180 unsigned int sharing; /* file sharing mode */
181 char *unix_name; /* unix file name */
182 WCHAR *nt_name; /* NT file name */
183 data_size_t nt_namelen; /* length of NT file name */
184 int unix_fd; /* unix file descriptor */
185 unsigned int no_fd_status;/* status to return when unix_fd is -1 */
186 unsigned int cacheable :1;/* can the fd be cached on the client side? */
187 unsigned int signaled :1; /* is the fd signaled? */
188 unsigned int fs_locks :1; /* can we use filesystem locks for this fd? */
189 int poll_index; /* index of fd in poll array */
190 struct async_queue read_q; /* async readers of this fd */
191 struct async_queue write_q; /* async writers of this fd */
192 struct async_queue wait_q; /* other async waiters of this fd */
193 struct completion *completion; /* completion object attached to this fd */
194 apc_param_t comp_key; /* completion key to set in completion events */
195 unsigned int comp_flags; /* completion flags */
198 static void fd_dump( struct object *obj, int verbose );
199 static void fd_destroy( struct object *obj );
201 static const struct object_ops fd_ops =
203 sizeof(struct fd), /* size */
204 &no_type, /* type */
205 fd_dump, /* dump */
206 no_add_queue, /* add_queue */
207 NULL, /* remove_queue */
208 NULL, /* signaled */
209 NULL, /* satisfied */
210 no_signal, /* signal */
211 no_get_fd, /* get_fd */
212 default_map_access, /* map_access */
213 default_get_sd, /* get_sd */
214 default_set_sd, /* set_sd */
215 no_get_full_name, /* get_full_name */
216 no_lookup_name, /* lookup_name */
217 no_link_name, /* link_name */
218 NULL, /* unlink_name */
219 no_open_file, /* open_file */
220 no_kernel_obj_list, /* get_kernel_obj_list */
221 no_close_handle, /* close_handle */
222 fd_destroy /* destroy */
225 /* device object */
227 #define DEVICE_HASH_SIZE 7
228 #define INODE_HASH_SIZE 17
230 struct device
232 struct object obj; /* object header */
233 struct list entry; /* entry in device hash list */
234 dev_t dev; /* device number */
235 int removable; /* removable device? (or -1 if unknown) */
236 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
239 static void device_dump( struct object *obj, int verbose );
240 static void device_destroy( struct object *obj );
242 static const struct object_ops device_ops =
244 sizeof(struct device), /* size */
245 &no_type, /* type */
246 device_dump, /* dump */
247 no_add_queue, /* add_queue */
248 NULL, /* remove_queue */
249 NULL, /* signaled */
250 NULL, /* satisfied */
251 no_signal, /* signal */
252 no_get_fd, /* get_fd */
253 default_map_access, /* map_access */
254 default_get_sd, /* get_sd */
255 default_set_sd, /* set_sd */
256 no_get_full_name, /* get_full_name */
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 &no_type, /* type */
286 inode_dump, /* dump */
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 default_map_access, /* map_access */
294 default_get_sd, /* get_sd */
295 default_set_sd, /* set_sd */
296 no_get_full_name, /* get_full_name */
297 no_lookup_name, /* lookup_name */
298 no_link_name, /* link_name */
299 NULL, /* unlink_name */
300 no_open_file, /* open_file */
301 no_kernel_obj_list, /* get_kernel_obj_list */
302 no_close_handle, /* close_handle */
303 inode_destroy /* destroy */
306 /* file lock object */
308 struct file_lock
310 struct object obj; /* object header */
311 struct fd *fd; /* fd owning this lock */
312 struct list fd_entry; /* entry in list of locks on a given fd */
313 struct list inode_entry; /* entry in inode list of locks */
314 int shared; /* shared lock? */
315 file_pos_t start; /* locked region is interval [start;end) */
316 file_pos_t end;
317 struct process *process; /* process owning this lock */
318 struct list proc_entry; /* entry in list of locks owned by the process */
321 static void file_lock_dump( struct object *obj, int verbose );
322 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry );
324 static const struct object_ops file_lock_ops =
326 sizeof(struct file_lock), /* size */
327 &no_type, /* type */
328 file_lock_dump, /* dump */
329 add_queue, /* add_queue */
330 remove_queue, /* remove_queue */
331 file_lock_signaled, /* signaled */
332 no_satisfied, /* satisfied */
333 no_signal, /* signal */
334 no_get_fd, /* get_fd */
335 default_map_access, /* map_access */
336 default_get_sd, /* get_sd */
337 default_set_sd, /* set_sd */
338 no_get_full_name, /* get_full_name */
339 no_lookup_name, /* lookup_name */
340 no_link_name, /* link_name */
341 NULL, /* unlink_name */
342 no_open_file, /* open_file */
343 no_kernel_obj_list, /* get_kernel_obj_list */
344 no_close_handle, /* close_handle */
345 no_destroy /* destroy */
349 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
350 #define FILE_POS_T_MAX (~(file_pos_t)0)
352 static file_pos_t max_unix_offset = OFF_T_MAX;
354 #define DUMP_LONG_LONG(val) do { \
355 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
356 fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
357 else \
358 fprintf( stderr, "%lx", (unsigned long)(val) ); \
359 } while (0)
363 /****************************************************************/
364 /* timeouts support */
366 struct timeout_user
368 struct list entry; /* entry in sorted timeout list */
369 abstime_t when; /* timeout expiry */
370 timeout_callback callback; /* callback function */
371 void *private; /* callback private data */
374 static struct list abs_timeout_list = LIST_INIT(abs_timeout_list); /* sorted absolute timeouts list */
375 static struct list rel_timeout_list = LIST_INIT(rel_timeout_list); /* sorted relative timeouts list */
376 timeout_t current_time;
377 timeout_t monotonic_time;
379 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
380 static const int user_shared_data_timeout = 16;
382 static void atomic_store_ulong(volatile ULONG *ptr, ULONG value)
384 /* on x86 there should be total store order guarantees, so volatile is
385 * enough to ensure the stores aren't reordered by the compiler, and then
386 * they will always be seen in-order from other CPUs. On other archs, we
387 * need atomic intrinsics to guarantee that. */
388 #if defined(__i386__) || defined(__x86_64__)
389 *ptr = value;
390 #else
391 __atomic_store_n(ptr, value, __ATOMIC_SEQ_CST);
392 #endif
395 static void atomic_store_long(volatile LONG *ptr, LONG value)
397 #if defined(__i386__) || defined(__x86_64__)
398 *ptr = value;
399 #else
400 __atomic_store_n(ptr, value, __ATOMIC_SEQ_CST);
401 #endif
404 static void set_user_shared_data_time(void)
406 timeout_t tick_count = monotonic_time / 10000;
407 static timeout_t last_timezone_update;
408 timeout_t timezone_bias;
409 struct tm *tm;
410 time_t now;
412 if (monotonic_time - last_timezone_update > TICKS_PER_SEC)
414 now = time( NULL );
415 tm = gmtime( &now );
416 timezone_bias = mktime( tm ) - now;
417 tm = localtime( &now );
418 if (tm->tm_isdst) timezone_bias -= 3600;
419 timezone_bias *= TICKS_PER_SEC;
421 atomic_store_long(&user_shared_data->TimeZoneBias.High2Time, timezone_bias >> 32);
422 atomic_store_ulong(&user_shared_data->TimeZoneBias.LowPart, timezone_bias);
423 atomic_store_long(&user_shared_data->TimeZoneBias.High1Time, timezone_bias >> 32);
425 last_timezone_update = monotonic_time;
428 atomic_store_long(&user_shared_data->SystemTime.High2Time, current_time >> 32);
429 atomic_store_ulong(&user_shared_data->SystemTime.LowPart, current_time);
430 atomic_store_long(&user_shared_data->SystemTime.High1Time, current_time >> 32);
432 atomic_store_long(&user_shared_data->InterruptTime.High2Time, monotonic_time >> 32);
433 atomic_store_ulong(&user_shared_data->InterruptTime.LowPart, monotonic_time);
434 atomic_store_long(&user_shared_data->InterruptTime.High1Time, monotonic_time >> 32);
436 atomic_store_long(&user_shared_data->TickCount.High2Time, tick_count >> 32);
437 atomic_store_ulong(&user_shared_data->TickCount.LowPart, tick_count);
438 atomic_store_long(&user_shared_data->TickCount.High1Time, tick_count >> 32);
439 atomic_store_ulong(&user_shared_data->TickCountLowDeprecated, tick_count);
442 void set_current_time(void)
444 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
445 struct timeval now;
446 gettimeofday( &now, NULL );
447 current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
448 monotonic_time = monotonic_counter();
449 if (user_shared_data) set_user_shared_data_time();
452 /* add a timeout user */
453 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
455 struct timeout_user *user;
456 struct list *ptr;
458 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
459 user->when = timeout_to_abstime( when );
460 user->callback = func;
461 user->private = private;
463 /* Now insert it in the linked list */
465 if (user->when > 0)
467 LIST_FOR_EACH( ptr, &abs_timeout_list )
469 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
470 if (timeout->when >= user->when) break;
473 else
475 LIST_FOR_EACH( ptr, &rel_timeout_list )
477 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
478 if (timeout->when <= user->when) break;
481 list_add_before( ptr, &user->entry );
482 return user;
485 /* remove a timeout user */
486 void remove_timeout_user( struct timeout_user *user )
488 list_remove( &user->entry );
489 free( user );
492 /* return a text description of a timeout for debugging purposes */
493 const char *get_timeout_str( timeout_t timeout )
495 static char buffer[64];
496 long secs, nsecs;
498 if (!timeout) return "0";
499 if (timeout == TIMEOUT_INFINITE) return "infinite";
501 if (timeout < 0) /* relative */
503 secs = -timeout / TICKS_PER_SEC;
504 nsecs = -timeout % TICKS_PER_SEC;
505 sprintf( buffer, "+%ld.%07ld", secs, nsecs );
507 else /* absolute */
509 secs = (timeout - current_time) / TICKS_PER_SEC;
510 nsecs = (timeout - current_time) % TICKS_PER_SEC;
511 if (nsecs < 0)
513 nsecs += TICKS_PER_SEC;
514 secs--;
516 if (secs >= 0)
517 sprintf( buffer, "%x%08x (+%ld.%07ld)",
518 (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
519 else
520 sprintf( buffer, "%x%08x (-%ld.%07ld)",
521 (unsigned int)(timeout >> 32), (unsigned int)timeout,
522 -(secs + 1), TICKS_PER_SEC - nsecs );
524 return buffer;
528 /****************************************************************/
529 /* poll support */
531 static struct fd **poll_users; /* users array */
532 static struct pollfd *pollfd; /* poll fd array */
533 static int nb_users; /* count of array entries actually in use */
534 static int active_users; /* current number of active users */
535 static int allocated_users; /* count of allocated entries in the array */
536 static struct fd **freelist; /* list of free entries in the array */
538 static int get_next_timeout(void);
540 static inline void fd_poll_event( struct fd *fd, int event )
542 fd->fd_ops->poll_event( fd, event );
545 #ifdef USE_EPOLL
547 static int epoll_fd = -1;
549 static inline void init_epoll(void)
551 epoll_fd = epoll_create( 128 );
554 /* set the events that epoll waits for on this fd; helper for set_fd_events */
555 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
557 struct epoll_event ev;
558 int ctl;
560 if (epoll_fd == -1) return;
562 if (events == -1) /* stop waiting on this fd completely */
564 if (pollfd[user].fd == -1) return; /* already removed */
565 ctl = EPOLL_CTL_DEL;
567 else if (pollfd[user].fd == -1)
569 ctl = EPOLL_CTL_ADD;
571 else
573 if (pollfd[user].events == events) return; /* nothing to do */
574 ctl = EPOLL_CTL_MOD;
577 ev.events = events;
578 memset(&ev.data, 0, sizeof(ev.data));
579 ev.data.u32 = user;
581 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
583 if (errno == ENOMEM) /* not enough memory, give up on epoll */
585 close( epoll_fd );
586 epoll_fd = -1;
588 else perror( "epoll_ctl" ); /* should not happen */
592 static inline void remove_epoll_user( struct fd *fd, int user )
594 if (epoll_fd == -1) return;
596 if (pollfd[user].fd != -1)
598 struct epoll_event dummy;
599 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
603 static inline void main_loop_epoll(void)
605 int i, ret, timeout;
606 struct epoll_event events[128];
608 assert( POLLIN == EPOLLIN );
609 assert( POLLOUT == EPOLLOUT );
610 assert( POLLERR == EPOLLERR );
611 assert( POLLHUP == EPOLLHUP );
613 if (epoll_fd == -1) return;
615 while (active_users)
617 timeout = get_next_timeout();
619 if (!active_users) break; /* last user removed by a timeout */
620 if (epoll_fd == -1) break; /* an error occurred with epoll */
622 ret = epoll_wait( epoll_fd, events, ARRAY_SIZE( events ), timeout );
623 set_current_time();
625 /* put the events into the pollfd array first, like poll does */
626 for (i = 0; i < ret; i++)
628 int user = events[i].data.u32;
629 pollfd[user].revents = events[i].events;
632 /* read events from the pollfd array, as set_fd_events may modify them */
633 for (i = 0; i < ret; i++)
635 int user = events[i].data.u32;
636 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
641 #elif defined(HAVE_KQUEUE)
643 static int kqueue_fd = -1;
645 static inline void init_epoll(void)
647 kqueue_fd = kqueue();
650 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
652 struct kevent ev[2];
654 if (kqueue_fd == -1) return;
656 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)(long)user );
657 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)(long)user );
659 if (events == -1) /* stop waiting on this fd completely */
661 if (pollfd[user].fd == -1) return; /* already removed */
662 ev[0].flags |= EV_DELETE;
663 ev[1].flags |= EV_DELETE;
665 else if (pollfd[user].fd == -1)
667 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
668 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
670 else
672 if (pollfd[user].events == events) return; /* nothing to do */
673 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
674 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
677 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
679 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
681 close( kqueue_fd );
682 kqueue_fd = -1;
684 else perror( "kevent" ); /* should not happen */
688 static inline void remove_epoll_user( struct fd *fd, int user )
690 if (kqueue_fd == -1) return;
692 if (pollfd[user].fd != -1)
694 struct kevent ev[2];
696 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
697 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
698 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
702 static inline void main_loop_epoll(void)
704 int i, ret, timeout;
705 struct kevent events[128];
707 if (kqueue_fd == -1) return;
709 while (active_users)
711 timeout = get_next_timeout();
713 if (!active_users) break; /* last user removed by a timeout */
714 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
716 if (timeout != -1)
718 struct timespec ts;
720 ts.tv_sec = timeout / 1000;
721 ts.tv_nsec = (timeout % 1000) * 1000000;
722 ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), &ts );
724 else ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), NULL );
726 set_current_time();
728 /* put the events into the pollfd array first, like poll does */
729 for (i = 0; i < ret; i++)
731 long user = (long)events[i].udata;
732 pollfd[user].revents = 0;
734 for (i = 0; i < ret; i++)
736 long user = (long)events[i].udata;
737 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
738 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
739 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
740 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
743 /* read events from the pollfd array, as set_fd_events may modify them */
744 for (i = 0; i < ret; i++)
746 long user = (long)events[i].udata;
747 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
748 pollfd[user].revents = 0;
753 #elif defined(USE_EVENT_PORTS)
755 static int port_fd = -1;
757 static inline void init_epoll(void)
759 port_fd = port_create();
762 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
764 int ret;
766 if (port_fd == -1) return;
768 if (events == -1) /* stop waiting on this fd completely */
770 if (pollfd[user].fd == -1) return; /* already removed */
771 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
773 else if (pollfd[user].fd == -1)
775 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
777 else
779 if (pollfd[user].events == events) return; /* nothing to do */
780 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
783 if (ret == -1)
785 if (errno == ENOMEM) /* not enough memory, give up on port_associate */
787 close( port_fd );
788 port_fd = -1;
790 else perror( "port_associate" ); /* should not happen */
794 static inline void remove_epoll_user( struct fd *fd, int user )
796 if (port_fd == -1) return;
798 if (pollfd[user].fd != -1)
800 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
804 static inline void main_loop_epoll(void)
806 int i, nget, ret, timeout;
807 port_event_t events[128];
809 if (port_fd == -1) return;
811 while (active_users)
813 timeout = get_next_timeout();
814 nget = 1;
816 if (!active_users) break; /* last user removed by a timeout */
817 if (port_fd == -1) break; /* an error occurred with event completion */
819 if (timeout != -1)
821 struct timespec ts;
823 ts.tv_sec = timeout / 1000;
824 ts.tv_nsec = (timeout % 1000) * 1000000;
825 ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, &ts );
827 else ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, NULL );
829 if (ret == -1) break; /* an error occurred with event completion */
831 set_current_time();
833 /* put the events into the pollfd array first, like poll does */
834 for (i = 0; i < nget; i++)
836 long user = (long)events[i].portev_user;
837 pollfd[user].revents = events[i].portev_events;
840 /* read events from the pollfd array, as set_fd_events may modify them */
841 for (i = 0; i < nget; i++)
843 long user = (long)events[i].portev_user;
844 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
845 /* if we are still interested, reassociate the fd */
846 if (pollfd[user].fd != -1) {
847 port_associate( port_fd, PORT_SOURCE_FD, pollfd[user].fd, pollfd[user].events, (void *)user );
853 #else /* HAVE_KQUEUE */
855 static inline void init_epoll(void) { }
856 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
857 static inline void remove_epoll_user( struct fd *fd, int user ) { }
858 static inline void main_loop_epoll(void) { }
860 #endif /* USE_EPOLL */
863 /* add a user in the poll array and return its index, or -1 on failure */
864 static int add_poll_user( struct fd *fd )
866 int ret;
867 if (freelist)
869 ret = freelist - poll_users;
870 freelist = (struct fd **)poll_users[ret];
872 else
874 if (nb_users == allocated_users)
876 struct fd **newusers;
877 struct pollfd *newpoll;
878 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
879 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
880 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
882 if (allocated_users)
883 poll_users = newusers;
884 else
885 free( newusers );
886 return -1;
888 poll_users = newusers;
889 pollfd = newpoll;
890 if (!allocated_users) init_epoll();
891 allocated_users = new_count;
893 ret = nb_users++;
895 pollfd[ret].fd = -1;
896 pollfd[ret].events = 0;
897 pollfd[ret].revents = 0;
898 poll_users[ret] = fd;
899 active_users++;
900 return ret;
903 /* remove a user from the poll list */
904 static void remove_poll_user( struct fd *fd, int user )
906 assert( user >= 0 );
907 assert( poll_users[user] == fd );
909 remove_epoll_user( fd, user );
910 pollfd[user].fd = -1;
911 pollfd[user].events = 0;
912 pollfd[user].revents = 0;
913 poll_users[user] = (struct fd *)freelist;
914 freelist = &poll_users[user];
915 active_users--;
918 /* process pending timeouts and return the time until the next timeout, in milliseconds */
919 static int get_next_timeout(void)
921 int ret = user_shared_data ? user_shared_data_timeout : -1;
923 if (!list_empty( &abs_timeout_list ) || !list_empty( &rel_timeout_list ))
925 struct list expired_list, *ptr;
927 /* first remove all expired timers from the list */
929 list_init( &expired_list );
930 while ((ptr = list_head( &abs_timeout_list )) != NULL)
932 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
934 if (timeout->when <= current_time)
936 list_remove( &timeout->entry );
937 list_add_tail( &expired_list, &timeout->entry );
939 else break;
941 while ((ptr = list_head( &rel_timeout_list )) != NULL)
943 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
945 if (-timeout->when <= monotonic_time)
947 list_remove( &timeout->entry );
948 list_add_tail( &expired_list, &timeout->entry );
950 else break;
953 /* now call the callback for all the removed timers */
955 while ((ptr = list_head( &expired_list )) != NULL)
957 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
958 list_remove( &timeout->entry );
959 timeout->callback( timeout->private );
960 free( timeout );
963 if ((ptr = list_head( &abs_timeout_list )) != NULL)
965 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
966 timeout_t diff = (timeout->when - current_time + 9999) / 10000;
967 if (diff > INT_MAX) diff = INT_MAX;
968 else if (diff < 0) diff = 0;
969 if (ret == -1 || diff < ret) ret = diff;
972 if ((ptr = list_head( &rel_timeout_list )) != NULL)
974 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
975 timeout_t diff = (-timeout->when - monotonic_time + 9999) / 10000;
976 if (diff > INT_MAX) diff = INT_MAX;
977 else if (diff < 0) diff = 0;
978 if (ret == -1 || diff < ret) ret = diff;
981 return ret;
984 /* server main poll() loop */
985 void main_loop(void)
987 int i, ret, timeout;
989 set_current_time();
990 server_start_time = current_time;
992 main_loop_epoll();
993 /* fall through to normal poll loop */
995 while (active_users)
997 timeout = get_next_timeout();
999 if (!active_users) break; /* last user removed by a timeout */
1001 ret = poll( pollfd, nb_users, timeout );
1002 set_current_time();
1004 if (ret > 0)
1006 for (i = 0; i < nb_users; i++)
1008 if (pollfd[i].revents)
1010 fd_poll_event( poll_users[i], pollfd[i].revents );
1011 if (!--ret) break;
1019 /****************************************************************/
1020 /* device functions */
1022 static struct list device_hash[DEVICE_HASH_SIZE];
1024 static int is_device_removable( dev_t dev, int unix_fd )
1026 #if defined(linux) && defined(HAVE_FSTATFS)
1027 struct statfs stfs;
1029 /* check for floppy disk */
1030 if (major(dev) == FLOPPY_MAJOR) return 1;
1032 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
1033 return (stfs.f_type == 0x9660 || /* iso9660 */
1034 stfs.f_type == 0x9fa1 || /* supermount */
1035 stfs.f_type == 0x15013346); /* udf */
1036 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
1037 struct statfs stfs;
1039 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
1040 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
1041 #elif defined(__NetBSD__)
1042 struct statvfs stfs;
1044 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
1045 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
1046 #elif defined(sun)
1047 # include <sys/dkio.h>
1048 # include <sys/vtoc.h>
1049 struct dk_cinfo dkinf;
1050 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
1051 return (dkinf.dki_ctype == DKC_CDROM ||
1052 dkinf.dki_ctype == DKC_NCRFLOPPY ||
1053 dkinf.dki_ctype == DKC_SMSFLOPPY ||
1054 dkinf.dki_ctype == DKC_INTEL82072 ||
1055 dkinf.dki_ctype == DKC_INTEL82077);
1056 #else
1057 return 0;
1058 #endif
1061 /* retrieve the device object for a given fd, creating it if needed */
1062 static struct device *get_device( dev_t dev, int unix_fd )
1064 struct device *device;
1065 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
1067 if (device_hash[hash].next)
1069 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
1070 if (device->dev == dev) return (struct device *)grab_object( device );
1072 else list_init( &device_hash[hash] );
1074 /* not found, create it */
1076 if (unix_fd == -1) return NULL;
1077 if ((device = alloc_object( &device_ops )))
1079 device->dev = dev;
1080 device->removable = is_device_removable( dev, unix_fd );
1081 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
1082 list_add_head( &device_hash[hash], &device->entry );
1084 return device;
1087 static void device_dump( struct object *obj, int verbose )
1089 struct device *device = (struct device *)obj;
1090 fprintf( stderr, "Device dev=" );
1091 DUMP_LONG_LONG( device->dev );
1092 fprintf( stderr, "\n" );
1095 static void device_destroy( struct object *obj )
1097 struct device *device = (struct device *)obj;
1098 unsigned int i;
1100 for (i = 0; i < INODE_HASH_SIZE; i++)
1101 assert( list_empty(&device->inode_hash[i]) );
1103 list_remove( &device->entry ); /* remove it from the hash table */
1106 /****************************************************************/
1107 /* inode functions */
1109 static void unlink_closed_fd( struct inode *inode, struct closed_fd *fd )
1111 /* make sure it is still the same file */
1112 struct stat st;
1113 if (!stat( fd->unix_name, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
1115 if (S_ISDIR(st.st_mode)) rmdir( fd->unix_name );
1116 else unlink( fd->unix_name );
1120 /* close all pending file descriptors in the closed list */
1121 static void inode_close_pending( struct inode *inode, int keep_unlinks )
1123 struct list *ptr = list_head( &inode->closed );
1125 while (ptr)
1127 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1128 struct list *next = list_next( &inode->closed, ptr );
1130 if (fd->unix_fd != -1)
1132 close( fd->unix_fd );
1133 fd->unix_fd = -1;
1136 /* get rid of it unless there's an unlink pending on that file */
1137 if (!keep_unlinks || !(fd->disp_flags & FILE_DISPOSITION_DELETE))
1139 list_remove( ptr );
1140 free( fd->unix_name );
1141 free( fd );
1143 ptr = next;
1147 static void inode_dump( struct object *obj, int verbose )
1149 struct inode *inode = (struct inode *)obj;
1150 fprintf( stderr, "Inode device=%p ino=", inode->device );
1151 DUMP_LONG_LONG( inode->ino );
1152 fprintf( stderr, "\n" );
1155 static void inode_destroy( struct object *obj )
1157 struct inode *inode = (struct inode *)obj;
1158 struct list *ptr;
1160 assert( list_empty(&inode->open) );
1161 assert( list_empty(&inode->locks) );
1163 list_remove( &inode->entry );
1165 while ((ptr = list_head( &inode->closed )))
1167 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1168 list_remove( ptr );
1169 if (fd->unix_fd != -1) close( fd->unix_fd );
1170 if (fd->disp_flags & FILE_DISPOSITION_DELETE)
1171 unlink_closed_fd( inode, fd );
1172 free( fd->unix_name );
1173 free( fd );
1175 release_object( inode->device );
1178 /* retrieve the inode object for a given fd, creating it if needed */
1179 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
1181 struct device *device;
1182 struct inode *inode;
1183 unsigned int hash = ino % INODE_HASH_SIZE;
1185 if (!(device = get_device( dev, unix_fd ))) return NULL;
1187 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
1189 if (inode->ino == ino)
1191 release_object( device );
1192 return (struct inode *)grab_object( inode );
1196 /* not found, create it */
1197 if ((inode = alloc_object( &inode_ops )))
1199 inode->device = device;
1200 inode->ino = ino;
1201 list_init( &inode->open );
1202 list_init( &inode->locks );
1203 list_init( &inode->closed );
1204 list_add_head( &device->inode_hash[hash], &inode->entry );
1206 else release_object( device );
1208 return inode;
1211 /* add fd to the inode list of file descriptors to close */
1212 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1214 if (!list_empty( &inode->locks ))
1216 list_add_head( &inode->closed, &fd->entry );
1218 else if ((fd->disp_flags & FILE_DISPOSITION_DELETE) &&
1219 (fd->disp_flags & FILE_DISPOSITION_POSIX_SEMANTICS))
1221 /* close the fd and unlink it at once */
1222 if (fd->unix_fd != -1) close( fd->unix_fd );
1223 unlink_closed_fd( inode, fd );
1224 free( fd->unix_name );
1225 free( fd );
1227 else if (fd->disp_flags & FILE_DISPOSITION_DELETE)
1229 /* close the fd but keep the structure around for unlink */
1230 if (fd->unix_fd != -1) close( fd->unix_fd );
1231 fd->unix_fd = -1;
1232 list_add_head( &inode->closed, &fd->entry );
1234 else /* no locks on this inode and no unlink, get rid of the fd */
1236 if (fd->unix_fd != -1) close( fd->unix_fd );
1237 free( fd->unix_name );
1238 free( fd );
1243 /****************************************************************/
1244 /* file lock functions */
1246 static void file_lock_dump( struct object *obj, int verbose )
1248 struct file_lock *lock = (struct file_lock *)obj;
1249 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1250 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1251 DUMP_LONG_LONG( lock->start );
1252 fprintf( stderr, " end=" );
1253 DUMP_LONG_LONG( lock->end );
1254 fprintf( stderr, "\n" );
1257 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry )
1259 struct file_lock *lock = (struct file_lock *)obj;
1260 /* lock is signaled if it has lost its owner */
1261 return !lock->process;
1264 /* set (or remove) a Unix lock if possible for the given range */
1265 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1267 struct flock fl;
1269 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1270 for (;;)
1272 if (start == end) return 1; /* can't set zero-byte lock */
1273 if (start > max_unix_offset) return 1; /* ignore it */
1274 fl.l_type = type;
1275 fl.l_whence = SEEK_SET;
1276 fl.l_start = start;
1277 if (!end || end > max_unix_offset) fl.l_len = 0;
1278 else fl.l_len = end - start;
1279 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1281 switch(errno)
1283 case EACCES:
1284 /* check whether locks work at all on this file system */
1285 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1287 set_error( STATUS_FILE_LOCK_CONFLICT );
1288 return 0;
1290 /* fall through */
1291 case EIO:
1292 case ENOLCK:
1293 case ENOTSUP:
1294 /* no locking on this fs, just ignore it */
1295 fd->fs_locks = 0;
1296 return 1;
1297 case EAGAIN:
1298 set_error( STATUS_FILE_LOCK_CONFLICT );
1299 return 0;
1300 case EBADF:
1301 /* this can happen if we try to set a write lock on a read-only file */
1302 /* try to at least grab a read lock */
1303 if (fl.l_type == F_WRLCK)
1305 type = F_RDLCK;
1306 break; /* retry */
1308 set_error( STATUS_ACCESS_DENIED );
1309 return 0;
1310 #ifdef EOVERFLOW
1311 case EOVERFLOW:
1312 #endif
1313 case EINVAL:
1314 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1315 /* in that case we shrink the limit and retry */
1316 if (max_unix_offset > INT_MAX)
1318 max_unix_offset = INT_MAX;
1319 break; /* retry */
1321 /* fall through */
1322 default:
1323 file_set_error();
1324 return 0;
1329 /* check if interval [start;end) overlaps the lock */
1330 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1332 if (lock->end && start >= lock->end) return 0;
1333 if (end && lock->start >= end) return 0;
1334 return 1;
1337 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1338 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1340 struct hole
1342 struct hole *next;
1343 struct hole *prev;
1344 file_pos_t start;
1345 file_pos_t end;
1346 } *first, *cur, *next, *buffer;
1348 struct list *ptr;
1349 int count = 0;
1351 if (!fd->inode) return;
1352 if (!fd->fs_locks) return;
1353 if (start == end || start > max_unix_offset) return;
1354 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1356 /* count the number of locks overlapping the specified area */
1358 LIST_FOR_EACH( ptr, &fd->inode->locks )
1360 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1361 if (lock->start == lock->end) continue;
1362 if (lock_overlaps( lock, start, end )) count++;
1365 if (!count) /* no locks at all, we can unlock everything */
1367 set_unix_lock( fd, start, end, F_UNLCK );
1368 return;
1371 /* allocate space for the list of holes */
1372 /* max. number of holes is number of locks + 1 */
1374 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1375 first = buffer;
1376 first->next = NULL;
1377 first->prev = NULL;
1378 first->start = start;
1379 first->end = end;
1380 next = first + 1;
1382 /* build a sorted list of unlocked holes in the specified area */
1384 LIST_FOR_EACH( ptr, &fd->inode->locks )
1386 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1387 if (lock->start == lock->end) continue;
1388 if (!lock_overlaps( lock, start, end )) continue;
1390 /* go through all the holes touched by this lock */
1391 for (cur = first; cur; cur = cur->next)
1393 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1394 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1396 /* now we know that lock is overlapping hole */
1398 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1400 cur->start = lock->end;
1401 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1402 /* now hole is empty, remove it */
1403 if (cur->next) cur->next->prev = cur->prev;
1404 if (cur->prev) cur->prev->next = cur->next;
1405 else if (!(first = cur->next)) goto done; /* no more holes at all */
1407 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1409 cur->end = lock->start;
1410 assert( cur->start < cur->end );
1412 else /* lock is in the middle of hole, split hole in two */
1414 next->prev = cur;
1415 next->next = cur->next;
1416 cur->next = next;
1417 next->start = lock->end;
1418 next->end = cur->end;
1419 cur->end = lock->start;
1420 assert( next->start < next->end );
1421 assert( cur->end < next->start );
1422 next++;
1423 break; /* done with this lock */
1428 /* clear Unix locks for all the holes */
1430 for (cur = first; cur; cur = cur->next)
1431 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1433 done:
1434 free( buffer );
1437 /* create a new lock on a fd */
1438 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1440 struct file_lock *lock;
1442 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1443 lock->shared = shared;
1444 lock->start = start;
1445 lock->end = end;
1446 lock->fd = fd;
1447 lock->process = current->process;
1449 /* now try to set a Unix lock */
1450 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1452 release_object( lock );
1453 return NULL;
1455 list_add_tail( &fd->locks, &lock->fd_entry );
1456 list_add_tail( &fd->inode->locks, &lock->inode_entry );
1457 list_add_tail( &lock->process->locks, &lock->proc_entry );
1458 return lock;
1461 /* remove an existing lock */
1462 static void remove_lock( struct file_lock *lock, int remove_unix )
1464 struct inode *inode = lock->fd->inode;
1466 list_remove( &lock->fd_entry );
1467 list_remove( &lock->inode_entry );
1468 list_remove( &lock->proc_entry );
1469 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1470 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1471 lock->process = NULL;
1472 wake_up( &lock->obj, 0 );
1473 release_object( lock );
1476 /* remove all locks owned by a given process */
1477 void remove_process_locks( struct process *process )
1479 struct list *ptr;
1481 while ((ptr = list_head( &process->locks )))
1483 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1484 remove_lock( lock, 1 ); /* this removes it from the list */
1488 /* remove all locks on a given fd */
1489 static void remove_fd_locks( struct fd *fd )
1491 file_pos_t start = FILE_POS_T_MAX, end = 0;
1492 struct list *ptr;
1494 while ((ptr = list_head( &fd->locks )))
1496 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1497 if (lock->start < start) start = lock->start;
1498 if (!lock->end || lock->end > end) end = lock->end - 1;
1499 remove_lock( lock, 0 );
1501 if (start < end) remove_unix_locks( fd, start, end + 1 );
1504 /* add a lock on an fd */
1505 /* returns handle to wait on */
1506 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1508 struct list *ptr;
1509 file_pos_t end = start + count;
1511 if (!fd->inode) /* not a regular file */
1513 set_error( STATUS_INVALID_DEVICE_REQUEST );
1514 return 0;
1517 /* don't allow wrapping locks */
1518 if (end && end < start)
1520 set_error( STATUS_INVALID_PARAMETER );
1521 return 0;
1524 /* check if another lock on that file overlaps the area */
1525 LIST_FOR_EACH( ptr, &fd->inode->locks )
1527 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1528 if (!lock_overlaps( lock, start, end )) continue;
1529 if (shared && (lock->shared || lock->fd == fd)) continue;
1530 /* found one */
1531 if (!wait)
1533 set_error( STATUS_FILE_LOCK_CONFLICT );
1534 return 0;
1536 set_error( STATUS_PENDING );
1537 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1540 /* not found, add it */
1541 if (add_lock( fd, shared, start, end )) return 0;
1542 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1544 /* Unix lock conflict -> tell client to wait and retry */
1545 if (wait) set_error( STATUS_PENDING );
1547 return 0;
1550 /* remove a lock on an fd */
1551 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1553 struct list *ptr;
1554 file_pos_t end = start + count;
1556 /* find an existing lock with the exact same parameters */
1557 LIST_FOR_EACH( ptr, &fd->locks )
1559 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1560 if ((lock->start == start) && (lock->end == end))
1562 remove_lock( lock, 1 );
1563 return;
1566 set_error( STATUS_FILE_LOCK_CONFLICT );
1570 /****************************************************************/
1571 /* file descriptor functions */
1573 static void fd_dump( struct object *obj, int verbose )
1575 struct fd *fd = (struct fd *)obj;
1576 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1577 if (fd->inode) fprintf( stderr, " inode=%p disp_flags=%x", fd->inode, fd->closed->disp_flags );
1578 fprintf( stderr, "\n" );
1581 static void fd_destroy( struct object *obj )
1583 struct fd *fd = (struct fd *)obj;
1585 free_async_queue( &fd->read_q );
1586 free_async_queue( &fd->write_q );
1587 free_async_queue( &fd->wait_q );
1589 if (fd->completion) release_object( fd->completion );
1590 remove_fd_locks( fd );
1591 list_remove( &fd->inode_entry );
1592 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1593 free( fd->nt_name );
1594 if (fd->inode)
1596 inode_add_closed_fd( fd->inode, fd->closed );
1597 release_object( fd->inode );
1599 else /* no inode, close it right away */
1601 if (fd->unix_fd != -1) close( fd->unix_fd );
1602 free( fd->unix_name );
1606 /* check if the desired access is possible without violating */
1607 /* the sharing mode of other opens of the same file */
1608 static unsigned int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing,
1609 unsigned int open_flags, unsigned int options )
1611 /* only a few access bits are meaningful wrt sharing */
1612 const unsigned int read_access = FILE_READ_DATA | FILE_EXECUTE;
1613 const unsigned int write_access = FILE_WRITE_DATA | FILE_APPEND_DATA;
1614 const unsigned int all_access = read_access | write_access | DELETE;
1616 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1617 unsigned int existing_access = 0;
1618 struct list *ptr;
1620 fd->access = access;
1621 fd->sharing = sharing;
1623 LIST_FOR_EACH( ptr, &fd->inode->open )
1625 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1626 if (fd_ptr != fd)
1628 /* if access mode is 0, sharing mode is ignored */
1629 if (fd_ptr->access & all_access) existing_sharing &= fd_ptr->sharing;
1630 existing_access |= fd_ptr->access;
1634 if (((access & read_access) && !(existing_sharing & FILE_SHARE_READ)) ||
1635 ((access & write_access) && !(existing_sharing & FILE_SHARE_WRITE)) ||
1636 ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)))
1637 return STATUS_SHARING_VIOLATION;
1638 if (((existing_access & FILE_MAPPING_WRITE) && !(sharing & FILE_SHARE_WRITE)) ||
1639 ((existing_access & FILE_MAPPING_IMAGE) && (access & FILE_WRITE_DATA)))
1640 return STATUS_SHARING_VIOLATION;
1641 if ((existing_access & FILE_MAPPING_IMAGE) && (options & FILE_DELETE_ON_CLOSE))
1642 return STATUS_CANNOT_DELETE;
1643 if ((existing_access & FILE_MAPPING_ACCESS) && (open_flags & O_TRUNC))
1644 return STATUS_USER_MAPPED_FILE;
1645 if (!(access & all_access))
1646 return 0; /* if access mode is 0, sharing mode is ignored (except for mappings) */
1647 if (((existing_access & read_access) && !(sharing & FILE_SHARE_READ)) ||
1648 ((existing_access & write_access) && !(sharing & FILE_SHARE_WRITE)) ||
1649 ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)))
1650 return STATUS_SHARING_VIOLATION;
1651 return 0;
1654 /* set the events that select waits for on this fd */
1655 void set_fd_events( struct fd *fd, int events )
1657 int user = fd->poll_index;
1658 assert( poll_users[user] == fd );
1660 set_fd_epoll_events( fd, user, events );
1662 if (events == -1) /* stop waiting on this fd completely */
1664 pollfd[user].fd = -1;
1665 pollfd[user].events = POLLERR;
1666 pollfd[user].revents = 0;
1668 else
1670 pollfd[user].fd = fd->unix_fd;
1671 pollfd[user].events = events;
1675 /* prepare an fd for unmounting its corresponding device */
1676 static inline void unmount_fd( struct fd *fd )
1678 assert( fd->inode );
1680 async_wake_up( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1681 async_wake_up( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1683 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1685 if (fd->unix_fd != -1) close( fd->unix_fd );
1687 fd->unix_fd = -1;
1688 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1689 fd->closed->unix_fd = -1;
1690 fd->closed->disp_flags = 0;
1692 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1693 fd->fs_locks = 0;
1696 /* allocate an fd object, without setting the unix fd yet */
1697 static struct fd *alloc_fd_object(void)
1699 struct fd *fd = alloc_object( &fd_ops );
1701 if (!fd) return NULL;
1703 fd->fd_ops = NULL;
1704 fd->user = NULL;
1705 fd->inode = NULL;
1706 fd->closed = NULL;
1707 fd->access = 0;
1708 fd->options = 0;
1709 fd->sharing = 0;
1710 fd->unix_fd = -1;
1711 fd->unix_name = NULL;
1712 fd->nt_name = NULL;
1713 fd->nt_namelen = 0;
1714 fd->cacheable = 0;
1715 fd->signaled = 1;
1716 fd->fs_locks = 1;
1717 fd->poll_index = -1;
1718 fd->completion = NULL;
1719 fd->comp_flags = 0;
1720 init_async_queue( &fd->read_q );
1721 init_async_queue( &fd->write_q );
1722 init_async_queue( &fd->wait_q );
1723 list_init( &fd->inode_entry );
1724 list_init( &fd->locks );
1726 if ((fd->poll_index = add_poll_user( fd )) == -1)
1728 release_object( fd );
1729 return NULL;
1731 return fd;
1734 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1735 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1737 struct fd *fd = alloc_object( &fd_ops );
1739 if (!fd) return NULL;
1741 fd->fd_ops = fd_user_ops;
1742 fd->user = user;
1743 fd->inode = NULL;
1744 fd->closed = NULL;
1745 fd->access = 0;
1746 fd->options = options;
1747 fd->sharing = 0;
1748 fd->unix_name = NULL;
1749 fd->nt_name = NULL;
1750 fd->nt_namelen = 0;
1751 fd->unix_fd = -1;
1752 fd->cacheable = 0;
1753 fd->signaled = 1;
1754 fd->fs_locks = 0;
1755 fd->poll_index = -1;
1756 fd->completion = NULL;
1757 fd->comp_flags = 0;
1758 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1759 init_async_queue( &fd->read_q );
1760 init_async_queue( &fd->write_q );
1761 init_async_queue( &fd->wait_q );
1762 list_init( &fd->inode_entry );
1763 list_init( &fd->locks );
1764 return fd;
1767 /* duplicate an fd object for a different user */
1768 struct fd *dup_fd_object( struct fd *orig, unsigned int access, unsigned int sharing, unsigned int options )
1770 unsigned int err;
1771 struct fd *fd = alloc_fd_object();
1773 if (!fd) return NULL;
1775 fd->options = options;
1776 fd->cacheable = orig->cacheable;
1778 if (orig->unix_name)
1780 if (!(fd->unix_name = mem_alloc( strlen(orig->unix_name) + 1 ))) goto failed;
1781 strcpy( fd->unix_name, orig->unix_name );
1783 if (orig->nt_namelen)
1785 if (!(fd->nt_name = memdup( orig->nt_name, orig->nt_namelen ))) goto failed;
1786 fd->nt_namelen = orig->nt_namelen;
1789 if (orig->inode)
1791 struct closed_fd *closed = mem_alloc( sizeof(*closed) );
1792 if (!closed) goto failed;
1793 if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1795 file_set_error();
1796 free( closed );
1797 goto failed;
1799 closed->unix_fd = fd->unix_fd;
1800 closed->disp_flags = 0;
1801 closed->unix_name = fd->unix_name;
1802 fd->closed = closed;
1803 fd->inode = (struct inode *)grab_object( orig->inode );
1804 list_add_head( &fd->inode->open, &fd->inode_entry );
1805 if ((err = check_sharing( fd, access, sharing, 0, options )))
1807 set_error( err );
1808 goto failed;
1811 else if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1813 file_set_error();
1814 goto failed;
1816 return fd;
1818 failed:
1819 release_object( fd );
1820 return NULL;
1823 /* find an existing fd object that can be reused for a mapping */
1824 struct fd *get_fd_object_for_mapping( struct fd *fd, unsigned int access, unsigned int sharing )
1826 struct fd *fd_ptr;
1828 if (!fd->inode) return NULL;
1830 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
1831 if (fd_ptr->access == access && fd_ptr->sharing == sharing)
1832 return (struct fd *)grab_object( fd_ptr );
1834 return NULL;
1837 /* sets the user of an fd that previously had no user */
1838 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1840 assert( fd->fd_ops == NULL );
1841 fd->fd_ops = user_ops;
1842 fd->user = user;
1845 char *dup_fd_name( struct fd *root, const char *name )
1847 char *ret;
1849 if (!root) return strdup( name );
1850 if (!root->unix_name) return NULL;
1852 /* skip . prefix */
1853 if (name[0] == '.' && (!name[1] || name[1] == '/')) name++;
1855 if ((ret = malloc( strlen(root->unix_name) + strlen(name) + 2 )))
1857 strcpy( ret, root->unix_name );
1858 if (name[0] && name[0] != '/') strcat( ret, "/" );
1859 strcat( ret, name );
1861 return ret;
1864 static WCHAR *dup_nt_name( struct fd *root, struct unicode_str name, data_size_t *len )
1866 WCHAR *ret;
1867 data_size_t retlen;
1869 if (!root)
1871 *len = name.len;
1872 if (!name.len) return NULL;
1873 return memdup( name.str, name.len );
1875 if (!root->nt_namelen) return NULL;
1876 retlen = root->nt_namelen;
1878 /* skip . prefix */
1879 if (name.len && name.str[0] == '.' && (name.len == sizeof(WCHAR) || name.str[1] == '\\'))
1881 name.str++;
1882 name.len -= sizeof(WCHAR);
1884 if ((ret = malloc( retlen + name.len + sizeof(WCHAR) )))
1886 memcpy( ret, root->nt_name, root->nt_namelen );
1887 if (name.len && name.str[0] != '\\' &&
1888 root->nt_namelen && root->nt_name[root->nt_namelen / sizeof(WCHAR) - 1] != '\\')
1890 ret[retlen / sizeof(WCHAR)] = '\\';
1891 retlen += sizeof(WCHAR);
1893 memcpy( ret + retlen / sizeof(WCHAR), name.str, name.len );
1894 *len = retlen + name.len;
1896 return ret;
1899 void get_nt_name( struct fd *fd, struct unicode_str *name )
1901 name->str = fd->nt_name;
1902 name->len = fd->nt_namelen;
1905 /* open() wrapper that returns a struct fd with no fd user set */
1906 struct fd *open_fd( struct fd *root, const char *name, struct unicode_str nt_name,
1907 int flags, mode_t *mode, unsigned int access,
1908 unsigned int sharing, unsigned int options )
1910 struct stat st;
1911 struct closed_fd *closed_fd;
1912 struct fd *fd;
1913 int root_fd = -1;
1914 int rw_mode;
1915 char *path;
1917 if (((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE)) ||
1918 ((options & FILE_DIRECTORY_FILE) && (flags & O_TRUNC)))
1920 set_error( STATUS_INVALID_PARAMETER );
1921 return NULL;
1924 if (!(fd = alloc_fd_object())) return NULL;
1926 fd->options = options;
1927 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
1929 release_object( fd );
1930 return NULL;
1933 if (root)
1935 if ((root_fd = get_unix_fd( root )) == -1) goto error;
1936 if (fchdir( root_fd ) == -1)
1938 file_set_error();
1939 root_fd = -1;
1940 goto error;
1944 /* create the directory if needed */
1945 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1947 if (mkdir( name, *mode ) == -1)
1949 if (errno != EEXIST || (flags & O_EXCL))
1951 file_set_error();
1952 goto error;
1955 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1958 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1960 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1961 else rw_mode = O_WRONLY;
1963 else rw_mode = O_RDONLY;
1965 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1967 /* if we tried to open a directory for write access, retry read-only */
1968 if (errno == EISDIR)
1970 if ((access & FILE_UNIX_WRITE_ACCESS) || (flags & O_CREAT))
1971 fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode );
1974 if (fd->unix_fd == -1)
1976 /* check for trailing slash on file path */
1977 if ((errno == ENOENT || errno == ENOTDIR) && name[strlen(name) - 1] == '/')
1978 set_error( STATUS_OBJECT_NAME_INVALID );
1979 else
1980 file_set_error();
1981 goto error;
1985 fd->nt_name = dup_nt_name( root, nt_name, &fd->nt_namelen );
1986 fd->unix_name = NULL;
1987 if ((path = dup_fd_name( root, name )))
1989 fd->unix_name = realpath( path, NULL );
1990 free( path );
1993 closed_fd->unix_fd = fd->unix_fd;
1994 closed_fd->disp_flags = 0;
1995 closed_fd->unix_name = fd->unix_name;
1996 fstat( fd->unix_fd, &st );
1997 *mode = st.st_mode;
1999 /* only bother with an inode for normal files and directories */
2000 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
2002 unsigned int err;
2003 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
2005 if (!inode)
2007 /* we can close the fd because there are no others open on the same file,
2008 * otherwise we wouldn't have failed to allocate a new inode
2010 goto error;
2012 fd->inode = inode;
2013 fd->closed = closed_fd;
2014 fd->cacheable = !inode->device->removable;
2015 list_add_head( &inode->open, &fd->inode_entry );
2016 closed_fd = NULL;
2018 /* check directory options */
2019 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
2021 set_error( STATUS_NOT_A_DIRECTORY );
2022 goto error;
2024 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
2026 set_error( STATUS_FILE_IS_A_DIRECTORY );
2027 goto error;
2029 if ((err = check_sharing( fd, access, sharing, flags, options )))
2031 set_error( err );
2032 goto error;
2035 /* can't unlink files if we don't have permission to access */
2036 if ((options & FILE_DELETE_ON_CLOSE) && !(flags & O_CREAT) &&
2037 !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2039 set_error( STATUS_CANNOT_DELETE );
2040 goto error;
2043 fd->closed->disp_flags = (options & FILE_DELETE_ON_CLOSE) ?
2044 FILE_DISPOSITION_DELETE : 0;
2045 if (flags & O_TRUNC)
2047 if (S_ISDIR(st.st_mode))
2049 set_error( STATUS_OBJECT_NAME_COLLISION );
2050 goto error;
2052 ftruncate( fd->unix_fd, 0 );
2055 else /* special file */
2057 if (options & FILE_DELETE_ON_CLOSE) /* we can't unlink special files */
2059 set_error( STATUS_INVALID_PARAMETER );
2060 goto error;
2062 free( closed_fd );
2063 fd->cacheable = 1;
2066 #ifdef HAVE_POSIX_FADVISE
2067 switch (options & (FILE_SEQUENTIAL_ONLY | FILE_RANDOM_ACCESS))
2069 case FILE_SEQUENTIAL_ONLY:
2070 posix_fadvise( fd->unix_fd, 0, 0, POSIX_FADV_SEQUENTIAL );
2071 break;
2072 case FILE_RANDOM_ACCESS:
2073 posix_fadvise( fd->unix_fd, 0, 0, POSIX_FADV_RANDOM );
2074 break;
2076 #endif
2078 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
2079 return fd;
2081 error:
2082 release_object( fd );
2083 free( closed_fd );
2084 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
2085 return NULL;
2088 /* create an fd for an anonymous file */
2089 /* if the function fails the unix fd is closed */
2090 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
2091 unsigned int options )
2093 struct fd *fd = alloc_fd_object();
2095 if (fd)
2097 set_fd_user( fd, fd_user_ops, user );
2098 fd->unix_fd = unix_fd;
2099 fd->options = options;
2100 return fd;
2102 close( unix_fd );
2103 return NULL;
2106 /* retrieve the object that is using an fd */
2107 void *get_fd_user( struct fd *fd )
2109 return fd->user;
2112 /* retrieve the opening options for the fd */
2113 unsigned int get_fd_options( struct fd *fd )
2115 return fd->options;
2118 /* retrieve the completion flags for the fd */
2119 unsigned int get_fd_comp_flags( struct fd *fd )
2121 return fd->comp_flags;
2124 /* check if fd is in overlapped mode */
2125 int is_fd_overlapped( struct fd *fd )
2127 return !(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
2130 /* retrieve the unix fd for an object */
2131 int get_unix_fd( struct fd *fd )
2133 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
2134 return fd->unix_fd;
2137 /* check if two file descriptors point to the same file */
2138 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
2140 return fd1->inode == fd2->inode;
2143 /* allow the fd to be cached (can't be reset once set) */
2144 void allow_fd_caching( struct fd *fd )
2146 fd->cacheable = 1;
2149 /* check if fd is on a removable device */
2150 int is_fd_removable( struct fd *fd )
2152 return (fd->inode && fd->inode->device->removable);
2155 /* set or clear the fd signaled state */
2156 void set_fd_signaled( struct fd *fd, int signaled )
2158 if (fd->comp_flags & FILE_SKIP_SET_EVENT_ON_HANDLE) return;
2159 fd->signaled = signaled;
2160 if (signaled) wake_up( fd->user, 0 );
2163 /* check if events are pending and if yes return which one(s) */
2164 int check_fd_events( struct fd *fd, int events )
2166 struct pollfd pfd;
2168 if (fd->unix_fd == -1) return POLLERR;
2169 if (fd->inode) return events; /* regular files are always signaled */
2171 pfd.fd = fd->unix_fd;
2172 pfd.events = events;
2173 if (poll( &pfd, 1, 0 ) <= 0) return 0;
2174 return pfd.revents;
2177 /* default signaled() routine for objects that poll() on an fd */
2178 int default_fd_signaled( struct object *obj, struct wait_queue_entry *entry )
2180 struct fd *fd = get_obj_fd( obj );
2181 int ret = fd->signaled;
2182 release_object( fd );
2183 return ret;
2186 int default_fd_get_poll_events( struct fd *fd )
2188 int events = 0;
2190 if (async_waiting( &fd->read_q )) events |= POLLIN;
2191 if (async_waiting( &fd->write_q )) events |= POLLOUT;
2192 return events;
2195 /* default handler for poll() events */
2196 void default_poll_event( struct fd *fd, int event )
2198 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( &fd->read_q, STATUS_ALERTED );
2199 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( &fd->write_q, STATUS_ALERTED );
2201 /* if an error occurred, stop polling this fd to avoid busy-looping */
2202 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
2203 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2206 void fd_queue_async( struct fd *fd, struct async *async, int type )
2208 struct async_queue *queue;
2210 switch (type)
2212 case ASYNC_TYPE_READ:
2213 queue = &fd->read_q;
2214 break;
2215 case ASYNC_TYPE_WRITE:
2216 queue = &fd->write_q;
2217 break;
2218 case ASYNC_TYPE_WAIT:
2219 queue = &fd->wait_q;
2220 break;
2221 default:
2222 queue = NULL;
2223 assert(0);
2226 queue_async( queue, async );
2228 if (type != ASYNC_TYPE_WAIT)
2230 if (!fd->inode)
2231 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2232 else /* regular files are always ready for read and write */
2233 async_wake_up( queue, STATUS_ALERTED );
2237 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
2239 switch (type)
2241 case ASYNC_TYPE_READ:
2242 async_wake_up( &fd->read_q, status );
2243 break;
2244 case ASYNC_TYPE_WRITE:
2245 async_wake_up( &fd->write_q, status );
2246 break;
2247 case ASYNC_TYPE_WAIT:
2248 async_wake_up( &fd->wait_q, status );
2249 break;
2250 default:
2251 assert(0);
2255 void fd_cancel_async( struct fd *fd, struct async *async )
2257 fd->fd_ops->cancel_async( fd, async );
2260 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
2262 fd->fd_ops->reselect_async( fd, queue );
2265 void no_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2267 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2270 void default_fd_cancel_async( struct fd *fd, struct async *async )
2272 async_terminate( async, STATUS_CANCELLED );
2275 void default_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2277 fd_queue_async( fd, async, type );
2278 set_error( STATUS_PENDING );
2281 /* default reselect_async() fd routine */
2282 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
2284 if (queue == &fd->read_q || queue == &fd->write_q)
2286 int poll_events = fd->fd_ops->get_poll_events( fd );
2287 int events = check_fd_events( fd, poll_events );
2288 if (events) fd->fd_ops->poll_event( fd, events );
2289 else set_fd_events( fd, poll_events );
2293 static inline int is_valid_mounted_device( struct stat *st )
2295 #if defined(linux) || defined(__sun__)
2296 return S_ISBLK( st->st_mode );
2297 #else
2298 /* disks are char devices on *BSD */
2299 return S_ISCHR( st->st_mode );
2300 #endif
2303 /* close all Unix file descriptors on a device to allow unmounting it */
2304 static void unmount_device( struct fd *device_fd )
2306 unsigned int i;
2307 struct stat st;
2308 struct device *device;
2309 struct inode *inode;
2310 struct fd *fd;
2311 int unix_fd = get_unix_fd( device_fd );
2313 if (unix_fd == -1) return;
2315 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2317 set_error( STATUS_INVALID_PARAMETER );
2318 return;
2321 if (!(device = get_device( st.st_rdev, -1 ))) return;
2323 for (i = 0; i < INODE_HASH_SIZE; i++)
2325 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
2327 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
2329 unmount_fd( fd );
2331 inode_close_pending( inode, 0 );
2334 /* remove it from the hash table */
2335 list_remove( &device->entry );
2336 list_init( &device->entry );
2337 release_object( device );
2340 /* default read() routine */
2341 void no_fd_read( struct fd *fd, struct async *async, file_pos_t pos )
2343 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2346 /* default write() routine */
2347 void no_fd_write( struct fd *fd, struct async *async, file_pos_t pos )
2349 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2352 /* default flush() routine */
2353 void no_fd_flush( struct fd *fd, struct async *async )
2355 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2358 /* default get_file_info() routine */
2359 void no_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2361 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2364 /* default get_file_info() routine */
2365 void default_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2367 switch (info_class)
2369 case FileAccessInformation:
2371 FILE_ACCESS_INFORMATION info;
2372 if (get_reply_max_size() < sizeof(info))
2374 set_error( STATUS_INFO_LENGTH_MISMATCH );
2375 return;
2377 info.AccessFlags = get_handle_access( current->process, handle );
2378 set_reply_data( &info, sizeof(info) );
2379 break;
2381 case FileModeInformation:
2383 FILE_MODE_INFORMATION info;
2384 if (get_reply_max_size() < sizeof(info))
2386 set_error( STATUS_INFO_LENGTH_MISMATCH );
2387 return;
2389 info.Mode = fd->options & ( FILE_WRITE_THROUGH
2390 | FILE_SEQUENTIAL_ONLY
2391 | FILE_NO_INTERMEDIATE_BUFFERING
2392 | FILE_SYNCHRONOUS_IO_ALERT
2393 | FILE_SYNCHRONOUS_IO_NONALERT );
2394 set_reply_data( &info, sizeof(info) );
2395 break;
2397 case FileIoCompletionNotificationInformation:
2399 FILE_IO_COMPLETION_NOTIFICATION_INFORMATION info;
2400 if (get_reply_max_size() < sizeof(info))
2402 set_error( STATUS_INFO_LENGTH_MISMATCH );
2403 return;
2405 info.Flags = fd->comp_flags;
2406 set_reply_data( &info, sizeof(info) );
2407 break;
2409 default:
2410 set_error( STATUS_NOT_IMPLEMENTED );
2414 /* default get_volume_info() routine */
2415 void no_fd_get_volume_info( struct fd *fd, struct async *async, unsigned int info_class )
2417 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2420 /* default ioctl() routine */
2421 void no_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2423 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2426 /* default ioctl() routine */
2427 void default_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2429 switch(code)
2431 case FSCTL_DISMOUNT_VOLUME:
2432 unmount_device( fd );
2433 break;
2435 default:
2436 set_error( STATUS_NOT_SUPPORTED );
2440 /* same as get_handle_obj but retrieve the struct fd associated to the object */
2441 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
2442 unsigned int access )
2444 struct fd *fd = NULL;
2445 struct object *obj;
2447 if ((obj = get_handle_obj( process, handle, access, NULL )))
2449 fd = get_obj_fd( obj );
2450 release_object( obj );
2452 return fd;
2455 static int is_dir_empty( int fd )
2457 DIR *dir;
2458 int empty;
2459 struct dirent *de;
2461 if ((fd = dup( fd )) == -1)
2462 return -1;
2464 if (!(dir = fdopendir( fd )))
2466 close( fd );
2467 return -1;
2470 empty = 1;
2471 while (empty && (de = readdir( dir )))
2473 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2474 empty = 0;
2476 closedir( dir );
2477 return empty;
2480 /* set disposition for the fd */
2481 static void set_fd_disposition( struct fd *fd, unsigned int flags )
2483 struct stat st;
2485 if (!fd->inode)
2487 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2488 return;
2491 if (fd->unix_fd == -1)
2493 set_error( fd->no_fd_status );
2494 return;
2497 if (flags & FILE_DISPOSITION_DELETE)
2499 struct fd *fd_ptr;
2501 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
2503 if (fd_ptr->access & FILE_MAPPING_ACCESS)
2505 set_error( STATUS_CANNOT_DELETE );
2506 return;
2510 if (fstat( fd->unix_fd, &st ) == -1)
2512 file_set_error();
2513 return;
2515 if (S_ISREG( st.st_mode )) /* can't unlink files we don't have permission to write */
2517 if (!(flags & FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE) &&
2518 !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2520 set_error( STATUS_CANNOT_DELETE );
2521 return;
2524 else if (S_ISDIR( st.st_mode )) /* can't remove non-empty directories */
2526 switch (is_dir_empty( fd->unix_fd ))
2528 case -1:
2529 file_set_error();
2530 return;
2531 case 0:
2532 set_error( STATUS_DIRECTORY_NOT_EMPTY );
2533 return;
2536 else /* can't unlink special files */
2538 set_error( STATUS_INVALID_PARAMETER );
2539 return;
2543 if (flags & FILE_DISPOSITION_ON_CLOSE)
2544 fd->options &= ~FILE_DELETE_ON_CLOSE;
2546 fd->closed->disp_flags =
2547 (flags & (FILE_DISPOSITION_DELETE | FILE_DISPOSITION_POSIX_SEMANTICS)) |
2548 ((fd->options & FILE_DELETE_ON_CLOSE) ? FILE_DISPOSITION_DELETE : 0);
2551 /* set new name for the fd */
2552 static void set_fd_name( struct fd *fd, struct fd *root, const char *nameptr, data_size_t len,
2553 struct unicode_str nt_name, int create_link, int replace )
2555 struct inode *inode;
2556 struct stat st, st2;
2557 char *name;
2559 if (!fd->inode || !fd->unix_name)
2561 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2562 return;
2564 if (fd->unix_fd == -1)
2566 set_error( fd->no_fd_status );
2567 return;
2570 if (!len || ((nameptr[0] == '/') ^ !root))
2572 set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
2573 return;
2575 if (!(name = mem_alloc( len + 1 ))) return;
2576 memcpy( name, nameptr, len );
2577 name[len] = 0;
2579 if (root)
2581 char *combined_name = dup_fd_name( root, name );
2582 if (!combined_name)
2584 set_error( STATUS_NO_MEMORY );
2585 goto failed;
2587 free( name );
2588 name = combined_name;
2591 /* when creating a hard link, source cannot be a dir */
2592 if (create_link && !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode ))
2594 set_error( STATUS_FILE_IS_A_DIRECTORY );
2595 goto failed;
2598 if (!stat( name, &st ))
2600 if (!fstat( fd->unix_fd, &st2 ) && st.st_ino == st2.st_ino && st.st_dev == st2.st_dev)
2602 if (create_link && !replace) set_error( STATUS_OBJECT_NAME_COLLISION );
2603 free( name );
2604 return;
2607 if (!replace)
2609 set_error( STATUS_OBJECT_NAME_COLLISION );
2610 goto failed;
2613 /* can't replace directories or special files */
2614 if (!S_ISREG( st.st_mode ))
2616 set_error( STATUS_ACCESS_DENIED );
2617 goto failed;
2620 /* can't replace an opened file */
2621 if ((inode = get_inode( st.st_dev, st.st_ino, -1 )))
2623 int is_empty = list_empty( &inode->open );
2624 release_object( inode );
2625 if (!is_empty)
2627 set_error( STATUS_ACCESS_DENIED );
2628 goto failed;
2632 /* link() expects that the target doesn't exist */
2633 /* rename() cannot replace files with directories */
2634 if (create_link || S_ISDIR( st2.st_mode ))
2636 if (unlink( name ))
2638 file_set_error();
2639 goto failed;
2644 if (create_link)
2646 if (link( fd->unix_name, name ))
2647 file_set_error();
2648 free( name );
2649 return;
2652 if (rename( fd->unix_name, name ))
2654 file_set_error();
2655 goto failed;
2658 if (is_file_executable( fd->unix_name ) != is_file_executable( name ) && !fstat( fd->unix_fd, &st ))
2660 if (is_file_executable( name ))
2661 /* set executable bit where read bit is set */
2662 st.st_mode |= (st.st_mode & 0444) >> 2;
2663 else
2664 st.st_mode &= ~0111;
2665 fchmod( fd->unix_fd, st.st_mode );
2668 free( fd->nt_name );
2669 fd->nt_name = dup_nt_name( root, nt_name, &fd->nt_namelen );
2670 free( fd->unix_name );
2671 fd->closed->unix_name = fd->unix_name = realpath( name, NULL );
2672 free( name );
2673 if (!fd->unix_name)
2674 set_error( STATUS_NO_MEMORY );
2675 return;
2677 failed:
2678 free( name );
2681 static void set_fd_eof( struct fd *fd, file_pos_t eof )
2683 struct stat st;
2685 if (!fd->inode)
2687 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2688 return;
2691 if (fd->unix_fd == -1)
2693 set_error( fd->no_fd_status );
2694 return;
2696 if (fstat( fd->unix_fd, &st) == -1)
2698 file_set_error();
2699 return;
2701 if (eof < st.st_size)
2703 struct fd *fd_ptr;
2704 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
2706 if (fd_ptr->access & FILE_MAPPING_ACCESS)
2708 set_error( STATUS_USER_MAPPED_FILE );
2709 return;
2712 if (ftruncate( fd->unix_fd, eof ) == -1) file_set_error();
2714 else grow_file( fd->unix_fd, eof );
2717 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
2719 *p_key = fd->comp_key;
2720 return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
2723 void fd_copy_completion( struct fd *src, struct fd *dst )
2725 assert( !dst->completion );
2726 dst->completion = fd_get_completion( src, &dst->comp_key );
2727 dst->comp_flags = src->comp_flags;
2730 /* flush a file buffers */
2731 DECL_HANDLER(flush)
2733 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, 0 );
2734 struct async *async;
2736 if (!fd) return;
2738 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2740 fd->fd_ops->flush( fd, async );
2741 reply->event = async_handoff( async, NULL, 1 );
2742 release_object( async );
2744 release_object( fd );
2747 /* query file info */
2748 DECL_HANDLER(get_file_info)
2750 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2752 if (fd)
2754 fd->fd_ops->get_file_info( fd, req->handle, req->info_class );
2755 release_object( fd );
2759 /* query volume info */
2760 DECL_HANDLER(get_volume_info)
2762 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2763 struct async *async;
2765 if (!fd) return;
2767 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2769 fd->fd_ops->get_volume_info( fd, async, req->info_class );
2770 reply->wait = async_handoff( async, NULL, 1 );
2771 release_object( async );
2773 release_object( fd );
2776 /* open a file object */
2777 DECL_HANDLER(open_file_object)
2779 struct unicode_str name = get_req_unicode_str();
2780 struct object *obj, *result, *root = NULL;
2782 if (req->rootdir && !(root = get_handle_obj( current->process, req->rootdir, 0, NULL ))) return;
2784 obj = open_named_object( root, NULL, &name, req->attributes );
2785 if (root) release_object( root );
2786 if (!obj) return;
2788 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
2790 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
2791 release_object( result );
2793 release_object( obj );
2796 /* get the Unix name from a file handle */
2797 DECL_HANDLER(get_handle_unix_name)
2799 struct fd *fd;
2801 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2803 if (fd->unix_name)
2805 data_size_t name_len = strlen( fd->unix_name );
2806 reply->name_len = name_len;
2807 if (name_len <= get_reply_max_size()) set_reply_data( fd->unix_name, name_len );
2808 else set_error( STATUS_BUFFER_OVERFLOW );
2810 else set_error( STATUS_OBJECT_TYPE_MISMATCH );
2811 release_object( fd );
2815 /* get a Unix fd to access a file */
2816 DECL_HANDLER(get_handle_fd)
2818 struct fd *fd;
2820 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2822 int unix_fd = get_unix_fd( fd );
2823 reply->cacheable = fd->cacheable;
2824 if (unix_fd != -1)
2826 reply->type = fd->fd_ops->get_fd_type( fd );
2827 reply->options = fd->options;
2828 reply->access = get_handle_access( current->process, req->handle );
2829 send_client_fd( current->process, unix_fd, req->handle );
2831 release_object( fd );
2835 /* perform a read on a file object */
2836 DECL_HANDLER(read)
2838 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_READ_DATA );
2839 struct async *async;
2841 if (!fd) return;
2843 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2845 fd->fd_ops->read( fd, async, req->pos );
2846 reply->wait = async_handoff( async, NULL, 0 );
2847 reply->options = fd->options;
2848 release_object( async );
2850 release_object( fd );
2853 /* perform a write on a file object */
2854 DECL_HANDLER(write)
2856 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_WRITE_DATA );
2857 struct async *async;
2859 if (!fd) return;
2861 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2863 fd->fd_ops->write( fd, async, req->pos );
2864 reply->wait = async_handoff( async, &reply->size, 0 );
2865 reply->options = fd->options;
2866 release_object( async );
2868 release_object( fd );
2871 /* perform an ioctl on a file */
2872 DECL_HANDLER(ioctl)
2874 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2875 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2876 struct async *async;
2878 if (!fd) return;
2880 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2882 fd->fd_ops->ioctl( fd, req->code, async );
2883 reply->wait = async_handoff( async, NULL, 0 );
2884 reply->options = fd->options;
2885 release_object( async );
2887 release_object( fd );
2890 /* create / reschedule an async I/O */
2891 DECL_HANDLER(register_async)
2893 unsigned int access;
2894 struct async *async;
2895 struct fd *fd;
2897 switch(req->type)
2899 case ASYNC_TYPE_READ:
2900 access = FILE_READ_DATA;
2901 break;
2902 case ASYNC_TYPE_WRITE:
2903 access = FILE_WRITE_DATA;
2904 break;
2905 default:
2906 set_error( STATUS_INVALID_PARAMETER );
2907 return;
2910 if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2912 if (get_unix_fd( fd ) != -1 && (async = create_async( fd, current, &req->async, NULL )))
2914 fd->fd_ops->queue_async( fd, async, req->type, req->count );
2915 release_object( async );
2917 release_object( fd );
2921 /* attach completion object to a fd */
2922 DECL_HANDLER(set_completion_info)
2924 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2926 if (fd)
2928 if (is_fd_overlapped( fd ) && !fd->completion)
2930 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2931 fd->comp_key = req->ckey;
2933 else set_error( STATUS_INVALID_PARAMETER );
2934 release_object( fd );
2938 /* push new completion msg into a completion queue attached to the fd */
2939 DECL_HANDLER(add_fd_completion)
2941 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2942 if (fd)
2944 if (fd->completion && (req->async || !(fd->comp_flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS)))
2945 add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2946 release_object( fd );
2950 /* set fd completion information */
2951 DECL_HANDLER(set_fd_completion_mode)
2953 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2954 if (fd)
2956 if (is_fd_overlapped( fd ))
2958 if (req->flags & FILE_SKIP_SET_EVENT_ON_HANDLE)
2959 set_fd_signaled( fd, 0 );
2960 /* removing flags is not allowed */
2961 fd->comp_flags |= req->flags & ( FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
2962 | FILE_SKIP_SET_EVENT_ON_HANDLE
2963 | FILE_SKIP_SET_USER_EVENT_ON_FAST_IO );
2965 else
2966 set_error( STATUS_INVALID_PARAMETER );
2967 release_object( fd );
2971 /* set fd disposition information */
2972 DECL_HANDLER(set_fd_disp_info)
2974 struct fd *fd = get_handle_fd_obj( current->process, req->handle, DELETE );
2975 if (fd)
2977 set_fd_disposition( fd, req->flags );
2978 release_object( fd );
2982 /* set fd name information */
2983 DECL_HANDLER(set_fd_name_info)
2985 struct fd *fd, *root_fd = NULL;
2986 struct unicode_str nt_name;
2988 if (req->namelen > get_req_data_size())
2990 set_error( STATUS_INVALID_PARAMETER );
2991 return;
2993 nt_name.str = get_req_data();
2994 nt_name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
2996 if (req->rootdir)
2998 struct dir *root;
3000 if (!(root = get_dir_obj( current->process, req->rootdir, 0 ))) return;
3001 root_fd = get_obj_fd( (struct object *)root );
3002 release_object( root );
3003 if (!root_fd) return;
3006 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
3008 set_fd_name( fd, root_fd, (const char *)get_req_data() + req->namelen,
3009 get_req_data_size() - req->namelen, nt_name, req->link, req->replace );
3010 release_object( fd );
3012 if (root_fd) release_object( root_fd );
3015 /* set fd eof information */
3016 DECL_HANDLER(set_fd_eof_info)
3018 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
3019 if (fd)
3021 set_fd_eof( fd, req->eof );
3022 release_object( fd );