user32/tests: Test pending redraw state with owner-drawn list box.
[wine.git] / server / fd.c
blobb953da2ab851f101f77a3ee9fbbc5f5017bc02b5
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 WCHAR *nt_name; /* NT file name */
189 data_size_t nt_namelen; /* length of NT file name */
190 int unix_fd; /* unix file descriptor */
191 unsigned int no_fd_status;/* status to return when unix_fd is -1 */
192 unsigned int cacheable :1;/* can the fd be cached on the client side? */
193 unsigned int signaled :1; /* is the fd signaled? */
194 unsigned int fs_locks :1; /* can we use filesystem locks for this fd? */
195 int poll_index; /* index of fd in poll array */
196 struct async_queue read_q; /* async readers of this fd */
197 struct async_queue write_q; /* async writers of this fd */
198 struct async_queue wait_q; /* other async waiters of this fd */
199 struct completion *completion; /* completion object attached to this fd */
200 apc_param_t comp_key; /* completion key to set in completion events */
201 unsigned int comp_flags; /* completion flags */
204 static void fd_dump( struct object *obj, int verbose );
205 static void fd_destroy( struct object *obj );
207 static const struct object_ops fd_ops =
209 sizeof(struct fd), /* size */
210 &no_type, /* type */
211 fd_dump, /* dump */
212 no_add_queue, /* add_queue */
213 NULL, /* remove_queue */
214 NULL, /* signaled */
215 NULL, /* satisfied */
216 no_signal, /* signal */
217 no_get_fd, /* get_fd */
218 default_map_access, /* map_access */
219 default_get_sd, /* get_sd */
220 default_set_sd, /* set_sd */
221 no_get_full_name, /* get_full_name */
222 no_lookup_name, /* lookup_name */
223 no_link_name, /* link_name */
224 NULL, /* unlink_name */
225 no_open_file, /* open_file */
226 no_kernel_obj_list, /* get_kernel_obj_list */
227 no_close_handle, /* close_handle */
228 fd_destroy /* destroy */
231 /* device object */
233 #define DEVICE_HASH_SIZE 7
234 #define INODE_HASH_SIZE 17
236 struct device
238 struct object obj; /* object header */
239 struct list entry; /* entry in device hash list */
240 dev_t dev; /* device number */
241 int removable; /* removable device? (or -1 if unknown) */
242 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
245 static void device_dump( struct object *obj, int verbose );
246 static void device_destroy( struct object *obj );
248 static const struct object_ops device_ops =
250 sizeof(struct device), /* size */
251 &no_type, /* type */
252 device_dump, /* dump */
253 no_add_queue, /* add_queue */
254 NULL, /* remove_queue */
255 NULL, /* signaled */
256 NULL, /* satisfied */
257 no_signal, /* signal */
258 no_get_fd, /* get_fd */
259 default_map_access, /* map_access */
260 default_get_sd, /* get_sd */
261 default_set_sd, /* set_sd */
262 no_get_full_name, /* get_full_name */
263 no_lookup_name, /* lookup_name */
264 no_link_name, /* link_name */
265 NULL, /* unlink_name */
266 no_open_file, /* open_file */
267 no_kernel_obj_list, /* get_kernel_obj_list */
268 no_close_handle, /* close_handle */
269 device_destroy /* destroy */
272 /* inode object */
274 struct inode
276 struct object obj; /* object header */
277 struct list entry; /* inode hash list entry */
278 struct device *device; /* device containing this inode */
279 ino_t ino; /* inode number */
280 struct list open; /* list of open file descriptors */
281 struct list locks; /* list of file locks */
282 struct list closed; /* list of file descriptors to close at destroy time */
285 static void inode_dump( struct object *obj, int verbose );
286 static void inode_destroy( struct object *obj );
288 static const struct object_ops inode_ops =
290 sizeof(struct inode), /* size */
291 &no_type, /* type */
292 inode_dump, /* dump */
293 no_add_queue, /* add_queue */
294 NULL, /* remove_queue */
295 NULL, /* signaled */
296 NULL, /* satisfied */
297 no_signal, /* signal */
298 no_get_fd, /* get_fd */
299 default_map_access, /* map_access */
300 default_get_sd, /* get_sd */
301 default_set_sd, /* set_sd */
302 no_get_full_name, /* get_full_name */
303 no_lookup_name, /* lookup_name */
304 no_link_name, /* link_name */
305 NULL, /* unlink_name */
306 no_open_file, /* open_file */
307 no_kernel_obj_list, /* get_kernel_obj_list */
308 no_close_handle, /* close_handle */
309 inode_destroy /* destroy */
312 /* file lock object */
314 struct file_lock
316 struct object obj; /* object header */
317 struct fd *fd; /* fd owning this lock */
318 struct list fd_entry; /* entry in list of locks on a given fd */
319 struct list inode_entry; /* entry in inode list of locks */
320 int shared; /* shared lock? */
321 file_pos_t start; /* locked region is interval [start;end) */
322 file_pos_t end;
323 struct process *process; /* process owning this lock */
324 struct list proc_entry; /* entry in list of locks owned by the process */
327 static void file_lock_dump( struct object *obj, int verbose );
328 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry );
330 static const struct object_ops file_lock_ops =
332 sizeof(struct file_lock), /* size */
333 &no_type, /* type */
334 file_lock_dump, /* dump */
335 add_queue, /* add_queue */
336 remove_queue, /* remove_queue */
337 file_lock_signaled, /* signaled */
338 no_satisfied, /* satisfied */
339 no_signal, /* signal */
340 no_get_fd, /* get_fd */
341 default_map_access, /* map_access */
342 default_get_sd, /* get_sd */
343 default_set_sd, /* set_sd */
344 no_get_full_name, /* get_full_name */
345 no_lookup_name, /* lookup_name */
346 no_link_name, /* link_name */
347 NULL, /* unlink_name */
348 no_open_file, /* open_file */
349 no_kernel_obj_list, /* get_kernel_obj_list */
350 no_close_handle, /* close_handle */
351 no_destroy /* destroy */
355 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
356 #define FILE_POS_T_MAX (~(file_pos_t)0)
358 static file_pos_t max_unix_offset = OFF_T_MAX;
360 #define DUMP_LONG_LONG(val) do { \
361 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
362 fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
363 else \
364 fprintf( stderr, "%lx", (unsigned long)(val) ); \
365 } while (0)
369 /****************************************************************/
370 /* timeouts support */
372 struct timeout_user
374 struct list entry; /* entry in sorted timeout list */
375 abstime_t when; /* timeout expiry */
376 timeout_callback callback; /* callback function */
377 void *private; /* callback private data */
380 static struct list abs_timeout_list = LIST_INIT(abs_timeout_list); /* sorted absolute timeouts list */
381 static struct list rel_timeout_list = LIST_INIT(rel_timeout_list); /* sorted relative timeouts list */
382 timeout_t current_time;
383 timeout_t monotonic_time;
385 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
386 static const int user_shared_data_timeout = 16;
388 static void set_user_shared_data_time(void)
390 timeout_t tick_count = monotonic_time / 10000;
392 /* on X86 there should be total store order guarantees, so volatile is enough
393 * to ensure the stores aren't reordered by the compiler, and then they will
394 * always be seen in-order from other CPUs. On other archs, we need atomic
395 * intrinsics to guarantee that. */
396 #if defined(__i386__) || defined(__x86_64__)
397 user_shared_data->SystemTime.High2Time = current_time >> 32;
398 user_shared_data->SystemTime.LowPart = current_time;
399 user_shared_data->SystemTime.High1Time = current_time >> 32;
401 user_shared_data->InterruptTime.High2Time = monotonic_time >> 32;
402 user_shared_data->InterruptTime.LowPart = monotonic_time;
403 user_shared_data->InterruptTime.High1Time = monotonic_time >> 32;
405 user_shared_data->TickCount.High2Time = tick_count >> 32;
406 user_shared_data->TickCount.LowPart = tick_count;
407 user_shared_data->TickCount.High1Time = tick_count >> 32;
408 *(volatile ULONG *)&user_shared_data->TickCountLowDeprecated = tick_count;
409 #else
410 __atomic_store_n(&user_shared_data->SystemTime.High2Time, current_time >> 32, __ATOMIC_SEQ_CST);
411 __atomic_store_n(&user_shared_data->SystemTime.LowPart, current_time, __ATOMIC_SEQ_CST);
412 __atomic_store_n(&user_shared_data->SystemTime.High1Time, current_time >> 32, __ATOMIC_SEQ_CST);
414 __atomic_store_n(&user_shared_data->InterruptTime.High2Time, monotonic_time >> 32, __ATOMIC_SEQ_CST);
415 __atomic_store_n(&user_shared_data->InterruptTime.LowPart, monotonic_time, __ATOMIC_SEQ_CST);
416 __atomic_store_n(&user_shared_data->InterruptTime.High1Time, monotonic_time >> 32, __ATOMIC_SEQ_CST);
418 __atomic_store_n(&user_shared_data->TickCount.High2Time, tick_count >> 32, __ATOMIC_SEQ_CST);
419 __atomic_store_n(&user_shared_data->TickCount.LowPart, tick_count, __ATOMIC_SEQ_CST);
420 __atomic_store_n(&user_shared_data->TickCount.High1Time, tick_count >> 32, __ATOMIC_SEQ_CST);
421 __atomic_store_n(&user_shared_data->TickCountLowDeprecated, tick_count, __ATOMIC_SEQ_CST);
422 #endif
425 void set_current_time(void)
427 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
428 struct timeval now;
429 gettimeofday( &now, NULL );
430 current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
431 monotonic_time = monotonic_counter();
432 if (user_shared_data) set_user_shared_data_time();
435 /* add a timeout user */
436 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
438 struct timeout_user *user;
439 struct list *ptr;
441 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
442 user->when = timeout_to_abstime( when );
443 user->callback = func;
444 user->private = private;
446 /* Now insert it in the linked list */
448 if (user->when > 0)
450 LIST_FOR_EACH( ptr, &abs_timeout_list )
452 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
453 if (timeout->when >= user->when) break;
456 else
458 LIST_FOR_EACH( ptr, &rel_timeout_list )
460 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
461 if (timeout->when <= user->when) break;
464 list_add_before( ptr, &user->entry );
465 return user;
468 /* remove a timeout user */
469 void remove_timeout_user( struct timeout_user *user )
471 list_remove( &user->entry );
472 free( user );
475 /* return a text description of a timeout for debugging purposes */
476 const char *get_timeout_str( timeout_t timeout )
478 static char buffer[64];
479 long secs, nsecs;
481 if (!timeout) return "0";
482 if (timeout == TIMEOUT_INFINITE) return "infinite";
484 if (timeout < 0) /* relative */
486 secs = -timeout / TICKS_PER_SEC;
487 nsecs = -timeout % TICKS_PER_SEC;
488 sprintf( buffer, "+%ld.%07ld", secs, nsecs );
490 else /* absolute */
492 secs = (timeout - current_time) / TICKS_PER_SEC;
493 nsecs = (timeout - current_time) % TICKS_PER_SEC;
494 if (nsecs < 0)
496 nsecs += TICKS_PER_SEC;
497 secs--;
499 if (secs >= 0)
500 sprintf( buffer, "%x%08x (+%ld.%07ld)",
501 (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
502 else
503 sprintf( buffer, "%x%08x (-%ld.%07ld)",
504 (unsigned int)(timeout >> 32), (unsigned int)timeout,
505 -(secs + 1), TICKS_PER_SEC - nsecs );
507 return buffer;
511 /****************************************************************/
512 /* poll support */
514 static struct fd **poll_users; /* users array */
515 static struct pollfd *pollfd; /* poll fd array */
516 static int nb_users; /* count of array entries actually in use */
517 static int active_users; /* current number of active users */
518 static int allocated_users; /* count of allocated entries in the array */
519 static struct fd **freelist; /* list of free entries in the array */
521 static int get_next_timeout(void);
523 static inline void fd_poll_event( struct fd *fd, int event )
525 fd->fd_ops->poll_event( fd, event );
528 #ifdef USE_EPOLL
530 static int epoll_fd = -1;
532 static inline void init_epoll(void)
534 epoll_fd = epoll_create( 128 );
537 /* set the events that epoll waits for on this fd; helper for set_fd_events */
538 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
540 struct epoll_event ev;
541 int ctl;
543 if (epoll_fd == -1) return;
545 if (events == -1) /* stop waiting on this fd completely */
547 if (pollfd[user].fd == -1) return; /* already removed */
548 ctl = EPOLL_CTL_DEL;
550 else if (pollfd[user].fd == -1)
552 ctl = EPOLL_CTL_ADD;
554 else
556 if (pollfd[user].events == events) return; /* nothing to do */
557 ctl = EPOLL_CTL_MOD;
560 ev.events = events;
561 memset(&ev.data, 0, sizeof(ev.data));
562 ev.data.u32 = user;
564 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
566 if (errno == ENOMEM) /* not enough memory, give up on epoll */
568 close( epoll_fd );
569 epoll_fd = -1;
571 else perror( "epoll_ctl" ); /* should not happen */
575 static inline void remove_epoll_user( struct fd *fd, int user )
577 if (epoll_fd == -1) return;
579 if (pollfd[user].fd != -1)
581 struct epoll_event dummy;
582 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
586 static inline void main_loop_epoll(void)
588 int i, ret, timeout;
589 struct epoll_event events[128];
591 assert( POLLIN == EPOLLIN );
592 assert( POLLOUT == EPOLLOUT );
593 assert( POLLERR == EPOLLERR );
594 assert( POLLHUP == EPOLLHUP );
596 if (epoll_fd == -1) return;
598 while (active_users)
600 timeout = get_next_timeout();
602 if (!active_users) break; /* last user removed by a timeout */
603 if (epoll_fd == -1) break; /* an error occurred with epoll */
605 ret = epoll_wait( epoll_fd, events, ARRAY_SIZE( events ), timeout );
606 set_current_time();
608 /* put the events into the pollfd array first, like poll does */
609 for (i = 0; i < ret; i++)
611 int user = events[i].data.u32;
612 pollfd[user].revents = events[i].events;
615 /* read events from the pollfd array, as set_fd_events may modify them */
616 for (i = 0; i < ret; i++)
618 int user = events[i].data.u32;
619 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
624 #elif defined(HAVE_KQUEUE)
626 static int kqueue_fd = -1;
628 static inline void init_epoll(void)
630 #ifdef __APPLE__ /* kqueue support is broken in Mac OS < 10.5 */
631 int mib[2];
632 char release[32];
633 size_t len = sizeof(release);
635 mib[0] = CTL_KERN;
636 mib[1] = KERN_OSRELEASE;
637 if (sysctl( mib, 2, release, &len, NULL, 0 ) == -1) return;
638 if (atoi(release) < 9) return;
639 #endif
640 kqueue_fd = kqueue();
643 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
645 struct kevent ev[2];
647 if (kqueue_fd == -1) return;
649 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)(long)user );
650 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)(long)user );
652 if (events == -1) /* stop waiting on this fd completely */
654 if (pollfd[user].fd == -1) return; /* already removed */
655 ev[0].flags |= EV_DELETE;
656 ev[1].flags |= EV_DELETE;
658 else if (pollfd[user].fd == -1)
660 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
661 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
663 else
665 if (pollfd[user].events == events) return; /* nothing to do */
666 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
667 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
670 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
672 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
674 close( kqueue_fd );
675 kqueue_fd = -1;
677 else perror( "kevent" ); /* should not happen */
681 static inline void remove_epoll_user( struct fd *fd, int user )
683 if (kqueue_fd == -1) return;
685 if (pollfd[user].fd != -1)
687 struct kevent ev[2];
689 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
690 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
691 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
695 static inline void main_loop_epoll(void)
697 int i, ret, timeout;
698 struct kevent events[128];
700 if (kqueue_fd == -1) return;
702 while (active_users)
704 timeout = get_next_timeout();
706 if (!active_users) break; /* last user removed by a timeout */
707 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
709 if (timeout != -1)
711 struct timespec ts;
713 ts.tv_sec = timeout / 1000;
714 ts.tv_nsec = (timeout % 1000) * 1000000;
715 ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), &ts );
717 else ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), NULL );
719 set_current_time();
721 /* put the events into the pollfd array first, like poll does */
722 for (i = 0; i < ret; i++)
724 long user = (long)events[i].udata;
725 pollfd[user].revents = 0;
727 for (i = 0; i < ret; i++)
729 long user = (long)events[i].udata;
730 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
731 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
732 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
733 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
736 /* read events from the pollfd array, as set_fd_events may modify them */
737 for (i = 0; i < ret; i++)
739 long user = (long)events[i].udata;
740 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
741 pollfd[user].revents = 0;
746 #elif defined(USE_EVENT_PORTS)
748 static int port_fd = -1;
750 static inline void init_epoll(void)
752 port_fd = port_create();
755 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
757 int ret;
759 if (port_fd == -1) return;
761 if (events == -1) /* stop waiting on this fd completely */
763 if (pollfd[user].fd == -1) return; /* already removed */
764 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
766 else if (pollfd[user].fd == -1)
768 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
770 else
772 if (pollfd[user].events == events) return; /* nothing to do */
773 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
776 if (ret == -1)
778 if (errno == ENOMEM) /* not enough memory, give up on port_associate */
780 close( port_fd );
781 port_fd = -1;
783 else perror( "port_associate" ); /* should not happen */
787 static inline void remove_epoll_user( struct fd *fd, int user )
789 if (port_fd == -1) return;
791 if (pollfd[user].fd != -1)
793 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
797 static inline void main_loop_epoll(void)
799 int i, nget, ret, timeout;
800 port_event_t events[128];
802 if (port_fd == -1) return;
804 while (active_users)
806 timeout = get_next_timeout();
807 nget = 1;
809 if (!active_users) break; /* last user removed by a timeout */
810 if (port_fd == -1) break; /* an error occurred with event completion */
812 if (timeout != -1)
814 struct timespec ts;
816 ts.tv_sec = timeout / 1000;
817 ts.tv_nsec = (timeout % 1000) * 1000000;
818 ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, &ts );
820 else ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, NULL );
822 if (ret == -1) break; /* an error occurred with event completion */
824 set_current_time();
826 /* put the events into the pollfd array first, like poll does */
827 for (i = 0; i < nget; i++)
829 long user = (long)events[i].portev_user;
830 pollfd[user].revents = events[i].portev_events;
833 /* read events from the pollfd array, as set_fd_events may modify them */
834 for (i = 0; i < nget; i++)
836 long user = (long)events[i].portev_user;
837 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
838 /* if we are still interested, reassociate the fd */
839 if (pollfd[user].fd != -1) {
840 port_associate( port_fd, PORT_SOURCE_FD, pollfd[user].fd, pollfd[user].events, (void *)user );
846 #else /* HAVE_KQUEUE */
848 static inline void init_epoll(void) { }
849 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
850 static inline void remove_epoll_user( struct fd *fd, int user ) { }
851 static inline void main_loop_epoll(void) { }
853 #endif /* USE_EPOLL */
856 /* add a user in the poll array and return its index, or -1 on failure */
857 static int add_poll_user( struct fd *fd )
859 int ret;
860 if (freelist)
862 ret = freelist - poll_users;
863 freelist = (struct fd **)poll_users[ret];
865 else
867 if (nb_users == allocated_users)
869 struct fd **newusers;
870 struct pollfd *newpoll;
871 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
872 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
873 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
875 if (allocated_users)
876 poll_users = newusers;
877 else
878 free( newusers );
879 return -1;
881 poll_users = newusers;
882 pollfd = newpoll;
883 if (!allocated_users) init_epoll();
884 allocated_users = new_count;
886 ret = nb_users++;
888 pollfd[ret].fd = -1;
889 pollfd[ret].events = 0;
890 pollfd[ret].revents = 0;
891 poll_users[ret] = fd;
892 active_users++;
893 return ret;
896 /* remove a user from the poll list */
897 static void remove_poll_user( struct fd *fd, int user )
899 assert( user >= 0 );
900 assert( poll_users[user] == fd );
902 remove_epoll_user( fd, user );
903 pollfd[user].fd = -1;
904 pollfd[user].events = 0;
905 pollfd[user].revents = 0;
906 poll_users[user] = (struct fd *)freelist;
907 freelist = &poll_users[user];
908 active_users--;
911 /* process pending timeouts and return the time until the next timeout, in milliseconds */
912 static int get_next_timeout(void)
914 int ret = user_shared_data ? user_shared_data_timeout : -1;
916 if (!list_empty( &abs_timeout_list ) || !list_empty( &rel_timeout_list ))
918 struct list expired_list, *ptr;
920 /* first remove all expired timers from the list */
922 list_init( &expired_list );
923 while ((ptr = list_head( &abs_timeout_list )) != NULL)
925 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
927 if (timeout->when <= current_time)
929 list_remove( &timeout->entry );
930 list_add_tail( &expired_list, &timeout->entry );
932 else break;
934 while ((ptr = list_head( &rel_timeout_list )) != NULL)
936 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
938 if (-timeout->when <= monotonic_time)
940 list_remove( &timeout->entry );
941 list_add_tail( &expired_list, &timeout->entry );
943 else break;
946 /* now call the callback for all the removed timers */
948 while ((ptr = list_head( &expired_list )) != NULL)
950 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
951 list_remove( &timeout->entry );
952 timeout->callback( timeout->private );
953 free( timeout );
956 if ((ptr = list_head( &abs_timeout_list )) != NULL)
958 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
959 timeout_t diff = (timeout->when - current_time + 9999) / 10000;
960 if (diff > INT_MAX) diff = INT_MAX;
961 else if (diff < 0) diff = 0;
962 if (ret == -1 || diff < ret) ret = diff;
965 if ((ptr = list_head( &rel_timeout_list )) != NULL)
967 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
968 timeout_t diff = (-timeout->when - monotonic_time + 9999) / 10000;
969 if (diff > INT_MAX) diff = INT_MAX;
970 else if (diff < 0) diff = 0;
971 if (ret == -1 || diff < ret) ret = diff;
974 return ret;
977 /* server main poll() loop */
978 void main_loop(void)
980 int i, ret, timeout;
982 set_current_time();
983 server_start_time = current_time;
985 main_loop_epoll();
986 /* fall through to normal poll loop */
988 while (active_users)
990 timeout = get_next_timeout();
992 if (!active_users) break; /* last user removed by a timeout */
994 ret = poll( pollfd, nb_users, timeout );
995 set_current_time();
997 if (ret > 0)
999 for (i = 0; i < nb_users; i++)
1001 if (pollfd[i].revents)
1003 fd_poll_event( poll_users[i], pollfd[i].revents );
1004 if (!--ret) break;
1012 /****************************************************************/
1013 /* device functions */
1015 static struct list device_hash[DEVICE_HASH_SIZE];
1017 static int is_device_removable( dev_t dev, int unix_fd )
1019 #if defined(linux) && defined(HAVE_FSTATFS)
1020 struct statfs stfs;
1022 /* check for floppy disk */
1023 if (major(dev) == FLOPPY_MAJOR) return 1;
1025 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
1026 return (stfs.f_type == 0x9660 || /* iso9660 */
1027 stfs.f_type == 0x9fa1 || /* supermount */
1028 stfs.f_type == 0x15013346); /* udf */
1029 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
1030 struct statfs stfs;
1032 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
1033 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
1034 #elif defined(__NetBSD__)
1035 struct statvfs stfs;
1037 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
1038 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
1039 #elif defined(sun)
1040 # include <sys/dkio.h>
1041 # include <sys/vtoc.h>
1042 struct dk_cinfo dkinf;
1043 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
1044 return (dkinf.dki_ctype == DKC_CDROM ||
1045 dkinf.dki_ctype == DKC_NCRFLOPPY ||
1046 dkinf.dki_ctype == DKC_SMSFLOPPY ||
1047 dkinf.dki_ctype == DKC_INTEL82072 ||
1048 dkinf.dki_ctype == DKC_INTEL82077);
1049 #else
1050 return 0;
1051 #endif
1054 /* retrieve the device object for a given fd, creating it if needed */
1055 static struct device *get_device( dev_t dev, int unix_fd )
1057 struct device *device;
1058 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
1060 if (device_hash[hash].next)
1062 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
1063 if (device->dev == dev) return (struct device *)grab_object( device );
1065 else list_init( &device_hash[hash] );
1067 /* not found, create it */
1069 if (unix_fd == -1) return NULL;
1070 if ((device = alloc_object( &device_ops )))
1072 device->dev = dev;
1073 device->removable = is_device_removable( dev, unix_fd );
1074 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
1075 list_add_head( &device_hash[hash], &device->entry );
1077 return device;
1080 static void device_dump( struct object *obj, int verbose )
1082 struct device *device = (struct device *)obj;
1083 fprintf( stderr, "Device dev=" );
1084 DUMP_LONG_LONG( device->dev );
1085 fprintf( stderr, "\n" );
1088 static void device_destroy( struct object *obj )
1090 struct device *device = (struct device *)obj;
1091 unsigned int i;
1093 for (i = 0; i < INODE_HASH_SIZE; i++)
1094 assert( list_empty(&device->inode_hash[i]) );
1096 list_remove( &device->entry ); /* remove it from the hash table */
1100 /****************************************************************/
1101 /* inode functions */
1103 /* close all pending file descriptors in the closed list */
1104 static void inode_close_pending( struct inode *inode, int keep_unlinks )
1106 struct list *ptr = list_head( &inode->closed );
1108 while (ptr)
1110 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1111 struct list *next = list_next( &inode->closed, ptr );
1113 if (fd->unix_fd != -1)
1115 close( fd->unix_fd );
1116 fd->unix_fd = -1;
1118 if (!keep_unlinks || !fd->unlink) /* get rid of it unless there's an unlink pending on that file */
1120 list_remove( ptr );
1121 free( fd->unix_name );
1122 free( fd );
1124 ptr = next;
1128 static void inode_dump( struct object *obj, int verbose )
1130 struct inode *inode = (struct inode *)obj;
1131 fprintf( stderr, "Inode device=%p ino=", inode->device );
1132 DUMP_LONG_LONG( inode->ino );
1133 fprintf( stderr, "\n" );
1136 static void inode_destroy( struct object *obj )
1138 struct inode *inode = (struct inode *)obj;
1139 struct list *ptr;
1141 assert( list_empty(&inode->open) );
1142 assert( list_empty(&inode->locks) );
1144 list_remove( &inode->entry );
1146 while ((ptr = list_head( &inode->closed )))
1148 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1149 list_remove( ptr );
1150 if (fd->unix_fd != -1) close( fd->unix_fd );
1151 if (fd->unlink)
1153 /* make sure it is still the same file */
1154 struct stat st;
1155 if (!stat( fd->unix_name, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
1157 if (S_ISDIR(st.st_mode)) rmdir( fd->unix_name );
1158 else unlink( fd->unix_name );
1161 free( fd->unix_name );
1162 free( fd );
1164 release_object( inode->device );
1167 /* retrieve the inode object for a given fd, creating it if needed */
1168 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
1170 struct device *device;
1171 struct inode *inode;
1172 unsigned int hash = ino % INODE_HASH_SIZE;
1174 if (!(device = get_device( dev, unix_fd ))) return NULL;
1176 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
1178 if (inode->ino == ino)
1180 release_object( device );
1181 return (struct inode *)grab_object( inode );
1185 /* not found, create it */
1186 if ((inode = alloc_object( &inode_ops )))
1188 inode->device = device;
1189 inode->ino = ino;
1190 list_init( &inode->open );
1191 list_init( &inode->locks );
1192 list_init( &inode->closed );
1193 list_add_head( &device->inode_hash[hash], &inode->entry );
1195 else release_object( device );
1197 return inode;
1200 /* add fd to the inode list of file descriptors to close */
1201 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1203 if (!list_empty( &inode->locks ))
1205 list_add_head( &inode->closed, &fd->entry );
1207 else if (fd->unlink) /* close the fd but keep the structure around for unlink */
1209 if (fd->unix_fd != -1) close( fd->unix_fd );
1210 fd->unix_fd = -1;
1211 list_add_head( &inode->closed, &fd->entry );
1213 else /* no locks on this inode and no unlink, get rid of the fd */
1215 if (fd->unix_fd != -1) close( fd->unix_fd );
1216 free( fd->unix_name );
1217 free( fd );
1222 /****************************************************************/
1223 /* file lock functions */
1225 static void file_lock_dump( struct object *obj, int verbose )
1227 struct file_lock *lock = (struct file_lock *)obj;
1228 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1229 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1230 DUMP_LONG_LONG( lock->start );
1231 fprintf( stderr, " end=" );
1232 DUMP_LONG_LONG( lock->end );
1233 fprintf( stderr, "\n" );
1236 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry )
1238 struct file_lock *lock = (struct file_lock *)obj;
1239 /* lock is signaled if it has lost its owner */
1240 return !lock->process;
1243 /* set (or remove) a Unix lock if possible for the given range */
1244 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1246 struct flock fl;
1248 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1249 for (;;)
1251 if (start == end) return 1; /* can't set zero-byte lock */
1252 if (start > max_unix_offset) return 1; /* ignore it */
1253 fl.l_type = type;
1254 fl.l_whence = SEEK_SET;
1255 fl.l_start = start;
1256 if (!end || end > max_unix_offset) fl.l_len = 0;
1257 else fl.l_len = end - start;
1258 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1260 switch(errno)
1262 case EACCES:
1263 /* check whether locks work at all on this file system */
1264 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1266 set_error( STATUS_FILE_LOCK_CONFLICT );
1267 return 0;
1269 /* fall through */
1270 case EIO:
1271 case ENOLCK:
1272 case ENOTSUP:
1273 /* no locking on this fs, just ignore it */
1274 fd->fs_locks = 0;
1275 return 1;
1276 case EAGAIN:
1277 set_error( STATUS_FILE_LOCK_CONFLICT );
1278 return 0;
1279 case EBADF:
1280 /* this can happen if we try to set a write lock on a read-only file */
1281 /* try to at least grab a read lock */
1282 if (fl.l_type == F_WRLCK)
1284 type = F_RDLCK;
1285 break; /* retry */
1287 set_error( STATUS_ACCESS_DENIED );
1288 return 0;
1289 #ifdef EOVERFLOW
1290 case EOVERFLOW:
1291 #endif
1292 case EINVAL:
1293 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1294 /* in that case we shrink the limit and retry */
1295 if (max_unix_offset > INT_MAX)
1297 max_unix_offset = INT_MAX;
1298 break; /* retry */
1300 /* fall through */
1301 default:
1302 file_set_error();
1303 return 0;
1308 /* check if interval [start;end) overlaps the lock */
1309 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1311 if (lock->end && start >= lock->end) return 0;
1312 if (end && lock->start >= end) return 0;
1313 return 1;
1316 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1317 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1319 struct hole
1321 struct hole *next;
1322 struct hole *prev;
1323 file_pos_t start;
1324 file_pos_t end;
1325 } *first, *cur, *next, *buffer;
1327 struct list *ptr;
1328 int count = 0;
1330 if (!fd->inode) return;
1331 if (!fd->fs_locks) return;
1332 if (start == end || start > max_unix_offset) return;
1333 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1335 /* count the number of locks overlapping the specified area */
1337 LIST_FOR_EACH( ptr, &fd->inode->locks )
1339 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1340 if (lock->start == lock->end) continue;
1341 if (lock_overlaps( lock, start, end )) count++;
1344 if (!count) /* no locks at all, we can unlock everything */
1346 set_unix_lock( fd, start, end, F_UNLCK );
1347 return;
1350 /* allocate space for the list of holes */
1351 /* max. number of holes is number of locks + 1 */
1353 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1354 first = buffer;
1355 first->next = NULL;
1356 first->prev = NULL;
1357 first->start = start;
1358 first->end = end;
1359 next = first + 1;
1361 /* build a sorted list of unlocked holes in the specified area */
1363 LIST_FOR_EACH( ptr, &fd->inode->locks )
1365 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1366 if (lock->start == lock->end) continue;
1367 if (!lock_overlaps( lock, start, end )) continue;
1369 /* go through all the holes touched by this lock */
1370 for (cur = first; cur; cur = cur->next)
1372 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1373 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1375 /* now we know that lock is overlapping hole */
1377 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1379 cur->start = lock->end;
1380 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1381 /* now hole is empty, remove it */
1382 if (cur->next) cur->next->prev = cur->prev;
1383 if (cur->prev) cur->prev->next = cur->next;
1384 else if (!(first = cur->next)) goto done; /* no more holes at all */
1386 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1388 cur->end = lock->start;
1389 assert( cur->start < cur->end );
1391 else /* lock is in the middle of hole, split hole in two */
1393 next->prev = cur;
1394 next->next = cur->next;
1395 cur->next = next;
1396 next->start = lock->end;
1397 next->end = cur->end;
1398 cur->end = lock->start;
1399 assert( next->start < next->end );
1400 assert( cur->end < next->start );
1401 next++;
1402 break; /* done with this lock */
1407 /* clear Unix locks for all the holes */
1409 for (cur = first; cur; cur = cur->next)
1410 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1412 done:
1413 free( buffer );
1416 /* create a new lock on a fd */
1417 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1419 struct file_lock *lock;
1421 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1422 lock->shared = shared;
1423 lock->start = start;
1424 lock->end = end;
1425 lock->fd = fd;
1426 lock->process = current->process;
1428 /* now try to set a Unix lock */
1429 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1431 release_object( lock );
1432 return NULL;
1434 list_add_tail( &fd->locks, &lock->fd_entry );
1435 list_add_tail( &fd->inode->locks, &lock->inode_entry );
1436 list_add_tail( &lock->process->locks, &lock->proc_entry );
1437 return lock;
1440 /* remove an existing lock */
1441 static void remove_lock( struct file_lock *lock, int remove_unix )
1443 struct inode *inode = lock->fd->inode;
1445 list_remove( &lock->fd_entry );
1446 list_remove( &lock->inode_entry );
1447 list_remove( &lock->proc_entry );
1448 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1449 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1450 lock->process = NULL;
1451 wake_up( &lock->obj, 0 );
1452 release_object( lock );
1455 /* remove all locks owned by a given process */
1456 void remove_process_locks( struct process *process )
1458 struct list *ptr;
1460 while ((ptr = list_head( &process->locks )))
1462 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1463 remove_lock( lock, 1 ); /* this removes it from the list */
1467 /* remove all locks on a given fd */
1468 static void remove_fd_locks( struct fd *fd )
1470 file_pos_t start = FILE_POS_T_MAX, end = 0;
1471 struct list *ptr;
1473 while ((ptr = list_head( &fd->locks )))
1475 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1476 if (lock->start < start) start = lock->start;
1477 if (!lock->end || lock->end > end) end = lock->end - 1;
1478 remove_lock( lock, 0 );
1480 if (start < end) remove_unix_locks( fd, start, end + 1 );
1483 /* add a lock on an fd */
1484 /* returns handle to wait on */
1485 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1487 struct list *ptr;
1488 file_pos_t end = start + count;
1490 if (!fd->inode) /* not a regular file */
1492 set_error( STATUS_INVALID_DEVICE_REQUEST );
1493 return 0;
1496 /* don't allow wrapping locks */
1497 if (end && end < start)
1499 set_error( STATUS_INVALID_PARAMETER );
1500 return 0;
1503 /* check if another lock on that file overlaps the area */
1504 LIST_FOR_EACH( ptr, &fd->inode->locks )
1506 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1507 if (!lock_overlaps( lock, start, end )) continue;
1508 if (shared && (lock->shared || lock->fd == fd)) continue;
1509 /* found one */
1510 if (!wait)
1512 set_error( STATUS_FILE_LOCK_CONFLICT );
1513 return 0;
1515 set_error( STATUS_PENDING );
1516 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1519 /* not found, add it */
1520 if (add_lock( fd, shared, start, end )) return 0;
1521 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1523 /* Unix lock conflict -> tell client to wait and retry */
1524 if (wait) set_error( STATUS_PENDING );
1526 return 0;
1529 /* remove a lock on an fd */
1530 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1532 struct list *ptr;
1533 file_pos_t end = start + count;
1535 /* find an existing lock with the exact same parameters */
1536 LIST_FOR_EACH( ptr, &fd->locks )
1538 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1539 if ((lock->start == start) && (lock->end == end))
1541 remove_lock( lock, 1 );
1542 return;
1545 set_error( STATUS_FILE_LOCK_CONFLICT );
1549 /****************************************************************/
1550 /* file descriptor functions */
1552 static void fd_dump( struct object *obj, int verbose )
1554 struct fd *fd = (struct fd *)obj;
1555 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1556 if (fd->inode) fprintf( stderr, " inode=%p unlink=%d", fd->inode, fd->closed->unlink );
1557 fprintf( stderr, "\n" );
1560 static void fd_destroy( struct object *obj )
1562 struct fd *fd = (struct fd *)obj;
1564 free_async_queue( &fd->read_q );
1565 free_async_queue( &fd->write_q );
1566 free_async_queue( &fd->wait_q );
1568 if (fd->completion) release_object( fd->completion );
1569 remove_fd_locks( fd );
1570 list_remove( &fd->inode_entry );
1571 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1572 free( fd->nt_name );
1573 if (fd->inode)
1575 inode_add_closed_fd( fd->inode, fd->closed );
1576 release_object( fd->inode );
1578 else /* no inode, close it right away */
1580 if (fd->unix_fd != -1) close( fd->unix_fd );
1581 free( fd->unix_name );
1585 /* check if the desired access is possible without violating */
1586 /* the sharing mode of other opens of the same file */
1587 static unsigned int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing,
1588 unsigned int open_flags, unsigned int options )
1590 /* only a few access bits are meaningful wrt sharing */
1591 const unsigned int read_access = FILE_READ_DATA | FILE_EXECUTE;
1592 const unsigned int write_access = FILE_WRITE_DATA | FILE_APPEND_DATA;
1593 const unsigned int all_access = read_access | write_access | DELETE;
1595 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1596 unsigned int existing_access = 0;
1597 struct list *ptr;
1599 fd->access = access;
1600 fd->sharing = sharing;
1602 LIST_FOR_EACH( ptr, &fd->inode->open )
1604 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1605 if (fd_ptr != fd)
1607 /* if access mode is 0, sharing mode is ignored */
1608 if (fd_ptr->access & all_access) existing_sharing &= fd_ptr->sharing;
1609 existing_access |= fd_ptr->access;
1613 if (((access & read_access) && !(existing_sharing & FILE_SHARE_READ)) ||
1614 ((access & write_access) && !(existing_sharing & FILE_SHARE_WRITE)) ||
1615 ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)))
1616 return STATUS_SHARING_VIOLATION;
1617 if (((existing_access & FILE_MAPPING_WRITE) && !(sharing & FILE_SHARE_WRITE)) ||
1618 ((existing_access & FILE_MAPPING_IMAGE) && (access & FILE_WRITE_DATA)))
1619 return STATUS_SHARING_VIOLATION;
1620 if ((existing_access & FILE_MAPPING_IMAGE) && (options & FILE_DELETE_ON_CLOSE))
1621 return STATUS_CANNOT_DELETE;
1622 if ((existing_access & FILE_MAPPING_ACCESS) && (open_flags & O_TRUNC))
1623 return STATUS_USER_MAPPED_FILE;
1624 if (!(access & all_access))
1625 return 0; /* if access mode is 0, sharing mode is ignored (except for mappings) */
1626 if (((existing_access & read_access) && !(sharing & FILE_SHARE_READ)) ||
1627 ((existing_access & write_access) && !(sharing & FILE_SHARE_WRITE)) ||
1628 ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)))
1629 return STATUS_SHARING_VIOLATION;
1630 return 0;
1633 /* set the events that select waits for on this fd */
1634 void set_fd_events( struct fd *fd, int events )
1636 int user = fd->poll_index;
1637 assert( poll_users[user] == fd );
1639 set_fd_epoll_events( fd, user, events );
1641 if (events == -1) /* stop waiting on this fd completely */
1643 pollfd[user].fd = -1;
1644 pollfd[user].events = POLLERR;
1645 pollfd[user].revents = 0;
1647 else
1649 pollfd[user].fd = fd->unix_fd;
1650 pollfd[user].events = events;
1654 /* prepare an fd for unmounting its corresponding device */
1655 static inline void unmount_fd( struct fd *fd )
1657 assert( fd->inode );
1659 async_wake_up( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1660 async_wake_up( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1662 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1664 if (fd->unix_fd != -1) close( fd->unix_fd );
1666 fd->unix_fd = -1;
1667 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1668 fd->closed->unix_fd = -1;
1669 fd->closed->unlink = 0;
1671 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1672 fd->fs_locks = 0;
1675 /* allocate an fd object, without setting the unix fd yet */
1676 static struct fd *alloc_fd_object(void)
1678 struct fd *fd = alloc_object( &fd_ops );
1680 if (!fd) return NULL;
1682 fd->fd_ops = NULL;
1683 fd->user = NULL;
1684 fd->inode = NULL;
1685 fd->closed = NULL;
1686 fd->access = 0;
1687 fd->options = 0;
1688 fd->sharing = 0;
1689 fd->unix_fd = -1;
1690 fd->unix_name = NULL;
1691 fd->nt_name = NULL;
1692 fd->nt_namelen = 0;
1693 fd->cacheable = 0;
1694 fd->signaled = 1;
1695 fd->fs_locks = 1;
1696 fd->poll_index = -1;
1697 fd->completion = NULL;
1698 fd->comp_flags = 0;
1699 init_async_queue( &fd->read_q );
1700 init_async_queue( &fd->write_q );
1701 init_async_queue( &fd->wait_q );
1702 list_init( &fd->inode_entry );
1703 list_init( &fd->locks );
1705 if ((fd->poll_index = add_poll_user( fd )) == -1)
1707 release_object( fd );
1708 return NULL;
1710 return fd;
1713 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1714 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1716 struct fd *fd = alloc_object( &fd_ops );
1718 if (!fd) return NULL;
1720 fd->fd_ops = fd_user_ops;
1721 fd->user = user;
1722 fd->inode = NULL;
1723 fd->closed = NULL;
1724 fd->access = 0;
1725 fd->options = options;
1726 fd->sharing = 0;
1727 fd->unix_name = NULL;
1728 fd->nt_name = NULL;
1729 fd->nt_namelen = 0;
1730 fd->unix_fd = -1;
1731 fd->cacheable = 0;
1732 fd->signaled = 0;
1733 fd->fs_locks = 0;
1734 fd->poll_index = -1;
1735 fd->completion = NULL;
1736 fd->comp_flags = 0;
1737 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1738 init_async_queue( &fd->read_q );
1739 init_async_queue( &fd->write_q );
1740 init_async_queue( &fd->wait_q );
1741 list_init( &fd->inode_entry );
1742 list_init( &fd->locks );
1743 return fd;
1746 /* duplicate an fd object for a different user */
1747 struct fd *dup_fd_object( struct fd *orig, unsigned int access, unsigned int sharing, unsigned int options )
1749 unsigned int err;
1750 struct fd *fd = alloc_fd_object();
1752 if (!fd) return NULL;
1754 fd->options = options;
1755 fd->cacheable = orig->cacheable;
1757 if (orig->unix_name)
1759 if (!(fd->unix_name = mem_alloc( strlen(orig->unix_name) + 1 ))) goto failed;
1760 strcpy( fd->unix_name, orig->unix_name );
1762 if (orig->nt_namelen)
1764 if (!(fd->nt_name = memdup( orig->nt_name, orig->nt_namelen ))) goto failed;
1765 fd->nt_namelen = orig->nt_namelen;
1768 if (orig->inode)
1770 struct closed_fd *closed = mem_alloc( sizeof(*closed) );
1771 if (!closed) goto failed;
1772 if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1774 file_set_error();
1775 free( closed );
1776 goto failed;
1778 closed->unix_fd = fd->unix_fd;
1779 closed->unlink = 0;
1780 closed->unix_name = fd->unix_name;
1781 fd->closed = closed;
1782 fd->inode = (struct inode *)grab_object( orig->inode );
1783 list_add_head( &fd->inode->open, &fd->inode_entry );
1784 if ((err = check_sharing( fd, access, sharing, 0, options )))
1786 set_error( err );
1787 goto failed;
1790 else if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1792 file_set_error();
1793 goto failed;
1795 return fd;
1797 failed:
1798 release_object( fd );
1799 return NULL;
1802 /* find an existing fd object that can be reused for a mapping */
1803 struct fd *get_fd_object_for_mapping( struct fd *fd, unsigned int access, unsigned int sharing )
1805 struct fd *fd_ptr;
1807 if (!fd->inode) return NULL;
1809 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
1810 if (fd_ptr->access == access && fd_ptr->sharing == sharing)
1811 return (struct fd *)grab_object( fd_ptr );
1813 return NULL;
1816 /* sets the user of an fd that previously had no user */
1817 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1819 assert( fd->fd_ops == NULL );
1820 fd->fd_ops = user_ops;
1821 fd->user = user;
1824 char *dup_fd_name( struct fd *root, const char *name )
1826 char *ret;
1828 if (!root) return strdup( name );
1829 if (!root->unix_name) return NULL;
1831 /* skip . prefix */
1832 if (name[0] == '.' && (!name[1] || name[1] == '/')) name++;
1834 if ((ret = malloc( strlen(root->unix_name) + strlen(name) + 2 )))
1836 strcpy( ret, root->unix_name );
1837 if (name[0] && name[0] != '/') strcat( ret, "/" );
1838 strcat( ret, name );
1840 return ret;
1843 static WCHAR *dup_nt_name( struct fd *root, struct unicode_str name, data_size_t *len )
1845 WCHAR *ret;
1846 data_size_t retlen;
1848 if (!root)
1850 *len = name.len;
1851 if (!name.len) return NULL;
1852 return memdup( name.str, name.len );
1854 if (!root->nt_namelen) return NULL;
1855 retlen = root->nt_namelen;
1857 /* skip . prefix */
1858 if (name.len && name.str[0] == '.' && (name.len == sizeof(WCHAR) || name.str[1] == '\\'))
1860 name.str++;
1861 name.len -= sizeof(WCHAR);
1863 if ((ret = malloc( retlen + name.len + 1 )))
1865 memcpy( ret, root->nt_name, root->nt_namelen );
1866 if (name.len && name.str[0] != '\\' &&
1867 root->nt_namelen && root->nt_name[root->nt_namelen / sizeof(WCHAR) - 1] != '\\')
1869 ret[retlen / sizeof(WCHAR)] = '\\';
1870 retlen += sizeof(WCHAR);
1872 memcpy( ret + retlen / sizeof(WCHAR), name.str, name.len );
1873 *len = retlen + name.len;
1875 return ret;
1878 void get_nt_name( struct fd *fd, struct unicode_str *name )
1880 name->str = fd->nt_name;
1881 name->len = fd->nt_namelen;
1884 /* open() wrapper that returns a struct fd with no fd user set */
1885 struct fd *open_fd( struct fd *root, const char *name, struct unicode_str nt_name,
1886 int flags, mode_t *mode, unsigned int access,
1887 unsigned int sharing, unsigned int options )
1889 struct stat st;
1890 struct closed_fd *closed_fd;
1891 struct fd *fd;
1892 int root_fd = -1;
1893 int rw_mode;
1894 char *path;
1896 if (((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE)) ||
1897 ((options & FILE_DIRECTORY_FILE) && (flags & O_TRUNC)))
1899 set_error( STATUS_INVALID_PARAMETER );
1900 return NULL;
1903 if (!(fd = alloc_fd_object())) return NULL;
1905 fd->options = options;
1906 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
1908 release_object( fd );
1909 return NULL;
1912 if (root)
1914 if ((root_fd = get_unix_fd( root )) == -1) goto error;
1915 if (fchdir( root_fd ) == -1)
1917 file_set_error();
1918 root_fd = -1;
1919 goto error;
1923 /* create the directory if needed */
1924 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1926 if (mkdir( name, *mode ) == -1)
1928 if (errno != EEXIST || (flags & O_EXCL))
1930 file_set_error();
1931 goto error;
1934 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1937 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1939 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1940 else rw_mode = O_WRONLY;
1942 else rw_mode = O_RDONLY;
1944 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1946 /* if we tried to open a directory for write access, retry read-only */
1947 if (errno == EISDIR)
1949 if ((access & FILE_UNIX_WRITE_ACCESS) || (flags & O_CREAT))
1950 fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode );
1953 if (fd->unix_fd == -1)
1955 file_set_error();
1956 goto error;
1960 fd->nt_name = dup_nt_name( root, nt_name, &fd->nt_namelen );
1961 fd->unix_name = NULL;
1962 if ((path = dup_fd_name( root, name )))
1964 fd->unix_name = realpath( path, NULL );
1965 free( path );
1968 closed_fd->unix_fd = fd->unix_fd;
1969 closed_fd->unlink = 0;
1970 closed_fd->unix_name = fd->unix_name;
1971 fstat( fd->unix_fd, &st );
1972 *mode = st.st_mode;
1974 /* only bother with an inode for normal files and directories */
1975 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1977 unsigned int err;
1978 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1980 if (!inode)
1982 /* we can close the fd because there are no others open on the same file,
1983 * otherwise we wouldn't have failed to allocate a new inode
1985 goto error;
1987 fd->inode = inode;
1988 fd->closed = closed_fd;
1989 fd->cacheable = !inode->device->removable;
1990 list_add_head( &inode->open, &fd->inode_entry );
1991 closed_fd = NULL;
1993 /* check directory options */
1994 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1996 set_error( STATUS_NOT_A_DIRECTORY );
1997 goto error;
1999 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
2001 set_error( STATUS_FILE_IS_A_DIRECTORY );
2002 goto error;
2004 if ((err = check_sharing( fd, access, sharing, flags, options )))
2006 set_error( err );
2007 goto error;
2010 /* can't unlink files if we don't have permission to access */
2011 if ((options & FILE_DELETE_ON_CLOSE) && !(flags & O_CREAT) &&
2012 !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2014 set_error( STATUS_CANNOT_DELETE );
2015 goto error;
2018 fd->closed->unlink = (options & FILE_DELETE_ON_CLOSE) ? -1 : 0;
2019 if (flags & O_TRUNC)
2021 if (S_ISDIR(st.st_mode))
2023 set_error( STATUS_OBJECT_NAME_COLLISION );
2024 goto error;
2026 ftruncate( fd->unix_fd, 0 );
2029 else /* special file */
2031 if (options & FILE_DELETE_ON_CLOSE) /* we can't unlink special files */
2033 set_error( STATUS_INVALID_PARAMETER );
2034 goto error;
2036 free( closed_fd );
2037 fd->cacheable = 1;
2039 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
2040 return fd;
2042 error:
2043 release_object( fd );
2044 free( closed_fd );
2045 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
2046 return NULL;
2049 /* create an fd for an anonymous file */
2050 /* if the function fails the unix fd is closed */
2051 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
2052 unsigned int options )
2054 struct fd *fd = alloc_fd_object();
2056 if (fd)
2058 set_fd_user( fd, fd_user_ops, user );
2059 fd->unix_fd = unix_fd;
2060 fd->options = options;
2061 return fd;
2063 close( unix_fd );
2064 return NULL;
2067 /* retrieve the object that is using an fd */
2068 void *get_fd_user( struct fd *fd )
2070 return fd->user;
2073 /* retrieve the opening options for the fd */
2074 unsigned int get_fd_options( struct fd *fd )
2076 return fd->options;
2079 /* retrieve the completion flags for the fd */
2080 unsigned int get_fd_comp_flags( struct fd *fd )
2082 return fd->comp_flags;
2085 /* check if fd is in overlapped mode */
2086 int is_fd_overlapped( struct fd *fd )
2088 return !(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
2091 /* retrieve the unix fd for an object */
2092 int get_unix_fd( struct fd *fd )
2094 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
2095 return fd->unix_fd;
2098 /* check if two file descriptors point to the same file */
2099 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
2101 return fd1->inode == fd2->inode;
2104 /* allow the fd to be cached (can't be reset once set) */
2105 void allow_fd_caching( struct fd *fd )
2107 fd->cacheable = 1;
2110 /* check if fd is on a removable device */
2111 int is_fd_removable( struct fd *fd )
2113 return (fd->inode && fd->inode->device->removable);
2116 /* set or clear the fd signaled state */
2117 void set_fd_signaled( struct fd *fd, int signaled )
2119 if (fd->comp_flags & FILE_SKIP_SET_EVENT_ON_HANDLE) return;
2120 fd->signaled = signaled;
2121 if (signaled) wake_up( fd->user, 0 );
2124 /* check if events are pending and if yes return which one(s) */
2125 int check_fd_events( struct fd *fd, int events )
2127 struct pollfd pfd;
2129 if (fd->unix_fd == -1) return POLLERR;
2130 if (fd->inode) return events; /* regular files are always signaled */
2132 pfd.fd = fd->unix_fd;
2133 pfd.events = events;
2134 if (poll( &pfd, 1, 0 ) <= 0) return 0;
2135 return pfd.revents;
2138 /* default signaled() routine for objects that poll() on an fd */
2139 int default_fd_signaled( struct object *obj, struct wait_queue_entry *entry )
2141 struct fd *fd = get_obj_fd( obj );
2142 int ret = fd->signaled;
2143 release_object( fd );
2144 return ret;
2147 int default_fd_get_poll_events( struct fd *fd )
2149 int events = 0;
2151 if (async_waiting( &fd->read_q )) events |= POLLIN;
2152 if (async_waiting( &fd->write_q )) events |= POLLOUT;
2153 return events;
2156 /* default handler for poll() events */
2157 void default_poll_event( struct fd *fd, int event )
2159 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( &fd->read_q, STATUS_ALERTED );
2160 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( &fd->write_q, STATUS_ALERTED );
2162 /* if an error occurred, stop polling this fd to avoid busy-looping */
2163 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
2164 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2167 void fd_queue_async( struct fd *fd, struct async *async, int type )
2169 struct async_queue *queue;
2171 switch (type)
2173 case ASYNC_TYPE_READ:
2174 queue = &fd->read_q;
2175 break;
2176 case ASYNC_TYPE_WRITE:
2177 queue = &fd->write_q;
2178 break;
2179 case ASYNC_TYPE_WAIT:
2180 queue = &fd->wait_q;
2181 break;
2182 default:
2183 queue = NULL;
2184 assert(0);
2187 queue_async( queue, async );
2189 if (type != ASYNC_TYPE_WAIT)
2191 if (!fd->inode)
2192 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2193 else /* regular files are always ready for read and write */
2194 async_wake_up( queue, STATUS_ALERTED );
2198 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
2200 switch (type)
2202 case ASYNC_TYPE_READ:
2203 async_wake_up( &fd->read_q, status );
2204 break;
2205 case ASYNC_TYPE_WRITE:
2206 async_wake_up( &fd->write_q, status );
2207 break;
2208 case ASYNC_TYPE_WAIT:
2209 async_wake_up( &fd->wait_q, status );
2210 break;
2211 default:
2212 assert(0);
2216 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
2218 fd->fd_ops->reselect_async( fd, queue );
2221 void no_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2223 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2226 void default_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2228 fd_queue_async( fd, async, type );
2229 set_error( STATUS_PENDING );
2232 /* default reselect_async() fd routine */
2233 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
2235 if (queue == &fd->read_q || queue == &fd->write_q)
2237 int poll_events = fd->fd_ops->get_poll_events( fd );
2238 int events = check_fd_events( fd, poll_events );
2239 if (events) fd->fd_ops->poll_event( fd, events );
2240 else set_fd_events( fd, poll_events );
2244 static inline int is_valid_mounted_device( struct stat *st )
2246 #if defined(linux) || defined(__sun__)
2247 return S_ISBLK( st->st_mode );
2248 #else
2249 /* disks are char devices on *BSD */
2250 return S_ISCHR( st->st_mode );
2251 #endif
2254 /* close all Unix file descriptors on a device to allow unmounting it */
2255 static void unmount_device( struct fd *device_fd )
2257 unsigned int i;
2258 struct stat st;
2259 struct device *device;
2260 struct inode *inode;
2261 struct fd *fd;
2262 int unix_fd = get_unix_fd( device_fd );
2264 if (unix_fd == -1) return;
2266 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2268 set_error( STATUS_INVALID_PARAMETER );
2269 return;
2272 if (!(device = get_device( st.st_rdev, -1 ))) return;
2274 for (i = 0; i < INODE_HASH_SIZE; i++)
2276 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
2278 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
2280 unmount_fd( fd );
2282 inode_close_pending( inode, 0 );
2285 /* remove it from the hash table */
2286 list_remove( &device->entry );
2287 list_init( &device->entry );
2288 release_object( device );
2291 /* default read() routine */
2292 int no_fd_read( struct fd *fd, struct async *async, file_pos_t pos )
2294 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2295 return 0;
2298 /* default write() routine */
2299 int no_fd_write( struct fd *fd, struct async *async, file_pos_t pos )
2301 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2302 return 0;
2305 /* default flush() routine */
2306 int no_fd_flush( struct fd *fd, struct async *async )
2308 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2309 return 0;
2312 /* default get_file_info() routine */
2313 void no_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2315 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2318 /* default get_file_info() routine */
2319 void default_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2321 switch (info_class)
2323 case FileAccessInformation:
2325 FILE_ACCESS_INFORMATION info;
2326 if (get_reply_max_size() < sizeof(info))
2328 set_error( STATUS_INFO_LENGTH_MISMATCH );
2329 return;
2331 info.AccessFlags = get_handle_access( current->process, handle );
2332 set_reply_data( &info, sizeof(info) );
2333 break;
2335 case FileModeInformation:
2337 FILE_MODE_INFORMATION info;
2338 if (get_reply_max_size() < sizeof(info))
2340 set_error( STATUS_INFO_LENGTH_MISMATCH );
2341 return;
2343 info.Mode = fd->options & ( FILE_WRITE_THROUGH
2344 | FILE_SEQUENTIAL_ONLY
2345 | FILE_NO_INTERMEDIATE_BUFFERING
2346 | FILE_SYNCHRONOUS_IO_ALERT
2347 | FILE_SYNCHRONOUS_IO_NONALERT );
2348 set_reply_data( &info, sizeof(info) );
2349 break;
2351 case FileIoCompletionNotificationInformation:
2353 FILE_IO_COMPLETION_NOTIFICATION_INFORMATION info;
2354 if (get_reply_max_size() < sizeof(info))
2356 set_error( STATUS_INFO_LENGTH_MISMATCH );
2357 return;
2359 info.Flags = fd->comp_flags;
2360 set_reply_data( &info, sizeof(info) );
2361 break;
2363 default:
2364 set_error( STATUS_NOT_IMPLEMENTED );
2368 /* default get_volume_info() routine */
2369 int no_fd_get_volume_info( struct fd *fd, struct async *async, unsigned int info_class )
2371 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2372 return 0;
2375 /* default ioctl() routine */
2376 int no_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2378 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2379 return 0;
2382 /* default ioctl() routine */
2383 int default_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2385 switch(code)
2387 case FSCTL_DISMOUNT_VOLUME:
2388 unmount_device( fd );
2389 return 1;
2390 default:
2391 set_error( STATUS_NOT_SUPPORTED );
2392 return 0;
2396 /* same as get_handle_obj but retrieve the struct fd associated to the object */
2397 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
2398 unsigned int access )
2400 struct fd *fd = NULL;
2401 struct object *obj;
2403 if ((obj = get_handle_obj( process, handle, access, NULL )))
2405 fd = get_obj_fd( obj );
2406 release_object( obj );
2408 return fd;
2411 static int is_dir_empty( int fd )
2413 DIR *dir;
2414 int empty;
2415 struct dirent *de;
2417 if ((fd = dup( fd )) == -1)
2418 return -1;
2420 if (!(dir = fdopendir( fd )))
2422 close( fd );
2423 return -1;
2426 empty = 1;
2427 while (empty && (de = readdir( dir )))
2429 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2430 empty = 0;
2432 closedir( dir );
2433 return empty;
2436 /* set disposition for the fd */
2437 static void set_fd_disposition( struct fd *fd, int unlink )
2439 struct stat st;
2441 if (!fd->inode)
2443 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2444 return;
2447 if (fd->unix_fd == -1)
2449 set_error( fd->no_fd_status );
2450 return;
2453 if (unlink)
2455 struct fd *fd_ptr;
2457 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
2459 if (fd_ptr->access & FILE_MAPPING_ACCESS)
2461 set_error( STATUS_CANNOT_DELETE );
2462 return;
2466 if (fstat( fd->unix_fd, &st ) == -1)
2468 file_set_error();
2469 return;
2471 if (S_ISREG( st.st_mode )) /* can't unlink files we don't have permission to write */
2473 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2475 set_error( STATUS_CANNOT_DELETE );
2476 return;
2479 else if (S_ISDIR( st.st_mode )) /* can't remove non-empty directories */
2481 switch (is_dir_empty( fd->unix_fd ))
2483 case -1:
2484 file_set_error();
2485 return;
2486 case 0:
2487 set_error( STATUS_DIRECTORY_NOT_EMPTY );
2488 return;
2491 else /* can't unlink special files */
2493 set_error( STATUS_INVALID_PARAMETER );
2494 return;
2498 fd->closed->unlink = unlink ? 1 : 0;
2499 if (fd->options & FILE_DELETE_ON_CLOSE)
2500 fd->closed->unlink = -1;
2503 /* set new name for the fd */
2504 static void set_fd_name( struct fd *fd, struct fd *root, const char *nameptr, data_size_t len,
2505 struct unicode_str nt_name, int create_link, int replace )
2507 struct inode *inode;
2508 struct stat st, st2;
2509 char *name;
2511 if (!fd->inode || !fd->unix_name)
2513 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2514 return;
2516 if (fd->unix_fd == -1)
2518 set_error( fd->no_fd_status );
2519 return;
2522 if (!len || ((nameptr[0] == '/') ^ !root))
2524 set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
2525 return;
2527 if (!(name = mem_alloc( len + 1 ))) return;
2528 memcpy( name, nameptr, len );
2529 name[len] = 0;
2531 if (root)
2533 char *combined_name = dup_fd_name( root, name );
2534 if (!combined_name)
2536 set_error( STATUS_NO_MEMORY );
2537 goto failed;
2539 free( name );
2540 name = combined_name;
2543 /* when creating a hard link, source cannot be a dir */
2544 if (create_link && !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode ))
2546 set_error( STATUS_FILE_IS_A_DIRECTORY );
2547 goto failed;
2550 if (!stat( name, &st ))
2552 if (!fstat( fd->unix_fd, &st2 ) && st.st_ino == st2.st_ino && st.st_dev == st2.st_dev)
2554 if (create_link && !replace) set_error( STATUS_OBJECT_NAME_COLLISION );
2555 free( name );
2556 return;
2559 if (!replace)
2561 set_error( STATUS_OBJECT_NAME_COLLISION );
2562 goto failed;
2565 /* can't replace directories or special files */
2566 if (!S_ISREG( st.st_mode ))
2568 set_error( STATUS_ACCESS_DENIED );
2569 goto failed;
2572 /* can't replace an opened file */
2573 if ((inode = get_inode( st.st_dev, st.st_ino, -1 )))
2575 int is_empty = list_empty( &inode->open );
2576 release_object( inode );
2577 if (!is_empty)
2579 set_error( STATUS_ACCESS_DENIED );
2580 goto failed;
2584 /* link() expects that the target doesn't exist */
2585 /* rename() cannot replace files with directories */
2586 if (create_link || S_ISDIR( st2.st_mode ))
2588 if (unlink( name ))
2590 file_set_error();
2591 goto failed;
2596 if (create_link)
2598 if (link( fd->unix_name, name ))
2599 file_set_error();
2600 free( name );
2601 return;
2604 if (rename( fd->unix_name, name ))
2606 file_set_error();
2607 goto failed;
2610 if (is_file_executable( fd->unix_name ) != is_file_executable( name ) && !fstat( fd->unix_fd, &st ))
2612 if (is_file_executable( name ))
2613 /* set executable bit where read bit is set */
2614 st.st_mode |= (st.st_mode & 0444) >> 2;
2615 else
2616 st.st_mode &= ~0111;
2617 fchmod( fd->unix_fd, st.st_mode );
2620 free( fd->nt_name );
2621 fd->nt_name = dup_nt_name( root, nt_name, &fd->nt_namelen );
2622 free( fd->unix_name );
2623 fd->closed->unix_name = fd->unix_name = realpath( name, NULL );
2624 free( name );
2625 if (!fd->unix_name)
2626 set_error( STATUS_NO_MEMORY );
2627 return;
2629 failed:
2630 free( name );
2633 static void set_fd_eof( struct fd *fd, file_pos_t eof )
2635 struct stat st;
2637 if (!fd->inode)
2639 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2640 return;
2643 if (fd->unix_fd == -1)
2645 set_error( fd->no_fd_status );
2646 return;
2648 if (fstat( fd->unix_fd, &st) == -1)
2650 file_set_error();
2651 return;
2653 if (eof < st.st_size)
2655 struct fd *fd_ptr;
2656 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
2658 if (fd_ptr->access & FILE_MAPPING_ACCESS)
2660 set_error( STATUS_USER_MAPPED_FILE );
2661 return;
2664 if (ftruncate( fd->unix_fd, eof ) == -1) file_set_error();
2666 else grow_file( fd->unix_fd, eof );
2669 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
2671 *p_key = fd->comp_key;
2672 return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
2675 void fd_copy_completion( struct fd *src, struct fd *dst )
2677 assert( !dst->completion );
2678 dst->completion = fd_get_completion( src, &dst->comp_key );
2679 dst->comp_flags = src->comp_flags;
2682 /* flush a file buffers */
2683 DECL_HANDLER(flush)
2685 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, 0 );
2686 struct async *async;
2688 if (!fd) return;
2690 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2692 reply->event = async_handoff( async, fd->fd_ops->flush( fd, async ), NULL, 1 );
2693 release_object( async );
2695 release_object( fd );
2698 /* query file info */
2699 DECL_HANDLER(get_file_info)
2701 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2703 if (fd)
2705 fd->fd_ops->get_file_info( fd, req->handle, req->info_class );
2706 release_object( fd );
2710 /* query volume info */
2711 DECL_HANDLER(get_volume_info)
2713 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2714 struct async *async;
2716 if (!fd) return;
2718 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2720 reply->wait = async_handoff( async, fd->fd_ops->get_volume_info( fd, async, req->info_class ), NULL, 1 );
2721 release_object( async );
2723 release_object( fd );
2726 /* open a file object */
2727 DECL_HANDLER(open_file_object)
2729 struct unicode_str name = get_req_unicode_str();
2730 struct object *obj, *result, *root = NULL;
2732 if (req->rootdir && !(root = get_handle_obj( current->process, req->rootdir, 0, NULL ))) return;
2734 obj = open_named_object( root, NULL, &name, req->attributes );
2735 if (root) release_object( root );
2736 if (!obj) return;
2738 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
2740 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
2741 release_object( result );
2743 release_object( obj );
2746 /* get the Unix name from a file handle */
2747 DECL_HANDLER(get_handle_unix_name)
2749 struct fd *fd;
2751 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2753 if (fd->unix_name)
2755 data_size_t name_len = strlen( fd->unix_name );
2756 reply->name_len = name_len;
2757 if (name_len <= get_reply_max_size()) set_reply_data( fd->unix_name, name_len );
2758 else set_error( STATUS_BUFFER_OVERFLOW );
2760 else set_error( STATUS_OBJECT_TYPE_MISMATCH );
2761 release_object( fd );
2765 /* get a Unix fd to access a file */
2766 DECL_HANDLER(get_handle_fd)
2768 struct fd *fd;
2770 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2772 int unix_fd = get_unix_fd( fd );
2773 reply->cacheable = fd->cacheable;
2774 if (unix_fd != -1)
2776 reply->type = fd->fd_ops->get_fd_type( fd );
2777 reply->options = fd->options;
2778 reply->access = get_handle_access( current->process, req->handle );
2779 send_client_fd( current->process, unix_fd, req->handle );
2781 release_object( fd );
2785 /* perform a read on a file object */
2786 DECL_HANDLER(read)
2788 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_READ_DATA );
2789 struct async *async;
2791 if (!fd) return;
2793 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2795 reply->wait = async_handoff( async, fd->fd_ops->read( fd, async, req->pos ), NULL, 0 );
2796 reply->options = fd->options;
2797 release_object( async );
2799 release_object( fd );
2802 /* perform a write on a file object */
2803 DECL_HANDLER(write)
2805 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_WRITE_DATA );
2806 struct async *async;
2808 if (!fd) return;
2810 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2812 reply->wait = async_handoff( async, fd->fd_ops->write( fd, async, req->pos ), &reply->size, 0 );
2813 reply->options = fd->options;
2814 release_object( async );
2816 release_object( fd );
2819 /* perform an ioctl on a file */
2820 DECL_HANDLER(ioctl)
2822 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2823 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2824 struct async *async;
2826 if (!fd) return;
2828 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2830 reply->wait = async_handoff( async, fd->fd_ops->ioctl( fd, req->code, async ), NULL, 0 );
2831 reply->options = fd->options;
2832 release_object( async );
2834 release_object( fd );
2837 /* create / reschedule an async I/O */
2838 DECL_HANDLER(register_async)
2840 unsigned int access;
2841 struct async *async;
2842 struct fd *fd;
2844 switch(req->type)
2846 case ASYNC_TYPE_READ:
2847 access = FILE_READ_DATA;
2848 break;
2849 case ASYNC_TYPE_WRITE:
2850 access = FILE_WRITE_DATA;
2851 break;
2852 default:
2853 set_error( STATUS_INVALID_PARAMETER );
2854 return;
2857 if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2859 if (get_unix_fd( fd ) != -1 && (async = create_async( fd, current, &req->async, NULL )))
2861 fd->fd_ops->queue_async( fd, async, req->type, req->count );
2862 release_object( async );
2864 release_object( fd );
2868 /* attach completion object to a fd */
2869 DECL_HANDLER(set_completion_info)
2871 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2873 if (fd)
2875 if (is_fd_overlapped( fd ) && !fd->completion)
2877 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2878 fd->comp_key = req->ckey;
2880 else set_error( STATUS_INVALID_PARAMETER );
2881 release_object( fd );
2885 /* push new completion msg into a completion queue attached to the fd */
2886 DECL_HANDLER(add_fd_completion)
2888 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2889 if (fd)
2891 if (fd->completion && (req->async || !(fd->comp_flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS)))
2892 add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2893 release_object( fd );
2897 /* set fd completion information */
2898 DECL_HANDLER(set_fd_completion_mode)
2900 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2901 if (fd)
2903 if (is_fd_overlapped( fd ))
2905 if (req->flags & FILE_SKIP_SET_EVENT_ON_HANDLE)
2906 set_fd_signaled( fd, 0 );
2907 /* removing flags is not allowed */
2908 fd->comp_flags |= req->flags & ( FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
2909 | FILE_SKIP_SET_EVENT_ON_HANDLE
2910 | FILE_SKIP_SET_USER_EVENT_ON_FAST_IO );
2912 else
2913 set_error( STATUS_INVALID_PARAMETER );
2914 release_object( fd );
2918 /* set fd disposition information */
2919 DECL_HANDLER(set_fd_disp_info)
2921 struct fd *fd = get_handle_fd_obj( current->process, req->handle, DELETE );
2922 if (fd)
2924 set_fd_disposition( fd, req->unlink );
2925 release_object( fd );
2929 /* set fd name information */
2930 DECL_HANDLER(set_fd_name_info)
2932 struct fd *fd, *root_fd = NULL;
2933 struct unicode_str nt_name;
2935 if (req->namelen > get_req_data_size())
2937 set_error( STATUS_INVALID_PARAMETER );
2938 return;
2940 nt_name.str = get_req_data();
2941 nt_name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
2943 if (req->rootdir)
2945 struct dir *root;
2947 if (!(root = get_dir_obj( current->process, req->rootdir, 0 ))) return;
2948 root_fd = get_obj_fd( (struct object *)root );
2949 release_object( root );
2950 if (!root_fd) return;
2953 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2955 set_fd_name( fd, root_fd, (const char *)get_req_data() + req->namelen,
2956 get_req_data_size() - req->namelen, nt_name, req->link, req->replace );
2957 release_object( fd );
2959 if (root_fd) release_object( root_fd );
2962 /* set fd eof information */
2963 DECL_HANDLER(set_fd_eof_info)
2965 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2966 if (fd)
2968 set_fd_eof( fd, req->eof );
2969 release_object( fd );