ole32: The METAFILEPICT created by OleMetafilePictFromIconAndLabel should have its...
[wine/multimedia.git] / server / fd.c
blob157db69f9565e632390693154966766015e89807
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 <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <signal.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #ifdef HAVE_POLL_H
35 #include <poll.h>
36 #endif
37 #ifdef HAVE_SYS_POLL_H
38 #include <sys/poll.h>
39 #endif
40 #ifdef HAVE_LINUX_MAJOR_H
41 #include <linux/major.h>
42 #endif
43 #ifdef HAVE_SYS_STATVFS_H
44 #include <sys/statvfs.h>
45 #endif
46 #ifdef HAVE_SYS_VFS_H
47 #include <sys/vfs.h>
48 #endif
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
51 #endif
52 #ifdef HAVE_SYS_MOUNT_H
53 #include <sys/mount.h>
54 #endif
55 #ifdef HAVE_SYS_STATFS_H
56 #include <sys/statfs.h>
57 #endif
58 #ifdef HAVE_SYS_EVENT_H
59 #include <sys/event.h>
60 #undef LIST_INIT
61 #undef LIST_ENTRY
62 #endif
63 #ifdef HAVE_STDINT_H
64 #include <stdint.h>
65 #endif
66 #include <sys/stat.h>
67 #include <sys/time.h>
68 #include <sys/types.h>
69 #include <unistd.h>
71 #include "ntstatus.h"
72 #define WIN32_NO_STATUS
73 #include "object.h"
74 #include "file.h"
75 #include "handle.h"
76 #include "process.h"
77 #include "request.h"
79 #include "winternl.h"
81 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
82 # include <sys/epoll.h>
83 # define USE_EPOLL
84 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
85 # define USE_EPOLL
86 # define EPOLLIN POLLIN
87 # define EPOLLOUT POLLOUT
88 # define EPOLLERR POLLERR
89 # define EPOLLHUP POLLHUP
90 # define EPOLL_CTL_ADD 1
91 # define EPOLL_CTL_DEL 2
92 # define EPOLL_CTL_MOD 3
94 typedef union epoll_data
96 void *ptr;
97 int fd;
98 uint32_t u32;
99 uint64_t u64;
100 } epoll_data_t;
102 struct epoll_event
104 uint32_t events;
105 epoll_data_t data;
108 #define SYSCALL_RET(ret) do { \
109 if (ret < 0) { errno = -ret; ret = -1; } \
110 return ret; \
111 } while(0)
113 static inline int epoll_create( int size )
115 int ret;
116 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
117 : "=a" (ret) : "0" (254 /*NR_epoll_create*/), "r" (size) );
118 SYSCALL_RET(ret);
121 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
123 int ret;
124 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
125 : "=a" (ret)
126 : "0" (255 /*NR_epoll_ctl*/), "r" (epfd), "c" (op), "d" (fd), "S" (event), "m" (*event) );
127 SYSCALL_RET(ret);
130 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
132 int ret;
133 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
134 : "=a" (ret)
135 : "0" (256 /*NR_epoll_wait*/), "r" (epfd), "c" (events), "d" (maxevents), "S" (timeout)
136 : "memory" );
137 SYSCALL_RET(ret);
139 #undef SYSCALL_RET
141 #endif /* linux && __i386__ && HAVE_STDINT_H */
144 /* Because of the stupid Posix locking semantics, we need to keep
145 * track of all file descriptors referencing a given file, and not
146 * close a single one until all the locks are gone (sigh).
149 /* file descriptor object */
151 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
152 struct closed_fd
154 struct list entry; /* entry in inode closed list */
155 int unix_fd; /* the unix file descriptor */
156 char unlink[1]; /* name to unlink on close (if any) */
159 struct fd
161 struct object obj; /* object header */
162 const struct fd_ops *fd_ops; /* file descriptor operations */
163 struct inode *inode; /* inode that this fd belongs to */
164 struct list inode_entry; /* entry in inode fd list */
165 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
166 struct object *user; /* object using this file descriptor */
167 struct list locks; /* list of locks on this fd */
168 unsigned int access; /* file access (FILE_READ_DATA etc.) */
169 unsigned int sharing; /* file sharing mode */
170 int unix_fd; /* unix file descriptor */
171 int fs_locks :1; /* can we use filesystem locks for this fd? */
172 int unmounted :1;/* has the device been unmounted? */
173 int poll_index; /* index of fd in poll array */
174 struct list read_q; /* async readers of this fd */
175 struct list write_q; /* async writers of this fd */
178 static void fd_dump( struct object *obj, int verbose );
179 static void fd_destroy( struct object *obj );
181 static const struct object_ops fd_ops =
183 sizeof(struct fd), /* size */
184 fd_dump, /* dump */
185 no_add_queue, /* add_queue */
186 NULL, /* remove_queue */
187 NULL, /* signaled */
188 NULL, /* satisfied */
189 no_signal, /* signal */
190 no_get_fd, /* get_fd */
191 no_map_access, /* map_access */
192 no_lookup_name, /* lookup_name */
193 no_close_handle, /* close_handle */
194 fd_destroy /* destroy */
197 /* device object */
199 #define DEVICE_HASH_SIZE 7
200 #define INODE_HASH_SIZE 17
202 struct device
204 struct object obj; /* object header */
205 struct list entry; /* entry in device hash list */
206 dev_t dev; /* device number */
207 int removable; /* removable device? (or -1 if unknown) */
208 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
211 static void device_dump( struct object *obj, int verbose );
212 static void device_destroy( struct object *obj );
214 static const struct object_ops device_ops =
216 sizeof(struct device), /* size */
217 device_dump, /* dump */
218 no_add_queue, /* add_queue */
219 NULL, /* remove_queue */
220 NULL, /* signaled */
221 NULL, /* satisfied */
222 no_signal, /* signal */
223 no_get_fd, /* get_fd */
224 no_map_access, /* map_access */
225 no_lookup_name, /* lookup_name */
226 no_close_handle, /* close_handle */
227 device_destroy /* destroy */
230 /* inode object */
232 struct inode
234 struct object obj; /* object header */
235 struct list entry; /* inode hash list entry */
236 struct device *device; /* device containing this inode */
237 ino_t ino; /* inode number */
238 struct list open; /* list of open file descriptors */
239 struct list locks; /* list of file locks */
240 struct list closed; /* list of file descriptors to close at destroy time */
243 static void inode_dump( struct object *obj, int verbose );
244 static void inode_destroy( struct object *obj );
246 static const struct object_ops inode_ops =
248 sizeof(struct inode), /* size */
249 inode_dump, /* dump */
250 no_add_queue, /* add_queue */
251 NULL, /* remove_queue */
252 NULL, /* signaled */
253 NULL, /* satisfied */
254 no_signal, /* signal */
255 no_get_fd, /* get_fd */
256 no_map_access, /* map_access */
257 no_lookup_name, /* lookup_name */
258 no_close_handle, /* close_handle */
259 inode_destroy /* destroy */
262 /* file lock object */
264 struct file_lock
266 struct object obj; /* object header */
267 struct fd *fd; /* fd owning this lock */
268 struct list fd_entry; /* entry in list of locks on a given fd */
269 struct list inode_entry; /* entry in inode list of locks */
270 int shared; /* shared lock? */
271 file_pos_t start; /* locked region is interval [start;end) */
272 file_pos_t end;
273 struct process *process; /* process owning this lock */
274 struct list proc_entry; /* entry in list of locks owned by the process */
277 static void file_lock_dump( struct object *obj, int verbose );
278 static int file_lock_signaled( struct object *obj, struct thread *thread );
280 static const struct object_ops file_lock_ops =
282 sizeof(struct file_lock), /* size */
283 file_lock_dump, /* dump */
284 add_queue, /* add_queue */
285 remove_queue, /* remove_queue */
286 file_lock_signaled, /* signaled */
287 no_satisfied, /* satisfied */
288 no_signal, /* signal */
289 no_get_fd, /* get_fd */
290 no_map_access, /* map_access */
291 no_lookup_name, /* lookup_name */
292 no_close_handle, /* close_handle */
293 no_destroy /* destroy */
297 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
298 #define FILE_POS_T_MAX (~(file_pos_t)0)
300 static file_pos_t max_unix_offset = OFF_T_MAX;
302 #define DUMP_LONG_LONG(val) do { \
303 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
304 fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
305 else \
306 fprintf( stderr, "%lx", (unsigned long)(val) ); \
307 } while (0)
311 /****************************************************************/
312 /* timeouts support */
314 struct timeout_user
316 struct list entry; /* entry in sorted timeout list */
317 struct timeval when; /* timeout expiry (absolute time) */
318 timeout_callback callback; /* callback function */
319 void *private; /* callback private data */
322 static struct list timeout_list = LIST_INIT(timeout_list); /* sorted timeouts list */
323 struct timeval current_time;
325 /* add a timeout user */
326 struct timeout_user *add_timeout_user( const struct timeval *when, timeout_callback func,
327 void *private )
329 struct timeout_user *user;
330 struct list *ptr;
332 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
333 user->when = *when;
334 user->callback = func;
335 user->private = private;
337 /* Now insert it in the linked list */
339 LIST_FOR_EACH( ptr, &timeout_list )
341 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
342 if (!time_before( &timeout->when, when )) break;
344 list_add_before( ptr, &user->entry );
345 return user;
348 /* remove a timeout user */
349 void remove_timeout_user( struct timeout_user *user )
351 list_remove( &user->entry );
352 free( user );
355 /* add a timeout in milliseconds to an absolute time */
356 void add_timeout( struct timeval *when, int timeout )
358 if (timeout)
360 long sec = timeout / 1000;
361 if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
363 when->tv_usec -= 1000000;
364 when->tv_sec++;
366 when->tv_sec += sec;
371 /****************************************************************/
372 /* poll support */
374 static struct fd **poll_users; /* users array */
375 static struct pollfd *pollfd; /* poll fd array */
376 static int nb_users; /* count of array entries actually in use */
377 static int active_users; /* current number of active users */
378 static int allocated_users; /* count of allocated entries in the array */
379 static struct fd **freelist; /* list of free entries in the array */
381 static int get_next_timeout(void);
383 #ifdef USE_EPOLL
385 static int epoll_fd = -1;
387 static inline void init_epoll(void)
389 epoll_fd = epoll_create( 128 );
392 /* set the events that epoll waits for on this fd; helper for set_fd_events */
393 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
395 struct epoll_event ev;
396 int ctl;
398 if (epoll_fd == -1) return;
400 if (events == -1) /* stop waiting on this fd completely */
402 if (pollfd[user].fd == -1) return; /* already removed */
403 ctl = EPOLL_CTL_DEL;
405 else if (pollfd[user].fd == -1)
407 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
408 ctl = EPOLL_CTL_ADD;
410 else
412 if (pollfd[user].events == events) return; /* nothing to do */
413 ctl = EPOLL_CTL_MOD;
416 ev.events = events;
417 memset(&ev.data, 0, sizeof(ev.data));
418 ev.data.u32 = user;
420 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
422 if (errno == ENOMEM) /* not enough memory, give up on epoll */
424 close( epoll_fd );
425 epoll_fd = -1;
427 else perror( "epoll_ctl" ); /* should not happen */
431 static inline void remove_epoll_user( struct fd *fd, int user )
433 if (epoll_fd == -1) return;
435 if (pollfd[user].fd != -1)
437 struct epoll_event dummy;
438 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
442 static inline void main_loop_epoll(void)
444 int i, ret, timeout;
445 struct epoll_event events[128];
447 assert( POLLIN == EPOLLIN );
448 assert( POLLOUT == EPOLLOUT );
449 assert( POLLERR == EPOLLERR );
450 assert( POLLHUP == EPOLLHUP );
452 if (epoll_fd == -1) return;
454 while (active_users)
456 timeout = get_next_timeout();
458 if (!active_users) break; /* last user removed by a timeout */
459 if (epoll_fd == -1) break; /* an error occurred with epoll */
461 ret = epoll_wait( epoll_fd, events, sizeof(events)/sizeof(events[0]), timeout );
462 gettimeofday( &current_time, NULL );
464 /* put the events into the pollfd array first, like poll does */
465 for (i = 0; i < ret; i++)
467 int user = events[i].data.u32;
468 pollfd[user].revents = events[i].events;
471 /* read events from the pollfd array, as set_fd_events may modify them */
472 for (i = 0; i < ret; i++)
474 int user = events[i].data.u32;
475 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
480 #elif defined(HAVE_KQUEUE)
482 static int kqueue_fd = -1;
484 static inline void init_epoll(void)
486 #ifndef __APPLE__ /* kqueue support is broken in the MacOS kernel so we can't use it */
487 kqueue_fd = kqueue();
488 #endif
491 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
493 struct kevent ev[2];
495 if (kqueue_fd == -1) return;
497 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)user );
498 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)user );
500 if (events == -1) /* stop waiting on this fd completely */
502 if (pollfd[user].fd == -1) return; /* already removed */
503 ev[0].flags |= EV_DELETE;
504 ev[1].flags |= EV_DELETE;
506 else if (pollfd[user].fd == -1)
508 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
509 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
510 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
512 else
514 if (pollfd[user].events == events) return; /* nothing to do */
515 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
516 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
519 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
521 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
523 close( kqueue_fd );
524 kqueue_fd = -1;
526 else perror( "kevent" ); /* should not happen */
530 static inline void remove_epoll_user( struct fd *fd, int user )
532 if (kqueue_fd == -1) return;
534 if (pollfd[user].fd != -1)
536 struct kevent ev[2];
538 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
539 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
540 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
544 static inline void main_loop_epoll(void)
546 int i, ret, timeout;
547 struct kevent events[128];
549 if (kqueue_fd == -1) return;
551 while (active_users)
553 timeout = get_next_timeout();
555 if (!active_users) break; /* last user removed by a timeout */
556 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
558 if (timeout != -1)
560 struct timespec ts;
562 ts.tv_sec = timeout / 1000;
563 ts.tv_nsec = (timeout % 1000) * 1000000;
564 ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), &ts );
566 else ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), NULL );
568 gettimeofday( &current_time, NULL );
570 /* put the events into the pollfd array first, like poll does */
571 for (i = 0; i < ret; i++)
573 long user = (long)events[i].udata;
574 pollfd[user].revents = 0;
576 for (i = 0; i < ret; i++)
578 long user = (long)events[i].udata;
579 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
580 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
581 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
582 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
585 /* read events from the pollfd array, as set_fd_events may modify them */
586 for (i = 0; i < ret; i++)
588 long user = (long)events[i].udata;
589 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
590 pollfd[user].revents = 0;
595 #else /* HAVE_KQUEUE */
597 static inline void init_epoll(void) { }
598 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
599 static inline void remove_epoll_user( struct fd *fd, int user ) { }
600 static inline void main_loop_epoll(void) { }
602 #endif /* USE_EPOLL */
605 /* add a user in the poll array and return its index, or -1 on failure */
606 static int add_poll_user( struct fd *fd )
608 int ret;
609 if (freelist)
611 ret = freelist - poll_users;
612 freelist = (struct fd **)poll_users[ret];
614 else
616 if (nb_users == allocated_users)
618 struct fd **newusers;
619 struct pollfd *newpoll;
620 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
621 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
622 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
624 if (allocated_users)
625 poll_users = newusers;
626 else
627 free( newusers );
628 return -1;
630 poll_users = newusers;
631 pollfd = newpoll;
632 if (!allocated_users) init_epoll();
633 allocated_users = new_count;
635 ret = nb_users++;
637 pollfd[ret].fd = -1;
638 pollfd[ret].events = 0;
639 pollfd[ret].revents = 0;
640 poll_users[ret] = fd;
641 active_users++;
642 return ret;
645 /* remove a user from the poll list */
646 static void remove_poll_user( struct fd *fd, int user )
648 assert( user >= 0 );
649 assert( poll_users[user] == fd );
651 remove_epoll_user( fd, user );
652 pollfd[user].fd = -1;
653 pollfd[user].events = 0;
654 pollfd[user].revents = 0;
655 poll_users[user] = (struct fd *)freelist;
656 freelist = &poll_users[user];
657 active_users--;
660 /* process pending timeouts and return the time until the next timeout, in milliseconds */
661 static int get_next_timeout(void)
663 if (!list_empty( &timeout_list ))
665 struct list expired_list, *ptr;
667 /* first remove all expired timers from the list */
669 list_init( &expired_list );
670 while ((ptr = list_head( &timeout_list )) != NULL)
672 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
674 if (!time_before( &current_time, &timeout->when ))
676 list_remove( &timeout->entry );
677 list_add_tail( &expired_list, &timeout->entry );
679 else break;
682 /* now call the callback for all the removed timers */
684 while ((ptr = list_head( &expired_list )) != NULL)
686 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
687 list_remove( &timeout->entry );
688 timeout->callback( timeout->private );
689 free( timeout );
692 if ((ptr = list_head( &timeout_list )) != NULL)
694 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
695 int diff = (timeout->when.tv_sec - current_time.tv_sec) * 1000
696 + (timeout->when.tv_usec - current_time.tv_usec + 999) / 1000;
697 if (diff < 0) diff = 0;
698 return diff;
701 return -1; /* no pending timeouts */
704 /* server main poll() loop */
705 void main_loop(void)
707 int i, ret, timeout;
709 gettimeofday( &current_time, NULL );
711 main_loop_epoll();
712 /* fall through to normal poll loop */
714 while (active_users)
716 timeout = get_next_timeout();
718 if (!active_users) break; /* last user removed by a timeout */
720 ret = poll( pollfd, nb_users, timeout );
721 gettimeofday( &current_time, NULL );
723 if (ret > 0)
725 for (i = 0; i < nb_users; i++)
727 if (pollfd[i].revents)
729 fd_poll_event( poll_users[i], pollfd[i].revents );
730 if (!--ret) break;
738 /****************************************************************/
739 /* device functions */
741 static struct list device_hash[DEVICE_HASH_SIZE];
743 static int is_device_removable( dev_t dev, int unix_fd )
745 #if defined(linux) && defined(HAVE_FSTATFS)
746 struct statfs stfs;
748 /* check for floppy disk */
749 if (major(dev) == FLOPPY_MAJOR) return 1;
751 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
752 return (stfs.f_type == 0x9660 || /* iso9660 */
753 stfs.f_type == 0x9fa1 || /* supermount */
754 stfs.f_type == 0x15013346); /* udf */
755 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
756 struct statfs stfs;
758 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
759 return (!strncmp("cd9660", stfs.f_fstypename, sizeof(stfs.f_fstypename)) ||
760 !strncmp("udf", stfs.f_fstypename, sizeof(stfs.f_fstypename)));
761 #elif defined(__NetBSD__)
762 struct statvfs stfs;
764 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
765 return (!strncmp("cd9660", stfs.f_fstypename, sizeof(stfs.f_fstypename)) ||
766 !strncmp("udf", stfs.f_fstypename, sizeof(stfs.f_fstypename)));
767 #elif defined(sun)
768 # include <sys/dkio.h>
769 # include <sys/vtoc.h>
770 struct dk_cinfo dkinf;
771 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
772 return (dkinf.dki_ctype == DKC_CDROM ||
773 dkinf.dki_ctype == DKC_NCRFLOPPY ||
774 dkinf.dki_ctype == DKC_SMSFLOPPY ||
775 dkinf.dki_ctype == DKC_INTEL82072 ||
776 dkinf.dki_ctype == DKC_INTEL82077);
777 #else
778 return 0;
779 #endif
782 /* retrieve the device object for a given fd, creating it if needed */
783 static struct device *get_device( dev_t dev, int unix_fd )
785 struct device *device;
786 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
788 if (device_hash[hash].next)
790 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
791 if (device->dev == dev) return (struct device *)grab_object( device );
793 else list_init( &device_hash[hash] );
795 /* not found, create it */
797 if (unix_fd == -1) return NULL;
798 if ((device = alloc_object( &device_ops )))
800 device->dev = dev;
801 device->removable = is_device_removable( dev, unix_fd );
802 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
803 list_add_head( &device_hash[hash], &device->entry );
805 return device;
808 static void device_dump( struct object *obj, int verbose )
810 struct device *device = (struct device *)obj;
811 fprintf( stderr, "Device dev=" );
812 DUMP_LONG_LONG( device->dev );
813 fprintf( stderr, "\n" );
816 static void device_destroy( struct object *obj )
818 struct device *device = (struct device *)obj;
819 unsigned int i;
821 for (i = 0; i < INODE_HASH_SIZE; i++)
822 assert( list_empty(&device->inode_hash[i]) );
824 list_remove( &device->entry ); /* remove it from the hash table */
828 /****************************************************************/
829 /* inode functions */
831 /* close all pending file descriptors in the closed list */
832 static void inode_close_pending( struct inode *inode, int keep_unlinks )
834 struct list *ptr = list_head( &inode->closed );
836 while (ptr)
838 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
839 struct list *next = list_next( &inode->closed, ptr );
841 if (fd->unix_fd != -1)
843 close( fd->unix_fd );
844 fd->unix_fd = -1;
846 if (!keep_unlinks || !fd->unlink[0]) /* get rid of it unless there's an unlink pending on that file */
848 list_remove( ptr );
849 free( fd );
851 ptr = next;
855 static void inode_dump( struct object *obj, int verbose )
857 struct inode *inode = (struct inode *)obj;
858 fprintf( stderr, "Inode device=%p ino=", inode->device );
859 DUMP_LONG_LONG( inode->ino );
860 fprintf( stderr, "\n" );
863 static void inode_destroy( struct object *obj )
865 struct inode *inode = (struct inode *)obj;
866 struct list *ptr;
868 assert( list_empty(&inode->open) );
869 assert( list_empty(&inode->locks) );
871 list_remove( &inode->entry );
873 while ((ptr = list_head( &inode->closed )))
875 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
876 list_remove( ptr );
877 if (fd->unix_fd != -1) close( fd->unix_fd );
878 if (fd->unlink[0])
880 /* make sure it is still the same file */
881 struct stat st;
882 if (!stat( fd->unlink, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
884 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
885 else unlink( fd->unlink );
888 free( fd );
890 release_object( inode->device );
893 /* retrieve the inode object for a given fd, creating it if needed */
894 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
896 struct device *device;
897 struct inode *inode;
898 unsigned int hash = ino % INODE_HASH_SIZE;
900 if (!(device = get_device( dev, unix_fd ))) return NULL;
902 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
904 if (inode->ino == ino)
906 release_object( device );
907 return (struct inode *)grab_object( inode );
911 /* not found, create it */
912 if ((inode = alloc_object( &inode_ops )))
914 inode->device = device;
915 inode->ino = ino;
916 list_init( &inode->open );
917 list_init( &inode->locks );
918 list_init( &inode->closed );
919 list_add_head( &device->inode_hash[hash], &inode->entry );
921 else release_object( device );
923 return inode;
926 /* add fd to the inode list of file descriptors to close */
927 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
929 if (!list_empty( &inode->locks ))
931 list_add_head( &inode->closed, &fd->entry );
933 else if (fd->unlink[0]) /* close the fd but keep the structure around for unlink */
935 if (fd->unix_fd != -1) close( fd->unix_fd );
936 fd->unix_fd = -1;
937 list_add_head( &inode->closed, &fd->entry );
939 else /* no locks on this inode and no unlink, get rid of the fd */
941 if (fd->unix_fd != -1) close( fd->unix_fd );
942 free( fd );
947 /****************************************************************/
948 /* file lock functions */
950 static void file_lock_dump( struct object *obj, int verbose )
952 struct file_lock *lock = (struct file_lock *)obj;
953 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
954 lock->shared ? "shared" : "excl", lock->fd, lock->process );
955 DUMP_LONG_LONG( lock->start );
956 fprintf( stderr, " end=" );
957 DUMP_LONG_LONG( lock->end );
958 fprintf( stderr, "\n" );
961 static int file_lock_signaled( struct object *obj, struct thread *thread )
963 struct file_lock *lock = (struct file_lock *)obj;
964 /* lock is signaled if it has lost its owner */
965 return !lock->process;
968 /* set (or remove) a Unix lock if possible for the given range */
969 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
971 struct flock fl;
973 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
974 for (;;)
976 if (start == end) return 1; /* can't set zero-byte lock */
977 if (start > max_unix_offset) return 1; /* ignore it */
978 fl.l_type = type;
979 fl.l_whence = SEEK_SET;
980 fl.l_start = start;
981 if (!end || end > max_unix_offset) fl.l_len = 0;
982 else fl.l_len = end - start;
983 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
985 switch(errno)
987 case EACCES:
988 /* check whether locks work at all on this file system */
989 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
991 set_error( STATUS_FILE_LOCK_CONFLICT );
992 return 0;
994 /* fall through */
995 case EIO:
996 case ENOLCK:
997 /* no locking on this fs, just ignore it */
998 fd->fs_locks = 0;
999 return 1;
1000 case EAGAIN:
1001 set_error( STATUS_FILE_LOCK_CONFLICT );
1002 return 0;
1003 case EBADF:
1004 /* this can happen if we try to set a write lock on a read-only file */
1005 /* we just ignore that error */
1006 if (fl.l_type == F_WRLCK) return 1;
1007 set_error( STATUS_ACCESS_DENIED );
1008 return 0;
1009 #ifdef EOVERFLOW
1010 case EOVERFLOW:
1011 #endif
1012 case EINVAL:
1013 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1014 /* in that case we shrink the limit and retry */
1015 if (max_unix_offset > INT_MAX)
1017 max_unix_offset = INT_MAX;
1018 break; /* retry */
1020 /* fall through */
1021 default:
1022 file_set_error();
1023 return 0;
1028 /* check if interval [start;end) overlaps the lock */
1029 inline static int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1031 if (lock->end && start >= lock->end) return 0;
1032 if (end && lock->start >= end) return 0;
1033 return 1;
1036 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1037 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1039 struct hole
1041 struct hole *next;
1042 struct hole *prev;
1043 file_pos_t start;
1044 file_pos_t end;
1045 } *first, *cur, *next, *buffer;
1047 struct list *ptr;
1048 int count = 0;
1050 if (!fd->inode) return;
1051 if (!fd->fs_locks) return;
1052 if (start == end || start > max_unix_offset) return;
1053 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1055 /* count the number of locks overlapping the specified area */
1057 LIST_FOR_EACH( ptr, &fd->inode->locks )
1059 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1060 if (lock->start == lock->end) continue;
1061 if (lock_overlaps( lock, start, end )) count++;
1064 if (!count) /* no locks at all, we can unlock everything */
1066 set_unix_lock( fd, start, end, F_UNLCK );
1067 return;
1070 /* allocate space for the list of holes */
1071 /* max. number of holes is number of locks + 1 */
1073 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1074 first = buffer;
1075 first->next = NULL;
1076 first->prev = NULL;
1077 first->start = start;
1078 first->end = end;
1079 next = first + 1;
1081 /* build a sorted list of unlocked holes in the specified area */
1083 LIST_FOR_EACH( ptr, &fd->inode->locks )
1085 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1086 if (lock->start == lock->end) continue;
1087 if (!lock_overlaps( lock, start, end )) continue;
1089 /* go through all the holes touched by this lock */
1090 for (cur = first; cur; cur = cur->next)
1092 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1093 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1095 /* now we know that lock is overlapping hole */
1097 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1099 cur->start = lock->end;
1100 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1101 /* now hole is empty, remove it */
1102 if (cur->next) cur->next->prev = cur->prev;
1103 if (cur->prev) cur->prev->next = cur->next;
1104 else if (!(first = cur->next)) goto done; /* no more holes at all */
1106 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1108 cur->end = lock->start;
1109 assert( cur->start < cur->end );
1111 else /* lock is in the middle of hole, split hole in two */
1113 next->prev = cur;
1114 next->next = cur->next;
1115 cur->next = next;
1116 next->start = lock->end;
1117 next->end = cur->end;
1118 cur->end = lock->start;
1119 assert( next->start < next->end );
1120 assert( cur->end < next->start );
1121 next++;
1122 break; /* done with this lock */
1127 /* clear Unix locks for all the holes */
1129 for (cur = first; cur; cur = cur->next)
1130 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1132 done:
1133 free( buffer );
1136 /* create a new lock on a fd */
1137 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1139 struct file_lock *lock;
1141 if (!fd->inode) /* not a regular file */
1143 set_error( STATUS_INVALID_HANDLE );
1144 return NULL;
1147 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1148 lock->shared = shared;
1149 lock->start = start;
1150 lock->end = end;
1151 lock->fd = fd;
1152 lock->process = current->process;
1154 /* now try to set a Unix lock */
1155 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1157 release_object( lock );
1158 return NULL;
1160 list_add_head( &fd->locks, &lock->fd_entry );
1161 list_add_head( &fd->inode->locks, &lock->inode_entry );
1162 list_add_head( &lock->process->locks, &lock->proc_entry );
1163 return lock;
1166 /* remove an existing lock */
1167 static void remove_lock( struct file_lock *lock, int remove_unix )
1169 struct inode *inode = lock->fd->inode;
1171 list_remove( &lock->fd_entry );
1172 list_remove( &lock->inode_entry );
1173 list_remove( &lock->proc_entry );
1174 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1175 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1176 lock->process = NULL;
1177 wake_up( &lock->obj, 0 );
1178 release_object( lock );
1181 /* remove all locks owned by a given process */
1182 void remove_process_locks( struct process *process )
1184 struct list *ptr;
1186 while ((ptr = list_head( &process->locks )))
1188 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1189 remove_lock( lock, 1 ); /* this removes it from the list */
1193 /* remove all locks on a given fd */
1194 static void remove_fd_locks( struct fd *fd )
1196 file_pos_t start = FILE_POS_T_MAX, end = 0;
1197 struct list *ptr;
1199 while ((ptr = list_head( &fd->locks )))
1201 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1202 if (lock->start < start) start = lock->start;
1203 if (!lock->end || lock->end > end) end = lock->end - 1;
1204 remove_lock( lock, 0 );
1206 if (start < end) remove_unix_locks( fd, start, end + 1 );
1209 /* add a lock on an fd */
1210 /* returns handle to wait on */
1211 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1213 struct list *ptr;
1214 file_pos_t end = start + count;
1216 /* don't allow wrapping locks */
1217 if (end && end < start)
1219 set_error( STATUS_INVALID_PARAMETER );
1220 return 0;
1223 /* check if another lock on that file overlaps the area */
1224 LIST_FOR_EACH( ptr, &fd->inode->locks )
1226 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1227 if (!lock_overlaps( lock, start, end )) continue;
1228 if (lock->shared && shared) continue;
1229 /* found one */
1230 if (!wait)
1232 set_error( STATUS_FILE_LOCK_CONFLICT );
1233 return 0;
1235 set_error( STATUS_PENDING );
1236 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1239 /* not found, add it */
1240 if (add_lock( fd, shared, start, end )) return 0;
1241 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1243 /* Unix lock conflict -> tell client to wait and retry */
1244 if (wait) set_error( STATUS_PENDING );
1246 return 0;
1249 /* remove a lock on an fd */
1250 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1252 struct list *ptr;
1253 file_pos_t end = start + count;
1255 /* find an existing lock with the exact same parameters */
1256 LIST_FOR_EACH( ptr, &fd->locks )
1258 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1259 if ((lock->start == start) && (lock->end == end))
1261 remove_lock( lock, 1 );
1262 return;
1265 set_error( STATUS_FILE_LOCK_CONFLICT );
1269 /****************************************************************/
1270 /* asynchronous operations support */
1272 struct async
1274 struct thread *thread;
1275 void *apc;
1276 void *user;
1277 void *sb;
1278 struct timeout_user *timeout;
1279 struct list entry;
1282 /* notifies client thread of new status of its async request */
1283 /* destroys the server side of it */
1284 static void async_terminate( struct async *async, int status )
1286 thread_queue_apc( async->thread, NULL, async->apc, APC_ASYNC_IO,
1287 1, async->user, async->sb, (void *)status );
1289 if (async->timeout) remove_timeout_user( async->timeout );
1290 async->timeout = NULL;
1291 list_remove( &async->entry );
1292 release_object( async->thread );
1293 free( async );
1296 /* cb for timeout on an async request */
1297 static void async_callback(void *private)
1299 struct async *async = (struct async *)private;
1301 /* fprintf(stderr, "async timeout out %p\n", async); */
1302 async->timeout = NULL;
1303 async_terminate( async, STATUS_TIMEOUT );
1306 /* create an async on a given queue of a fd */
1307 struct async *create_async( struct thread *thread, const struct timeval *timeout,
1308 struct list *queue, void *io_apc, void *io_user, void* io_sb )
1310 struct async *async = mem_alloc( sizeof(struct async) );
1312 if (!async) return NULL;
1314 async->thread = (struct thread *)grab_object(thread);
1315 async->apc = io_apc;
1316 async->user = io_user;
1317 async->sb = io_sb;
1319 list_add_tail( queue, &async->entry );
1321 if (timeout) async->timeout = add_timeout_user( timeout, async_callback, async );
1322 else async->timeout = NULL;
1324 return async;
1327 /* terminate the async operation at the head of the queue */
1328 void async_terminate_head( struct list *queue, int status )
1330 struct list *ptr = list_head( queue );
1331 if (ptr) async_terminate( LIST_ENTRY( ptr, struct async, entry ), status );
1334 /****************************************************************/
1335 /* file descriptor functions */
1337 static void fd_dump( struct object *obj, int verbose )
1339 struct fd *fd = (struct fd *)obj;
1340 fprintf( stderr, "Fd unix_fd=%d user=%p", fd->unix_fd, fd->user );
1341 if (fd->inode) fprintf( stderr, " inode=%p unlink='%s'", fd->inode, fd->closed->unlink );
1342 fprintf( stderr, "\n" );
1345 static void fd_destroy( struct object *obj )
1347 struct fd *fd = (struct fd *)obj;
1349 async_terminate_queue( &fd->read_q, STATUS_CANCELLED );
1350 async_terminate_queue( &fd->write_q, STATUS_CANCELLED );
1352 remove_fd_locks( fd );
1353 list_remove( &fd->inode_entry );
1354 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1355 if (fd->inode)
1357 inode_add_closed_fd( fd->inode, fd->closed );
1358 release_object( fd->inode );
1360 else /* no inode, close it right away */
1362 if (fd->unix_fd != -1) close( fd->unix_fd );
1366 /* set the events that select waits for on this fd */
1367 void set_fd_events( struct fd *fd, int events )
1369 int user = fd->poll_index;
1370 assert( poll_users[user] == fd );
1372 set_fd_epoll_events( fd, user, events );
1374 if (events == -1) /* stop waiting on this fd completely */
1376 pollfd[user].fd = -1;
1377 pollfd[user].events = POLLERR;
1378 pollfd[user].revents = 0;
1380 else if (pollfd[user].fd != -1 || !pollfd[user].events)
1382 pollfd[user].fd = fd->unix_fd;
1383 pollfd[user].events = events;
1387 /* prepare an fd for unmounting its corresponding device */
1388 static inline void unmount_fd( struct fd *fd )
1390 assert( fd->inode );
1392 async_terminate_queue( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1393 async_terminate_queue( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1395 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1397 if (fd->unix_fd != -1) close( fd->unix_fd );
1399 fd->unix_fd = -1;
1400 fd->unmounted = 1;
1401 fd->closed->unix_fd = -1;
1402 fd->closed->unlink[0] = 0;
1404 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1405 fd->fs_locks = 0;
1408 /* allocate an fd object, without setting the unix fd yet */
1409 static struct fd *alloc_fd_object(void)
1411 struct fd *fd = alloc_object( &fd_ops );
1413 if (!fd) return NULL;
1415 fd->fd_ops = NULL;
1416 fd->user = NULL;
1417 fd->inode = NULL;
1418 fd->closed = NULL;
1419 fd->access = 0;
1420 fd->sharing = 0;
1421 fd->unix_fd = -1;
1422 fd->fs_locks = 1;
1423 fd->unmounted = 0;
1424 fd->poll_index = -1;
1425 list_init( &fd->inode_entry );
1426 list_init( &fd->locks );
1427 list_init( &fd->read_q );
1428 list_init( &fd->write_q );
1430 if ((fd->poll_index = add_poll_user( fd )) == -1)
1432 release_object( fd );
1433 return NULL;
1435 return fd;
1438 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1439 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user )
1441 struct fd *fd = alloc_object( &fd_ops );
1443 if (!fd) return NULL;
1445 fd->fd_ops = fd_user_ops;
1446 fd->user = user;
1447 fd->inode = NULL;
1448 fd->closed = NULL;
1449 fd->access = 0;
1450 fd->sharing = 0;
1451 fd->unix_fd = -1;
1452 fd->fs_locks = 0;
1453 fd->unmounted = 0;
1454 fd->poll_index = -1;
1455 list_init( &fd->inode_entry );
1456 list_init( &fd->locks );
1457 list_init( &fd->read_q );
1458 list_init( &fd->write_q );
1459 return fd;
1462 /* check if the desired access is possible without violating */
1463 /* the sharing mode of other opens of the same file */
1464 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
1466 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1467 unsigned int existing_access = 0;
1468 struct list *ptr;
1470 /* if access mode is 0, sharing mode is ignored */
1471 if (!access) sharing = existing_sharing;
1472 fd->access = access;
1473 fd->sharing = sharing;
1475 LIST_FOR_EACH( ptr, &fd->inode->open )
1477 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1478 if (fd_ptr != fd)
1480 existing_sharing &= fd_ptr->sharing;
1481 existing_access |= fd_ptr->access;
1485 if ((access & FILE_UNIX_READ_ACCESS) && !(existing_sharing & FILE_SHARE_READ)) return 0;
1486 if ((access & FILE_UNIX_WRITE_ACCESS) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1487 if ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1488 if ((existing_access & FILE_UNIX_READ_ACCESS) && !(sharing & FILE_SHARE_READ)) return 0;
1489 if ((existing_access & FILE_UNIX_WRITE_ACCESS) && !(sharing & FILE_SHARE_WRITE)) return 0;
1490 if ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)) return 0;
1491 return 1;
1494 /* sets the user of an fd that previously had no user */
1495 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1497 assert( fd->fd_ops == NULL );
1498 fd->fd_ops = user_ops;
1499 fd->user = user;
1502 /* open() wrapper that returns a struct fd with no fd user set */
1503 struct fd *open_fd( const char *name, int flags, mode_t *mode, unsigned int access,
1504 unsigned int sharing, unsigned int options )
1506 struct stat st;
1507 struct closed_fd *closed_fd;
1508 struct fd *fd;
1509 const char *unlink_name = "";
1510 int rw_mode;
1512 if ((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE))
1514 set_error( STATUS_INVALID_PARAMETER );
1515 return NULL;
1518 if (!(fd = alloc_fd_object())) return NULL;
1520 if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1521 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1523 release_object( fd );
1524 return NULL;
1527 /* create the directory if needed */
1528 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1530 if (mkdir( name, 0777 ) == -1)
1532 if (errno != EEXIST || (flags & O_EXCL))
1534 file_set_error();
1535 goto error;
1538 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1541 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1543 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1544 else rw_mode = O_WRONLY;
1546 else rw_mode = O_RDONLY;
1548 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1550 /* if we tried to open a directory for write access, retry read-only */
1551 if (errno != EISDIR ||
1552 !(access & FILE_UNIX_WRITE_ACCESS) ||
1553 (fd->unix_fd = open( name, O_RDONLY | (flags & ~O_TRUNC), *mode )) == -1)
1555 file_set_error();
1556 goto error;
1560 closed_fd->unix_fd = fd->unix_fd;
1561 closed_fd->unlink[0] = 0;
1562 fstat( fd->unix_fd, &st );
1563 *mode = st.st_mode;
1565 /* only bother with an inode for normal files and directories */
1566 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1568 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1570 if (!inode)
1572 /* we can close the fd because there are no others open on the same file,
1573 * otherwise we wouldn't have failed to allocate a new inode
1575 goto error;
1577 fd->inode = inode;
1578 fd->closed = closed_fd;
1579 list_add_head( &inode->open, &fd->inode_entry );
1581 /* check directory options */
1582 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1584 release_object( fd );
1585 set_error( STATUS_NOT_A_DIRECTORY );
1586 return NULL;
1588 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1590 release_object( fd );
1591 set_error( STATUS_FILE_IS_A_DIRECTORY );
1592 return NULL;
1594 if (!check_sharing( fd, access, sharing ))
1596 release_object( fd );
1597 set_error( STATUS_SHARING_VIOLATION );
1598 return NULL;
1600 strcpy( closed_fd->unlink, unlink_name );
1601 if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1603 else /* special file */
1605 if (options & FILE_DIRECTORY_FILE)
1607 set_error( STATUS_NOT_A_DIRECTORY );
1608 goto error;
1610 if (unlink_name[0]) /* we can't unlink special files */
1612 set_error( STATUS_INVALID_PARAMETER );
1613 goto error;
1615 free( closed_fd );
1617 return fd;
1619 error:
1620 release_object( fd );
1621 free( closed_fd );
1622 return NULL;
1625 /* create an fd for an anonymous file */
1626 /* if the function fails the unix fd is closed */
1627 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user )
1629 struct fd *fd = alloc_fd_object();
1631 if (fd)
1633 set_fd_user( fd, fd_user_ops, user );
1634 fd->unix_fd = unix_fd;
1635 return fd;
1637 close( unix_fd );
1638 return NULL;
1641 /* retrieve the object that is using an fd */
1642 void *get_fd_user( struct fd *fd )
1644 return fd->user;
1647 /* retrieve the unix fd for an object */
1648 int get_unix_fd( struct fd *fd )
1650 if (fd->unix_fd == -1)
1652 if (fd->unmounted) set_error( STATUS_VOLUME_DISMOUNTED );
1653 else set_error( STATUS_BAD_DEVICE_TYPE );
1655 return fd->unix_fd;
1658 /* check if two file descriptors point to the same file */
1659 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1661 return fd1->inode == fd2->inode;
1664 /* handler for close_handle that refuses to close fd-associated handles in other processes */
1665 int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
1667 return (!current || current->process == process);
1670 /* callback for event happening in the main poll() loop */
1671 void fd_poll_event( struct fd *fd, int event )
1673 return fd->fd_ops->poll_event( fd, event );
1676 /* check if events are pending and if yes return which one(s) */
1677 int check_fd_events( struct fd *fd, int events )
1679 struct pollfd pfd;
1681 if (fd->unix_fd == -1) return POLLERR;
1683 pfd.fd = fd->unix_fd;
1684 pfd.events = events;
1685 if (poll( &pfd, 1, 0 ) <= 0) return 0;
1686 return pfd.revents;
1689 /* default add_queue() routine for objects that poll() on an fd */
1690 int default_fd_add_queue( struct object *obj, struct wait_queue_entry *entry )
1692 struct fd *fd = get_obj_fd( obj );
1694 if (!fd) return 0;
1695 if (!fd->inode && list_empty( &obj->wait_queue )) /* first on the queue */
1696 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1697 add_queue( obj, entry );
1698 release_object( fd );
1699 return 1;
1702 /* default remove_queue() routine for objects that poll() on an fd */
1703 void default_fd_remove_queue( struct object *obj, struct wait_queue_entry *entry )
1705 struct fd *fd = get_obj_fd( obj );
1707 grab_object( obj );
1708 remove_queue( obj, entry );
1709 if (!fd->inode && list_empty( &obj->wait_queue )) /* last on the queue is gone */
1710 set_fd_events( fd, 0 );
1711 release_object( obj );
1712 release_object( fd );
1715 /* default signaled() routine for objects that poll() on an fd */
1716 int default_fd_signaled( struct object *obj, struct thread *thread )
1718 int events, ret;
1719 struct fd *fd = get_obj_fd( obj );
1721 if (fd->inode) ret = 1; /* regular files are always signaled */
1722 else
1724 events = fd->fd_ops->get_poll_events( fd );
1725 ret = check_fd_events( fd, events ) != 0;
1727 if (ret)
1729 /* stop waiting on select() if we are signaled */
1730 set_fd_events( fd, 0 );
1732 else if (!list_empty( &obj->wait_queue ))
1734 /* restart waiting on poll() if we are no longer signaled */
1735 set_fd_events( fd, events );
1738 release_object( fd );
1739 return ret;
1742 int default_fd_get_poll_events( struct fd *fd )
1744 int events = 0;
1746 if (!list_empty( &fd->read_q ))
1747 events |= POLLIN;
1748 if (!list_empty( &fd->write_q ))
1749 events |= POLLOUT;
1751 return events;
1754 /* default handler for poll() events */
1755 void default_poll_event( struct fd *fd, int event )
1757 if (!list_empty( &fd->read_q ) && (POLLIN & event) )
1759 async_terminate_head( &fd->read_q, STATUS_ALERTED );
1760 return;
1762 if (!list_empty( &fd->write_q ) && (POLLOUT & event) )
1764 async_terminate_head( &fd->write_q, STATUS_ALERTED );
1765 return;
1768 /* if an error occurred, stop polling this fd to avoid busy-looping */
1769 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1770 wake_up( fd->user, 0 );
1773 void fd_queue_async_timeout( struct fd *fd, void *apc, void *user, void *io_sb, int type, int count,
1774 const struct timeval *timeout )
1776 struct list *queue;
1777 int events, flags;
1779 fd->fd_ops->get_file_info( fd, &flags );
1780 if (!(flags & (FD_FLAG_OVERLAPPED|FD_FLAG_TIMEOUT)))
1782 set_error( STATUS_INVALID_HANDLE );
1783 return;
1786 switch (type)
1788 case ASYNC_TYPE_READ:
1789 queue = &fd->read_q;
1790 break;
1791 case ASYNC_TYPE_WRITE:
1792 queue = &fd->write_q;
1793 break;
1794 default:
1795 set_error( STATUS_INVALID_PARAMETER );
1796 return;
1799 if (!create_async( current, timeout, queue, apc, user, io_sb ))
1800 return;
1802 /* Check if the new pending request can be served immediately */
1803 events = check_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1804 if (events) fd->fd_ops->poll_event( fd, events );
1806 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1809 void default_fd_queue_async( struct fd *fd, void *apc, void *user, void *io_sb, int type, int count )
1811 fd_queue_async_timeout( fd, apc, user, io_sb, type, count, NULL );
1814 void default_fd_cancel_async( struct fd *fd )
1816 async_terminate_queue( &fd->read_q, STATUS_CANCELLED );
1817 async_terminate_queue( &fd->write_q, STATUS_CANCELLED );
1820 /* default flush() routine */
1821 int no_flush( struct fd *fd, struct event **event )
1823 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1824 return 0;
1827 /* default get_file_info() routine */
1828 enum server_fd_type no_get_file_info( struct fd *fd, int *flags )
1830 *flags = 0;
1831 return FD_TYPE_INVALID;
1834 /* default queue_async() routine */
1835 void no_queue_async( struct fd *fd, void* apc, void* user, void* io_sb,
1836 int type, int count)
1838 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1841 /* default cancel_async() routine */
1842 void no_cancel_async( struct fd *fd )
1844 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1847 static inline int is_valid_mounted_device( struct stat *st )
1849 #if defined(linux) || defined(__sun__)
1850 return S_ISBLK( st->st_mode );
1851 #else
1852 /* disks are char devices on *BSD */
1853 return S_ISCHR( st->st_mode );
1854 #endif
1857 /* close all Unix file descriptors on a device to allow unmounting it */
1858 static void unmount_device( struct fd *device_fd )
1860 unsigned int i;
1861 struct stat st;
1862 struct device *device;
1863 struct inode *inode;
1864 struct fd *fd;
1865 int unix_fd = get_unix_fd( device_fd );
1867 if (unix_fd == -1) return;
1869 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
1871 set_error( STATUS_INVALID_PARAMETER );
1872 return;
1875 if (!(device = get_device( st.st_rdev, -1 ))) return;
1877 for (i = 0; i < INODE_HASH_SIZE; i++)
1879 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
1881 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
1883 unmount_fd( fd );
1885 inode_close_pending( inode, 0 );
1888 /* remove it from the hash table */
1889 list_remove( &device->entry );
1890 list_init( &device->entry );
1891 release_object( device );
1894 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1895 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1896 unsigned int access )
1898 struct fd *fd = NULL;
1899 struct object *obj;
1901 if ((obj = get_handle_obj( process, handle, access, NULL )))
1903 fd = get_obj_fd( obj );
1904 release_object( obj );
1906 return fd;
1909 /* flush a file buffers */
1910 DECL_HANDLER(flush_file)
1912 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1913 struct event * event = NULL;
1915 if (fd)
1917 fd->fd_ops->flush( fd, &event );
1918 if ( event )
1920 reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1922 release_object( fd );
1926 /* open a file object */
1927 DECL_HANDLER(open_file_object)
1929 struct unicode_str name;
1930 struct directory *root = NULL;
1931 struct object *obj;
1933 get_req_unicode_str( &name );
1934 if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
1935 return;
1937 if ((obj = open_object_dir( root, &name, req->attributes, NULL )))
1939 /* make sure this is a valid file object */
1940 struct fd *fd = get_obj_fd( obj );
1941 if (fd)
1943 reply->handle = alloc_handle( current->process, obj, req->access, req->attributes );
1944 release_object( fd );
1946 release_object( obj );
1949 if (root) release_object( root );
1952 /* get a Unix fd to access a file */
1953 DECL_HANDLER(get_handle_fd)
1955 struct fd *fd;
1957 if ((fd = get_handle_fd_obj( current->process, req->handle, req->access )))
1959 reply->type = fd->fd_ops->get_file_info( fd, &reply->flags );
1960 if (reply->type != FD_TYPE_INVALID)
1962 if (fd->inode && fd->inode->device->removable) reply->flags |= FD_FLAG_REMOVABLE;
1963 if (!req->cached)
1965 int unix_fd = get_unix_fd( fd );
1966 if (unix_fd != -1) send_client_fd( current->process, unix_fd, req->handle );
1969 else set_error( STATUS_OBJECT_TYPE_MISMATCH );
1970 release_object( fd );
1974 /* get ready to unmount a Unix device */
1975 DECL_HANDLER(unmount_device)
1977 struct fd *fd;
1979 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
1981 unmount_device( fd );
1982 release_object( fd );
1986 /* create / reschedule an async I/O */
1987 DECL_HANDLER(register_async)
1989 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1992 * The queue_async method must do the following:
1994 * 1. Get the async_queue for the request of given type.
1995 * 2. Create a new asynchronous request for the selected queue
1996 * 3. Carry out any operations necessary to adjust the object's poll events
1997 * Usually: set_elect_events (obj, obj->ops->get_poll_events()).
1998 * 4. When the async request is triggered, then send back (with a proper APC)
1999 * the trigger (STATUS_ALERTED) to the thread that posted the request.
2000 * async_destroy() is to be called: it will both notify the sender about
2001 * the trigger and destroy the request by itself
2002 * See also the implementations in file.c, serial.c, and sock.c.
2005 if (fd)
2007 fd->fd_ops->queue_async( fd, req->io_apc, req->io_user, req->io_sb,
2008 req->type, req->count );
2009 release_object( fd );
2013 /* cancels all async I/O */
2014 DECL_HANDLER(cancel_async)
2016 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2017 if (fd)
2019 /* Note: we don't kill the queued APC_ASYNC_IO on this thread because
2020 * NtCancelIoFile() will force the pending APC to be run. Since,
2021 * Windows only guarantees that the current thread will have no async
2022 * operation on the current fd when NtCancelIoFile returns, this shall
2023 * do the work.
2025 fd->fd_ops->cancel_async( fd );
2026 release_object( fd );