kernel32/tests: Add tests for the current console font size.
[wine.git] / server / fd.c
blobc9a21186722617bc1abc7ed422ab73cd41be5ec4
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 int unlink; /* whether to unlink on close: -1 - implicit FILE_DELETE_ON_CLOSE, 1 - explicit disposition */
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 */
1107 /****************************************************************/
1108 /* inode functions */
1110 /* close all pending file descriptors in the closed list */
1111 static void inode_close_pending( struct inode *inode, int keep_unlinks )
1113 struct list *ptr = list_head( &inode->closed );
1115 while (ptr)
1117 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1118 struct list *next = list_next( &inode->closed, ptr );
1120 if (fd->unix_fd != -1)
1122 close( fd->unix_fd );
1123 fd->unix_fd = -1;
1125 if (!keep_unlinks || !fd->unlink) /* get rid of it unless there's an unlink pending on that file */
1127 list_remove( ptr );
1128 free( fd->unix_name );
1129 free( fd );
1131 ptr = next;
1135 static void inode_dump( struct object *obj, int verbose )
1137 struct inode *inode = (struct inode *)obj;
1138 fprintf( stderr, "Inode device=%p ino=", inode->device );
1139 DUMP_LONG_LONG( inode->ino );
1140 fprintf( stderr, "\n" );
1143 static void inode_destroy( struct object *obj )
1145 struct inode *inode = (struct inode *)obj;
1146 struct list *ptr;
1148 assert( list_empty(&inode->open) );
1149 assert( list_empty(&inode->locks) );
1151 list_remove( &inode->entry );
1153 while ((ptr = list_head( &inode->closed )))
1155 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1156 list_remove( ptr );
1157 if (fd->unix_fd != -1) close( fd->unix_fd );
1158 if (fd->unlink)
1160 /* make sure it is still the same file */
1161 struct stat st;
1162 if (!stat( fd->unix_name, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
1164 if (S_ISDIR(st.st_mode)) rmdir( fd->unix_name );
1165 else unlink( fd->unix_name );
1168 free( fd->unix_name );
1169 free( fd );
1171 release_object( inode->device );
1174 /* retrieve the inode object for a given fd, creating it if needed */
1175 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
1177 struct device *device;
1178 struct inode *inode;
1179 unsigned int hash = ino % INODE_HASH_SIZE;
1181 if (!(device = get_device( dev, unix_fd ))) return NULL;
1183 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
1185 if (inode->ino == ino)
1187 release_object( device );
1188 return (struct inode *)grab_object( inode );
1192 /* not found, create it */
1193 if ((inode = alloc_object( &inode_ops )))
1195 inode->device = device;
1196 inode->ino = ino;
1197 list_init( &inode->open );
1198 list_init( &inode->locks );
1199 list_init( &inode->closed );
1200 list_add_head( &device->inode_hash[hash], &inode->entry );
1202 else release_object( device );
1204 return inode;
1207 /* add fd to the inode list of file descriptors to close */
1208 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1210 if (!list_empty( &inode->locks ))
1212 list_add_head( &inode->closed, &fd->entry );
1214 else if (fd->unlink) /* close the fd but keep the structure around for unlink */
1216 if (fd->unix_fd != -1) close( fd->unix_fd );
1217 fd->unix_fd = -1;
1218 list_add_head( &inode->closed, &fd->entry );
1220 else /* no locks on this inode and no unlink, get rid of the fd */
1222 if (fd->unix_fd != -1) close( fd->unix_fd );
1223 free( fd->unix_name );
1224 free( fd );
1229 /****************************************************************/
1230 /* file lock functions */
1232 static void file_lock_dump( struct object *obj, int verbose )
1234 struct file_lock *lock = (struct file_lock *)obj;
1235 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1236 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1237 DUMP_LONG_LONG( lock->start );
1238 fprintf( stderr, " end=" );
1239 DUMP_LONG_LONG( lock->end );
1240 fprintf( stderr, "\n" );
1243 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry )
1245 struct file_lock *lock = (struct file_lock *)obj;
1246 /* lock is signaled if it has lost its owner */
1247 return !lock->process;
1250 /* set (or remove) a Unix lock if possible for the given range */
1251 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1253 struct flock fl;
1255 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1256 for (;;)
1258 if (start == end) return 1; /* can't set zero-byte lock */
1259 if (start > max_unix_offset) return 1; /* ignore it */
1260 fl.l_type = type;
1261 fl.l_whence = SEEK_SET;
1262 fl.l_start = start;
1263 if (!end || end > max_unix_offset) fl.l_len = 0;
1264 else fl.l_len = end - start;
1265 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1267 switch(errno)
1269 case EACCES:
1270 /* check whether locks work at all on this file system */
1271 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1273 set_error( STATUS_FILE_LOCK_CONFLICT );
1274 return 0;
1276 /* fall through */
1277 case EIO:
1278 case ENOLCK:
1279 case ENOTSUP:
1280 /* no locking on this fs, just ignore it */
1281 fd->fs_locks = 0;
1282 return 1;
1283 case EAGAIN:
1284 set_error( STATUS_FILE_LOCK_CONFLICT );
1285 return 0;
1286 case EBADF:
1287 /* this can happen if we try to set a write lock on a read-only file */
1288 /* try to at least grab a read lock */
1289 if (fl.l_type == F_WRLCK)
1291 type = F_RDLCK;
1292 break; /* retry */
1294 set_error( STATUS_ACCESS_DENIED );
1295 return 0;
1296 #ifdef EOVERFLOW
1297 case EOVERFLOW:
1298 #endif
1299 case EINVAL:
1300 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1301 /* in that case we shrink the limit and retry */
1302 if (max_unix_offset > INT_MAX)
1304 max_unix_offset = INT_MAX;
1305 break; /* retry */
1307 /* fall through */
1308 default:
1309 file_set_error();
1310 return 0;
1315 /* check if interval [start;end) overlaps the lock */
1316 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1318 if (lock->end && start >= lock->end) return 0;
1319 if (end && lock->start >= end) return 0;
1320 return 1;
1323 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1324 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1326 struct hole
1328 struct hole *next;
1329 struct hole *prev;
1330 file_pos_t start;
1331 file_pos_t end;
1332 } *first, *cur, *next, *buffer;
1334 struct list *ptr;
1335 int count = 0;
1337 if (!fd->inode) return;
1338 if (!fd->fs_locks) return;
1339 if (start == end || start > max_unix_offset) return;
1340 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1342 /* count the number of locks overlapping the specified area */
1344 LIST_FOR_EACH( ptr, &fd->inode->locks )
1346 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1347 if (lock->start == lock->end) continue;
1348 if (lock_overlaps( lock, start, end )) count++;
1351 if (!count) /* no locks at all, we can unlock everything */
1353 set_unix_lock( fd, start, end, F_UNLCK );
1354 return;
1357 /* allocate space for the list of holes */
1358 /* max. number of holes is number of locks + 1 */
1360 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1361 first = buffer;
1362 first->next = NULL;
1363 first->prev = NULL;
1364 first->start = start;
1365 first->end = end;
1366 next = first + 1;
1368 /* build a sorted list of unlocked holes in the specified area */
1370 LIST_FOR_EACH( ptr, &fd->inode->locks )
1372 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1373 if (lock->start == lock->end) continue;
1374 if (!lock_overlaps( lock, start, end )) continue;
1376 /* go through all the holes touched by this lock */
1377 for (cur = first; cur; cur = cur->next)
1379 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1380 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1382 /* now we know that lock is overlapping hole */
1384 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1386 cur->start = lock->end;
1387 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1388 /* now hole is empty, remove it */
1389 if (cur->next) cur->next->prev = cur->prev;
1390 if (cur->prev) cur->prev->next = cur->next;
1391 else if (!(first = cur->next)) goto done; /* no more holes at all */
1393 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1395 cur->end = lock->start;
1396 assert( cur->start < cur->end );
1398 else /* lock is in the middle of hole, split hole in two */
1400 next->prev = cur;
1401 next->next = cur->next;
1402 cur->next = next;
1403 next->start = lock->end;
1404 next->end = cur->end;
1405 cur->end = lock->start;
1406 assert( next->start < next->end );
1407 assert( cur->end < next->start );
1408 next++;
1409 break; /* done with this lock */
1414 /* clear Unix locks for all the holes */
1416 for (cur = first; cur; cur = cur->next)
1417 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1419 done:
1420 free( buffer );
1423 /* create a new lock on a fd */
1424 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1426 struct file_lock *lock;
1428 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1429 lock->shared = shared;
1430 lock->start = start;
1431 lock->end = end;
1432 lock->fd = fd;
1433 lock->process = current->process;
1435 /* now try to set a Unix lock */
1436 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1438 release_object( lock );
1439 return NULL;
1441 list_add_tail( &fd->locks, &lock->fd_entry );
1442 list_add_tail( &fd->inode->locks, &lock->inode_entry );
1443 list_add_tail( &lock->process->locks, &lock->proc_entry );
1444 return lock;
1447 /* remove an existing lock */
1448 static void remove_lock( struct file_lock *lock, int remove_unix )
1450 struct inode *inode = lock->fd->inode;
1452 list_remove( &lock->fd_entry );
1453 list_remove( &lock->inode_entry );
1454 list_remove( &lock->proc_entry );
1455 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1456 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1457 lock->process = NULL;
1458 wake_up( &lock->obj, 0 );
1459 release_object( lock );
1462 /* remove all locks owned by a given process */
1463 void remove_process_locks( struct process *process )
1465 struct list *ptr;
1467 while ((ptr = list_head( &process->locks )))
1469 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1470 remove_lock( lock, 1 ); /* this removes it from the list */
1474 /* remove all locks on a given fd */
1475 static void remove_fd_locks( struct fd *fd )
1477 file_pos_t start = FILE_POS_T_MAX, end = 0;
1478 struct list *ptr;
1480 while ((ptr = list_head( &fd->locks )))
1482 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1483 if (lock->start < start) start = lock->start;
1484 if (!lock->end || lock->end > end) end = lock->end - 1;
1485 remove_lock( lock, 0 );
1487 if (start < end) remove_unix_locks( fd, start, end + 1 );
1490 /* add a lock on an fd */
1491 /* returns handle to wait on */
1492 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1494 struct list *ptr;
1495 file_pos_t end = start + count;
1497 if (!fd->inode) /* not a regular file */
1499 set_error( STATUS_INVALID_DEVICE_REQUEST );
1500 return 0;
1503 /* don't allow wrapping locks */
1504 if (end && end < start)
1506 set_error( STATUS_INVALID_PARAMETER );
1507 return 0;
1510 /* check if another lock on that file overlaps the area */
1511 LIST_FOR_EACH( ptr, &fd->inode->locks )
1513 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1514 if (!lock_overlaps( lock, start, end )) continue;
1515 if (shared && (lock->shared || lock->fd == fd)) continue;
1516 /* found one */
1517 if (!wait)
1519 set_error( STATUS_FILE_LOCK_CONFLICT );
1520 return 0;
1522 set_error( STATUS_PENDING );
1523 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1526 /* not found, add it */
1527 if (add_lock( fd, shared, start, end )) return 0;
1528 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1530 /* Unix lock conflict -> tell client to wait and retry */
1531 if (wait) set_error( STATUS_PENDING );
1533 return 0;
1536 /* remove a lock on an fd */
1537 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1539 struct list *ptr;
1540 file_pos_t end = start + count;
1542 /* find an existing lock with the exact same parameters */
1543 LIST_FOR_EACH( ptr, &fd->locks )
1545 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1546 if ((lock->start == start) && (lock->end == end))
1548 remove_lock( lock, 1 );
1549 return;
1552 set_error( STATUS_FILE_LOCK_CONFLICT );
1556 /****************************************************************/
1557 /* file descriptor functions */
1559 static void fd_dump( struct object *obj, int verbose )
1561 struct fd *fd = (struct fd *)obj;
1562 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1563 if (fd->inode) fprintf( stderr, " inode=%p unlink=%d", fd->inode, fd->closed->unlink );
1564 fprintf( stderr, "\n" );
1567 static void fd_destroy( struct object *obj )
1569 struct fd *fd = (struct fd *)obj;
1571 free_async_queue( &fd->read_q );
1572 free_async_queue( &fd->write_q );
1573 free_async_queue( &fd->wait_q );
1575 if (fd->completion) release_object( fd->completion );
1576 remove_fd_locks( fd );
1577 list_remove( &fd->inode_entry );
1578 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1579 free( fd->nt_name );
1580 if (fd->inode)
1582 inode_add_closed_fd( fd->inode, fd->closed );
1583 release_object( fd->inode );
1585 else /* no inode, close it right away */
1587 if (fd->unix_fd != -1) close( fd->unix_fd );
1588 free( fd->unix_name );
1592 /* check if the desired access is possible without violating */
1593 /* the sharing mode of other opens of the same file */
1594 static unsigned int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing,
1595 unsigned int open_flags, unsigned int options )
1597 /* only a few access bits are meaningful wrt sharing */
1598 const unsigned int read_access = FILE_READ_DATA | FILE_EXECUTE;
1599 const unsigned int write_access = FILE_WRITE_DATA | FILE_APPEND_DATA;
1600 const unsigned int all_access = read_access | write_access | DELETE;
1602 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1603 unsigned int existing_access = 0;
1604 struct list *ptr;
1606 fd->access = access;
1607 fd->sharing = sharing;
1609 LIST_FOR_EACH( ptr, &fd->inode->open )
1611 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1612 if (fd_ptr != fd)
1614 /* if access mode is 0, sharing mode is ignored */
1615 if (fd_ptr->access & all_access) existing_sharing &= fd_ptr->sharing;
1616 existing_access |= fd_ptr->access;
1620 if (((access & read_access) && !(existing_sharing & FILE_SHARE_READ)) ||
1621 ((access & write_access) && !(existing_sharing & FILE_SHARE_WRITE)) ||
1622 ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)))
1623 return STATUS_SHARING_VIOLATION;
1624 if (((existing_access & FILE_MAPPING_WRITE) && !(sharing & FILE_SHARE_WRITE)) ||
1625 ((existing_access & FILE_MAPPING_IMAGE) && (access & FILE_WRITE_DATA)))
1626 return STATUS_SHARING_VIOLATION;
1627 if ((existing_access & FILE_MAPPING_IMAGE) && (options & FILE_DELETE_ON_CLOSE))
1628 return STATUS_CANNOT_DELETE;
1629 if ((existing_access & FILE_MAPPING_ACCESS) && (open_flags & O_TRUNC))
1630 return STATUS_USER_MAPPED_FILE;
1631 if (!(access & all_access))
1632 return 0; /* if access mode is 0, sharing mode is ignored (except for mappings) */
1633 if (((existing_access & read_access) && !(sharing & FILE_SHARE_READ)) ||
1634 ((existing_access & write_access) && !(sharing & FILE_SHARE_WRITE)) ||
1635 ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)))
1636 return STATUS_SHARING_VIOLATION;
1637 return 0;
1640 /* set the events that select waits for on this fd */
1641 void set_fd_events( struct fd *fd, int events )
1643 int user = fd->poll_index;
1644 assert( poll_users[user] == fd );
1646 set_fd_epoll_events( fd, user, events );
1648 if (events == -1) /* stop waiting on this fd completely */
1650 pollfd[user].fd = -1;
1651 pollfd[user].events = POLLERR;
1652 pollfd[user].revents = 0;
1654 else
1656 pollfd[user].fd = fd->unix_fd;
1657 pollfd[user].events = events;
1661 /* prepare an fd for unmounting its corresponding device */
1662 static inline void unmount_fd( struct fd *fd )
1664 assert( fd->inode );
1666 async_wake_up( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1667 async_wake_up( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1669 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1671 if (fd->unix_fd != -1) close( fd->unix_fd );
1673 fd->unix_fd = -1;
1674 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1675 fd->closed->unix_fd = -1;
1676 fd->closed->unlink = 0;
1678 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1679 fd->fs_locks = 0;
1682 /* allocate an fd object, without setting the unix fd yet */
1683 static struct fd *alloc_fd_object(void)
1685 struct fd *fd = alloc_object( &fd_ops );
1687 if (!fd) return NULL;
1689 fd->fd_ops = NULL;
1690 fd->user = NULL;
1691 fd->inode = NULL;
1692 fd->closed = NULL;
1693 fd->access = 0;
1694 fd->options = 0;
1695 fd->sharing = 0;
1696 fd->unix_fd = -1;
1697 fd->unix_name = NULL;
1698 fd->nt_name = NULL;
1699 fd->nt_namelen = 0;
1700 fd->cacheable = 0;
1701 fd->signaled = 1;
1702 fd->fs_locks = 1;
1703 fd->poll_index = -1;
1704 fd->completion = NULL;
1705 fd->comp_flags = 0;
1706 init_async_queue( &fd->read_q );
1707 init_async_queue( &fd->write_q );
1708 init_async_queue( &fd->wait_q );
1709 list_init( &fd->inode_entry );
1710 list_init( &fd->locks );
1712 if ((fd->poll_index = add_poll_user( fd )) == -1)
1714 release_object( fd );
1715 return NULL;
1717 return fd;
1720 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1721 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1723 struct fd *fd = alloc_object( &fd_ops );
1725 if (!fd) return NULL;
1727 fd->fd_ops = fd_user_ops;
1728 fd->user = user;
1729 fd->inode = NULL;
1730 fd->closed = NULL;
1731 fd->access = 0;
1732 fd->options = options;
1733 fd->sharing = 0;
1734 fd->unix_name = NULL;
1735 fd->nt_name = NULL;
1736 fd->nt_namelen = 0;
1737 fd->unix_fd = -1;
1738 fd->cacheable = 0;
1739 fd->signaled = 1;
1740 fd->fs_locks = 0;
1741 fd->poll_index = -1;
1742 fd->completion = NULL;
1743 fd->comp_flags = 0;
1744 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1745 init_async_queue( &fd->read_q );
1746 init_async_queue( &fd->write_q );
1747 init_async_queue( &fd->wait_q );
1748 list_init( &fd->inode_entry );
1749 list_init( &fd->locks );
1750 return fd;
1753 /* duplicate an fd object for a different user */
1754 struct fd *dup_fd_object( struct fd *orig, unsigned int access, unsigned int sharing, unsigned int options )
1756 unsigned int err;
1757 struct fd *fd = alloc_fd_object();
1759 if (!fd) return NULL;
1761 fd->options = options;
1762 fd->cacheable = orig->cacheable;
1764 if (orig->unix_name)
1766 if (!(fd->unix_name = mem_alloc( strlen(orig->unix_name) + 1 ))) goto failed;
1767 strcpy( fd->unix_name, orig->unix_name );
1769 if (orig->nt_namelen)
1771 if (!(fd->nt_name = memdup( orig->nt_name, orig->nt_namelen ))) goto failed;
1772 fd->nt_namelen = orig->nt_namelen;
1775 if (orig->inode)
1777 struct closed_fd *closed = mem_alloc( sizeof(*closed) );
1778 if (!closed) goto failed;
1779 if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1781 file_set_error();
1782 free( closed );
1783 goto failed;
1785 closed->unix_fd = fd->unix_fd;
1786 closed->unlink = 0;
1787 closed->unix_name = fd->unix_name;
1788 fd->closed = closed;
1789 fd->inode = (struct inode *)grab_object( orig->inode );
1790 list_add_head( &fd->inode->open, &fd->inode_entry );
1791 if ((err = check_sharing( fd, access, sharing, 0, options )))
1793 set_error( err );
1794 goto failed;
1797 else if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1799 file_set_error();
1800 goto failed;
1802 return fd;
1804 failed:
1805 release_object( fd );
1806 return NULL;
1809 /* find an existing fd object that can be reused for a mapping */
1810 struct fd *get_fd_object_for_mapping( struct fd *fd, unsigned int access, unsigned int sharing )
1812 struct fd *fd_ptr;
1814 if (!fd->inode) return NULL;
1816 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
1817 if (fd_ptr->access == access && fd_ptr->sharing == sharing)
1818 return (struct fd *)grab_object( fd_ptr );
1820 return NULL;
1823 /* sets the user of an fd that previously had no user */
1824 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1826 assert( fd->fd_ops == NULL );
1827 fd->fd_ops = user_ops;
1828 fd->user = user;
1831 char *dup_fd_name( struct fd *root, const char *name )
1833 char *ret;
1835 if (!root) return strdup( name );
1836 if (!root->unix_name) return NULL;
1838 /* skip . prefix */
1839 if (name[0] == '.' && (!name[1] || name[1] == '/')) name++;
1841 if ((ret = malloc( strlen(root->unix_name) + strlen(name) + 2 )))
1843 strcpy( ret, root->unix_name );
1844 if (name[0] && name[0] != '/') strcat( ret, "/" );
1845 strcat( ret, name );
1847 return ret;
1850 static WCHAR *dup_nt_name( struct fd *root, struct unicode_str name, data_size_t *len )
1852 WCHAR *ret;
1853 data_size_t retlen;
1855 if (!root)
1857 *len = name.len;
1858 if (!name.len) return NULL;
1859 return memdup( name.str, name.len );
1861 if (!root->nt_namelen) return NULL;
1862 retlen = root->nt_namelen;
1864 /* skip . prefix */
1865 if (name.len && name.str[0] == '.' && (name.len == sizeof(WCHAR) || name.str[1] == '\\'))
1867 name.str++;
1868 name.len -= sizeof(WCHAR);
1870 if ((ret = malloc( retlen + name.len + 1 )))
1872 memcpy( ret, root->nt_name, root->nt_namelen );
1873 if (name.len && name.str[0] != '\\' &&
1874 root->nt_namelen && root->nt_name[root->nt_namelen / sizeof(WCHAR) - 1] != '\\')
1876 ret[retlen / sizeof(WCHAR)] = '\\';
1877 retlen += sizeof(WCHAR);
1879 memcpy( ret + retlen / sizeof(WCHAR), name.str, name.len );
1880 *len = retlen + name.len;
1882 return ret;
1885 void get_nt_name( struct fd *fd, struct unicode_str *name )
1887 name->str = fd->nt_name;
1888 name->len = fd->nt_namelen;
1891 /* open() wrapper that returns a struct fd with no fd user set */
1892 struct fd *open_fd( struct fd *root, const char *name, struct unicode_str nt_name,
1893 int flags, mode_t *mode, unsigned int access,
1894 unsigned int sharing, unsigned int options )
1896 struct stat st;
1897 struct closed_fd *closed_fd;
1898 struct fd *fd;
1899 int root_fd = -1;
1900 int rw_mode;
1901 char *path;
1903 if (((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE)) ||
1904 ((options & FILE_DIRECTORY_FILE) && (flags & O_TRUNC)))
1906 set_error( STATUS_INVALID_PARAMETER );
1907 return NULL;
1910 if (!(fd = alloc_fd_object())) return NULL;
1912 fd->options = options;
1913 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
1915 release_object( fd );
1916 return NULL;
1919 if (root)
1921 if ((root_fd = get_unix_fd( root )) == -1) goto error;
1922 if (fchdir( root_fd ) == -1)
1924 file_set_error();
1925 root_fd = -1;
1926 goto error;
1930 /* create the directory if needed */
1931 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1933 if (mkdir( name, *mode ) == -1)
1935 if (errno != EEXIST || (flags & O_EXCL))
1937 file_set_error();
1938 goto error;
1941 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1944 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1946 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1947 else rw_mode = O_WRONLY;
1949 else rw_mode = O_RDONLY;
1951 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1953 /* if we tried to open a directory for write access, retry read-only */
1954 if (errno == EISDIR)
1956 if ((access & FILE_UNIX_WRITE_ACCESS) || (flags & O_CREAT))
1957 fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode );
1960 if (fd->unix_fd == -1)
1962 file_set_error();
1963 goto error;
1967 fd->nt_name = dup_nt_name( root, nt_name, &fd->nt_namelen );
1968 fd->unix_name = NULL;
1969 if ((path = dup_fd_name( root, name )))
1971 fd->unix_name = realpath( path, NULL );
1972 free( path );
1975 closed_fd->unix_fd = fd->unix_fd;
1976 closed_fd->unlink = 0;
1977 closed_fd->unix_name = fd->unix_name;
1978 fstat( fd->unix_fd, &st );
1979 *mode = st.st_mode;
1981 /* only bother with an inode for normal files and directories */
1982 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1984 unsigned int err;
1985 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1987 if (!inode)
1989 /* we can close the fd because there are no others open on the same file,
1990 * otherwise we wouldn't have failed to allocate a new inode
1992 goto error;
1994 fd->inode = inode;
1995 fd->closed = closed_fd;
1996 fd->cacheable = !inode->device->removable;
1997 list_add_head( &inode->open, &fd->inode_entry );
1998 closed_fd = NULL;
2000 /* check directory options */
2001 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
2003 set_error( STATUS_NOT_A_DIRECTORY );
2004 goto error;
2006 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
2008 set_error( STATUS_FILE_IS_A_DIRECTORY );
2009 goto error;
2011 if ((err = check_sharing( fd, access, sharing, flags, options )))
2013 set_error( err );
2014 goto error;
2017 /* can't unlink files if we don't have permission to access */
2018 if ((options & FILE_DELETE_ON_CLOSE) && !(flags & O_CREAT) &&
2019 !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2021 set_error( STATUS_CANNOT_DELETE );
2022 goto error;
2025 fd->closed->unlink = (options & FILE_DELETE_ON_CLOSE) ? -1 : 0;
2026 if (flags & O_TRUNC)
2028 if (S_ISDIR(st.st_mode))
2030 set_error( STATUS_OBJECT_NAME_COLLISION );
2031 goto error;
2033 ftruncate( fd->unix_fd, 0 );
2036 else /* special file */
2038 if (options & FILE_DELETE_ON_CLOSE) /* we can't unlink special files */
2040 set_error( STATUS_INVALID_PARAMETER );
2041 goto error;
2043 free( closed_fd );
2044 fd->cacheable = 1;
2047 #ifdef HAVE_POSIX_FADVISE
2048 switch (options & (FILE_SEQUENTIAL_ONLY | FILE_RANDOM_ACCESS))
2050 case FILE_SEQUENTIAL_ONLY:
2051 posix_fadvise( fd->unix_fd, 0, 0, POSIX_FADV_SEQUENTIAL );
2052 break;
2053 case FILE_RANDOM_ACCESS:
2054 posix_fadvise( fd->unix_fd, 0, 0, POSIX_FADV_RANDOM );
2055 break;
2057 #endif
2059 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
2060 return fd;
2062 error:
2063 release_object( fd );
2064 free( closed_fd );
2065 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
2066 return NULL;
2069 /* create an fd for an anonymous file */
2070 /* if the function fails the unix fd is closed */
2071 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
2072 unsigned int options )
2074 struct fd *fd = alloc_fd_object();
2076 if (fd)
2078 set_fd_user( fd, fd_user_ops, user );
2079 fd->unix_fd = unix_fd;
2080 fd->options = options;
2081 return fd;
2083 close( unix_fd );
2084 return NULL;
2087 /* retrieve the object that is using an fd */
2088 void *get_fd_user( struct fd *fd )
2090 return fd->user;
2093 /* retrieve the opening options for the fd */
2094 unsigned int get_fd_options( struct fd *fd )
2096 return fd->options;
2099 /* retrieve the completion flags for the fd */
2100 unsigned int get_fd_comp_flags( struct fd *fd )
2102 return fd->comp_flags;
2105 /* check if fd is in overlapped mode */
2106 int is_fd_overlapped( struct fd *fd )
2108 return !(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
2111 /* retrieve the unix fd for an object */
2112 int get_unix_fd( struct fd *fd )
2114 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
2115 return fd->unix_fd;
2118 /* check if two file descriptors point to the same file */
2119 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
2121 return fd1->inode == fd2->inode;
2124 /* allow the fd to be cached (can't be reset once set) */
2125 void allow_fd_caching( struct fd *fd )
2127 fd->cacheable = 1;
2130 /* check if fd is on a removable device */
2131 int is_fd_removable( struct fd *fd )
2133 return (fd->inode && fd->inode->device->removable);
2136 /* set or clear the fd signaled state */
2137 void set_fd_signaled( struct fd *fd, int signaled )
2139 if (fd->comp_flags & FILE_SKIP_SET_EVENT_ON_HANDLE) return;
2140 fd->signaled = signaled;
2141 if (signaled) wake_up( fd->user, 0 );
2144 /* check if events are pending and if yes return which one(s) */
2145 int check_fd_events( struct fd *fd, int events )
2147 struct pollfd pfd;
2149 if (fd->unix_fd == -1) return POLLERR;
2150 if (fd->inode) return events; /* regular files are always signaled */
2152 pfd.fd = fd->unix_fd;
2153 pfd.events = events;
2154 if (poll( &pfd, 1, 0 ) <= 0) return 0;
2155 return pfd.revents;
2158 /* default signaled() routine for objects that poll() on an fd */
2159 int default_fd_signaled( struct object *obj, struct wait_queue_entry *entry )
2161 struct fd *fd = get_obj_fd( obj );
2162 int ret = fd->signaled;
2163 release_object( fd );
2164 return ret;
2167 int default_fd_get_poll_events( struct fd *fd )
2169 int events = 0;
2171 if (async_waiting( &fd->read_q )) events |= POLLIN;
2172 if (async_waiting( &fd->write_q )) events |= POLLOUT;
2173 return events;
2176 /* default handler for poll() events */
2177 void default_poll_event( struct fd *fd, int event )
2179 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( &fd->read_q, STATUS_ALERTED );
2180 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( &fd->write_q, STATUS_ALERTED );
2182 /* if an error occurred, stop polling this fd to avoid busy-looping */
2183 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
2184 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2187 void fd_queue_async( struct fd *fd, struct async *async, int type )
2189 struct async_queue *queue;
2191 switch (type)
2193 case ASYNC_TYPE_READ:
2194 queue = &fd->read_q;
2195 break;
2196 case ASYNC_TYPE_WRITE:
2197 queue = &fd->write_q;
2198 break;
2199 case ASYNC_TYPE_WAIT:
2200 queue = &fd->wait_q;
2201 break;
2202 default:
2203 queue = NULL;
2204 assert(0);
2207 queue_async( queue, async );
2209 if (type != ASYNC_TYPE_WAIT)
2211 if (!fd->inode)
2212 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2213 else /* regular files are always ready for read and write */
2214 async_wake_up( queue, STATUS_ALERTED );
2218 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
2220 switch (type)
2222 case ASYNC_TYPE_READ:
2223 async_wake_up( &fd->read_q, status );
2224 break;
2225 case ASYNC_TYPE_WRITE:
2226 async_wake_up( &fd->write_q, status );
2227 break;
2228 case ASYNC_TYPE_WAIT:
2229 async_wake_up( &fd->wait_q, status );
2230 break;
2231 default:
2232 assert(0);
2236 void fd_cancel_async( struct fd *fd, struct async *async )
2238 fd->fd_ops->cancel_async( fd, async );
2241 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
2243 fd->fd_ops->reselect_async( fd, queue );
2246 void no_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2248 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2251 void default_fd_cancel_async( struct fd *fd, struct async *async )
2253 async_terminate( async, STATUS_CANCELLED );
2256 void default_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2258 fd_queue_async( fd, async, type );
2259 set_error( STATUS_PENDING );
2262 /* default reselect_async() fd routine */
2263 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
2265 if (queue == &fd->read_q || queue == &fd->write_q)
2267 int poll_events = fd->fd_ops->get_poll_events( fd );
2268 int events = check_fd_events( fd, poll_events );
2269 if (events) fd->fd_ops->poll_event( fd, events );
2270 else set_fd_events( fd, poll_events );
2274 static inline int is_valid_mounted_device( struct stat *st )
2276 #if defined(linux) || defined(__sun__)
2277 return S_ISBLK( st->st_mode );
2278 #else
2279 /* disks are char devices on *BSD */
2280 return S_ISCHR( st->st_mode );
2281 #endif
2284 /* close all Unix file descriptors on a device to allow unmounting it */
2285 static void unmount_device( struct fd *device_fd )
2287 unsigned int i;
2288 struct stat st;
2289 struct device *device;
2290 struct inode *inode;
2291 struct fd *fd;
2292 int unix_fd = get_unix_fd( device_fd );
2294 if (unix_fd == -1) return;
2296 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2298 set_error( STATUS_INVALID_PARAMETER );
2299 return;
2302 if (!(device = get_device( st.st_rdev, -1 ))) return;
2304 for (i = 0; i < INODE_HASH_SIZE; i++)
2306 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
2308 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
2310 unmount_fd( fd );
2312 inode_close_pending( inode, 0 );
2315 /* remove it from the hash table */
2316 list_remove( &device->entry );
2317 list_init( &device->entry );
2318 release_object( device );
2321 /* default read() routine */
2322 void no_fd_read( struct fd *fd, struct async *async, file_pos_t pos )
2324 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2327 /* default write() routine */
2328 void no_fd_write( struct fd *fd, struct async *async, file_pos_t pos )
2330 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2333 /* default flush() routine */
2334 void no_fd_flush( struct fd *fd, struct async *async )
2336 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2339 /* default get_file_info() routine */
2340 void no_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2342 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2345 /* default get_file_info() routine */
2346 void default_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2348 switch (info_class)
2350 case FileAccessInformation:
2352 FILE_ACCESS_INFORMATION info;
2353 if (get_reply_max_size() < sizeof(info))
2355 set_error( STATUS_INFO_LENGTH_MISMATCH );
2356 return;
2358 info.AccessFlags = get_handle_access( current->process, handle );
2359 set_reply_data( &info, sizeof(info) );
2360 break;
2362 case FileModeInformation:
2364 FILE_MODE_INFORMATION info;
2365 if (get_reply_max_size() < sizeof(info))
2367 set_error( STATUS_INFO_LENGTH_MISMATCH );
2368 return;
2370 info.Mode = fd->options & ( FILE_WRITE_THROUGH
2371 | FILE_SEQUENTIAL_ONLY
2372 | FILE_NO_INTERMEDIATE_BUFFERING
2373 | FILE_SYNCHRONOUS_IO_ALERT
2374 | FILE_SYNCHRONOUS_IO_NONALERT );
2375 set_reply_data( &info, sizeof(info) );
2376 break;
2378 case FileIoCompletionNotificationInformation:
2380 FILE_IO_COMPLETION_NOTIFICATION_INFORMATION info;
2381 if (get_reply_max_size() < sizeof(info))
2383 set_error( STATUS_INFO_LENGTH_MISMATCH );
2384 return;
2386 info.Flags = fd->comp_flags;
2387 set_reply_data( &info, sizeof(info) );
2388 break;
2390 default:
2391 set_error( STATUS_NOT_IMPLEMENTED );
2395 /* default get_volume_info() routine */
2396 void no_fd_get_volume_info( struct fd *fd, struct async *async, unsigned int info_class )
2398 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2401 /* default ioctl() routine */
2402 void no_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2404 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2407 /* default ioctl() routine */
2408 void default_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2410 switch(code)
2412 case FSCTL_DISMOUNT_VOLUME:
2413 unmount_device( fd );
2414 break;
2416 default:
2417 set_error( STATUS_NOT_SUPPORTED );
2421 /* same as get_handle_obj but retrieve the struct fd associated to the object */
2422 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
2423 unsigned int access )
2425 struct fd *fd = NULL;
2426 struct object *obj;
2428 if ((obj = get_handle_obj( process, handle, access, NULL )))
2430 fd = get_obj_fd( obj );
2431 release_object( obj );
2433 return fd;
2436 static int is_dir_empty( int fd )
2438 DIR *dir;
2439 int empty;
2440 struct dirent *de;
2442 if ((fd = dup( fd )) == -1)
2443 return -1;
2445 if (!(dir = fdopendir( fd )))
2447 close( fd );
2448 return -1;
2451 empty = 1;
2452 while (empty && (de = readdir( dir )))
2454 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2455 empty = 0;
2457 closedir( dir );
2458 return empty;
2461 /* set disposition for the fd */
2462 static void set_fd_disposition( struct fd *fd, int unlink )
2464 struct stat st;
2466 if (!fd->inode)
2468 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2469 return;
2472 if (fd->unix_fd == -1)
2474 set_error( fd->no_fd_status );
2475 return;
2478 if (unlink)
2480 struct fd *fd_ptr;
2482 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
2484 if (fd_ptr->access & FILE_MAPPING_ACCESS)
2486 set_error( STATUS_CANNOT_DELETE );
2487 return;
2491 if (fstat( fd->unix_fd, &st ) == -1)
2493 file_set_error();
2494 return;
2496 if (S_ISREG( st.st_mode )) /* can't unlink files we don't have permission to write */
2498 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2500 set_error( STATUS_CANNOT_DELETE );
2501 return;
2504 else if (S_ISDIR( st.st_mode )) /* can't remove non-empty directories */
2506 switch (is_dir_empty( fd->unix_fd ))
2508 case -1:
2509 file_set_error();
2510 return;
2511 case 0:
2512 set_error( STATUS_DIRECTORY_NOT_EMPTY );
2513 return;
2516 else /* can't unlink special files */
2518 set_error( STATUS_INVALID_PARAMETER );
2519 return;
2523 fd->closed->unlink = unlink ? 1 : 0;
2524 if (fd->options & FILE_DELETE_ON_CLOSE)
2525 fd->closed->unlink = -1;
2528 /* set new name for the fd */
2529 static void set_fd_name( struct fd *fd, struct fd *root, const char *nameptr, data_size_t len,
2530 struct unicode_str nt_name, int create_link, int replace )
2532 struct inode *inode;
2533 struct stat st, st2;
2534 char *name;
2536 if (!fd->inode || !fd->unix_name)
2538 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2539 return;
2541 if (fd->unix_fd == -1)
2543 set_error( fd->no_fd_status );
2544 return;
2547 if (!len || ((nameptr[0] == '/') ^ !root))
2549 set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
2550 return;
2552 if (!(name = mem_alloc( len + 1 ))) return;
2553 memcpy( name, nameptr, len );
2554 name[len] = 0;
2556 if (root)
2558 char *combined_name = dup_fd_name( root, name );
2559 if (!combined_name)
2561 set_error( STATUS_NO_MEMORY );
2562 goto failed;
2564 free( name );
2565 name = combined_name;
2568 /* when creating a hard link, source cannot be a dir */
2569 if (create_link && !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode ))
2571 set_error( STATUS_FILE_IS_A_DIRECTORY );
2572 goto failed;
2575 if (!stat( name, &st ))
2577 if (!fstat( fd->unix_fd, &st2 ) && st.st_ino == st2.st_ino && st.st_dev == st2.st_dev)
2579 if (create_link && !replace) set_error( STATUS_OBJECT_NAME_COLLISION );
2580 free( name );
2581 return;
2584 if (!replace)
2586 set_error( STATUS_OBJECT_NAME_COLLISION );
2587 goto failed;
2590 /* can't replace directories or special files */
2591 if (!S_ISREG( st.st_mode ))
2593 set_error( STATUS_ACCESS_DENIED );
2594 goto failed;
2597 /* can't replace an opened file */
2598 if ((inode = get_inode( st.st_dev, st.st_ino, -1 )))
2600 int is_empty = list_empty( &inode->open );
2601 release_object( inode );
2602 if (!is_empty)
2604 set_error( STATUS_ACCESS_DENIED );
2605 goto failed;
2609 /* link() expects that the target doesn't exist */
2610 /* rename() cannot replace files with directories */
2611 if (create_link || S_ISDIR( st2.st_mode ))
2613 if (unlink( name ))
2615 file_set_error();
2616 goto failed;
2621 if (create_link)
2623 if (link( fd->unix_name, name ))
2624 file_set_error();
2625 free( name );
2626 return;
2629 if (rename( fd->unix_name, name ))
2631 file_set_error();
2632 goto failed;
2635 if (is_file_executable( fd->unix_name ) != is_file_executable( name ) && !fstat( fd->unix_fd, &st ))
2637 if (is_file_executable( name ))
2638 /* set executable bit where read bit is set */
2639 st.st_mode |= (st.st_mode & 0444) >> 2;
2640 else
2641 st.st_mode &= ~0111;
2642 fchmod( fd->unix_fd, st.st_mode );
2645 free( fd->nt_name );
2646 fd->nt_name = dup_nt_name( root, nt_name, &fd->nt_namelen );
2647 free( fd->unix_name );
2648 fd->closed->unix_name = fd->unix_name = realpath( name, NULL );
2649 free( name );
2650 if (!fd->unix_name)
2651 set_error( STATUS_NO_MEMORY );
2652 return;
2654 failed:
2655 free( name );
2658 static void set_fd_eof( struct fd *fd, file_pos_t eof )
2660 struct stat st;
2662 if (!fd->inode)
2664 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2665 return;
2668 if (fd->unix_fd == -1)
2670 set_error( fd->no_fd_status );
2671 return;
2673 if (fstat( fd->unix_fd, &st) == -1)
2675 file_set_error();
2676 return;
2678 if (eof < st.st_size)
2680 struct fd *fd_ptr;
2681 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
2683 if (fd_ptr->access & FILE_MAPPING_ACCESS)
2685 set_error( STATUS_USER_MAPPED_FILE );
2686 return;
2689 if (ftruncate( fd->unix_fd, eof ) == -1) file_set_error();
2691 else grow_file( fd->unix_fd, eof );
2694 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
2696 *p_key = fd->comp_key;
2697 return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
2700 void fd_copy_completion( struct fd *src, struct fd *dst )
2702 assert( !dst->completion );
2703 dst->completion = fd_get_completion( src, &dst->comp_key );
2704 dst->comp_flags = src->comp_flags;
2707 /* flush a file buffers */
2708 DECL_HANDLER(flush)
2710 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, 0 );
2711 struct async *async;
2713 if (!fd) return;
2715 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2717 fd->fd_ops->flush( fd, async );
2718 reply->event = async_handoff( async, NULL, 1 );
2719 release_object( async );
2721 release_object( fd );
2724 /* query file info */
2725 DECL_HANDLER(get_file_info)
2727 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2729 if (fd)
2731 fd->fd_ops->get_file_info( fd, req->handle, req->info_class );
2732 release_object( fd );
2736 /* query volume info */
2737 DECL_HANDLER(get_volume_info)
2739 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2740 struct async *async;
2742 if (!fd) return;
2744 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2746 fd->fd_ops->get_volume_info( fd, async, req->info_class );
2747 reply->wait = async_handoff( async, NULL, 1 );
2748 release_object( async );
2750 release_object( fd );
2753 /* open a file object */
2754 DECL_HANDLER(open_file_object)
2756 struct unicode_str name = get_req_unicode_str();
2757 struct object *obj, *result, *root = NULL;
2759 if (req->rootdir && !(root = get_handle_obj( current->process, req->rootdir, 0, NULL ))) return;
2761 obj = open_named_object( root, NULL, &name, req->attributes );
2762 if (root) release_object( root );
2763 if (!obj) return;
2765 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
2767 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
2768 release_object( result );
2770 release_object( obj );
2773 /* get the Unix name from a file handle */
2774 DECL_HANDLER(get_handle_unix_name)
2776 struct fd *fd;
2778 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2780 if (fd->unix_name)
2782 data_size_t name_len = strlen( fd->unix_name );
2783 reply->name_len = name_len;
2784 if (name_len <= get_reply_max_size()) set_reply_data( fd->unix_name, name_len );
2785 else set_error( STATUS_BUFFER_OVERFLOW );
2787 else set_error( STATUS_OBJECT_TYPE_MISMATCH );
2788 release_object( fd );
2792 /* get a Unix fd to access a file */
2793 DECL_HANDLER(get_handle_fd)
2795 struct fd *fd;
2797 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2799 int unix_fd = get_unix_fd( fd );
2800 reply->cacheable = fd->cacheable;
2801 if (unix_fd != -1)
2803 reply->type = fd->fd_ops->get_fd_type( fd );
2804 reply->options = fd->options;
2805 reply->access = get_handle_access( current->process, req->handle );
2806 send_client_fd( current->process, unix_fd, req->handle );
2808 release_object( fd );
2812 /* perform a read on a file object */
2813 DECL_HANDLER(read)
2815 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_READ_DATA );
2816 struct async *async;
2818 if (!fd) return;
2820 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2822 fd->fd_ops->read( fd, async, req->pos );
2823 reply->wait = async_handoff( async, NULL, 0 );
2824 reply->options = fd->options;
2825 release_object( async );
2827 release_object( fd );
2830 /* perform a write on a file object */
2831 DECL_HANDLER(write)
2833 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_WRITE_DATA );
2834 struct async *async;
2836 if (!fd) return;
2838 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2840 fd->fd_ops->write( fd, async, req->pos );
2841 reply->wait = async_handoff( async, &reply->size, 0 );
2842 reply->options = fd->options;
2843 release_object( async );
2845 release_object( fd );
2848 /* perform an ioctl on a file */
2849 DECL_HANDLER(ioctl)
2851 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2852 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2853 struct async *async;
2855 if (!fd) return;
2857 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2859 fd->fd_ops->ioctl( fd, req->code, async );
2860 reply->wait = async_handoff( async, NULL, 0 );
2861 reply->options = fd->options;
2862 release_object( async );
2864 release_object( fd );
2867 /* create / reschedule an async I/O */
2868 DECL_HANDLER(register_async)
2870 unsigned int access;
2871 struct async *async;
2872 struct fd *fd;
2874 switch(req->type)
2876 case ASYNC_TYPE_READ:
2877 access = FILE_READ_DATA;
2878 break;
2879 case ASYNC_TYPE_WRITE:
2880 access = FILE_WRITE_DATA;
2881 break;
2882 default:
2883 set_error( STATUS_INVALID_PARAMETER );
2884 return;
2887 if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2889 if (get_unix_fd( fd ) != -1 && (async = create_async( fd, current, &req->async, NULL )))
2891 fd->fd_ops->queue_async( fd, async, req->type, req->count );
2892 release_object( async );
2894 release_object( fd );
2898 /* attach completion object to a fd */
2899 DECL_HANDLER(set_completion_info)
2901 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2903 if (fd)
2905 if (is_fd_overlapped( fd ) && !fd->completion)
2907 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2908 fd->comp_key = req->ckey;
2910 else set_error( STATUS_INVALID_PARAMETER );
2911 release_object( fd );
2915 /* push new completion msg into a completion queue attached to the fd */
2916 DECL_HANDLER(add_fd_completion)
2918 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2919 if (fd)
2921 if (fd->completion && (req->async || !(fd->comp_flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS)))
2922 add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2923 release_object( fd );
2927 /* set fd completion information */
2928 DECL_HANDLER(set_fd_completion_mode)
2930 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2931 if (fd)
2933 if (is_fd_overlapped( fd ))
2935 if (req->flags & FILE_SKIP_SET_EVENT_ON_HANDLE)
2936 set_fd_signaled( fd, 0 );
2937 /* removing flags is not allowed */
2938 fd->comp_flags |= req->flags & ( FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
2939 | FILE_SKIP_SET_EVENT_ON_HANDLE
2940 | FILE_SKIP_SET_USER_EVENT_ON_FAST_IO );
2942 else
2943 set_error( STATUS_INVALID_PARAMETER );
2944 release_object( fd );
2948 /* set fd disposition information */
2949 DECL_HANDLER(set_fd_disp_info)
2951 struct fd *fd = get_handle_fd_obj( current->process, req->handle, DELETE );
2952 if (fd)
2954 set_fd_disposition( fd, req->unlink );
2955 release_object( fd );
2959 /* set fd name information */
2960 DECL_HANDLER(set_fd_name_info)
2962 struct fd *fd, *root_fd = NULL;
2963 struct unicode_str nt_name;
2965 if (req->namelen > get_req_data_size())
2967 set_error( STATUS_INVALID_PARAMETER );
2968 return;
2970 nt_name.str = get_req_data();
2971 nt_name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
2973 if (req->rootdir)
2975 struct dir *root;
2977 if (!(root = get_dir_obj( current->process, req->rootdir, 0 ))) return;
2978 root_fd = get_obj_fd( (struct object *)root );
2979 release_object( root );
2980 if (!root_fd) return;
2983 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2985 set_fd_name( fd, root_fd, (const char *)get_req_data() + req->namelen,
2986 get_req_data_size() - req->namelen, nt_name, req->link, req->replace );
2987 release_object( fd );
2989 if (root_fd) release_object( root_fd );
2992 /* set fd eof information */
2993 DECL_HANDLER(set_fd_eof_info)
2995 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2996 if (fd)
2998 set_fd_eof( fd, req->eof );
2999 release_object( fd );