msvcr120: Add [_]strtoimax[_l] and [_]strtoumax[_l].
[wine.git] / server / fd.c
bloba88ba39ef014dcc9349d43f9b832f3a7ef405312
1 /*
2 * Server-side file descriptor management
4 * Copyright (C) 2000, 2003 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <dirent.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <limits.h>
30 #include <signal.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <stdlib.h>
35 #ifdef HAVE_POLL_H
36 #include <poll.h>
37 #endif
38 #ifdef HAVE_SYS_POLL_H
39 #include <sys/poll.h>
40 #endif
41 #ifdef HAVE_LINUX_MAJOR_H
42 #include <linux/major.h>
43 #endif
44 #ifdef HAVE_SYS_STATVFS_H
45 #include <sys/statvfs.h>
46 #endif
47 #ifdef HAVE_SYS_VFS_H
48 /* Work around a conflict with Solaris' system list defined in sys/list.h. */
49 #define list SYSLIST
50 #define list_next SYSLIST_NEXT
51 #define list_prev SYSLIST_PREV
52 #define list_head SYSLIST_HEAD
53 #define list_tail SYSLIST_TAIL
54 #define list_move_tail SYSLIST_MOVE_TAIL
55 #define list_remove SYSLIST_REMOVE
56 #include <sys/vfs.h>
57 #undef list
58 #undef list_next
59 #undef list_prev
60 #undef list_head
61 #undef list_tail
62 #undef list_move_tail
63 #undef list_remove
64 #endif
65 #ifdef HAVE_SYS_PARAM_H
66 #include <sys/param.h>
67 #endif
68 #ifdef HAVE_SYS_MOUNT_H
69 #include <sys/mount.h>
70 #endif
71 #ifdef HAVE_SYS_STATFS_H
72 #include <sys/statfs.h>
73 #endif
74 #ifdef HAVE_SYS_SYSCTL_H
75 #include <sys/sysctl.h>
76 #endif
77 #ifdef HAVE_SYS_EVENT_H
78 #include <sys/event.h>
79 #undef LIST_INIT
80 #undef LIST_ENTRY
81 #endif
82 #ifdef HAVE_STDINT_H
83 #include <stdint.h>
84 #endif
85 #include <sys/stat.h>
86 #include <sys/time.h>
87 #ifdef MAJOR_IN_MKDEV
88 #include <sys/mkdev.h>
89 #elif defined(MAJOR_IN_SYSMACROS)
90 #include <sys/sysmacros.h>
91 #endif
92 #include <sys/types.h>
93 #include <unistd.h>
94 #ifdef HAVE_SYS_SYSCALL_H
95 #include <sys/syscall.h>
96 #endif
98 #include "ntstatus.h"
99 #define WIN32_NO_STATUS
100 #include "object.h"
101 #include "file.h"
102 #include "handle.h"
103 #include "process.h"
104 #include "request.h"
106 #include "winternl.h"
107 #include "winioctl.h"
108 #include "ddk/wdm.h"
110 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
111 # include <sys/epoll.h>
112 # define USE_EPOLL
113 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
114 # define USE_EPOLL
115 # define EPOLLIN POLLIN
116 # define EPOLLOUT POLLOUT
117 # define EPOLLERR POLLERR
118 # define EPOLLHUP POLLHUP
119 # define EPOLL_CTL_ADD 1
120 # define EPOLL_CTL_DEL 2
121 # define EPOLL_CTL_MOD 3
123 typedef union epoll_data
125 void *ptr;
126 int fd;
127 uint32_t u32;
128 uint64_t u64;
129 } epoll_data_t;
131 struct epoll_event
133 uint32_t events;
134 epoll_data_t data;
137 static inline int epoll_create( int size )
139 return syscall( 254 /*NR_epoll_create*/, size );
142 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
144 return syscall( 255 /*NR_epoll_ctl*/, epfd, op, fd, event );
147 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
149 return syscall( 256 /*NR_epoll_wait*/, epfd, events, maxevents, timeout );
152 #endif /* linux && __i386__ && HAVE_STDINT_H */
154 #if defined(HAVE_PORT_H) && defined(HAVE_PORT_CREATE)
155 # include <port.h>
156 # define USE_EVENT_PORTS
157 #endif /* HAVE_PORT_H && HAVE_PORT_CREATE */
159 /* Because of the stupid Posix locking semantics, we need to keep
160 * track of all file descriptors referencing a given file, and not
161 * close a single one until all the locks are gone (sigh).
164 /* file descriptor object */
166 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
167 struct closed_fd
169 struct list entry; /* entry in inode closed list */
170 int unix_fd; /* the unix file descriptor */
171 int unlink; /* whether to unlink on close: -1 - implicit FILE_DELETE_ON_CLOSE, 1 - explicit disposition */
172 char *unix_name; /* name to unlink on close, points to parent fd unix_name */
175 struct fd
177 struct object obj; /* object header */
178 const struct fd_ops *fd_ops; /* file descriptor operations */
179 struct inode *inode; /* inode that this fd belongs to */
180 struct list inode_entry; /* entry in inode fd list */
181 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
182 struct object *user; /* object using this file descriptor */
183 struct list locks; /* list of locks on this fd */
184 unsigned int access; /* file access (FILE_READ_DATA etc.) */
185 unsigned int options; /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
186 unsigned int sharing; /* file sharing mode */
187 char *unix_name; /* unix file name */
188 int unix_fd; /* unix file descriptor */
189 unsigned int no_fd_status;/* status to return when unix_fd is -1 */
190 unsigned int cacheable :1;/* can the fd be cached on the client side? */
191 unsigned int signaled :1; /* is the fd signaled? */
192 unsigned int fs_locks :1; /* can we use filesystem locks for this fd? */
193 int poll_index; /* index of fd in poll array */
194 struct async_queue read_q; /* async readers of this fd */
195 struct async_queue write_q; /* async writers of this fd */
196 struct async_queue wait_q; /* other async waiters of this fd */
197 struct completion *completion; /* completion object attached to this fd */
198 apc_param_t comp_key; /* completion key to set in completion events */
199 unsigned int comp_flags; /* completion flags */
202 static void fd_dump( struct object *obj, int verbose );
203 static void fd_destroy( struct object *obj );
205 static const struct object_ops fd_ops =
207 sizeof(struct fd), /* size */
208 fd_dump, /* dump */
209 no_get_type, /* get_type */
210 no_add_queue, /* add_queue */
211 NULL, /* remove_queue */
212 NULL, /* signaled */
213 NULL, /* satisfied */
214 no_signal, /* signal */
215 no_get_fd, /* get_fd */
216 no_map_access, /* map_access */
217 default_get_sd, /* get_sd */
218 default_set_sd, /* set_sd */
219 no_lookup_name, /* lookup_name */
220 no_link_name, /* link_name */
221 NULL, /* unlink_name */
222 no_open_file, /* open_file */
223 no_kernel_obj_list, /* get_kernel_obj_list */
224 no_close_handle, /* close_handle */
225 fd_destroy /* destroy */
228 /* device object */
230 #define DEVICE_HASH_SIZE 7
231 #define INODE_HASH_SIZE 17
233 struct device
235 struct object obj; /* object header */
236 struct list entry; /* entry in device hash list */
237 dev_t dev; /* device number */
238 int removable; /* removable device? (or -1 if unknown) */
239 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
242 static void device_dump( struct object *obj, int verbose );
243 static void device_destroy( struct object *obj );
245 static const struct object_ops device_ops =
247 sizeof(struct device), /* size */
248 device_dump, /* dump */
249 no_get_type, /* get_type */
250 no_add_queue, /* add_queue */
251 NULL, /* remove_queue */
252 NULL, /* signaled */
253 NULL, /* satisfied */
254 no_signal, /* signal */
255 no_get_fd, /* get_fd */
256 no_map_access, /* map_access */
257 default_get_sd, /* get_sd */
258 default_set_sd, /* set_sd */
259 no_lookup_name, /* lookup_name */
260 no_link_name, /* link_name */
261 NULL, /* unlink_name */
262 no_open_file, /* open_file */
263 no_kernel_obj_list, /* get_kernel_obj_list */
264 no_close_handle, /* close_handle */
265 device_destroy /* destroy */
268 /* inode object */
270 struct inode
272 struct object obj; /* object header */
273 struct list entry; /* inode hash list entry */
274 struct device *device; /* device containing this inode */
275 ino_t ino; /* inode number */
276 struct list open; /* list of open file descriptors */
277 struct list locks; /* list of file locks */
278 struct list closed; /* list of file descriptors to close at destroy time */
281 static void inode_dump( struct object *obj, int verbose );
282 static void inode_destroy( struct object *obj );
284 static const struct object_ops inode_ops =
286 sizeof(struct inode), /* size */
287 inode_dump, /* dump */
288 no_get_type, /* get_type */
289 no_add_queue, /* add_queue */
290 NULL, /* remove_queue */
291 NULL, /* signaled */
292 NULL, /* satisfied */
293 no_signal, /* signal */
294 no_get_fd, /* get_fd */
295 no_map_access, /* map_access */
296 default_get_sd, /* get_sd */
297 default_set_sd, /* set_sd */
298 no_lookup_name, /* lookup_name */
299 no_link_name, /* link_name */
300 NULL, /* unlink_name */
301 no_open_file, /* open_file */
302 no_kernel_obj_list, /* get_kernel_obj_list */
303 no_close_handle, /* close_handle */
304 inode_destroy /* destroy */
307 /* file lock object */
309 struct file_lock
311 struct object obj; /* object header */
312 struct fd *fd; /* fd owning this lock */
313 struct list fd_entry; /* entry in list of locks on a given fd */
314 struct list inode_entry; /* entry in inode list of locks */
315 int shared; /* shared lock? */
316 file_pos_t start; /* locked region is interval [start;end) */
317 file_pos_t end;
318 struct process *process; /* process owning this lock */
319 struct list proc_entry; /* entry in list of locks owned by the process */
322 static void file_lock_dump( struct object *obj, int verbose );
323 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry );
325 static const struct object_ops file_lock_ops =
327 sizeof(struct file_lock), /* size */
328 file_lock_dump, /* dump */
329 no_get_type, /* get_type */
330 add_queue, /* add_queue */
331 remove_queue, /* remove_queue */
332 file_lock_signaled, /* signaled */
333 no_satisfied, /* satisfied */
334 no_signal, /* signal */
335 no_get_fd, /* get_fd */
336 no_map_access, /* map_access */
337 default_get_sd, /* get_sd */
338 default_set_sd, /* set_sd */
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 set_user_shared_data_time(void)
384 timeout_t tick_count = monotonic_time / 10000;
386 /* on X86 there should be total store order guarantees, so volatile is enough
387 * to ensure the stores aren't reordered by the compiler, and then they will
388 * always be seen in-order from other CPUs. On other archs, we need atomic
389 * intrinsics to guarantee that. */
390 #if defined(__i386__) || defined(__x86_64__)
391 user_shared_data->SystemTime.High2Time = current_time >> 32;
392 user_shared_data->SystemTime.LowPart = current_time;
393 user_shared_data->SystemTime.High1Time = current_time >> 32;
395 user_shared_data->InterruptTime.High2Time = monotonic_time >> 32;
396 user_shared_data->InterruptTime.LowPart = monotonic_time;
397 user_shared_data->InterruptTime.High1Time = monotonic_time >> 32;
399 user_shared_data->TickCount.High2Time = tick_count >> 32;
400 user_shared_data->TickCount.LowPart = tick_count;
401 user_shared_data->TickCount.High1Time = tick_count >> 32;
402 *(volatile ULONG *)&user_shared_data->TickCountLowDeprecated = tick_count;
403 #else
404 __atomic_store_n(&user_shared_data->SystemTime.High2Time, current_time >> 32, __ATOMIC_SEQ_CST);
405 __atomic_store_n(&user_shared_data->SystemTime.LowPart, current_time, __ATOMIC_SEQ_CST);
406 __atomic_store_n(&user_shared_data->SystemTime.High1Time, current_time >> 32, __ATOMIC_SEQ_CST);
408 __atomic_store_n(&user_shared_data->InterruptTime.High2Time, monotonic_time >> 32, __ATOMIC_SEQ_CST);
409 __atomic_store_n(&user_shared_data->InterruptTime.LowPart, monotonic_time, __ATOMIC_SEQ_CST);
410 __atomic_store_n(&user_shared_data->InterruptTime.High1Time, monotonic_time >> 32, __ATOMIC_SEQ_CST);
412 __atomic_store_n(&user_shared_data->TickCount.High2Time, tick_count >> 32, __ATOMIC_SEQ_CST);
413 __atomic_store_n(&user_shared_data->TickCount.LowPart, tick_count, __ATOMIC_SEQ_CST);
414 __atomic_store_n(&user_shared_data->TickCount.High1Time, tick_count >> 32, __ATOMIC_SEQ_CST);
415 __atomic_store_n(&user_shared_data->TickCountLowDeprecated, tick_count, __ATOMIC_SEQ_CST);
416 #endif
419 void set_current_time(void)
421 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
422 struct timeval now;
423 gettimeofday( &now, NULL );
424 current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
425 monotonic_time = monotonic_counter();
426 if (user_shared_data) set_user_shared_data_time();
429 /* add a timeout user */
430 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
432 struct timeout_user *user;
433 struct list *ptr;
435 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
436 user->when = timeout_to_abstime( when );
437 user->callback = func;
438 user->private = private;
440 /* Now insert it in the linked list */
442 if (user->when > 0)
444 LIST_FOR_EACH( ptr, &abs_timeout_list )
446 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
447 if (timeout->when >= user->when) break;
450 else
452 LIST_FOR_EACH( ptr, &rel_timeout_list )
454 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
455 if (timeout->when <= user->when) break;
458 list_add_before( ptr, &user->entry );
459 return user;
462 /* remove a timeout user */
463 void remove_timeout_user( struct timeout_user *user )
465 list_remove( &user->entry );
466 free( user );
469 /* return a text description of a timeout for debugging purposes */
470 const char *get_timeout_str( timeout_t timeout )
472 static char buffer[64];
473 long secs, nsecs;
475 if (!timeout) return "0";
476 if (timeout == TIMEOUT_INFINITE) return "infinite";
478 if (timeout < 0) /* relative */
480 secs = -timeout / TICKS_PER_SEC;
481 nsecs = -timeout % TICKS_PER_SEC;
482 sprintf( buffer, "+%ld.%07ld", secs, nsecs );
484 else /* absolute */
486 secs = (timeout - current_time) / TICKS_PER_SEC;
487 nsecs = (timeout - current_time) % TICKS_PER_SEC;
488 if (nsecs < 0)
490 nsecs += TICKS_PER_SEC;
491 secs--;
493 if (secs >= 0)
494 sprintf( buffer, "%x%08x (+%ld.%07ld)",
495 (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
496 else
497 sprintf( buffer, "%x%08x (-%ld.%07ld)",
498 (unsigned int)(timeout >> 32), (unsigned int)timeout,
499 -(secs + 1), TICKS_PER_SEC - nsecs );
501 return buffer;
505 /****************************************************************/
506 /* poll support */
508 static struct fd **poll_users; /* users array */
509 static struct pollfd *pollfd; /* poll fd array */
510 static int nb_users; /* count of array entries actually in use */
511 static int active_users; /* current number of active users */
512 static int allocated_users; /* count of allocated entries in the array */
513 static struct fd **freelist; /* list of free entries in the array */
515 static int get_next_timeout(void);
517 static inline void fd_poll_event( struct fd *fd, int event )
519 fd->fd_ops->poll_event( fd, event );
522 #ifdef USE_EPOLL
524 static int epoll_fd = -1;
526 static inline void init_epoll(void)
528 epoll_fd = epoll_create( 128 );
531 /* set the events that epoll waits for on this fd; helper for set_fd_events */
532 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
534 struct epoll_event ev;
535 int ctl;
537 if (epoll_fd == -1) return;
539 if (events == -1) /* stop waiting on this fd completely */
541 if (pollfd[user].fd == -1) return; /* already removed */
542 ctl = EPOLL_CTL_DEL;
544 else if (pollfd[user].fd == -1)
546 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
547 ctl = EPOLL_CTL_ADD;
549 else
551 if (pollfd[user].events == events) return; /* nothing to do */
552 ctl = EPOLL_CTL_MOD;
555 ev.events = events;
556 memset(&ev.data, 0, sizeof(ev.data));
557 ev.data.u32 = user;
559 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
561 if (errno == ENOMEM) /* not enough memory, give up on epoll */
563 close( epoll_fd );
564 epoll_fd = -1;
566 else perror( "epoll_ctl" ); /* should not happen */
570 static inline void remove_epoll_user( struct fd *fd, int user )
572 if (epoll_fd == -1) return;
574 if (pollfd[user].fd != -1)
576 struct epoll_event dummy;
577 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
581 static inline void main_loop_epoll(void)
583 int i, ret, timeout;
584 struct epoll_event events[128];
586 assert( POLLIN == EPOLLIN );
587 assert( POLLOUT == EPOLLOUT );
588 assert( POLLERR == EPOLLERR );
589 assert( POLLHUP == EPOLLHUP );
591 if (epoll_fd == -1) return;
593 while (active_users)
595 timeout = get_next_timeout();
597 if (!active_users) break; /* last user removed by a timeout */
598 if (epoll_fd == -1) break; /* an error occurred with epoll */
600 ret = epoll_wait( epoll_fd, events, ARRAY_SIZE( events ), timeout );
601 set_current_time();
603 /* put the events into the pollfd array first, like poll does */
604 for (i = 0; i < ret; i++)
606 int user = events[i].data.u32;
607 pollfd[user].revents = events[i].events;
610 /* read events from the pollfd array, as set_fd_events may modify them */
611 for (i = 0; i < ret; i++)
613 int user = events[i].data.u32;
614 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
619 #elif defined(HAVE_KQUEUE)
621 static int kqueue_fd = -1;
623 static inline void init_epoll(void)
625 #ifdef __APPLE__ /* kqueue support is broken in Mac OS < 10.5 */
626 int mib[2];
627 char release[32];
628 size_t len = sizeof(release);
630 mib[0] = CTL_KERN;
631 mib[1] = KERN_OSRELEASE;
632 if (sysctl( mib, 2, release, &len, NULL, 0 ) == -1) return;
633 if (atoi(release) < 9) return;
634 #endif
635 kqueue_fd = kqueue();
638 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
640 struct kevent ev[2];
642 if (kqueue_fd == -1) return;
644 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)(long)user );
645 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)(long)user );
647 if (events == -1) /* stop waiting on this fd completely */
649 if (pollfd[user].fd == -1) return; /* already removed */
650 ev[0].flags |= EV_DELETE;
651 ev[1].flags |= EV_DELETE;
653 else if (pollfd[user].fd == -1)
655 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
656 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
657 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
659 else
661 if (pollfd[user].events == events) return; /* nothing to do */
662 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
663 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
666 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
668 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
670 close( kqueue_fd );
671 kqueue_fd = -1;
673 else perror( "kevent" ); /* should not happen */
677 static inline void remove_epoll_user( struct fd *fd, int user )
679 if (kqueue_fd == -1) return;
681 if (pollfd[user].fd != -1)
683 struct kevent ev[2];
685 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
686 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
687 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
691 static inline void main_loop_epoll(void)
693 int i, ret, timeout;
694 struct kevent events[128];
696 if (kqueue_fd == -1) return;
698 while (active_users)
700 timeout = get_next_timeout();
702 if (!active_users) break; /* last user removed by a timeout */
703 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
705 if (timeout != -1)
707 struct timespec ts;
709 ts.tv_sec = timeout / 1000;
710 ts.tv_nsec = (timeout % 1000) * 1000000;
711 ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), &ts );
713 else ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), NULL );
715 set_current_time();
717 /* put the events into the pollfd array first, like poll does */
718 for (i = 0; i < ret; i++)
720 long user = (long)events[i].udata;
721 pollfd[user].revents = 0;
723 for (i = 0; i < ret; i++)
725 long user = (long)events[i].udata;
726 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
727 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
728 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
729 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
732 /* read events from the pollfd array, as set_fd_events may modify them */
733 for (i = 0; i < ret; i++)
735 long user = (long)events[i].udata;
736 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
737 pollfd[user].revents = 0;
742 #elif defined(USE_EVENT_PORTS)
744 static int port_fd = -1;
746 static inline void init_epoll(void)
748 port_fd = port_create();
751 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
753 int ret;
755 if (port_fd == -1) return;
757 if (events == -1) /* stop waiting on this fd completely */
759 if (pollfd[user].fd == -1) return; /* already removed */
760 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
762 else if (pollfd[user].fd == -1)
764 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
765 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
767 else
769 if (pollfd[user].events == events) return; /* nothing to do */
770 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
773 if (ret == -1)
775 if (errno == ENOMEM) /* not enough memory, give up on port_associate */
777 close( port_fd );
778 port_fd = -1;
780 else perror( "port_associate" ); /* should not happen */
784 static inline void remove_epoll_user( struct fd *fd, int user )
786 if (port_fd == -1) return;
788 if (pollfd[user].fd != -1)
790 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
794 static inline void main_loop_epoll(void)
796 int i, nget, ret, timeout;
797 port_event_t events[128];
799 if (port_fd == -1) return;
801 while (active_users)
803 timeout = get_next_timeout();
804 nget = 1;
806 if (!active_users) break; /* last user removed by a timeout */
807 if (port_fd == -1) break; /* an error occurred with event completion */
809 if (timeout != -1)
811 struct timespec ts;
813 ts.tv_sec = timeout / 1000;
814 ts.tv_nsec = (timeout % 1000) * 1000000;
815 ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, &ts );
817 else ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, NULL );
819 if (ret == -1) break; /* an error occurred with event completion */
821 set_current_time();
823 /* put the events into the pollfd array first, like poll does */
824 for (i = 0; i < nget; i++)
826 long user = (long)events[i].portev_user;
827 pollfd[user].revents = events[i].portev_events;
830 /* read events from the pollfd array, as set_fd_events may modify them */
831 for (i = 0; i < nget; i++)
833 long user = (long)events[i].portev_user;
834 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
835 /* if we are still interested, reassociate the fd */
836 if (pollfd[user].fd != -1) {
837 port_associate( port_fd, PORT_SOURCE_FD, pollfd[user].fd, pollfd[user].events, (void *)user );
843 #else /* HAVE_KQUEUE */
845 static inline void init_epoll(void) { }
846 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
847 static inline void remove_epoll_user( struct fd *fd, int user ) { }
848 static inline void main_loop_epoll(void) { }
850 #endif /* USE_EPOLL */
853 /* add a user in the poll array and return its index, or -1 on failure */
854 static int add_poll_user( struct fd *fd )
856 int ret;
857 if (freelist)
859 ret = freelist - poll_users;
860 freelist = (struct fd **)poll_users[ret];
862 else
864 if (nb_users == allocated_users)
866 struct fd **newusers;
867 struct pollfd *newpoll;
868 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
869 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
870 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
872 if (allocated_users)
873 poll_users = newusers;
874 else
875 free( newusers );
876 return -1;
878 poll_users = newusers;
879 pollfd = newpoll;
880 if (!allocated_users) init_epoll();
881 allocated_users = new_count;
883 ret = nb_users++;
885 pollfd[ret].fd = -1;
886 pollfd[ret].events = 0;
887 pollfd[ret].revents = 0;
888 poll_users[ret] = fd;
889 active_users++;
890 return ret;
893 /* remove a user from the poll list */
894 static void remove_poll_user( struct fd *fd, int user )
896 assert( user >= 0 );
897 assert( poll_users[user] == fd );
899 remove_epoll_user( fd, user );
900 pollfd[user].fd = -1;
901 pollfd[user].events = 0;
902 pollfd[user].revents = 0;
903 poll_users[user] = (struct fd *)freelist;
904 freelist = &poll_users[user];
905 active_users--;
908 /* process pending timeouts and return the time until the next timeout, in milliseconds */
909 static int get_next_timeout(void)
911 int ret = user_shared_data ? user_shared_data_timeout : -1;
913 if (!list_empty( &abs_timeout_list ) || !list_empty( &rel_timeout_list ))
915 struct list expired_list, *ptr;
917 /* first remove all expired timers from the list */
919 list_init( &expired_list );
920 while ((ptr = list_head( &abs_timeout_list )) != NULL)
922 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
924 if (timeout->when <= current_time)
926 list_remove( &timeout->entry );
927 list_add_tail( &expired_list, &timeout->entry );
929 else break;
931 while ((ptr = list_head( &rel_timeout_list )) != NULL)
933 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
935 if (-timeout->when <= monotonic_time)
937 list_remove( &timeout->entry );
938 list_add_tail( &expired_list, &timeout->entry );
940 else break;
943 /* now call the callback for all the removed timers */
945 while ((ptr = list_head( &expired_list )) != NULL)
947 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
948 list_remove( &timeout->entry );
949 timeout->callback( timeout->private );
950 free( timeout );
953 if ((ptr = list_head( &abs_timeout_list )) != NULL)
955 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
956 int diff = (timeout->when - current_time + 9999) / 10000;
957 if (diff < 0) diff = 0;
958 if (ret == -1 || diff < ret) ret = diff;
961 if ((ptr = list_head( &rel_timeout_list )) != NULL)
963 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
964 int diff = (-timeout->when - monotonic_time + 9999) / 10000;
965 if (diff < 0) diff = 0;
966 if (ret == -1 || diff < ret) ret = diff;
969 return ret;
972 /* server main poll() loop */
973 void main_loop(void)
975 int i, ret, timeout;
977 set_current_time();
978 server_start_time = current_time;
980 main_loop_epoll();
981 /* fall through to normal poll loop */
983 while (active_users)
985 timeout = get_next_timeout();
987 if (!active_users) break; /* last user removed by a timeout */
989 ret = poll( pollfd, nb_users, timeout );
990 set_current_time();
992 if (ret > 0)
994 for (i = 0; i < nb_users; i++)
996 if (pollfd[i].revents)
998 fd_poll_event( poll_users[i], pollfd[i].revents );
999 if (!--ret) break;
1007 /****************************************************************/
1008 /* device functions */
1010 static struct list device_hash[DEVICE_HASH_SIZE];
1012 static int is_device_removable( dev_t dev, int unix_fd )
1014 #if defined(linux) && defined(HAVE_FSTATFS)
1015 struct statfs stfs;
1017 /* check for floppy disk */
1018 if (major(dev) == FLOPPY_MAJOR) return 1;
1020 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
1021 return (stfs.f_type == 0x9660 || /* iso9660 */
1022 stfs.f_type == 0x9fa1 || /* supermount */
1023 stfs.f_type == 0x15013346); /* udf */
1024 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
1025 struct statfs stfs;
1027 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
1028 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
1029 #elif defined(__NetBSD__)
1030 struct statvfs stfs;
1032 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
1033 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
1034 #elif defined(sun)
1035 # include <sys/dkio.h>
1036 # include <sys/vtoc.h>
1037 struct dk_cinfo dkinf;
1038 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
1039 return (dkinf.dki_ctype == DKC_CDROM ||
1040 dkinf.dki_ctype == DKC_NCRFLOPPY ||
1041 dkinf.dki_ctype == DKC_SMSFLOPPY ||
1042 dkinf.dki_ctype == DKC_INTEL82072 ||
1043 dkinf.dki_ctype == DKC_INTEL82077);
1044 #else
1045 return 0;
1046 #endif
1049 /* retrieve the device object for a given fd, creating it if needed */
1050 static struct device *get_device( dev_t dev, int unix_fd )
1052 struct device *device;
1053 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
1055 if (device_hash[hash].next)
1057 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
1058 if (device->dev == dev) return (struct device *)grab_object( device );
1060 else list_init( &device_hash[hash] );
1062 /* not found, create it */
1064 if (unix_fd == -1) return NULL;
1065 if ((device = alloc_object( &device_ops )))
1067 device->dev = dev;
1068 device->removable = is_device_removable( dev, unix_fd );
1069 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
1070 list_add_head( &device_hash[hash], &device->entry );
1072 return device;
1075 static void device_dump( struct object *obj, int verbose )
1077 struct device *device = (struct device *)obj;
1078 fprintf( stderr, "Device dev=" );
1079 DUMP_LONG_LONG( device->dev );
1080 fprintf( stderr, "\n" );
1083 static void device_destroy( struct object *obj )
1085 struct device *device = (struct device *)obj;
1086 unsigned int i;
1088 for (i = 0; i < INODE_HASH_SIZE; i++)
1089 assert( list_empty(&device->inode_hash[i]) );
1091 list_remove( &device->entry ); /* remove it from the hash table */
1095 /****************************************************************/
1096 /* inode functions */
1098 /* close all pending file descriptors in the closed list */
1099 static void inode_close_pending( struct inode *inode, int keep_unlinks )
1101 struct list *ptr = list_head( &inode->closed );
1103 while (ptr)
1105 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1106 struct list *next = list_next( &inode->closed, ptr );
1108 if (fd->unix_fd != -1)
1110 close( fd->unix_fd );
1111 fd->unix_fd = -1;
1113 if (!keep_unlinks || !fd->unlink) /* get rid of it unless there's an unlink pending on that file */
1115 list_remove( ptr );
1116 free( fd->unix_name );
1117 free( fd );
1119 ptr = next;
1123 static void inode_dump( struct object *obj, int verbose )
1125 struct inode *inode = (struct inode *)obj;
1126 fprintf( stderr, "Inode device=%p ino=", inode->device );
1127 DUMP_LONG_LONG( inode->ino );
1128 fprintf( stderr, "\n" );
1131 static void inode_destroy( struct object *obj )
1133 struct inode *inode = (struct inode *)obj;
1134 struct list *ptr;
1136 assert( list_empty(&inode->open) );
1137 assert( list_empty(&inode->locks) );
1139 list_remove( &inode->entry );
1141 while ((ptr = list_head( &inode->closed )))
1143 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1144 list_remove( ptr );
1145 if (fd->unix_fd != -1) close( fd->unix_fd );
1146 if (fd->unlink)
1148 /* make sure it is still the same file */
1149 struct stat st;
1150 if (!stat( fd->unix_name, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
1152 if (S_ISDIR(st.st_mode)) rmdir( fd->unix_name );
1153 else unlink( fd->unix_name );
1156 free( fd->unix_name );
1157 free( fd );
1159 release_object( inode->device );
1162 /* retrieve the inode object for a given fd, creating it if needed */
1163 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
1165 struct device *device;
1166 struct inode *inode;
1167 unsigned int hash = ino % INODE_HASH_SIZE;
1169 if (!(device = get_device( dev, unix_fd ))) return NULL;
1171 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
1173 if (inode->ino == ino)
1175 release_object( device );
1176 return (struct inode *)grab_object( inode );
1180 /* not found, create it */
1181 if ((inode = alloc_object( &inode_ops )))
1183 inode->device = device;
1184 inode->ino = ino;
1185 list_init( &inode->open );
1186 list_init( &inode->locks );
1187 list_init( &inode->closed );
1188 list_add_head( &device->inode_hash[hash], &inode->entry );
1190 else release_object( device );
1192 return inode;
1195 /* add fd to the inode list of file descriptors to close */
1196 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1198 if (!list_empty( &inode->locks ))
1200 list_add_head( &inode->closed, &fd->entry );
1202 else if (fd->unlink) /* close the fd but keep the structure around for unlink */
1204 if (fd->unix_fd != -1) close( fd->unix_fd );
1205 fd->unix_fd = -1;
1206 list_add_head( &inode->closed, &fd->entry );
1208 else /* no locks on this inode and no unlink, get rid of the fd */
1210 if (fd->unix_fd != -1) close( fd->unix_fd );
1211 free( fd->unix_name );
1212 free( fd );
1217 /****************************************************************/
1218 /* file lock functions */
1220 static void file_lock_dump( struct object *obj, int verbose )
1222 struct file_lock *lock = (struct file_lock *)obj;
1223 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1224 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1225 DUMP_LONG_LONG( lock->start );
1226 fprintf( stderr, " end=" );
1227 DUMP_LONG_LONG( lock->end );
1228 fprintf( stderr, "\n" );
1231 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry )
1233 struct file_lock *lock = (struct file_lock *)obj;
1234 /* lock is signaled if it has lost its owner */
1235 return !lock->process;
1238 /* set (or remove) a Unix lock if possible for the given range */
1239 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1241 struct flock fl;
1243 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1244 for (;;)
1246 if (start == end) return 1; /* can't set zero-byte lock */
1247 if (start > max_unix_offset) return 1; /* ignore it */
1248 fl.l_type = type;
1249 fl.l_whence = SEEK_SET;
1250 fl.l_start = start;
1251 if (!end || end > max_unix_offset) fl.l_len = 0;
1252 else fl.l_len = end - start;
1253 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1255 switch(errno)
1257 case EACCES:
1258 /* check whether locks work at all on this file system */
1259 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1261 set_error( STATUS_FILE_LOCK_CONFLICT );
1262 return 0;
1264 /* fall through */
1265 case EIO:
1266 case ENOLCK:
1267 case ENOTSUP:
1268 /* no locking on this fs, just ignore it */
1269 fd->fs_locks = 0;
1270 return 1;
1271 case EAGAIN:
1272 set_error( STATUS_FILE_LOCK_CONFLICT );
1273 return 0;
1274 case EBADF:
1275 /* this can happen if we try to set a write lock on a read-only file */
1276 /* try to at least grab a read lock */
1277 if (fl.l_type == F_WRLCK)
1279 type = F_RDLCK;
1280 break; /* retry */
1282 set_error( STATUS_ACCESS_DENIED );
1283 return 0;
1284 #ifdef EOVERFLOW
1285 case EOVERFLOW:
1286 #endif
1287 case EINVAL:
1288 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1289 /* in that case we shrink the limit and retry */
1290 if (max_unix_offset > INT_MAX)
1292 max_unix_offset = INT_MAX;
1293 break; /* retry */
1295 /* fall through */
1296 default:
1297 file_set_error();
1298 return 0;
1303 /* check if interval [start;end) overlaps the lock */
1304 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1306 if (lock->end && start >= lock->end) return 0;
1307 if (end && lock->start >= end) return 0;
1308 return 1;
1311 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1312 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1314 struct hole
1316 struct hole *next;
1317 struct hole *prev;
1318 file_pos_t start;
1319 file_pos_t end;
1320 } *first, *cur, *next, *buffer;
1322 struct list *ptr;
1323 int count = 0;
1325 if (!fd->inode) return;
1326 if (!fd->fs_locks) return;
1327 if (start == end || start > max_unix_offset) return;
1328 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1330 /* count the number of locks overlapping the specified area */
1332 LIST_FOR_EACH( ptr, &fd->inode->locks )
1334 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1335 if (lock->start == lock->end) continue;
1336 if (lock_overlaps( lock, start, end )) count++;
1339 if (!count) /* no locks at all, we can unlock everything */
1341 set_unix_lock( fd, start, end, F_UNLCK );
1342 return;
1345 /* allocate space for the list of holes */
1346 /* max. number of holes is number of locks + 1 */
1348 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1349 first = buffer;
1350 first->next = NULL;
1351 first->prev = NULL;
1352 first->start = start;
1353 first->end = end;
1354 next = first + 1;
1356 /* build a sorted list of unlocked holes in 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 )) continue;
1364 /* go through all the holes touched by this lock */
1365 for (cur = first; cur; cur = cur->next)
1367 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1368 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1370 /* now we know that lock is overlapping hole */
1372 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1374 cur->start = lock->end;
1375 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1376 /* now hole is empty, remove it */
1377 if (cur->next) cur->next->prev = cur->prev;
1378 if (cur->prev) cur->prev->next = cur->next;
1379 else if (!(first = cur->next)) goto done; /* no more holes at all */
1381 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1383 cur->end = lock->start;
1384 assert( cur->start < cur->end );
1386 else /* lock is in the middle of hole, split hole in two */
1388 next->prev = cur;
1389 next->next = cur->next;
1390 cur->next = next;
1391 next->start = lock->end;
1392 next->end = cur->end;
1393 cur->end = lock->start;
1394 assert( next->start < next->end );
1395 assert( cur->end < next->start );
1396 next++;
1397 break; /* done with this lock */
1402 /* clear Unix locks for all the holes */
1404 for (cur = first; cur; cur = cur->next)
1405 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1407 done:
1408 free( buffer );
1411 /* create a new lock on a fd */
1412 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1414 struct file_lock *lock;
1416 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1417 lock->shared = shared;
1418 lock->start = start;
1419 lock->end = end;
1420 lock->fd = fd;
1421 lock->process = current->process;
1423 /* now try to set a Unix lock */
1424 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1426 release_object( lock );
1427 return NULL;
1429 list_add_tail( &fd->locks, &lock->fd_entry );
1430 list_add_tail( &fd->inode->locks, &lock->inode_entry );
1431 list_add_tail( &lock->process->locks, &lock->proc_entry );
1432 return lock;
1435 /* remove an existing lock */
1436 static void remove_lock( struct file_lock *lock, int remove_unix )
1438 struct inode *inode = lock->fd->inode;
1440 list_remove( &lock->fd_entry );
1441 list_remove( &lock->inode_entry );
1442 list_remove( &lock->proc_entry );
1443 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1444 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1445 lock->process = NULL;
1446 wake_up( &lock->obj, 0 );
1447 release_object( lock );
1450 /* remove all locks owned by a given process */
1451 void remove_process_locks( struct process *process )
1453 struct list *ptr;
1455 while ((ptr = list_head( &process->locks )))
1457 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1458 remove_lock( lock, 1 ); /* this removes it from the list */
1462 /* remove all locks on a given fd */
1463 static void remove_fd_locks( struct fd *fd )
1465 file_pos_t start = FILE_POS_T_MAX, end = 0;
1466 struct list *ptr;
1468 while ((ptr = list_head( &fd->locks )))
1470 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1471 if (lock->start < start) start = lock->start;
1472 if (!lock->end || lock->end > end) end = lock->end - 1;
1473 remove_lock( lock, 0 );
1475 if (start < end) remove_unix_locks( fd, start, end + 1 );
1478 /* add a lock on an fd */
1479 /* returns handle to wait on */
1480 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1482 struct list *ptr;
1483 file_pos_t end = start + count;
1485 if (!fd->inode) /* not a regular file */
1487 set_error( STATUS_INVALID_DEVICE_REQUEST );
1488 return 0;
1491 /* don't allow wrapping locks */
1492 if (end && end < start)
1494 set_error( STATUS_INVALID_PARAMETER );
1495 return 0;
1498 /* check if another lock on that file overlaps the area */
1499 LIST_FOR_EACH( ptr, &fd->inode->locks )
1501 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1502 if (!lock_overlaps( lock, start, end )) continue;
1503 if (shared && (lock->shared || lock->fd == fd)) continue;
1504 /* found one */
1505 if (!wait)
1507 set_error( STATUS_FILE_LOCK_CONFLICT );
1508 return 0;
1510 set_error( STATUS_PENDING );
1511 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1514 /* not found, add it */
1515 if (add_lock( fd, shared, start, end )) return 0;
1516 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1518 /* Unix lock conflict -> tell client to wait and retry */
1519 if (wait) set_error( STATUS_PENDING );
1521 return 0;
1524 /* remove a lock on an fd */
1525 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1527 struct list *ptr;
1528 file_pos_t end = start + count;
1530 /* find an existing lock with the exact same parameters */
1531 LIST_FOR_EACH( ptr, &fd->locks )
1533 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1534 if ((lock->start == start) && (lock->end == end))
1536 remove_lock( lock, 1 );
1537 return;
1540 set_error( STATUS_FILE_LOCK_CONFLICT );
1544 /****************************************************************/
1545 /* file descriptor functions */
1547 static void fd_dump( struct object *obj, int verbose )
1549 struct fd *fd = (struct fd *)obj;
1550 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1551 if (fd->inode) fprintf( stderr, " inode=%p unlink=%d", fd->inode, fd->closed->unlink );
1552 fprintf( stderr, "\n" );
1555 static void fd_destroy( struct object *obj )
1557 struct fd *fd = (struct fd *)obj;
1559 free_async_queue( &fd->read_q );
1560 free_async_queue( &fd->write_q );
1561 free_async_queue( &fd->wait_q );
1563 if (fd->completion) release_object( fd->completion );
1564 remove_fd_locks( fd );
1565 list_remove( &fd->inode_entry );
1566 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1567 if (fd->inode)
1569 inode_add_closed_fd( fd->inode, fd->closed );
1570 release_object( fd->inode );
1572 else /* no inode, close it right away */
1574 if (fd->unix_fd != -1) close( fd->unix_fd );
1575 free( fd->unix_name );
1579 /* check if the desired access is possible without violating */
1580 /* the sharing mode of other opens of the same file */
1581 static unsigned int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing,
1582 unsigned int open_flags, unsigned int options )
1584 /* only a few access bits are meaningful wrt sharing */
1585 const unsigned int read_access = FILE_READ_DATA | FILE_EXECUTE;
1586 const unsigned int write_access = FILE_WRITE_DATA | FILE_APPEND_DATA;
1587 const unsigned int all_access = read_access | write_access | DELETE;
1589 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1590 unsigned int existing_access = 0;
1591 struct list *ptr;
1593 fd->access = access;
1594 fd->sharing = sharing;
1596 LIST_FOR_EACH( ptr, &fd->inode->open )
1598 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1599 if (fd_ptr != fd)
1601 /* if access mode is 0, sharing mode is ignored */
1602 if (fd_ptr->access & all_access) existing_sharing &= fd_ptr->sharing;
1603 existing_access |= fd_ptr->access;
1607 if (((access & read_access) && !(existing_sharing & FILE_SHARE_READ)) ||
1608 ((access & write_access) && !(existing_sharing & FILE_SHARE_WRITE)) ||
1609 ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)))
1610 return STATUS_SHARING_VIOLATION;
1611 if (((existing_access & FILE_MAPPING_WRITE) && !(sharing & FILE_SHARE_WRITE)) ||
1612 ((existing_access & FILE_MAPPING_IMAGE) && (access & FILE_WRITE_DATA)))
1613 return STATUS_SHARING_VIOLATION;
1614 if ((existing_access & FILE_MAPPING_IMAGE) && (options & FILE_DELETE_ON_CLOSE))
1615 return STATUS_CANNOT_DELETE;
1616 if ((existing_access & FILE_MAPPING_ACCESS) && (open_flags & O_TRUNC))
1617 return STATUS_USER_MAPPED_FILE;
1618 if (!(access & all_access))
1619 return 0; /* if access mode is 0, sharing mode is ignored (except for mappings) */
1620 if (((existing_access & read_access) && !(sharing & FILE_SHARE_READ)) ||
1621 ((existing_access & write_access) && !(sharing & FILE_SHARE_WRITE)) ||
1622 ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)))
1623 return STATUS_SHARING_VIOLATION;
1624 return 0;
1627 /* set the events that select waits for on this fd */
1628 void set_fd_events( struct fd *fd, int events )
1630 int user = fd->poll_index;
1631 assert( poll_users[user] == fd );
1633 set_fd_epoll_events( fd, user, events );
1635 if (events == -1) /* stop waiting on this fd completely */
1637 pollfd[user].fd = -1;
1638 pollfd[user].events = POLLERR;
1639 pollfd[user].revents = 0;
1641 else if (pollfd[user].fd != -1 || !pollfd[user].events)
1643 pollfd[user].fd = fd->unix_fd;
1644 pollfd[user].events = events;
1648 /* prepare an fd for unmounting its corresponding device */
1649 static inline void unmount_fd( struct fd *fd )
1651 assert( fd->inode );
1653 async_wake_up( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1654 async_wake_up( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1656 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1658 if (fd->unix_fd != -1) close( fd->unix_fd );
1660 fd->unix_fd = -1;
1661 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1662 fd->closed->unix_fd = -1;
1663 fd->closed->unlink = 0;
1665 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1666 fd->fs_locks = 0;
1669 /* allocate an fd object, without setting the unix fd yet */
1670 static struct fd *alloc_fd_object(void)
1672 struct fd *fd = alloc_object( &fd_ops );
1674 if (!fd) return NULL;
1676 fd->fd_ops = NULL;
1677 fd->user = NULL;
1678 fd->inode = NULL;
1679 fd->closed = NULL;
1680 fd->access = 0;
1681 fd->options = 0;
1682 fd->sharing = 0;
1683 fd->unix_fd = -1;
1684 fd->unix_name = NULL;
1685 fd->cacheable = 0;
1686 fd->signaled = 1;
1687 fd->fs_locks = 1;
1688 fd->poll_index = -1;
1689 fd->completion = NULL;
1690 fd->comp_flags = 0;
1691 init_async_queue( &fd->read_q );
1692 init_async_queue( &fd->write_q );
1693 init_async_queue( &fd->wait_q );
1694 list_init( &fd->inode_entry );
1695 list_init( &fd->locks );
1697 if ((fd->poll_index = add_poll_user( fd )) == -1)
1699 release_object( fd );
1700 return NULL;
1702 return fd;
1705 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1706 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1708 struct fd *fd = alloc_object( &fd_ops );
1710 if (!fd) return NULL;
1712 fd->fd_ops = fd_user_ops;
1713 fd->user = user;
1714 fd->inode = NULL;
1715 fd->closed = NULL;
1716 fd->access = 0;
1717 fd->options = options;
1718 fd->sharing = 0;
1719 fd->unix_name = NULL;
1720 fd->unix_fd = -1;
1721 fd->cacheable = 0;
1722 fd->signaled = 0;
1723 fd->fs_locks = 0;
1724 fd->poll_index = -1;
1725 fd->completion = NULL;
1726 fd->comp_flags = 0;
1727 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1728 init_async_queue( &fd->read_q );
1729 init_async_queue( &fd->write_q );
1730 init_async_queue( &fd->wait_q );
1731 list_init( &fd->inode_entry );
1732 list_init( &fd->locks );
1733 return fd;
1736 /* duplicate an fd object for a different user */
1737 struct fd *dup_fd_object( struct fd *orig, unsigned int access, unsigned int sharing, unsigned int options )
1739 unsigned int err;
1740 struct fd *fd = alloc_fd_object();
1742 if (!fd) return NULL;
1744 fd->options = options;
1745 fd->cacheable = orig->cacheable;
1747 if (orig->unix_name)
1749 if (!(fd->unix_name = mem_alloc( strlen(orig->unix_name) + 1 ))) goto failed;
1750 strcpy( fd->unix_name, orig->unix_name );
1753 if (orig->inode)
1755 struct closed_fd *closed = mem_alloc( sizeof(*closed) );
1756 if (!closed) goto failed;
1757 if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1759 file_set_error();
1760 free( closed );
1761 goto failed;
1763 closed->unix_fd = fd->unix_fd;
1764 closed->unlink = 0;
1765 closed->unix_name = fd->unix_name;
1766 fd->closed = closed;
1767 fd->inode = (struct inode *)grab_object( orig->inode );
1768 list_add_head( &fd->inode->open, &fd->inode_entry );
1769 if ((err = check_sharing( fd, access, sharing, 0, options )))
1771 set_error( err );
1772 goto failed;
1775 else if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1777 file_set_error();
1778 goto failed;
1780 return fd;
1782 failed:
1783 release_object( fd );
1784 return NULL;
1787 /* find an existing fd object that can be reused for a mapping */
1788 struct fd *get_fd_object_for_mapping( struct fd *fd, unsigned int access, unsigned int sharing )
1790 struct fd *fd_ptr;
1792 if (!fd->inode) return NULL;
1794 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
1795 if (fd_ptr->access == access && fd_ptr->sharing == sharing)
1796 return (struct fd *)grab_object( fd_ptr );
1798 return NULL;
1801 /* sets the user of an fd that previously had no user */
1802 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1804 assert( fd->fd_ops == NULL );
1805 fd->fd_ops = user_ops;
1806 fd->user = user;
1809 char *dup_fd_name( struct fd *root, const char *name )
1811 char *ret;
1813 if (!root) return strdup( name );
1814 if (!root->unix_name) return NULL;
1816 /* skip . prefix */
1817 if (name[0] == '.' && (!name[1] || name[1] == '/')) name++;
1819 if ((ret = malloc( strlen(root->unix_name) + strlen(name) + 2 )))
1821 strcpy( ret, root->unix_name );
1822 if (name[0] && name[0] != '/') strcat( ret, "/" );
1823 strcat( ret, name );
1825 return ret;
1828 /* open() wrapper that returns a struct fd with no fd user set */
1829 struct fd *open_fd( struct fd *root, const char *name, int flags, mode_t *mode, unsigned int access,
1830 unsigned int sharing, unsigned int options )
1832 struct stat st;
1833 struct closed_fd *closed_fd;
1834 struct fd *fd;
1835 int root_fd = -1;
1836 int rw_mode;
1837 char *path;
1839 if (((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE)) ||
1840 ((options & FILE_DIRECTORY_FILE) && (flags & O_TRUNC)))
1842 set_error( STATUS_INVALID_PARAMETER );
1843 return NULL;
1846 if (!(fd = alloc_fd_object())) return NULL;
1848 fd->options = options;
1849 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
1851 release_object( fd );
1852 return NULL;
1855 if (root)
1857 if ((root_fd = get_unix_fd( root )) == -1) goto error;
1858 if (fchdir( root_fd ) == -1)
1860 file_set_error();
1861 root_fd = -1;
1862 goto error;
1866 /* create the directory if needed */
1867 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1869 if (mkdir( name, *mode ) == -1)
1871 if (errno != EEXIST || (flags & O_EXCL))
1873 file_set_error();
1874 goto error;
1877 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1880 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1882 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1883 else rw_mode = O_WRONLY;
1885 else rw_mode = O_RDONLY;
1887 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1889 /* if we tried to open a directory for write access, retry read-only */
1890 if (errno == EISDIR)
1892 if ((access & FILE_UNIX_WRITE_ACCESS) || (flags & O_CREAT))
1893 fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode );
1896 if (fd->unix_fd == -1)
1898 file_set_error();
1899 goto error;
1903 fd->unix_name = NULL;
1904 if ((path = dup_fd_name( root, name )))
1906 fd->unix_name = realpath( path, NULL );
1907 free( path );
1910 closed_fd->unix_fd = fd->unix_fd;
1911 closed_fd->unlink = 0;
1912 closed_fd->unix_name = fd->unix_name;
1913 fstat( fd->unix_fd, &st );
1914 *mode = st.st_mode;
1916 /* only bother with an inode for normal files and directories */
1917 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1919 unsigned int err;
1920 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1922 if (!inode)
1924 /* we can close the fd because there are no others open on the same file,
1925 * otherwise we wouldn't have failed to allocate a new inode
1927 goto error;
1929 fd->inode = inode;
1930 fd->closed = closed_fd;
1931 fd->cacheable = !inode->device->removable;
1932 list_add_head( &inode->open, &fd->inode_entry );
1933 closed_fd = NULL;
1935 /* check directory options */
1936 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1938 set_error( STATUS_NOT_A_DIRECTORY );
1939 goto error;
1941 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1943 set_error( STATUS_FILE_IS_A_DIRECTORY );
1944 goto error;
1946 if ((err = check_sharing( fd, access, sharing, flags, options )))
1948 set_error( err );
1949 goto error;
1952 /* can't unlink files if we don't have permission to access */
1953 if ((options & FILE_DELETE_ON_CLOSE) && !(flags & O_CREAT) &&
1954 !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1956 set_error( STATUS_CANNOT_DELETE );
1957 goto error;
1960 fd->closed->unlink = (options & FILE_DELETE_ON_CLOSE) ? -1 : 0;
1961 if (flags & O_TRUNC)
1963 if (S_ISDIR(st.st_mode))
1965 set_error( STATUS_OBJECT_NAME_COLLISION );
1966 goto error;
1968 ftruncate( fd->unix_fd, 0 );
1971 else /* special file */
1973 if (options & FILE_DELETE_ON_CLOSE) /* we can't unlink special files */
1975 set_error( STATUS_INVALID_PARAMETER );
1976 goto error;
1978 free( closed_fd );
1979 fd->cacheable = 1;
1981 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1982 return fd;
1984 error:
1985 release_object( fd );
1986 free( closed_fd );
1987 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1988 return NULL;
1991 /* create an fd for an anonymous file */
1992 /* if the function fails the unix fd is closed */
1993 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
1994 unsigned int options )
1996 struct fd *fd = alloc_fd_object();
1998 if (fd)
2000 set_fd_user( fd, fd_user_ops, user );
2001 fd->unix_fd = unix_fd;
2002 fd->options = options;
2003 return fd;
2005 close( unix_fd );
2006 return NULL;
2009 /* retrieve the object that is using an fd */
2010 void *get_fd_user( struct fd *fd )
2012 return fd->user;
2015 /* retrieve the opening options for the fd */
2016 unsigned int get_fd_options( struct fd *fd )
2018 return fd->options;
2021 /* check if fd is in overlapped mode */
2022 int is_fd_overlapped( struct fd *fd )
2024 return !(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
2027 /* retrieve the unix fd for an object */
2028 int get_unix_fd( struct fd *fd )
2030 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
2031 return fd->unix_fd;
2034 /* check if two file descriptors point to the same file */
2035 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
2037 return fd1->inode == fd2->inode;
2040 /* allow the fd to be cached (can't be reset once set) */
2041 void allow_fd_caching( struct fd *fd )
2043 fd->cacheable = 1;
2046 /* check if fd is on a removable device */
2047 int is_fd_removable( struct fd *fd )
2049 return (fd->inode && fd->inode->device->removable);
2052 /* set or clear the fd signaled state */
2053 void set_fd_signaled( struct fd *fd, int signaled )
2055 if (fd->comp_flags & FILE_SKIP_SET_EVENT_ON_HANDLE) return;
2056 fd->signaled = signaled;
2057 if (signaled) wake_up( fd->user, 0 );
2060 /* handler for close_handle that refuses to close fd-associated handles in other processes */
2061 int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
2063 return (!current || current->process == process);
2066 /* check if events are pending and if yes return which one(s) */
2067 int check_fd_events( struct fd *fd, int events )
2069 struct pollfd pfd;
2071 if (fd->unix_fd == -1) return POLLERR;
2072 if (fd->inode) return events; /* regular files are always signaled */
2074 pfd.fd = fd->unix_fd;
2075 pfd.events = events;
2076 if (poll( &pfd, 1, 0 ) <= 0) return 0;
2077 return pfd.revents;
2080 /* default signaled() routine for objects that poll() on an fd */
2081 int default_fd_signaled( struct object *obj, struct wait_queue_entry *entry )
2083 struct fd *fd = get_obj_fd( obj );
2084 int ret = fd->signaled;
2085 release_object( fd );
2086 return ret;
2089 /* default map_access() routine for objects that behave like an fd */
2090 unsigned int default_fd_map_access( struct object *obj, unsigned int access )
2092 if (access & GENERIC_READ) access |= FILE_GENERIC_READ;
2093 if (access & GENERIC_WRITE) access |= FILE_GENERIC_WRITE;
2094 if (access & GENERIC_EXECUTE) access |= FILE_GENERIC_EXECUTE;
2095 if (access & GENERIC_ALL) access |= FILE_ALL_ACCESS;
2096 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
2099 int default_fd_get_poll_events( struct fd *fd )
2101 int events = 0;
2103 if (async_waiting( &fd->read_q )) events |= POLLIN;
2104 if (async_waiting( &fd->write_q )) events |= POLLOUT;
2105 return events;
2108 /* default handler for poll() events */
2109 void default_poll_event( struct fd *fd, int event )
2111 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( &fd->read_q, STATUS_ALERTED );
2112 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( &fd->write_q, STATUS_ALERTED );
2114 /* if an error occurred, stop polling this fd to avoid busy-looping */
2115 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
2116 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2119 void fd_queue_async( struct fd *fd, struct async *async, int type )
2121 struct async_queue *queue;
2123 switch (type)
2125 case ASYNC_TYPE_READ:
2126 queue = &fd->read_q;
2127 break;
2128 case ASYNC_TYPE_WRITE:
2129 queue = &fd->write_q;
2130 break;
2131 case ASYNC_TYPE_WAIT:
2132 queue = &fd->wait_q;
2133 break;
2134 default:
2135 queue = NULL;
2136 assert(0);
2139 queue_async( queue, async );
2141 if (type != ASYNC_TYPE_WAIT)
2143 if (!fd->inode)
2144 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2145 else /* regular files are always ready for read and write */
2146 async_wake_up( queue, STATUS_ALERTED );
2150 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
2152 switch (type)
2154 case ASYNC_TYPE_READ:
2155 async_wake_up( &fd->read_q, status );
2156 break;
2157 case ASYNC_TYPE_WRITE:
2158 async_wake_up( &fd->write_q, status );
2159 break;
2160 case ASYNC_TYPE_WAIT:
2161 async_wake_up( &fd->wait_q, status );
2162 break;
2163 default:
2164 assert(0);
2168 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
2170 fd->fd_ops->reselect_async( fd, queue );
2173 void no_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2175 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2178 void default_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2180 fd_queue_async( fd, async, type );
2181 set_error( STATUS_PENDING );
2184 /* default reselect_async() fd routine */
2185 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
2187 if (queue == &fd->read_q || queue == &fd->write_q)
2189 int poll_events = fd->fd_ops->get_poll_events( fd );
2190 int events = check_fd_events( fd, poll_events );
2191 if (events) fd->fd_ops->poll_event( fd, events );
2192 else set_fd_events( fd, poll_events );
2196 static inline int is_valid_mounted_device( struct stat *st )
2198 #if defined(linux) || defined(__sun__)
2199 return S_ISBLK( st->st_mode );
2200 #else
2201 /* disks are char devices on *BSD */
2202 return S_ISCHR( st->st_mode );
2203 #endif
2206 /* close all Unix file descriptors on a device to allow unmounting it */
2207 static void unmount_device( struct fd *device_fd )
2209 unsigned int i;
2210 struct stat st;
2211 struct device *device;
2212 struct inode *inode;
2213 struct fd *fd;
2214 int unix_fd = get_unix_fd( device_fd );
2216 if (unix_fd == -1) return;
2218 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2220 set_error( STATUS_INVALID_PARAMETER );
2221 return;
2224 if (!(device = get_device( st.st_rdev, -1 ))) return;
2226 for (i = 0; i < INODE_HASH_SIZE; i++)
2228 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
2230 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
2232 unmount_fd( fd );
2234 inode_close_pending( inode, 0 );
2237 /* remove it from the hash table */
2238 list_remove( &device->entry );
2239 list_init( &device->entry );
2240 release_object( device );
2243 /* default read() routine */
2244 int no_fd_read( struct fd *fd, struct async *async, file_pos_t pos )
2246 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2247 return 0;
2250 /* default write() routine */
2251 int no_fd_write( struct fd *fd, struct async *async, file_pos_t pos )
2253 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2254 return 0;
2257 /* default flush() routine */
2258 int no_fd_flush( struct fd *fd, struct async *async )
2260 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2261 return 0;
2264 /* default get_file_info() routine */
2265 void no_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2267 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2270 /* default get_file_info() routine */
2271 void default_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2273 switch (info_class)
2275 case FileAccessInformation:
2277 FILE_ACCESS_INFORMATION info;
2278 if (get_reply_max_size() < sizeof(info))
2280 set_error( STATUS_INFO_LENGTH_MISMATCH );
2281 return;
2283 info.AccessFlags = get_handle_access( current->process, handle );
2284 set_reply_data( &info, sizeof(info) );
2285 break;
2287 case FileModeInformation:
2289 FILE_MODE_INFORMATION info;
2290 if (get_reply_max_size() < sizeof(info))
2292 set_error( STATUS_INFO_LENGTH_MISMATCH );
2293 return;
2295 info.Mode = fd->options & ( FILE_WRITE_THROUGH
2296 | FILE_SEQUENTIAL_ONLY
2297 | FILE_NO_INTERMEDIATE_BUFFERING
2298 | FILE_SYNCHRONOUS_IO_ALERT
2299 | FILE_SYNCHRONOUS_IO_NONALERT );
2300 set_reply_data( &info, sizeof(info) );
2301 break;
2303 case FileIoCompletionNotificationInformation:
2305 FILE_IO_COMPLETION_NOTIFICATION_INFORMATION info;
2306 if (get_reply_max_size() < sizeof(info))
2308 set_error( STATUS_INFO_LENGTH_MISMATCH );
2309 return;
2311 info.Flags = fd->comp_flags;
2312 set_reply_data( &info, sizeof(info) );
2313 break;
2315 default:
2316 set_error( STATUS_NOT_IMPLEMENTED );
2320 /* default get_volume_info() routine */
2321 void no_fd_get_volume_info( struct fd *fd, unsigned int info_class )
2323 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2326 /* default ioctl() routine */
2327 int no_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2329 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2330 return 0;
2333 /* default ioctl() routine */
2334 int default_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2336 switch(code)
2338 case FSCTL_DISMOUNT_VOLUME:
2339 unmount_device( fd );
2340 return 1;
2341 default:
2342 set_error( STATUS_NOT_SUPPORTED );
2343 return 0;
2347 /* same as get_handle_obj but retrieve the struct fd associated to the object */
2348 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
2349 unsigned int access )
2351 struct fd *fd = NULL;
2352 struct object *obj;
2354 if ((obj = get_handle_obj( process, handle, access, NULL )))
2356 fd = get_obj_fd( obj );
2357 release_object( obj );
2359 return fd;
2362 static int is_dir_empty( int fd )
2364 DIR *dir;
2365 int empty;
2366 struct dirent *de;
2368 if ((fd = dup( fd )) == -1)
2369 return -1;
2371 if (!(dir = fdopendir( fd )))
2373 close( fd );
2374 return -1;
2377 empty = 1;
2378 while (empty && (de = readdir( dir )))
2380 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2381 empty = 0;
2383 closedir( dir );
2384 return empty;
2387 /* set disposition for the fd */
2388 static void set_fd_disposition( struct fd *fd, int unlink )
2390 struct stat st;
2392 if (!fd->inode)
2394 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2395 return;
2398 if (fd->unix_fd == -1)
2400 set_error( fd->no_fd_status );
2401 return;
2404 if (unlink)
2406 if (fstat( fd->unix_fd, &st ) == -1)
2408 file_set_error();
2409 return;
2411 if (S_ISREG( st.st_mode )) /* can't unlink files we don't have permission to write */
2413 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2415 set_error( STATUS_CANNOT_DELETE );
2416 return;
2419 else if (S_ISDIR( st.st_mode )) /* can't remove non-empty directories */
2421 switch (is_dir_empty( fd->unix_fd ))
2423 case -1:
2424 file_set_error();
2425 return;
2426 case 0:
2427 set_error( STATUS_DIRECTORY_NOT_EMPTY );
2428 return;
2431 else /* can't unlink special files */
2433 set_error( STATUS_INVALID_PARAMETER );
2434 return;
2438 fd->closed->unlink = unlink ? 1 : 0;
2439 if (fd->options & FILE_DELETE_ON_CLOSE)
2440 fd->closed->unlink = -1;
2443 /* set new name for the fd */
2444 static void set_fd_name( struct fd *fd, struct fd *root, const char *nameptr,
2445 data_size_t len, int create_link, int replace )
2447 struct inode *inode;
2448 struct stat st, st2;
2449 char *name;
2451 if (!fd->inode || !fd->unix_name)
2453 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2454 return;
2456 if (fd->unix_fd == -1)
2458 set_error( fd->no_fd_status );
2459 return;
2462 if (!len || ((nameptr[0] == '/') ^ !root))
2464 set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
2465 return;
2467 if (!(name = mem_alloc( len + 1 ))) return;
2468 memcpy( name, nameptr, len );
2469 name[len] = 0;
2471 if (root)
2473 char *combined_name = dup_fd_name( root, name );
2474 if (!combined_name)
2476 set_error( STATUS_NO_MEMORY );
2477 goto failed;
2479 free( name );
2480 name = combined_name;
2483 /* when creating a hard link, source cannot be a dir */
2484 if (create_link && !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode ))
2486 set_error( STATUS_FILE_IS_A_DIRECTORY );
2487 goto failed;
2490 if (!stat( name, &st ))
2492 if (!fstat( fd->unix_fd, &st2 ) && st.st_ino == st2.st_ino && st.st_dev == st2.st_dev)
2494 if (create_link && !replace) set_error( STATUS_OBJECT_NAME_COLLISION );
2495 free( name );
2496 return;
2499 if (!replace)
2501 set_error( STATUS_OBJECT_NAME_COLLISION );
2502 goto failed;
2505 /* can't replace directories or special files */
2506 if (!S_ISREG( st.st_mode ))
2508 set_error( STATUS_ACCESS_DENIED );
2509 goto failed;
2512 /* can't replace an opened file */
2513 if ((inode = get_inode( st.st_dev, st.st_ino, -1 )))
2515 int is_empty = list_empty( &inode->open );
2516 release_object( inode );
2517 if (!is_empty)
2519 set_error( STATUS_ACCESS_DENIED );
2520 goto failed;
2524 /* link() expects that the target doesn't exist */
2525 /* rename() cannot replace files with directories */
2526 if (create_link || S_ISDIR( st2.st_mode ))
2528 if (unlink( name ))
2530 file_set_error();
2531 goto failed;
2536 if (create_link)
2538 if (link( fd->unix_name, name ))
2539 file_set_error();
2540 free( name );
2541 return;
2544 if (rename( fd->unix_name, name ))
2546 file_set_error();
2547 goto failed;
2550 if (is_file_executable( fd->unix_name ) != is_file_executable( name ) && !fstat( fd->unix_fd, &st ))
2552 if (is_file_executable( name ))
2553 /* set executable bit where read bit is set */
2554 st.st_mode |= (st.st_mode & 0444) >> 2;
2555 else
2556 st.st_mode &= ~0111;
2557 fchmod( fd->unix_fd, st.st_mode );
2560 free( fd->unix_name );
2561 fd->closed->unix_name = fd->unix_name = realpath( name, NULL );
2562 free( name );
2563 if (!fd->unix_name)
2564 set_error( STATUS_NO_MEMORY );
2565 return;
2567 failed:
2568 free( name );
2571 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
2573 *p_key = fd->comp_key;
2574 return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
2577 void fd_copy_completion( struct fd *src, struct fd *dst )
2579 assert( !dst->completion );
2580 dst->completion = fd_get_completion( src, &dst->comp_key );
2581 dst->comp_flags = src->comp_flags;
2584 /* flush a file buffers */
2585 DECL_HANDLER(flush)
2587 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, 0 );
2588 struct async *async;
2590 if (!fd) return;
2592 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2594 reply->event = async_handoff( async, fd->fd_ops->flush( fd, async ), NULL, 1 );
2595 release_object( async );
2597 release_object( fd );
2600 /* query file info */
2601 DECL_HANDLER(get_file_info)
2603 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2605 if (fd)
2607 fd->fd_ops->get_file_info( fd, req->handle, req->info_class );
2608 release_object( fd );
2612 /* query volume info */
2613 DECL_HANDLER(get_volume_info)
2615 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2617 if (fd)
2619 fd->fd_ops->get_volume_info( fd, req->info_class );
2620 release_object( fd );
2624 /* open a file object */
2625 DECL_HANDLER(open_file_object)
2627 struct unicode_str name = get_req_unicode_str();
2628 struct object *obj, *result, *root = NULL;
2630 if (req->rootdir && !(root = get_handle_obj( current->process, req->rootdir, 0, NULL ))) return;
2632 obj = open_named_object( root, NULL, &name, req->attributes );
2633 if (root) release_object( root );
2634 if (!obj) return;
2636 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
2638 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
2639 release_object( result );
2641 release_object( obj );
2644 /* get the Unix name from a file handle */
2645 DECL_HANDLER(get_handle_unix_name)
2647 struct fd *fd;
2649 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2651 if (fd->unix_name)
2653 data_size_t name_len = strlen( fd->unix_name );
2654 reply->name_len = name_len;
2655 if (name_len <= get_reply_max_size()) set_reply_data( fd->unix_name, name_len );
2656 else set_error( STATUS_BUFFER_OVERFLOW );
2658 else set_error( STATUS_OBJECT_TYPE_MISMATCH );
2659 release_object( fd );
2663 /* get a Unix fd to access a file */
2664 DECL_HANDLER(get_handle_fd)
2666 struct fd *fd;
2668 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2670 int unix_fd = get_unix_fd( fd );
2671 reply->cacheable = fd->cacheable;
2672 if (unix_fd != -1)
2674 reply->type = fd->fd_ops->get_fd_type( fd );
2675 reply->options = fd->options;
2676 reply->access = get_handle_access( current->process, req->handle );
2677 send_client_fd( current->process, unix_fd, req->handle );
2679 release_object( fd );
2683 /* perform a read on a file object */
2684 DECL_HANDLER(read)
2686 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_READ_DATA );
2687 struct async *async;
2689 if (!fd) return;
2691 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2693 reply->wait = async_handoff( async, fd->fd_ops->read( fd, async, req->pos ), NULL, 0 );
2694 reply->options = fd->options;
2695 release_object( async );
2697 release_object( fd );
2700 /* perform a write on a file object */
2701 DECL_HANDLER(write)
2703 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_WRITE_DATA );
2704 struct async *async;
2706 if (!fd) return;
2708 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2710 reply->wait = async_handoff( async, fd->fd_ops->write( fd, async, req->pos ), &reply->size, 0 );
2711 reply->options = fd->options;
2712 release_object( async );
2714 release_object( fd );
2717 /* perform an ioctl on a file */
2718 DECL_HANDLER(ioctl)
2720 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2721 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2722 struct async *async;
2724 if (!fd) return;
2726 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2728 reply->wait = async_handoff( async, fd->fd_ops->ioctl( fd, req->code, async ), NULL, 0 );
2729 reply->options = fd->options;
2730 release_object( async );
2732 release_object( fd );
2735 /* create / reschedule an async I/O */
2736 DECL_HANDLER(register_async)
2738 unsigned int access;
2739 struct async *async;
2740 struct fd *fd;
2742 switch(req->type)
2744 case ASYNC_TYPE_READ:
2745 access = FILE_READ_DATA;
2746 break;
2747 case ASYNC_TYPE_WRITE:
2748 access = FILE_WRITE_DATA;
2749 break;
2750 default:
2751 set_error( STATUS_INVALID_PARAMETER );
2752 return;
2755 if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2757 if (get_unix_fd( fd ) != -1 && (async = create_async( fd, current, &req->async, NULL )))
2759 fd->fd_ops->queue_async( fd, async, req->type, req->count );
2760 release_object( async );
2762 release_object( fd );
2766 /* attach completion object to a fd */
2767 DECL_HANDLER(set_completion_info)
2769 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2771 if (fd)
2773 if (is_fd_overlapped( fd ) && !fd->completion)
2775 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2776 fd->comp_key = req->ckey;
2778 else set_error( STATUS_INVALID_PARAMETER );
2779 release_object( fd );
2783 /* push new completion msg into a completion queue attached to the fd */
2784 DECL_HANDLER(add_fd_completion)
2786 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2787 if (fd)
2789 if (fd->completion && (req->async || !(fd->comp_flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS)))
2790 add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2791 release_object( fd );
2795 /* set fd completion information */
2796 DECL_HANDLER(set_fd_completion_mode)
2798 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2799 if (fd)
2801 if (is_fd_overlapped( fd ))
2803 if (req->flags & FILE_SKIP_SET_EVENT_ON_HANDLE)
2804 set_fd_signaled( fd, 0 );
2805 /* removing flags is not allowed */
2806 fd->comp_flags |= req->flags & ( FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
2807 | FILE_SKIP_SET_EVENT_ON_HANDLE
2808 | FILE_SKIP_SET_USER_EVENT_ON_FAST_IO );
2810 else
2811 set_error( STATUS_INVALID_PARAMETER );
2812 release_object( fd );
2816 /* set fd disposition information */
2817 DECL_HANDLER(set_fd_disp_info)
2819 struct fd *fd = get_handle_fd_obj( current->process, req->handle, DELETE );
2820 if (fd)
2822 set_fd_disposition( fd, req->unlink );
2823 release_object( fd );
2827 /* set fd name information */
2828 DECL_HANDLER(set_fd_name_info)
2830 struct fd *fd, *root_fd = NULL;
2832 if (req->rootdir)
2834 struct dir *root;
2836 if (!(root = get_dir_obj( current->process, req->rootdir, 0 ))) return;
2837 root_fd = get_obj_fd( (struct object *)root );
2838 release_object( root );
2839 if (!root_fd) return;
2842 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2844 set_fd_name( fd, root_fd, get_req_data(), get_req_data_size(), req->link, req->replace );
2845 release_object( fd );
2847 if (root_fd) release_object( root_fd );