Put space between include directive and include file.
[wine/wine-kai.git] / server / fd.c
blobef5b31cf4137498845065e6ac3f2717d48395eee
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "config.h"
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <signal.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #ifdef HAVE_POLL_H
34 #include <poll.h>
35 #endif
36 #ifdef HAVE_SYS_POLL_H
37 #include <sys/poll.h>
38 #endif
39 #ifdef HAVE_STDINT_H
40 #include <stdint.h>
41 #endif
42 #include <sys/stat.h>
43 #include <sys/time.h>
44 #include <sys/types.h>
45 #include <unistd.h>
47 #include "object.h"
48 #include "file.h"
49 #include "handle.h"
50 #include "process.h"
51 #include "request.h"
53 #include "winbase.h"
54 #include "winreg.h"
55 #include "winternl.h"
57 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
58 # include <sys/epoll.h>
59 # define USE_EPOLL
60 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
61 # define USE_EPOLL
62 # define EPOLLIN POLLIN
63 # define EPOLLOUT POLLOUT
64 # define EPOLLERR POLLERR
65 # define EPOLLHUP POLLHUP
66 # define EPOLL_CTL_ADD 1
67 # define EPOLL_CTL_DEL 2
68 # define EPOLL_CTL_MOD 3
70 typedef union epoll_data
72 void *ptr;
73 int fd;
74 uint32_t u32;
75 uint64_t u64;
76 } epoll_data_t;
78 struct epoll_event
80 uint32_t events;
81 epoll_data_t data;
84 #define SYSCALL_RET(ret) do { \
85 if (ret < 0) { errno = -ret; ret = -1; } \
86 return ret; \
87 } while(0)
89 static inline int epoll_create( int size )
91 int ret;
92 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
93 : "=a" (ret) : "0" (254 /*NR_epoll_create*/), "r" (size) );
94 SYSCALL_RET(ret);
97 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
99 int ret;
100 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
101 : "=a" (ret)
102 : "0" (255 /*NR_epoll_ctl*/), "r" (epfd), "c" (op), "d" (fd), "S" (event), "m" (*event) );
103 SYSCALL_RET(ret);
106 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
108 int ret;
109 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
110 : "=a" (ret)
111 : "0" (256 /*NR_epoll_wait*/), "r" (epfd), "c" (events), "d" (maxevents), "S" (timeout)
112 : "memory" );
113 SYSCALL_RET(ret);
115 #undef SYSCALL_RET
117 #endif /* linux && __i386__ && HAVE_STDINT_H */
120 /* Because of the stupid Posix locking semantics, we need to keep
121 * track of all file descriptors referencing a given file, and not
122 * close a single one until all the locks are gone (sigh).
125 /* file descriptor object */
127 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
128 struct closed_fd
130 struct list entry; /* entry in inode closed list */
131 int fd; /* the unix file descriptor */
132 char unlink[1]; /* name to unlink on close (if any) */
135 struct fd
137 struct object obj; /* object header */
138 const struct fd_ops *fd_ops; /* file descriptor operations */
139 struct inode *inode; /* inode that this fd belongs to */
140 struct list inode_entry; /* entry in inode fd list */
141 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
142 struct object *user; /* object using this file descriptor */
143 struct list locks; /* list of locks on this fd */
144 unsigned int access; /* file access (GENERIC_READ/WRITE) */
145 unsigned int sharing; /* file sharing mode */
146 int unix_fd; /* unix file descriptor */
147 int fs_locks; /* can we use filesystem locks for this fd? */
148 int poll_index; /* index of fd in poll array */
151 static void fd_dump( struct object *obj, int verbose );
152 static void fd_destroy( struct object *obj );
154 static const struct object_ops fd_ops =
156 sizeof(struct fd), /* size */
157 fd_dump, /* dump */
158 no_add_queue, /* add_queue */
159 NULL, /* remove_queue */
160 NULL, /* signaled */
161 NULL, /* satisfied */
162 no_get_fd, /* get_fd */
163 fd_destroy /* destroy */
166 /* inode object */
168 struct inode
170 struct object obj; /* object header */
171 struct list entry; /* inode hash list entry */
172 unsigned int hash; /* hashing code */
173 dev_t dev; /* device number */
174 ino_t ino; /* inode number */
175 struct list open; /* list of open file descriptors */
176 struct list locks; /* list of file locks */
177 struct list closed; /* list of file descriptors to close at destroy time */
180 static void inode_dump( struct object *obj, int verbose );
181 static void inode_destroy( struct object *obj );
183 static const struct object_ops inode_ops =
185 sizeof(struct inode), /* size */
186 inode_dump, /* dump */
187 no_add_queue, /* add_queue */
188 NULL, /* remove_queue */
189 NULL, /* signaled */
190 NULL, /* satisfied */
191 no_get_fd, /* get_fd */
192 inode_destroy /* destroy */
195 /* file lock object */
197 struct file_lock
199 struct object obj; /* object header */
200 struct fd *fd; /* fd owning this lock */
201 struct list fd_entry; /* entry in list of locks on a given fd */
202 struct list inode_entry; /* entry in inode list of locks */
203 int shared; /* shared lock? */
204 file_pos_t start; /* locked region is interval [start;end) */
205 file_pos_t end;
206 struct process *process; /* process owning this lock */
207 struct list proc_entry; /* entry in list of locks owned by the process */
210 static void file_lock_dump( struct object *obj, int verbose );
211 static int file_lock_signaled( struct object *obj, struct thread *thread );
213 static const struct object_ops file_lock_ops =
215 sizeof(struct file_lock), /* size */
216 file_lock_dump, /* dump */
217 add_queue, /* add_queue */
218 remove_queue, /* remove_queue */
219 file_lock_signaled, /* signaled */
220 no_satisfied, /* satisfied */
221 no_get_fd, /* get_fd */
222 no_destroy /* destroy */
226 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
227 #define FILE_POS_T_MAX (~(file_pos_t)0)
229 static file_pos_t max_unix_offset = OFF_T_MAX;
231 #define DUMP_LONG_LONG(val) do { \
232 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
233 fprintf( stderr, "%lx%08lx", (unsigned long)((val) >> 32), (unsigned long)(val) ); \
234 else \
235 fprintf( stderr, "%lx", (unsigned long)(val) ); \
236 } while (0)
240 /****************************************************************/
241 /* timeouts support */
243 struct timeout_user
245 struct list entry; /* entry in sorted timeout list */
246 struct timeval when; /* timeout expiry (absolute time) */
247 timeout_callback callback; /* callback function */
248 void *private; /* callback private data */
251 static struct list timeout_list = LIST_INIT(timeout_list); /* sorted timeouts list */
253 /* add a timeout user */
254 struct timeout_user *add_timeout_user( const struct timeval *when, timeout_callback func,
255 void *private )
257 struct timeout_user *user;
258 struct list *ptr;
260 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
261 user->when = *when;
262 user->callback = func;
263 user->private = private;
265 /* Now insert it in the linked list */
267 LIST_FOR_EACH( ptr, &timeout_list )
269 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
270 if (!time_before( &timeout->when, when )) break;
272 list_add_before( ptr, &user->entry );
273 return user;
276 /* remove a timeout user */
277 void remove_timeout_user( struct timeout_user *user )
279 list_remove( &user->entry );
280 free( user );
283 /* add a timeout in milliseconds to an absolute time */
284 void add_timeout( struct timeval *when, int timeout )
286 if (timeout)
288 long sec = timeout / 1000;
289 if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
291 when->tv_usec -= 1000000;
292 when->tv_sec++;
294 when->tv_sec += sec;
299 /****************************************************************/
300 /* poll support */
302 static struct fd **poll_users; /* users array */
303 static struct pollfd *pollfd; /* poll fd array */
304 static int nb_users; /* count of array entries actually in use */
305 static int active_users; /* current number of active users */
306 static int allocated_users; /* count of allocated entries in the array */
307 static struct fd **freelist; /* list of free entries in the array */
309 #ifdef USE_EPOLL
311 static int epoll_fd;
312 static struct epoll_event *epoll_events;
314 /* set the events that epoll waits for on this fd; helper for set_fd_events */
315 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
317 struct epoll_event ev;
318 int ctl;
320 if (epoll_fd == -1) return;
322 if (events == -1) /* stop waiting on this fd completely */
324 if (pollfd[user].fd == -1) return; /* already removed */
325 ctl = EPOLL_CTL_DEL;
327 else if (pollfd[user].fd == -1)
329 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
330 ctl = EPOLL_CTL_ADD;
332 else
334 if (pollfd[user].events == events) return; /* nothing to do */
335 ctl = EPOLL_CTL_MOD;
338 ev.events = events;
339 ev.data.u32 = user;
341 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
343 if (errno == ENOMEM) /* not enough memory, give up on epoll */
345 close( epoll_fd );
346 epoll_fd = -1;
348 else perror( "epoll_ctl" ); /* should not happen */
352 #else /* USE_EPOLL */
354 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
358 #endif /* USE_EPOLL */
361 /* add a user in the poll array and return its index, or -1 on failure */
362 static int add_poll_user( struct fd *fd )
364 int ret;
365 if (freelist)
367 ret = freelist - poll_users;
368 freelist = (struct fd **)poll_users[ret];
370 else
372 if (nb_users == allocated_users)
374 struct fd **newusers;
375 struct pollfd *newpoll;
376 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
377 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
378 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
380 if (allocated_users)
381 poll_users = newusers;
382 else
383 free( newusers );
384 return -1;
386 poll_users = newusers;
387 pollfd = newpoll;
388 #ifdef USE_EPOLL
389 if (!allocated_users) epoll_fd = epoll_create( new_count );
390 if (epoll_fd != -1)
392 struct epoll_event *new_events;
393 if (!(new_events = realloc( epoll_events, new_count * sizeof(*epoll_events) )))
394 return -1;
395 epoll_events = new_events;
397 #endif
398 allocated_users = new_count;
400 ret = nb_users++;
402 pollfd[ret].fd = -1;
403 pollfd[ret].events = 0;
404 pollfd[ret].revents = 0;
405 poll_users[ret] = fd;
406 active_users++;
407 return ret;
410 /* remove a user from the poll list */
411 static void remove_poll_user( struct fd *fd, int user )
413 assert( user >= 0 );
414 assert( poll_users[user] == fd );
416 #ifdef USE_EPOLL
417 if (epoll_fd != -1 && pollfd[user].fd != -1)
419 struct epoll_event dummy;
420 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
422 #endif
423 pollfd[user].fd = -1;
424 pollfd[user].events = 0;
425 pollfd[user].revents = 0;
426 poll_users[user] = (struct fd *)freelist;
427 freelist = &poll_users[user];
428 active_users--;
431 /* process pending timeouts and return the time until the next timeout, in milliseconds */
432 static int get_next_timeout(void)
434 if (!list_empty( &timeout_list ))
436 struct list expired_list, *ptr;
437 struct timeval now;
439 gettimeofday( &now, NULL );
441 /* first remove all expired timers from the list */
443 list_init( &expired_list );
444 while ((ptr = list_head( &timeout_list )) != NULL)
446 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
448 if (!time_before( &now, &timeout->when ))
450 list_remove( &timeout->entry );
451 list_add_tail( &expired_list, &timeout->entry );
453 else break;
456 /* now call the callback for all the removed timers */
458 while ((ptr = list_head( &expired_list )) != NULL)
460 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
461 list_remove( &timeout->entry );
462 timeout->callback( timeout->private );
463 free( timeout );
466 if ((ptr = list_head( &timeout_list )) != NULL)
468 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
469 int diff = (timeout->when.tv_sec - now.tv_sec) * 1000
470 + (timeout->when.tv_usec - now.tv_usec) / 1000;
471 if (diff < 0) diff = 0;
472 return diff;
475 return -1; /* no pending timeouts */
478 /* server main poll() loop */
479 void main_loop(void)
481 int i, ret, timeout;
483 #ifdef USE_EPOLL
484 assert( POLLIN == EPOLLIN );
485 assert( POLLOUT == EPOLLOUT );
486 assert( POLLERR == EPOLLERR );
487 assert( POLLHUP == EPOLLHUP );
489 if (epoll_fd != -1)
491 while (active_users)
493 timeout = get_next_timeout();
495 if (!active_users) break; /* last user removed by a timeout */
496 if (epoll_fd == -1) break; /* an error occurred with epoll */
498 ret = epoll_wait( epoll_fd, epoll_events, allocated_users, timeout );
500 /* put the events into the pollfd array first, like poll does */
501 for (i = 0; i < ret; i++)
503 int user = epoll_events[i].data.u32;
504 pollfd[user].revents = epoll_events[i].events;
507 /* read events from the pollfd array, as set_fd_events may modify them */
508 for (i = 0; i < ret; i++)
510 int user = epoll_events[i].data.u32;
511 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
515 /* fall through to normal poll loop */
516 #endif /* USE_EPOLL */
518 while (active_users)
520 timeout = get_next_timeout();
522 if (!active_users) break; /* last user removed by a timeout */
524 ret = poll( pollfd, nb_users, timeout );
525 if (ret > 0)
527 for (i = 0; i < nb_users; i++)
529 if (pollfd[i].revents)
531 fd_poll_event( poll_users[i], pollfd[i].revents );
532 if (!--ret) break;
540 /****************************************************************/
541 /* inode functions */
543 #define HASH_SIZE 37
545 static struct list inode_hash[HASH_SIZE];
547 /* close all pending file descriptors in the closed list */
548 static void inode_close_pending( struct inode *inode )
550 struct list *ptr = list_head( &inode->closed );
552 while (ptr)
554 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
555 struct list *next = list_next( &inode->closed, ptr );
557 if (fd->fd != -1)
559 close( fd->fd );
560 fd->fd = -1;
562 if (!fd->unlink) /* get rid of it unless there's an unlink pending on that file */
564 list_remove( ptr );
565 free( fd );
567 ptr = next;
572 static void inode_dump( struct object *obj, int verbose )
574 struct inode *inode = (struct inode *)obj;
575 fprintf( stderr, "Inode dev=" );
576 DUMP_LONG_LONG( inode->dev );
577 fprintf( stderr, " ino=" );
578 DUMP_LONG_LONG( inode->ino );
579 fprintf( stderr, "\n" );
582 static void inode_destroy( struct object *obj )
584 struct inode *inode = (struct inode *)obj;
585 struct list *ptr;
587 assert( list_empty(&inode->open) );
588 assert( list_empty(&inode->locks) );
590 list_remove( &inode->entry );
592 while ((ptr = list_head( &inode->closed )))
594 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
595 list_remove( ptr );
596 if (fd->fd != -1) close( fd->fd );
597 if (fd->unlink[0])
599 /* make sure it is still the same file */
600 struct stat st;
601 if (!stat( fd->unlink, &st ) && st.st_dev == inode->dev && st.st_ino == inode->ino)
603 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
604 else unlink( fd->unlink );
607 free( fd );
611 /* retrieve the inode object for a given fd, creating it if needed */
612 static struct inode *get_inode( dev_t dev, ino_t ino )
614 struct list *ptr;
615 struct inode *inode;
616 unsigned int hash = (dev ^ ino) % HASH_SIZE;
618 if (inode_hash[hash].next)
620 LIST_FOR_EACH( ptr, &inode_hash[hash] )
622 inode = LIST_ENTRY( ptr, struct inode, entry );
623 if (inode->dev == dev && inode->ino == ino)
624 return (struct inode *)grab_object( inode );
627 else list_init( &inode_hash[hash] );
629 /* not found, create it */
630 if ((inode = alloc_object( &inode_ops )))
632 inode->hash = hash;
633 inode->dev = dev;
634 inode->ino = ino;
635 list_init( &inode->open );
636 list_init( &inode->locks );
637 list_init( &inode->closed );
638 list_add_head( &inode_hash[hash], &inode->entry );
640 return inode;
643 /* add fd to the indoe list of file descriptors to close */
644 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
646 if (!list_empty( &inode->locks ))
648 list_add_head( &inode->closed, &fd->entry );
650 else if (fd->unlink[0]) /* close the fd but keep the structure around for unlink */
652 close( fd->fd );
653 fd->fd = -1;
654 list_add_head( &inode->closed, &fd->entry );
656 else /* no locks on this inode and no unlink, get rid of the fd */
658 close( fd->fd );
659 free( fd );
664 /****************************************************************/
665 /* file lock functions */
667 static void file_lock_dump( struct object *obj, int verbose )
669 struct file_lock *lock = (struct file_lock *)obj;
670 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
671 lock->shared ? "shared" : "excl", lock->fd, lock->process );
672 DUMP_LONG_LONG( lock->start );
673 fprintf( stderr, " end=" );
674 DUMP_LONG_LONG( lock->end );
675 fprintf( stderr, "\n" );
678 static int file_lock_signaled( struct object *obj, struct thread *thread )
680 struct file_lock *lock = (struct file_lock *)obj;
681 /* lock is signaled if it has lost its owner */
682 return !lock->process;
685 /* set (or remove) a Unix lock if possible for the given range */
686 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
688 struct flock fl;
690 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
691 for (;;)
693 if (start == end) return 1; /* can't set zero-byte lock */
694 if (start > max_unix_offset) return 1; /* ignore it */
695 fl.l_type = type;
696 fl.l_whence = SEEK_SET;
697 fl.l_start = start;
698 if (!end || end > max_unix_offset) fl.l_len = 0;
699 else fl.l_len = end - start;
700 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
702 switch(errno)
704 case EACCES:
705 /* check whether locks work at all on this file system */
706 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
708 set_error( STATUS_FILE_LOCK_CONFLICT );
709 return 0;
711 /* fall through */
712 case EIO:
713 case ENOLCK:
714 /* no locking on this fs, just ignore it */
715 fd->fs_locks = 0;
716 return 1;
717 case EAGAIN:
718 set_error( STATUS_FILE_LOCK_CONFLICT );
719 return 0;
720 case EBADF:
721 /* this can happen if we try to set a write lock on a read-only file */
722 /* we just ignore that error */
723 if (fl.l_type == F_WRLCK) return 1;
724 set_error( STATUS_ACCESS_DENIED );
725 return 0;
726 #ifdef EOVERFLOW
727 case EOVERFLOW:
728 #endif
729 case EINVAL:
730 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
731 /* in that case we shrink the limit and retry */
732 if (max_unix_offset > INT_MAX)
734 max_unix_offset = INT_MAX;
735 break; /* retry */
737 /* fall through */
738 default:
739 file_set_error();
740 return 0;
745 /* check if interval [start;end) overlaps the lock */
746 inline static int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
748 if (lock->end && start >= lock->end) return 0;
749 if (end && lock->start >= end) return 0;
750 return 1;
753 /* remove Unix locks for all bytes in the specified area that are no longer locked */
754 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
756 struct hole
758 struct hole *next;
759 struct hole *prev;
760 file_pos_t start;
761 file_pos_t end;
762 } *first, *cur, *next, *buffer;
764 struct list *ptr;
765 int count = 0;
767 if (!fd->inode) return;
768 if (!fd->fs_locks) return;
769 if (start == end || start > max_unix_offset) return;
770 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
772 /* count the number of locks overlapping the specified area */
774 LIST_FOR_EACH( ptr, &fd->inode->locks )
776 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
777 if (lock->start == lock->end) continue;
778 if (lock_overlaps( lock, start, end )) count++;
781 if (!count) /* no locks at all, we can unlock everything */
783 set_unix_lock( fd, start, end, F_UNLCK );
784 return;
787 /* allocate space for the list of holes */
788 /* max. number of holes is number of locks + 1 */
790 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
791 first = buffer;
792 first->next = NULL;
793 first->prev = NULL;
794 first->start = start;
795 first->end = end;
796 next = first + 1;
798 /* build a sorted list of unlocked holes in the specified area */
800 LIST_FOR_EACH( ptr, &fd->inode->locks )
802 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
803 if (lock->start == lock->end) continue;
804 if (!lock_overlaps( lock, start, end )) continue;
806 /* go through all the holes touched by this lock */
807 for (cur = first; cur; cur = cur->next)
809 if (cur->end <= lock->start) continue; /* hole is before start of lock */
810 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
812 /* now we know that lock is overlapping hole */
814 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
816 cur->start = lock->end;
817 if (cur->start && cur->start < cur->end) break; /* done with this lock */
818 /* now hole is empty, remove it */
819 if (cur->next) cur->next->prev = cur->prev;
820 if (cur->prev) cur->prev->next = cur->next;
821 else if (!(first = cur->next)) goto done; /* no more holes at all */
823 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
825 cur->end = lock->start;
826 assert( cur->start < cur->end );
828 else /* lock is in the middle of hole, split hole in two */
830 next->prev = cur;
831 next->next = cur->next;
832 cur->next = next;
833 next->start = lock->end;
834 next->end = cur->end;
835 cur->end = lock->start;
836 assert( next->start < next->end );
837 assert( cur->end < next->start );
838 next++;
839 break; /* done with this lock */
844 /* clear Unix locks for all the holes */
846 for (cur = first; cur; cur = cur->next)
847 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
849 done:
850 free( buffer );
853 /* create a new lock on a fd */
854 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
856 struct file_lock *lock;
858 if (!fd->inode) /* not a regular file */
860 set_error( STATUS_INVALID_HANDLE );
861 return NULL;
864 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
865 lock->shared = shared;
866 lock->start = start;
867 lock->end = end;
868 lock->fd = fd;
869 lock->process = current->process;
871 /* now try to set a Unix lock */
872 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
874 release_object( lock );
875 return NULL;
877 list_add_head( &fd->locks, &lock->fd_entry );
878 list_add_head( &fd->inode->locks, &lock->inode_entry );
879 list_add_head( &lock->process->locks, &lock->proc_entry );
880 return lock;
883 /* remove an existing lock */
884 static void remove_lock( struct file_lock *lock, int remove_unix )
886 struct inode *inode = lock->fd->inode;
888 list_remove( &lock->fd_entry );
889 list_remove( &lock->inode_entry );
890 list_remove( &lock->proc_entry );
891 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
892 if (list_empty( &inode->locks )) inode_close_pending( inode );
893 lock->process = NULL;
894 wake_up( &lock->obj, 0 );
895 release_object( lock );
898 /* remove all locks owned by a given process */
899 void remove_process_locks( struct process *process )
901 struct list *ptr;
903 while ((ptr = list_head( &process->locks )))
905 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
906 remove_lock( lock, 1 ); /* this removes it from the list */
910 /* remove all locks on a given fd */
911 static void remove_fd_locks( struct fd *fd )
913 file_pos_t start = FILE_POS_T_MAX, end = 0;
914 struct list *ptr;
916 while ((ptr = list_head( &fd->locks )))
918 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
919 if (lock->start < start) start = lock->start;
920 if (!lock->end || lock->end > end) end = lock->end - 1;
921 remove_lock( lock, 0 );
923 if (start < end) remove_unix_locks( fd, start, end + 1 );
926 /* add a lock on an fd */
927 /* returns handle to wait on */
928 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
930 struct list *ptr;
931 file_pos_t end = start + count;
933 /* don't allow wrapping locks */
934 if (end && end < start)
936 set_error( STATUS_INVALID_PARAMETER );
937 return 0;
940 /* check if another lock on that file overlaps the area */
941 LIST_FOR_EACH( ptr, &fd->inode->locks )
943 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
944 if (!lock_overlaps( lock, start, end )) continue;
945 if (lock->shared && shared) continue;
946 /* found one */
947 if (!wait)
949 set_error( STATUS_FILE_LOCK_CONFLICT );
950 return 0;
952 set_error( STATUS_PENDING );
953 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
956 /* not found, add it */
957 if (add_lock( fd, shared, start, end )) return 0;
958 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
960 /* Unix lock conflict -> tell client to wait and retry */
961 if (wait) set_error( STATUS_PENDING );
963 return 0;
966 /* remove a lock on an fd */
967 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
969 struct list *ptr;
970 file_pos_t end = start + count;
972 /* find an existing lock with the exact same parameters */
973 LIST_FOR_EACH( ptr, &fd->locks )
975 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
976 if ((lock->start == start) && (lock->end == end))
978 remove_lock( lock, 1 );
979 return;
982 set_error( STATUS_FILE_LOCK_CONFLICT );
986 /****************************************************************/
987 /* asynchronous operations support */
989 struct async
991 struct thread *thread;
992 void *apc;
993 void *user;
994 void *sb;
995 struct timeout_user *timeout;
996 struct list entry;
999 /* notifies client thread of new status of its async request */
1000 /* destroys the server side of it */
1001 static void async_terminate( struct async *async, int status )
1003 thread_queue_apc( async->thread, NULL, async->apc, APC_ASYNC_IO,
1004 1, async->user, async->sb, (void *)status );
1006 if (async->timeout) remove_timeout_user( async->timeout );
1007 async->timeout = NULL;
1008 list_remove( &async->entry );
1009 release_object( async->thread );
1010 free( async );
1013 /* cb for timeout on an async request */
1014 static void async_callback(void *private)
1016 struct async *async = (struct async *)private;
1018 /* fprintf(stderr, "async timeout out %p\n", async); */
1019 async->timeout = NULL;
1020 async_terminate( async, STATUS_TIMEOUT );
1023 /* create an async on a given queue of a fd */
1024 struct async *create_async(struct thread *thread, int* timeout, struct list *queue,
1025 void *io_apc, void *io_user, void* io_sb)
1027 struct async *async = mem_alloc( sizeof(struct async) );
1029 if (!async) return NULL;
1031 async->thread = (struct thread *)grab_object(thread);
1032 async->apc = io_apc;
1033 async->user = io_user;
1034 async->sb = io_sb;
1036 list_add_tail( queue, &async->entry );
1038 if (timeout)
1040 struct timeval when;
1042 gettimeofday( &when, 0 );
1043 add_timeout( &when, *timeout );
1044 async->timeout = add_timeout_user( &when, async_callback, async );
1046 else async->timeout = NULL;
1048 return async;
1051 /* terminate the async operation at the head of the queue */
1052 void async_terminate_head( struct list *queue, int status )
1054 struct list *ptr = list_head( queue );
1055 if (ptr) async_terminate( LIST_ENTRY( ptr, struct async, entry ), status );
1058 /****************************************************************/
1059 /* file descriptor functions */
1061 static void fd_dump( struct object *obj, int verbose )
1063 struct fd *fd = (struct fd *)obj;
1064 fprintf( stderr, "Fd unix_fd=%d user=%p", fd->unix_fd, fd->user );
1065 if (fd->inode) fprintf( stderr, " inode=%p unlink='%s'", fd->inode, fd->closed->unlink );
1066 fprintf( stderr, "\n" );
1069 static void fd_destroy( struct object *obj )
1071 struct fd *fd = (struct fd *)obj;
1073 remove_fd_locks( fd );
1074 list_remove( &fd->inode_entry );
1075 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1076 if (fd->inode)
1078 inode_add_closed_fd( fd->inode, fd->closed );
1079 release_object( fd->inode );
1081 else /* no inode, close it right away */
1083 if (fd->unix_fd != -1) close( fd->unix_fd );
1087 /* set the events that select waits for on this fd */
1088 void set_fd_events( struct fd *fd, int events )
1090 int user = fd->poll_index;
1091 assert( poll_users[user] == fd );
1093 set_fd_epoll_events( fd, user, events );
1095 if (events == -1) /* stop waiting on this fd completely */
1097 pollfd[user].fd = -1;
1098 pollfd[user].events = POLLERR;
1099 pollfd[user].revents = 0;
1101 else if (pollfd[user].fd != -1 || !pollfd[user].events)
1103 pollfd[user].fd = fd->unix_fd;
1104 pollfd[user].events = events;
1108 /* allocate an fd object, without setting the unix fd yet */
1109 struct fd *alloc_fd( const struct fd_ops *fd_user_ops, struct object *user )
1111 struct fd *fd = alloc_object( &fd_ops );
1113 if (!fd) return NULL;
1115 fd->fd_ops = fd_user_ops;
1116 fd->user = user;
1117 fd->inode = NULL;
1118 fd->closed = NULL;
1119 fd->access = 0;
1120 fd->sharing = 0;
1121 fd->unix_fd = -1;
1122 fd->fs_locks = 1;
1123 fd->poll_index = -1;
1124 list_init( &fd->inode_entry );
1125 list_init( &fd->locks );
1127 if ((fd->poll_index = add_poll_user( fd )) == -1)
1129 release_object( fd );
1130 return NULL;
1132 return fd;
1135 /* check if the desired access is possible without violating */
1136 /* the sharing mode of other opens of the same file */
1137 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
1139 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1140 unsigned int existing_access = 0;
1141 int unlink = 0;
1142 struct list *ptr;
1144 /* if access mode is 0, sharing mode is ignored */
1145 if (!access) sharing = existing_sharing;
1146 fd->access = access;
1147 fd->sharing = sharing;
1149 LIST_FOR_EACH( ptr, &fd->inode->open )
1151 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1152 if (fd_ptr != fd)
1154 existing_sharing &= fd_ptr->sharing;
1155 existing_access |= fd_ptr->access;
1156 if (fd_ptr->closed->unlink[0]) unlink = 1;
1160 if ((access & GENERIC_READ) && !(existing_sharing & FILE_SHARE_READ)) return 0;
1161 if ((access & GENERIC_WRITE) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1162 if ((existing_access & GENERIC_READ) && !(sharing & FILE_SHARE_READ)) return 0;
1163 if ((existing_access & GENERIC_WRITE) && !(sharing & FILE_SHARE_WRITE)) return 0;
1164 if (fd->closed->unlink[0] && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1165 if (unlink && !(sharing & FILE_SHARE_DELETE)) return 0;
1166 return 1;
1169 /* open() wrapper using a struct fd */
1170 /* the fd must have been created with alloc_fd */
1171 /* on error the fd object is released */
1172 struct fd *open_fd( struct fd *fd, const char *name, int flags, mode_t *mode,
1173 unsigned int access, unsigned int sharing, unsigned int options )
1175 struct stat st;
1176 struct closed_fd *closed_fd;
1177 const char *unlink_name = "";
1179 assert( fd->unix_fd == -1 );
1181 if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1182 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1184 release_object( fd );
1185 return NULL;
1187 /* create the directory if needed */
1188 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1190 if (mkdir( name, 0777 ) == -1)
1192 if (errno != EEXIST || (flags & O_EXCL))
1194 file_set_error();
1195 release_object( fd );
1196 free( closed_fd );
1197 return NULL;
1200 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1202 if ((fd->unix_fd = open( name, flags & ~O_TRUNC, *mode )) == -1)
1204 file_set_error();
1205 release_object( fd );
1206 free( closed_fd );
1207 return NULL;
1209 closed_fd->fd = fd->unix_fd;
1210 closed_fd->unlink[0] = 0;
1211 fstat( fd->unix_fd, &st );
1212 *mode = st.st_mode;
1214 /* only bother with an inode for normal files and directories */
1215 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1217 struct inode *inode = get_inode( st.st_dev, st.st_ino );
1219 if (!inode)
1221 /* we can close the fd because there are no others open on the same file,
1222 * otherwise we wouldn't have failed to allocate a new inode
1224 goto error;
1226 fd->inode = inode;
1227 fd->closed = closed_fd;
1228 list_add_head( &inode->open, &fd->inode_entry );
1230 /* check directory options */
1231 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1233 release_object( fd );
1234 set_error( STATUS_NOT_A_DIRECTORY );
1235 return NULL;
1237 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1239 release_object( fd );
1240 set_error( STATUS_FILE_IS_A_DIRECTORY );
1241 return NULL;
1243 if (!check_sharing( fd, access, sharing ))
1245 release_object( fd );
1246 set_error( STATUS_SHARING_VIOLATION );
1247 return NULL;
1249 strcpy( closed_fd->unlink, unlink_name );
1250 if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1252 else /* special file */
1254 if (options & FILE_DIRECTORY_FILE)
1256 set_error( STATUS_NOT_A_DIRECTORY );
1257 goto error;
1259 if (unlink_name[0]) /* we can't unlink special files */
1261 set_error( STATUS_INVALID_PARAMETER );
1262 goto error;
1264 free( closed_fd );
1266 return fd;
1268 error:
1269 release_object( fd );
1270 free( closed_fd );
1271 return NULL;
1274 /* create an fd for an anonymous file */
1275 /* if the function fails the unix fd is closed */
1276 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user )
1278 struct fd *fd = alloc_fd( fd_user_ops, user );
1280 if (fd)
1282 fd->unix_fd = unix_fd;
1283 return fd;
1285 close( unix_fd );
1286 return NULL;
1289 /* retrieve the object that is using an fd */
1290 void *get_fd_user( struct fd *fd )
1292 return fd->user;
1295 /* retrieve the unix fd for an object */
1296 int get_unix_fd( struct fd *fd )
1298 return fd->unix_fd;
1301 /* check if two file descriptors point to the same file */
1302 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1304 return fd1->inode == fd2->inode;
1307 /* callback for event happening in the main poll() loop */
1308 void fd_poll_event( struct fd *fd, int event )
1310 return fd->fd_ops->poll_event( fd, event );
1313 /* check if events are pending and if yes return which one(s) */
1314 int check_fd_events( struct fd *fd, int events )
1316 struct pollfd pfd;
1318 pfd.fd = fd->unix_fd;
1319 pfd.events = events;
1320 if (poll( &pfd, 1, 0 ) <= 0) return 0;
1321 return pfd.revents;
1324 /* default add_queue() routine for objects that poll() on an fd */
1325 int default_fd_add_queue( struct object *obj, struct wait_queue_entry *entry )
1327 struct fd *fd = get_obj_fd( obj );
1329 if (!fd) return 0;
1330 if (list_empty( &obj->wait_queue )) /* first on the queue */
1331 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1332 add_queue( obj, entry );
1333 release_object( fd );
1334 return 1;
1337 /* default remove_queue() routine for objects that poll() on an fd */
1338 void default_fd_remove_queue( struct object *obj, struct wait_queue_entry *entry )
1340 struct fd *fd = get_obj_fd( obj );
1342 grab_object( obj );
1343 remove_queue( obj, entry );
1344 if (list_empty( &obj->wait_queue )) /* last on the queue is gone */
1345 set_fd_events( fd, 0 );
1346 release_object( obj );
1347 release_object( fd );
1350 /* default signaled() routine for objects that poll() on an fd */
1351 int default_fd_signaled( struct object *obj, struct thread *thread )
1353 int events, ret;
1354 struct fd *fd = get_obj_fd( obj );
1356 if (fd->inode) return 1; /* regular files are always signaled */
1358 events = fd->fd_ops->get_poll_events( fd );
1359 ret = check_fd_events( fd, events ) != 0;
1361 if (ret)
1362 set_fd_events( fd, 0 ); /* stop waiting on select() if we are signaled */
1363 else if (!list_empty( &obj->wait_queue ))
1364 set_fd_events( fd, events ); /* restart waiting on poll() if we are no longer signaled */
1366 release_object( fd );
1367 return ret;
1370 /* default handler for poll() events */
1371 void default_poll_event( struct fd *fd, int event )
1373 /* an error occurred, stop polling this fd to avoid busy-looping */
1374 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1375 wake_up( fd->user, 0 );
1378 /* default flush() routine */
1379 int no_flush( struct fd *fd, struct event **event )
1381 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1382 return 0;
1385 /* default get_file_info() routine */
1386 int no_get_file_info( struct fd *fd )
1388 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1389 return 0;
1392 /* default queue_async() routine */
1393 void no_queue_async( struct fd *fd, void* apc, void* user, void* io_sb,
1394 int type, int count)
1396 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1399 /* default cancel_async() routine */
1400 void no_cancel_async( struct fd *fd )
1402 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1405 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1406 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1407 unsigned int access )
1409 struct fd *fd = NULL;
1410 struct object *obj;
1412 if ((obj = get_handle_obj( process, handle, access, NULL )))
1414 fd = get_obj_fd( obj );
1415 release_object( obj );
1417 return fd;
1420 /* flush a file buffers */
1421 DECL_HANDLER(flush_file)
1423 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1424 struct event * event = NULL;
1426 if (fd)
1428 fd->fd_ops->flush( fd, &event );
1429 if ( event )
1431 reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1433 release_object( fd );
1437 /* get a Unix fd to access a file */
1438 DECL_HANDLER(get_handle_fd)
1440 struct fd *fd;
1442 reply->fd = -1;
1444 if ((fd = get_handle_fd_obj( current->process, req->handle, req->access )))
1446 int unix_fd = get_handle_unix_fd( current->process, req->handle, req->access );
1447 if (unix_fd != -1) reply->fd = unix_fd;
1448 else if (!get_error())
1450 assert( fd->unix_fd != -1 );
1451 send_client_fd( current->process, fd->unix_fd, req->handle );
1453 reply->flags = fd->fd_ops->get_file_info( fd );
1454 release_object( fd );
1458 /* create / reschedule an async I/O */
1459 DECL_HANDLER(register_async)
1461 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1464 * The queue_async method must do the following:
1466 * 1. Get the async_queue for the request of given type.
1467 * 2. Create a new asynchronous request for the selected queue
1468 * 3. Carry out any operations necessary to adjust the object's poll events
1469 * Usually: set_elect_events (obj, obj->ops->get_poll_events()).
1470 * 4. When the async request is triggered, then send back (with a proper APC)
1471 * the trigger (STATUS_ALERTED) to the thread that posted the request.
1472 * async_destroy() is to be called: it will both notify the sender about
1473 * the trigger and destroy the request by itself
1474 * See also the implementations in file.c, serial.c, and sock.c.
1477 if (fd)
1479 fd->fd_ops->queue_async( fd, req->io_apc, req->io_user, req->io_sb,
1480 req->type, req->count );
1481 release_object( fd );
1485 /* cancels all async I/O */
1486 DECL_HANDLER(cancel_async)
1488 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1489 if (fd)
1491 /* Note: we don't kill the queued APC_ASYNC_IO on this thread because
1492 * NtCancelIoFile() will force the pending APC to be run. Since,
1493 * Windows only guarantees that the current thread will have no async
1494 * operation on the current fd when NtCancelIoFile returns, this shall
1495 * do the work.
1497 fd->fd_ops->cancel_async( fd );
1498 release_object( fd );