- use interfaces rather than internal functions
[wine/multimedia.git] / server / fd.c
blobafd1ddb1942b3dc5dc22d3f290d926e9fc0229de
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 "winternl.h"
56 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
57 # include <sys/epoll.h>
58 # define USE_EPOLL
59 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
60 # define USE_EPOLL
61 # define EPOLLIN POLLIN
62 # define EPOLLOUT POLLOUT
63 # define EPOLLERR POLLERR
64 # define EPOLLHUP POLLHUP
65 # define EPOLL_CTL_ADD 1
66 # define EPOLL_CTL_DEL 2
67 # define EPOLL_CTL_MOD 3
69 typedef union epoll_data
71 void *ptr;
72 int fd;
73 uint32_t u32;
74 uint64_t u64;
75 } epoll_data_t;
77 struct epoll_event
79 uint32_t events;
80 epoll_data_t data;
83 #define SYSCALL_RET(ret) do { \
84 if (ret < 0) { errno = -ret; ret = -1; } \
85 return ret; \
86 } while(0)
88 static inline int epoll_create( int size )
90 int ret;
91 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
92 : "=a" (ret) : "0" (254 /*NR_epoll_create*/), "r" (size) );
93 SYSCALL_RET(ret);
96 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
98 int ret;
99 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
100 : "=a" (ret)
101 : "0" (255 /*NR_epoll_ctl*/), "r" (epfd), "c" (op), "d" (fd), "S" (event), "m" (*event) );
102 SYSCALL_RET(ret);
105 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
107 int ret;
108 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
109 : "=a" (ret)
110 : "0" (256 /*NR_epoll_wait*/), "r" (epfd), "c" (events), "d" (maxevents), "S" (timeout)
111 : "memory" );
112 SYSCALL_RET(ret);
114 #undef SYSCALL_RET
116 #endif /* linux && __i386__ && HAVE_STDINT_H */
119 /* Because of the stupid Posix locking semantics, we need to keep
120 * track of all file descriptors referencing a given file, and not
121 * close a single one until all the locks are gone (sigh).
124 /* file descriptor object */
126 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
127 struct closed_fd
129 struct list entry; /* entry in inode closed list */
130 int fd; /* the unix file descriptor */
131 char unlink[1]; /* name to unlink on close (if any) */
134 struct fd
136 struct object obj; /* object header */
137 const struct fd_ops *fd_ops; /* file descriptor operations */
138 struct inode *inode; /* inode that this fd belongs to */
139 struct list inode_entry; /* entry in inode fd list */
140 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
141 struct object *user; /* object using this file descriptor */
142 struct list locks; /* list of locks on this fd */
143 unsigned int access; /* file access (GENERIC_READ/WRITE) */
144 unsigned int sharing; /* file sharing mode */
145 int unix_fd; /* unix file descriptor */
146 int fs_locks; /* can we use filesystem locks for this fd? */
147 int poll_index; /* index of fd in poll array */
148 struct list read_q; /* async readers of this fd */
149 struct list write_q; /* async writers of this fd */
152 static void fd_dump( struct object *obj, int verbose );
153 static void fd_destroy( struct object *obj );
155 static const struct object_ops fd_ops =
157 sizeof(struct fd), /* size */
158 fd_dump, /* dump */
159 no_add_queue, /* add_queue */
160 NULL, /* remove_queue */
161 NULL, /* signaled */
162 NULL, /* satisfied */
163 no_signal, /* signal */
164 no_get_fd, /* get_fd */
165 no_close_handle, /* close_handle */
166 fd_destroy /* destroy */
169 /* inode object */
171 struct inode
173 struct object obj; /* object header */
174 struct list entry; /* inode hash list entry */
175 unsigned int hash; /* hashing code */
176 dev_t dev; /* device number */
177 ino_t ino; /* inode number */
178 struct list open; /* list of open file descriptors */
179 struct list locks; /* list of file locks */
180 struct list closed; /* list of file descriptors to close at destroy time */
183 static void inode_dump( struct object *obj, int verbose );
184 static void inode_destroy( struct object *obj );
186 static const struct object_ops inode_ops =
188 sizeof(struct inode), /* size */
189 inode_dump, /* dump */
190 no_add_queue, /* add_queue */
191 NULL, /* remove_queue */
192 NULL, /* signaled */
193 NULL, /* satisfied */
194 no_signal, /* signal */
195 no_get_fd, /* get_fd */
196 no_close_handle, /* close_handle */
197 inode_destroy /* destroy */
200 /* file lock object */
202 struct file_lock
204 struct object obj; /* object header */
205 struct fd *fd; /* fd owning this lock */
206 struct list fd_entry; /* entry in list of locks on a given fd */
207 struct list inode_entry; /* entry in inode list of locks */
208 int shared; /* shared lock? */
209 file_pos_t start; /* locked region is interval [start;end) */
210 file_pos_t end;
211 struct process *process; /* process owning this lock */
212 struct list proc_entry; /* entry in list of locks owned by the process */
215 static void file_lock_dump( struct object *obj, int verbose );
216 static int file_lock_signaled( struct object *obj, struct thread *thread );
218 static const struct object_ops file_lock_ops =
220 sizeof(struct file_lock), /* size */
221 file_lock_dump, /* dump */
222 add_queue, /* add_queue */
223 remove_queue, /* remove_queue */
224 file_lock_signaled, /* signaled */
225 no_satisfied, /* satisfied */
226 no_signal, /* signal */
227 no_get_fd, /* get_fd */
228 no_close_handle, /* close_handle */
229 no_destroy /* destroy */
233 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
234 #define FILE_POS_T_MAX (~(file_pos_t)0)
236 static file_pos_t max_unix_offset = OFF_T_MAX;
238 #define DUMP_LONG_LONG(val) do { \
239 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
240 fprintf( stderr, "%lx%08lx", (unsigned long)((val) >> 32), (unsigned long)(val) ); \
241 else \
242 fprintf( stderr, "%lx", (unsigned long)(val) ); \
243 } while (0)
247 /****************************************************************/
248 /* timeouts support */
250 struct timeout_user
252 struct list entry; /* entry in sorted timeout list */
253 struct timeval when; /* timeout expiry (absolute time) */
254 timeout_callback callback; /* callback function */
255 void *private; /* callback private data */
258 static struct list timeout_list = LIST_INIT(timeout_list); /* sorted timeouts list */
260 /* add a timeout user */
261 struct timeout_user *add_timeout_user( const struct timeval *when, timeout_callback func,
262 void *private )
264 struct timeout_user *user;
265 struct list *ptr;
267 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
268 user->when = *when;
269 user->callback = func;
270 user->private = private;
272 /* Now insert it in the linked list */
274 LIST_FOR_EACH( ptr, &timeout_list )
276 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
277 if (!time_before( &timeout->when, when )) break;
279 list_add_before( ptr, &user->entry );
280 return user;
283 /* remove a timeout user */
284 void remove_timeout_user( struct timeout_user *user )
286 list_remove( &user->entry );
287 free( user );
290 /* add a timeout in milliseconds to an absolute time */
291 void add_timeout( struct timeval *when, int timeout )
293 if (timeout)
295 long sec = timeout / 1000;
296 if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
298 when->tv_usec -= 1000000;
299 when->tv_sec++;
301 when->tv_sec += sec;
306 /****************************************************************/
307 /* poll support */
309 static struct fd **poll_users; /* users array */
310 static struct pollfd *pollfd; /* poll fd array */
311 static int nb_users; /* count of array entries actually in use */
312 static int active_users; /* current number of active users */
313 static int allocated_users; /* count of allocated entries in the array */
314 static struct fd **freelist; /* list of free entries in the array */
316 #ifdef USE_EPOLL
318 static int epoll_fd;
319 static struct epoll_event *epoll_events;
321 /* set the events that epoll waits for on this fd; helper for set_fd_events */
322 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
324 struct epoll_event ev;
325 int ctl;
327 if (epoll_fd == -1) return;
329 if (events == -1) /* stop waiting on this fd completely */
331 if (pollfd[user].fd == -1) return; /* already removed */
332 ctl = EPOLL_CTL_DEL;
334 else if (pollfd[user].fd == -1)
336 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
337 ctl = EPOLL_CTL_ADD;
339 else
341 if (pollfd[user].events == events) return; /* nothing to do */
342 ctl = EPOLL_CTL_MOD;
345 ev.events = events;
346 ev.data.u32 = user;
348 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
350 if (errno == ENOMEM) /* not enough memory, give up on epoll */
352 close( epoll_fd );
353 epoll_fd = -1;
355 else perror( "epoll_ctl" ); /* should not happen */
359 #else /* USE_EPOLL */
361 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
365 #endif /* USE_EPOLL */
368 /* add a user in the poll array and return its index, or -1 on failure */
369 static int add_poll_user( struct fd *fd )
371 int ret;
372 if (freelist)
374 ret = freelist - poll_users;
375 freelist = (struct fd **)poll_users[ret];
377 else
379 if (nb_users == allocated_users)
381 struct fd **newusers;
382 struct pollfd *newpoll;
383 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
384 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
385 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
387 if (allocated_users)
388 poll_users = newusers;
389 else
390 free( newusers );
391 return -1;
393 poll_users = newusers;
394 pollfd = newpoll;
395 #ifdef USE_EPOLL
396 if (!allocated_users) epoll_fd = epoll_create( new_count );
397 if (epoll_fd != -1)
399 struct epoll_event *new_events;
400 if (!(new_events = realloc( epoll_events, new_count * sizeof(*epoll_events) )))
401 return -1;
402 epoll_events = new_events;
404 #endif
405 allocated_users = new_count;
407 ret = nb_users++;
409 pollfd[ret].fd = -1;
410 pollfd[ret].events = 0;
411 pollfd[ret].revents = 0;
412 poll_users[ret] = fd;
413 active_users++;
414 return ret;
417 /* remove a user from the poll list */
418 static void remove_poll_user( struct fd *fd, int user )
420 assert( user >= 0 );
421 assert( poll_users[user] == fd );
423 #ifdef USE_EPOLL
424 if (epoll_fd != -1 && pollfd[user].fd != -1)
426 struct epoll_event dummy;
427 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
429 #endif
430 pollfd[user].fd = -1;
431 pollfd[user].events = 0;
432 pollfd[user].revents = 0;
433 poll_users[user] = (struct fd *)freelist;
434 freelist = &poll_users[user];
435 active_users--;
438 /* process pending timeouts and return the time until the next timeout, in milliseconds */
439 static int get_next_timeout(void)
441 if (!list_empty( &timeout_list ))
443 struct list expired_list, *ptr;
444 struct timeval now;
446 gettimeofday( &now, NULL );
448 /* first remove all expired timers from the list */
450 list_init( &expired_list );
451 while ((ptr = list_head( &timeout_list )) != NULL)
453 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
455 if (!time_before( &now, &timeout->when ))
457 list_remove( &timeout->entry );
458 list_add_tail( &expired_list, &timeout->entry );
460 else break;
463 /* now call the callback for all the removed timers */
465 while ((ptr = list_head( &expired_list )) != NULL)
467 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
468 list_remove( &timeout->entry );
469 timeout->callback( timeout->private );
470 free( timeout );
473 if ((ptr = list_head( &timeout_list )) != NULL)
475 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
476 int diff = (timeout->when.tv_sec - now.tv_sec) * 1000
477 + (timeout->when.tv_usec - now.tv_usec) / 1000;
478 if (diff < 0) diff = 0;
479 return diff;
482 return -1; /* no pending timeouts */
485 /* server main poll() loop */
486 void main_loop(void)
488 int i, ret, timeout;
490 #ifdef USE_EPOLL
491 assert( POLLIN == EPOLLIN );
492 assert( POLLOUT == EPOLLOUT );
493 assert( POLLERR == EPOLLERR );
494 assert( POLLHUP == EPOLLHUP );
496 if (epoll_fd != -1)
498 while (active_users)
500 timeout = get_next_timeout();
502 if (!active_users) break; /* last user removed by a timeout */
503 if (epoll_fd == -1) break; /* an error occurred with epoll */
505 ret = epoll_wait( epoll_fd, epoll_events, allocated_users, timeout );
507 /* put the events into the pollfd array first, like poll does */
508 for (i = 0; i < ret; i++)
510 int user = epoll_events[i].data.u32;
511 pollfd[user].revents = epoll_events[i].events;
514 /* read events from the pollfd array, as set_fd_events may modify them */
515 for (i = 0; i < ret; i++)
517 int user = epoll_events[i].data.u32;
518 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
522 /* fall through to normal poll loop */
523 #endif /* USE_EPOLL */
525 while (active_users)
527 timeout = get_next_timeout();
529 if (!active_users) break; /* last user removed by a timeout */
531 ret = poll( pollfd, nb_users, timeout );
532 if (ret > 0)
534 for (i = 0; i < nb_users; i++)
536 if (pollfd[i].revents)
538 fd_poll_event( poll_users[i], pollfd[i].revents );
539 if (!--ret) break;
547 /****************************************************************/
548 /* inode functions */
550 #define HASH_SIZE 37
552 static struct list inode_hash[HASH_SIZE];
554 /* close all pending file descriptors in the closed list */
555 static void inode_close_pending( struct inode *inode )
557 struct list *ptr = list_head( &inode->closed );
559 while (ptr)
561 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
562 struct list *next = list_next( &inode->closed, ptr );
564 if (fd->fd != -1)
566 close( fd->fd );
567 fd->fd = -1;
569 if (!fd->unlink) /* get rid of it unless there's an unlink pending on that file */
571 list_remove( ptr );
572 free( fd );
574 ptr = next;
579 static void inode_dump( struct object *obj, int verbose )
581 struct inode *inode = (struct inode *)obj;
582 fprintf( stderr, "Inode dev=" );
583 DUMP_LONG_LONG( inode->dev );
584 fprintf( stderr, " ino=" );
585 DUMP_LONG_LONG( inode->ino );
586 fprintf( stderr, "\n" );
589 static void inode_destroy( struct object *obj )
591 struct inode *inode = (struct inode *)obj;
592 struct list *ptr;
594 assert( list_empty(&inode->open) );
595 assert( list_empty(&inode->locks) );
597 list_remove( &inode->entry );
599 while ((ptr = list_head( &inode->closed )))
601 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
602 list_remove( ptr );
603 if (fd->fd != -1) close( fd->fd );
604 if (fd->unlink[0])
606 /* make sure it is still the same file */
607 struct stat st;
608 if (!stat( fd->unlink, &st ) && st.st_dev == inode->dev && st.st_ino == inode->ino)
610 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
611 else unlink( fd->unlink );
614 free( fd );
618 /* retrieve the inode object for a given fd, creating it if needed */
619 static struct inode *get_inode( dev_t dev, ino_t ino )
621 struct list *ptr;
622 struct inode *inode;
623 unsigned int hash = (dev ^ ino) % HASH_SIZE;
625 if (inode_hash[hash].next)
627 LIST_FOR_EACH( ptr, &inode_hash[hash] )
629 inode = LIST_ENTRY( ptr, struct inode, entry );
630 if (inode->dev == dev && inode->ino == ino)
631 return (struct inode *)grab_object( inode );
634 else list_init( &inode_hash[hash] );
636 /* not found, create it */
637 if ((inode = alloc_object( &inode_ops )))
639 inode->hash = hash;
640 inode->dev = dev;
641 inode->ino = ino;
642 list_init( &inode->open );
643 list_init( &inode->locks );
644 list_init( &inode->closed );
645 list_add_head( &inode_hash[hash], &inode->entry );
647 return inode;
650 /* add fd to the indoe list of file descriptors to close */
651 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
653 if (!list_empty( &inode->locks ))
655 list_add_head( &inode->closed, &fd->entry );
657 else if (fd->unlink[0]) /* close the fd but keep the structure around for unlink */
659 close( fd->fd );
660 fd->fd = -1;
661 list_add_head( &inode->closed, &fd->entry );
663 else /* no locks on this inode and no unlink, get rid of the fd */
665 close( fd->fd );
666 free( fd );
671 /****************************************************************/
672 /* file lock functions */
674 static void file_lock_dump( struct object *obj, int verbose )
676 struct file_lock *lock = (struct file_lock *)obj;
677 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
678 lock->shared ? "shared" : "excl", lock->fd, lock->process );
679 DUMP_LONG_LONG( lock->start );
680 fprintf( stderr, " end=" );
681 DUMP_LONG_LONG( lock->end );
682 fprintf( stderr, "\n" );
685 static int file_lock_signaled( struct object *obj, struct thread *thread )
687 struct file_lock *lock = (struct file_lock *)obj;
688 /* lock is signaled if it has lost its owner */
689 return !lock->process;
692 /* set (or remove) a Unix lock if possible for the given range */
693 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
695 struct flock fl;
697 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
698 for (;;)
700 if (start == end) return 1; /* can't set zero-byte lock */
701 if (start > max_unix_offset) return 1; /* ignore it */
702 fl.l_type = type;
703 fl.l_whence = SEEK_SET;
704 fl.l_start = start;
705 if (!end || end > max_unix_offset) fl.l_len = 0;
706 else fl.l_len = end - start;
707 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
709 switch(errno)
711 case EACCES:
712 /* check whether locks work at all on this file system */
713 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
715 set_error( STATUS_FILE_LOCK_CONFLICT );
716 return 0;
718 /* fall through */
719 case EIO:
720 case ENOLCK:
721 /* no locking on this fs, just ignore it */
722 fd->fs_locks = 0;
723 return 1;
724 case EAGAIN:
725 set_error( STATUS_FILE_LOCK_CONFLICT );
726 return 0;
727 case EBADF:
728 /* this can happen if we try to set a write lock on a read-only file */
729 /* we just ignore that error */
730 if (fl.l_type == F_WRLCK) return 1;
731 set_error( STATUS_ACCESS_DENIED );
732 return 0;
733 #ifdef EOVERFLOW
734 case EOVERFLOW:
735 #endif
736 case EINVAL:
737 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
738 /* in that case we shrink the limit and retry */
739 if (max_unix_offset > INT_MAX)
741 max_unix_offset = INT_MAX;
742 break; /* retry */
744 /* fall through */
745 default:
746 file_set_error();
747 return 0;
752 /* check if interval [start;end) overlaps the lock */
753 inline static int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
755 if (lock->end && start >= lock->end) return 0;
756 if (end && lock->start >= end) return 0;
757 return 1;
760 /* remove Unix locks for all bytes in the specified area that are no longer locked */
761 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
763 struct hole
765 struct hole *next;
766 struct hole *prev;
767 file_pos_t start;
768 file_pos_t end;
769 } *first, *cur, *next, *buffer;
771 struct list *ptr;
772 int count = 0;
774 if (!fd->inode) return;
775 if (!fd->fs_locks) return;
776 if (start == end || start > max_unix_offset) return;
777 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
779 /* count the number of locks overlapping the specified area */
781 LIST_FOR_EACH( ptr, &fd->inode->locks )
783 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
784 if (lock->start == lock->end) continue;
785 if (lock_overlaps( lock, start, end )) count++;
788 if (!count) /* no locks at all, we can unlock everything */
790 set_unix_lock( fd, start, end, F_UNLCK );
791 return;
794 /* allocate space for the list of holes */
795 /* max. number of holes is number of locks + 1 */
797 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
798 first = buffer;
799 first->next = NULL;
800 first->prev = NULL;
801 first->start = start;
802 first->end = end;
803 next = first + 1;
805 /* build a sorted list of unlocked holes in the specified area */
807 LIST_FOR_EACH( ptr, &fd->inode->locks )
809 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
810 if (lock->start == lock->end) continue;
811 if (!lock_overlaps( lock, start, end )) continue;
813 /* go through all the holes touched by this lock */
814 for (cur = first; cur; cur = cur->next)
816 if (cur->end <= lock->start) continue; /* hole is before start of lock */
817 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
819 /* now we know that lock is overlapping hole */
821 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
823 cur->start = lock->end;
824 if (cur->start && cur->start < cur->end) break; /* done with this lock */
825 /* now hole is empty, remove it */
826 if (cur->next) cur->next->prev = cur->prev;
827 if (cur->prev) cur->prev->next = cur->next;
828 else if (!(first = cur->next)) goto done; /* no more holes at all */
830 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
832 cur->end = lock->start;
833 assert( cur->start < cur->end );
835 else /* lock is in the middle of hole, split hole in two */
837 next->prev = cur;
838 next->next = cur->next;
839 cur->next = next;
840 next->start = lock->end;
841 next->end = cur->end;
842 cur->end = lock->start;
843 assert( next->start < next->end );
844 assert( cur->end < next->start );
845 next++;
846 break; /* done with this lock */
851 /* clear Unix locks for all the holes */
853 for (cur = first; cur; cur = cur->next)
854 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
856 done:
857 free( buffer );
860 /* create a new lock on a fd */
861 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
863 struct file_lock *lock;
865 if (!fd->inode) /* not a regular file */
867 set_error( STATUS_INVALID_HANDLE );
868 return NULL;
871 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
872 lock->shared = shared;
873 lock->start = start;
874 lock->end = end;
875 lock->fd = fd;
876 lock->process = current->process;
878 /* now try to set a Unix lock */
879 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
881 release_object( lock );
882 return NULL;
884 list_add_head( &fd->locks, &lock->fd_entry );
885 list_add_head( &fd->inode->locks, &lock->inode_entry );
886 list_add_head( &lock->process->locks, &lock->proc_entry );
887 return lock;
890 /* remove an existing lock */
891 static void remove_lock( struct file_lock *lock, int remove_unix )
893 struct inode *inode = lock->fd->inode;
895 list_remove( &lock->fd_entry );
896 list_remove( &lock->inode_entry );
897 list_remove( &lock->proc_entry );
898 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
899 if (list_empty( &inode->locks )) inode_close_pending( inode );
900 lock->process = NULL;
901 wake_up( &lock->obj, 0 );
902 release_object( lock );
905 /* remove all locks owned by a given process */
906 void remove_process_locks( struct process *process )
908 struct list *ptr;
910 while ((ptr = list_head( &process->locks )))
912 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
913 remove_lock( lock, 1 ); /* this removes it from the list */
917 /* remove all locks on a given fd */
918 static void remove_fd_locks( struct fd *fd )
920 file_pos_t start = FILE_POS_T_MAX, end = 0;
921 struct list *ptr;
923 while ((ptr = list_head( &fd->locks )))
925 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
926 if (lock->start < start) start = lock->start;
927 if (!lock->end || lock->end > end) end = lock->end - 1;
928 remove_lock( lock, 0 );
930 if (start < end) remove_unix_locks( fd, start, end + 1 );
933 /* add a lock on an fd */
934 /* returns handle to wait on */
935 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
937 struct list *ptr;
938 file_pos_t end = start + count;
940 /* don't allow wrapping locks */
941 if (end && end < start)
943 set_error( STATUS_INVALID_PARAMETER );
944 return 0;
947 /* check if another lock on that file overlaps the area */
948 LIST_FOR_EACH( ptr, &fd->inode->locks )
950 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
951 if (!lock_overlaps( lock, start, end )) continue;
952 if (lock->shared && shared) continue;
953 /* found one */
954 if (!wait)
956 set_error( STATUS_FILE_LOCK_CONFLICT );
957 return 0;
959 set_error( STATUS_PENDING );
960 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
963 /* not found, add it */
964 if (add_lock( fd, shared, start, end )) return 0;
965 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
967 /* Unix lock conflict -> tell client to wait and retry */
968 if (wait) set_error( STATUS_PENDING );
970 return 0;
973 /* remove a lock on an fd */
974 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
976 struct list *ptr;
977 file_pos_t end = start + count;
979 /* find an existing lock with the exact same parameters */
980 LIST_FOR_EACH( ptr, &fd->locks )
982 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
983 if ((lock->start == start) && (lock->end == end))
985 remove_lock( lock, 1 );
986 return;
989 set_error( STATUS_FILE_LOCK_CONFLICT );
993 /****************************************************************/
994 /* asynchronous operations support */
996 struct async
998 struct thread *thread;
999 void *apc;
1000 void *user;
1001 void *sb;
1002 struct timeout_user *timeout;
1003 struct list entry;
1006 /* notifies client thread of new status of its async request */
1007 /* destroys the server side of it */
1008 static void async_terminate( struct async *async, int status )
1010 thread_queue_apc( async->thread, NULL, async->apc, APC_ASYNC_IO,
1011 1, async->user, async->sb, (void *)status );
1013 if (async->timeout) remove_timeout_user( async->timeout );
1014 async->timeout = NULL;
1015 list_remove( &async->entry );
1016 release_object( async->thread );
1017 free( async );
1020 /* cb for timeout on an async request */
1021 static void async_callback(void *private)
1023 struct async *async = (struct async *)private;
1025 /* fprintf(stderr, "async timeout out %p\n", async); */
1026 async->timeout = NULL;
1027 async_terminate( async, STATUS_TIMEOUT );
1030 /* create an async on a given queue of a fd */
1031 struct async *create_async(struct thread *thread, int* timeout, struct list *queue,
1032 void *io_apc, void *io_user, void* io_sb)
1034 struct async *async = mem_alloc( sizeof(struct async) );
1036 if (!async) return NULL;
1038 async->thread = (struct thread *)grab_object(thread);
1039 async->apc = io_apc;
1040 async->user = io_user;
1041 async->sb = io_sb;
1043 list_add_tail( queue, &async->entry );
1045 if (timeout)
1047 struct timeval when;
1049 gettimeofday( &when, NULL );
1050 add_timeout( &when, *timeout );
1051 async->timeout = add_timeout_user( &when, async_callback, async );
1053 else async->timeout = NULL;
1055 return async;
1058 /* terminate the async operation at the head of the queue */
1059 void async_terminate_head( struct list *queue, int status )
1061 struct list *ptr = list_head( queue );
1062 if (ptr) async_terminate( LIST_ENTRY( ptr, struct async, entry ), status );
1065 /****************************************************************/
1066 /* file descriptor functions */
1068 static void fd_dump( struct object *obj, int verbose )
1070 struct fd *fd = (struct fd *)obj;
1071 fprintf( stderr, "Fd unix_fd=%d user=%p", fd->unix_fd, fd->user );
1072 if (fd->inode) fprintf( stderr, " inode=%p unlink='%s'", fd->inode, fd->closed->unlink );
1073 fprintf( stderr, "\n" );
1076 static void fd_destroy( struct object *obj )
1078 struct fd *fd = (struct fd *)obj;
1080 async_terminate_queue( &fd->read_q, STATUS_CANCELLED );
1081 async_terminate_queue( &fd->write_q, STATUS_CANCELLED );
1083 remove_fd_locks( fd );
1084 list_remove( &fd->inode_entry );
1085 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1086 if (fd->inode)
1088 inode_add_closed_fd( fd->inode, fd->closed );
1089 release_object( fd->inode );
1091 else /* no inode, close it right away */
1093 if (fd->unix_fd != -1) close( fd->unix_fd );
1097 /* set the events that select waits for on this fd */
1098 void set_fd_events( struct fd *fd, int events )
1100 int user = fd->poll_index;
1101 assert( poll_users[user] == fd );
1103 set_fd_epoll_events( fd, user, events );
1105 if (events == -1) /* stop waiting on this fd completely */
1107 pollfd[user].fd = -1;
1108 pollfd[user].events = POLLERR;
1109 pollfd[user].revents = 0;
1111 else if (pollfd[user].fd != -1 || !pollfd[user].events)
1113 pollfd[user].fd = fd->unix_fd;
1114 pollfd[user].events = events;
1118 /* allocate an fd object, without setting the unix fd yet */
1119 struct fd *alloc_fd( const struct fd_ops *fd_user_ops, struct object *user )
1121 struct fd *fd = alloc_object( &fd_ops );
1123 if (!fd) return NULL;
1125 fd->fd_ops = fd_user_ops;
1126 fd->user = user;
1127 fd->inode = NULL;
1128 fd->closed = NULL;
1129 fd->access = 0;
1130 fd->sharing = 0;
1131 fd->unix_fd = -1;
1132 fd->fs_locks = 1;
1133 fd->poll_index = -1;
1134 list_init( &fd->inode_entry );
1135 list_init( &fd->locks );
1136 list_init( &fd->read_q );
1137 list_init( &fd->write_q );
1139 if ((fd->poll_index = add_poll_user( fd )) == -1)
1141 release_object( fd );
1142 return NULL;
1144 return fd;
1147 /* check if the desired access is possible without violating */
1148 /* the sharing mode of other opens of the same file */
1149 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
1151 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1152 unsigned int existing_access = 0;
1153 int unlink = 0;
1154 struct list *ptr;
1156 /* if access mode is 0, sharing mode is ignored */
1157 if (!access) sharing = existing_sharing;
1158 fd->access = access;
1159 fd->sharing = sharing;
1161 LIST_FOR_EACH( ptr, &fd->inode->open )
1163 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1164 if (fd_ptr != fd)
1166 existing_sharing &= fd_ptr->sharing;
1167 existing_access |= fd_ptr->access;
1168 if (fd_ptr->closed->unlink[0]) unlink = 1;
1172 if ((access & GENERIC_READ) && !(existing_sharing & FILE_SHARE_READ)) return 0;
1173 if ((access & GENERIC_WRITE) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1174 if ((existing_access & GENERIC_READ) && !(sharing & FILE_SHARE_READ)) return 0;
1175 if ((existing_access & GENERIC_WRITE) && !(sharing & FILE_SHARE_WRITE)) return 0;
1176 if (fd->closed->unlink[0] && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1177 if (unlink && !(sharing & FILE_SHARE_DELETE)) return 0;
1178 return 1;
1181 /* open() wrapper using a struct fd */
1182 /* the fd must have been created with alloc_fd */
1183 /* on error the fd object is released */
1184 struct fd *open_fd( struct fd *fd, const char *name, int flags, mode_t *mode,
1185 unsigned int access, unsigned int sharing, unsigned int options )
1187 struct stat st;
1188 struct closed_fd *closed_fd;
1189 const char *unlink_name = "";
1191 assert( fd->unix_fd == -1 );
1193 if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1194 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1196 release_object( fd );
1197 return NULL;
1199 /* create the directory if needed */
1200 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1202 if (mkdir( name, 0777 ) == -1)
1204 if (errno != EEXIST || (flags & O_EXCL))
1206 file_set_error();
1207 release_object( fd );
1208 free( closed_fd );
1209 return NULL;
1212 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1214 if ((fd->unix_fd = open( name, flags & ~O_TRUNC, *mode )) == -1)
1216 file_set_error();
1217 release_object( fd );
1218 free( closed_fd );
1219 return NULL;
1221 closed_fd->fd = fd->unix_fd;
1222 closed_fd->unlink[0] = 0;
1223 fstat( fd->unix_fd, &st );
1224 *mode = st.st_mode;
1226 /* only bother with an inode for normal files and directories */
1227 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1229 struct inode *inode = get_inode( st.st_dev, st.st_ino );
1231 if (!inode)
1233 /* we can close the fd because there are no others open on the same file,
1234 * otherwise we wouldn't have failed to allocate a new inode
1236 goto error;
1238 fd->inode = inode;
1239 fd->closed = closed_fd;
1240 list_add_head( &inode->open, &fd->inode_entry );
1242 /* check directory options */
1243 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1245 release_object( fd );
1246 set_error( STATUS_NOT_A_DIRECTORY );
1247 return NULL;
1249 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1251 release_object( fd );
1252 set_error( STATUS_FILE_IS_A_DIRECTORY );
1253 return NULL;
1255 if (!check_sharing( fd, access, sharing ))
1257 release_object( fd );
1258 set_error( STATUS_SHARING_VIOLATION );
1259 return NULL;
1261 strcpy( closed_fd->unlink, unlink_name );
1262 if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1264 else /* special file */
1266 if (options & FILE_DIRECTORY_FILE)
1268 set_error( STATUS_NOT_A_DIRECTORY );
1269 goto error;
1271 if (unlink_name[0]) /* we can't unlink special files */
1273 set_error( STATUS_INVALID_PARAMETER );
1274 goto error;
1276 free( closed_fd );
1278 return fd;
1280 error:
1281 release_object( fd );
1282 free( closed_fd );
1283 return NULL;
1286 /* create an fd for an anonymous file */
1287 /* if the function fails the unix fd is closed */
1288 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user )
1290 struct fd *fd = alloc_fd( fd_user_ops, user );
1292 if (fd)
1294 fd->unix_fd = unix_fd;
1295 return fd;
1297 close( unix_fd );
1298 return NULL;
1301 /* retrieve the object that is using an fd */
1302 void *get_fd_user( struct fd *fd )
1304 return fd->user;
1307 /* retrieve the unix fd for an object */
1308 int get_unix_fd( struct fd *fd )
1310 return fd->unix_fd;
1313 /* check if two file descriptors point to the same file */
1314 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1316 return fd1->inode == fd2->inode;
1319 /* callback for event happening in the main poll() loop */
1320 void fd_poll_event( struct fd *fd, int event )
1322 return fd->fd_ops->poll_event( fd, event );
1325 /* check if events are pending and if yes return which one(s) */
1326 int check_fd_events( struct fd *fd, int events )
1328 struct pollfd pfd;
1330 pfd.fd = fd->unix_fd;
1331 pfd.events = events;
1332 if (poll( &pfd, 1, 0 ) <= 0) return 0;
1333 return pfd.revents;
1336 /* default add_queue() routine for objects that poll() on an fd */
1337 int default_fd_add_queue( struct object *obj, struct wait_queue_entry *entry )
1339 struct fd *fd = get_obj_fd( obj );
1341 if (!fd) return 0;
1342 if (list_empty( &obj->wait_queue )) /* first on the queue */
1343 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1344 add_queue( obj, entry );
1345 release_object( fd );
1346 return 1;
1349 /* default remove_queue() routine for objects that poll() on an fd */
1350 void default_fd_remove_queue( struct object *obj, struct wait_queue_entry *entry )
1352 struct fd *fd = get_obj_fd( obj );
1354 grab_object( obj );
1355 remove_queue( obj, entry );
1356 if (list_empty( &obj->wait_queue )) /* last on the queue is gone */
1357 set_fd_events( fd, 0 );
1358 release_object( obj );
1359 release_object( fd );
1362 /* default signaled() routine for objects that poll() on an fd */
1363 int default_fd_signaled( struct object *obj, struct thread *thread )
1365 int events, ret;
1366 struct fd *fd = get_obj_fd( obj );
1368 if (fd->inode) return 1; /* regular files are always signaled */
1370 events = fd->fd_ops->get_poll_events( fd );
1371 ret = check_fd_events( fd, events ) != 0;
1373 if (ret)
1374 set_fd_events( fd, 0 ); /* stop waiting on select() if we are signaled */
1375 else if (!list_empty( &obj->wait_queue ))
1376 set_fd_events( fd, events ); /* restart waiting on poll() if we are no longer signaled */
1378 release_object( fd );
1379 return ret;
1382 int default_fd_get_poll_events( struct fd *fd )
1384 int events = 0;
1386 if (!list_empty( &fd->read_q ))
1387 events |= POLLIN;
1388 if (!list_empty( &fd->write_q ))
1389 events |= POLLOUT;
1391 return events;
1394 /* default handler for poll() events */
1395 void default_poll_event( struct fd *fd, int event )
1397 if (!list_empty( &fd->read_q ) && (POLLIN & event) )
1399 async_terminate_head( &fd->read_q, STATUS_ALERTED );
1400 return;
1402 if (!list_empty( &fd->write_q ) && (POLLOUT & event) )
1404 async_terminate_head( &fd->write_q, STATUS_ALERTED );
1405 return;
1408 /* if an error occurred, stop polling this fd to avoid busy-looping */
1409 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1410 wake_up( fd->user, 0 );
1413 void default_fd_queue_async( struct fd *fd, void *apc, void *user, void *io_sb, int type, int count )
1415 struct list *queue;
1416 int events;
1418 if (!(fd->fd_ops->get_file_info( fd ) & FD_FLAG_OVERLAPPED))
1420 set_error( STATUS_INVALID_HANDLE );
1421 return;
1424 switch (type)
1426 case ASYNC_TYPE_READ:
1427 queue = &fd->read_q;
1428 break;
1429 case ASYNC_TYPE_WRITE:
1430 queue = &fd->write_q;
1431 break;
1432 default:
1433 set_error( STATUS_INVALID_PARAMETER );
1434 return;
1437 if (!create_async( current, NULL, queue, apc, user, io_sb ))
1438 return;
1440 /* Check if the new pending request can be served immediately */
1441 events = check_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1442 if (events) fd->fd_ops->poll_event( fd, events );
1444 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1447 void default_fd_cancel_async( struct fd *fd )
1449 async_terminate_queue( &fd->read_q, STATUS_CANCELLED );
1450 async_terminate_queue( &fd->write_q, STATUS_CANCELLED );
1453 /* default flush() routine */
1454 int no_flush( struct fd *fd, struct event **event )
1456 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1457 return 0;
1460 /* default get_file_info() routine */
1461 int no_get_file_info( struct fd *fd )
1463 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1464 return 0;
1467 /* default queue_async() routine */
1468 void no_queue_async( struct fd *fd, void* apc, void* user, void* io_sb,
1469 int type, int count)
1471 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1474 /* default cancel_async() routine */
1475 void no_cancel_async( struct fd *fd )
1477 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1480 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1481 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1482 unsigned int access )
1484 struct fd *fd = NULL;
1485 struct object *obj;
1487 if ((obj = get_handle_obj( process, handle, access, NULL )))
1489 fd = get_obj_fd( obj );
1490 release_object( obj );
1492 return fd;
1495 /* flush a file buffers */
1496 DECL_HANDLER(flush_file)
1498 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1499 struct event * event = NULL;
1501 if (fd)
1503 fd->fd_ops->flush( fd, &event );
1504 if ( event )
1506 reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1508 release_object( fd );
1512 /* get a Unix fd to access a file */
1513 DECL_HANDLER(get_handle_fd)
1515 struct fd *fd;
1517 reply->fd = -1;
1519 if ((fd = get_handle_fd_obj( current->process, req->handle, req->access )))
1521 int unix_fd = get_handle_unix_fd( current->process, req->handle, req->access );
1522 if (unix_fd != -1) reply->fd = unix_fd;
1523 else if (!get_error())
1525 assert( fd->unix_fd != -1 );
1526 send_client_fd( current->process, fd->unix_fd, req->handle );
1528 reply->flags = fd->fd_ops->get_file_info( fd );
1529 release_object( fd );
1533 /* create / reschedule an async I/O */
1534 DECL_HANDLER(register_async)
1536 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1539 * The queue_async method must do the following:
1541 * 1. Get the async_queue for the request of given type.
1542 * 2. Create a new asynchronous request for the selected queue
1543 * 3. Carry out any operations necessary to adjust the object's poll events
1544 * Usually: set_elect_events (obj, obj->ops->get_poll_events()).
1545 * 4. When the async request is triggered, then send back (with a proper APC)
1546 * the trigger (STATUS_ALERTED) to the thread that posted the request.
1547 * async_destroy() is to be called: it will both notify the sender about
1548 * the trigger and destroy the request by itself
1549 * See also the implementations in file.c, serial.c, and sock.c.
1552 if (fd)
1554 fd->fd_ops->queue_async( fd, req->io_apc, req->io_user, req->io_sb,
1555 req->type, req->count );
1556 release_object( fd );
1560 /* cancels all async I/O */
1561 DECL_HANDLER(cancel_async)
1563 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1564 if (fd)
1566 /* Note: we don't kill the queued APC_ASYNC_IO on this thread because
1567 * NtCancelIoFile() will force the pending APC to be run. Since,
1568 * Windows only guarantees that the current thread will have no async
1569 * operation on the current fd when NtCancelIoFile returns, this shall
1570 * do the work.
1572 fd->fd_ops->cancel_async( fd );
1573 release_object( fd );