Don't mark a file as readonly if it has any write bit set.
[wine/wine-kai.git] / server / fd.c
blob0dcaee7d858fb5a68dc88be4eb6961db2b33ab28
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( struct timeval *when, timeout_callback func, void *private )
256 struct timeout_user *user;
257 struct list *ptr;
259 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
260 user->when = *when;
261 user->callback = func;
262 user->private = private;
264 /* Now insert it in the linked list */
266 LIST_FOR_EACH( ptr, &timeout_list )
268 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
269 if (!time_before( &timeout->when, when )) break;
271 list_add_before( ptr, &user->entry );
272 return user;
275 /* remove a timeout user */
276 void remove_timeout_user( struct timeout_user *user )
278 list_remove( &user->entry );
279 free( user );
282 /* add a timeout in milliseconds to an absolute time */
283 void add_timeout( struct timeval *when, int timeout )
285 if (timeout)
287 long sec = timeout / 1000;
288 if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
290 when->tv_usec -= 1000000;
291 when->tv_sec++;
293 when->tv_sec += sec;
298 /****************************************************************/
299 /* poll support */
301 static struct fd **poll_users; /* users array */
302 static struct pollfd *pollfd; /* poll fd array */
303 static int nb_users; /* count of array entries actually in use */
304 static int active_users; /* current number of active users */
305 static int allocated_users; /* count of allocated entries in the array */
306 static struct fd **freelist; /* list of free entries in the array */
308 #ifdef USE_EPOLL
310 static int epoll_fd;
311 static struct epoll_event *epoll_events;
313 /* set the events that epoll waits for on this fd; helper for set_fd_events */
314 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
316 struct epoll_event ev;
317 int ctl;
319 if (epoll_fd == -1) return;
321 if (events == -1) /* stop waiting on this fd completely */
323 if (pollfd[user].fd == -1) return; /* already removed */
324 ctl = EPOLL_CTL_DEL;
326 else if (pollfd[user].fd == -1)
328 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
329 ctl = EPOLL_CTL_ADD;
331 else
333 if (pollfd[user].events == events) return; /* nothing to do */
334 ctl = EPOLL_CTL_MOD;
337 ev.events = events;
338 ev.data.u32 = user;
340 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
342 if (errno == ENOMEM) /* not enough memory, give up on epoll */
344 close( epoll_fd );
345 epoll_fd = -1;
347 else perror( "epoll_ctl" ); /* should not happen */
351 #else /* USE_EPOLL */
353 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
357 #endif /* USE_EPOLL */
360 /* add a user in the poll array and return its index, or -1 on failure */
361 static int add_poll_user( struct fd *fd )
363 int ret;
364 if (freelist)
366 ret = freelist - poll_users;
367 freelist = (struct fd **)poll_users[ret];
369 else
371 if (nb_users == allocated_users)
373 struct fd **newusers;
374 struct pollfd *newpoll;
375 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
376 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
377 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
379 if (allocated_users)
380 poll_users = newusers;
381 else
382 free( newusers );
383 return -1;
385 poll_users = newusers;
386 pollfd = newpoll;
387 #ifdef USE_EPOLL
388 if (!allocated_users) epoll_fd = epoll_create( new_count );
389 if (epoll_fd != -1)
391 struct epoll_event *new_events;
392 if (!(new_events = realloc( epoll_events, new_count * sizeof(*epoll_events) )))
393 return -1;
394 epoll_events = new_events;
396 #endif
397 allocated_users = new_count;
399 ret = nb_users++;
401 pollfd[ret].fd = -1;
402 pollfd[ret].events = 0;
403 pollfd[ret].revents = 0;
404 poll_users[ret] = fd;
405 active_users++;
406 return ret;
409 /* remove a user from the poll list */
410 static void remove_poll_user( struct fd *fd, int user )
412 assert( user >= 0 );
413 assert( poll_users[user] == fd );
415 #ifdef USE_EPOLL
416 if (epoll_fd != -1 && pollfd[user].fd != -1)
418 struct epoll_event dummy;
419 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
421 #endif
422 pollfd[user].fd = -1;
423 pollfd[user].events = 0;
424 pollfd[user].revents = 0;
425 poll_users[user] = (struct fd *)freelist;
426 freelist = &poll_users[user];
427 active_users--;
430 /* process pending timeouts and return the time until the next timeout, in milliseconds */
431 static int get_next_timeout(void)
433 if (!list_empty( &timeout_list ))
435 struct list expired_list, *ptr;
436 struct timeval now;
438 gettimeofday( &now, NULL );
440 /* first remove all expired timers from the list */
442 list_init( &expired_list );
443 while ((ptr = list_head( &timeout_list )) != NULL)
445 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
447 if (!time_before( &now, &timeout->when ))
449 list_remove( &timeout->entry );
450 list_add_tail( &expired_list, &timeout->entry );
452 else break;
455 /* now call the callback for all the removed timers */
457 while ((ptr = list_head( &expired_list )) != NULL)
459 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
460 list_remove( &timeout->entry );
461 timeout->callback( timeout->private );
462 free( timeout );
465 if ((ptr = list_head( &timeout_list )) != NULL)
467 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
468 int diff = (timeout->when.tv_sec - now.tv_sec) * 1000
469 + (timeout->when.tv_usec - now.tv_usec) / 1000;
470 if (diff < 0) diff = 0;
471 return diff;
474 return -1; /* no pending timeouts */
477 /* server main poll() loop */
478 void main_loop(void)
480 int i, ret, timeout;
482 #ifdef USE_EPOLL
483 assert( POLLIN == EPOLLIN );
484 assert( POLLOUT == EPOLLOUT );
485 assert( POLLERR == EPOLLERR );
486 assert( POLLHUP == EPOLLHUP );
488 if (epoll_fd != -1)
490 while (active_users)
492 timeout = get_next_timeout();
494 if (!active_users) break; /* last user removed by a timeout */
495 if (epoll_fd == -1) break; /* an error occurred with epoll */
497 ret = epoll_wait( epoll_fd, epoll_events, allocated_users, timeout );
499 /* put the events into the pollfd array first, like poll does */
500 for (i = 0; i < ret; i++)
502 int user = epoll_events[i].data.u32;
503 pollfd[user].revents = epoll_events[i].events;
506 /* read events from the pollfd array, as set_fd_events may modify them */
507 for (i = 0; i < ret; i++)
509 int user = epoll_events[i].data.u32;
510 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
514 /* fall through to normal poll loop */
515 #endif /* USE_EPOLL */
517 while (active_users)
519 timeout = get_next_timeout();
521 if (!active_users) break; /* last user removed by a timeout */
523 ret = poll( pollfd, nb_users, timeout );
524 if (ret > 0)
526 for (i = 0; i < nb_users; i++)
528 if (pollfd[i].revents)
530 fd_poll_event( poll_users[i], pollfd[i].revents );
531 if (!--ret) break;
539 /****************************************************************/
540 /* inode functions */
542 #define HASH_SIZE 37
544 static struct list inode_hash[HASH_SIZE];
546 /* close all pending file descriptors in the closed list */
547 static void inode_close_pending( struct inode *inode )
549 struct list *ptr = list_head( &inode->closed );
551 while (ptr)
553 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
554 struct list *next = list_next( &inode->closed, ptr );
556 if (fd->fd != -1)
558 close( fd->fd );
559 fd->fd = -1;
561 if (!fd->unlink) /* get rid of it unless there's an unlink pending on that file */
563 list_remove( ptr );
564 free( fd );
566 ptr = next;
571 static void inode_dump( struct object *obj, int verbose )
573 struct inode *inode = (struct inode *)obj;
574 fprintf( stderr, "Inode dev=" );
575 DUMP_LONG_LONG( inode->dev );
576 fprintf( stderr, " ino=" );
577 DUMP_LONG_LONG( inode->ino );
578 fprintf( stderr, "\n" );
581 static void inode_destroy( struct object *obj )
583 struct inode *inode = (struct inode *)obj;
584 struct list *ptr;
586 assert( list_empty(&inode->open) );
587 assert( list_empty(&inode->locks) );
589 list_remove( &inode->entry );
591 while ((ptr = list_head( &inode->closed )))
593 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
594 list_remove( ptr );
595 if (fd->fd != -1) close( fd->fd );
596 if (fd->unlink[0])
598 /* make sure it is still the same file */
599 struct stat st;
600 if (!stat( fd->unlink, &st ) && st.st_dev == inode->dev && st.st_ino == inode->ino)
602 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
603 else unlink( fd->unlink );
606 free( fd );
610 /* retrieve the inode object for a given fd, creating it if needed */
611 static struct inode *get_inode( dev_t dev, ino_t ino )
613 struct list *ptr;
614 struct inode *inode;
615 unsigned int hash = (dev ^ ino) % HASH_SIZE;
617 if (inode_hash[hash].next)
619 LIST_FOR_EACH( ptr, &inode_hash[hash] )
621 inode = LIST_ENTRY( ptr, struct inode, entry );
622 if (inode->dev == dev && inode->ino == ino)
623 return (struct inode *)grab_object( inode );
626 else list_init( &inode_hash[hash] );
628 /* not found, create it */
629 if ((inode = alloc_object( &inode_ops )))
631 inode->hash = hash;
632 inode->dev = dev;
633 inode->ino = ino;
634 list_init( &inode->open );
635 list_init( &inode->locks );
636 list_init( &inode->closed );
637 list_add_head( &inode_hash[hash], &inode->entry );
639 return inode;
642 /* add fd to the indoe list of file descriptors to close */
643 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
645 if (!list_empty( &inode->locks ))
647 list_add_head( &inode->closed, &fd->entry );
649 else if (fd->unlink[0]) /* close the fd but keep the structure around for unlink */
651 close( fd->fd );
652 fd->fd = -1;
653 list_add_head( &inode->closed, &fd->entry );
655 else /* no locks on this inode and no unlink, get rid of the fd */
657 close( fd->fd );
658 free( fd );
663 /****************************************************************/
664 /* file lock functions */
666 static void file_lock_dump( struct object *obj, int verbose )
668 struct file_lock *lock = (struct file_lock *)obj;
669 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
670 lock->shared ? "shared" : "excl", lock->fd, lock->process );
671 DUMP_LONG_LONG( lock->start );
672 fprintf( stderr, " end=" );
673 DUMP_LONG_LONG( lock->end );
674 fprintf( stderr, "\n" );
677 static int file_lock_signaled( struct object *obj, struct thread *thread )
679 struct file_lock *lock = (struct file_lock *)obj;
680 /* lock is signaled if it has lost its owner */
681 return !lock->process;
684 /* set (or remove) a Unix lock if possible for the given range */
685 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
687 struct flock fl;
689 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
690 for (;;)
692 if (start == end) return 1; /* can't set zero-byte lock */
693 if (start > max_unix_offset) return 1; /* ignore it */
694 fl.l_type = type;
695 fl.l_whence = SEEK_SET;
696 fl.l_start = start;
697 if (!end || end > max_unix_offset) fl.l_len = 0;
698 else fl.l_len = end - start;
699 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
701 switch(errno)
703 case EACCES:
704 /* check whether locks work at all on this file system */
705 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
707 set_error( STATUS_FILE_LOCK_CONFLICT );
708 return 0;
710 /* fall through */
711 case EIO:
712 case ENOLCK:
713 /* no locking on this fs, just ignore it */
714 fd->fs_locks = 0;
715 return 1;
716 case EAGAIN:
717 set_error( STATUS_FILE_LOCK_CONFLICT );
718 return 0;
719 case EBADF:
720 /* this can happen if we try to set a write lock on a read-only file */
721 /* we just ignore that error */
722 if (fl.l_type == F_WRLCK) return 1;
723 set_error( STATUS_ACCESS_DENIED );
724 return 0;
725 #ifdef EOVERFLOW
726 case EOVERFLOW:
727 #endif
728 case EINVAL:
729 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
730 /* in that case we shrink the limit and retry */
731 if (max_unix_offset > INT_MAX)
733 max_unix_offset = INT_MAX;
734 break; /* retry */
736 /* fall through */
737 default:
738 file_set_error();
739 return 0;
744 /* check if interval [start;end) overlaps the lock */
745 inline static int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
747 if (lock->end && start >= lock->end) return 0;
748 if (end && lock->start >= end) return 0;
749 return 1;
752 /* remove Unix locks for all bytes in the specified area that are no longer locked */
753 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
755 struct hole
757 struct hole *next;
758 struct hole *prev;
759 file_pos_t start;
760 file_pos_t end;
761 } *first, *cur, *next, *buffer;
763 struct list *ptr;
764 int count = 0;
766 if (!fd->inode) return;
767 if (!fd->fs_locks) return;
768 if (start == end || start > max_unix_offset) return;
769 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
771 /* count the number of locks overlapping the specified area */
773 LIST_FOR_EACH( ptr, &fd->inode->locks )
775 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
776 if (lock->start == lock->end) continue;
777 if (lock_overlaps( lock, start, end )) count++;
780 if (!count) /* no locks at all, we can unlock everything */
782 set_unix_lock( fd, start, end, F_UNLCK );
783 return;
786 /* allocate space for the list of holes */
787 /* max. number of holes is number of locks + 1 */
789 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
790 first = buffer;
791 first->next = NULL;
792 first->prev = NULL;
793 first->start = start;
794 first->end = end;
795 next = first + 1;
797 /* build a sorted list of unlocked holes in the specified area */
799 LIST_FOR_EACH( ptr, &fd->inode->locks )
801 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
802 if (lock->start == lock->end) continue;
803 if (!lock_overlaps( lock, start, end )) continue;
805 /* go through all the holes touched by this lock */
806 for (cur = first; cur; cur = cur->next)
808 if (cur->end <= lock->start) continue; /* hole is before start of lock */
809 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
811 /* now we know that lock is overlapping hole */
813 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
815 cur->start = lock->end;
816 if (cur->start && cur->start < cur->end) break; /* done with this lock */
817 /* now hole is empty, remove it */
818 if (cur->next) cur->next->prev = cur->prev;
819 if (cur->prev) cur->prev->next = cur->next;
820 else if (!(first = cur->next)) goto done; /* no more holes at all */
822 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
824 cur->end = lock->start;
825 assert( cur->start < cur->end );
827 else /* lock is in the middle of hole, split hole in two */
829 next->prev = cur;
830 next->next = cur->next;
831 cur->next = next;
832 next->start = lock->end;
833 next->end = cur->end;
834 cur->end = lock->start;
835 assert( next->start < next->end );
836 assert( cur->end < next->start );
837 next++;
838 break; /* done with this lock */
843 /* clear Unix locks for all the holes */
845 for (cur = first; cur; cur = cur->next)
846 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
848 done:
849 free( buffer );
852 /* create a new lock on a fd */
853 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
855 struct file_lock *lock;
857 if (!fd->inode) /* not a regular file */
859 set_error( STATUS_INVALID_HANDLE );
860 return NULL;
863 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
864 lock->shared = shared;
865 lock->start = start;
866 lock->end = end;
867 lock->fd = fd;
868 lock->process = current->process;
870 /* now try to set a Unix lock */
871 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
873 release_object( lock );
874 return NULL;
876 list_add_head( &fd->locks, &lock->fd_entry );
877 list_add_head( &fd->inode->locks, &lock->inode_entry );
878 list_add_head( &lock->process->locks, &lock->proc_entry );
879 return lock;
882 /* remove an existing lock */
883 static void remove_lock( struct file_lock *lock, int remove_unix )
885 struct inode *inode = lock->fd->inode;
887 list_remove( &lock->fd_entry );
888 list_remove( &lock->inode_entry );
889 list_remove( &lock->proc_entry );
890 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
891 if (list_empty( &inode->locks )) inode_close_pending( inode );
892 lock->process = NULL;
893 wake_up( &lock->obj, 0 );
894 release_object( lock );
897 /* remove all locks owned by a given process */
898 void remove_process_locks( struct process *process )
900 struct list *ptr;
902 while ((ptr = list_head( &process->locks )))
904 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
905 remove_lock( lock, 1 ); /* this removes it from the list */
909 /* remove all locks on a given fd */
910 static void remove_fd_locks( struct fd *fd )
912 file_pos_t start = FILE_POS_T_MAX, end = 0;
913 struct list *ptr;
915 while ((ptr = list_head( &fd->locks )))
917 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
918 if (lock->start < start) start = lock->start;
919 if (!lock->end || lock->end > end) end = lock->end - 1;
920 remove_lock( lock, 0 );
922 if (start < end) remove_unix_locks( fd, start, end + 1 );
925 /* add a lock on an fd */
926 /* returns handle to wait on */
927 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
929 struct list *ptr;
930 file_pos_t end = start + count;
932 /* don't allow wrapping locks */
933 if (end && end < start)
935 set_error( STATUS_INVALID_PARAMETER );
936 return 0;
939 /* check if another lock on that file overlaps the area */
940 LIST_FOR_EACH( ptr, &fd->inode->locks )
942 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
943 if (!lock_overlaps( lock, start, end )) continue;
944 if (lock->shared && shared) continue;
945 /* found one */
946 if (!wait)
948 set_error( STATUS_FILE_LOCK_CONFLICT );
949 return 0;
951 set_error( STATUS_PENDING );
952 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
955 /* not found, add it */
956 if (add_lock( fd, shared, start, end )) return 0;
957 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
959 /* Unix lock conflict -> tell client to wait and retry */
960 if (wait) set_error( STATUS_PENDING );
962 return 0;
965 /* remove a lock on an fd */
966 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
968 struct list *ptr;
969 file_pos_t end = start + count;
971 /* find an existing lock with the exact same parameters */
972 LIST_FOR_EACH( ptr, &fd->locks )
974 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
975 if ((lock->start == start) && (lock->end == end))
977 remove_lock( lock, 1 );
978 return;
981 set_error( STATUS_FILE_LOCK_CONFLICT );
985 /****************************************************************/
986 /* asynchronous operations support */
988 struct async
990 struct fd *fd;
991 struct thread *thread;
992 void *apc;
993 void *user;
994 void *sb;
995 struct timeval when;
996 struct timeout_user *timeout;
997 struct list entry;
1000 /* notifies client thread of new status of its async request */
1001 /* destroys the server side of it */
1002 static void async_terminate( struct async *async, int status )
1004 thread_queue_apc( async->thread, NULL, async->apc, APC_ASYNC_IO,
1005 1, async->user, async->sb, (void *)status );
1007 if (async->timeout) remove_timeout_user( async->timeout );
1008 async->timeout = NULL;
1009 list_remove( &async->entry );
1010 release_object( async->thread );
1011 free( async );
1014 /* cb for timeout on an async request */
1015 static void async_callback(void *private)
1017 struct async *async = (struct async *)private;
1019 /* fprintf(stderr, "async timeout out %p\n", async); */
1020 async->timeout = NULL;
1021 async_terminate( async, STATUS_TIMEOUT );
1024 /* create an async on a given queue of a fd */
1025 struct async *create_async(struct fd *fd, struct thread *thread, int timeout, struct list *queue,
1026 void *io_apc, void *io_user, void* io_sb)
1028 struct async *async = mem_alloc( sizeof(struct async) );
1030 if (!async) return NULL;
1032 async->fd = fd;
1033 async->thread = (struct thread *)grab_object(thread);
1034 async->apc = io_apc;
1035 async->user = io_user;
1036 async->sb = io_sb;
1038 list_add_tail( queue, &async->entry );
1040 if (timeout)
1042 gettimeofday( &async->when, 0 );
1043 add_timeout( &async->when, timeout );
1044 async->timeout = add_timeout_user( &async->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 );